HEX
Server: LiteSpeed
System: Linux s3604.bom1.stableserver.net 4.18.0-513.11.1.lve.el8.x86_64 #1 SMP Thu Jan 18 16:21:02 UTC 2024 x86_64
User: dmstechonline (1480)
PHP: 7.4.33
Disabled: NONE
Upload Files
File: /home/dmstechonline/whatsapp.dmstech.online/node_modules/monaco-editor/dev/vs/editor/editor.main.js
/*!-----------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Version: 0.52.0(f6dc0eb8fce67e57f6036f4769d92c1666cdf546)
 * Released under the MIT license
 * https://github.com/microsoft/vscode/blob/main/LICENSE.txt */ /* This fix ensures that old nls-plugin configurations are still respected by the new localization solution. */ /* We should try to avoid this file and find a different solution.  */ /* Warning: This file still has to work when replacing "\n" with " "! */  /**  * @type {typeof define}  */ const globalDefine = globalThis.define; globalDefine('vs/nls.messages-loader', [], function (...args) { 	return { 		load: (name, req, load, config) => { 			const requestedLanguage = config['vs/nls']?.availableLanguages?.['*']; 			if (!requestedLanguage || requestedLanguage === 'en') { 				load({}); 			} else { 				req([`vs/nls.messages.${requestedLanguage}`], () => { 					load({}); 				}); 			} 		} 	}; }); globalDefine( 	'vs/nls.messages', 	['require', 'exports', 'vs/nls.messages-loader!'], 	function (require, exports) { 		Object.assign(exports, { 			getNLSMessages: () => globalThis._VSCODE_NLS_MESSAGES, 			getNLSLanguage: () => globalThis._VSCODE_NLS_LANGUAGE 		}); 	} ); define = function (...args) { 	if (args.length > 0 && args[0] === 'vs/nls.messages') { 		return; 	} 	return globalDefine(...args); }; define.amd = true;  /*
 *-----------------------------------------------------------*/

(function() {
var __m = ["exports","require","vs/base/common/lifecycle","vs/nls","vs/editor/common/core/range","vs/base/browser/dom","vs/base/common/event","vs/platform/instantiation/common/instantiation","vs/base/common/errors","vs/editor/common/core/position","vs/css!vs/editor/editor.main","vs/base/common/strings","vs/platform/contextkey/common/contextkey","vs/base/common/arrays","vs/base/common/async","vs/editor/browser/editorExtensions","vs/base/common/platform","vs/editor/common/services/languageFeatures","vs/base/common/cancellation","vs/base/common/types","vs/editor/common/editorContextKeys","vs/base/common/observable","vs/base/common/uri","vs/editor/common/core/selection","vs/platform/commands/common/commands","vs/platform/theme/common/themeService","vs/base/common/codicons","vs/editor/common/languages","vs/platform/configuration/common/configuration","vs/platform/actions/common/actions","vs/base/common/themables","vs/platform/keybinding/common/keybinding","vs/platform/theme/common/colorRegistry","vs/base/common/color","vs/editor/browser/services/codeEditorService","vs/editor/common/model/textModel","vs/editor/common/languages/languageConfigurationRegistry","vs/editor/common/config/editorOptions","vs/platform/registry/common/platform","vs/base/browser/fastDomNode","vs/editor/common/model","vs/base/common/actions","vs/base/common/network","vs/editor/common/languages/language","vs/base/browser/ui/hover/hoverDelegateFactory","vs/base/common/map","vs/base/browser/ui/aria/aria","vs/base/browser/keyboardEvent","vs/base/common/resources","vs/platform/instantiation/common/extensions","vs/platform/notification/common/notification","vs/editor/common/services/model","vs/base/browser/window","vs/base/common/iterator","vs/base/common/stopwatch","vs/editor/common/core/lineRange","vs/editor/browser/view/viewPart","vs/base/common/htmlContent","vs/platform/contextview/browser/contextView","vs/platform/opener/common/opener","vs/base/common/objects","vs/platform/accessibility/common/accessibility","vs/platform/log/common/log","vs/platform/telemetry/common/telemetry","vs/base/browser/browser","vs/base/common/observableInternal/derived","vs/platform/quickinput/common/quickInput","vs/base/common/arraysFind","vs/editor/common/core/offsetRange","vs/base/browser/touch","vs/editor/common/languages/modesRegistry","vs/platform/theme/common/iconRegistry","vs/base/common/keyCodes","vs/base/common/linkedList","vs/editor/browser/config/domFontInfo","vs/editor/common/core/editOperation","vs/editor/common/cursorCommon","vs/base/browser/mouseEvent","vs/editor/common/services/resolverService","vs/editor/common/services/languageFeatureDebounce","vs/editor/common/core/editorColorRegistry","vs/base/browser/ui/hover/hoverDelegate2","vs/base/common/filters","vs/editor/common/tokens/lineTokens","vs/editor/contrib/hover/browser/hoverTypes","vs/base/browser/ui/widget","vs/base/browser/ui/scrollbar/scrollableElement","vs/base/browser/ui/actionbar/actionbar","vs/editor/browser/widget/diffEditor/utils","vs/platform/theme/common/colorUtils","vs/base/common/assert","vs/base/common/hierarchicalKind","vs/base/common/observableInternal/base","vs/base/browser/event","vs/editor/common/core/cursorColumns","vs/editor/common/viewModel","vs/platform/progress/common/progress","vs/platform/theme/common/theme","vs/base/common/lazy","vs/base/common/path","vs/editor/common/services/editorWorker","vs/platform/storage/common/storage","vs/base/common/equals","vs/base/browser/trustedTypes","vs/editor/common/core/textEdit","vs/editor/common/diff/rangeMapping","vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/length","vs/editor/common/standaloneStrings","vs/platform/markers/common/markers","vs/platform/configuration/common/configurationRegistry","vs/platform/theme/browser/defaultStyles","vs/base/common/severity","vs/editor/browser/observableCodeEditor","vs/editor/common/core/textLength","vs/base/browser/ui/iconLabel/iconLabels","vs/base/browser/ui/list/listWidget","vs/editor/common/core/stringBuilder","vs/platform/clipboard/common/clipboardService","vs/platform/hover/browser/hover","vs/platform/layout/browser/layoutService","vs/editor/browser/widget/markdownRenderer/browser/markdownRenderer","vs/platform/keybinding/common/keybindingsRegistry","vs/editor/contrib/editorState/browser/editorState","vs/platform/theme/common/colors/baseColors","vs/platform/actions/browser/menuEntryActionViewItem","vs/editor/browser/widget/codeEditor/embeddedCodeEditorWidget","vs/base/common/decorators","vs/base/common/functional","vs/base/common/mime","vs/base/common/hash","vs/editor/common/editorFeatures","vs/editor/common/languages/languageConfiguration","vs/editor/common/textModelEvents","vs/editor/browser/view/dynamicViewOverlay","vs/editor/contrib/codeAction/common/types","vs/editor/contrib/snippet/browser/snippetParser","vs/editor/common/viewLayout/viewLineRenderer","vs/platform/accessibilitySignal/browser/accessibilitySignalService","vs/platform/theme/common/colors/editorColors","vs/editor/browser/widget/diffEditor/registrations.contribution","vs/base/common/keybindings","vs/base/common/numbers","vs/base/common/iconLabels","vs/editor/browser/stableEditorScroll","vs/editor/common/core/characterClassifier","vs/editor/common/core/eolCounter","vs/editor/common/commands/replaceCommand","vs/editor/common/core/wordHelper","vs/editor/common/encodedTokenAttributes","vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/smallImmutableSet","vs/editor/common/viewLayout/lineDecorations","vs/base/browser/ui/actionbar/actionViewItems","vs/editor/browser/services/bulkEditService","vs/editor/standalone/common/standaloneTheme","vs/platform/instantiation/common/serviceCollection","vs/editor/contrib/suggest/browser/suggest","vs/platform/quickinput/common/quickAccess","vs/editor/contrib/codeAction/browser/codeAction","vs/editor/contrib/peekView/browser/peekView","vs/base/browser/ui/tree/tree","vs/base/common/buffer","vs/base/common/observableInternal/debugName","vs/base/common/observableInternal/logging","vs/base/common/scrollable","vs/editor/browser/view/renderingContext","vs/editor/common/config/editorZoom","vs/editor/common/core/wordCharacterClassifier","vs/editor/common/diff/defaultLinesDiffComputer/algorithms/diffAlgorithm","vs/editor/browser/editorBrowser","vs/editor/common/languages/supports","vs/editor/common/viewEventHandler","vs/base/common/hotReloadHelpers","vs/base/browser/globalPointerMoveMonitor","vs/base/browser/ui/sash/sash","vs/base/browser/ui/hover/hoverWidget","vs/base/browser/ui/toggle/toggle","vs/base/browser/ui/tree/abstractTree","vs/editor/common/languages/nullTokenize","vs/editor/contrib/gotoSymbol/browser/referencesModel","vs/platform/contextkey/common/contextkeys","vs/platform/dialogs/common/dialogs","vs/platform/label/common/label","vs/editor/contrib/documentSymbols/browser/outlineModel","vs/editor/common/commands/shiftCommand","vs/editor/contrib/message/browser/messageController","vs/editor/browser/editorDom","vs/platform/workspace/common/workspace","vs/base/common/idGenerator","vs/base/common/range","vs/base/common/observableInternal/utils","vs/base/common/diff/diff","vs/base/common/codiconsUtil","vs/base/common/uint","vs/base/common/uuid","vs/base/common/dataTransfer","vs/base/browser/ui/codicons/codiconStyles","vs/css!vs/editor/contrib/hover/browser/hover","vs/editor/common/core/textModelDefaults","vs/editor/common/editorCommon","vs/editor/common/cursor/cursorWordOperations","vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/beforeEditPositionMapper","vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/ast","vs/editor/common/model/textModelSearch","vs/editor/contrib/folding/browser/foldingRanges","vs/editor/contrib/inlineCompletions/browser/model/ghostText","vs/editor/contrib/inlineCompletions/browser/utils","vs/base/browser/ui/keybindingLabel/keybindingLabel","vs/base/browser/markdownRenderer","vs/editor/common/languages/supports/richEditBrackets","vs/editor/contrib/gotoSymbol/browser/link/clickLinkGesture","vs/editor/contrib/hover/browser/hoverUtils","vs/editor/common/services/textResourceConfiguration","vs/editor/browser/controller/textAreaInput","vs/editor/common/cursor/cursorTypeEditOperations","vs/editor/browser/coreCommands","vs/editor/browser/widget/diffEditor/diffProviderFactoryService","vs/platform/list/browser/listService","vs/editor/contrib/hover/browser/markdownHoverParticipant","vs/platform/actions/browser/toolbar","vs/editor/browser/widget/codeEditor/codeEditorWidget","vs/editor/contrib/find/browser/findModel","vs/editor/contrib/snippet/browser/snippetController2","vs/editor/standalone/browser/standaloneServices","vs/base/browser/ui/scrollbar/scrollbarState","vs/base/browser/dnd","vs/base/common/ternarySearchTree","vs/base/browser/ui/mouseCursor/mouseCursor","vs/css!vs/editor/contrib/colorPicker/browser/colorPicker","vs/css!vs/platform/quickinput/browser/media/quickInput","vs/editor/browser/config/tabFocus","vs/editor/common/core/indentation","vs/editor/common/diff/defaultLinesDiffComputer/utils","vs/editor/common/diff/linesDiffComputer","vs/editor/common/cursor/cursorMoveOperations","vs/editor/common/cursor/cursorDeleteOperations","vs/editor/common/cursor/cursorMoveCommands","vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/tokenizer","vs/editor/common/model/utils","vs/editor/common/standalone/standaloneEnums","vs/editor/common/textModelGuides","vs/editor/common/languages/supports/indentationLineProcessor","vs/editor/common/languages/autoIndent","vs/editor/browser/viewParts/glyphMargin/glyphMargin","vs/editor/common/viewEvents","vs/editor/common/viewModelEventDispatcher","vs/editor/contrib/inlineCompletions/browser/controller/commandIds","vs/editor/contrib/inlineCompletions/browser/model/singleTextEdit","vs/base/common/keybindingLabels","vs/base/browser/canIUse","vs/base/browser/ui/tree/indexTreeModel","vs/base/browser/ui/tree/objectTreeModel","vs/base/common/extpath","vs/base/common/marshalling","vs/base/browser/pixelRatio","vs/base/browser/ui/iconLabel/iconLabel","vs/base/browser/ui/resizable/resizable","vs/base/browser/ui/scrollbar/scrollbarArrow","vs/base/browser/ui/list/listView","vs/base/browser/ui/button/button","vs/base/browser/ui/inputbox/inputBox","vs/base/browser/ui/findinput/findInput","vs/editor/common/config/fontInfo","vs/editor/browser/view/viewLayer","vs/editor/common/model/tokens","vs/editor/contrib/hover/browser/hoverActionIds","vs/platform/instantiation/common/descriptors","vs/editor/common/services/markerDecorations","vs/editor/common/services/semanticTokensStyling","vs/editor/contrib/dropOrPasteInto/browser/edit","vs/editor/contrib/inlineCompletions/browser/controller/inlineCompletionContextKeys","vs/editor/contrib/parameterHints/browser/provideSignatureHelp","vs/platform/environment/common/environment","vs/platform/quickinput/browser/quickInput","vs/platform/jsonschemas/common/jsonContributionRegistry","vs/editor/common/config/editorConfigurationSchema","vs/editor/common/languages/enterAction","vs/editor/common/cursor/cursorTypeOperations","vs/editor/contrib/gotoSymbol/browser/goToSymbol","vs/platform/theme/common/colors/miscColors","vs/platform/theme/common/colors/listColors","vs/editor/contrib/symbolIcons/browser/symbolIcons","vs/editor/browser/viewParts/lines/viewLine","vs/editor/common/services/semanticTokensProviderStyling","vs/editor/contrib/inlineCompletions/browser/hintsWidget/inlineCompletionsHintsWidget","vs/platform/undoRedo/common/undoRedo","vs/editor/browser/widget/diffEditor/components/diffEditorViewZones/diffEditorViewZones","vs/editor/browser/widget/diffEditor/diffEditorWidget","vs/editor/contrib/codeAction/browser/codeActionController","vs/editor/contrib/colorPicker/browser/colorHoverParticipant","vs/editor/contrib/folding/browser/folding","vs/editor/contrib/inlineProgress/browser/inlineProgress","vs/editor/contrib/gotoSymbol/browser/goToCommands","vs/editor/contrib/hover/browser/contentHoverController2","vs/editor/contrib/dropOrPasteInto/browser/defaultProviders","vs/editor/contrib/suggest/browser/suggestController","vs/editor/contrib/inlineCompletions/browser/controller/inlineCompletionsController","vs/base/browser/performance","vs/base/common/cache","vs/base/common/collections","vs/base/common/observableInternal/autorun","vs/base/common/ime","vs/base/common/symbols","vs/css!vs/base/browser/ui/actionbar/actionbar","vs/css!vs/base/browser/ui/dropdown/dropdown","vs/css!vs/base/browser/ui/findinput/findInput","vs/css!vs/base/browser/ui/list/list","vs/css!vs/platform/actionWidget/browser/actionWidget","vs/editor/browser/viewParts/minimap/minimapCharSheet","vs/editor/common/config/diffEditor","vs/editor/browser/view/viewUserInputEvents","vs/editor/browser/controller/textAreaState","vs/editor/common/core/rgba","vs/editor/common/commands/surroundSelectionCommand","vs/editor/common/cursor/cursorAtomicMoveOperations","vs/editor/common/diff/defaultLinesDiffComputer/algorithms/myersDiffAlgorithm","vs/editor/common/diff/defaultLinesDiffComputer/heuristicSequenceOptimizations","vs/editor/common/diff/defaultLinesDiffComputer/linesSliceCharSequence","vs/editor/common/diff/defaultLinesDiffComputer/defaultLinesDiffComputer","vs/editor/common/editorAction","vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/combineTextEditInfos","vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/parser","vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/brackets","vs/editor/common/model/prefixSumComputer","vs/editor/common/model/textModelPart","vs/editor/common/model/pieceTreeTextBuffer/pieceTreeBase","vs/editor/common/modelLineProjectionData","vs/editor/common/services/editorWorkerHost","vs/editor/common/services/treeViewsDnd","vs/editor/common/services/unicodeTextModelHighlighter","vs/editor/common/model/guidesTextModelPart","vs/editor/common/tokens/contiguousMultilineTokensBuilder","vs/editor/browser/viewParts/margin/margin","vs/editor/common/viewModel/overviewZoneManager","vs/editor/contrib/comment/browser/blockCommentCommand","vs/editor/contrib/folding/browser/foldingModel","vs/editor/contrib/folding/browser/indentRangeProvider","vs/editor/contrib/folding/browser/syntaxRangeProvider","vs/editor/contrib/format/browser/formattingEdit","vs/editor/contrib/indentation/common/indentUtils","vs/editor/contrib/semanticTokens/common/semanticTokensConfig","vs/editor/contrib/smartSelect/browser/bracketSelections","vs/editor/contrib/stickyScroll/browser/stickyScrollElement","vs/editor/contrib/suggest/browser/completionModel","vs/editor/contrib/suggest/browser/wordDistance","vs/editor/standalone/common/monarch/monarchCommon","vs/nls.messages","vs/base/common/errorMessage","vs/base/browser/fonts","vs/base/common/process","vs/base/common/hotReload","vs/base/common/glob","vs/base/browser/dompurify/dompurify","vs/base/browser/formattedTextRenderer","vs/base/browser/ui/contextview/contextview","vs/base/browser/ui/countBadge/countBadge","vs/base/browser/ui/highlightedlabel/highlightedLabel","vs/base/browser/ui/scrollbar/abstractScrollbar","vs/base/browser/ui/splitview/splitview","vs/base/browser/ui/findinput/findInputToggles","vs/base/browser/ui/dropdown/dropdownActionViewItem","vs/base/browser/ui/tree/objectTree","vs/base/common/worker/simpleWorker","vs/editor/browser/config/elementSizeObserver","vs/editor/browser/widget/diffEditor/components/diffEditorSash","vs/editor/browser/widget/diffEditor/features/movedBlocksLinesFeature","vs/editor/browser/widget/multiDiffEditor/utils","vs/editor/browser/config/fontMeasurements","vs/editor/common/core/textChange","vs/editor/common/languageSelector","vs/editor/common/languages/textToHtmlTokenizer","vs/editor/common/model/editStack","vs/editor/common/model/pieceTreeTextBuffer/pieceTreeTextBuffer","vs/editor/common/services/editorBaseApi","vs/editor/common/services/textModelSync/textModelSync.impl","vs/editor/common/viewModel/minimapTokensColorTracker","vs/editor/common/viewModel/viewModelDecorations","vs/editor/contrib/hover/browser/hoverOperation","vs/editor/contrib/inlayHints/browser/inlayHints","vs/editor/contrib/inlineCompletions/browser/model/provideInlineCompletions","vs/editor/contrib/placeholderText/browser/placeholderTextContribution","vs/platform/accessibility/browser/accessibleViewRegistry","vs/platform/action/common/action","vs/platform/files/common/files","vs/editor/browser/widget/diffEditor/features/hideUnchangedRegionsFeature","vs/editor/common/services/treeSitterParserService","vs/editor/contrib/colorPicker/browser/defaultDocumentColorProvider","vs/editor/contrib/codelens/browser/codelens","vs/editor/contrib/semanticTokens/common/getSemanticTokens","vs/editor/contrib/colorPicker/browser/color","vs/editor/standalone/common/monarch/monarchLexer","vs/editor/contrib/inlineEdits/browser/consts","vs/editor/contrib/hover/browser/contentHoverStatusBar","vs/platform/keybinding/common/keybindingResolver","vs/platform/keybinding/common/resolvedKeybindingItem","vs/editor/standalone/browser/standaloneLayoutService","vs/platform/contextview/browser/contextViewService","vs/editor/contrib/dropOrPasteInto/browser/postEditWidget","vs/platform/observable/common/platformObservableUtils","vs/platform/quickinput/browser/quickInputUtils","vs/platform/dnd/browser/dnd","vs/editor/browser/dnd","vs/editor/browser/services/editorWorkerService","vs/editor/contrib/suggest/browser/suggestWidgetDetails","vs/platform/configuration/common/configurationModels","vs/platform/history/browser/contextScopedHistoryWidget","vs/editor/contrib/suggest/browser/suggestMemory","vs/platform/actions/common/menuService","vs/editor/browser/widget/diffEditor/diffEditorViewModel","vs/editor/contrib/codeAction/browser/codeActionModel","vs/editor/contrib/format/browser/format","vs/editor/contrib/hover/browser/getHover","vs/editor/contrib/wordOperations/browser/wordOperations","vs/platform/theme/common/colors/inputColors","vs/platform/theme/common/colors/minimapColors","vs/editor/browser/controller/mouseTarget","vs/editor/browser/widget/diffEditor/features/overviewRulerFeature","vs/editor/browser/viewParts/lineNumbers/lineNumbers","vs/editor/contrib/quickAccess/browser/editorNavigationQuickAccess","vs/editor/standalone/browser/standaloneCodeEditorService","vs/editor/standalone/browser/standaloneThemeService","vs/editor/browser/widget/multiDiffEditor/diffEditorItemTemplate","vs/editor/contrib/codeAction/browser/lightBulbWidget","vs/editor/contrib/colorPicker/browser/colorDetector","vs/editor/contrib/find/browser/findController","vs/editor/contrib/folding/browser/foldingDecorations","vs/editor/contrib/inlineEdit/browser/inlineEditController","vs/editor/contrib/wordHighlighter/browser/highlightDecorations","vs/editor/contrib/gotoError/browser/gotoError","vs/editor/contrib/gotoSymbol/browser/peek/referencesController","vs/editor/contrib/gotoSymbol/browser/link/goToDefinitionAtPosition","vs/editor/contrib/inlayHints/browser/inlayHintsLocations","vs/editor/contrib/inlayHints/browser/inlayHintsController","vs/editor/contrib/inlayHints/browser/inlayHintsHover","vs/editor/contrib/stickyScroll/browser/stickyScrollController","vs/editor/contrib/contextmenu/browser/contextmenu","vs/editor/contrib/dropOrPasteInto/browser/copyPasteController","vs/editor/contrib/snippet/browser/snippetSession","vs/editor/contrib/suggest/browser/suggestModel","vs/editor/contrib/inlineEdits/browser/inlineEditsWidget","vs/editor/contrib/inlineEdits/browser/inlineEditsController","vs/platform/workspace/common/workspaceTrust","vs/base/browser/iframe","vs/base/browser/ui/list/list","vs/base/browser/ui/list/splice","vs/base/common/diff/diffChange","vs/base/common/comparers","vs/base/common/linkedText","vs/base/common/marked/marked","vs/base/common/naturalLanguage/korean","vs/base/common/navigator","vs/base/common/history","vs/base/common/observableInternal/lazyObservableValue","vs/base/common/observableInternal/api","vs/base/common/observableInternal/promise","vs/base/browser/ui/list/rangeMap","vs/base/common/search","vs/base/common/tfIdf","vs/base/common/codiconsLibrary","vs/css!vs/base/browser/ui/aria/aria","vs/css!vs/base/browser/ui/button/button","vs/css!vs/base/browser/ui/codicons/codicon/codicon","vs/css!vs/base/browser/ui/codicons/codicon/codicon-modifiers","vs/css!vs/base/browser/ui/contextview/contextview","vs/css!vs/base/browser/ui/countBadge/countBadge","vs/css!vs/base/browser/ui/hover/hoverWidget","vs/css!vs/base/browser/ui/iconLabel/iconlabel","vs/css!vs/base/browser/ui/inputbox/inputBox","vs/css!vs/base/browser/ui/keybindingLabel/keybindingLabel","vs/css!vs/base/browser/ui/mouseCursor/mouseCursor","vs/css!vs/base/browser/ui/progressbar/progressbar","vs/css!vs/base/browser/ui/sash/sash","vs/css!vs/base/browser/ui/scrollbar/media/scrollbars","vs/css!vs/base/browser/ui/selectBox/selectBox","vs/css!vs/base/browser/ui/selectBox/selectBoxCustom","vs/css!vs/base/browser/ui/splitview/splitview","vs/css!vs/base/browser/ui/table/table","vs/css!vs/base/browser/ui/toggle/toggle","vs/css!vs/base/browser/ui/toolbar/toolbar","vs/css!vs/base/browser/ui/tree/media/tree","vs/css!vs/editor/browser/controller/textAreaHandler","vs/css!vs/editor/browser/services/hoverService/hover","vs/css!vs/editor/browser/viewParts/blockDecorations/blockDecorations","vs/css!vs/editor/browser/viewParts/currentLineHighlight/currentLineHighlight","vs/css!vs/editor/browser/viewParts/decorations/decorations","vs/css!vs/editor/browser/viewParts/glyphMargin/glyphMargin","vs/css!vs/editor/browser/viewParts/indentGuides/indentGuides","vs/css!vs/editor/browser/viewParts/lineNumbers/lineNumbers","vs/css!vs/editor/browser/viewParts/lines/viewLines","vs/css!vs/editor/browser/viewParts/linesDecorations/linesDecorations","vs/css!vs/editor/browser/viewParts/margin/margin","vs/css!vs/editor/browser/viewParts/marginDecorations/marginDecorations","vs/css!vs/editor/browser/viewParts/minimap/minimap","vs/css!vs/editor/browser/viewParts/overlayWidgets/overlayWidgets","vs/css!vs/editor/browser/viewParts/rulers/rulers","vs/css!vs/editor/browser/viewParts/scrollDecoration/scrollDecoration","vs/css!vs/editor/browser/viewParts/selections/selections","vs/css!vs/editor/browser/viewParts/viewCursors/viewCursors","vs/css!vs/editor/browser/viewParts/whitespace/whitespace","vs/css!vs/editor/browser/widget/codeEditor/editor","vs/css!vs/editor/browser/widget/diffEditor/components/accessibleDiffViewer","vs/css!vs/editor/browser/widget/diffEditor/style","vs/css!vs/editor/browser/widget/markdownRenderer/browser/renderedMarkdown","vs/css!vs/editor/browser/widget/multiDiffEditor/style","vs/css!vs/editor/contrib/anchorSelect/browser/anchorSelect","vs/css!vs/editor/contrib/bracketMatching/browser/bracketMatching","vs/css!vs/editor/contrib/codeAction/browser/lightBulbWidget","vs/css!vs/editor/contrib/codelens/browser/codelensWidget","vs/css!vs/editor/contrib/dnd/browser/dnd","vs/css!vs/editor/contrib/dropOrPasteInto/browser/postEditWidget","vs/css!vs/editor/contrib/find/browser/findOptionsWidget","vs/css!vs/editor/contrib/find/browser/findWidget","vs/css!vs/editor/contrib/folding/browser/folding","vs/css!vs/editor/contrib/gotoError/browser/media/gotoErrorWidget","vs/css!vs/editor/contrib/gotoSymbol/browser/link/goToDefinitionAtPosition","vs/css!vs/editor/contrib/gotoSymbol/browser/peek/referencesWidget","vs/css!vs/editor/contrib/inPlaceReplace/browser/inPlaceReplace","vs/css!vs/editor/contrib/inlineCompletions/browser/hintsWidget/inlineCompletionsHintsWidget","vs/css!vs/editor/contrib/inlineCompletions/browser/view/ghostTextView","vs/css!vs/editor/contrib/inlineEdit/browser/inlineEdit","vs/css!vs/editor/contrib/inlineEdit/browser/inlineEditHintsWidget","vs/css!vs/editor/contrib/inlineEdit/browser/inlineEditSideBySideWidget","vs/css!vs/editor/contrib/inlineEdits/browser/inlineEditsWidget","vs/css!vs/editor/contrib/inlineProgress/browser/inlineProgressWidget","vs/css!vs/editor/contrib/linkedEditing/browser/linkedEditing","vs/css!vs/editor/contrib/links/browser/links","vs/css!vs/editor/contrib/message/browser/messageController","vs/css!vs/editor/contrib/parameterHints/browser/parameterHints","vs/css!vs/editor/contrib/peekView/browser/media/peekViewWidget","vs/css!vs/editor/contrib/placeholderText/browser/placeholderText","vs/css!vs/editor/contrib/rename/browser/renameWidget","vs/css!vs/editor/contrib/snippet/browser/snippetSession","vs/css!vs/editor/contrib/stickyScroll/browser/stickyScroll","vs/css!vs/editor/contrib/suggest/browser/media/suggest","vs/css!vs/editor/contrib/symbolIcons/browser/symbolIcons","vs/css!vs/editor/contrib/unicodeHighlighter/browser/bannerController","vs/css!vs/editor/contrib/unicodeHighlighter/browser/unicodeHighlighter","vs/css!vs/editor/contrib/wordHighlighter/browser/highlightDecorations","vs/css!vs/editor/contrib/zoneWidget/browser/zoneWidget","vs/css!vs/editor/standalone/browser/iPadShowKeyboard/iPadShowKeyboard","vs/css!vs/editor/standalone/browser/inspectTokens/inspectTokens","vs/css!vs/editor/standalone/browser/quickInput/standaloneQuickInput","vs/css!vs/editor/standalone/browser/standalone-tokens","vs/css!vs/platform/actions/browser/menuEntryActionViewItem","vs/css!vs/platform/opener/browser/link","vs/css!vs/platform/severityIcon/browser/media/severityIcon","vs/editor/browser/config/charWidthReader","vs/editor/browser/config/migrateOptions","vs/editor/browser/viewParts/lines/domReadingContext","vs/editor/browser/viewParts/lines/rangeUtil","vs/editor/browser/viewParts/minimap/minimapCharRenderer","vs/editor/browser/viewParts/minimap/minimapPreBaked","vs/editor/browser/viewParts/minimap/minimapCharRendererFactory","vs/editor/browser/widget/diffEditor/delegatingEditorImpl","vs/editor/browser/widget/multiDiffEditor/objectPool","vs/editor/common/commands/trimTrailingWhitespaceCommand","vs/editor/common/core/positionToOffset","vs/editor/common/cursor/cursorContext","vs/editor/common/diff/defaultLinesDiffComputer/lineSequence","vs/editor/common/diff/defaultLinesDiffComputer/algorithms/dynamicProgrammingDiffing","vs/editor/common/diff/defaultLinesDiffComputer/computeMovedLines","vs/editor/common/diff/legacyLinesDiffComputer","vs/editor/common/diff/linesDiffComputers","vs/editor/common/editorTheme","vs/editor/common/languages/defaultDocumentColorsComputer","vs/editor/common/languages/linkComputer","vs/editor/common/cursor/cursorColumnSelection","vs/editor/common/cursor/oneCursor","vs/editor/common/cursor/cursorCollection","vs/editor/common/languages/supports/characterPair","vs/editor/common/languages/supports/indentRules","vs/editor/common/languages/supports/inplaceReplaceSupport","vs/editor/common/languages/supports/onEnter","vs/editor/common/languages/supports/tokenization","vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/nodeReader","vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/concat23Trees","vs/editor/common/model/bracketPairsTextModelPart/fixBrackets","vs/editor/common/model/fixedArray","vs/editor/common/model/indentationGuesser","vs/editor/common/model/intervalTree","vs/editor/common/model/pieceTreeTextBuffer/rbTreeBase","vs/editor/common/model/mirrorTextModel","vs/editor/common/model/textModelText","vs/editor/common/services/findSectionHeaders","vs/editor/common/textModelBracketPairs","vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/bracketPairsTree","vs/editor/common/tokenizationRegistry","vs/editor/common/tokens/contiguousMultilineTokens","vs/editor/common/tokens/contiguousTokensEditing","vs/editor/common/tokens/contiguousTokensStore","vs/editor/common/tokens/sparseMultilineTokens","vs/editor/common/tokens/sparseTokensStore","vs/editor/browser/viewParts/blockDecorations/blockDecorations","vs/editor/browser/viewParts/decorations/decorations","vs/editor/browser/viewParts/linesDecorations/linesDecorations","vs/editor/browser/viewParts/marginDecorations/marginDecorations","vs/editor/browser/viewParts/rulers/rulers","vs/editor/browser/viewParts/scrollDecoration/scrollDecoration","vs/editor/browser/viewParts/viewZones/viewZones","vs/editor/common/viewLayout/linePart","vs/editor/common/viewLayout/linesLayout","vs/editor/common/viewLayout/viewLinesViewportData","vs/editor/common/viewModel/glyphLanesModel","vs/editor/common/viewModel/modelLineProjection","vs/editor/common/viewModel/monospaceLineBreaksComputer","vs/editor/browser/viewParts/overviewRuler/overviewRuler","vs/editor/common/viewModel/viewContext","vs/editor/common/viewLayout/viewLayout","vs/editor/contrib/caretOperations/browser/moveCaretCommand","vs/editor/contrib/colorPicker/browser/colorPickerModel","vs/editor/contrib/comment/browser/lineCommentCommand","vs/editor/contrib/dnd/browser/dragAndDropCommand","vs/editor/contrib/find/browser/replaceAllCommand","vs/editor/contrib/find/browser/replacePattern","vs/editor/contrib/folding/browser/hiddenRangeModel","vs/editor/contrib/hover/browser/contentHoverTypes","vs/editor/contrib/hover/browser/hoverAccessibleViews","vs/editor/contrib/inPlaceReplace/browser/inPlaceReplaceCommand","vs/editor/contrib/inlineCompletions/browser/inlineCompletionsAccessibleView","vs/editor/contrib/inlineEdit/browser/commandIds","vs/editor/contrib/linesOperations/browser/copyLinesCommand","vs/editor/contrib/linesOperations/browser/sortLinesCommand","vs/editor/contrib/smartSelect/browser/wordSelections","vs/editor/contrib/suggest/browser/suggestCommitCharacters","vs/editor/contrib/suggest/browser/suggestOvertypingCapturer","vs/editor/standalone/browser/standaloneTreeSitterService","vs/editor/standalone/common/monarch/monarchCompile","vs/base/browser/ui/scrollbar/scrollbarVisibilityController","vs/base/browser/ui/tree/compressedObjectTreeModel","vs/base/common/fuzzyScorer","vs/base/common/labels","vs/base/browser/domObservable","vs/base/browser/ui/dropdown/dropdown","vs/base/browser/ui/list/rowCache","vs/base/browser/ui/progressbar/progressbar","vs/base/browser/ui/selectBox/selectBoxNative","vs/base/browser/ui/scrollbar/horizontalScrollbar","vs/base/browser/ui/scrollbar/verticalScrollbar","vs/base/browser/ui/list/listPaging","vs/base/browser/ui/table/tableWidget","vs/base/browser/ui/selectBox/selectBoxCustom","vs/base/browser/ui/selectBox/selectBox","vs/base/browser/ui/findinput/replaceInput","vs/base/browser/ui/menu/menu","vs/base/browser/ui/toolbar/toolbar","vs/base/browser/ui/tree/dataTree","vs/base/browser/ui/tree/asyncDataTree","vs/base/browser/defaultWorkerFactory","vs/base/parts/storage/common/storage","vs/editor/browser/services/hoverService/updatableHoverWidget","vs/editor/browser/viewParts/contentWidgets/contentWidgets","vs/editor/browser/viewParts/overlayWidgets/overlayWidgets","vs/editor/browser/widget/codeEditor/codeEditorContributions","vs/editor/browser/widget/diffEditor/components/diffEditorViewZones/inlineDiffDeletedCodeMargin","vs/editor/browser/widget/diffEditor/features/revertButtonsFeature","vs/editor/browser/widget/diffEditor/utils/editorGutter","vs/editor/browser/viewParts/viewCursors/viewCursor","vs/editor/browser/view/domLineBreaksComputer","vs/editor/browser/view/viewOverlays","vs/editor/common/languageFeatureRegistry","vs/editor/common/languages/supports/electricCharacter","vs/editor/common/languages/supports/languageBracketsConfiguration","vs/editor/common/model/bracketPairsTextModelPart/bracketPairsImpl","vs/editor/common/model/pieceTreeTextBuffer/pieceTreeTextBufferBuilder","vs/editor/common/model/textModelTokens","vs/editor/common/model/treeSitterTokens","vs/editor/common/services/semanticTokensDto","vs/editor/common/services/editorSimpleWorker","vs/editor/browser/widget/diffEditor/components/diffEditorViewZones/renderLines","vs/editor/contrib/hover/browser/contentHoverComputer","vs/editor/contrib/hover/browser/marginHoverComputer","vs/editor/contrib/hover/browser/resizableContentWidget","vs/platform/action/common/actionCommonCategories","vs/platform/contextkey/common/scanner","vs/platform/editor/common/editor","vs/platform/extensions/common/extensions","vs/platform/history/browser/historyWidgetKeybindingHint","vs/platform/instantiation/common/graph","vs/editor/common/services/languageFeaturesService","vs/editor/common/services/treeViewsDndService","vs/editor/contrib/inlineCompletions/browser/view/ghostTextView","vs/editor/contrib/wordHighlighter/browser/textualHighlightProvider","vs/editor/contrib/links/browser/getLinks","vs/editor/standalone/browser/colorizer","vs/editor/contrib/parameterHints/browser/parameterHintsModel","vs/editor/contrib/suggest/browser/suggestAlternatives","vs/editor/contrib/suggest/browser/wordContextKey","vs/editor/browser/config/editorConfiguration","vs/platform/contextkey/browser/contextKeyService","vs/platform/instantiation/common/instantiationService","vs/platform/keybinding/common/baseResolvedKeybinding","vs/editor/contrib/hover/browser/contentHoverWidget","vs/platform/keybinding/common/abstractKeybindingService","vs/platform/keybinding/common/usLayoutResolvedKeybinding","vs/platform/accessibility/browser/accessibilityService","vs/editor/contrib/diffEditorBreadcrumbs/browser/contribution","vs/editor/contrib/documentSymbols/browser/documentSymbols","vs/platform/clipboard/browser/clipboardService","vs/platform/log/common/logService","vs/editor/contrib/gotoError/browser/markerNavigationService","vs/platform/markers/common/markerService","vs/platform/observable/common/wrapInReloadableClass","vs/editor/browser/services/openerService","vs/platform/opener/browser/link","vs/platform/quickinput/browser/pickerQuickAccess","vs/platform/quickinput/browser/quickInputBox","vs/editor/browser/services/hoverService/hoverWidget","vs/editor/common/cursor/cursor","vs/editor/common/model/tokenizationTextModelPart","vs/editor/common/services/getIconClasses","vs/editor/common/services/languagesAssociations","vs/editor/common/services/languagesRegistry","vs/editor/common/services/languageService","vs/editor/contrib/hover/browser/marginHoverWidget","vs/editor/contrib/hover/browser/marginHoverController","vs/editor/contrib/indentation/common/indentation","vs/editor/contrib/inlineCompletions/browser/model/inlineCompletionsSource","vs/editor/contrib/linesOperations/browser/moveLinesCommand","vs/platform/configuration/common/configurations","vs/editor/contrib/toggleTabFocusMode/browser/toggleTabFocusMode","vs/platform/quickinput/browser/quickInputActions","vs/platform/quickinput/browser/helpQuickAccess","vs/editor/standalone/browser/quickAccess/standaloneHelpQuickAccess","vs/platform/quickinput/browser/quickAccess","vs/platform/severityIcon/browser/severityIcon","vs/editor/contrib/codelens/browser/codeLensCache","vs/editor/browser/services/markerDecorations","vs/editor/browser/view/viewController","vs/editor/contrib/anchorSelect/browser/anchorSelect","vs/editor/contrib/caretOperations/browser/caretOperations","vs/editor/contrib/caretOperations/browser/transpose","vs/editor/contrib/comment/browser/comment","vs/editor/contrib/cursorUndo/browser/cursorUndo","vs/editor/contrib/editorState/browser/keybindingCancellation","vs/editor/contrib/codeAction/browser/codeActionKeybindingResolver","vs/editor/contrib/fontZoom/browser/fontZoom","vs/editor/contrib/format/browser/formatActions","vs/editor/contrib/gotoSymbol/browser/symbolNavigation","vs/editor/contrib/indentation/browser/indentation","vs/editor/contrib/lineSelection/browser/lineSelection","vs/editor/contrib/linesOperations/browser/linesOperations","vs/editor/contrib/longLinesHelper/browser/longLinesHelper","vs/editor/contrib/readOnlyMessage/browser/contribution","vs/editor/contrib/smartSelect/browser/smartSelect","vs/editor/contrib/tokenization/browser/tokenization","vs/editor/contrib/unusualLineTerminators/browser/unusualLineTerminators","vs/editor/contrib/wordPartOperations/browser/wordPartOperations","vs/editor/standalone/browser/iPadShowKeyboard/iPadShowKeyboard","vs/editor/standalone/browser/inspectTokens/inspectTokens","vs/platform/quickinput/browser/commandsQuickAccess","vs/editor/contrib/quickAccess/browser/commandsQuickAccess","vs/editor/standalone/browser/quickAccess/standaloneCommandsQuickAccess","vs/platform/theme/common/colors/menuColors","vs/platform/theme/common/colors/chartsColors","vs/platform/theme/common/colors/quickpickColors","vs/platform/theme/common/colors/searchColors","vs/editor/browser/viewParts/minimap/minimap","vs/editor/browser/widget/multiDiffEditor/colors","vs/editor/contrib/codeAction/browser/codeActionMenu","vs/editor/contrib/gotoSymbol/browser/peek/referencesTree","vs/platform/actionWidget/browser/actionList","vs/platform/actionWidget/browser/actionWidget","vs/platform/contextview/browser/contextMenuHandler","vs/editor/browser/widget/diffEditor/components/accessibleDiffViewer","vs/editor/contrib/colorPicker/browser/colorPickerWidget","vs/editor/contrib/parameterHints/browser/parameterHintsWidget","vs/editor/contrib/parameterHints/browser/parameterHints","vs/editor/contrib/unicodeHighlighter/browser/bannerController","vs/platform/theme/browser/iconsStyleSheet","vs/editor/browser/controller/mouseHandler","vs/editor/browser/controller/pointerHandler","vs/editor/browser/viewParts/lines/viewLines","vs/editor/browser/services/abstractCodeEditorService","vs/editor/browser/services/hoverService/hoverService","vs/editor/browser/viewParts/editorScrollbar/editorScrollbar","vs/editor/browser/viewParts/selections/selections","vs/editor/browser/widget/diffEditor/components/diffEditorEditors","vs/editor/browser/viewParts/currentLineHighlight/currentLineHighlight","vs/editor/browser/viewParts/indentGuides/indentGuides","vs/editor/browser/controller/textAreaHandler","vs/editor/browser/viewParts/overviewRuler/decorationsOverviewRuler","vs/editor/browser/viewParts/viewCursors/viewCursors","vs/editor/browser/viewParts/whitespace/whitespace","vs/editor/browser/view","vs/editor/common/model/bracketPairsTextModelPart/colorizedBracketPairsDecorationProvider","vs/editor/common/services/markerDecorationsService","vs/editor/common/services/semanticTokensStylingService","vs/editor/contrib/placeholderText/browser/placeholderText.contribution","vs/editor/contrib/quickAccess/browser/gotoLineQuickAccess","vs/editor/contrib/quickAccess/browser/gotoSymbolQuickAccess","vs/editor/contrib/rename/browser/renameWidget","vs/editor/contrib/rename/browser/rename","vs/editor/contrib/semanticTokens/browser/documentSemanticTokens","vs/editor/contrib/semanticTokens/browser/viewportSemanticTokens","vs/editor/contrib/suggest/browser/suggestWidgetRenderer","vs/editor/standalone/browser/quickAccess/standaloneGotoLineQuickAccess","vs/editor/standalone/browser/quickAccess/standaloneGotoSymbolQuickAccess","vs/editor/standalone/common/themes","vs/editor/standalone/browser/toggleHighContrast/toggleHighContrast","vs/editor/contrib/suggest/browser/suggestWidgetStatus","vs/editor/browser/widget/diffEditor/features/gutterFeature","vs/editor/contrib/inlineEdit/browser/inlineEditHintsWidget","vs/platform/contextview/browser/contextMenuService","vs/platform/quickinput/browser/quickInputTree","vs/platform/quickinput/browser/quickInputController","vs/platform/quickinput/browser/quickInputService","vs/editor/standalone/browser/quickInput/standaloneQuickInputService","vs/editor/browser/widget/diffEditor/components/diffEditorDecorations","vs/editor/browser/widget/diffEditor/diffEditorOptions","vs/editor/common/services/modelService","vs/editor/common/viewModel/viewModelLines","vs/editor/common/viewModel/viewModelImpl","vs/editor/browser/widget/diffEditor/commands","vs/editor/browser/widget/diffEditor/diffEditor.contribution","vs/editor/browser/widget/multiDiffEditor/multiDiffEditorWidgetImpl","vs/editor/browser/widget/multiDiffEditor/multiDiffEditorWidget","vs/editor/contrib/bracketMatching/browser/bracketMatching","vs/editor/contrib/codeAction/browser/codeActionCommands","vs/editor/contrib/codeAction/browser/codeActionContributions","vs/editor/contrib/codelens/browser/codelensWidget","vs/editor/contrib/codelens/browser/codelensController","vs/editor/contrib/colorPicker/browser/standaloneColorPickerWidget","vs/editor/contrib/colorPicker/browser/standaloneColorPickerActions","vs/editor/contrib/dnd/browser/dnd","vs/editor/contrib/find/browser/findDecorations","vs/editor/contrib/find/browser/findOptionsWidget","vs/editor/contrib/find/browser/findState","vs/editor/contrib/find/browser/findWidget","vs/editor/contrib/inPlaceReplace/browser/inPlaceReplace","vs/editor/contrib/inlineEdit/browser/ghostTextWidget","vs/editor/contrib/inlineEdit/browser/inlineEditSideBySideWidget","vs/editor/contrib/inlineEdit/browser/commands","vs/editor/contrib/inlineEdit/browser/inlineEdit.contribution","vs/editor/contrib/dropOrPasteInto/browser/dropIntoEditorController","vs/editor/contrib/linkedEditing/browser/linkedEditing","vs/editor/contrib/links/browser/links","vs/editor/contrib/sectionHeaders/browser/sectionHeaders","vs/editor/contrib/stickyScroll/browser/stickyScrollModelProvider","vs/editor/contrib/stickyScroll/browser/stickyScrollProvider","vs/editor/contrib/stickyScroll/browser/stickyScrollWidget","vs/editor/contrib/suggest/browser/suggestWidget","vs/editor/contrib/multicursor/browser/multicursor","vs/editor/contrib/wordHighlighter/browser/wordHighlighter","vs/editor/contrib/zoneWidget/browser/zoneWidget","vs/editor/contrib/gotoError/browser/gotoErrorWidget","vs/editor/contrib/gotoSymbol/browser/peek/referencesWidget","vs/editor/contrib/hover/browser/markerHoverParticipant","vs/editor/contrib/hover/browser/contentHoverRendered","vs/editor/contrib/hover/browser/contentHoverWidgetWrapper","vs/editor/contrib/colorPicker/browser/colorContributions","vs/editor/contrib/hover/browser/hoverActions","vs/editor/contrib/hover/browser/hoverContribution","vs/editor/contrib/inlayHints/browser/inlayHintsContribution","vs/editor/contrib/stickyScroll/browser/stickyScrollActions","vs/editor/contrib/stickyScroll/browser/stickyScrollContribution","vs/editor/standalone/browser/referenceSearch/standaloneReferenceSearch","vs/platform/undoRedo/common/undoRedoService","vs/editor/contrib/clipboard/browser/clipboard","vs/editor/contrib/dropOrPasteInto/browser/copyPasteContribution","vs/editor/contrib/dropOrPasteInto/browser/dropIntoEditorContribution","vs/editor/contrib/snippet/browser/snippetVariables","vs/editor/contrib/inlineCompletions/browser/model/inlineCompletionsModel","vs/editor/contrib/inlineCompletions/browser/model/suggestWidgetAdaptor","vs/editor/contrib/inlineCompletions/browser/controller/commands","vs/editor/contrib/inlineCompletions/browser/hintsWidget/hoverParticipant","vs/editor/contrib/inlineCompletions/browser/inlineCompletions.contribution","vs/editor/contrib/inlineEdits/browser/inlineEditsModel","vs/editor/contrib/inlineEdits/browser/commands","vs/editor/contrib/inlineEdits/browser/inlineEdits.contribution","vs/editor/contrib/suggest/browser/suggestInlineCompletions","vs/editor/contrib/unicodeHighlighter/browser/unicodeHighlighter","vs/editor/editor.all","vs/editor/standalone/browser/standaloneCodeEditor","vs/editor/standalone/browser/standaloneLanguages","vs/editor/standalone/browser/standaloneWebWorker","vs/editor/standalone/browser/standaloneEditor","vs/editor/editor.api","vs/css","vs/editor/edcore.main"];
var __M = function(deps) {
  var result = [];
  for (var i = 0, len = deps.length; i < len; i++) {
    result[i] = __m[deps[i]];
  }
  return result;
};
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[876/*vs/css*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.load = load;
    /**
     * Invoked by the loader at run-time
     *
     * @skipMangle
     */
    function load(name, req, load, config) {
        config = config || {};
        const cssConfig = (config['vs/css'] || {});
        if (cssConfig.disabled) {
            // the plugin is asked to not create any style sheets
            load({});
            return;
        }
        const cssUrl = req.toUrl(name + '.css');
        loadCSS(name, cssUrl, () => {
            load({});
        }, (err) => {
            if (typeof load.error === 'function') {
                load.error('Could not find ' + cssUrl + '.');
            }
        });
    }
    function loadCSS(name, cssUrl, callback, errorback) {
        if (linkTagExists(name, cssUrl)) {
            callback();
            return;
        }
        createLinkTag(name, cssUrl, callback, errorback);
    }
    function linkTagExists(name, cssUrl) {
        // eslint-disable-next-line no-restricted-globals
        const links = window.document.getElementsByTagName('link');
        for (let i = 0, len = links.length; i < len; i++) {
            const nameAttr = links[i].getAttribute('data-name');
            const hrefAttr = links[i].getAttribute('href');
            if (nameAttr === name || hrefAttr === cssUrl) {
                return true;
            }
        }
        return false;
    }
    function createLinkTag(name, cssUrl, callback, errorback) {
        const linkNode = document.createElement('link');
        linkNode.setAttribute('rel', 'stylesheet');
        linkNode.setAttribute('type', 'text/css');
        linkNode.setAttribute('data-name', name);
        attachListeners(name, linkNode, callback, errorback);
        linkNode.setAttribute('href', cssUrl);
        // eslint-disable-next-line no-restricted-globals
        const head = window.document.head || window.document.getElementsByTagName('head')[0];
        head.appendChild(linkNode);
    }
    function attachListeners(name, linkNode, callback, errorback) {
        const unbind = () => {
            linkNode.removeEventListener('load', loadEventListener);
            linkNode.removeEventListener('error', errorEventListener);
        };
        const loadEventListener = (e) => {
            unbind();
            callback();
        };
        const errorEventListener = (e) => {
            unbind();
            errorback(e);
        };
        linkNode.addEventListener('load', loadEventListener);
        linkNode.addEventListener('error', errorEventListener);
    }
});

/*! @license DOMPurify 3.0.5 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.0.5/LICENSE */

const {
	entries,
	setPrototypeOf,
	isFrozen,
	getPrototypeOf,
	getOwnPropertyDescriptor
} = Object;
let {
	freeze,
	seal,
	create
} = Object; // eslint-disable-line import/no-mutable-exports

let {
	apply,
	construct
} = typeof Reflect !== 'undefined' && Reflect;

if (!apply) {
	apply = function apply(fun, thisValue, args) {
		return fun.apply(thisValue, args);
	};
}

if (!freeze) {
	freeze = function freeze(x) {
		return x;
	};
}

if (!seal) {
	seal = function seal(x) {
		return x;
	};
}

if (!construct) {
	construct = function construct(Func, args) {
		return new Func(...args);
	};
}

const arrayForEach = unapply(Array.prototype.forEach);
const arrayPop = unapply(Array.prototype.pop);
const arrayPush = unapply(Array.prototype.push);
const stringToLowerCase = unapply(String.prototype.toLowerCase);
const stringToString = unapply(String.prototype.toString);
const stringMatch = unapply(String.prototype.match);
const stringReplace = unapply(String.prototype.replace);
const stringIndexOf = unapply(String.prototype.indexOf);
const stringTrim = unapply(String.prototype.trim);
const regExpTest = unapply(RegExp.prototype.test);
const typeErrorCreate = unconstruct(TypeError);
function unapply(func) {
	return function (thisArg) {
		for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
			args[_key - 1] = arguments[_key];
		}

		return apply(func, thisArg, args);
	};
}
function unconstruct(func) {
	return function () {
		for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
			args[_key2] = arguments[_key2];
		}

		return construct(func, args);
	};
}
/* Add properties to a lookup table */

function addToSet(set, array, transformCaseFunc) {
	var _transformCaseFunc;

	transformCaseFunc = (_transformCaseFunc = transformCaseFunc) !== null && _transformCaseFunc !== void 0 ? _transformCaseFunc : stringToLowerCase;

	if (setPrototypeOf) {
		// Make 'in' and truthy checks like Boolean(set.constructor)
		// independent of any properties defined on Object.prototype.
		// Prevent prototype setters from intercepting set as a this value.
		setPrototypeOf(set, null);
	}

	let l = array.length;

	while (l--) {
		let element = array[l];

		if (typeof element === 'string') {
			const lcElement = transformCaseFunc(element);

			if (lcElement !== element) {
				// Config presets (e.g. tags.js, attrs.js) are immutable.
				if (!isFrozen(array)) {
					array[l] = lcElement;
				}

				element = lcElement;
			}
		}

		set[element] = true;
	}

	return set;
}
/* Shallow clone an object */

function clone(object) {
	const newObject = create(null);

	for (const [property, value] of entries(object)) {
		newObject[property] = value;
	}

	return newObject;
}
/* This method automatically checks if the prop is function
 * or getter and behaves accordingly. */

function lookupGetter(object, prop) {
	while (object !== null) {
		const desc = getOwnPropertyDescriptor(object, prop);

		if (desc) {
			if (desc.get) {
				return unapply(desc.get);
			}

			if (typeof desc.value === 'function') {
				return unapply(desc.value);
			}
		}

		object = getPrototypeOf(object);
	}

	function fallbackValue(element) {
		console.warn('fallback value for', element);
		return null;
	}

	return fallbackValue;
}

const html$1 = freeze(['a', 'abbr', 'acronym', 'address', 'area', 'article', 'aside', 'audio', 'b', 'bdi', 'bdo', 'big', 'blink', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'content', 'data', 'datalist', 'dd', 'decorator', 'del', 'details', 'dfn', 'dialog', 'dir', 'div', 'dl', 'dt', 'element', 'em', 'fieldset', 'figcaption', 'figure', 'font', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'img', 'input', 'ins', 'kbd', 'label', 'legend', 'li', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meter', 'nav', 'nobr', 'ol', 'optgroup', 'option', 'output', 'p', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'section', 'select', 'shadow', 'small', 'source', 'spacer', 'span', 'strike', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'time', 'tr', 'track', 'tt', 'u', 'ul', 'var', 'video', 'wbr']); // SVG

const svg$1 = freeze(['svg', 'a', 'altglyph', 'altglyphdef', 'altglyphitem', 'animatecolor', 'animatemotion', 'animatetransform', 'circle', 'clippath', 'defs', 'desc', 'ellipse', 'filter', 'font', 'g', 'glyph', 'glyphref', 'hkern', 'image', 'line', 'lineargradient', 'marker', 'mask', 'metadata', 'mpath', 'path', 'pattern', 'polygon', 'polyline', 'radialgradient', 'rect', 'stop', 'style', 'switch', 'symbol', 'text', 'textpath', 'title', 'tref', 'tspan', 'view', 'vkern']);
const svgFilters = freeze(['feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feDropShadow', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feImage', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence']); // List of SVG elements that are disallowed by default.
// We still need to know them so that we can do namespace
// checks properly in case one wants to add them to
// allow-list.

const svgDisallowed = freeze(['animate', 'color-profile', 'cursor', 'discard', 'font-face', 'font-face-format', 'font-face-name', 'font-face-src', 'font-face-uri', 'foreignobject', 'hatch', 'hatchpath', 'mesh', 'meshgradient', 'meshpatch', 'meshrow', 'missing-glyph', 'script', 'set', 'solidcolor', 'unknown', 'use']);
const mathMl$1 = freeze(['math', 'menclose', 'merror', 'mfenced', 'mfrac', 'mglyph', 'mi', 'mlabeledtr', 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded', 'mphantom', 'mroot', 'mrow', 'ms', 'mspace', 'msqrt', 'mstyle', 'msub', 'msup', 'msubsup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder', 'munderover', 'mprescripts']); // Similarly to SVG, we want to know all MathML elements,
// even those that we disallow by default.

const mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'none']);
const text = freeze(['#text']);

const html = freeze(['accept', 'action', 'align', 'alt', 'autocapitalize', 'autocomplete', 'autopictureinpicture', 'autoplay', 'background', 'bgcolor', 'border', 'capture', 'cellpadding', 'cellspacing', 'checked', 'cite', 'class', 'clear', 'color', 'cols', 'colspan', 'controls', 'controlslist', 'coords', 'crossorigin', 'datetime', 'decoding', 'default', 'dir', 'disabled', 'disablepictureinpicture', 'disableremoteplayback', 'download', 'draggable', 'enctype', 'enterkeyhint', 'face', 'for', 'headers', 'height', 'hidden', 'high', 'href', 'hreflang', 'id', 'inputmode', 'integrity', 'ismap', 'kind', 'label', 'lang', 'list', 'loading', 'loop', 'low', 'max', 'maxlength', 'media', 'method', 'min', 'minlength', 'multiple', 'muted', 'name', 'nonce', 'noshade', 'novalidate', 'nowrap', 'open', 'optimum', 'pattern', 'placeholder', 'playsinline', 'poster', 'preload', 'pubdate', 'radiogroup', 'readonly', 'rel', 'required', 'rev', 'reversed', 'role', 'rows', 'rowspan', 'spellcheck', 'scope', 'selected', 'shape', 'size', 'sizes', 'span', 'srclang', 'start', 'src', 'srcset', 'step', 'style', 'summary', 'tabindex', 'title', 'translate', 'type', 'usemap', 'valign', 'value', 'width', 'xmlns', 'slot']);
const svg = freeze(['accent-height', 'accumulate', 'additive', 'alignment-baseline', 'ascent', 'attributename', 'attributetype', 'azimuth', 'basefrequency', 'baseline-shift', 'begin', 'bias', 'by', 'class', 'clip', 'clippathunits', 'clip-path', 'clip-rule', 'color', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'cx', 'cy', 'd', 'dx', 'dy', 'diffuseconstant', 'direction', 'display', 'divisor', 'dur', 'edgemode', 'elevation', 'end', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'filterunits', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'fx', 'fy', 'g1', 'g2', 'glyph-name', 'glyphref', 'gradientunits', 'gradienttransform', 'height', 'href', 'id', 'image-rendering', 'in', 'in2', 'k', 'k1', 'k2', 'k3', 'k4', 'kerning', 'keypoints', 'keysplines', 'keytimes', 'lang', 'lengthadjust', 'letter-spacing', 'kernelmatrix', 'kernelunitlength', 'lighting-color', 'local', 'marker-end', 'marker-mid', 'marker-start', 'markerheight', 'markerunits', 'markerwidth', 'maskcontentunits', 'maskunits', 'max', 'mask', 'media', 'method', 'mode', 'min', 'name', 'numoctaves', 'offset', 'operator', 'opacity', 'order', 'orient', 'orientation', 'origin', 'overflow', 'paint-order', 'path', 'pathlength', 'patterncontentunits', 'patterntransform', 'patternunits', 'points', 'preservealpha', 'preserveaspectratio', 'primitiveunits', 'r', 'rx', 'ry', 'radius', 'refx', 'refy', 'repeatcount', 'repeatdur', 'restart', 'result', 'rotate', 'scale', 'seed', 'shape-rendering', 'specularconstant', 'specularexponent', 'spreadmethod', 'startoffset', 'stddeviation', 'stitchtiles', 'stop-color', 'stop-opacity', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke', 'stroke-width', 'style', 'surfacescale', 'systemlanguage', 'tabindex', 'targetx', 'targety', 'transform', 'transform-origin', 'text-anchor', 'text-decoration', 'text-rendering', 'textlength', 'type', 'u1', 'u2', 'unicode', 'values', 'viewbox', 'visibility', 'version', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'width', 'word-spacing', 'wrap', 'writing-mode', 'xchannelselector', 'ychannelselector', 'x', 'x1', 'x2', 'xmlns', 'y', 'y1', 'y2', 'z', 'zoomandpan']);
const mathMl = freeze(['accent', 'accentunder', 'align', 'bevelled', 'close', 'columnsalign', 'columnlines', 'columnspan', 'denomalign', 'depth', 'dir', 'display', 'displaystyle', 'encoding', 'fence', 'frame', 'height', 'href', 'id', 'largeop', 'length', 'linethickness', 'lspace', 'lquote', 'mathbackground', 'mathcolor', 'mathsize', 'mathvariant', 'maxsize', 'minsize', 'movablelimits', 'notation', 'numalign', 'open', 'rowalign', 'rowlines', 'rowspacing', 'rowspan', 'rspace', 'rquote', 'scriptlevel', 'scriptminsize', 'scriptsizemultiplier', 'selection', 'separator', 'separators', 'stretchy', 'subscriptshift', 'supscriptshift', 'symmetric', 'voffset', 'width', 'xmlns']);
const xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']);

const MUSTACHE_EXPR = seal(/\{\{[\w\W]*|[\w\W]*\}\}/gm); // Specify template detection regex for SAFE_FOR_TEMPLATES mode

const ERB_EXPR = seal(/<%[\w\W]*|[\w\W]*%>/gm);
const TMPLIT_EXPR = seal(/\${[\w\W]*}/gm);
const DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]/); // eslint-disable-line no-useless-escape

const ARIA_ATTR = seal(/^aria-[\-\w]+$/); // eslint-disable-line no-useless-escape

const IS_ALLOWED_URI = seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i // eslint-disable-line no-useless-escape
);
const IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i);
const ATTR_WHITESPACE = seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g // eslint-disable-line no-control-regex
);
const DOCTYPE_NAME = seal(/^html$/i);

var EXPRESSIONS = /*#__PURE__*/Object.freeze({
	__proto__: null,
	MUSTACHE_EXPR: MUSTACHE_EXPR,
	ERB_EXPR: ERB_EXPR,
	TMPLIT_EXPR: TMPLIT_EXPR,
	DATA_ATTR: DATA_ATTR,
	ARIA_ATTR: ARIA_ATTR,
	IS_ALLOWED_URI: IS_ALLOWED_URI,
	IS_SCRIPT_OR_DATA: IS_SCRIPT_OR_DATA,
	ATTR_WHITESPACE: ATTR_WHITESPACE,
	DOCTYPE_NAME: DOCTYPE_NAME
});

const getGlobal = () => typeof window === 'undefined' ? null : window;
/**
 * Creates a no-op policy for internal use only.
 * Don't export this function outside this module!
 * @param {?TrustedTypePolicyFactory} trustedTypes The policy factory.
 * @param {HTMLScriptElement} purifyHostElement The Script element used to load DOMPurify (to determine policy name suffix).
 * @return {?TrustedTypePolicy} The policy created (or null, if Trusted Types
 * are not supported or creating the policy failed).
 */


const _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, purifyHostElement) {
	if (typeof trustedTypes !== 'object' || typeof trustedTypes.createPolicy !== 'function') {
		return null;
	} // Allow the callers to control the unique policy name
	// by adding a data-tt-policy-suffix to the script element with the DOMPurify.
	// Policy creation with duplicate names throws in Trusted Types.


	let suffix = null;
	const ATTR_NAME = 'data-tt-policy-suffix';

	if (purifyHostElement && purifyHostElement.hasAttribute(ATTR_NAME)) {
		suffix = purifyHostElement.getAttribute(ATTR_NAME);
	}

	const policyName = 'dompurify' + (suffix ? '#' + suffix : '');

	try {
		return trustedTypes.createPolicy(policyName, {
			createHTML(html) {
				return html;
			},

			createScriptURL(scriptUrl) {
				return scriptUrl;
			}

		});
	} catch (_) {
		// Policy creation failed (most likely another DOMPurify script has
		// already run). Skip creating the policy, as this will only cause errors
		// if TT are enforced.
		console.warn('TrustedTypes policy ' + policyName + ' could not be created.');
		return null;
	}
};

function createDOMPurify() {
	let window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal();

	const DOMPurify = root => createDOMPurify(root);
	/**
	 * Version label, exposed for easier checks
	 * if DOMPurify is up to date or not
	 */


	DOMPurify.version = '3.0.5';
	/**
	 * Array of elements that DOMPurify removed during sanitation.
	 * Empty if nothing was removed.
	 */

	DOMPurify.removed = [];

	if (!window || !window.document || window.document.nodeType !== 9) {
		// Not running in a browser, provide a factory function
		// so that you can pass your own Window
		DOMPurify.isSupported = false;
		return DOMPurify;
	}

	const originalDocument = window.document;
	const currentScript = originalDocument.currentScript;
	let {
		document
	} = window;
	const {
		DocumentFragment,
		HTMLTemplateElement,
		Node,
		Element,
		NodeFilter,
		NamedNodeMap = window.NamedNodeMap || window.MozNamedAttrMap,
		HTMLFormElement,
		DOMParser,
		trustedTypes
	} = window;
	const ElementPrototype = Element.prototype;
	const cloneNode = lookupGetter(ElementPrototype, 'cloneNode');
	const getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');
	const getChildNodes = lookupGetter(ElementPrototype, 'childNodes');
	const getParentNode = lookupGetter(ElementPrototype, 'parentNode'); // As per issue #47, the web-components registry is inherited by a
	// new document created via createHTMLDocument. As per the spec
	// (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)
	// a new empty registry is used when creating a template contents owner
	// document, so we use that as our parent document to ensure nothing
	// is inherited.

	if (typeof HTMLTemplateElement === 'function') {
		const template = document.createElement('template');

		if (template.content && template.content.ownerDocument) {
			document = template.content.ownerDocument;
		}
	}

	let trustedTypesPolicy;
	let emptyHTML = '';
	const {
		implementation,
		createNodeIterator,
		createDocumentFragment,
		getElementsByTagName
	} = document;
	const {
		importNode
	} = originalDocument;
	let hooks = {};
	/**
	 * Expose whether this browser supports running the full DOMPurify.
	 */

	DOMPurify.isSupported = typeof entries === 'function' && typeof getParentNode === 'function' && implementation && implementation.createHTMLDocument !== undefined;
	const {
		MUSTACHE_EXPR,
		ERB_EXPR,
		TMPLIT_EXPR,
		DATA_ATTR,
		ARIA_ATTR,
		IS_SCRIPT_OR_DATA,
		ATTR_WHITESPACE
	} = EXPRESSIONS;
	let {
		IS_ALLOWED_URI: IS_ALLOWED_URI$1
	} = EXPRESSIONS;
	/**
	 * We consider the elements and attributes below to be safe. Ideally
	 * don't add any new ones but feel free to remove unwanted ones.
	 */

	/* allowed element names */

	let ALLOWED_TAGS = null;
	const DEFAULT_ALLOWED_TAGS = addToSet({}, [...html$1, ...svg$1, ...svgFilters, ...mathMl$1, ...text]);
	/* Allowed attribute names */

	let ALLOWED_ATTR = null;
	const DEFAULT_ALLOWED_ATTR = addToSet({}, [...html, ...svg, ...mathMl, ...xml]);
	/*
	 * Configure how DOMPUrify should handle custom elements and their attributes as well as customized built-in elements.
	 * @property {RegExp|Function|null} tagNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any custom elements)
	 * @property {RegExp|Function|null} attributeNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any attributes not on the allow list)
	 * @property {boolean} allowCustomizedBuiltInElements allow custom elements derived from built-ins if they pass CUSTOM_ELEMENT_HANDLING.tagNameCheck. Default: `false`.
	 */

	let CUSTOM_ELEMENT_HANDLING = Object.seal(Object.create(null, {
		tagNameCheck: {
			writable: true,
			configurable: false,
			enumerable: true,
			value: null
		},
		attributeNameCheck: {
			writable: true,
			configurable: false,
			enumerable: true,
			value: null
		},
		allowCustomizedBuiltInElements: {
			writable: true,
			configurable: false,
			enumerable: true,
			value: false
		}
	}));
	/* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */

	let FORBID_TAGS = null;
	/* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */

	let FORBID_ATTR = null;
	/* Decide if ARIA attributes are okay */

	let ALLOW_ARIA_ATTR = true;
	/* Decide if custom data attributes are okay */

	let ALLOW_DATA_ATTR = true;
	/* Decide if unknown protocols are okay */

	let ALLOW_UNKNOWN_PROTOCOLS = false;
	/* Decide if self-closing tags in attributes are allowed.
	 * Usually removed due to a mXSS issue in jQuery 3.0 */

	let ALLOW_SELF_CLOSE_IN_ATTR = true;
	/* Output should be safe for common template engines.
	 * This means, DOMPurify removes data attributes, mustaches and ERB
	 */

	let SAFE_FOR_TEMPLATES = false;
	/* Decide if document with <html>... should be returned */

	let WHOLE_DOCUMENT = false;
	/* Track whether config is already set on this instance of DOMPurify. */

	let SET_CONFIG = false;
	/* Decide if all elements (e.g. style, script) must be children of
	 * document.body. By default, browsers might move them to document.head */

	let FORCE_BODY = false;
	/* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html
	 * string (or a TrustedHTML object if Trusted Types are supported).
	 * If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead
	 */

	let RETURN_DOM = false;
	/* Decide if a DOM `DocumentFragment` should be returned, instead of a html
	 * string  (or a TrustedHTML object if Trusted Types are supported) */

	let RETURN_DOM_FRAGMENT = false;
	/* Try to return a Trusted Type object instead of a string, return a string in
	 * case Trusted Types are not supported  */

	let RETURN_TRUSTED_TYPE = false;
	/* Output should be free from DOM clobbering attacks?
	 * This sanitizes markups named with colliding, clobberable built-in DOM APIs.
	 */

	let SANITIZE_DOM = true;
	/* Achieve full DOM Clobbering protection by isolating the namespace of named
	 * properties and JS variables, mitigating attacks that abuse the HTML/DOM spec rules.
	 *
	 * HTML/DOM spec rules that enable DOM Clobbering:
	 *   - Named Access on Window (§7.3.3)
	 *   - DOM Tree Accessors (§3.1.5)
	 *   - Form Element Parent-Child Relations (§4.10.3)
	 *   - Iframe srcdoc / Nested WindowProxies (§4.8.5)
	 *   - HTMLCollection (§4.2.10.2)
	 *
	 * Namespace isolation is implemented by prefixing `id` and `name` attributes
	 * with a constant string, i.e., `user-content-`
	 */

	let SANITIZE_NAMED_PROPS = false;
	const SANITIZE_NAMED_PROPS_PREFIX = 'user-content-';
	/* Keep element content when removing element? */

	let KEEP_CONTENT = true;
	/* If a `Node` is passed to sanitize(), then performs sanitization in-place instead
	 * of importing it into a new Document and returning a sanitized copy */

	let IN_PLACE = false;
	/* Allow usage of profiles like html, svg and mathMl */

	let USE_PROFILES = {};
	/* Tags to ignore content of when KEEP_CONTENT is true */

	let FORBID_CONTENTS = null;
	const DEFAULT_FORBID_CONTENTS = addToSet({}, ['annotation-xml', 'audio', 'colgroup', 'desc', 'foreignobject', 'head', 'iframe', 'math', 'mi', 'mn', 'mo', 'ms', 'mtext', 'noembed', 'noframes', 'noscript', 'plaintext', 'script', 'style', 'svg', 'template', 'thead', 'title', 'video', 'xmp']);
	/* Tags that are safe for data: URIs */

	let DATA_URI_TAGS = null;
	const DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']);
	/* Attributes safe for values like "javascript:" */

	let URI_SAFE_ATTRIBUTES = null;
	const DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ['alt', 'class', 'for', 'id', 'label', 'name', 'pattern', 'placeholder', 'role', 'summary', 'title', 'value', 'style', 'xmlns']);
	const MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
	const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
	const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';
	/* Document namespace */

	let NAMESPACE = HTML_NAMESPACE;
	let IS_EMPTY_INPUT = false;
	/* Allowed XHTML+XML namespaces */

	let ALLOWED_NAMESPACES = null;
	const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString);
	/* Parsing of strict XHTML documents */

	let PARSER_MEDIA_TYPE;
	const SUPPORTED_PARSER_MEDIA_TYPES = ['application/xhtml+xml', 'text/html'];
	const DEFAULT_PARSER_MEDIA_TYPE = 'text/html';
	let transformCaseFunc;
	/* Keep a reference to config to pass to hooks */

	let CONFIG = null;
	/* Ideally, do not touch anything below this line */

	/* ______________________________________________ */

	const formElement = document.createElement('form');

	const isRegexOrFunction = function isRegexOrFunction(testValue) {
		return testValue instanceof RegExp || testValue instanceof Function;
	};
	/**
	 * _parseConfig
	 *
	 * @param  {Object} cfg optional config literal
	 */
	// eslint-disable-next-line complexity


	const _parseConfig = function _parseConfig(cfg) {
		if (CONFIG && CONFIG === cfg) {
			return;
		}
		/* Shield configuration object from tampering */


		if (!cfg || typeof cfg !== 'object') {
			cfg = {};
		}
		/* Shield configuration object from prototype pollution */


		cfg = clone(cfg);
		PARSER_MEDIA_TYPE = // eslint-disable-next-line unicorn/prefer-includes
			SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? PARSER_MEDIA_TYPE = DEFAULT_PARSER_MEDIA_TYPE : PARSER_MEDIA_TYPE = cfg.PARSER_MEDIA_TYPE; // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is.

		transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? stringToString : stringToLowerCase;
		/* Set configuration parameters */

		ALLOWED_TAGS = 'ALLOWED_TAGS' in cfg ? addToSet({}, cfg.ALLOWED_TAGS, transformCaseFunc) : DEFAULT_ALLOWED_TAGS;
		ALLOWED_ATTR = 'ALLOWED_ATTR' in cfg ? addToSet({}, cfg.ALLOWED_ATTR, transformCaseFunc) : DEFAULT_ALLOWED_ATTR;
		ALLOWED_NAMESPACES = 'ALLOWED_NAMESPACES' in cfg ? addToSet({}, cfg.ALLOWED_NAMESPACES, stringToString) : DEFAULT_ALLOWED_NAMESPACES;
		URI_SAFE_ATTRIBUTES = 'ADD_URI_SAFE_ATTR' in cfg ? addToSet(clone(DEFAULT_URI_SAFE_ATTRIBUTES), // eslint-disable-line indent
			cfg.ADD_URI_SAFE_ATTR, // eslint-disable-line indent
			transformCaseFunc // eslint-disable-line indent
		) // eslint-disable-line indent
			: DEFAULT_URI_SAFE_ATTRIBUTES;
		DATA_URI_TAGS = 'ADD_DATA_URI_TAGS' in cfg ? addToSet(clone(DEFAULT_DATA_URI_TAGS), // eslint-disable-line indent
			cfg.ADD_DATA_URI_TAGS, // eslint-disable-line indent
			transformCaseFunc // eslint-disable-line indent
		) // eslint-disable-line indent
			: DEFAULT_DATA_URI_TAGS;
		FORBID_CONTENTS = 'FORBID_CONTENTS' in cfg ? addToSet({}, cfg.FORBID_CONTENTS, transformCaseFunc) : DEFAULT_FORBID_CONTENTS;
		FORBID_TAGS = 'FORBID_TAGS' in cfg ? addToSet({}, cfg.FORBID_TAGS, transformCaseFunc) : {};
		FORBID_ATTR = 'FORBID_ATTR' in cfg ? addToSet({}, cfg.FORBID_ATTR, transformCaseFunc) : {};
		USE_PROFILES = 'USE_PROFILES' in cfg ? cfg.USE_PROFILES : false;
		ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true

		ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true

		ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false

		ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false; // Default true

		SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false

		WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false

		RETURN_DOM = cfg.RETURN_DOM || false; // Default false

		RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false

		RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false

		FORCE_BODY = cfg.FORCE_BODY || false; // Default false

		SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true

		SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false

		KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true

		IN_PLACE = cfg.IN_PLACE || false; // Default false

		IS_ALLOWED_URI$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI;
		NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE;
		CUSTOM_ELEMENT_HANDLING = cfg.CUSTOM_ELEMENT_HANDLING || {};

		if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck)) {
			CUSTOM_ELEMENT_HANDLING.tagNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck;
		}

		if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)) {
			CUSTOM_ELEMENT_HANDLING.attributeNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck;
		}

		if (cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements === 'boolean') {
			CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements;
		}

		if (SAFE_FOR_TEMPLATES) {
			ALLOW_DATA_ATTR = false;
		}

		if (RETURN_DOM_FRAGMENT) {
			RETURN_DOM = true;
		}
		/* Parse profile info */


		if (USE_PROFILES) {
			ALLOWED_TAGS = addToSet({}, [...text]);
			ALLOWED_ATTR = [];

			if (USE_PROFILES.html === true) {
				addToSet(ALLOWED_TAGS, html$1);
				addToSet(ALLOWED_ATTR, html);
			}

			if (USE_PROFILES.svg === true) {
				addToSet(ALLOWED_TAGS, svg$1);
				addToSet(ALLOWED_ATTR, svg);
				addToSet(ALLOWED_ATTR, xml);
			}

			if (USE_PROFILES.svgFilters === true) {
				addToSet(ALLOWED_TAGS, svgFilters);
				addToSet(ALLOWED_ATTR, svg);
				addToSet(ALLOWED_ATTR, xml);
			}

			if (USE_PROFILES.mathMl === true) {
				addToSet(ALLOWED_TAGS, mathMl$1);
				addToSet(ALLOWED_ATTR, mathMl);
				addToSet(ALLOWED_ATTR, xml);
			}
		}
		/* Merge configuration parameters */


		if (cfg.ADD_TAGS) {
			if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {
				ALLOWED_TAGS = clone(ALLOWED_TAGS);
			}

			addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc);
		}

		if (cfg.ADD_ATTR) {
			if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {
				ALLOWED_ATTR = clone(ALLOWED_ATTR);
			}

			addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc);
		}

		if (cfg.ADD_URI_SAFE_ATTR) {
			addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc);
		}

		if (cfg.FORBID_CONTENTS) {
			if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
				FORBID_CONTENTS = clone(FORBID_CONTENTS);
			}

			addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc);
		}
		/* Add #text in case KEEP_CONTENT is set to true */


		if (KEEP_CONTENT) {
			ALLOWED_TAGS['#text'] = true;
		}
		/* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */


		if (WHOLE_DOCUMENT) {
			addToSet(ALLOWED_TAGS, ['html', 'head', 'body']);
		}
		/* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */


		if (ALLOWED_TAGS.table) {
			addToSet(ALLOWED_TAGS, ['tbody']);
			delete FORBID_TAGS.tbody;
		}

		if (cfg.TRUSTED_TYPES_POLICY) {
			if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== 'function') {
				throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');
			}

			if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== 'function') {
				throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');
			} // Overwrite existing TrustedTypes policy.


			trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY; // Sign local variables required by `sanitize`.

			emptyHTML = trustedTypesPolicy.createHTML('');
		} else {
			// Uninitialized policy, attempt to initialize the internal dompurify policy.
			if (trustedTypesPolicy === undefined) {
				trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript);
			} // If creating the internal policy succeeded sign internal variables.


			if (trustedTypesPolicy !== null && typeof emptyHTML === 'string') {
				emptyHTML = trustedTypesPolicy.createHTML('');
			}
		} // Prevent further manipulation of configuration.
		// Not available in IE8, Safari 5, etc.


		if (freeze) {
			freeze(cfg);
		}

		CONFIG = cfg;
	};

	const MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']);
	const HTML_INTEGRATION_POINTS = addToSet({}, ['foreignobject', 'desc', 'title', 'annotation-xml']); // Certain elements are allowed in both SVG and HTML
	// namespace. We need to specify them explicitly
	// so that they don't get erroneously deleted from
	// HTML namespace.

	const COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, ['title', 'style', 'font', 'a', 'script']);
	/* Keep track of all possible SVG and MathML tags
	 * so that we can perform the namespace checks
	 * correctly. */

	const ALL_SVG_TAGS = addToSet({}, svg$1);
	addToSet(ALL_SVG_TAGS, svgFilters);
	addToSet(ALL_SVG_TAGS, svgDisallowed);
	const ALL_MATHML_TAGS = addToSet({}, mathMl$1);
	addToSet(ALL_MATHML_TAGS, mathMlDisallowed);
	/**
	 *
	 *
	 * @param  {Element} element a DOM element whose namespace is being checked
	 * @returns {boolean} Return false if the element has a
	 *  namespace that a spec-compliant parser would never
	 *  return. Return true otherwise.
	 */

	const _checkValidNamespace = function _checkValidNamespace(element) {
		let parent = getParentNode(element); // In JSDOM, if we're inside shadow DOM, then parentNode
		// can be null. We just simulate parent in this case.

		if (!parent || !parent.tagName) {
			parent = {
				namespaceURI: NAMESPACE,
				tagName: 'template'
			};
		}

		const tagName = stringToLowerCase(element.tagName);
		const parentTagName = stringToLowerCase(parent.tagName);

		if (!ALLOWED_NAMESPACES[element.namespaceURI]) {
			return false;
		}

		if (element.namespaceURI === SVG_NAMESPACE) {
			// The only way to switch from HTML namespace to SVG
			// is via <svg>. If it happens via any other tag, then
			// it should be killed.
			if (parent.namespaceURI === HTML_NAMESPACE) {
				return tagName === 'svg';
			} // The only way to switch from MathML to SVG is via`
			// svg if parent is either <annotation-xml> or MathML
			// text integration points.


			if (parent.namespaceURI === MATHML_NAMESPACE) {
				return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
			} // We only allow elements that are defined in SVG
			// spec. All others are disallowed in SVG namespace.


			return Boolean(ALL_SVG_TAGS[tagName]);
		}

		if (element.namespaceURI === MATHML_NAMESPACE) {
			// The only way to switch from HTML namespace to MathML
			// is via <math>. If it happens via any other tag, then
			// it should be killed.
			if (parent.namespaceURI === HTML_NAMESPACE) {
				return tagName === 'math';
			} // The only way to switch from SVG to MathML is via
			// <math> and HTML integration points


			if (parent.namespaceURI === SVG_NAMESPACE) {
				return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];
			} // We only allow elements that are defined in MathML
			// spec. All others are disallowed in MathML namespace.


			return Boolean(ALL_MATHML_TAGS[tagName]);
		}

		if (element.namespaceURI === HTML_NAMESPACE) {
			// The only way to switch from SVG to HTML is via
			// HTML integration points, and from MathML to HTML
			// is via MathML text integration points
			if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {
				return false;
			}

			if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {
				return false;
			} // We disallow tags that are specific for MathML
			// or SVG and should never appear in HTML namespace


			return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);
		} // For XHTML and XML documents that support custom namespaces


		if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && ALLOWED_NAMESPACES[element.namespaceURI]) {
			return true;
		} // The code should never reach this place (this means
		// that the element somehow got namespace that is not
		// HTML, SVG, MathML or allowed via ALLOWED_NAMESPACES).
		// Return false just in case.


		return false;
	};
	/**
	 * _forceRemove
	 *
	 * @param  {Node} node a DOM node
	 */


	const _forceRemove = function _forceRemove(node) {
		arrayPush(DOMPurify.removed, {
			element: node
		});

		try {
			// eslint-disable-next-line unicorn/prefer-dom-node-remove
			node.parentNode.removeChild(node);
		} catch (_) {
			node.remove();
		}
	};
	/**
	 * _removeAttribute
	 *
	 * @param  {String} name an Attribute name
	 * @param  {Node} node a DOM node
	 */


	const _removeAttribute = function _removeAttribute(name, node) {
		try {
			arrayPush(DOMPurify.removed, {
				attribute: node.getAttributeNode(name),
				from: node
			});
		} catch (_) {
			arrayPush(DOMPurify.removed, {
				attribute: null,
				from: node
			});
		}

		node.removeAttribute(name); // We void attribute values for unremovable "is"" attributes

		if (name === 'is' && !ALLOWED_ATTR[name]) {
			if (RETURN_DOM || RETURN_DOM_FRAGMENT) {
				try {
					_forceRemove(node);
				} catch (_) { }
			} else {
				try {
					node.setAttribute(name, '');
				} catch (_) { }
			}
		}
	};
	/**
	 * _initDocument
	 *
	 * @param  {String} dirty a string of dirty markup
	 * @return {Document} a DOM, filled with the dirty markup
	 */


	const _initDocument = function _initDocument(dirty) {
		/* Create a HTML document */
		let doc;
		let leadingWhitespace;

		if (FORCE_BODY) {
			dirty = '<remove></remove>' + dirty;
		} else {
			/* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */
			const matches = stringMatch(dirty, /^[\r\n\t ]+/);
			leadingWhitespace = matches && matches[0];
		}

		if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && NAMESPACE === HTML_NAMESPACE) {
			// Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict)
			dirty = '<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>' + dirty + '</body></html>';
		}

		const dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty;
		/*
		 * Use the DOMParser API by default, fallback later if needs be
		 * DOMParser not work for svg when has multiple root element.
		 */

		if (NAMESPACE === HTML_NAMESPACE) {
			try {
				doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE);
			} catch (_) { }
		}
		/* Use createHTMLDocument in case DOMParser is not available */


		if (!doc || !doc.documentElement) {
			doc = implementation.createDocument(NAMESPACE, 'template', null);

			try {
				doc.documentElement.innerHTML = IS_EMPTY_INPUT ? emptyHTML : dirtyPayload;
			} catch (_) {// Syntax error if dirtyPayload is invalid xml
			}
		}

		const body = doc.body || doc.documentElement;

		if (dirty && leadingWhitespace) {
			body.insertBefore(document.createTextNode(leadingWhitespace), body.childNodes[0] || null);
		}
		/* Work on whole document or just its body */


		if (NAMESPACE === HTML_NAMESPACE) {
			return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[0];
		}

		return WHOLE_DOCUMENT ? doc.documentElement : body;
	};
	/**
	 * _createIterator
	 *
	 * @param  {Document} root document/fragment to create iterator for
	 * @return {Iterator} iterator instance
	 */


	const _createIterator = function _createIterator(root) {
		return createNodeIterator.call(root.ownerDocument || root, root, // eslint-disable-next-line no-bitwise
			NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT, null, false);
	};
	/**
	 * _isClobbered
	 *
	 * @param  {Node} elm element to check for clobbering attacks
	 * @return {Boolean} true if clobbered, false if safe
	 */


	const _isClobbered = function _isClobbered(elm) {
		return elm instanceof HTMLFormElement && (typeof elm.nodeName !== 'string' || typeof elm.textContent !== 'string' || typeof elm.removeChild !== 'function' || !(elm.attributes instanceof NamedNodeMap) || typeof elm.removeAttribute !== 'function' || typeof elm.setAttribute !== 'function' || typeof elm.namespaceURI !== 'string' || typeof elm.insertBefore !== 'function' || typeof elm.hasChildNodes !== 'function');
	};
	/**
	 * _isNode
	 *
	 * @param  {Node} obj object to check whether it's a DOM node
	 * @return {Boolean} true is object is a DOM node
	 */


	const _isNode = function _isNode(object) {
		return typeof Node === 'object' ? object instanceof Node : object && typeof object === 'object' && typeof object.nodeType === 'number' && typeof object.nodeName === 'string';
	};
	/**
	 * _executeHook
	 * Execute user configurable hooks
	 *
	 * @param  {String} entryPoint  Name of the hook's entry point
	 * @param  {Node} currentNode node to work on with the hook
	 * @param  {Object} data additional hook parameters
	 */


	const _executeHook = function _executeHook(entryPoint, currentNode, data) {
		if (!hooks[entryPoint]) {
			return;
		}

		arrayForEach(hooks[entryPoint], hook => {
			hook.call(DOMPurify, currentNode, data, CONFIG);
		});
	};
	/**
	 * _sanitizeElements
	 *
	 * @protect nodeName
	 * @protect textContent
	 * @protect removeChild
	 *
	 * @param   {Node} currentNode to check for permission to exist
	 * @return  {Boolean} true if node was killed, false if left alive
	 */


	const _sanitizeElements = function _sanitizeElements(currentNode) {
		let content;
		/* Execute a hook if present */

		_executeHook('beforeSanitizeElements', currentNode, null);
		/* Check if element is clobbered or can clobber */


		if (_isClobbered(currentNode)) {
			_forceRemove(currentNode);

			return true;
		}
		/* Now let's check the element's type and name */


		const tagName = transformCaseFunc(currentNode.nodeName);
		/* Execute a hook if present */

		_executeHook('uponSanitizeElement', currentNode, {
			tagName,
			allowedTags: ALLOWED_TAGS
		});
		/* Detect mXSS attempts abusing namespace confusion */


		if (currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && (!_isNode(currentNode.content) || !_isNode(currentNode.content.firstElementChild)) && regExpTest(/<[/\w]/g, currentNode.innerHTML) && regExpTest(/<[/\w]/g, currentNode.textContent)) {
			_forceRemove(currentNode);

			return true;
		}
		/* Remove element if anything forbids its presence */


		if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
			/* Check if we have a custom element to handle */
			if (!FORBID_TAGS[tagName] && _basicCustomElementTest(tagName)) {
				if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) return false;
				if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) return false;
			}
			/* Keep content except for bad-listed elements */


			if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
				const parentNode = getParentNode(currentNode) || currentNode.parentNode;
				const childNodes = getChildNodes(currentNode) || currentNode.childNodes;

				if (childNodes && parentNode) {
					const childCount = childNodes.length;

					for (let i = childCount - 1; i >= 0; --i) {
						parentNode.insertBefore(cloneNode(childNodes[i], true), getNextSibling(currentNode));
					}
				}
			}

			_forceRemove(currentNode);

			return true;
		}
		/* Check whether element has a valid namespace */


		if (currentNode instanceof Element && !_checkValidNamespace(currentNode)) {
			_forceRemove(currentNode);

			return true;
		}
		/* Make sure that older browsers don't get fallback-tag mXSS */


		if ((tagName === 'noscript' || tagName === 'noembed' || tagName === 'noframes') && regExpTest(/<\/no(script|embed|frames)/i, currentNode.innerHTML)) {
			_forceRemove(currentNode);

			return true;
		}
		/* Sanitize element content to be template-safe */


		if (SAFE_FOR_TEMPLATES && currentNode.nodeType === 3) {
			/* Get the element's text content */
			content = currentNode.textContent;
			content = stringReplace(content, MUSTACHE_EXPR, ' ');
			content = stringReplace(content, ERB_EXPR, ' ');
			content = stringReplace(content, TMPLIT_EXPR, ' ');

			if (currentNode.textContent !== content) {
				arrayPush(DOMPurify.removed, {
					element: currentNode.cloneNode()
				});
				currentNode.textContent = content;
			}
		}
		/* Execute a hook if present */


		_executeHook('afterSanitizeElements', currentNode, null);

		return false;
	};
	/**
	 * _isValidAttribute
	 *
	 * @param  {string} lcTag Lowercase tag name of containing element.
	 * @param  {string} lcName Lowercase attribute name.
	 * @param  {string} value Attribute value.
	 * @return {Boolean} Returns true if `value` is valid, otherwise false.
	 */
	// eslint-disable-next-line complexity


	const _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) {
		/* Make sure attribute cannot clobber */
		if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) {
			return false;
		}
		/* Allow valid data-* attributes: At least one character after "-"
				(https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)
				XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)
				We don't need to check the value; it's always URI safe. */


		if (ALLOW_DATA_ATTR && !FORBID_ATTR[lcName] && regExpTest(DATA_ATTR, lcName)); else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR, lcName)); else if (!ALLOWED_ATTR[lcName] || FORBID_ATTR[lcName]) {
			if ( // First condition does a very basic check if a) it's basically a valid custom element tagname AND
				// b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
				// and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck
				_basicCustomElementTest(lcTag) && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(lcTag)) && (CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.attributeNameCheck, lcName) || CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.attributeNameCheck(lcName)) || // Alternative, second condition checks if it's an `is`-attribute, AND
				// the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
				lcName === 'is' && CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(value))); else {
				return false;
			}
			/* Check value is safe. First, is attr inert? If so, is safe */

		} else if (URI_SAFE_ATTRIBUTES[lcName]); else if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value, ATTR_WHITESPACE, ''))); else if ((lcName === 'src' || lcName === 'xlink:href' || lcName === 'href') && lcTag !== 'script' && stringIndexOf(value, 'data:') === 0 && DATA_URI_TAGS[lcTag]); else if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA, stringReplace(value, ATTR_WHITESPACE, ''))); else if (value) {
			return false;
		} else;

		return true;
	};
	/**
	 * _basicCustomElementCheck
	 * checks if at least one dash is included in tagName, and it's not the first char
	 * for more sophisticated checking see https://github.com/sindresorhus/validate-element-name
	 * @param {string} tagName name of the tag of the node to sanitize
	 */


	const _basicCustomElementTest = function _basicCustomElementTest(tagName) {
		return tagName.indexOf('-') > 0;
	};
	/**
	 * _sanitizeAttributes
	 *
	 * @protect attributes
	 * @protect nodeName
	 * @protect removeAttribute
	 * @protect setAttribute
	 *
	 * @param  {Node} currentNode to sanitize
	 */


	const _sanitizeAttributes = function _sanitizeAttributes(currentNode) {
		let attr;
		let value;
		let lcName;
		let l;
		/* Execute a hook if present */

		_executeHook('beforeSanitizeAttributes', currentNode, null);

		const {
			attributes
		} = currentNode;
		/* Check if we have attributes; if not we might have a text node */

		if (!attributes) {
			return;
		}

		const hookEvent = {
			attrName: '',
			attrValue: '',
			keepAttr: true,
			allowedAttributes: ALLOWED_ATTR
		};
		l = attributes.length;
		/* Go backwards over all attributes; safely remove bad ones */

		while (l--) {
			attr = attributes[l];
			const {
				name,
				namespaceURI
			} = attr;
			value = name === 'value' ? attr.value : stringTrim(attr.value);
			lcName = transformCaseFunc(name);
			/* Execute a hook if present */

			hookEvent.attrName = lcName;
			hookEvent.attrValue = value;
			hookEvent.keepAttr = true;
			hookEvent.forceKeepAttr = undefined; // Allows developers to see this is a property they can set

			_executeHook('uponSanitizeAttribute', currentNode, hookEvent);

			value = hookEvent.attrValue;
			/* Did the hooks approve of the attribute? */

			if (hookEvent.forceKeepAttr) {
				continue;
			}
			/* Remove attribute */


			_removeAttribute(name, currentNode);
			/* Did the hooks approve of the attribute? */


			if (!hookEvent.keepAttr) {
				continue;
			}
			/* Work around a security issue in jQuery 3.0 */


			if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(/\/>/i, value)) {
				_removeAttribute(name, currentNode);

				continue;
			}
			/* Sanitize attribute content to be template-safe */


			if (SAFE_FOR_TEMPLATES) {
				value = stringReplace(value, MUSTACHE_EXPR, ' ');
				value = stringReplace(value, ERB_EXPR, ' ');
				value = stringReplace(value, TMPLIT_EXPR, ' ');
			}
			/* Is `value` valid for this attribute? */


			const lcTag = transformCaseFunc(currentNode.nodeName);

			if (!_isValidAttribute(lcTag, lcName, value)) {
				continue;
			}
			/* Full DOM Clobbering protection via namespace isolation,
			 * Prefix id and name attributes with `user-content-`
			 */


			if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name')) {
				// Remove the attribute with this value
				_removeAttribute(name, currentNode); // Prefix the value and later re-create the attribute with the sanitized value


				value = SANITIZE_NAMED_PROPS_PREFIX + value;
			}
			/* Handle attributes that require Trusted Types */


			if (trustedTypesPolicy && typeof trustedTypes === 'object' && typeof trustedTypes.getAttributeType === 'function') {
				if (namespaceURI); else {
					switch (trustedTypes.getAttributeType(lcTag, lcName)) {
						case 'TrustedHTML':
							{
								value = trustedTypesPolicy.createHTML(value);
								break;
							}

						case 'TrustedScriptURL':
							{
								value = trustedTypesPolicy.createScriptURL(value);
								break;
							}
					}
				}
			}
			/* Handle invalid data-* attribute set by try-catching it */


			try {
				if (namespaceURI) {
					currentNode.setAttributeNS(namespaceURI, name, value);
				} else {
					/* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */
					currentNode.setAttribute(name, value);
				}

				arrayPop(DOMPurify.removed);
			} catch (_) { }
		}
		/* Execute a hook if present */


		_executeHook('afterSanitizeAttributes', currentNode, null);
	};
	/**
	 * _sanitizeShadowDOM
	 *
	 * @param  {DocumentFragment} fragment to iterate over recursively
	 */


	const _sanitizeShadowDOM = function _sanitizeShadowDOM(fragment) {
		let shadowNode;

		const shadowIterator = _createIterator(fragment);
		/* Execute a hook if present */


		_executeHook('beforeSanitizeShadowDOM', fragment, null);

		while (shadowNode = shadowIterator.nextNode()) {
			/* Execute a hook if present */
			_executeHook('uponSanitizeShadowNode', shadowNode, null);
			/* Sanitize tags and elements */


			if (_sanitizeElements(shadowNode)) {
				continue;
			}
			/* Deep shadow DOM detected */


			if (shadowNode.content instanceof DocumentFragment) {
				_sanitizeShadowDOM(shadowNode.content);
			}
			/* Check attributes, sanitize if necessary */


			_sanitizeAttributes(shadowNode);
		}
		/* Execute a hook if present */


		_executeHook('afterSanitizeShadowDOM', fragment, null);
	};
	/**
	 * Sanitize
	 * Public method providing core sanitation functionality
	 *
	 * @param {String|Node} dirty string or DOM node
	 * @param {Object} configuration object
	 */
	// eslint-disable-next-line complexity


	DOMPurify.sanitize = function (dirty) {
		let cfg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
		let body;
		let importedNode;
		let currentNode;
		let returnNode;
		/* Make sure we have a string to sanitize.
			DO NOT return early, as this will return the wrong type if
			the user has requested a DOM object rather than a string */

		IS_EMPTY_INPUT = !dirty;

		if (IS_EMPTY_INPUT) {
			dirty = '<!-->';
		}
		/* Stringify, in case dirty is an object */


		if (typeof dirty !== 'string' && !_isNode(dirty)) {
			if (typeof dirty.toString === 'function') {
				dirty = dirty.toString();

				if (typeof dirty !== 'string') {
					throw typeErrorCreate('dirty is not a string, aborting');
				}
			} else {
				throw typeErrorCreate('toString is not a function');
			}
		}
		/* Return dirty HTML if DOMPurify cannot run */


		if (!DOMPurify.isSupported) {
			return dirty;
		}
		/* Assign config vars */


		if (!SET_CONFIG) {
			_parseConfig(cfg);
		}
		/* Clean up removed elements */


		DOMPurify.removed = [];
		/* Check if dirty is correctly typed for IN_PLACE */

		if (typeof dirty === 'string') {
			IN_PLACE = false;
		}

		if (IN_PLACE) {
			/* Do some early pre-sanitization to avoid unsafe root nodes */
			if (dirty.nodeName) {
				const tagName = transformCaseFunc(dirty.nodeName);

				if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
					throw typeErrorCreate('root node is forbidden and cannot be sanitized in-place');
				}
			}
		} else if (dirty instanceof Node) {
			/* If dirty is a DOM element, append to an empty document to avoid
				 elements being stripped by the parser */
			body = _initDocument('<!---->');
			importedNode = body.ownerDocument.importNode(dirty, true);

			if (importedNode.nodeType === 1 && importedNode.nodeName === 'BODY') {
				/* Node is already a body, use as is */
				body = importedNode;
			} else if (importedNode.nodeName === 'HTML') {
				body = importedNode;
			} else {
				// eslint-disable-next-line unicorn/prefer-dom-node-append
				body.appendChild(importedNode);
			}
		} else {
			/* Exit directly if we have nothing to do */
			if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT && // eslint-disable-next-line unicorn/prefer-includes
				dirty.indexOf('<') === -1) {
				return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty;
			}
			/* Initialize the document to work on */


			body = _initDocument(dirty);
			/* Check we have a DOM node from the data */

			if (!body) {
				return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : '';
			}
		}
		/* Remove first element node (ours) if FORCE_BODY is set */


		if (body && FORCE_BODY) {
			_forceRemove(body.firstChild);
		}
		/* Get node iterator */


		const nodeIterator = _createIterator(IN_PLACE ? dirty : body);
		/* Now start iterating over the created document */


		while (currentNode = nodeIterator.nextNode()) {
			/* Sanitize tags and elements */
			if (_sanitizeElements(currentNode)) {
				continue;
			}
			/* Shadow DOM detected, sanitize it */


			if (currentNode.content instanceof DocumentFragment) {
				_sanitizeShadowDOM(currentNode.content);
			}
			/* Check attributes, sanitize if necessary */


			_sanitizeAttributes(currentNode);
		}
		/* If we sanitized `dirty` in-place, return it. */


		if (IN_PLACE) {
			return dirty;
		}
		/* Return sanitized string or DOM */


		if (RETURN_DOM) {
			if (RETURN_DOM_FRAGMENT) {
				returnNode = createDocumentFragment.call(body.ownerDocument);

				while (body.firstChild) {
					// eslint-disable-next-line unicorn/prefer-dom-node-append
					returnNode.appendChild(body.firstChild);
				}
			} else {
				returnNode = body;
			}

			if (ALLOWED_ATTR.shadowroot || ALLOWED_ATTR.shadowrootmode) {
				/*
					AdoptNode() is not used because internal state is not reset
					(e.g. the past names map of a HTMLFormElement), this is safe
					in theory but we would rather not risk another attack vector.
					The state that is cloned by importNode() is explicitly defined
					by the specs.
				*/
				returnNode = importNode.call(originalDocument, returnNode, true);
			}

			return returnNode;
		}

		let serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;
		/* Serialize doctype if allowed */

		if (WHOLE_DOCUMENT && ALLOWED_TAGS['!doctype'] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) {
			serializedHTML = '<!DOCTYPE ' + body.ownerDocument.doctype.name + '>\n' + serializedHTML;
		}
		/* Sanitize final string template-safe */


		if (SAFE_FOR_TEMPLATES) {
			serializedHTML = stringReplace(serializedHTML, MUSTACHE_EXPR, ' ');
			serializedHTML = stringReplace(serializedHTML, ERB_EXPR, ' ');
			serializedHTML = stringReplace(serializedHTML, TMPLIT_EXPR, ' ');
		}

		return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML;
	};
	/**
	 * Public method to set the configuration once
	 * setConfig
	 *
	 * @param {Object} cfg configuration object
	 */


	DOMPurify.setConfig = function (cfg) {
		_parseConfig(cfg);

		SET_CONFIG = true;
	};
	/**
	 * Public method to remove the configuration
	 * clearConfig
	 *
	 */


	DOMPurify.clearConfig = function () {
		CONFIG = null;
		SET_CONFIG = false;
	};
	/**
	 * Public method to check if an attribute value is valid.
	 * Uses last set config, if any. Otherwise, uses config defaults.
	 * isValidAttribute
	 *
	 * @param  {string} tag Tag name of containing element.
	 * @param  {string} attr Attribute name.
	 * @param  {string} value Attribute value.
	 * @return {Boolean} Returns true if `value` is valid. Otherwise, returns false.
	 */


	DOMPurify.isValidAttribute = function (tag, attr, value) {
		/* Initialize shared config vars if necessary. */
		if (!CONFIG) {
			_parseConfig({});
		}

		const lcTag = transformCaseFunc(tag);
		const lcName = transformCaseFunc(attr);
		return _isValidAttribute(lcTag, lcName, value);
	};
	/**
	 * AddHook
	 * Public method to add DOMPurify hooks
	 *
	 * @param {String} entryPoint entry point for the hook to add
	 * @param {Function} hookFunction function to execute
	 */


	DOMPurify.addHook = function (entryPoint, hookFunction) {
		if (typeof hookFunction !== 'function') {
			return;
		}

		hooks[entryPoint] = hooks[entryPoint] || [];
		arrayPush(hooks[entryPoint], hookFunction);
	};
	/**
	 * RemoveHook
	 * Public method to remove a DOMPurify hook at a given entryPoint
	 * (pops it from the stack of hooks if more are present)
	 *
	 * @param {String} entryPoint entry point for the hook to remove
	 * @return {Function} removed(popped) hook
	 */


	DOMPurify.removeHook = function (entryPoint) {
		if (hooks[entryPoint]) {
			return arrayPop(hooks[entryPoint]);
		}
	};
	/**
	 * RemoveHooks
	 * Public method to remove all DOMPurify hooks at a given entryPoint
	 *
	 * @param  {String} entryPoint entry point for the hooks to remove
	 */


	DOMPurify.removeHooks = function (entryPoint) {
		if (hooks[entryPoint]) {
			hooks[entryPoint] = [];
		}
	};
	/**
	 * RemoveAllHooks
	 * Public method to remove all DOMPurify hooks
	 *
	 */


	DOMPurify.removeAllHooks = function () {
		hooks = {};
	};

	return DOMPurify;
}

var purify = createDOMPurify();

// ESM-comment-begin
define("vs/base/browser/dompurify/dompurify", function () { return purify; });
// ESM-comment-end

// ESM-uncomment-begin
// export default purify;
// export const version = purify.version;
// export const isSupported = purify.isSupported;
// export const sanitize = purify.sanitize;
// export const setConfig = purify.setConfig;
// export const clearConfig = purify.clearConfig;
// export const isValidAttribute = purify.isValidAttribute;
// export const addHook = purify.addHook;
// export const removeHook = purify.removeHook;
// export const removeHooks = purify.removeHooks;
// export const removeAllHooks = purify.removeAllHooks;
// ESM-uncomment-end

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[39/*vs/base/browser/fastDomNode*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.FastDomNode = void 0;
    exports.createFastDomNode = createFastDomNode;
    class FastDomNode {
        constructor(domNode) {
            this.domNode = domNode;
            this._maxWidth = '';
            this._width = '';
            this._height = '';
            this._top = '';
            this._left = '';
            this._bottom = '';
            this._right = '';
            this._paddingLeft = '';
            this._fontFamily = '';
            this._fontWeight = '';
            this._fontSize = '';
            this._fontStyle = '';
            this._fontFeatureSettings = '';
            this._fontVariationSettings = '';
            this._textDecoration = '';
            this._lineHeight = '';
            this._letterSpacing = '';
            this._className = '';
            this._display = '';
            this._position = '';
            this._visibility = '';
            this._color = '';
            this._backgroundColor = '';
            this._layerHint = false;
            this._contain = 'none';
            this._boxShadow = '';
        }
        setMaxWidth(_maxWidth) {
            const maxWidth = numberAsPixels(_maxWidth);
            if (this._maxWidth === maxWidth) {
                return;
            }
            this._maxWidth = maxWidth;
            this.domNode.style.maxWidth = this._maxWidth;
        }
        setWidth(_width) {
            const width = numberAsPixels(_width);
            if (this._width === width) {
                return;
            }
            this._width = width;
            this.domNode.style.width = this._width;
        }
        setHeight(_height) {
            const height = numberAsPixels(_height);
            if (this._height === height) {
                return;
            }
            this._height = height;
            this.domNode.style.height = this._height;
        }
        setTop(_top) {
            const top = numberAsPixels(_top);
            if (this._top === top) {
                return;
            }
            this._top = top;
            this.domNode.style.top = this._top;
        }
        setLeft(_left) {
            const left = numberAsPixels(_left);
            if (this._left === left) {
                return;
            }
            this._left = left;
            this.domNode.style.left = this._left;
        }
        setBottom(_bottom) {
            const bottom = numberAsPixels(_bottom);
            if (this._bottom === bottom) {
                return;
            }
            this._bottom = bottom;
            this.domNode.style.bottom = this._bottom;
        }
        setRight(_right) {
            const right = numberAsPixels(_right);
            if (this._right === right) {
                return;
            }
            this._right = right;
            this.domNode.style.right = this._right;
        }
        setPaddingLeft(_paddingLeft) {
            const paddingLeft = numberAsPixels(_paddingLeft);
            if (this._paddingLeft === paddingLeft) {
                return;
            }
            this._paddingLeft = paddingLeft;
            this.domNode.style.paddingLeft = this._paddingLeft;
        }
        setFontFamily(fontFamily) {
            if (this._fontFamily === fontFamily) {
                return;
            }
            this._fontFamily = fontFamily;
            this.domNode.style.fontFamily = this._fontFamily;
        }
        setFontWeight(fontWeight) {
            if (this._fontWeight === fontWeight) {
                return;
            }
            this._fontWeight = fontWeight;
            this.domNode.style.fontWeight = this._fontWeight;
        }
        setFontSize(_fontSize) {
            const fontSize = numberAsPixels(_fontSize);
            if (this._fontSize === fontSize) {
                return;
            }
            this._fontSize = fontSize;
            this.domNode.style.fontSize = this._fontSize;
        }
        setFontStyle(fontStyle) {
            if (this._fontStyle === fontStyle) {
                return;
            }
            this._fontStyle = fontStyle;
            this.domNode.style.fontStyle = this._fontStyle;
        }
        setFontFeatureSettings(fontFeatureSettings) {
            if (this._fontFeatureSettings === fontFeatureSettings) {
                return;
            }
            this._fontFeatureSettings = fontFeatureSettings;
            this.domNode.style.fontFeatureSettings = this._fontFeatureSettings;
        }
        setFontVariationSettings(fontVariationSettings) {
            if (this._fontVariationSettings === fontVariationSettings) {
                return;
            }
            this._fontVariationSettings = fontVariationSettings;
            this.domNode.style.fontVariationSettings = this._fontVariationSettings;
        }
        setTextDecoration(textDecoration) {
            if (this._textDecoration === textDecoration) {
                return;
            }
            this._textDecoration = textDecoration;
            this.domNode.style.textDecoration = this._textDecoration;
        }
        setLineHeight(_lineHeight) {
            const lineHeight = numberAsPixels(_lineHeight);
            if (this._lineHeight === lineHeight) {
                return;
            }
            this._lineHeight = lineHeight;
            this.domNode.style.lineHeight = this._lineHeight;
        }
        setLetterSpacing(_letterSpacing) {
            const letterSpacing = numberAsPixels(_letterSpacing);
            if (this._letterSpacing === letterSpacing) {
                return;
            }
            this._letterSpacing = letterSpacing;
            this.domNode.style.letterSpacing = this._letterSpacing;
        }
        setClassName(className) {
            if (this._className === className) {
                return;
            }
            this._className = className;
            this.domNode.className = this._className;
        }
        toggleClassName(className, shouldHaveIt) {
            this.domNode.classList.toggle(className, shouldHaveIt);
            this._className = this.domNode.className;
        }
        setDisplay(display) {
            if (this._display === display) {
                return;
            }
            this._display = display;
            this.domNode.style.display = this._display;
        }
        setPosition(position) {
            if (this._position === position) {
                return;
            }
            this._position = position;
            this.domNode.style.position = this._position;
        }
        setVisibility(visibility) {
            if (this._visibility === visibility) {
                return;
            }
            this._visibility = visibility;
            this.domNode.style.visibility = this._visibility;
        }
        setColor(color) {
            if (this._color === color) {
                return;
            }
            this._color = color;
            this.domNode.style.color = this._color;
        }
        setBackgroundColor(backgroundColor) {
            if (this._backgroundColor === backgroundColor) {
                return;
            }
            this._backgroundColor = backgroundColor;
            this.domNode.style.backgroundColor = this._backgroundColor;
        }
        setLayerHinting(layerHint) {
            if (this._layerHint === layerHint) {
                return;
            }
            this._layerHint = layerHint;
            this.domNode.style.transform = this._layerHint ? 'translate3d(0px, 0px, 0px)' : '';
        }
        setBoxShadow(boxShadow) {
            if (this._boxShadow === boxShadow) {
                return;
            }
            this._boxShadow = boxShadow;
            this.domNode.style.boxShadow = boxShadow;
        }
        setContain(contain) {
            if (this._contain === contain) {
                return;
            }
            this._contain = contain;
            this.domNode.style.contain = this._contain;
        }
        setAttribute(name, value) {
            this.domNode.setAttribute(name, value);
        }
        removeAttribute(name) {
            this.domNode.removeAttribute(name);
        }
        appendChild(child) {
            this.domNode.appendChild(child.domNode);
        }
        removeChild(child) {
            this.domNode.removeChild(child.domNode);
        }
    }
    exports.FastDomNode = FastDomNode;
    function numberAsPixels(value) {
        return (typeof value === 'number' ? `${value}px` : value);
    }
    function createFastDomNode(domNode) {
        return new FastDomNode(domNode);
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[441/*vs/base/browser/iframe*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.IframeUtils = void 0;
    const sameOriginWindowChainCache = new WeakMap();
    function getParentWindowIfSameOrigin(w) {
        if (!w.parent || w.parent === w) {
            return null;
        }
        // Cannot really tell if we have access to the parent window unless we try to access something in it
        try {
            const location = w.location;
            const parentLocation = w.parent.location;
            if (location.origin !== 'null' && parentLocation.origin !== 'null' && location.origin !== parentLocation.origin) {
                return null;
            }
        }
        catch (e) {
            return null;
        }
        return w.parent;
    }
    class IframeUtils {
        /**
         * Returns a chain of embedded windows with the same origin (which can be accessed programmatically).
         * Having a chain of length 1 might mean that the current execution environment is running outside of an iframe or inside an iframe embedded in a window with a different origin.
         */
        static getSameOriginWindowChain(targetWindow) {
            let windowChainCache = sameOriginWindowChainCache.get(targetWindow);
            if (!windowChainCache) {
                windowChainCache = [];
                sameOriginWindowChainCache.set(targetWindow, windowChainCache);
                let w = targetWindow;
                let parent;
                do {
                    parent = getParentWindowIfSameOrigin(w);
                    if (parent) {
                        windowChainCache.push({
                            window: new WeakRef(w),
                            iframeElement: w.frameElement || null
                        });
                    }
                    else {
                        windowChainCache.push({
                            window: new WeakRef(w),
                            iframeElement: null
                        });
                    }
                    w = parent;
                } while (w);
            }
            return windowChainCache.slice(0);
        }
        /**
         * Returns the position of `childWindow` relative to `ancestorWindow`
         */
        static getPositionOfChildWindowRelativeToAncestorWindow(childWindow, ancestorWindow) {
            if (!ancestorWindow || childWindow === ancestorWindow) {
                return {
                    top: 0,
                    left: 0
                };
            }
            let top = 0, left = 0;
            const windowChain = this.getSameOriginWindowChain(childWindow);
            for (const windowChainEl of windowChain) {
                const windowInChain = windowChainEl.window.deref();
                top += windowInChain?.scrollY ?? 0;
                left += windowInChain?.scrollX ?? 0;
                if (windowInChain === ancestorWindow) {
                    break;
                }
                if (!windowChainEl.iframeElement) {
                    break;
                }
                const boundingRect = windowChainEl.iframeElement.getBoundingClientRect();
                top += boundingRect.top;
                left += boundingRect.left;
            }
            return {
                top: top,
                left: left
            };
        }
    }
    exports.IframeUtils = IframeUtils;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[296/*vs/base/browser/performance*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.inputLatency = void 0;
    var inputLatency;
    (function (inputLatency) {
        const totalKeydownTime = { total: 0, min: Number.MAX_VALUE, max: 0 };
        const totalInputTime = { ...totalKeydownTime };
        const totalRenderTime = { ...totalKeydownTime };
        const totalInputLatencyTime = { ...totalKeydownTime };
        let measurementsCount = 0;
        const state = {
            keydown: 0 /* EventPhase.Before */,
            input: 0 /* EventPhase.Before */,
            render: 0 /* EventPhase.Before */,
        };
        /**
         * Record the start of the keydown event.
         */
        function onKeyDown() {
            /** Direct Check C. See explanation in {@link recordIfFinished} */
            recordIfFinished();
            performance.mark('inputlatency/start');
            performance.mark('keydown/start');
            state.keydown = 1 /* EventPhase.InProgress */;
            queueMicrotask(markKeyDownEnd);
        }
        inputLatency.onKeyDown = onKeyDown;
        /**
         * Mark the end of the keydown event.
         */
        function markKeyDownEnd() {
            if (state.keydown === 1 /* EventPhase.InProgress */) {
                performance.mark('keydown/end');
                state.keydown = 2 /* EventPhase.Finished */;
            }
        }
        /**
         * Record the start of the beforeinput event.
         */
        function onBeforeInput() {
            performance.mark('input/start');
            state.input = 1 /* EventPhase.InProgress */;
            /** Schedule Task A. See explanation in {@link recordIfFinished} */
            scheduleRecordIfFinishedTask();
        }
        inputLatency.onBeforeInput = onBeforeInput;
        /**
         * Record the start of the input event.
         */
        function onInput() {
            if (state.input === 0 /* EventPhase.Before */) {
                // it looks like we didn't receive a `beforeinput`
                onBeforeInput();
            }
            queueMicrotask(markInputEnd);
        }
        inputLatency.onInput = onInput;
        function markInputEnd() {
            if (state.input === 1 /* EventPhase.InProgress */) {
                performance.mark('input/end');
                state.input = 2 /* EventPhase.Finished */;
            }
        }
        /**
         * Record the start of the keyup event.
         */
        function onKeyUp() {
            /** Direct Check D. See explanation in {@link recordIfFinished} */
            recordIfFinished();
        }
        inputLatency.onKeyUp = onKeyUp;
        /**
         * Record the start of the selectionchange event.
         */
        function onSelectionChange() {
            /** Direct Check E. See explanation in {@link recordIfFinished} */
            recordIfFinished();
        }
        inputLatency.onSelectionChange = onSelectionChange;
        /**
         * Record the start of the animation frame performing the rendering.
         */
        function onRenderStart() {
            // Render may be triggered during input, but we only measure the following animation frame
            if (state.keydown === 2 /* EventPhase.Finished */ && state.input === 2 /* EventPhase.Finished */ && state.render === 0 /* EventPhase.Before */) {
                // Only measure the first render after keyboard input
                performance.mark('render/start');
                state.render = 1 /* EventPhase.InProgress */;
                queueMicrotask(markRenderEnd);
                /** Schedule Task B. See explanation in {@link recordIfFinished} */
                scheduleRecordIfFinishedTask();
            }
        }
        inputLatency.onRenderStart = onRenderStart;
        /**
         * Mark the end of the animation frame performing the rendering.
         */
        function markRenderEnd() {
            if (state.render === 1 /* EventPhase.InProgress */) {
                performance.mark('render/end');
                state.render = 2 /* EventPhase.Finished */;
            }
        }
        function scheduleRecordIfFinishedTask() {
            // Here we can safely assume that the `setTimeout` will not be
            // artificially delayed by 4ms because we schedule it from
            // event handlers
            setTimeout(recordIfFinished);
        }
        /**
         * Record the input latency sample if input handling and rendering are finished.
         *
         * The challenge here is that we want to record the latency in such a way that it includes
         * also the layout and painting work the browser does during the animation frame task.
         *
         * Simply scheduling a new task (via `setTimeout`) from the animation frame task would
         * schedule the new task at the end of the task queue (after other code that uses `setTimeout`),
         * so we need to use multiple strategies to make sure our task runs before others:
         *
         * We schedule tasks (A and B):
         *    - we schedule a task A (via a `setTimeout` call) when the input starts in `markInputStart`.
         *      If the animation frame task is scheduled quickly by the browser, then task A has a very good
         *      chance of being the very first task after the animation frame and thus will record the input latency.
         *    - however, if the animation frame task is scheduled a bit later, then task A might execute
         *      before the animation frame task. We therefore schedule another task B from `markRenderStart`.
         *
         * We do direct checks in browser event handlers (C, D, E):
         *    - if the browser has multiple keydown events queued up, they will be scheduled before the `setTimeout` tasks,
         *      so we do a direct check in the keydown event handler (C).
         *    - depending on timing, sometimes the animation frame is scheduled even before the `keyup` event, so we
         *      do a direct check there too (E).
         *    - the browser oftentimes emits a `selectionchange` event after an `input`, so we do a direct check there (D).
         */
        function recordIfFinished() {
            if (state.keydown === 2 /* EventPhase.Finished */ && state.input === 2 /* EventPhase.Finished */ && state.render === 2 /* EventPhase.Finished */) {
                performance.mark('inputlatency/end');
                performance.measure('keydown', 'keydown/start', 'keydown/end');
                performance.measure('input', 'input/start', 'input/end');
                performance.measure('render', 'render/start', 'render/end');
                performance.measure('inputlatency', 'inputlatency/start', 'inputlatency/end');
                addMeasure('keydown', totalKeydownTime);
                addMeasure('input', totalInputTime);
                addMeasure('render', totalRenderTime);
                addMeasure('inputlatency', totalInputLatencyTime);
                // console.info(
                // 	`input latency=${performance.getEntriesByName('inputlatency')[0].duration.toFixed(1)} [` +
                // 	`keydown=${performance.getEntriesByName('keydown')[0].duration.toFixed(1)}, ` +
                // 	`input=${performance.getEntriesByName('input')[0].duration.toFixed(1)}, ` +
                // 	`render=${performance.getEntriesByName('render')[0].duration.toFixed(1)}` +
                // 	`]`
                // );
                measurementsCount++;
                reset();
            }
        }
        function addMeasure(entryName, cumulativeMeasurement) {
            const duration = performance.getEntriesByName(entryName)[0].duration;
            cumulativeMeasurement.total += duration;
            cumulativeMeasurement.min = Math.min(cumulativeMeasurement.min, duration);
            cumulativeMeasurement.max = Math.max(cumulativeMeasurement.max, duration);
        }
        /**
         * Clear the current sample.
         */
        function reset() {
            performance.clearMarks('keydown/start');
            performance.clearMarks('keydown/end');
            performance.clearMarks('input/start');
            performance.clearMarks('input/end');
            performance.clearMarks('render/start');
            performance.clearMarks('render/end');
            performance.clearMarks('inputlatency/start');
            performance.clearMarks('inputlatency/end');
            performance.clearMeasures('keydown');
            performance.clearMeasures('input');
            performance.clearMeasures('render');
            performance.clearMeasures('inputlatency');
            state.keydown = 0 /* EventPhase.Before */;
            state.input = 0 /* EventPhase.Before */;
            state.render = 0 /* EventPhase.Before */;
        }
        /**
         * Gets all input latency samples and clears the internal buffers to start recording a new set
         * of samples.
         */
        function getAndClearMeasurements() {
            if (measurementsCount === 0) {
                return undefined;
            }
            // Assemble the result
            const result = {
                keydown: cumulativeToFinalMeasurement(totalKeydownTime),
                input: cumulativeToFinalMeasurement(totalInputTime),
                render: cumulativeToFinalMeasurement(totalRenderTime),
                total: cumulativeToFinalMeasurement(totalInputLatencyTime),
                sampleCount: measurementsCount
            };
            // Clear the cumulative measurements
            clearCumulativeMeasurement(totalKeydownTime);
            clearCumulativeMeasurement(totalInputTime);
            clearCumulativeMeasurement(totalRenderTime);
            clearCumulativeMeasurement(totalInputLatencyTime);
            measurementsCount = 0;
            return result;
        }
        inputLatency.getAndClearMeasurements = getAndClearMeasurements;
        function cumulativeToFinalMeasurement(cumulative) {
            return {
                average: cumulative.total / measurementsCount,
                max: cumulative.max,
                min: cumulative.min,
            };
        }
        function clearCumulativeMeasurement(cumulative) {
            cumulative.total = 0;
            cumulative.min = Number.MAX_VALUE;
            cumulative.max = 0;
        }
    })(inputLatency || (exports.inputLatency = inputLatency = {}));
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[81/*vs/base/browser/ui/hover/hoverDelegate2*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.setBaseLayerHoverDelegate = setBaseLayerHoverDelegate;
    exports.getBaseLayerHoverDelegate = getBaseLayerHoverDelegate;
    let baseHoverDelegate = {
        showHover: () => undefined,
        hideHover: () => undefined,
        showAndFocusLastHover: () => undefined,
        setupManagedHover: () => null,
        showManagedHover: () => undefined
    };
    /**
     * Sets the hover delegate for use **only in the `base/` layer**.
     */
    function setBaseLayerHoverDelegate(hoverDelegate) {
        baseHoverDelegate = hoverDelegate;
    }
    /**
     * Gets the hover delegate for use **only in the `base/` layer**.
     *
     * Since the hover service depends on various platform services, this delegate essentially bypasses
     * the standard dependency injection mechanism by injecting a global hover service at start up. The
     * only reason this should be used is if `IHoverService` is not available.
     */
    function getBaseLayerHoverDelegate() {
        return baseHoverDelegate;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[442/*vs/base/browser/ui/list/list*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ListError = void 0;
    class ListError extends Error {
        constructor(user, message) {
            super(`ListError [${user}] ${message}`);
        }
    }
    exports.ListError = ListError;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[443/*vs/base/browser/ui/list/splice*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CombinedSpliceable = void 0;
    class CombinedSpliceable {
        constructor(spliceables) {
            this.spliceables = spliceables;
        }
        splice(start, deleteCount, elements) {
            this.spliceables.forEach(s => s.splice(start, deleteCount, elements));
        }
    }
    exports.CombinedSpliceable = CombinedSpliceable;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[223/*vs/base/browser/ui/scrollbar/scrollbarState*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ScrollbarState = void 0;
    /**
     * The minimal size of the slider (such that it can still be clickable) -- it is artificially enlarged.
     */
    const MINIMUM_SLIDER_SIZE = 20;
    class ScrollbarState {
        constructor(arrowSize, scrollbarSize, oppositeScrollbarSize, visibleSize, scrollSize, scrollPosition) {
            this._scrollbarSize = Math.round(scrollbarSize);
            this._oppositeScrollbarSize = Math.round(oppositeScrollbarSize);
            this._arrowSize = Math.round(arrowSize);
            this._visibleSize = visibleSize;
            this._scrollSize = scrollSize;
            this._scrollPosition = scrollPosition;
            this._computedAvailableSize = 0;
            this._computedIsNeeded = false;
            this._computedSliderSize = 0;
            this._computedSliderRatio = 0;
            this._computedSliderPosition = 0;
            this._refreshComputedValues();
        }
        clone() {
            return new ScrollbarState(this._arrowSize, this._scrollbarSize, this._oppositeScrollbarSize, this._visibleSize, this._scrollSize, this._scrollPosition);
        }
        setVisibleSize(visibleSize) {
            const iVisibleSize = Math.round(visibleSize);
            if (this._visibleSize !== iVisibleSize) {
                this._visibleSize = iVisibleSize;
                this._refreshComputedValues();
                return true;
            }
            return false;
        }
        setScrollSize(scrollSize) {
            const iScrollSize = Math.round(scrollSize);
            if (this._scrollSize !== iScrollSize) {
                this._scrollSize = iScrollSize;
                this._refreshComputedValues();
                return true;
            }
            return false;
        }
        setScrollPosition(scrollPosition) {
            const iScrollPosition = Math.round(scrollPosition);
            if (this._scrollPosition !== iScrollPosition) {
                this._scrollPosition = iScrollPosition;
                this._refreshComputedValues();
                return true;
            }
            return false;
        }
        setScrollbarSize(scrollbarSize) {
            this._scrollbarSize = Math.round(scrollbarSize);
        }
        setOppositeScrollbarSize(oppositeScrollbarSize) {
            this._oppositeScrollbarSize = Math.round(oppositeScrollbarSize);
        }
        static _computeValues(oppositeScrollbarSize, arrowSize, visibleSize, scrollSize, scrollPosition) {
            const computedAvailableSize = Math.max(0, visibleSize - oppositeScrollbarSize);
            const computedRepresentableSize = Math.max(0, computedAvailableSize - 2 * arrowSize);
            const computedIsNeeded = (scrollSize > 0 && scrollSize > visibleSize);
            if (!computedIsNeeded) {
                // There is no need for a slider
                return {
                    computedAvailableSize: Math.round(computedAvailableSize),
                    computedIsNeeded: computedIsNeeded,
                    computedSliderSize: Math.round(computedRepresentableSize),
                    computedSliderRatio: 0,
                    computedSliderPosition: 0,
                };
            }
            // We must artificially increase the size of the slider if needed, since the slider would be too small to grab with the mouse otherwise
            const computedSliderSize = Math.round(Math.max(MINIMUM_SLIDER_SIZE, Math.floor(visibleSize * computedRepresentableSize / scrollSize)));
            // The slider can move from 0 to `computedRepresentableSize` - `computedSliderSize`
            // in the same way `scrollPosition` can move from 0 to `scrollSize` - `visibleSize`.
            const computedSliderRatio = (computedRepresentableSize - computedSliderSize) / (scrollSize - visibleSize);
            const computedSliderPosition = (scrollPosition * computedSliderRatio);
            return {
                computedAvailableSize: Math.round(computedAvailableSize),
                computedIsNeeded: computedIsNeeded,
                computedSliderSize: Math.round(computedSliderSize),
                computedSliderRatio: computedSliderRatio,
                computedSliderPosition: Math.round(computedSliderPosition),
            };
        }
        _refreshComputedValues() {
            const r = ScrollbarState._computeValues(this._oppositeScrollbarSize, this._arrowSize, this._visibleSize, this._scrollSize, this._scrollPosition);
            this._computedAvailableSize = r.computedAvailableSize;
            this._computedIsNeeded = r.computedIsNeeded;
            this._computedSliderSize = r.computedSliderSize;
            this._computedSliderRatio = r.computedSliderRatio;
            this._computedSliderPosition = r.computedSliderPosition;
        }
        getArrowSize() {
            return this._arrowSize;
        }
        getScrollPosition() {
            return this._scrollPosition;
        }
        getRectangleLargeSize() {
            return this._computedAvailableSize;
        }
        getRectangleSmallSize() {
            return this._scrollbarSize;
        }
        isNeeded() {
            return this._computedIsNeeded;
        }
        getSliderSize() {
            return this._computedSliderSize;
        }
        getSliderPosition() {
            return this._computedSliderPosition;
        }
        /**
         * Compute a desired `scrollPosition` such that `offset` ends up in the center of the slider.
         * `offset` is based on the same coordinate system as the `sliderPosition`.
         */
        getDesiredScrollPositionFromOffset(offset) {
            if (!this._computedIsNeeded) {
                // no need for a slider
                return 0;
            }
            const desiredSliderPosition = offset - this._arrowSize - this._computedSliderSize / 2;
            return Math.round(desiredSliderPosition / this._computedSliderRatio);
        }
        /**
         * Compute a desired `scrollPosition` from if offset is before or after the slider position.
         * If offset is before slider, treat as a page up (or left).  If after, page down (or right).
         * `offset` and `_computedSliderPosition` are based on the same coordinate system.
         * `_visibleSize` corresponds to a "page" of lines in the returned coordinate system.
         */
        getDesiredScrollPositionFromOffsetPaged(offset) {
            if (!this._computedIsNeeded) {
                // no need for a slider
                return 0;
            }
            const correctedOffset = offset - this._arrowSize; // compensate if has arrows
            let desiredScrollPosition = this._scrollPosition;
            if (correctedOffset < this._computedSliderPosition) {
                desiredScrollPosition -= this._visibleSize; // page up/left
            }
            else {
                desiredScrollPosition += this._visibleSize; // page down/right
            }
            return desiredScrollPosition;
        }
        /**
         * Compute a desired `scrollPosition` such that the slider moves by `delta`.
         */
        getDesiredScrollPositionFromDelta(delta) {
            if (!this._computedIsNeeded) {
                // no need for a slider
                return 0;
            }
            const desiredSliderPosition = this._computedSliderPosition + delta;
            return Math.round(desiredSliderPosition / this._computedSliderRatio);
        }
    }
    exports.ScrollbarState = ScrollbarState;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[159/*vs/base/browser/ui/tree/tree*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.WeakMapper = exports.TreeError = exports.TreeMouseEventTarget = exports.ObjectTreeElementCollapseState = void 0;
    var ObjectTreeElementCollapseState;
    (function (ObjectTreeElementCollapseState) {
        ObjectTreeElementCollapseState[ObjectTreeElementCollapseState["Expanded"] = 0] = "Expanded";
        ObjectTreeElementCollapseState[ObjectTreeElementCollapseState["Collapsed"] = 1] = "Collapsed";
        /**
         * If the element is already in the tree, preserve its current state. Else, expand it.
         */
        ObjectTreeElementCollapseState[ObjectTreeElementCollapseState["PreserveOrExpanded"] = 2] = "PreserveOrExpanded";
        /**
         * If the element is already in the tree, preserve its current state. Else, collapse it.
         */
        ObjectTreeElementCollapseState[ObjectTreeElementCollapseState["PreserveOrCollapsed"] = 3] = "PreserveOrCollapsed";
    })(ObjectTreeElementCollapseState || (exports.ObjectTreeElementCollapseState = ObjectTreeElementCollapseState = {}));
    var TreeMouseEventTarget;
    (function (TreeMouseEventTarget) {
        TreeMouseEventTarget[TreeMouseEventTarget["Unknown"] = 0] = "Unknown";
        TreeMouseEventTarget[TreeMouseEventTarget["Twistie"] = 1] = "Twistie";
        TreeMouseEventTarget[TreeMouseEventTarget["Element"] = 2] = "Element";
        TreeMouseEventTarget[TreeMouseEventTarget["Filter"] = 3] = "Filter";
    })(TreeMouseEventTarget || (exports.TreeMouseEventTarget = TreeMouseEventTarget = {}));
    class TreeError extends Error {
        constructor(user, message) {
            super(`TreeError [${user}] ${message}`);
        }
    }
    exports.TreeError = TreeError;
    class WeakMapper {
        constructor(fn) {
            this.fn = fn;
            this._map = new WeakMap();
        }
        map(key) {
            let result = this._map.get(key);
            if (!result) {
                result = this.fn(key);
                this._map.set(key, result);
            }
            return result;
        }
    }
    exports.WeakMapper = WeakMapper;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[52/*vs/base/browser/window*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.mainWindow = void 0;
    exports.ensureCodeWindow = ensureCodeWindow;
    function ensureCodeWindow(targetWindow, fallbackWindowId) {
        const codeWindow = targetWindow;
        if (typeof codeWindow.vscodeWindowId !== 'number') {
            Object.defineProperty(codeWindow, 'vscodeWindowId', {
                get: () => fallbackWindowId
            });
        }
    }
    // eslint-disable-next-line no-restricted-globals
    exports.mainWindow = window;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[64/*vs/base/browser/browser*/], __M([1/*require*/,0/*exports*/,52/*vs/base/browser/window*/]), function (require, exports, window_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.isAndroid = exports.isElectron = exports.isWebkitWebView = exports.isSafari = exports.isChrome = exports.isWebKit = exports.isFirefox = void 0;
    exports.addMatchMediaChangeListener = addMatchMediaChangeListener;
    exports.getZoomFactor = getZoomFactor;
    exports.isStandalone = isStandalone;
    class WindowManager {
        constructor() {
            // --- Zoom Factor
            this.mapWindowIdToZoomFactor = new Map();
        }
        static { this.INSTANCE = new WindowManager(); }
        getZoomFactor(targetWindow) {
            return this.mapWindowIdToZoomFactor.get(this.getWindowId(targetWindow)) ?? 1;
        }
        getWindowId(targetWindow) {
            return targetWindow.vscodeWindowId;
        }
    }
    function addMatchMediaChangeListener(targetWindow, query, callback) {
        if (typeof query === 'string') {
            query = targetWindow.matchMedia(query);
        }
        query.addEventListener('change', callback);
    }
    /** The zoom scale for an index, e.g. 1, 1.2, 1.4 */
    function getZoomFactor(targetWindow) {
        return WindowManager.INSTANCE.getZoomFactor(targetWindow);
    }
    const userAgent = navigator.userAgent;
    exports.isFirefox = (userAgent.indexOf('Firefox') >= 0);
    exports.isWebKit = (userAgent.indexOf('AppleWebKit') >= 0);
    exports.isChrome = (userAgent.indexOf('Chrome') >= 0);
    exports.isSafari = (!exports.isChrome && (userAgent.indexOf('Safari') >= 0));
    exports.isWebkitWebView = (!exports.isChrome && !exports.isSafari && exports.isWebKit);
    exports.isElectron = (userAgent.indexOf('Electron/') >= 0);
    exports.isAndroid = (userAgent.indexOf('Android') >= 0);
    let standalone = false;
    if (typeof window_1.mainWindow.matchMedia === 'function') {
        const standaloneMatchMedia = window_1.mainWindow.matchMedia('(display-mode: standalone) or (display-mode: window-controls-overlay)');
        const fullScreenMatchMedia = window_1.mainWindow.matchMedia('(display-mode: fullscreen)');
        standalone = standaloneMatchMedia.matches;
        addMatchMediaChangeListener(window_1.mainWindow, standaloneMatchMedia, ({ matches }) => {
            // entering fullscreen would change standaloneMatchMedia.matches to false
            // if standalone is true (running as PWA) and entering fullscreen, skip this change
            if (standalone && fullScreenMatchMedia.matches) {
                return;
            }
            // otherwise update standalone (browser to PWA or PWA to browser)
            standalone = matches;
        });
    }
    function isStandalone() {
        return standalone;
    }
});

define(__m[13/*vs/base/common/arrays*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Permutation = exports.CallbackIterable = exports.ArrayQueue = exports.booleanComparator = exports.numberComparator = exports.CompareResult = void 0;
    exports.tail = tail;
    exports.tail2 = tail2;
    exports.equals = equals;
    exports.removeFastWithoutKeepingOrder = removeFastWithoutKeepingOrder;
    exports.binarySearch = binarySearch;
    exports.binarySearch2 = binarySearch2;
    exports.quickSelect = quickSelect;
    exports.groupBy = groupBy;
    exports.groupAdjacentBy = groupAdjacentBy;
    exports.forEachAdjacent = forEachAdjacent;
    exports.forEachWithNeighbors = forEachWithNeighbors;
    exports.coalesce = coalesce;
    exports.coalesceInPlace = coalesceInPlace;
    exports.isFalsyOrEmpty = isFalsyOrEmpty;
    exports.isNonEmptyArray = isNonEmptyArray;
    exports.distinct = distinct;
    exports.firstOrDefault = firstOrDefault;
    exports.range = range;
    exports.arrayInsert = arrayInsert;
    exports.pushToStart = pushToStart;
    exports.pushToEnd = pushToEnd;
    exports.pushMany = pushMany;
    exports.asArray = asArray;
    exports.insertInto = insertInto;
    exports.splice = splice;
    exports.compareBy = compareBy;
    exports.tieBreakComparators = tieBreakComparators;
    exports.reverseOrder = reverseOrder;
    /**
     * Returns the last element of an array.
     * @param array The array.
     * @param n Which element from the end (default is zero).
     */
    function tail(array, n = 0) {
        return array[array.length - (1 + n)];
    }
    function tail2(arr) {
        if (arr.length === 0) {
            throw new Error('Invalid tail call');
        }
        return [arr.slice(0, arr.length - 1), arr[arr.length - 1]];
    }
    function equals(one, other, itemEquals = (a, b) => a === b) {
        if (one === other) {
            return true;
        }
        if (!one || !other) {
            return false;
        }
        if (one.length !== other.length) {
            return false;
        }
        for (let i = 0, len = one.length; i < len; i++) {
            if (!itemEquals(one[i], other[i])) {
                return false;
            }
        }
        return true;
    }
    /**
     * Remove the element at `index` by replacing it with the last element. This is faster than `splice`
     * but changes the order of the array
     */
    function removeFastWithoutKeepingOrder(array, index) {
        const last = array.length - 1;
        if (index < last) {
            array[index] = array[last];
        }
        array.pop();
    }
    /**
     * Performs a binary search algorithm over a sorted array.
     *
     * @param array The array being searched.
     * @param key The value we search for.
     * @param comparator A function that takes two array elements and returns zero
     *   if they are equal, a negative number if the first element precedes the
     *   second one in the sorting order, or a positive number if the second element
     *   precedes the first one.
     * @return See {@link binarySearch2}
     */
    function binarySearch(array, key, comparator) {
        return binarySearch2(array.length, i => comparator(array[i], key));
    }
    /**
     * Performs a binary search algorithm over a sorted collection. Useful for cases
     * when we need to perform a binary search over something that isn't actually an
     * array, and converting data to an array would defeat the use of binary search
     * in the first place.
     *
     * @param length The collection length.
     * @param compareToKey A function that takes an index of an element in the
     *   collection and returns zero if the value at this index is equal to the
     *   search key, a negative number if the value precedes the search key in the
     *   sorting order, or a positive number if the search key precedes the value.
     * @return A non-negative index of an element, if found. If not found, the
     *   result is -(n+1) (or ~n, using bitwise notation), where n is the index
     *   where the key should be inserted to maintain the sorting order.
     */
    function binarySearch2(length, compareToKey) {
        let low = 0, high = length - 1;
        while (low <= high) {
            const mid = ((low + high) / 2) | 0;
            const comp = compareToKey(mid);
            if (comp < 0) {
                low = mid + 1;
            }
            else if (comp > 0) {
                high = mid - 1;
            }
            else {
                return mid;
            }
        }
        return -(low + 1);
    }
    function quickSelect(nth, data, compare) {
        nth = nth | 0;
        if (nth >= data.length) {
            throw new TypeError('invalid index');
        }
        const pivotValue = data[Math.floor(data.length * Math.random())];
        const lower = [];
        const higher = [];
        const pivots = [];
        for (const value of data) {
            const val = compare(value, pivotValue);
            if (val < 0) {
                lower.push(value);
            }
            else if (val > 0) {
                higher.push(value);
            }
            else {
                pivots.push(value);
            }
        }
        if (nth < lower.length) {
            return quickSelect(nth, lower, compare);
        }
        else if (nth < lower.length + pivots.length) {
            return pivots[0];
        }
        else {
            return quickSelect(nth - (lower.length + pivots.length), higher, compare);
        }
    }
    function groupBy(data, compare) {
        const result = [];
        let currentGroup = undefined;
        for (const element of data.slice(0).sort(compare)) {
            if (!currentGroup || compare(currentGroup[0], element) !== 0) {
                currentGroup = [element];
                result.push(currentGroup);
            }
            else {
                currentGroup.push(element);
            }
        }
        return result;
    }
    /**
     * Splits the given items into a list of (non-empty) groups.
     * `shouldBeGrouped` is used to decide if two consecutive items should be in the same group.
     * The order of the items is preserved.
     */
    function* groupAdjacentBy(items, shouldBeGrouped) {
        let currentGroup;
        let last;
        for (const item of items) {
            if (last !== undefined && shouldBeGrouped(last, item)) {
                currentGroup.push(item);
            }
            else {
                if (currentGroup) {
                    yield currentGroup;
                }
                currentGroup = [item];
            }
            last = item;
        }
        if (currentGroup) {
            yield currentGroup;
        }
    }
    function forEachAdjacent(arr, f) {
        for (let i = 0; i <= arr.length; i++) {
            f(i === 0 ? undefined : arr[i - 1], i === arr.length ? undefined : arr[i]);
        }
    }
    function forEachWithNeighbors(arr, f) {
        for (let i = 0; i < arr.length; i++) {
            f(i === 0 ? undefined : arr[i - 1], arr[i], i + 1 === arr.length ? undefined : arr[i + 1]);
        }
    }
    /**
     * @returns New array with all falsy values removed. The original array IS NOT modified.
     */
    function coalesce(array) {
        return array.filter((e) => !!e);
    }
    /**
     * Remove all falsy values from `array`. The original array IS modified.
     */
    function coalesceInPlace(array) {
        let to = 0;
        for (let i = 0; i < array.length; i++) {
            if (!!array[i]) {
                array[to] = array[i];
                to += 1;
            }
        }
        array.length = to;
    }
    /**
     * @returns false if the provided object is an array and not empty.
     */
    function isFalsyOrEmpty(obj) {
        return !Array.isArray(obj) || obj.length === 0;
    }
    function isNonEmptyArray(obj) {
        return Array.isArray(obj) && obj.length > 0;
    }
    /**
     * Removes duplicates from the given array. The optional keyFn allows to specify
     * how elements are checked for equality by returning an alternate value for each.
     */
    function distinct(array, keyFn = value => value) {
        const seen = new Set();
        return array.filter(element => {
            const key = keyFn(element);
            if (seen.has(key)) {
                return false;
            }
            seen.add(key);
            return true;
        });
    }
    function firstOrDefault(array, notFoundValue) {
        return array.length > 0 ? array[0] : notFoundValue;
    }
    function range(arg, to) {
        let from = typeof to === 'number' ? arg : 0;
        if (typeof to === 'number') {
            from = arg;
        }
        else {
            from = 0;
            to = arg;
        }
        const result = [];
        if (from <= to) {
            for (let i = from; i < to; i++) {
                result.push(i);
            }
        }
        else {
            for (let i = from; i > to; i--) {
                result.push(i);
            }
        }
        return result;
    }
    /**
     * Insert `insertArr` inside `target` at `insertIndex`.
     * Please don't touch unless you understand https://jsperf.com/inserting-an-array-within-an-array
     */
    function arrayInsert(target, insertIndex, insertArr) {
        const before = target.slice(0, insertIndex);
        const after = target.slice(insertIndex);
        return before.concat(insertArr, after);
    }
    /**
     * Pushes an element to the start of the array, if found.
     */
    function pushToStart(arr, value) {
        const index = arr.indexOf(value);
        if (index > -1) {
            arr.splice(index, 1);
            arr.unshift(value);
        }
    }
    /**
     * Pushes an element to the end of the array, if found.
     */
    function pushToEnd(arr, value) {
        const index = arr.indexOf(value);
        if (index > -1) {
            arr.splice(index, 1);
            arr.push(value);
        }
    }
    function pushMany(arr, items) {
        for (const item of items) {
            arr.push(item);
        }
    }
    function asArray(x) {
        return Array.isArray(x) ? x : [x];
    }
    /**
     * Insert the new items in the array.
     * @param array The original array.
     * @param start The zero-based location in the array from which to start inserting elements.
     * @param newItems The items to be inserted
     */
    function insertInto(array, start, newItems) {
        const startIdx = getActualStartIndex(array, start);
        const originalLength = array.length;
        const newItemsLength = newItems.length;
        array.length = originalLength + newItemsLength;
        // Move the items after the start index, start from the end so that we don't overwrite any value.
        for (let i = originalLength - 1; i >= startIdx; i--) {
            array[i + newItemsLength] = array[i];
        }
        for (let i = 0; i < newItemsLength; i++) {
            array[i + startIdx] = newItems[i];
        }
    }
    /**
     * Removes elements from an array and inserts new elements in their place, returning the deleted elements. Alternative to the native Array.splice method, it
     * can only support limited number of items due to the maximum call stack size limit.
     * @param array The original array.
     * @param start The zero-based location in the array from which to start removing elements.
     * @param deleteCount The number of elements to remove.
     * @returns An array containing the elements that were deleted.
     */
    function splice(array, start, deleteCount, newItems) {
        const index = getActualStartIndex(array, start);
        let result = array.splice(index, deleteCount);
        if (result === undefined) {
            // see https://bugs.webkit.org/show_bug.cgi?id=261140
            result = [];
        }
        insertInto(array, index, newItems);
        return result;
    }
    /**
     * Determine the actual start index (same logic as the native splice() or slice())
     * If greater than the length of the array, start will be set to the length of the array. In this case, no element will be deleted but the method will behave as an adding function, adding as many element as item[n*] provided.
     * If negative, it will begin that many elements from the end of the array. (In this case, the origin -1, meaning -n is the index of the nth last element, and is therefore equivalent to the index of array.length - n.) If array.length + start is less than 0, it will begin from index 0.
     * @param array The target array.
     * @param start The operation index.
     */
    function getActualStartIndex(array, start) {
        return start < 0 ? Math.max(start + array.length, 0) : Math.min(start, array.length);
    }
    var CompareResult;
    (function (CompareResult) {
        function isLessThan(result) {
            return result < 0;
        }
        CompareResult.isLessThan = isLessThan;
        function isLessThanOrEqual(result) {
            return result <= 0;
        }
        CompareResult.isLessThanOrEqual = isLessThanOrEqual;
        function isGreaterThan(result) {
            return result > 0;
        }
        CompareResult.isGreaterThan = isGreaterThan;
        function isNeitherLessOrGreaterThan(result) {
            return result === 0;
        }
        CompareResult.isNeitherLessOrGreaterThan = isNeitherLessOrGreaterThan;
        CompareResult.greaterThan = 1;
        CompareResult.lessThan = -1;
        CompareResult.neitherLessOrGreaterThan = 0;
    })(CompareResult || (exports.CompareResult = CompareResult = {}));
    function compareBy(selector, comparator) {
        return (a, b) => comparator(selector(a), selector(b));
    }
    function tieBreakComparators(...comparators) {
        return (item1, item2) => {
            for (const comparator of comparators) {
                const result = comparator(item1, item2);
                if (!CompareResult.isNeitherLessOrGreaterThan(result)) {
                    return result;
                }
            }
            return CompareResult.neitherLessOrGreaterThan;
        };
    }
    /**
     * The natural order on numbers.
    */
    const numberComparator = (a, b) => a - b;
    exports.numberComparator = numberComparator;
    const booleanComparator = (a, b) => (0, exports.numberComparator)(a ? 1 : 0, b ? 1 : 0);
    exports.booleanComparator = booleanComparator;
    function reverseOrder(comparator) {
        return (a, b) => -comparator(a, b);
    }
    class ArrayQueue {
        /**
         * Constructs a queue that is backed by the given array. Runtime is O(1).
        */
        constructor(items) {
            this.items = items;
            this.firstIdx = 0;
            this.lastIdx = this.items.length - 1;
        }
        get length() {
            return this.lastIdx - this.firstIdx + 1;
        }
        /**
         * Consumes elements from the beginning of the queue as long as the predicate returns true.
         * If no elements were consumed, `null` is returned. Has a runtime of O(result.length).
        */
        takeWhile(predicate) {
            // P(k) := k <= this.lastIdx && predicate(this.items[k])
            // Find s := min { k | k >= this.firstIdx && !P(k) } and return this.data[this.firstIdx...s)
            let startIdx = this.firstIdx;
            while (startIdx < this.items.length && predicate(this.items[startIdx])) {
                startIdx++;
            }
            const result = startIdx === this.firstIdx ? null : this.items.slice(this.firstIdx, startIdx);
            this.firstIdx = startIdx;
            return result;
        }
        /**
         * Consumes elements from the end of the queue as long as the predicate returns true.
         * If no elements were consumed, `null` is returned.
         * The result has the same order as the underlying array!
        */
        takeFromEndWhile(predicate) {
            // P(k) := this.firstIdx >= k && predicate(this.items[k])
            // Find s := max { k | k <= this.lastIdx && !P(k) } and return this.data(s...this.lastIdx]
            let endIdx = this.lastIdx;
            while (endIdx >= 0 && predicate(this.items[endIdx])) {
                endIdx--;
            }
            const result = endIdx === this.lastIdx ? null : this.items.slice(endIdx + 1, this.lastIdx + 1);
            this.lastIdx = endIdx;
            return result;
        }
        peek() {
            if (this.length === 0) {
                return undefined;
            }
            return this.items[this.firstIdx];
        }
        dequeue() {
            const result = this.items[this.firstIdx];
            this.firstIdx++;
            return result;
        }
        takeCount(count) {
            const result = this.items.slice(this.firstIdx, this.firstIdx + count);
            this.firstIdx += count;
            return result;
        }
    }
    exports.ArrayQueue = ArrayQueue;
    /**
     * This class is faster than an iterator and array for lazy computed data.
    */
    class CallbackIterable {
        static { this.empty = new CallbackIterable(_callback => { }); }
        constructor(
        /**
         * Calls the callback for every item.
         * Stops when the callback returns false.
        */
        iterate) {
            this.iterate = iterate;
        }
        toArray() {
            const result = [];
            this.iterate(item => { result.push(item); return true; });
            return result;
        }
        filter(predicate) {
            return new CallbackIterable(cb => this.iterate(item => predicate(item) ? cb(item) : true));
        }
        map(mapFn) {
            return new CallbackIterable(cb => this.iterate(item => cb(mapFn(item))));
        }
        findLast(predicate) {
            let result;
            this.iterate(item => {
                if (predicate(item)) {
                    result = item;
                }
                return true;
            });
            return result;
        }
        findLastMaxBy(comparator) {
            let result;
            let first = true;
            this.iterate(item => {
                if (first || CompareResult.isGreaterThan(comparator(item, result))) {
                    first = false;
                    result = item;
                }
                return true;
            });
            return result;
        }
    }
    exports.CallbackIterable = CallbackIterable;
    /**
     * Represents a re-arrangement of items in an array.
     */
    class Permutation {
        constructor(_indexMap) {
            this._indexMap = _indexMap;
        }
        /**
         * Returns a permutation that sorts the given array according to the given compare function.
         */
        static createSortPermutation(arr, compareFn) {
            const sortIndices = Array.from(arr.keys()).sort((index1, index2) => compareFn(arr[index1], arr[index2]));
            return new Permutation(sortIndices);
        }
        /**
         * Returns a new array with the elements of the given array re-arranged according to this permutation.
         */
        apply(arr) {
            return arr.map((_, index) => arr[this._indexMap[index]]);
        }
        /**
         * Returns a new permutation that undoes the re-arrangement of this permutation.
        */
        inverse() {
            const inverseIndexMap = this._indexMap.slice();
            for (let i = 0; i < this._indexMap.length; i++) {
                inverseIndexMap[this._indexMap[i]] = i;
            }
            return new Permutation(inverseIndexMap);
        }
    }
    exports.Permutation = Permutation;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[67/*vs/base/common/arraysFind*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MonotonousArray = void 0;
    exports.findLast = findLast;
    exports.findLastIdx = findLastIdx;
    exports.findLastMonotonous = findLastMonotonous;
    exports.findLastIdxMonotonous = findLastIdxMonotonous;
    exports.findFirstMonotonous = findFirstMonotonous;
    exports.findFirstIdxMonotonousOrArrLen = findFirstIdxMonotonousOrArrLen;
    exports.findFirstMax = findFirstMax;
    exports.findLastMax = findLastMax;
    exports.findFirstMin = findFirstMin;
    exports.findMaxIdx = findMaxIdx;
    exports.mapFindFirst = mapFindFirst;
    function findLast(array, predicate) {
        const idx = findLastIdx(array, predicate);
        if (idx === -1) {
            return undefined;
        }
        return array[idx];
    }
    function findLastIdx(array, predicate, fromIndex = array.length - 1) {
        for (let i = fromIndex; i >= 0; i--) {
            const element = array[i];
            if (predicate(element)) {
                return i;
            }
        }
        return -1;
    }
    /**
     * Finds the last item where predicate is true using binary search.
     * `predicate` must be monotonous, i.e. `arr.map(predicate)` must be like `[true, ..., true, false, ..., false]`!
     *
     * @returns `undefined` if no item matches, otherwise the last item that matches the predicate.
     */
    function findLastMonotonous(array, predicate) {
        const idx = findLastIdxMonotonous(array, predicate);
        return idx === -1 ? undefined : array[idx];
    }
    /**
     * Finds the last item where predicate is true using binary search.
     * `predicate` must be monotonous, i.e. `arr.map(predicate)` must be like `[true, ..., true, false, ..., false]`!
     *
     * @returns `startIdx - 1` if predicate is false for all items, otherwise the index of the last item that matches the predicate.
     */
    function findLastIdxMonotonous(array, predicate, startIdx = 0, endIdxEx = array.length) {
        let i = startIdx;
        let j = endIdxEx;
        while (i < j) {
            const k = Math.floor((i + j) / 2);
            if (predicate(array[k])) {
                i = k + 1;
            }
            else {
                j = k;
            }
        }
        return i - 1;
    }
    /**
     * Finds the first item where predicate is true using binary search.
     * `predicate` must be monotonous, i.e. `arr.map(predicate)` must be like `[false, ..., false, true, ..., true]`!
     *
     * @returns `undefined` if no item matches, otherwise the first item that matches the predicate.
     */
    function findFirstMonotonous(array, predicate) {
        const idx = findFirstIdxMonotonousOrArrLen(array, predicate);
        return idx === array.length ? undefined : array[idx];
    }
    /**
     * Finds the first item where predicate is true using binary search.
     * `predicate` must be monotonous, i.e. `arr.map(predicate)` must be like `[false, ..., false, true, ..., true]`!
     *
     * @returns `endIdxEx` if predicate is false for all items, otherwise the index of the first item that matches the predicate.
     */
    function findFirstIdxMonotonousOrArrLen(array, predicate, startIdx = 0, endIdxEx = array.length) {
        let i = startIdx;
        let j = endIdxEx;
        while (i < j) {
            const k = Math.floor((i + j) / 2);
            if (predicate(array[k])) {
                j = k;
            }
            else {
                i = k + 1;
            }
        }
        return i;
    }
    /**
     * Use this when
     * * You have a sorted array
     * * You query this array with a monotonous predicate to find the last item that has a certain property.
     * * You query this array multiple times with monotonous predicates that get weaker and weaker.
     */
    class MonotonousArray {
        static { this.assertInvariants = false; }
        constructor(_array) {
            this._array = _array;
            this._findLastMonotonousLastIdx = 0;
        }
        /**
         * The predicate must be monotonous, i.e. `arr.map(predicate)` must be like `[true, ..., true, false, ..., false]`!
         * For subsequent calls, current predicate must be weaker than (or equal to) the previous predicate, i.e. more entries must be `true`.
         */
        findLastMonotonous(predicate) {
            if (MonotonousArray.assertInvariants) {
                if (this._prevFindLastPredicate) {
                    for (const item of this._array) {
                        if (this._prevFindLastPredicate(item) && !predicate(item)) {
                            throw new Error('MonotonousArray: current predicate must be weaker than (or equal to) the previous predicate.');
                        }
                    }
                }
                this._prevFindLastPredicate = predicate;
            }
            const idx = findLastIdxMonotonous(this._array, predicate, this._findLastMonotonousLastIdx);
            this._findLastMonotonousLastIdx = idx + 1;
            return idx === -1 ? undefined : this._array[idx];
        }
    }
    exports.MonotonousArray = MonotonousArray;
    /**
     * Returns the first item that is equal to or greater than every other item.
    */
    function findFirstMax(array, comparator) {
        if (array.length === 0) {
            return undefined;
        }
        let max = array[0];
        for (let i = 1; i < array.length; i++) {
            const item = array[i];
            if (comparator(item, max) > 0) {
                max = item;
            }
        }
        return max;
    }
    /**
     * Returns the last item that is equal to or greater than every other item.
    */
    function findLastMax(array, comparator) {
        if (array.length === 0) {
            return undefined;
        }
        let max = array[0];
        for (let i = 1; i < array.length; i++) {
            const item = array[i];
            if (comparator(item, max) >= 0) {
                max = item;
            }
        }
        return max;
    }
    /**
     * Returns the first item that is equal to or less than every other item.
    */
    function findFirstMin(array, comparator) {
        return findFirstMax(array, (a, b) => -comparator(a, b));
    }
    function findMaxIdx(array, comparator) {
        if (array.length === 0) {
            return -1;
        }
        let maxIdx = 0;
        for (let i = 1; i < array.length; i++) {
            const item = array[i];
            if (comparator(item, array[maxIdx]) > 0) {
                maxIdx = i;
            }
        }
        return maxIdx;
    }
    /**
     * Returns the first mapped value of the array which is not undefined.
     */
    function mapFindFirst(items, mapFn) {
        for (const value of items) {
            const mapped = mapFn(value);
            if (mapped !== undefined) {
                return mapped;
            }
        }
        return undefined;
    }
});

define(__m[297/*vs/base/common/cache*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CachedFunction = exports.LRUCachedFunction = void 0;
    exports.identity = identity;
    function identity(t) {
        return t;
    }
    /**
     * Uses a LRU cache to make a given parametrized function cached.
     * Caches just the last key/value.
    */
    class LRUCachedFunction {
        constructor(arg1, arg2) {
            this.lastCache = undefined;
            this.lastArgKey = undefined;
            if (typeof arg1 === 'function') {
                this._fn = arg1;
                this._computeKey = identity;
            }
            else {
                this._fn = arg2;
                this._computeKey = arg1.getCacheKey;
            }
        }
        get(arg) {
            const key = this._computeKey(arg);
            if (this.lastArgKey !== key) {
                this.lastArgKey = key;
                this.lastCache = this._fn(arg);
            }
            return this.lastCache;
        }
    }
    exports.LRUCachedFunction = LRUCachedFunction;
    /**
     * Uses an unbounded cache to memoize the results of the given function.
    */
    class CachedFunction {
        get cachedValues() {
            return this._map;
        }
        constructor(arg1, arg2) {
            this._map = new Map();
            this._map2 = new Map();
            if (typeof arg1 === 'function') {
                this._fn = arg1;
                this._computeKey = identity;
            }
            else {
                this._fn = arg2;
                this._computeKey = arg1.getCacheKey;
            }
        }
        get(arg) {
            const key = this._computeKey(arg);
            if (this._map2.has(key)) {
                return this._map2.get(key);
            }
            const value = this._fn(arg);
            this._map.set(arg, value);
            this._map2.set(key, value);
            return value;
        }
    }
    exports.CachedFunction = CachedFunction;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[298/*vs/base/common/collections*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.diffSets = diffSets;
    exports.intersection = intersection;
    function diffSets(before, after) {
        const removed = [];
        const added = [];
        for (const element of before) {
            if (!after.has(element)) {
                removed.push(element);
            }
        }
        for (const element of after) {
            if (!before.has(element)) {
                added.push(element);
            }
        }
        return { removed, added };
    }
    /**
     * Computes the intersection of two sets.
     *
     * @param setA - The first set.
     * @param setB - The second iterable.
     * @returns A new set containing the elements that are in both `setA` and `setB`.
     */
    function intersection(setA, setB) {
        const result = new Set();
        for (const elem of setB) {
            if (setA.has(elem)) {
                result.add(elem);
            }
        }
        return result;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[33/*vs/base/common/color*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Color = exports.HSVA = exports.HSLA = exports.RGBA = void 0;
    function roundFloat(number, decimalPoints) {
        const decimal = Math.pow(10, decimalPoints);
        return Math.round(number * decimal) / decimal;
    }
    class RGBA {
        constructor(r, g, b, a = 1) {
            this._rgbaBrand = undefined;
            this.r = Math.min(255, Math.max(0, r)) | 0;
            this.g = Math.min(255, Math.max(0, g)) | 0;
            this.b = Math.min(255, Math.max(0, b)) | 0;
            this.a = roundFloat(Math.max(Math.min(1, a), 0), 3);
        }
        static equals(a, b) {
            return a.r === b.r && a.g === b.g && a.b === b.b && a.a === b.a;
        }
    }
    exports.RGBA = RGBA;
    class HSLA {
        constructor(h, s, l, a) {
            this._hslaBrand = undefined;
            this.h = Math.max(Math.min(360, h), 0) | 0;
            this.s = roundFloat(Math.max(Math.min(1, s), 0), 3);
            this.l = roundFloat(Math.max(Math.min(1, l), 0), 3);
            this.a = roundFloat(Math.max(Math.min(1, a), 0), 3);
        }
        static equals(a, b) {
            return a.h === b.h && a.s === b.s && a.l === b.l && a.a === b.a;
        }
        /**
         * Converts an RGB color value to HSL. Conversion formula
         * adapted from http://en.wikipedia.org/wiki/HSL_color_space.
         * Assumes r, g, and b are contained in the set [0, 255] and
         * returns h in the set [0, 360], s, and l in the set [0, 1].
         */
        static fromRGBA(rgba) {
            const r = rgba.r / 255;
            const g = rgba.g / 255;
            const b = rgba.b / 255;
            const a = rgba.a;
            const max = Math.max(r, g, b);
            const min = Math.min(r, g, b);
            let h = 0;
            let s = 0;
            const l = (min + max) / 2;
            const chroma = max - min;
            if (chroma > 0) {
                s = Math.min((l <= 0.5 ? chroma / (2 * l) : chroma / (2 - (2 * l))), 1);
                switch (max) {
                    case r:
                        h = (g - b) / chroma + (g < b ? 6 : 0);
                        break;
                    case g:
                        h = (b - r) / chroma + 2;
                        break;
                    case b:
                        h = (r - g) / chroma + 4;
                        break;
                }
                h *= 60;
                h = Math.round(h);
            }
            return new HSLA(h, s, l, a);
        }
        static _hue2rgb(p, q, t) {
            if (t < 0) {
                t += 1;
            }
            if (t > 1) {
                t -= 1;
            }
            if (t < 1 / 6) {
                return p + (q - p) * 6 * t;
            }
            if (t < 1 / 2) {
                return q;
            }
            if (t < 2 / 3) {
                return p + (q - p) * (2 / 3 - t) * 6;
            }
            return p;
        }
        /**
         * Converts an HSL color value to RGB. Conversion formula
         * adapted from http://en.wikipedia.org/wiki/HSL_color_space.
         * Assumes h in the set [0, 360] s, and l are contained in the set [0, 1] and
         * returns r, g, and b in the set [0, 255].
         */
        static toRGBA(hsla) {
            const h = hsla.h / 360;
            const { s, l, a } = hsla;
            let r, g, b;
            if (s === 0) {
                r = g = b = l; // achromatic
            }
            else {
                const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
                const p = 2 * l - q;
                r = HSLA._hue2rgb(p, q, h + 1 / 3);
                g = HSLA._hue2rgb(p, q, h);
                b = HSLA._hue2rgb(p, q, h - 1 / 3);
            }
            return new RGBA(Math.round(r * 255), Math.round(g * 255), Math.round(b * 255), a);
        }
    }
    exports.HSLA = HSLA;
    class HSVA {
        constructor(h, s, v, a) {
            this._hsvaBrand = undefined;
            this.h = Math.max(Math.min(360, h), 0) | 0;
            this.s = roundFloat(Math.max(Math.min(1, s), 0), 3);
            this.v = roundFloat(Math.max(Math.min(1, v), 0), 3);
            this.a = roundFloat(Math.max(Math.min(1, a), 0), 3);
        }
        static equals(a, b) {
            return a.h === b.h && a.s === b.s && a.v === b.v && a.a === b.a;
        }
        // from http://www.rapidtables.com/convert/color/rgb-to-hsv.htm
        static fromRGBA(rgba) {
            const r = rgba.r / 255;
            const g = rgba.g / 255;
            const b = rgba.b / 255;
            const cmax = Math.max(r, g, b);
            const cmin = Math.min(r, g, b);
            const delta = cmax - cmin;
            const s = cmax === 0 ? 0 : (delta / cmax);
            let m;
            if (delta === 0) {
                m = 0;
            }
            else if (cmax === r) {
                m = ((((g - b) / delta) % 6) + 6) % 6;
            }
            else if (cmax === g) {
                m = ((b - r) / delta) + 2;
            }
            else {
                m = ((r - g) / delta) + 4;
            }
            return new HSVA(Math.round(m * 60), s, cmax, rgba.a);
        }
        // from http://www.rapidtables.com/convert/color/hsv-to-rgb.htm
        static toRGBA(hsva) {
            const { h, s, v, a } = hsva;
            const c = v * s;
            const x = c * (1 - Math.abs((h / 60) % 2 - 1));
            const m = v - c;
            let [r, g, b] = [0, 0, 0];
            if (h < 60) {
                r = c;
                g = x;
            }
            else if (h < 120) {
                r = x;
                g = c;
            }
            else if (h < 180) {
                g = c;
                b = x;
            }
            else if (h < 240) {
                g = x;
                b = c;
            }
            else if (h < 300) {
                r = x;
                b = c;
            }
            else if (h <= 360) {
                r = c;
                b = x;
            }
            r = Math.round((r + m) * 255);
            g = Math.round((g + m) * 255);
            b = Math.round((b + m) * 255);
            return new RGBA(r, g, b, a);
        }
    }
    exports.HSVA = HSVA;
    class Color {
        static fromHex(hex) {
            return Color.Format.CSS.parseHex(hex) || Color.red;
        }
        static equals(a, b) {
            if (!a && !b) {
                return true;
            }
            if (!a || !b) {
                return false;
            }
            return a.equals(b);
        }
        get hsla() {
            if (this._hsla) {
                return this._hsla;
            }
            else {
                return HSLA.fromRGBA(this.rgba);
            }
        }
        get hsva() {
            if (this._hsva) {
                return this._hsva;
            }
            return HSVA.fromRGBA(this.rgba);
        }
        constructor(arg) {
            if (!arg) {
                throw new Error('Color needs a value');
            }
            else if (arg instanceof RGBA) {
                this.rgba = arg;
            }
            else if (arg instanceof HSLA) {
                this._hsla = arg;
                this.rgba = HSLA.toRGBA(arg);
            }
            else if (arg instanceof HSVA) {
                this._hsva = arg;
                this.rgba = HSVA.toRGBA(arg);
            }
            else {
                throw new Error('Invalid color ctor argument');
            }
        }
        equals(other) {
            return !!other && RGBA.equals(this.rgba, other.rgba) && HSLA.equals(this.hsla, other.hsla) && HSVA.equals(this.hsva, other.hsva);
        }
        /**
         * http://www.w3.org/TR/WCAG20/#relativeluminancedef
         * Returns the number in the set [0, 1]. O => Darkest Black. 1 => Lightest white.
         */
        getRelativeLuminance() {
            const R = Color._relativeLuminanceForComponent(this.rgba.r);
            const G = Color._relativeLuminanceForComponent(this.rgba.g);
            const B = Color._relativeLuminanceForComponent(this.rgba.b);
            const luminance = 0.2126 * R + 0.7152 * G + 0.0722 * B;
            return roundFloat(luminance, 4);
        }
        static _relativeLuminanceForComponent(color) {
            const c = color / 255;
            return (c <= 0.03928) ? c / 12.92 : Math.pow(((c + 0.055) / 1.055), 2.4);
        }
        /**
         *	http://24ways.org/2010/calculating-color-contrast
         *  Return 'true' if lighter color otherwise 'false'
         */
        isLighter() {
            const yiq = (this.rgba.r * 299 + this.rgba.g * 587 + this.rgba.b * 114) / 1000;
            return yiq >= 128;
        }
        isLighterThan(another) {
            const lum1 = this.getRelativeLuminance();
            const lum2 = another.getRelativeLuminance();
            return lum1 > lum2;
        }
        isDarkerThan(another) {
            const lum1 = this.getRelativeLuminance();
            const lum2 = another.getRelativeLuminance();
            return lum1 < lum2;
        }
        lighten(factor) {
            return new Color(new HSLA(this.hsla.h, this.hsla.s, this.hsla.l + this.hsla.l * factor, this.hsla.a));
        }
        darken(factor) {
            return new Color(new HSLA(this.hsla.h, this.hsla.s, this.hsla.l - this.hsla.l * factor, this.hsla.a));
        }
        transparent(factor) {
            const { r, g, b, a } = this.rgba;
            return new Color(new RGBA(r, g, b, a * factor));
        }
        isTransparent() {
            return this.rgba.a === 0;
        }
        isOpaque() {
            return this.rgba.a === 1;
        }
        opposite() {
            return new Color(new RGBA(255 - this.rgba.r, 255 - this.rgba.g, 255 - this.rgba.b, this.rgba.a));
        }
        makeOpaque(opaqueBackground) {
            if (this.isOpaque() || opaqueBackground.rgba.a !== 1) {
                // only allow to blend onto a non-opaque color onto a opaque color
                return this;
            }
            const { r, g, b, a } = this.rgba;
            // https://stackoverflow.com/questions/12228548/finding-equivalent-color-with-opacity
            return new Color(new RGBA(opaqueBackground.rgba.r - a * (opaqueBackground.rgba.r - r), opaqueBackground.rgba.g - a * (opaqueBackground.rgba.g - g), opaqueBackground.rgba.b - a * (opaqueBackground.rgba.b - b), 1));
        }
        toString() {
            if (!this._toString) {
                this._toString = Color.Format.CSS.format(this);
            }
            return this._toString;
        }
        static getLighterColor(of, relative, factor) {
            if (of.isLighterThan(relative)) {
                return of;
            }
            factor = factor ? factor : 0.5;
            const lum1 = of.getRelativeLuminance();
            const lum2 = relative.getRelativeLuminance();
            factor = factor * (lum2 - lum1) / lum2;
            return of.lighten(factor);
        }
        static getDarkerColor(of, relative, factor) {
            if (of.isDarkerThan(relative)) {
                return of;
            }
            factor = factor ? factor : 0.5;
            const lum1 = of.getRelativeLuminance();
            const lum2 = relative.getRelativeLuminance();
            factor = factor * (lum1 - lum2) / lum1;
            return of.darken(factor);
        }
        static { this.white = new Color(new RGBA(255, 255, 255, 1)); }
        static { this.black = new Color(new RGBA(0, 0, 0, 1)); }
        static { this.red = new Color(new RGBA(255, 0, 0, 1)); }
        static { this.blue = new Color(new RGBA(0, 0, 255, 1)); }
        static { this.green = new Color(new RGBA(0, 255, 0, 1)); }
        static { this.cyan = new Color(new RGBA(0, 255, 255, 1)); }
        static { this.lightgrey = new Color(new RGBA(211, 211, 211, 1)); }
        static { this.transparent = new Color(new RGBA(0, 0, 0, 0)); }
    }
    exports.Color = Color;
    (function (Color) {
        let Format;
        (function (Format) {
            let CSS;
            (function (CSS) {
                function formatRGB(color) {
                    if (color.rgba.a === 1) {
                        return `rgb(${color.rgba.r}, ${color.rgba.g}, ${color.rgba.b})`;
                    }
                    return Color.Format.CSS.formatRGBA(color);
                }
                CSS.formatRGB = formatRGB;
                function formatRGBA(color) {
                    return `rgba(${color.rgba.r}, ${color.rgba.g}, ${color.rgba.b}, ${+(color.rgba.a).toFixed(2)})`;
                }
                CSS.formatRGBA = formatRGBA;
                function formatHSL(color) {
                    if (color.hsla.a === 1) {
                        return `hsl(${color.hsla.h}, ${(color.hsla.s * 100).toFixed(2)}%, ${(color.hsla.l * 100).toFixed(2)}%)`;
                    }
                    return Color.Format.CSS.formatHSLA(color);
                }
                CSS.formatHSL = formatHSL;
                function formatHSLA(color) {
                    return `hsla(${color.hsla.h}, ${(color.hsla.s * 100).toFixed(2)}%, ${(color.hsla.l * 100).toFixed(2)}%, ${color.hsla.a.toFixed(2)})`;
                }
                CSS.formatHSLA = formatHSLA;
                function _toTwoDigitHex(n) {
                    const r = n.toString(16);
                    return r.length !== 2 ? '0' + r : r;
                }
                /**
                 * Formats the color as #RRGGBB
                 */
                function formatHex(color) {
                    return `#${_toTwoDigitHex(color.rgba.r)}${_toTwoDigitHex(color.rgba.g)}${_toTwoDigitHex(color.rgba.b)}`;
                }
                CSS.formatHex = formatHex;
                /**
                 * Formats the color as #RRGGBBAA
                 * If 'compact' is set, colors without transparancy will be printed as #RRGGBB
                 */
                function formatHexA(color, compact = false) {
                    if (compact && color.rgba.a === 1) {
                        return Color.Format.CSS.formatHex(color);
                    }
                    return `#${_toTwoDigitHex(color.rgba.r)}${_toTwoDigitHex(color.rgba.g)}${_toTwoDigitHex(color.rgba.b)}${_toTwoDigitHex(Math.round(color.rgba.a * 255))}`;
                }
                CSS.formatHexA = formatHexA;
                /**
                 * The default format will use HEX if opaque and RGBA otherwise.
                 */
                function format(color) {
                    if (color.isOpaque()) {
                        return Color.Format.CSS.formatHex(color);
                    }
                    return Color.Format.CSS.formatRGBA(color);
                }
                CSS.format = format;
                /**
                 * Converts an Hex color value to a Color.
                 * returns r, g, and b are contained in the set [0, 255]
                 * @param hex string (#RGB, #RGBA, #RRGGBB or #RRGGBBAA).
                 */
                function parseHex(hex) {
                    const length = hex.length;
                    if (length === 0) {
                        // Invalid color
                        return null;
                    }
                    if (hex.charCodeAt(0) !== 35 /* CharCode.Hash */) {
                        // Does not begin with a #
                        return null;
                    }
                    if (length === 7) {
                        // #RRGGBB format
                        const r = 16 * _parseHexDigit(hex.charCodeAt(1)) + _parseHexDigit(hex.charCodeAt(2));
                        const g = 16 * _parseHexDigit(hex.charCodeAt(3)) + _parseHexDigit(hex.charCodeAt(4));
                        const b = 16 * _parseHexDigit(hex.charCodeAt(5)) + _parseHexDigit(hex.charCodeAt(6));
                        return new Color(new RGBA(r, g, b, 1));
                    }
                    if (length === 9) {
                        // #RRGGBBAA format
                        const r = 16 * _parseHexDigit(hex.charCodeAt(1)) + _parseHexDigit(hex.charCodeAt(2));
                        const g = 16 * _parseHexDigit(hex.charCodeAt(3)) + _parseHexDigit(hex.charCodeAt(4));
                        const b = 16 * _parseHexDigit(hex.charCodeAt(5)) + _parseHexDigit(hex.charCodeAt(6));
                        const a = 16 * _parseHexDigit(hex.charCodeAt(7)) + _parseHexDigit(hex.charCodeAt(8));
                        return new Color(new RGBA(r, g, b, a / 255));
                    }
                    if (length === 4) {
                        // #RGB format
                        const r = _parseHexDigit(hex.charCodeAt(1));
                        const g = _parseHexDigit(hex.charCodeAt(2));
                        const b = _parseHexDigit(hex.charCodeAt(3));
                        return new Color(new RGBA(16 * r + r, 16 * g + g, 16 * b + b));
                    }
                    if (length === 5) {
                        // #RGBA format
                        const r = _parseHexDigit(hex.charCodeAt(1));
                        const g = _parseHexDigit(hex.charCodeAt(2));
                        const b = _parseHexDigit(hex.charCodeAt(3));
                        const a = _parseHexDigit(hex.charCodeAt(4));
                        return new Color(new RGBA(16 * r + r, 16 * g + g, 16 * b + b, (16 * a + a) / 255));
                    }
                    // Invalid color
                    return null;
                }
                CSS.parseHex = parseHex;
                function _parseHexDigit(charCode) {
                    switch (charCode) {
                        case 48 /* CharCode.Digit0 */: return 0;
                        case 49 /* CharCode.Digit1 */: return 1;
                        case 50 /* CharCode.Digit2 */: return 2;
                        case 51 /* CharCode.Digit3 */: return 3;
                        case 52 /* CharCode.Digit4 */: return 4;
                        case 53 /* CharCode.Digit5 */: return 5;
                        case 54 /* CharCode.Digit6 */: return 6;
                        case 55 /* CharCode.Digit7 */: return 7;
                        case 56 /* CharCode.Digit8 */: return 8;
                        case 57 /* CharCode.Digit9 */: return 9;
                        case 97 /* CharCode.a */: return 10;
                        case 65 /* CharCode.A */: return 10;
                        case 98 /* CharCode.b */: return 11;
                        case 66 /* CharCode.B */: return 11;
                        case 99 /* CharCode.c */: return 12;
                        case 67 /* CharCode.C */: return 12;
                        case 100 /* CharCode.d */: return 13;
                        case 68 /* CharCode.D */: return 13;
                        case 101 /* CharCode.e */: return 14;
                        case 69 /* CharCode.E */: return 14;
                        case 102 /* CharCode.f */: return 15;
                        case 70 /* CharCode.F */: return 15;
                    }
                    return 0;
                }
            })(CSS = Format.CSS || (Format.CSS = {}));
        })(Format = Color.Format || (Color.Format = {}));
    })(Color || (exports.Color = Color = {}));
});

define(__m[126/*vs/base/common/decorators*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.memoize = memoize;
    function memoize(_target, key, descriptor) {
        let fnKey = null;
        let fn = null;
        if (typeof descriptor.value === 'function') {
            fnKey = 'value';
            fn = descriptor.value;
            if (fn.length !== 0) {
                console.warn('Memoize should only be used in functions with zero parameters');
            }
        }
        else if (typeof descriptor.get === 'function') {
            fnKey = 'get';
            fn = descriptor.get;
        }
        if (!fn) {
            throw new Error('not supported');
        }
        const memoizeKey = `$memoize$${key}`;
        descriptor[fnKey] = function (...args) {
            if (!this.hasOwnProperty(memoizeKey)) {
                Object.defineProperty(this, memoizeKey, {
                    configurable: false,
                    enumerable: false,
                    writable: false,
                    value: fn.apply(this, args)
                });
            }
            return this[memoizeKey];
        };
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[444/*vs/base/common/diff/diffChange*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DiffChange = void 0;
    /**
     * Represents information about a specific difference between two sequences.
     */
    class DiffChange {
        /**
         * Constructs a new DiffChange with the given sequence information
         * and content.
         */
        constructor(originalStart, originalLength, modifiedStart, modifiedLength) {
            //Debug.Assert(originalLength > 0 || modifiedLength > 0, "originalLength and modifiedLength cannot both be <= 0");
            this.originalStart = originalStart;
            this.originalLength = originalLength;
            this.modifiedStart = modifiedStart;
            this.modifiedLength = modifiedLength;
        }
        /**
         * The end point (exclusive) of the change in the original sequence.
         */
        getOriginalEnd() {
            return this.originalStart + this.originalLength;
        }
        /**
         * The end point (exclusive) of the change in the modified sequence.
         */
        getModifiedEnd() {
            return this.modifiedStart + this.modifiedLength;
        }
    }
    exports.DiffChange = DiffChange;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[102/*vs/base/common/equals*/], __M([1/*require*/,0/*exports*/,13/*vs/base/common/arrays*/]), function (require, exports, arrays) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.strictEquals = void 0;
    exports.itemsEquals = itemsEquals;
    exports.itemEquals = itemEquals;
    exports.equalsIfDefined = equalsIfDefined;
    exports.structuralEquals = structuralEquals;
    /**
     * Compares two items for equality using strict equality.
    */
    const strictEquals = (a, b) => a === b;
    exports.strictEquals = strictEquals;
    /**
     * Checks if the items of two arrays are equal.
     * By default, strict equality is used to compare elements, but a custom equality comparer can be provided.
     */
    function itemsEquals(itemEquals = exports.strictEquals) {
        return (a, b) => arrays.equals(a, b, itemEquals);
    }
    /**
     * Uses `item.equals(other)` to determine equality.
     */
    function itemEquals() {
        return (a, b) => a.equals(b);
    }
    function equalsIfDefined(equalsOrV1, v2, equals) {
        if (equals !== undefined) {
            const v1 = equalsOrV1;
            if (v1 === undefined || v1 === null || v2 === undefined || v2 === null) {
                return v2 === v1;
            }
            return equals(v1, v2);
        }
        else {
            const equals = equalsOrV1;
            return (v1, v2) => {
                if (v1 === undefined || v1 === null || v2 === undefined || v2 === null) {
                    return v2 === v1;
                }
                return equals(v1, v2);
            };
        }
    }
    /**
     * Drills into arrays (items ordered) and objects (keys unordered) and uses strict equality on everything else.
    */
    function structuralEquals(a, b) {
        if (a === b) {
            return true;
        }
        if (Array.isArray(a) && Array.isArray(b)) {
            if (a.length !== b.length) {
                return false;
            }
            for (let i = 0; i < a.length; i++) {
                if (!structuralEquals(a[i], b[i])) {
                    return false;
                }
            }
            return true;
        }
        if (a && typeof a === 'object' && b && typeof b === 'object') {
            if (Object.getPrototypeOf(a) === Object.prototype && Object.getPrototypeOf(b) === Object.prototype) {
                const aObj = a;
                const bObj = b;
                const keysA = Object.keys(aObj);
                const keysB = Object.keys(bObj);
                const keysBSet = new Set(keysB);
                if (keysA.length !== keysB.length) {
                    return false;
                }
                for (const key of keysA) {
                    if (!keysBSet.has(key)) {
                        return false;
                    }
                    if (!structuralEquals(aObj[key], bObj[key])) {
                        return false;
                    }
                }
                return true;
            }
        }
        return false;
    }
    const objIds = new WeakMap();
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[8/*vs/base/common/errors*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.BugIndicatingError = exports.ErrorNoTelemetry = exports.NotSupportedError = exports.CancellationError = exports.errorHandler = exports.ErrorHandler = void 0;
    exports.onUnexpectedError = onUnexpectedError;
    exports.onUnexpectedExternalError = onUnexpectedExternalError;
    exports.transformErrorForSerialization = transformErrorForSerialization;
    exports.isCancellationError = isCancellationError;
    exports.canceled = canceled;
    exports.illegalArgument = illegalArgument;
    exports.illegalState = illegalState;
    // Avoid circular dependency on EventEmitter by implementing a subset of the interface.
    class ErrorHandler {
        constructor() {
            this.listeners = [];
            this.unexpectedErrorHandler = function (e) {
                setTimeout(() => {
                    if (e.stack) {
                        if (ErrorNoTelemetry.isErrorNoTelemetry(e)) {
                            throw new ErrorNoTelemetry(e.message + '\n\n' + e.stack);
                        }
                        throw new Error(e.message + '\n\n' + e.stack);
                    }
                    throw e;
                }, 0);
            };
        }
        emit(e) {
            this.listeners.forEach((listener) => {
                listener(e);
            });
        }
        onUnexpectedError(e) {
            this.unexpectedErrorHandler(e);
            this.emit(e);
        }
        // For external errors, we don't want the listeners to be called
        onUnexpectedExternalError(e) {
            this.unexpectedErrorHandler(e);
        }
    }
    exports.ErrorHandler = ErrorHandler;
    exports.errorHandler = new ErrorHandler();
    function onUnexpectedError(e) {
        // ignore errors from cancelled promises
        if (!isCancellationError(e)) {
            exports.errorHandler.onUnexpectedError(e);
        }
        return undefined;
    }
    function onUnexpectedExternalError(e) {
        // ignore errors from cancelled promises
        if (!isCancellationError(e)) {
            exports.errorHandler.onUnexpectedExternalError(e);
        }
        return undefined;
    }
    function transformErrorForSerialization(error) {
        if (error instanceof Error) {
            const { name, message } = error;
            const stack = error.stacktrace || error.stack;
            return {
                $isError: true,
                name,
                message,
                stack,
                noTelemetry: ErrorNoTelemetry.isErrorNoTelemetry(error)
            };
        }
        // return as is
        return error;
    }
    const canceledName = 'Canceled';
    /**
     * Checks if the given error is a promise in canceled state
     */
    function isCancellationError(error) {
        if (error instanceof CancellationError) {
            return true;
        }
        return error instanceof Error && error.name === canceledName && error.message === canceledName;
    }
    // !!!IMPORTANT!!!
    // Do NOT change this class because it is also used as an API-type.
    class CancellationError extends Error {
        constructor() {
            super(canceledName);
            this.name = this.message;
        }
    }
    exports.CancellationError = CancellationError;
    /**
     * @deprecated use {@link CancellationError `new CancellationError()`} instead
     */
    function canceled() {
        const error = new Error(canceledName);
        error.name = error.message;
        return error;
    }
    function illegalArgument(name) {
        if (name) {
            return new Error(`Illegal argument: ${name}`);
        }
        else {
            return new Error('Illegal argument');
        }
    }
    function illegalState(name) {
        if (name) {
            return new Error(`Illegal state: ${name}`);
        }
        else {
            return new Error('Illegal state');
        }
    }
    class NotSupportedError extends Error {
        constructor(message) {
            super('NotSupported');
            if (message) {
                this.message = message;
            }
        }
    }
    exports.NotSupportedError = NotSupportedError;
    /**
     * Error that when thrown won't be logged in telemetry as an unhandled error.
     */
    class ErrorNoTelemetry extends Error {
        constructor(msg) {
            super(msg);
            this.name = 'CodeExpectedError';
        }
        static fromError(err) {
            if (err instanceof ErrorNoTelemetry) {
                return err;
            }
            const result = new ErrorNoTelemetry();
            result.message = err.message;
            result.stack = err.stack;
            return result;
        }
        static isErrorNoTelemetry(err) {
            return err.name === 'CodeExpectedError';
        }
    }
    exports.ErrorNoTelemetry = ErrorNoTelemetry;
    /**
     * This error indicates a bug.
     * Do not throw this for invalid user input.
     * Only catch this error to recover gracefully from bugs.
     */
    class BugIndicatingError extends Error {
        constructor(message) {
            super(message || 'An unexpected bug occurred.');
            Object.setPrototypeOf(this, BugIndicatingError.prototype);
            // Because we know for sure only buggy code throws this,
            // we definitely want to break here and fix the bug.
            // eslint-disable-next-line no-debugger
            // debugger;
        }
    }
    exports.BugIndicatingError = BugIndicatingError;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[103/*vs/base/browser/trustedTypes*/], __M([1/*require*/,0/*exports*/,8/*vs/base/common/errors*/]), function (require, exports, errors_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.createTrustedTypesPolicy = createTrustedTypesPolicy;
    function createTrustedTypesPolicy(policyName, policyOptions) {
        const monacoEnvironment = globalThis.MonacoEnvironment;
        if (monacoEnvironment?.createTrustedTypesPolicy) {
            try {
                return monacoEnvironment.createTrustedTypesPolicy(policyName, policyOptions);
            }
            catch (err) {
                (0, errors_1.onUnexpectedError)(err);
                return undefined;
            }
        }
        try {
            return globalThis.trustedTypes?.createPolicy(policyName, policyOptions);
        }
        catch (err) {
            (0, errors_1.onUnexpectedError)(err);
            return undefined;
        }
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[90/*vs/base/common/assert*/], __M([1/*require*/,0/*exports*/,8/*vs/base/common/errors*/]), function (require, exports, errors_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ok = ok;
    exports.assertNever = assertNever;
    exports.softAssert = softAssert;
    exports.assertFn = assertFn;
    exports.checkAdjacentItems = checkAdjacentItems;
    /**
     * Throws an error with the provided message if the provided value does not evaluate to a true Javascript value.
     *
     * @deprecated Use `assert(...)` instead.
     * This method is usually used like this:
     * ```ts
     * import * as assert from 'vs/base/common/assert';
     * assert.ok(...);
     * ```
     *
     * However, `assert` in that example is a user chosen name.
     * There is no tooling for generating such an import statement.
     * Thus, the `assert(...)` function should be used instead.
     */
    function ok(value, message) {
        if (!value) {
            throw new Error(message ? `Assertion failed (${message})` : 'Assertion Failed');
        }
    }
    function assertNever(value, message = 'Unreachable') {
        throw new Error(message);
    }
    /**
     * Like assert, but doesn't throw.
     */
    function softAssert(condition) {
        if (!condition) {
            (0, errors_1.onUnexpectedError)(new errors_1.BugIndicatingError('Soft Assertion Failed'));
        }
    }
    /**
     * condition must be side-effect free!
     */
    function assertFn(condition) {
        if (!condition()) {
            // eslint-disable-next-line no-debugger
            debugger;
            // Reevaluate `condition` again to make debugging easier
            condition();
            (0, errors_1.onUnexpectedError)(new errors_1.BugIndicatingError('Assertion Failed'));
        }
    }
    function checkAdjacentItems(items, predicate) {
        let i = 0;
        while (i < items.length - 1) {
            const a = items[i];
            const b = items[i + 1];
            if (!predicate(a, b)) {
                return false;
            }
            i++;
        }
        return true;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[127/*vs/base/common/functional*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.createSingleCallFunction = createSingleCallFunction;
    /**
     * Given a function, returns a function that is only calling that function once.
     */
    function createSingleCallFunction(fn, fnDidRunCallback) {
        const _this = this;
        let didCall = false;
        let result;
        return function () {
            if (didCall) {
                return result;
            }
            didCall = true;
            if (fnDidRunCallback) {
                try {
                    result = fn.apply(_this, arguments);
                }
                finally {
                    fnDidRunCallback();
                }
            }
            else {
                result = fn.apply(_this, arguments);
            }
            return result;
        };
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[91/*vs/base/common/hierarchicalKind*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.HierarchicalKind = void 0;
    class HierarchicalKind {
        static { this.sep = '.'; }
        static { this.None = new HierarchicalKind('@@none@@'); } // Special kind that matches nothing
        static { this.Empty = new HierarchicalKind(''); }
        constructor(value) {
            this.value = value;
        }
        equals(other) {
            return this.value === other.value;
        }
        contains(other) {
            return this.equals(other) || this.value === '' || other.value.startsWith(this.value + HierarchicalKind.sep);
        }
        intersects(other) {
            return this.contains(other) || other.contains(this);
        }
        append(...parts) {
            return new HierarchicalKind((this.value ? [this.value, ...parts] : parts).join(HierarchicalKind.sep));
        }
    }
    exports.HierarchicalKind = HierarchicalKind;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[187/*vs/base/common/idGenerator*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.defaultGenerator = exports.IdGenerator = void 0;
    class IdGenerator {
        constructor(prefix) {
            this._prefix = prefix;
            this._lastId = 0;
        }
        nextId() {
            return this._prefix + (++this._lastId);
        }
    }
    exports.IdGenerator = IdGenerator;
    exports.defaultGenerator = new IdGenerator('id#');
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[53/*vs/base/common/iterator*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Iterable = void 0;
    var Iterable;
    (function (Iterable) {
        function is(thing) {
            return thing && typeof thing === 'object' && typeof thing[Symbol.iterator] === 'function';
        }
        Iterable.is = is;
        const _empty = Object.freeze([]);
        function empty() {
            return _empty;
        }
        Iterable.empty = empty;
        function* single(element) {
            yield element;
        }
        Iterable.single = single;
        function wrap(iterableOrElement) {
            if (is(iterableOrElement)) {
                return iterableOrElement;
            }
            else {
                return single(iterableOrElement);
            }
        }
        Iterable.wrap = wrap;
        function from(iterable) {
            return iterable || _empty;
        }
        Iterable.from = from;
        function* reverse(array) {
            for (let i = array.length - 1; i >= 0; i--) {
                yield array[i];
            }
        }
        Iterable.reverse = reverse;
        function isEmpty(iterable) {
            return !iterable || iterable[Symbol.iterator]().next().done === true;
        }
        Iterable.isEmpty = isEmpty;
        function first(iterable) {
            return iterable[Symbol.iterator]().next().value;
        }
        Iterable.first = first;
        function some(iterable, predicate) {
            let i = 0;
            for (const element of iterable) {
                if (predicate(element, i++)) {
                    return true;
                }
            }
            return false;
        }
        Iterable.some = some;
        function find(iterable, predicate) {
            for (const element of iterable) {
                if (predicate(element)) {
                    return element;
                }
            }
            return undefined;
        }
        Iterable.find = find;
        function* filter(iterable, predicate) {
            for (const element of iterable) {
                if (predicate(element)) {
                    yield element;
                }
            }
        }
        Iterable.filter = filter;
        function* map(iterable, fn) {
            let index = 0;
            for (const element of iterable) {
                yield fn(element, index++);
            }
        }
        Iterable.map = map;
        function* flatMap(iterable, fn) {
            let index = 0;
            for (const element of iterable) {
                yield* fn(element, index++);
            }
        }
        Iterable.flatMap = flatMap;
        function* concat(...iterables) {
            for (const iterable of iterables) {
                yield* iterable;
            }
        }
        Iterable.concat = concat;
        function reduce(iterable, reducer, initialValue) {
            let value = initialValue;
            for (const element of iterable) {
                value = reducer(value, element);
            }
            return value;
        }
        Iterable.reduce = reduce;
        /**
         * Returns an iterable slice of the array, with the same semantics as `array.slice()`.
         */
        function* slice(arr, from, to = arr.length) {
            if (from < 0) {
                from += arr.length;
            }
            if (to < 0) {
                to += arr.length;
            }
            else if (to > arr.length) {
                to = arr.length;
            }
            for (; from < to; from++) {
                yield arr[from];
            }
        }
        Iterable.slice = slice;
        /**
         * Consumes `atMost` elements from iterable and returns the consumed elements,
         * and an iterable for the rest of the elements.
         */
        function consume(iterable, atMost = Number.POSITIVE_INFINITY) {
            const consumed = [];
            if (atMost === 0) {
                return [consumed, iterable];
            }
            const iterator = iterable[Symbol.iterator]();
            for (let i = 0; i < atMost; i++) {
                const next = iterator.next();
                if (next.done) {
                    return [consumed, Iterable.empty()];
                }
                consumed.push(next.value);
            }
            return [consumed, { [Symbol.iterator]() { return iterator; } }];
        }
        Iterable.consume = consume;
        async function asyncToArray(iterable) {
            const result = [];
            for await (const item of iterable) {
                result.push(item);
            }
            return Promise.resolve(result);
        }
        Iterable.asyncToArray = asyncToArray;
    })(Iterable || (exports.Iterable = Iterable = {}));
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[72/*vs/base/common/keyCodes*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.KeyCodeUtils = exports.IMMUTABLE_KEY_CODE_TO_CODE = exports.IMMUTABLE_CODE_TO_KEY_CODE = exports.NATIVE_WINDOWS_KEY_CODE_TO_KEY_CODE = exports.EVENT_KEY_CODE_MAP = void 0;
    exports.KeyChord = KeyChord;
    class KeyCodeStrMap {
        constructor() {
            this._keyCodeToStr = [];
            this._strToKeyCode = Object.create(null);
        }
        define(keyCode, str) {
            this._keyCodeToStr[keyCode] = str;
            this._strToKeyCode[str.toLowerCase()] = keyCode;
        }
        keyCodeToStr(keyCode) {
            return this._keyCodeToStr[keyCode];
        }
        strToKeyCode(str) {
            return this._strToKeyCode[str.toLowerCase()] || 0 /* KeyCode.Unknown */;
        }
    }
    const uiMap = new KeyCodeStrMap();
    const userSettingsUSMap = new KeyCodeStrMap();
    const userSettingsGeneralMap = new KeyCodeStrMap();
    exports.EVENT_KEY_CODE_MAP = new Array(230);
    exports.NATIVE_WINDOWS_KEY_CODE_TO_KEY_CODE = {};
    const scanCodeIntToStr = [];
    const scanCodeStrToInt = Object.create(null);
    const scanCodeLowerCaseStrToInt = Object.create(null);
    /**
     * -1 if a ScanCode => KeyCode mapping depends on kb layout.
     */
    exports.IMMUTABLE_CODE_TO_KEY_CODE = [];
    /**
     * -1 if a KeyCode => ScanCode mapping depends on kb layout.
     */
    exports.IMMUTABLE_KEY_CODE_TO_CODE = [];
    for (let i = 0; i <= 193 /* ScanCode.MAX_VALUE */; i++) {
        exports.IMMUTABLE_CODE_TO_KEY_CODE[i] = -1 /* KeyCode.DependsOnKbLayout */;
    }
    for (let i = 0; i <= 132 /* KeyCode.MAX_VALUE */; i++) {
        exports.IMMUTABLE_KEY_CODE_TO_CODE[i] = -1 /* ScanCode.DependsOnKbLayout */;
    }
    (function () {
        // See https://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx
        // See https://github.com/microsoft/node-native-keymap/blob/88c0b0e5/deps/chromium/keyboard_codes_win.h
        const empty = '';
        const mappings = [
            // immutable, scanCode, scanCodeStr, keyCode, keyCodeStr, eventKeyCode, vkey, usUserSettingsLabel, generalUserSettingsLabel
            [1, 0 /* ScanCode.None */, 'None', 0 /* KeyCode.Unknown */, 'unknown', 0, 'VK_UNKNOWN', empty, empty],
            [1, 1 /* ScanCode.Hyper */, 'Hyper', 0 /* KeyCode.Unknown */, empty, 0, empty, empty, empty],
            [1, 2 /* ScanCode.Super */, 'Super', 0 /* KeyCode.Unknown */, empty, 0, empty, empty, empty],
            [1, 3 /* ScanCode.Fn */, 'Fn', 0 /* KeyCode.Unknown */, empty, 0, empty, empty, empty],
            [1, 4 /* ScanCode.FnLock */, 'FnLock', 0 /* KeyCode.Unknown */, empty, 0, empty, empty, empty],
            [1, 5 /* ScanCode.Suspend */, 'Suspend', 0 /* KeyCode.Unknown */, empty, 0, empty, empty, empty],
            [1, 6 /* ScanCode.Resume */, 'Resume', 0 /* KeyCode.Unknown */, empty, 0, empty, empty, empty],
            [1, 7 /* ScanCode.Turbo */, 'Turbo', 0 /* KeyCode.Unknown */, empty, 0, empty, empty, empty],
            [1, 8 /* ScanCode.Sleep */, 'Sleep', 0 /* KeyCode.Unknown */, empty, 0, 'VK_SLEEP', empty, empty],
            [1, 9 /* ScanCode.WakeUp */, 'WakeUp', 0 /* KeyCode.Unknown */, empty, 0, empty, empty, empty],
            [0, 10 /* ScanCode.KeyA */, 'KeyA', 31 /* KeyCode.KeyA */, 'A', 65, 'VK_A', empty, empty],
            [0, 11 /* ScanCode.KeyB */, 'KeyB', 32 /* KeyCode.KeyB */, 'B', 66, 'VK_B', empty, empty],
            [0, 12 /* ScanCode.KeyC */, 'KeyC', 33 /* KeyCode.KeyC */, 'C', 67, 'VK_C', empty, empty],
            [0, 13 /* ScanCode.KeyD */, 'KeyD', 34 /* KeyCode.KeyD */, 'D', 68, 'VK_D', empty, empty],
            [0, 14 /* ScanCode.KeyE */, 'KeyE', 35 /* KeyCode.KeyE */, 'E', 69, 'VK_E', empty, empty],
            [0, 15 /* ScanCode.KeyF */, 'KeyF', 36 /* KeyCode.KeyF */, 'F', 70, 'VK_F', empty, empty],
            [0, 16 /* ScanCode.KeyG */, 'KeyG', 37 /* KeyCode.KeyG */, 'G', 71, 'VK_G', empty, empty],
            [0, 17 /* ScanCode.KeyH */, 'KeyH', 38 /* KeyCode.KeyH */, 'H', 72, 'VK_H', empty, empty],
            [0, 18 /* ScanCode.KeyI */, 'KeyI', 39 /* KeyCode.KeyI */, 'I', 73, 'VK_I', empty, empty],
            [0, 19 /* ScanCode.KeyJ */, 'KeyJ', 40 /* KeyCode.KeyJ */, 'J', 74, 'VK_J', empty, empty],
            [0, 20 /* ScanCode.KeyK */, 'KeyK', 41 /* KeyCode.KeyK */, 'K', 75, 'VK_K', empty, empty],
            [0, 21 /* ScanCode.KeyL */, 'KeyL', 42 /* KeyCode.KeyL */, 'L', 76, 'VK_L', empty, empty],
            [0, 22 /* ScanCode.KeyM */, 'KeyM', 43 /* KeyCode.KeyM */, 'M', 77, 'VK_M', empty, empty],
            [0, 23 /* ScanCode.KeyN */, 'KeyN', 44 /* KeyCode.KeyN */, 'N', 78, 'VK_N', empty, empty],
            [0, 24 /* ScanCode.KeyO */, 'KeyO', 45 /* KeyCode.KeyO */, 'O', 79, 'VK_O', empty, empty],
            [0, 25 /* ScanCode.KeyP */, 'KeyP', 46 /* KeyCode.KeyP */, 'P', 80, 'VK_P', empty, empty],
            [0, 26 /* ScanCode.KeyQ */, 'KeyQ', 47 /* KeyCode.KeyQ */, 'Q', 81, 'VK_Q', empty, empty],
            [0, 27 /* ScanCode.KeyR */, 'KeyR', 48 /* KeyCode.KeyR */, 'R', 82, 'VK_R', empty, empty],
            [0, 28 /* ScanCode.KeyS */, 'KeyS', 49 /* KeyCode.KeyS */, 'S', 83, 'VK_S', empty, empty],
            [0, 29 /* ScanCode.KeyT */, 'KeyT', 50 /* KeyCode.KeyT */, 'T', 84, 'VK_T', empty, empty],
            [0, 30 /* ScanCode.KeyU */, 'KeyU', 51 /* KeyCode.KeyU */, 'U', 85, 'VK_U', empty, empty],
            [0, 31 /* ScanCode.KeyV */, 'KeyV', 52 /* KeyCode.KeyV */, 'V', 86, 'VK_V', empty, empty],
            [0, 32 /* ScanCode.KeyW */, 'KeyW', 53 /* KeyCode.KeyW */, 'W', 87, 'VK_W', empty, empty],
            [0, 33 /* ScanCode.KeyX */, 'KeyX', 54 /* KeyCode.KeyX */, 'X', 88, 'VK_X', empty, empty],
            [0, 34 /* ScanCode.KeyY */, 'KeyY', 55 /* KeyCode.KeyY */, 'Y', 89, 'VK_Y', empty, empty],
            [0, 35 /* ScanCode.KeyZ */, 'KeyZ', 56 /* KeyCode.KeyZ */, 'Z', 90, 'VK_Z', empty, empty],
            [0, 36 /* ScanCode.Digit1 */, 'Digit1', 22 /* KeyCode.Digit1 */, '1', 49, 'VK_1', empty, empty],
            [0, 37 /* ScanCode.Digit2 */, 'Digit2', 23 /* KeyCode.Digit2 */, '2', 50, 'VK_2', empty, empty],
            [0, 38 /* ScanCode.Digit3 */, 'Digit3', 24 /* KeyCode.Digit3 */, '3', 51, 'VK_3', empty, empty],
            [0, 39 /* ScanCode.Digit4 */, 'Digit4', 25 /* KeyCode.Digit4 */, '4', 52, 'VK_4', empty, empty],
            [0, 40 /* ScanCode.Digit5 */, 'Digit5', 26 /* KeyCode.Digit5 */, '5', 53, 'VK_5', empty, empty],
            [0, 41 /* ScanCode.Digit6 */, 'Digit6', 27 /* KeyCode.Digit6 */, '6', 54, 'VK_6', empty, empty],
            [0, 42 /* ScanCode.Digit7 */, 'Digit7', 28 /* KeyCode.Digit7 */, '7', 55, 'VK_7', empty, empty],
            [0, 43 /* ScanCode.Digit8 */, 'Digit8', 29 /* KeyCode.Digit8 */, '8', 56, 'VK_8', empty, empty],
            [0, 44 /* ScanCode.Digit9 */, 'Digit9', 30 /* KeyCode.Digit9 */, '9', 57, 'VK_9', empty, empty],
            [0, 45 /* ScanCode.Digit0 */, 'Digit0', 21 /* KeyCode.Digit0 */, '0', 48, 'VK_0', empty, empty],
            [1, 46 /* ScanCode.Enter */, 'Enter', 3 /* KeyCode.Enter */, 'Enter', 13, 'VK_RETURN', empty, empty],
            [1, 47 /* ScanCode.Escape */, 'Escape', 9 /* KeyCode.Escape */, 'Escape', 27, 'VK_ESCAPE', empty, empty],
            [1, 48 /* ScanCode.Backspace */, 'Backspace', 1 /* KeyCode.Backspace */, 'Backspace', 8, 'VK_BACK', empty, empty],
            [1, 49 /* ScanCode.Tab */, 'Tab', 2 /* KeyCode.Tab */, 'Tab', 9, 'VK_TAB', empty, empty],
            [1, 50 /* ScanCode.Space */, 'Space', 10 /* KeyCode.Space */, 'Space', 32, 'VK_SPACE', empty, empty],
            [0, 51 /* ScanCode.Minus */, 'Minus', 88 /* KeyCode.Minus */, '-', 189, 'VK_OEM_MINUS', '-', 'OEM_MINUS'],
            [0, 52 /* ScanCode.Equal */, 'Equal', 86 /* KeyCode.Equal */, '=', 187, 'VK_OEM_PLUS', '=', 'OEM_PLUS'],
            [0, 53 /* ScanCode.BracketLeft */, 'BracketLeft', 92 /* KeyCode.BracketLeft */, '[', 219, 'VK_OEM_4', '[', 'OEM_4'],
            [0, 54 /* ScanCode.BracketRight */, 'BracketRight', 94 /* KeyCode.BracketRight */, ']', 221, 'VK_OEM_6', ']', 'OEM_6'],
            [0, 55 /* ScanCode.Backslash */, 'Backslash', 93 /* KeyCode.Backslash */, '\\', 220, 'VK_OEM_5', '\\', 'OEM_5'],
            [0, 56 /* ScanCode.IntlHash */, 'IntlHash', 0 /* KeyCode.Unknown */, empty, 0, empty, empty, empty], // has been dropped from the w3c spec
            [0, 57 /* ScanCode.Semicolon */, 'Semicolon', 85 /* KeyCode.Semicolon */, ';', 186, 'VK_OEM_1', ';', 'OEM_1'],
            [0, 58 /* ScanCode.Quote */, 'Quote', 95 /* KeyCode.Quote */, '\'', 222, 'VK_OEM_7', '\'', 'OEM_7'],
            [0, 59 /* ScanCode.Backquote */, 'Backquote', 91 /* KeyCode.Backquote */, '`', 192, 'VK_OEM_3', '`', 'OEM_3'],
            [0, 60 /* ScanCode.Comma */, 'Comma', 87 /* KeyCode.Comma */, ',', 188, 'VK_OEM_COMMA', ',', 'OEM_COMMA'],
            [0, 61 /* ScanCode.Period */, 'Period', 89 /* KeyCode.Period */, '.', 190, 'VK_OEM_PERIOD', '.', 'OEM_PERIOD'],
            [0, 62 /* ScanCode.Slash */, 'Slash', 90 /* KeyCode.Slash */, '/', 191, 'VK_OEM_2', '/', 'OEM_2'],
            [1, 63 /* ScanCode.CapsLock */, 'CapsLock', 8 /* KeyCode.CapsLock */, 'CapsLock', 20, 'VK_CAPITAL', empty, empty],
            [1, 64 /* ScanCode.F1 */, 'F1', 59 /* KeyCode.F1 */, 'F1', 112, 'VK_F1', empty, empty],
            [1, 65 /* ScanCode.F2 */, 'F2', 60 /* KeyCode.F2 */, 'F2', 113, 'VK_F2', empty, empty],
            [1, 66 /* ScanCode.F3 */, 'F3', 61 /* KeyCode.F3 */, 'F3', 114, 'VK_F3', empty, empty],
            [1, 67 /* ScanCode.F4 */, 'F4', 62 /* KeyCode.F4 */, 'F4', 115, 'VK_F4', empty, empty],
            [1, 68 /* ScanCode.F5 */, 'F5', 63 /* KeyCode.F5 */, 'F5', 116, 'VK_F5', empty, empty],
            [1, 69 /* ScanCode.F6 */, 'F6', 64 /* KeyCode.F6 */, 'F6', 117, 'VK_F6', empty, empty],
            [1, 70 /* ScanCode.F7 */, 'F7', 65 /* KeyCode.F7 */, 'F7', 118, 'VK_F7', empty, empty],
            [1, 71 /* ScanCode.F8 */, 'F8', 66 /* KeyCode.F8 */, 'F8', 119, 'VK_F8', empty, empty],
            [1, 72 /* ScanCode.F9 */, 'F9', 67 /* KeyCode.F9 */, 'F9', 120, 'VK_F9', empty, empty],
            [1, 73 /* ScanCode.F10 */, 'F10', 68 /* KeyCode.F10 */, 'F10', 121, 'VK_F10', empty, empty],
            [1, 74 /* ScanCode.F11 */, 'F11', 69 /* KeyCode.F11 */, 'F11', 122, 'VK_F11', empty, empty],
            [1, 75 /* ScanCode.F12 */, 'F12', 70 /* KeyCode.F12 */, 'F12', 123, 'VK_F12', empty, empty],
            [1, 76 /* ScanCode.PrintScreen */, 'PrintScreen', 0 /* KeyCode.Unknown */, empty, 0, empty, empty, empty],
            [1, 77 /* ScanCode.ScrollLock */, 'ScrollLock', 84 /* KeyCode.ScrollLock */, 'ScrollLock', 145, 'VK_SCROLL', empty, empty],
            [1, 78 /* ScanCode.Pause */, 'Pause', 7 /* KeyCode.PauseBreak */, 'PauseBreak', 19, 'VK_PAUSE', empty, empty],
            [1, 79 /* ScanCode.Insert */, 'Insert', 19 /* KeyCode.Insert */, 'Insert', 45, 'VK_INSERT', empty, empty],
            [1, 80 /* ScanCode.Home */, 'Home', 14 /* KeyCode.Home */, 'Home', 36, 'VK_HOME', empty, empty],
            [1, 81 /* ScanCode.PageUp */, 'PageUp', 11 /* KeyCode.PageUp */, 'PageUp', 33, 'VK_PRIOR', empty, empty],
            [1, 82 /* ScanCode.Delete */, 'Delete', 20 /* KeyCode.Delete */, 'Delete', 46, 'VK_DELETE', empty, empty],
            [1, 83 /* ScanCode.End */, 'End', 13 /* KeyCode.End */, 'End', 35, 'VK_END', empty, empty],
            [1, 84 /* ScanCode.PageDown */, 'PageDown', 12 /* KeyCode.PageDown */, 'PageDown', 34, 'VK_NEXT', empty, empty],
            [1, 85 /* ScanCode.ArrowRight */, 'ArrowRight', 17 /* KeyCode.RightArrow */, 'RightArrow', 39, 'VK_RIGHT', 'Right', empty],
            [1, 86 /* ScanCode.ArrowLeft */, 'ArrowLeft', 15 /* KeyCode.LeftArrow */, 'LeftArrow', 37, 'VK_LEFT', 'Left', empty],
            [1, 87 /* ScanCode.ArrowDown */, 'ArrowDown', 18 /* KeyCode.DownArrow */, 'DownArrow', 40, 'VK_DOWN', 'Down', empty],
            [1, 88 /* ScanCode.ArrowUp */, 'ArrowUp', 16 /* KeyCode.UpArrow */, 'UpArrow', 38, 'VK_UP', 'Up', empty],
            [1, 89 /* ScanCode.NumLock */, 'NumLock', 83 /* KeyCode.NumLock */, 'NumLock', 144, 'VK_NUMLOCK', empty, empty],
            [1, 90 /* ScanCode.NumpadDivide */, 'NumpadDivide', 113 /* KeyCode.NumpadDivide */, 'NumPad_Divide', 111, 'VK_DIVIDE', empty, empty],
            [1, 91 /* ScanCode.NumpadMultiply */, 'NumpadMultiply', 108 /* KeyCode.NumpadMultiply */, 'NumPad_Multiply', 106, 'VK_MULTIPLY', empty, empty],
            [1, 92 /* ScanCode.NumpadSubtract */, 'NumpadSubtract', 111 /* KeyCode.NumpadSubtract */, 'NumPad_Subtract', 109, 'VK_SUBTRACT', empty, empty],
            [1, 93 /* ScanCode.NumpadAdd */, 'NumpadAdd', 109 /* KeyCode.NumpadAdd */, 'NumPad_Add', 107, 'VK_ADD', empty, empty],
            [1, 94 /* ScanCode.NumpadEnter */, 'NumpadEnter', 3 /* KeyCode.Enter */, empty, 0, empty, empty, empty],
            [1, 95 /* ScanCode.Numpad1 */, 'Numpad1', 99 /* KeyCode.Numpad1 */, 'NumPad1', 97, 'VK_NUMPAD1', empty, empty],
            [1, 96 /* ScanCode.Numpad2 */, 'Numpad2', 100 /* KeyCode.Numpad2 */, 'NumPad2', 98, 'VK_NUMPAD2', empty, empty],
            [1, 97 /* ScanCode.Numpad3 */, 'Numpad3', 101 /* KeyCode.Numpad3 */, 'NumPad3', 99, 'VK_NUMPAD3', empty, empty],
            [1, 98 /* ScanCode.Numpad4 */, 'Numpad4', 102 /* KeyCode.Numpad4 */, 'NumPad4', 100, 'VK_NUMPAD4', empty, empty],
            [1, 99 /* ScanCode.Numpad5 */, 'Numpad5', 103 /* KeyCode.Numpad5 */, 'NumPad5', 101, 'VK_NUMPAD5', empty, empty],
            [1, 100 /* ScanCode.Numpad6 */, 'Numpad6', 104 /* KeyCode.Numpad6 */, 'NumPad6', 102, 'VK_NUMPAD6', empty, empty],
            [1, 101 /* ScanCode.Numpad7 */, 'Numpad7', 105 /* KeyCode.Numpad7 */, 'NumPad7', 103, 'VK_NUMPAD7', empty, empty],
            [1, 102 /* ScanCode.Numpad8 */, 'Numpad8', 106 /* KeyCode.Numpad8 */, 'NumPad8', 104, 'VK_NUMPAD8', empty, empty],
            [1, 103 /* ScanCode.Numpad9 */, 'Numpad9', 107 /* KeyCode.Numpad9 */, 'NumPad9', 105, 'VK_NUMPAD9', empty, empty],
            [1, 104 /* ScanCode.Numpad0 */, 'Numpad0', 98 /* KeyCode.Numpad0 */, 'NumPad0', 96, 'VK_NUMPAD0', empty, empty],
            [1, 105 /* ScanCode.NumpadDecimal */, 'NumpadDecimal', 112 /* KeyCode.NumpadDecimal */, 'NumPad_Decimal', 110, 'VK_DECIMAL', empty, empty],
            [0, 106 /* ScanCode.IntlBackslash */, 'IntlBackslash', 97 /* KeyCode.IntlBackslash */, 'OEM_102', 226, 'VK_OEM_102', empty, empty],
            [1, 107 /* ScanCode.ContextMenu */, 'ContextMenu', 58 /* KeyCode.ContextMenu */, 'ContextMenu', 93, empty, empty, empty],
            [1, 108 /* ScanCode.Power */, 'Power', 0 /* KeyCode.Unknown */, empty, 0, empty, empty, empty],
            [1, 109 /* ScanCode.NumpadEqual */, 'NumpadEqual', 0 /* KeyCode.Unknown */, empty, 0, empty, empty, empty],
            [1, 110 /* ScanCode.F13 */, 'F13', 71 /* KeyCode.F13 */, 'F13', 124, 'VK_F13', empty, empty],
            [1, 111 /* ScanCode.F14 */, 'F14', 72 /* KeyCode.F14 */, 'F14', 125, 'VK_F14', empty, empty],
            [1, 112 /* ScanCode.F15 */, 'F15', 73 /* KeyCode.F15 */, 'F15', 126, 'VK_F15', empty, empty],
            [1, 113 /* ScanCode.F16 */, 'F16', 74 /* KeyCode.F16 */, 'F16', 127, 'VK_F16', empty, empty],
            [1, 114 /* ScanCode.F17 */, 'F17', 75 /* KeyCode.F17 */, 'F17', 128, 'VK_F17', empty, empty],
            [1, 115 /* ScanCode.F18 */, 'F18', 76 /* KeyCode.F18 */, 'F18', 129, 'VK_F18', empty, empty],
            [1, 116 /* ScanCode.F19 */, 'F19', 77 /* KeyCode.F19 */, 'F19', 130, 'VK_F19', empty, empty],
            [1, 117 /* ScanCode.F20 */, 'F20', 78 /* KeyCode.F20 */, 'F20', 131, 'VK_F20', empty, empty],
            [1, 118 /* ScanCode.F21 */, 'F21', 79 /* KeyCode.F21 */, 'F21', 132, 'VK_F21', empty, empty],
            [1, 119 /* ScanCode.F22 */, 'F22', 80 /* KeyCode.F22 */, 'F22', 133, 'VK_F22', empty, empty],
            [1, 120 /* ScanCode.F23 */, 'F23', 81 /* KeyCode.F23 */, 'F23', 134, 'VK_F23', empty, empty],
            [1, 121 /* ScanCode.F24 */, 'F24', 82 /* KeyCode.F24 */, 'F24', 135, 'VK_F24', empty, empty],
            [1, 122 /* ScanCode.Open */, 'Open', 0 /* KeyCode.Unknown */, empty, 0, empty, empty, empty],
            [1, 123 /* ScanCode.Help */, 'Help', 0 /* KeyCode.Unknown */, empty, 0, empty, empty, empty],
            [1, 124 /* ScanCode.Select */, 'Select', 0 /* KeyCode.Unknown */, empty, 0, empty, empty, empty],
            [1, 125 /* ScanCode.Again */, 'Again', 0 /* KeyCode.Unknown */, empty, 0, empty, empty, empty],
            [1, 126 /* ScanCode.Undo */, 'Undo', 0 /* KeyCode.Unknown */, empty, 0, empty, empty, empty],
            [1, 127 /* ScanCode.Cut */, 'Cut', 0 /* KeyCode.Unknown */, empty, 0, empty, empty, empty],
            [1, 128 /* ScanCode.Copy */, 'Copy', 0 /* KeyCode.Unknown */, empty, 0, empty, empty, empty],
            [1, 129 /* ScanCode.Paste */, 'Paste', 0 /* KeyCode.Unknown */, empty, 0, empty, empty, empty],
            [1, 130 /* ScanCode.Find */, 'Find', 0 /* KeyCode.Unknown */, empty, 0, empty, empty, empty],
            [1, 131 /* ScanCode.AudioVolumeMute */, 'AudioVolumeMute', 117 /* KeyCode.AudioVolumeMute */, 'AudioVolumeMute', 173, 'VK_VOLUME_MUTE', empty, empty],
            [1, 132 /* ScanCode.AudioVolumeUp */, 'AudioVolumeUp', 118 /* KeyCode.AudioVolumeUp */, 'AudioVolumeUp', 175, 'VK_VOLUME_UP', empty, empty],
            [1, 133 /* ScanCode.AudioVolumeDown */, 'AudioVolumeDown', 119 /* KeyCode.AudioVolumeDown */, 'AudioVolumeDown', 174, 'VK_VOLUME_DOWN', empty, empty],
            [1, 134 /* ScanCode.NumpadComma */, 'NumpadComma', 110 /* KeyCode.NUMPAD_SEPARATOR */, 'NumPad_Separator', 108, 'VK_SEPARATOR', empty, empty],
            [0, 135 /* ScanCode.IntlRo */, 'IntlRo', 115 /* KeyCode.ABNT_C1 */, 'ABNT_C1', 193, 'VK_ABNT_C1', empty, empty],
            [1, 136 /* ScanCode.KanaMode */, 'KanaMode', 0 /* KeyCode.Unknown */, empty, 0, empty, empty, empty],
            [0, 137 /* ScanCode.IntlYen */, 'IntlYen', 0 /* KeyCode.Unknown */, empty, 0, empty, empty, empty],
            [1, 138 /* ScanCode.Convert */, 'Convert', 0 /* KeyCode.Unknown */, empty, 0, empty, empty, empty],
            [1, 139 /* ScanCode.NonConvert */, 'NonConvert', 0 /* KeyCode.Unknown */, empty, 0, empty, empty, empty],
            [1, 140 /* ScanCode.Lang1 */, 'Lang1', 0 /* KeyCode.Unknown */, empty, 0, empty, empty, empty],
            [1, 141 /* ScanCode.Lang2 */, 'Lang2', 0 /* KeyCode.Unknown */, empty, 0, empty, empty, empty],
            [1, 142 /* ScanCode.Lang3 */, 'Lang3', 0 /* KeyCode.Unknown */, empty, 0, empty, empty, empty],
            [1, 143 /* ScanCode.Lang4 */, 'Lang4', 0 /* KeyCode.Unknown */, empty, 0, empty, empty, empty],
            [1, 144 /* ScanCode.Lang5 */, 'Lang5', 0 /* KeyCode.Unknown */, empty, 0, empty, empty, empty],
            [1, 145 /* ScanCode.Abort */, 'Abort', 0 /* KeyCode.Unknown */, empty, 0, empty, empty, empty],
            [1, 146 /* ScanCode.Props */, 'Props', 0 /* KeyCode.Unknown */, empty, 0, empty, empty, empty],
            [1, 147 /* ScanCode.NumpadParenLeft */, 'NumpadParenLeft', 0 /* KeyCode.Unknown */, empty, 0, empty, empty, empty],
            [1, 148 /* ScanCode.NumpadParenRight */, 'NumpadParenRight', 0 /* KeyCode.Unknown */, empty, 0, empty, empty, empty],
            [1, 149 /* ScanCode.NumpadBackspace */, 'NumpadBackspace', 0 /* KeyCode.Unknown */, empty, 0, empty, empty, empty],
            [1, 150 /* ScanCode.NumpadMemoryStore */, 'NumpadMemoryStore', 0 /* KeyCode.Unknown */, empty, 0, empty, empty, empty],
            [1, 151 /* ScanCode.NumpadMemoryRecall */, 'NumpadMemoryRecall', 0 /* KeyCode.Unknown */, empty, 0, empty, empty, empty],
            [1, 152 /* ScanCode.NumpadMemoryClear */, 'NumpadMemoryClear', 0 /* KeyCode.Unknown */, empty, 0, empty, empty, empty],
            [1, 153 /* ScanCode.NumpadMemoryAdd */, 'NumpadMemoryAdd', 0 /* KeyCode.Unknown */, empty, 0, empty, empty, empty],
            [1, 154 /* ScanCode.NumpadMemorySubtract */, 'NumpadMemorySubtract', 0 /* KeyCode.Unknown */, empty, 0, empty, empty, empty],
            [1, 155 /* ScanCode.NumpadClear */, 'NumpadClear', 131 /* KeyCode.Clear */, 'Clear', 12, 'VK_CLEAR', empty, empty],
            [1, 156 /* ScanCode.NumpadClearEntry */, 'NumpadClearEntry', 0 /* KeyCode.Unknown */, empty, 0, empty, empty, empty],
            [1, 0 /* ScanCode.None */, empty, 5 /* KeyCode.Ctrl */, 'Ctrl', 17, 'VK_CONTROL', empty, empty],
            [1, 0 /* ScanCode.None */, empty, 4 /* KeyCode.Shift */, 'Shift', 16, 'VK_SHIFT', empty, empty],
            [1, 0 /* ScanCode.None */, empty, 6 /* KeyCode.Alt */, 'Alt', 18, 'VK_MENU', empty, empty],
            [1, 0 /* ScanCode.None */, empty, 57 /* KeyCode.Meta */, 'Meta', 91, 'VK_COMMAND', empty, empty],
            [1, 157 /* ScanCode.ControlLeft */, 'ControlLeft', 5 /* KeyCode.Ctrl */, empty, 0, 'VK_LCONTROL', empty, empty],
            [1, 158 /* ScanCode.ShiftLeft */, 'ShiftLeft', 4 /* KeyCode.Shift */, empty, 0, 'VK_LSHIFT', empty, empty],
            [1, 159 /* ScanCode.AltLeft */, 'AltLeft', 6 /* KeyCode.Alt */, empty, 0, 'VK_LMENU', empty, empty],
            [1, 160 /* ScanCode.MetaLeft */, 'MetaLeft', 57 /* KeyCode.Meta */, empty, 0, 'VK_LWIN', empty, empty],
            [1, 161 /* ScanCode.ControlRight */, 'ControlRight', 5 /* KeyCode.Ctrl */, empty, 0, 'VK_RCONTROL', empty, empty],
            [1, 162 /* ScanCode.ShiftRight */, 'ShiftRight', 4 /* KeyCode.Shift */, empty, 0, 'VK_RSHIFT', empty, empty],
            [1, 163 /* ScanCode.AltRight */, 'AltRight', 6 /* KeyCode.Alt */, empty, 0, 'VK_RMENU', empty, empty],
            [1, 164 /* ScanCode.MetaRight */, 'MetaRight', 57 /* KeyCode.Meta */, empty, 0, 'VK_RWIN', empty, empty],
            [1, 165 /* ScanCode.BrightnessUp */, 'BrightnessUp', 0 /* KeyCode.Unknown */, empty, 0, empty, empty, empty],
            [1, 166 /* ScanCode.BrightnessDown */, 'BrightnessDown', 0 /* KeyCode.Unknown */, empty, 0, empty, empty, empty],
            [1, 167 /* ScanCode.MediaPlay */, 'MediaPlay', 0 /* KeyCode.Unknown */, empty, 0, empty, empty, empty],
            [1, 168 /* ScanCode.MediaRecord */, 'MediaRecord', 0 /* KeyCode.Unknown */, empty, 0, empty, empty, empty],
            [1, 169 /* ScanCode.MediaFastForward */, 'MediaFastForward', 0 /* KeyCode.Unknown */, empty, 0, empty, empty, empty],
            [1, 170 /* ScanCode.MediaRewind */, 'MediaRewind', 0 /* KeyCode.Unknown */, empty, 0, empty, empty, empty],
            [1, 171 /* ScanCode.MediaTrackNext */, 'MediaTrackNext', 124 /* KeyCode.MediaTrackNext */, 'MediaTrackNext', 176, 'VK_MEDIA_NEXT_TRACK', empty, empty],
            [1, 172 /* ScanCode.MediaTrackPrevious */, 'MediaTrackPrevious', 125 /* KeyCode.MediaTrackPrevious */, 'MediaTrackPrevious', 177, 'VK_MEDIA_PREV_TRACK', empty, empty],
            [1, 173 /* ScanCode.MediaStop */, 'MediaStop', 126 /* KeyCode.MediaStop */, 'MediaStop', 178, 'VK_MEDIA_STOP', empty, empty],
            [1, 174 /* ScanCode.Eject */, 'Eject', 0 /* KeyCode.Unknown */, empty, 0, empty, empty, empty],
            [1, 175 /* ScanCode.MediaPlayPause */, 'MediaPlayPause', 127 /* KeyCode.MediaPlayPause */, 'MediaPlayPause', 179, 'VK_MEDIA_PLAY_PAUSE', empty, empty],
            [1, 176 /* ScanCode.MediaSelect */, 'MediaSelect', 128 /* KeyCode.LaunchMediaPlayer */, 'LaunchMediaPlayer', 181, 'VK_MEDIA_LAUNCH_MEDIA_SELECT', empty, empty],
            [1, 177 /* ScanCode.LaunchMail */, 'LaunchMail', 129 /* KeyCode.LaunchMail */, 'LaunchMail', 180, 'VK_MEDIA_LAUNCH_MAIL', empty, empty],
            [1, 178 /* ScanCode.LaunchApp2 */, 'LaunchApp2', 130 /* KeyCode.LaunchApp2 */, 'LaunchApp2', 183, 'VK_MEDIA_LAUNCH_APP2', empty, empty],
            [1, 179 /* ScanCode.LaunchApp1 */, 'LaunchApp1', 0 /* KeyCode.Unknown */, empty, 0, 'VK_MEDIA_LAUNCH_APP1', empty, empty],
            [1, 180 /* ScanCode.SelectTask */, 'SelectTask', 0 /* KeyCode.Unknown */, empty, 0, empty, empty, empty],
            [1, 181 /* ScanCode.LaunchScreenSaver */, 'LaunchScreenSaver', 0 /* KeyCode.Unknown */, empty, 0, empty, empty, empty],
            [1, 182 /* ScanCode.BrowserSearch */, 'BrowserSearch', 120 /* KeyCode.BrowserSearch */, 'BrowserSearch', 170, 'VK_BROWSER_SEARCH', empty, empty],
            [1, 183 /* ScanCode.BrowserHome */, 'BrowserHome', 121 /* KeyCode.BrowserHome */, 'BrowserHome', 172, 'VK_BROWSER_HOME', empty, empty],
            [1, 184 /* ScanCode.BrowserBack */, 'BrowserBack', 122 /* KeyCode.BrowserBack */, 'BrowserBack', 166, 'VK_BROWSER_BACK', empty, empty],
            [1, 185 /* ScanCode.BrowserForward */, 'BrowserForward', 123 /* KeyCode.BrowserForward */, 'BrowserForward', 167, 'VK_BROWSER_FORWARD', empty, empty],
            [1, 186 /* ScanCode.BrowserStop */, 'BrowserStop', 0 /* KeyCode.Unknown */, empty, 0, 'VK_BROWSER_STOP', empty, empty],
            [1, 187 /* ScanCode.BrowserRefresh */, 'BrowserRefresh', 0 /* KeyCode.Unknown */, empty, 0, 'VK_BROWSER_REFRESH', empty, empty],
            [1, 188 /* ScanCode.BrowserFavorites */, 'BrowserFavorites', 0 /* KeyCode.Unknown */, empty, 0, 'VK_BROWSER_FAVORITES', empty, empty],
            [1, 189 /* ScanCode.ZoomToggle */, 'ZoomToggle', 0 /* KeyCode.Unknown */, empty, 0, empty, empty, empty],
            [1, 190 /* ScanCode.MailReply */, 'MailReply', 0 /* KeyCode.Unknown */, empty, 0, empty, empty, empty],
            [1, 191 /* ScanCode.MailForward */, 'MailForward', 0 /* KeyCode.Unknown */, empty, 0, empty, empty, empty],
            [1, 192 /* ScanCode.MailSend */, 'MailSend', 0 /* KeyCode.Unknown */, empty, 0, empty, empty, empty],
            // See https://lists.w3.org/Archives/Public/www-dom/2010JulSep/att-0182/keyCode-spec.html
            // If an Input Method Editor is processing key input and the event is keydown, return 229.
            [1, 0 /* ScanCode.None */, empty, 114 /* KeyCode.KEY_IN_COMPOSITION */, 'KeyInComposition', 229, empty, empty, empty],
            [1, 0 /* ScanCode.None */, empty, 116 /* KeyCode.ABNT_C2 */, 'ABNT_C2', 194, 'VK_ABNT_C2', empty, empty],
            [1, 0 /* ScanCode.None */, empty, 96 /* KeyCode.OEM_8 */, 'OEM_8', 223, 'VK_OEM_8', empty, empty],
            [1, 0 /* ScanCode.None */, empty, 0 /* KeyCode.Unknown */, empty, 0, 'VK_KANA', empty, empty],
            [1, 0 /* ScanCode.None */, empty, 0 /* KeyCode.Unknown */, empty, 0, 'VK_HANGUL', empty, empty],
            [1, 0 /* ScanCode.None */, empty, 0 /* KeyCode.Unknown */, empty, 0, 'VK_JUNJA', empty, empty],
            [1, 0 /* ScanCode.None */, empty, 0 /* KeyCode.Unknown */, empty, 0, 'VK_FINAL', empty, empty],
            [1, 0 /* ScanCode.None */, empty, 0 /* KeyCode.Unknown */, empty, 0, 'VK_HANJA', empty, empty],
            [1, 0 /* ScanCode.None */, empty, 0 /* KeyCode.Unknown */, empty, 0, 'VK_KANJI', empty, empty],
            [1, 0 /* ScanCode.None */, empty, 0 /* KeyCode.Unknown */, empty, 0, 'VK_CONVERT', empty, empty],
            [1, 0 /* ScanCode.None */, empty, 0 /* KeyCode.Unknown */, empty, 0, 'VK_NONCONVERT', empty, empty],
            [1, 0 /* ScanCode.None */, empty, 0 /* KeyCode.Unknown */, empty, 0, 'VK_ACCEPT', empty, empty],
            [1, 0 /* ScanCode.None */, empty, 0 /* KeyCode.Unknown */, empty, 0, 'VK_MODECHANGE', empty, empty],
            [1, 0 /* ScanCode.None */, empty, 0 /* KeyCode.Unknown */, empty, 0, 'VK_SELECT', empty, empty],
            [1, 0 /* ScanCode.None */, empty, 0 /* KeyCode.Unknown */, empty, 0, 'VK_PRINT', empty, empty],
            [1, 0 /* ScanCode.None */, empty, 0 /* KeyCode.Unknown */, empty, 0, 'VK_EXECUTE', empty, empty],
            [1, 0 /* ScanCode.None */, empty, 0 /* KeyCode.Unknown */, empty, 0, 'VK_SNAPSHOT', empty, empty],
            [1, 0 /* ScanCode.None */, empty, 0 /* KeyCode.Unknown */, empty, 0, 'VK_HELP', empty, empty],
            [1, 0 /* ScanCode.None */, empty, 0 /* KeyCode.Unknown */, empty, 0, 'VK_APPS', empty, empty],
            [1, 0 /* ScanCode.None */, empty, 0 /* KeyCode.Unknown */, empty, 0, 'VK_PROCESSKEY', empty, empty],
            [1, 0 /* ScanCode.None */, empty, 0 /* KeyCode.Unknown */, empty, 0, 'VK_PACKET', empty, empty],
            [1, 0 /* ScanCode.None */, empty, 0 /* KeyCode.Unknown */, empty, 0, 'VK_DBE_SBCSCHAR', empty, empty],
            [1, 0 /* ScanCode.None */, empty, 0 /* KeyCode.Unknown */, empty, 0, 'VK_DBE_DBCSCHAR', empty, empty],
            [1, 0 /* ScanCode.None */, empty, 0 /* KeyCode.Unknown */, empty, 0, 'VK_ATTN', empty, empty],
            [1, 0 /* ScanCode.None */, empty, 0 /* KeyCode.Unknown */, empty, 0, 'VK_CRSEL', empty, empty],
            [1, 0 /* ScanCode.None */, empty, 0 /* KeyCode.Unknown */, empty, 0, 'VK_EXSEL', empty, empty],
            [1, 0 /* ScanCode.None */, empty, 0 /* KeyCode.Unknown */, empty, 0, 'VK_EREOF', empty, empty],
            [1, 0 /* ScanCode.None */, empty, 0 /* KeyCode.Unknown */, empty, 0, 'VK_PLAY', empty, empty],
            [1, 0 /* ScanCode.None */, empty, 0 /* KeyCode.Unknown */, empty, 0, 'VK_ZOOM', empty, empty],
            [1, 0 /* ScanCode.None */, empty, 0 /* KeyCode.Unknown */, empty, 0, 'VK_NONAME', empty, empty],
            [1, 0 /* ScanCode.None */, empty, 0 /* KeyCode.Unknown */, empty, 0, 'VK_PA1', empty, empty],
            [1, 0 /* ScanCode.None */, empty, 0 /* KeyCode.Unknown */, empty, 0, 'VK_OEM_CLEAR', empty, empty],
        ];
        const seenKeyCode = [];
        const seenScanCode = [];
        for (const mapping of mappings) {
            const [immutable, scanCode, scanCodeStr, keyCode, keyCodeStr, eventKeyCode, vkey, usUserSettingsLabel, generalUserSettingsLabel] = mapping;
            if (!seenScanCode[scanCode]) {
                seenScanCode[scanCode] = true;
                scanCodeIntToStr[scanCode] = scanCodeStr;
                scanCodeStrToInt[scanCodeStr] = scanCode;
                scanCodeLowerCaseStrToInt[scanCodeStr.toLowerCase()] = scanCode;
                if (immutable) {
                    exports.IMMUTABLE_CODE_TO_KEY_CODE[scanCode] = keyCode;
                    if ((keyCode !== 0 /* KeyCode.Unknown */)
                        && (keyCode !== 3 /* KeyCode.Enter */)
                        && (keyCode !== 5 /* KeyCode.Ctrl */)
                        && (keyCode !== 4 /* KeyCode.Shift */)
                        && (keyCode !== 6 /* KeyCode.Alt */)
                        && (keyCode !== 57 /* KeyCode.Meta */)) {
                        exports.IMMUTABLE_KEY_CODE_TO_CODE[keyCode] = scanCode;
                    }
                }
            }
            if (!seenKeyCode[keyCode]) {
                seenKeyCode[keyCode] = true;
                if (!keyCodeStr) {
                    throw new Error(`String representation missing for key code ${keyCode} around scan code ${scanCodeStr}`);
                }
                uiMap.define(keyCode, keyCodeStr);
                userSettingsUSMap.define(keyCode, usUserSettingsLabel || keyCodeStr);
                userSettingsGeneralMap.define(keyCode, generalUserSettingsLabel || usUserSettingsLabel || keyCodeStr);
            }
            if (eventKeyCode) {
                exports.EVENT_KEY_CODE_MAP[eventKeyCode] = keyCode;
            }
            if (vkey) {
                exports.NATIVE_WINDOWS_KEY_CODE_TO_KEY_CODE[vkey] = keyCode;
            }
        }
        // Manually added due to the exclusion above (due to duplication with NumpadEnter)
        exports.IMMUTABLE_KEY_CODE_TO_CODE[3 /* KeyCode.Enter */] = 46 /* ScanCode.Enter */;
    })();
    var KeyCodeUtils;
    (function (KeyCodeUtils) {
        function toString(keyCode) {
            return uiMap.keyCodeToStr(keyCode);
        }
        KeyCodeUtils.toString = toString;
        function fromString(key) {
            return uiMap.strToKeyCode(key);
        }
        KeyCodeUtils.fromString = fromString;
        function toUserSettingsUS(keyCode) {
            return userSettingsUSMap.keyCodeToStr(keyCode);
        }
        KeyCodeUtils.toUserSettingsUS = toUserSettingsUS;
        function toUserSettingsGeneral(keyCode) {
            return userSettingsGeneralMap.keyCodeToStr(keyCode);
        }
        KeyCodeUtils.toUserSettingsGeneral = toUserSettingsGeneral;
        function fromUserSettings(key) {
            return userSettingsUSMap.strToKeyCode(key) || userSettingsGeneralMap.strToKeyCode(key);
        }
        KeyCodeUtils.fromUserSettings = fromUserSettings;
        function toElectronAccelerator(keyCode) {
            if (keyCode >= 98 /* KeyCode.Numpad0 */ && keyCode <= 113 /* KeyCode.NumpadDivide */) {
                // [Electron Accelerators] Electron is able to parse numpad keys, but unfortunately it
                // renders them just as regular keys in menus. For example, num0 is rendered as "0",
                // numdiv is rendered as "/", numsub is rendered as "-".
                //
                // This can lead to incredible confusion, as it makes numpad based keybindings indistinguishable
                // from keybindings based on regular keys.
                //
                // We therefore need to fall back to custom rendering for numpad keys.
                return null;
            }
            switch (keyCode) {
                case 16 /* KeyCode.UpArrow */:
                    return 'Up';
                case 18 /* KeyCode.DownArrow */:
                    return 'Down';
                case 15 /* KeyCode.LeftArrow */:
                    return 'Left';
                case 17 /* KeyCode.RightArrow */:
                    return 'Right';
            }
            return uiMap.keyCodeToStr(keyCode);
        }
        KeyCodeUtils.toElectronAccelerator = toElectronAccelerator;
    })(KeyCodeUtils || (exports.KeyCodeUtils = KeyCodeUtils = {}));
    function KeyChord(firstPart, secondPart) {
        const chordPart = ((secondPart & 0x0000FFFF) << 16) >>> 0;
        return (firstPart | chordPart) >>> 0;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[140/*vs/base/common/keybindings*/], __M([1/*require*/,0/*exports*/,8/*vs/base/common/errors*/]), function (require, exports, errors_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ResolvedKeybinding = exports.ResolvedChord = exports.Keybinding = exports.ScanCodeChord = exports.KeyCodeChord = void 0;
    exports.decodeKeybinding = decodeKeybinding;
    exports.createSimpleKeybinding = createSimpleKeybinding;
    function decodeKeybinding(keybinding, OS) {
        if (typeof keybinding === 'number') {
            if (keybinding === 0) {
                return null;
            }
            const firstChord = (keybinding & 0x0000FFFF) >>> 0;
            const secondChord = (keybinding & 0xFFFF0000) >>> 16;
            if (secondChord !== 0) {
                return new Keybinding([
                    createSimpleKeybinding(firstChord, OS),
                    createSimpleKeybinding(secondChord, OS)
                ]);
            }
            return new Keybinding([createSimpleKeybinding(firstChord, OS)]);
        }
        else {
            const chords = [];
            for (let i = 0; i < keybinding.length; i++) {
                chords.push(createSimpleKeybinding(keybinding[i], OS));
            }
            return new Keybinding(chords);
        }
    }
    function createSimpleKeybinding(keybinding, OS) {
        const ctrlCmd = (keybinding & 2048 /* BinaryKeybindingsMask.CtrlCmd */ ? true : false);
        const winCtrl = (keybinding & 256 /* BinaryKeybindingsMask.WinCtrl */ ? true : false);
        const ctrlKey = (OS === 2 /* OperatingSystem.Macintosh */ ? winCtrl : ctrlCmd);
        const shiftKey = (keybinding & 1024 /* BinaryKeybindingsMask.Shift */ ? true : false);
        const altKey = (keybinding & 512 /* BinaryKeybindingsMask.Alt */ ? true : false);
        const metaKey = (OS === 2 /* OperatingSystem.Macintosh */ ? ctrlCmd : winCtrl);
        const keyCode = (keybinding & 255 /* BinaryKeybindingsMask.KeyCode */);
        return new KeyCodeChord(ctrlKey, shiftKey, altKey, metaKey, keyCode);
    }
    /**
     * Represents a chord which uses the `keyCode` field of keyboard events.
     * A chord is a combination of keys pressed simultaneously.
     */
    class KeyCodeChord {
        constructor(ctrlKey, shiftKey, altKey, metaKey, keyCode) {
            this.ctrlKey = ctrlKey;
            this.shiftKey = shiftKey;
            this.altKey = altKey;
            this.metaKey = metaKey;
            this.keyCode = keyCode;
        }
        equals(other) {
            return (other instanceof KeyCodeChord
                && this.ctrlKey === other.ctrlKey
                && this.shiftKey === other.shiftKey
                && this.altKey === other.altKey
                && this.metaKey === other.metaKey
                && this.keyCode === other.keyCode);
        }
        isModifierKey() {
            return (this.keyCode === 0 /* KeyCode.Unknown */
                || this.keyCode === 5 /* KeyCode.Ctrl */
                || this.keyCode === 57 /* KeyCode.Meta */
                || this.keyCode === 6 /* KeyCode.Alt */
                || this.keyCode === 4 /* KeyCode.Shift */);
        }
        /**
         * Does this keybinding refer to the key code of a modifier and it also has the modifier flag?
         */
        isDuplicateModifierCase() {
            return ((this.ctrlKey && this.keyCode === 5 /* KeyCode.Ctrl */)
                || (this.shiftKey && this.keyCode === 4 /* KeyCode.Shift */)
                || (this.altKey && this.keyCode === 6 /* KeyCode.Alt */)
                || (this.metaKey && this.keyCode === 57 /* KeyCode.Meta */));
        }
    }
    exports.KeyCodeChord = KeyCodeChord;
    /**
     * Represents a chord which uses the `code` field of keyboard events.
     * A chord is a combination of keys pressed simultaneously.
     */
    class ScanCodeChord {
        constructor(ctrlKey, shiftKey, altKey, metaKey, scanCode) {
            this.ctrlKey = ctrlKey;
            this.shiftKey = shiftKey;
            this.altKey = altKey;
            this.metaKey = metaKey;
            this.scanCode = scanCode;
        }
        /**
         * Does this keybinding refer to the key code of a modifier and it also has the modifier flag?
         */
        isDuplicateModifierCase() {
            return ((this.ctrlKey && (this.scanCode === 157 /* ScanCode.ControlLeft */ || this.scanCode === 161 /* ScanCode.ControlRight */))
                || (this.shiftKey && (this.scanCode === 158 /* ScanCode.ShiftLeft */ || this.scanCode === 162 /* ScanCode.ShiftRight */))
                || (this.altKey && (this.scanCode === 159 /* ScanCode.AltLeft */ || this.scanCode === 163 /* ScanCode.AltRight */))
                || (this.metaKey && (this.scanCode === 160 /* ScanCode.MetaLeft */ || this.scanCode === 164 /* ScanCode.MetaRight */)));
        }
    }
    exports.ScanCodeChord = ScanCodeChord;
    /**
     * A keybinding is a sequence of chords.
     */
    class Keybinding {
        constructor(chords) {
            if (chords.length === 0) {
                throw (0, errors_1.illegalArgument)(`chords`);
            }
            this.chords = chords;
        }
    }
    exports.Keybinding = Keybinding;
    class ResolvedChord {
        constructor(ctrlKey, shiftKey, altKey, metaKey, keyLabel, keyAriaLabel) {
            this.ctrlKey = ctrlKey;
            this.shiftKey = shiftKey;
            this.altKey = altKey;
            this.metaKey = metaKey;
            this.keyLabel = keyLabel;
            this.keyAriaLabel = keyAriaLabel;
        }
    }
    exports.ResolvedChord = ResolvedChord;
    /**
     * A resolved keybinding. Consists of one or multiple chords.
     */
    class ResolvedKeybinding {
    }
    exports.ResolvedKeybinding = ResolvedKeybinding;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[98/*vs/base/common/lazy*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Lazy = void 0;
    class Lazy {
        constructor(executor) {
            this.executor = executor;
            this._didRun = false;
        }
        /**
         * Get the wrapped value.
         *
         * This will force evaluation of the lazy value if it has not been resolved yet. Lazy values are only
         * resolved once. `getValue` will re-throw exceptions that are hit while resolving the value
         */
        get value() {
            if (!this._didRun) {
                try {
                    this._value = this.executor();
                }
                catch (err) {
                    this._error = err;
                }
                finally {
                    this._didRun = true;
                }
            }
            if (this._error) {
                throw this._error;
            }
            return this._value;
        }
        /**
         * Get the wrapped value without forcing evaluation.
         */
        get rawValue() { return this._value; }
    }
    exports.Lazy = Lazy;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[44/*vs/base/browser/ui/hover/hoverDelegateFactory*/], __M([1/*require*/,0/*exports*/,98/*vs/base/common/lazy*/]), function (require, exports, lazy_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.setHoverDelegateFactory = setHoverDelegateFactory;
    exports.getDefaultHoverDelegate = getDefaultHoverDelegate;
    exports.createInstantHoverDelegate = createInstantHoverDelegate;
    const nullHoverDelegateFactory = () => ({
        get delay() { return -1; },
        dispose: () => { },
        showHover: () => { return undefined; },
    });
    let hoverDelegateFactory = nullHoverDelegateFactory;
    const defaultHoverDelegateMouse = new lazy_1.Lazy(() => hoverDelegateFactory('mouse', false));
    const defaultHoverDelegateElement = new lazy_1.Lazy(() => hoverDelegateFactory('element', false));
    // TODO: Remove when getDefaultHoverDelegate is no longer used
    function setHoverDelegateFactory(hoverDelegateProvider) {
        hoverDelegateFactory = hoverDelegateProvider;
    }
    // TODO: Refine type for use in new IHoverService interface
    function getDefaultHoverDelegate(placement) {
        if (placement === 'element') {
            return defaultHoverDelegateElement.value;
        }
        return defaultHoverDelegateMouse.value;
    }
    // TODO: Create equivalent in IHoverService
    function createInstantHoverDelegate() {
        // Creates a hover delegate with instant hover enabled.
        // This hover belongs to the consumer and requires the them to dispose it.
        // Instant hover only makes sense for 'element' placement.
        return hoverDelegateFactory('element', true);
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[160/*vs/base/common/buffer*/], __M([1/*require*/,0/*exports*/,98/*vs/base/common/lazy*/]), function (require, exports, lazy_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.VSBuffer = void 0;
    exports.readUInt16LE = readUInt16LE;
    exports.writeUInt16LE = writeUInt16LE;
    exports.readUInt32BE = readUInt32BE;
    exports.writeUInt32BE = writeUInt32BE;
    exports.readUInt8 = readUInt8;
    exports.writeUInt8 = writeUInt8;
    const hasBuffer = (typeof Buffer !== 'undefined');
    const indexOfTable = new lazy_1.Lazy(() => new Uint8Array(256));
    let textDecoder;
    class VSBuffer {
        /**
         * When running in a nodejs context, if `actual` is not a nodejs Buffer, the backing store for
         * the returned `VSBuffer` instance might use a nodejs Buffer allocated from node's Buffer pool,
         * which is not transferrable.
         */
        static wrap(actual) {
            if (hasBuffer && !(Buffer.isBuffer(actual))) {
                // https://nodejs.org/dist/latest-v10.x/docs/api/buffer.html#buffer_class_method_buffer_from_arraybuffer_byteoffset_length
                // Create a zero-copy Buffer wrapper around the ArrayBuffer pointed to by the Uint8Array
                actual = Buffer.from(actual.buffer, actual.byteOffset, actual.byteLength);
            }
            return new VSBuffer(actual);
        }
        constructor(buffer) {
            this.buffer = buffer;
            this.byteLength = this.buffer.byteLength;
        }
        toString() {
            if (hasBuffer) {
                return this.buffer.toString();
            }
            else {
                if (!textDecoder) {
                    textDecoder = new TextDecoder();
                }
                return textDecoder.decode(this.buffer);
            }
        }
    }
    exports.VSBuffer = VSBuffer;
    function readUInt16LE(source, offset) {
        return (((source[offset + 0] << 0) >>> 0) |
            ((source[offset + 1] << 8) >>> 0));
    }
    function writeUInt16LE(destination, value, offset) {
        destination[offset + 0] = (value & 0b11111111);
        value = value >>> 8;
        destination[offset + 1] = (value & 0b11111111);
    }
    function readUInt32BE(source, offset) {
        return (source[offset] * 2 ** 24
            + source[offset + 1] * 2 ** 16
            + source[offset + 2] * 2 ** 8
            + source[offset + 3]);
    }
    function writeUInt32BE(destination, value, offset) {
        destination[offset + 3] = value;
        value = value >>> 8;
        destination[offset + 2] = value;
        value = value >>> 8;
        destination[offset + 1] = value;
        value = value >>> 8;
        destination[offset] = value;
    }
    function readUInt8(source, offset) {
        return source[offset];
    }
    function writeUInt8(destination, value, offset) {
        destination[offset] = value;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[445/*vs/base/common/comparers*/], __M([1/*require*/,0/*exports*/,98/*vs/base/common/lazy*/]), function (require, exports, lazy_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.compareFileNames = compareFileNames;
    exports.compareAnything = compareAnything;
    exports.compareByPrefix = compareByPrefix;
    // When comparing large numbers of strings it's better for performance to create an
    // Intl.Collator object and use the function provided by its compare property
    // than it is to use String.prototype.localeCompare()
    // A collator with numeric sorting enabled, and no sensitivity to case, accents or diacritics.
    const intlFileNameCollatorBaseNumeric = new lazy_1.Lazy(() => {
        const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' });
        return {
            collator,
            collatorIsNumeric: collator.resolvedOptions().numeric
        };
    });
    // A collator with numeric sorting enabled.
    const intlFileNameCollatorNumeric = new lazy_1.Lazy(() => {
        const collator = new Intl.Collator(undefined, { numeric: true });
        return {
            collator
        };
    });
    // A collator with numeric sorting enabled, and sensitivity to accents and diacritics but not case.
    const intlFileNameCollatorNumericCaseInsensitive = new lazy_1.Lazy(() => {
        const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'accent' });
        return {
            collator
        };
    });
    /** Compares filenames without distinguishing the name from the extension. Disambiguates by unicode comparison. */
    function compareFileNames(one, other, caseSensitive = false) {
        const a = one || '';
        const b = other || '';
        const result = intlFileNameCollatorBaseNumeric.value.collator.compare(a, b);
        // Using the numeric option will make compare(`foo1`, `foo01`) === 0. Disambiguate.
        if (intlFileNameCollatorBaseNumeric.value.collatorIsNumeric && result === 0 && a !== b) {
            return a < b ? -1 : 1;
        }
        return result;
    }
    function compareAnything(one, other, lookFor) {
        const elementAName = one.toLowerCase();
        const elementBName = other.toLowerCase();
        // Sort prefix matches over non prefix matches
        const prefixCompare = compareByPrefix(one, other, lookFor);
        if (prefixCompare) {
            return prefixCompare;
        }
        // Sort suffix matches over non suffix matches
        const elementASuffixMatch = elementAName.endsWith(lookFor);
        const elementBSuffixMatch = elementBName.endsWith(lookFor);
        if (elementASuffixMatch !== elementBSuffixMatch) {
            return elementASuffixMatch ? -1 : 1;
        }
        // Understand file names
        const r = compareFileNames(elementAName, elementBName);
        if (r !== 0) {
            return r;
        }
        // Compare by name
        return elementAName.localeCompare(elementBName);
    }
    function compareByPrefix(one, other, lookFor) {
        const elementAName = one.toLowerCase();
        const elementBName = other.toLowerCase();
        // Sort prefix matches over non prefix matches
        const elementAPrefixMatch = elementAName.startsWith(lookFor);
        const elementBPrefixMatch = elementBName.startsWith(lookFor);
        if (elementAPrefixMatch !== elementBPrefixMatch) {
            return elementAPrefixMatch ? -1 : 1;
        }
        // Same prefix: Sort shorter matches to the top to have those on top that match more precisely
        else if (elementAPrefixMatch && elementBPrefixMatch) {
            if (elementAName.length < elementBName.length) {
                return -1;
            }
            if (elementAName.length > elementBName.length) {
                return 1;
            }
        }
        return 0;
    }
});

define(__m[2/*vs/base/common/lifecycle*/], __M([1/*require*/,0/*exports*/,127/*vs/base/common/functional*/,53/*vs/base/common/iterator*/]), function (require, exports, functional_1, iterator_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DisposableMap = exports.ImmortalReference = exports.RefCountedDisposable = exports.MutableDisposable = exports.Disposable = exports.DisposableStore = void 0;
    exports.setDisposableTracker = setDisposableTracker;
    exports.trackDisposable = trackDisposable;
    exports.markAsDisposed = markAsDisposed;
    exports.markAsSingleton = markAsSingleton;
    exports.isDisposable = isDisposable;
    exports.dispose = dispose;
    exports.combinedDisposable = combinedDisposable;
    exports.toDisposable = toDisposable;
    // #region Disposable Tracking
    /**
     * Enables logging of potentially leaked disposables.
     *
     * A disposable is considered leaked if it is not disposed or not registered as the child of
     * another disposable. This tracking is very simple an only works for classes that either
     * extend Disposable or use a DisposableStore. This means there are a lot of false positives.
     */
    const TRACK_DISPOSABLES = false;
    let disposableTracker = null;
    function setDisposableTracker(tracker) {
        disposableTracker = tracker;
    }
    if (TRACK_DISPOSABLES) {
        const __is_disposable_tracked__ = '__is_disposable_tracked__';
        setDisposableTracker(new class {
            trackDisposable(x) {
                const stack = new Error('Potentially leaked disposable').stack;
                setTimeout(() => {
                    if (!x[__is_disposable_tracked__]) {
                        console.log(stack);
                    }
                }, 3000);
            }
            setParent(child, parent) {
                if (child && child !== Disposable.None) {
                    try {
                        child[__is_disposable_tracked__] = true;
                    }
                    catch {
                        // noop
                    }
                }
            }
            markAsDisposed(disposable) {
                if (disposable && disposable !== Disposable.None) {
                    try {
                        disposable[__is_disposable_tracked__] = true;
                    }
                    catch {
                        // noop
                    }
                }
            }
            markAsSingleton(disposable) { }
        });
    }
    function trackDisposable(x) {
        disposableTracker?.trackDisposable(x);
        return x;
    }
    function markAsDisposed(disposable) {
        disposableTracker?.markAsDisposed(disposable);
    }
    function setParentOfDisposable(child, parent) {
        disposableTracker?.setParent(child, parent);
    }
    function setParentOfDisposables(children, parent) {
        if (!disposableTracker) {
            return;
        }
        for (const child of children) {
            disposableTracker.setParent(child, parent);
        }
    }
    /**
     * Indicates that the given object is a singleton which does not need to be disposed.
    */
    function markAsSingleton(singleton) {
        disposableTracker?.markAsSingleton(singleton);
        return singleton;
    }
    /**
     * Check if `thing` is {@link IDisposable disposable}.
     */
    function isDisposable(thing) {
        return typeof thing === 'object' && thing !== null && typeof thing.dispose === 'function' && thing.dispose.length === 0;
    }
    function dispose(arg) {
        if (iterator_1.Iterable.is(arg)) {
            const errors = [];
            for (const d of arg) {
                if (d) {
                    try {
                        d.dispose();
                    }
                    catch (e) {
                        errors.push(e);
                    }
                }
            }
            if (errors.length === 1) {
                throw errors[0];
            }
            else if (errors.length > 1) {
                throw new AggregateError(errors, 'Encountered errors while disposing of store');
            }
            return Array.isArray(arg) ? [] : arg;
        }
        else if (arg) {
            arg.dispose();
            return arg;
        }
    }
    /**
     * Combine multiple disposable values into a single {@link IDisposable}.
     */
    function combinedDisposable(...disposables) {
        const parent = toDisposable(() => dispose(disposables));
        setParentOfDisposables(disposables, parent);
        return parent;
    }
    /**
     * Turn a function that implements dispose into an {@link IDisposable}.
     *
     * @param fn Clean up function, guaranteed to be called only **once**.
     */
    function toDisposable(fn) {
        const self = trackDisposable({
            dispose: (0, functional_1.createSingleCallFunction)(() => {
                markAsDisposed(self);
                fn();
            })
        });
        return self;
    }
    /**
     * Manages a collection of disposable values.
     *
     * This is the preferred way to manage multiple disposables. A `DisposableStore` is safer to work with than an
     * `IDisposable[]` as it considers edge cases, such as registering the same value multiple times or adding an item to a
     * store that has already been disposed of.
     */
    class DisposableStore {
        static { this.DISABLE_DISPOSED_WARNING = false; }
        constructor() {
            this._toDispose = new Set();
            this._isDisposed = false;
            trackDisposable(this);
        }
        /**
         * Dispose of all registered disposables and mark this object as disposed.
         *
         * Any future disposables added to this object will be disposed of on `add`.
         */
        dispose() {
            if (this._isDisposed) {
                return;
            }
            markAsDisposed(this);
            this._isDisposed = true;
            this.clear();
        }
        /**
         * @return `true` if this object has been disposed of.
         */
        get isDisposed() {
            return this._isDisposed;
        }
        /**
         * Dispose of all registered disposables but do not mark this object as disposed.
         */
        clear() {
            if (this._toDispose.size === 0) {
                return;
            }
            try {
                dispose(this._toDispose);
            }
            finally {
                this._toDispose.clear();
            }
        }
        /**
         * Add a new {@link IDisposable disposable} to the collection.
         */
        add(o) {
            if (!o) {
                return o;
            }
            if (o === this) {
                throw new Error('Cannot register a disposable on itself!');
            }
            setParentOfDisposable(o, this);
            if (this._isDisposed) {
                if (!DisposableStore.DISABLE_DISPOSED_WARNING) {
                    console.warn(new Error('Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!').stack);
                }
            }
            else {
                this._toDispose.add(o);
            }
            return o;
        }
        /**
         * Deletes the value from the store, but does not dispose it.
         */
        deleteAndLeak(o) {
            if (!o) {
                return;
            }
            if (this._toDispose.has(o)) {
                this._toDispose.delete(o);
                setParentOfDisposable(o, null);
            }
        }
    }
    exports.DisposableStore = DisposableStore;
    /**
     * Abstract base class for a {@link IDisposable disposable} object.
     *
     * Subclasses can {@linkcode _register} disposables that will be automatically cleaned up when this object is disposed of.
     */
    class Disposable {
        /**
         * A disposable that does nothing when it is disposed of.
         *
         * TODO: This should not be a static property.
         */
        static { this.None = Object.freeze({ dispose() { } }); }
        constructor() {
            this._store = new DisposableStore();
            trackDisposable(this);
            setParentOfDisposable(this._store, this);
        }
        dispose() {
            markAsDisposed(this);
            this._store.dispose();
        }
        /**
         * Adds `o` to the collection of disposables managed by this object.
         */
        _register(o) {
            if (o === this) {
                throw new Error('Cannot register a disposable on itself!');
            }
            return this._store.add(o);
        }
    }
    exports.Disposable = Disposable;
    /**
     * Manages the lifecycle of a disposable value that may be changed.
     *
     * This ensures that when the disposable value is changed, the previously held disposable is disposed of. You can
     * also register a `MutableDisposable` on a `Disposable` to ensure it is automatically cleaned up.
     */
    class MutableDisposable {
        constructor() {
            this._isDisposed = false;
            trackDisposable(this);
        }
        get value() {
            return this._isDisposed ? undefined : this._value;
        }
        set value(value) {
            if (this._isDisposed || value === this._value) {
                return;
            }
            this._value?.dispose();
            if (value) {
                setParentOfDisposable(value, this);
            }
            this._value = value;
        }
        /**
         * Resets the stored value and disposed of the previously stored value.
         */
        clear() {
            this.value = undefined;
        }
        dispose() {
            this._isDisposed = true;
            markAsDisposed(this);
            this._value?.dispose();
            this._value = undefined;
        }
    }
    exports.MutableDisposable = MutableDisposable;
    class RefCountedDisposable {
        constructor(_disposable) {
            this._disposable = _disposable;
            this._counter = 1;
        }
        acquire() {
            this._counter++;
            return this;
        }
        release() {
            if (--this._counter === 0) {
                this._disposable.dispose();
            }
            return this;
        }
    }
    exports.RefCountedDisposable = RefCountedDisposable;
    class ImmortalReference {
        constructor(object) {
            this.object = object;
        }
        dispose() { }
    }
    exports.ImmortalReference = ImmortalReference;
    /**
     * A map the manages the lifecycle of the values that it stores.
     */
    class DisposableMap {
        constructor() {
            this._store = new Map();
            this._isDisposed = false;
            trackDisposable(this);
        }
        /**
         * Disposes of all stored values and mark this object as disposed.
         *
         * Trying to use this object after it has been disposed of is an error.
         */
        dispose() {
            markAsDisposed(this);
            this._isDisposed = true;
            this.clearAndDisposeAll();
        }
        /**
         * Disposes of all stored values and clear the map, but DO NOT mark this object as disposed.
         */
        clearAndDisposeAll() {
            if (!this._store.size) {
                return;
            }
            try {
                dispose(this._store.values());
            }
            finally {
                this._store.clear();
            }
        }
        get(key) {
            return this._store.get(key);
        }
        set(key, value, skipDisposeOnOverwrite = false) {
            if (this._isDisposed) {
                console.warn(new Error('Trying to add a disposable to a DisposableMap that has already been disposed of. The added object will be leaked!').stack);
            }
            if (!skipDisposeOnOverwrite) {
                this._store.get(key)?.dispose();
            }
            this._store.set(key, value);
        }
        /**
         * Delete the value stored for `key` from this map and also dispose of it.
         */
        deleteAndDispose(key) {
            this._store.get(key)?.dispose();
            this._store.delete(key);
        }
        [Symbol.iterator]() {
            return this._store[Symbol.iterator]();
        }
    }
    exports.DisposableMap = DisposableMap;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[73/*vs/base/common/linkedList*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.LinkedList = void 0;
    class Node {
        static { this.Undefined = new Node(undefined); }
        constructor(element) {
            this.element = element;
            this.next = Node.Undefined;
            this.prev = Node.Undefined;
        }
    }
    class LinkedList {
        constructor() {
            this._first = Node.Undefined;
            this._last = Node.Undefined;
            this._size = 0;
        }
        get size() {
            return this._size;
        }
        isEmpty() {
            return this._first === Node.Undefined;
        }
        clear() {
            let node = this._first;
            while (node !== Node.Undefined) {
                const next = node.next;
                node.prev = Node.Undefined;
                node.next = Node.Undefined;
                node = next;
            }
            this._first = Node.Undefined;
            this._last = Node.Undefined;
            this._size = 0;
        }
        unshift(element) {
            return this._insert(element, false);
        }
        push(element) {
            return this._insert(element, true);
        }
        _insert(element, atTheEnd) {
            const newNode = new Node(element);
            if (this._first === Node.Undefined) {
                this._first = newNode;
                this._last = newNode;
            }
            else if (atTheEnd) {
                // push
                const oldLast = this._last;
                this._last = newNode;
                newNode.prev = oldLast;
                oldLast.next = newNode;
            }
            else {
                // unshift
                const oldFirst = this._first;
                this._first = newNode;
                newNode.next = oldFirst;
                oldFirst.prev = newNode;
            }
            this._size += 1;
            let didRemove = false;
            return () => {
                if (!didRemove) {
                    didRemove = true;
                    this._remove(newNode);
                }
            };
        }
        shift() {
            if (this._first === Node.Undefined) {
                return undefined;
            }
            else {
                const res = this._first.element;
                this._remove(this._first);
                return res;
            }
        }
        pop() {
            if (this._last === Node.Undefined) {
                return undefined;
            }
            else {
                const res = this._last.element;
                this._remove(this._last);
                return res;
            }
        }
        _remove(node) {
            if (node.prev !== Node.Undefined && node.next !== Node.Undefined) {
                // middle
                const anchor = node.prev;
                anchor.next = node.next;
                node.next.prev = anchor;
            }
            else if (node.prev === Node.Undefined && node.next === Node.Undefined) {
                // only node
                this._first = Node.Undefined;
                this._last = Node.Undefined;
            }
            else if (node.next === Node.Undefined) {
                // last
                this._last = this._last.prev;
                this._last.next = Node.Undefined;
            }
            else if (node.prev === Node.Undefined) {
                // first
                this._first = this._first.next;
                this._first.prev = Node.Undefined;
            }
            // done
            this._size -= 1;
        }
        *[Symbol.iterator]() {
            let node = this._first;
            while (node !== Node.Undefined) {
                yield node.element;
                node = node.next;
            }
        }
    }
    exports.LinkedList = LinkedList;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    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;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
define(__m[446/*vs/base/common/linkedText*/], __M([1/*require*/,0/*exports*/,126/*vs/base/common/decorators*/]), function (require, exports, decorators_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.LinkedText = void 0;
    exports.parseLinkedText = parseLinkedText;
    class LinkedText {
        constructor(nodes) {
            this.nodes = nodes;
        }
        toString() {
            return this.nodes.map(node => typeof node === 'string' ? node : node.label).join('');
        }
    }
    exports.LinkedText = LinkedText;
    __decorate([
        decorators_1.memoize
    ], LinkedText.prototype, "toString", null);
    const LINK_REGEX = /\[([^\]]+)\]\(((?:https?:\/\/|command:|file:)[^\)\s]+)(?: (["'])(.+?)(\3))?\)/gi;
    function parseLinkedText(text) {
        const result = [];
        let index = 0;
        let match;
        while (match = LINK_REGEX.exec(text)) {
            if (match.index - index > 0) {
                result.push(text.substring(index, match.index));
            }
            const [, label, href, , title] = match;
            if (title) {
                result.push({ label, href, title });
            }
            else {
                result.push({ label, href });
            }
            index = match.index + match[0].length;
        }
        if (index < text.length) {
            result.push(text.substring(index));
        }
        return new LinkedText(result);
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[45/*vs/base/common/map*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    var _a, _b;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SetMap = exports.BidirectionalMap = exports.LRUCache = exports.LinkedMap = exports.ResourceMap = void 0;
    class ResourceMapEntry {
        constructor(uri, value) {
            this.uri = uri;
            this.value = value;
        }
    }
    function isEntries(arg) {
        return Array.isArray(arg);
    }
    class ResourceMap {
        static { this.defaultToKey = (resource) => resource.toString(); }
        constructor(arg, toKey) {
            this[_a] = 'ResourceMap';
            if (arg instanceof ResourceMap) {
                this.map = new Map(arg.map);
                this.toKey = toKey ?? ResourceMap.defaultToKey;
            }
            else if (isEntries(arg)) {
                this.map = new Map();
                this.toKey = toKey ?? ResourceMap.defaultToKey;
                for (const [resource, value] of arg) {
                    this.set(resource, value);
                }
            }
            else {
                this.map = new Map();
                this.toKey = arg ?? ResourceMap.defaultToKey;
            }
        }
        set(resource, value) {
            this.map.set(this.toKey(resource), new ResourceMapEntry(resource, value));
            return this;
        }
        get(resource) {
            return this.map.get(this.toKey(resource))?.value;
        }
        has(resource) {
            return this.map.has(this.toKey(resource));
        }
        get size() {
            return this.map.size;
        }
        clear() {
            this.map.clear();
        }
        delete(resource) {
            return this.map.delete(this.toKey(resource));
        }
        forEach(clb, thisArg) {
            if (typeof thisArg !== 'undefined') {
                clb = clb.bind(thisArg);
            }
            for (const [_, entry] of this.map) {
                clb(entry.value, entry.uri, this);
            }
        }
        *values() {
            for (const entry of this.map.values()) {
                yield entry.value;
            }
        }
        *keys() {
            for (const entry of this.map.values()) {
                yield entry.uri;
            }
        }
        *entries() {
            for (const entry of this.map.values()) {
                yield [entry.uri, entry.value];
            }
        }
        *[(_a = Symbol.toStringTag, Symbol.iterator)]() {
            for (const [, entry] of this.map) {
                yield [entry.uri, entry.value];
            }
        }
    }
    exports.ResourceMap = ResourceMap;
    class LinkedMap {
        constructor() {
            this[_b] = 'LinkedMap';
            this._map = new Map();
            this._head = undefined;
            this._tail = undefined;
            this._size = 0;
            this._state = 0;
        }
        clear() {
            this._map.clear();
            this._head = undefined;
            this._tail = undefined;
            this._size = 0;
            this._state++;
        }
        isEmpty() {
            return !this._head && !this._tail;
        }
        get size() {
            return this._size;
        }
        get first() {
            return this._head?.value;
        }
        get last() {
            return this._tail?.value;
        }
        has(key) {
            return this._map.has(key);
        }
        get(key, touch = 0 /* Touch.None */) {
            const item = this._map.get(key);
            if (!item) {
                return undefined;
            }
            if (touch !== 0 /* Touch.None */) {
                this.touch(item, touch);
            }
            return item.value;
        }
        set(key, value, touch = 0 /* Touch.None */) {
            let item = this._map.get(key);
            if (item) {
                item.value = value;
                if (touch !== 0 /* Touch.None */) {
                    this.touch(item, touch);
                }
            }
            else {
                item = { key, value, next: undefined, previous: undefined };
                switch (touch) {
                    case 0 /* Touch.None */:
                        this.addItemLast(item);
                        break;
                    case 1 /* Touch.AsOld */:
                        this.addItemFirst(item);
                        break;
                    case 2 /* Touch.AsNew */:
                        this.addItemLast(item);
                        break;
                    default:
                        this.addItemLast(item);
                        break;
                }
                this._map.set(key, item);
                this._size++;
            }
            return this;
        }
        delete(key) {
            return !!this.remove(key);
        }
        remove(key) {
            const item = this._map.get(key);
            if (!item) {
                return undefined;
            }
            this._map.delete(key);
            this.removeItem(item);
            this._size--;
            return item.value;
        }
        shift() {
            if (!this._head && !this._tail) {
                return undefined;
            }
            if (!this._head || !this._tail) {
                throw new Error('Invalid list');
            }
            const item = this._head;
            this._map.delete(item.key);
            this.removeItem(item);
            this._size--;
            return item.value;
        }
        forEach(callbackfn, thisArg) {
            const state = this._state;
            let current = this._head;
            while (current) {
                if (thisArg) {
                    callbackfn.bind(thisArg)(current.value, current.key, this);
                }
                else {
                    callbackfn(current.value, current.key, this);
                }
                if (this._state !== state) {
                    throw new Error(`LinkedMap got modified during iteration.`);
                }
                current = current.next;
            }
        }
        keys() {
            const map = this;
            const state = this._state;
            let current = this._head;
            const iterator = {
                [Symbol.iterator]() {
                    return iterator;
                },
                next() {
                    if (map._state !== state) {
                        throw new Error(`LinkedMap got modified during iteration.`);
                    }
                    if (current) {
                        const result = { value: current.key, done: false };
                        current = current.next;
                        return result;
                    }
                    else {
                        return { value: undefined, done: true };
                    }
                }
            };
            return iterator;
        }
        values() {
            const map = this;
            const state = this._state;
            let current = this._head;
            const iterator = {
                [Symbol.iterator]() {
                    return iterator;
                },
                next() {
                    if (map._state !== state) {
                        throw new Error(`LinkedMap got modified during iteration.`);
                    }
                    if (current) {
                        const result = { value: current.value, done: false };
                        current = current.next;
                        return result;
                    }
                    else {
                        return { value: undefined, done: true };
                    }
                }
            };
            return iterator;
        }
        entries() {
            const map = this;
            const state = this._state;
            let current = this._head;
            const iterator = {
                [Symbol.iterator]() {
                    return iterator;
                },
                next() {
                    if (map._state !== state) {
                        throw new Error(`LinkedMap got modified during iteration.`);
                    }
                    if (current) {
                        const result = { value: [current.key, current.value], done: false };
                        current = current.next;
                        return result;
                    }
                    else {
                        return { value: undefined, done: true };
                    }
                }
            };
            return iterator;
        }
        [(_b = Symbol.toStringTag, Symbol.iterator)]() {
            return this.entries();
        }
        trimOld(newSize) {
            if (newSize >= this.size) {
                return;
            }
            if (newSize === 0) {
                this.clear();
                return;
            }
            let current = this._head;
            let currentSize = this.size;
            while (current && currentSize > newSize) {
                this._map.delete(current.key);
                current = current.next;
                currentSize--;
            }
            this._head = current;
            this._size = currentSize;
            if (current) {
                current.previous = undefined;
            }
            this._state++;
        }
        trimNew(newSize) {
            if (newSize >= this.size) {
                return;
            }
            if (newSize === 0) {
                this.clear();
                return;
            }
            let current = this._tail;
            let currentSize = this.size;
            while (current && currentSize > newSize) {
                this._map.delete(current.key);
                current = current.previous;
                currentSize--;
            }
            this._tail = current;
            this._size = currentSize;
            if (current) {
                current.next = undefined;
            }
            this._state++;
        }
        addItemFirst(item) {
            // First time Insert
            if (!this._head && !this._tail) {
                this._tail = item;
            }
            else if (!this._head) {
                throw new Error('Invalid list');
            }
            else {
                item.next = this._head;
                this._head.previous = item;
            }
            this._head = item;
            this._state++;
        }
        addItemLast(item) {
            // First time Insert
            if (!this._head && !this._tail) {
                this._head = item;
            }
            else if (!this._tail) {
                throw new Error('Invalid list');
            }
            else {
                item.previous = this._tail;
                this._tail.next = item;
            }
            this._tail = item;
            this._state++;
        }
        removeItem(item) {
            if (item === this._head && item === this._tail) {
                this._head = undefined;
                this._tail = undefined;
            }
            else if (item === this._head) {
                // This can only happen if size === 1 which is handled
                // by the case above.
                if (!item.next) {
                    throw new Error('Invalid list');
                }
                item.next.previous = undefined;
                this._head = item.next;
            }
            else if (item === this._tail) {
                // This can only happen if size === 1 which is handled
                // by the case above.
                if (!item.previous) {
                    throw new Error('Invalid list');
                }
                item.previous.next = undefined;
                this._tail = item.previous;
            }
            else {
                const next = item.next;
                const previous = item.previous;
                if (!next || !previous) {
                    throw new Error('Invalid list');
                }
                next.previous = previous;
                previous.next = next;
            }
            item.next = undefined;
            item.previous = undefined;
            this._state++;
        }
        touch(item, touch) {
            if (!this._head || !this._tail) {
                throw new Error('Invalid list');
            }
            if ((touch !== 1 /* Touch.AsOld */ && touch !== 2 /* Touch.AsNew */)) {
                return;
            }
            if (touch === 1 /* Touch.AsOld */) {
                if (item === this._head) {
                    return;
                }
                const next = item.next;
                const previous = item.previous;
                // Unlink the item
                if (item === this._tail) {
                    // previous must be defined since item was not head but is tail
                    // So there are more than on item in the map
                    previous.next = undefined;
                    this._tail = previous;
                }
                else {
                    // Both next and previous are not undefined since item was neither head nor tail.
                    next.previous = previous;
                    previous.next = next;
                }
                // Insert the node at head
                item.previous = undefined;
                item.next = this._head;
                this._head.previous = item;
                this._head = item;
                this._state++;
            }
            else if (touch === 2 /* Touch.AsNew */) {
                if (item === this._tail) {
                    return;
                }
                const next = item.next;
                const previous = item.previous;
                // Unlink the item.
                if (item === this._head) {
                    // next must be defined since item was not tail but is head
                    // So there are more than on item in the map
                    next.previous = undefined;
                    this._head = next;
                }
                else {
                    // Both next and previous are not undefined since item was neither head nor tail.
                    next.previous = previous;
                    previous.next = next;
                }
                item.next = undefined;
                item.previous = this._tail;
                this._tail.next = item;
                this._tail = item;
                this._state++;
            }
        }
        toJSON() {
            const data = [];
            this.forEach((value, key) => {
                data.push([key, value]);
            });
            return data;
        }
        fromJSON(data) {
            this.clear();
            for (const [key, value] of data) {
                this.set(key, value);
            }
        }
    }
    exports.LinkedMap = LinkedMap;
    class Cache extends LinkedMap {
        constructor(limit, ratio = 1) {
            super();
            this._limit = limit;
            this._ratio = Math.min(Math.max(0, ratio), 1);
        }
        get limit() {
            return this._limit;
        }
        set limit(limit) {
            this._limit = limit;
            this.checkTrim();
        }
        get(key, touch = 2 /* Touch.AsNew */) {
            return super.get(key, touch);
        }
        peek(key) {
            return super.get(key, 0 /* Touch.None */);
        }
        set(key, value) {
            super.set(key, value, 2 /* Touch.AsNew */);
            return this;
        }
        checkTrim() {
            if (this.size > this._limit) {
                this.trim(Math.round(this._limit * this._ratio));
            }
        }
    }
    class LRUCache extends Cache {
        constructor(limit, ratio = 1) {
            super(limit, ratio);
        }
        trim(newSize) {
            this.trimOld(newSize);
        }
        set(key, value) {
            super.set(key, value);
            this.checkTrim();
            return this;
        }
    }
    exports.LRUCache = LRUCache;
    /**
     * A map that allows access both by keys and values.
     * **NOTE**: values need to be unique.
     */
    class BidirectionalMap {
        constructor(entries) {
            this._m1 = new Map();
            this._m2 = new Map();
            if (entries) {
                for (const [key, value] of entries) {
                    this.set(key, value);
                }
            }
        }
        clear() {
            this._m1.clear();
            this._m2.clear();
        }
        set(key, value) {
            this._m1.set(key, value);
            this._m2.set(value, key);
        }
        get(key) {
            return this._m1.get(key);
        }
        getKey(value) {
            return this._m2.get(value);
        }
        delete(key) {
            const value = this._m1.get(key);
            if (value === undefined) {
                return false;
            }
            this._m1.delete(key);
            this._m2.delete(value);
            return true;
        }
        keys() {
            return this._m1.keys();
        }
        values() {
            return this._m1.values();
        }
    }
    exports.BidirectionalMap = BidirectionalMap;
    class SetMap {
        constructor() {
            this.map = new Map();
        }
        add(key, value) {
            let values = this.map.get(key);
            if (!values) {
                values = new Set();
                this.map.set(key, values);
            }
            values.add(value);
        }
        delete(key, value) {
            const values = this.map.get(key);
            if (!values) {
                return;
            }
            values.delete(value);
            if (values.size === 0) {
                this.map.delete(key);
            }
        }
        forEach(key, fn) {
            const values = this.map.get(key);
            if (!values) {
                return;
            }
            values.forEach(fn);
        }
        get(key) {
            const values = this.map.get(key);
            if (!values) {
                return new Set();
            }
            return values;
        }
    }
    exports.SetMap = SetMap;
});

/**
 * marked v14.0.0 - a markdown parser
 * Copyright (c) 2011-2024, Christopher Jeffrey. (MIT Licensed)
 * https://github.com/markedjs/marked
 */

/**
 * DO NOT EDIT THIS FILE
 * The code in this file is generated from files in ./src/
 */

// ESM-uncomment-begin
// let __marked_exports = {};
// (function() {
//   function define(deps, factory) {
//     factory(__marked_exports);
//   }
//   define.amd = true;
// ESM-uncomment-end

(function (global, factory) {
	typeof define === 'function' && define.amd ? define(__m[447/*vs/base/common/marked/marked*/], __M([0/*exports*/]), factory) :
	typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
	(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.marked = {}));
  })(this, (function (exports) {
	'use strict';

	/**
	 * Gets the original marked default options.
	 */
	function _getDefaults() {
		return {
			async: false,
			breaks: false,
			extensions: null,
			gfm: true,
			hooks: null,
			pedantic: false,
			renderer: null,
			silent: false,
			tokenizer: null,
			walkTokens: null,
		};
	}
	exports.defaults = _getDefaults();
	function changeDefaults(newDefaults) {
		exports.defaults = newDefaults;
	}

	/**
	 * Helpers
	 */
	const escapeTest = /[&<>"']/;
	const escapeReplace = new RegExp(escapeTest.source, 'g');
	const escapeTestNoEncode = /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/;
	const escapeReplaceNoEncode = new RegExp(escapeTestNoEncode.source, 'g');
	const escapeReplacements = {
		'&': '&amp;',
		'<': '&lt;',
		'>': '&gt;',
		'"': '&quot;',
		"'": '&#39;',
	};
	const getEscapeReplacement = (ch) => escapeReplacements[ch];
	function escape$1(html, encode) {
		if (encode) {
			if (escapeTest.test(html)) {
				return html.replace(escapeReplace, getEscapeReplacement);
			}
		}
		else {
			if (escapeTestNoEncode.test(html)) {
				return html.replace(escapeReplaceNoEncode, getEscapeReplacement);
			}
		}
		return html;
	}
	const caret = /(^|[^\[])\^/g;
	function edit(regex, opt) {
		let source = typeof regex === 'string' ? regex : regex.source;
		opt = opt || '';
		const obj = {
			replace: (name, val) => {
				let valSource = typeof val === 'string' ? val : val.source;
				valSource = valSource.replace(caret, '$1');
				source = source.replace(name, valSource);
				return obj;
			},
			getRegex: () => {
				return new RegExp(source, opt);
			},
		};
		return obj;
	}
	function cleanUrl(href) {
		try {
			href = encodeURI(href).replace(/%25/g, '%');
		}
		catch {
			return null;
		}
		return href;
	}
	const noopTest = { exec: () => null };
	function splitCells(tableRow, count) {
		// ensure that every cell-delimiting pipe has a space
		// before it to distinguish it from an escaped pipe
		const row = tableRow.replace(/\|/g, (match, offset, str) => {
			let escaped = false;
			let curr = offset;
			while (--curr >= 0 && str[curr] === '\\')
				escaped = !escaped;
			if (escaped) {
				// odd number of slashes means | is escaped
				// so we leave it alone
				return '|';
			}
			else {
				// add space before unescaped |
				return ' |';
			}
		}), cells = row.split(/ \|/);
		let i = 0;
		// First/last cell in a row cannot be empty if it has no leading/trailing pipe
		if (!cells[0].trim()) {
			cells.shift();
		}
		if (cells.length > 0 && !cells[cells.length - 1].trim()) {
			cells.pop();
		}
		if (count) {
			if (cells.length > count) {
				cells.splice(count);
			}
			else {
				while (cells.length < count)
					cells.push('');
			}
		}
		for (; i < cells.length; i++) {
			// leading or trailing whitespace is ignored per the gfm spec
			cells[i] = cells[i].trim().replace(/\\\|/g, '|');
		}
		return cells;
	}
	/**
	 * Remove trailing 'c's. Equivalent to str.replace(/c*$/, '').
	 * /c*$/ is vulnerable to REDOS.
	 *
	 * @param str
	 * @param c
	 * @param invert Remove suffix of non-c chars instead. Default falsey.
	 */
	function rtrim(str, c, invert) {
		const l = str.length;
		if (l === 0) {
			return '';
		}
		// Length of suffix matching the invert condition.
		let suffLen = 0;
		// Step left until we fail to match the invert condition.
		while (suffLen < l) {
			const currChar = str.charAt(l - suffLen - 1);
			if (currChar === c && !invert) {
				suffLen++;
			}
			else if (currChar !== c && invert) {
				suffLen++;
			}
			else {
				break;
			}
		}
		return str.slice(0, l - suffLen);
	}
	function findClosingBracket(str, b) {
		if (str.indexOf(b[1]) === -1) {
			return -1;
		}
		let level = 0;
		for (let i = 0; i < str.length; i++) {
			if (str[i] === '\\') {
				i++;
			}
			else if (str[i] === b[0]) {
				level++;
			}
			else if (str[i] === b[1]) {
				level--;
				if (level < 0) {
					return i;
				}
			}
		}
		return -1;
	}

	function outputLink(cap, link, raw, lexer) {
		const href = link.href;
		const title = link.title ? escape$1(link.title) : null;
		const text = cap[1].replace(/\\([\[\]])/g, '$1');
		if (cap[0].charAt(0) !== '!') {
			lexer.state.inLink = true;
			const token = {
				type: 'link',
				raw,
				href,
				title,
				text,
				tokens: lexer.inlineTokens(text),
			};
			lexer.state.inLink = false;
			return token;
		}
		return {
			type: 'image',
			raw,
			href,
			title,
			text: escape$1(text),
		};
	}
	function indentCodeCompensation(raw, text) {
		const matchIndentToCode = raw.match(/^(\s+)(?:```)/);
		if (matchIndentToCode === null) {
			return text;
		}
		const indentToCode = matchIndentToCode[1];
		return text
			.split('\n')
			.map(node => {
				const matchIndentInNode = node.match(/^\s+/);
				if (matchIndentInNode === null) {
					return node;
				}
				const [indentInNode] = matchIndentInNode;
				if (indentInNode.length >= indentToCode.length) {
					return node.slice(indentToCode.length);
				}
				return node;
			})
			.join('\n');
	}
	/**
	 * Tokenizer
	 */
	class _Tokenizer {
		options;
		rules; // set by the lexer
		lexer; // set by the lexer
		constructor(options) {
			this.options = options || exports.defaults;
		}
		space(src) {
			const cap = this.rules.block.newline.exec(src);
			if (cap && cap[0].length > 0) {
				return {
					type: 'space',
					raw: cap[0],
				};
			}
		}
		code(src) {
			const cap = this.rules.block.code.exec(src);
			if (cap) {
				const text = cap[0].replace(/^ {1,4}/gm, '');
				return {
					type: 'code',
					raw: cap[0],
					codeBlockStyle: 'indented',
					text: !this.options.pedantic
						? rtrim(text, '\n')
						: text,
				};
			}
		}
		fences(src) {
			const cap = this.rules.block.fences.exec(src);
			if (cap) {
				const raw = cap[0];
				const text = indentCodeCompensation(raw, cap[3] || '');
				return {
					type: 'code',
					raw,
					lang: cap[2] ? cap[2].trim().replace(this.rules.inline.anyPunctuation, '$1') : cap[2],
					text,
				};
			}
		}
		heading(src) {
			const cap = this.rules.block.heading.exec(src);
			if (cap) {
				let text = cap[2].trim();
				// remove trailing #s
				if (/#$/.test(text)) {
					const trimmed = rtrim(text, '#');
					if (this.options.pedantic) {
						text = trimmed.trim();
					}
					else if (!trimmed || / $/.test(trimmed)) {
						// CommonMark requires space before trailing #s
						text = trimmed.trim();
					}
				}
				return {
					type: 'heading',
					raw: cap[0],
					depth: cap[1].length,
					text,
					tokens: this.lexer.inline(text),
				};
			}
		}
		hr(src) {
			const cap = this.rules.block.hr.exec(src);
			if (cap) {
				return {
					type: 'hr',
					raw: rtrim(cap[0], '\n'),
				};
			}
		}
		blockquote(src) {
			const cap = this.rules.block.blockquote.exec(src);
			if (cap) {
				let lines = rtrim(cap[0], '\n').split('\n');
				let raw = '';
				let text = '';
				const tokens = [];
				while (lines.length > 0) {
					let inBlockquote = false;
					const currentLines = [];
					let i;
					for (i = 0; i < lines.length; i++) {
						// get lines up to a continuation
						if (/^ {0,3}>/.test(lines[i])) {
							currentLines.push(lines[i]);
							inBlockquote = true;
						}
						else if (!inBlockquote) {
							currentLines.push(lines[i]);
						}
						else {
							break;
						}
					}
					lines = lines.slice(i);
					const currentRaw = currentLines.join('\n');
					const currentText = currentRaw
						// precede setext continuation with 4 spaces so it isn't a setext
						.replace(/\n {0,3}((?:=+|-+) *)(?=\n|$)/g, '\n    $1')
						.replace(/^ {0,3}>[ \t]?/gm, '');
					raw = raw ? `${raw}\n${currentRaw}` : currentRaw;
					text = text ? `${text}\n${currentText}` : currentText;
					// parse blockquote lines as top level tokens
					// merge paragraphs if this is a continuation
					const top = this.lexer.state.top;
					this.lexer.state.top = true;
					this.lexer.blockTokens(currentText, tokens, true);
					this.lexer.state.top = top;
					// if there is no continuation then we are done
					if (lines.length === 0) {
						break;
					}
					const lastToken = tokens[tokens.length - 1];
					if (lastToken?.type === 'code') {
						// blockquote continuation cannot be preceded by a code block
						break;
					}
					else if (lastToken?.type === 'blockquote') {
						// include continuation in nested blockquote
						const oldToken = lastToken;
						const newText = oldToken.raw + '\n' + lines.join('\n');
						const newToken = this.blockquote(newText);
						tokens[tokens.length - 1] = newToken;
						raw = raw.substring(0, raw.length - oldToken.raw.length) + newToken.raw;
						text = text.substring(0, text.length - oldToken.text.length) + newToken.text;
						break;
					}
					else if (lastToken?.type === 'list') {
						// include continuation in nested list
						const oldToken = lastToken;
						const newText = oldToken.raw + '\n' + lines.join('\n');
						const newToken = this.list(newText);
						tokens[tokens.length - 1] = newToken;
						raw = raw.substring(0, raw.length - lastToken.raw.length) + newToken.raw;
						text = text.substring(0, text.length - oldToken.raw.length) + newToken.raw;
						lines = newText.substring(tokens[tokens.length - 1].raw.length).split('\n');
						continue;
					}
				}
				return {
					type: 'blockquote',
					raw,
					tokens,
					text,
				};
			}
		}
		list(src) {
			let cap = this.rules.block.list.exec(src);
			if (cap) {
				let bull = cap[1].trim();
				const isordered = bull.length > 1;
				const list = {
					type: 'list',
					raw: '',
					ordered: isordered,
					start: isordered ? +bull.slice(0, -1) : '',
					loose: false,
					items: [],
				};
				bull = isordered ? `\\d{1,9}\\${bull.slice(-1)}` : `\\${bull}`;
				if (this.options.pedantic) {
					bull = isordered ? bull : '[*+-]';
				}
				// Get next list item
				const itemRegex = new RegExp(`^( {0,3}${bull})((?:[\t ][^\\n]*)?(?:\\n|$))`);
				let endsWithBlankLine = false;
				// Check if current bullet point can start a new List Item
				while (src) {
					let endEarly = false;
					let raw = '';
					let itemContents = '';
					if (!(cap = itemRegex.exec(src))) {
						break;
					}
					if (this.rules.block.hr.test(src)) { // End list if bullet was actually HR (possibly move into itemRegex?)
						break;
					}
					raw = cap[0];
					src = src.substring(raw.length);
					let line = cap[2].split('\n', 1)[0].replace(/^\t+/, (t) => ' '.repeat(3 * t.length));
					let nextLine = src.split('\n', 1)[0];
					let blankLine = !line.trim();
					let indent = 0;
					if (this.options.pedantic) {
						indent = 2;
						itemContents = line.trimStart();
					}
					else if (blankLine) {
						indent = cap[1].length + 1;
					}
					else {
						indent = cap[2].search(/[^ ]/); // Find first non-space char
						indent = indent > 4 ? 1 : indent; // Treat indented code blocks (> 4 spaces) as having only 1 indent
						itemContents = line.slice(indent);
						indent += cap[1].length;
					}
					if (blankLine && /^ *$/.test(nextLine)) { // Items begin with at most one blank line
						raw += nextLine + '\n';
						src = src.substring(nextLine.length + 1);
						endEarly = true;
					}
					if (!endEarly) {
						const nextBulletRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ \t][^\\n]*)?(?:\\n|$))`);
						const hrRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`);
						const fencesBeginRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:\`\`\`|~~~)`);
						const headingBeginRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}#`);
						// Check if following lines should be included in List Item
						while (src) {
							const rawLine = src.split('\n', 1)[0];
							nextLine = rawLine;
							// Re-align to follow commonmark nesting rules
							if (this.options.pedantic) {
								nextLine = nextLine.replace(/^ {1,4}(?=( {4})*[^ ])/g, '  ');
							}
							// End list item if found code fences
							if (fencesBeginRegex.test(nextLine)) {
								break;
							}
							// End list item if found start of new heading
							if (headingBeginRegex.test(nextLine)) {
								break;
							}
							// End list item if found start of new bullet
							if (nextBulletRegex.test(nextLine)) {
								break;
							}
							// Horizontal rule found
							if (hrRegex.test(src)) {
								break;
							}
							if (nextLine.search(/[^ ]/) >= indent || !nextLine.trim()) { // Dedent if possible
								itemContents += '\n' + nextLine.slice(indent);
							}
							else {
								// not enough indentation
								if (blankLine) {
									break;
								}
								// paragraph continuation unless last line was a different block level element
								if (line.search(/[^ ]/) >= 4) { // indented code block
									break;
								}
								if (fencesBeginRegex.test(line)) {
									break;
								}
								if (headingBeginRegex.test(line)) {
									break;
								}
								if (hrRegex.test(line)) {
									break;
								}
								itemContents += '\n' + nextLine;
							}
							if (!blankLine && !nextLine.trim()) { // Check if current line is blank
								blankLine = true;
							}
							raw += rawLine + '\n';
							src = src.substring(rawLine.length + 1);
							line = nextLine.slice(indent);
						}
					}
					if (!list.loose) {
						// If the previous item ended with a blank line, the list is loose
						if (endsWithBlankLine) {
							list.loose = true;
						}
						else if (/\n *\n *$/.test(raw)) {
							endsWithBlankLine = true;
						}
					}
					let istask = null;
					let ischecked;
					// Check for task list items
					if (this.options.gfm) {
						istask = /^\[[ xX]\] /.exec(itemContents);
						if (istask) {
							ischecked = istask[0] !== '[ ] ';
							itemContents = itemContents.replace(/^\[[ xX]\] +/, '');
						}
					}
					list.items.push({
						type: 'list_item',
						raw,
						task: !!istask,
						checked: ischecked,
						loose: false,
						text: itemContents,
						tokens: [],
					});
					list.raw += raw;
				}
				// Do not consume newlines at end of final item. Alternatively, make itemRegex *start* with any newlines to simplify/speed up endsWithBlankLine logic
				list.items[list.items.length - 1].raw = list.items[list.items.length - 1].raw.trimEnd();
				list.items[list.items.length - 1].text = list.items[list.items.length - 1].text.trimEnd();
				list.raw = list.raw.trimEnd();
				// Item child tokens handled here at end because we needed to have the final item to trim it first
				for (let i = 0; i < list.items.length; i++) {
					this.lexer.state.top = false;
					list.items[i].tokens = this.lexer.blockTokens(list.items[i].text, []);
					if (!list.loose) {
						// Check if list should be loose
						const spacers = list.items[i].tokens.filter(t => t.type === 'space');
						const hasMultipleLineBreaks = spacers.length > 0 && spacers.some(t => /\n.*\n/.test(t.raw));
						list.loose = hasMultipleLineBreaks;
					}
				}
				// Set all items to loose if list is loose
				if (list.loose) {
					for (let i = 0; i < list.items.length; i++) {
						list.items[i].loose = true;
					}
				}
				return list;
			}
		}
		html(src) {
			const cap = this.rules.block.html.exec(src);
			if (cap) {
				const token = {
					type: 'html',
					block: true,
					raw: cap[0],
					pre: cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style',
					text: cap[0],
				};
				return token;
			}
		}
		def(src) {
			const cap = this.rules.block.def.exec(src);
			if (cap) {
				const tag = cap[1].toLowerCase().replace(/\s+/g, ' ');
				const href = cap[2] ? cap[2].replace(/^<(.*)>$/, '$1').replace(this.rules.inline.anyPunctuation, '$1') : '';
				const title = cap[3] ? cap[3].substring(1, cap[3].length - 1).replace(this.rules.inline.anyPunctuation, '$1') : cap[3];
				return {
					type: 'def',
					tag,
					raw: cap[0],
					href,
					title,
				};
			}
		}
		table(src) {
			const cap = this.rules.block.table.exec(src);
			if (!cap) {
				return;
			}
			if (!/[:|]/.test(cap[2])) {
				// delimiter row must have a pipe (|) or colon (:) otherwise it is a setext heading
				return;
			}
			const headers = splitCells(cap[1]);
			const aligns = cap[2].replace(/^\||\| *$/g, '').split('|');
			const rows = cap[3] && cap[3].trim() ? cap[3].replace(/\n[ \t]*$/, '').split('\n') : [];
			const item = {
				type: 'table',
				raw: cap[0],
				header: [],
				align: [],
				rows: [],
			};
			if (headers.length !== aligns.length) {
				// header and align columns must be equal, rows can be different.
				return;
			}
			for (const align of aligns) {
				if (/^ *-+: *$/.test(align)) {
					item.align.push('right');
				}
				else if (/^ *:-+: *$/.test(align)) {
					item.align.push('center');
				}
				else if (/^ *:-+ *$/.test(align)) {
					item.align.push('left');
				}
				else {
					item.align.push(null);
				}
			}
			for (let i = 0; i < headers.length; i++) {
				item.header.push({
					text: headers[i],
					tokens: this.lexer.inline(headers[i]),
					header: true,
					align: item.align[i],
				});
			}
			for (const row of rows) {
				item.rows.push(splitCells(row, item.header.length).map((cell, i) => {
					return {
						text: cell,
						tokens: this.lexer.inline(cell),
						header: false,
						align: item.align[i],
					};
				}));
			}
			return item;
		}
		lheading(src) {
			const cap = this.rules.block.lheading.exec(src);
			if (cap) {
				return {
					type: 'heading',
					raw: cap[0],
					depth: cap[2].charAt(0) === '=' ? 1 : 2,
					text: cap[1],
					tokens: this.lexer.inline(cap[1]),
				};
			}
		}
		paragraph(src) {
			const cap = this.rules.block.paragraph.exec(src);
			if (cap) {
				const text = cap[1].charAt(cap[1].length - 1) === '\n'
					? cap[1].slice(0, -1)
					: cap[1];
				return {
					type: 'paragraph',
					raw: cap[0],
					text,
					tokens: this.lexer.inline(text),
				};
			}
		}
		text(src) {
			const cap = this.rules.block.text.exec(src);
			if (cap) {
				return {
					type: 'text',
					raw: cap[0],
					text: cap[0],
					tokens: this.lexer.inline(cap[0]),
				};
			}
		}
		escape(src) {
			const cap = this.rules.inline.escape.exec(src);
			if (cap) {
				return {
					type: 'escape',
					raw: cap[0],
					text: escape$1(cap[1]),
				};
			}
		}
		tag(src) {
			const cap = this.rules.inline.tag.exec(src);
			if (cap) {
				if (!this.lexer.state.inLink && /^<a /i.test(cap[0])) {
					this.lexer.state.inLink = true;
				}
				else if (this.lexer.state.inLink && /^<\/a>/i.test(cap[0])) {
					this.lexer.state.inLink = false;
				}
				if (!this.lexer.state.inRawBlock && /^<(pre|code|kbd|script)(\s|>)/i.test(cap[0])) {
					this.lexer.state.inRawBlock = true;
				}
				else if (this.lexer.state.inRawBlock && /^<\/(pre|code|kbd|script)(\s|>)/i.test(cap[0])) {
					this.lexer.state.inRawBlock = false;
				}
				return {
					type: 'html',
					raw: cap[0],
					inLink: this.lexer.state.inLink,
					inRawBlock: this.lexer.state.inRawBlock,
					block: false,
					text: cap[0],
				};
			}
		}
		link(src) {
			const cap = this.rules.inline.link.exec(src);
			if (cap) {
				const trimmedUrl = cap[2].trim();
				if (!this.options.pedantic && /^</.test(trimmedUrl)) {
					// commonmark requires matching angle brackets
					if (!(/>$/.test(trimmedUrl))) {
						return;
					}
					// ending angle bracket cannot be escaped
					const rtrimSlash = rtrim(trimmedUrl.slice(0, -1), '\\');
					if ((trimmedUrl.length - rtrimSlash.length) % 2 === 0) {
						return;
					}
				}
				else {
					// find closing parenthesis
					const lastParenIndex = findClosingBracket(cap[2], '()');
					if (lastParenIndex > -1) {
						const start = cap[0].indexOf('!') === 0 ? 5 : 4;
						const linkLen = start + cap[1].length + lastParenIndex;
						cap[2] = cap[2].substring(0, lastParenIndex);
						cap[0] = cap[0].substring(0, linkLen).trim();
						cap[3] = '';
					}
				}
				let href = cap[2];
				let title = '';
				if (this.options.pedantic) {
					// split pedantic href and title
					const link = /^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(href);
					if (link) {
						href = link[1];
						title = link[3];
					}
				}
				else {
					title = cap[3] ? cap[3].slice(1, -1) : '';
				}
				href = href.trim();
				if (/^</.test(href)) {
					if (this.options.pedantic && !(/>$/.test(trimmedUrl))) {
						// pedantic allows starting angle bracket without ending angle bracket
						href = href.slice(1);
					}
					else {
						href = href.slice(1, -1);
					}
				}
				return outputLink(cap, {
					href: href ? href.replace(this.rules.inline.anyPunctuation, '$1') : href,
					title: title ? title.replace(this.rules.inline.anyPunctuation, '$1') : title,
				}, cap[0], this.lexer);
			}
		}
		reflink(src, links) {
			let cap;
			if ((cap = this.rules.inline.reflink.exec(src))
				|| (cap = this.rules.inline.nolink.exec(src))) {
				const linkString = (cap[2] || cap[1]).replace(/\s+/g, ' ');
				const link = links[linkString.toLowerCase()];
				if (!link) {
					const text = cap[0].charAt(0);
					return {
						type: 'text',
						raw: text,
						text,
					};
				}
				return outputLink(cap, link, cap[0], this.lexer);
			}
		}
		emStrong(src, maskedSrc, prevChar = '') {
			let match = this.rules.inline.emStrongLDelim.exec(src);
			if (!match)
				return;
			// _ can't be between two alphanumerics. \p{L}\p{N} includes non-english alphabet/numbers as well
			if (match[3] && prevChar.match(/[\p{L}\p{N}]/u))
				return;
			const nextChar = match[1] || match[2] || '';
			if (!nextChar || !prevChar || this.rules.inline.punctuation.exec(prevChar)) {
				// unicode Regex counts emoji as 1 char; spread into array for proper count (used multiple times below)
				const lLength = [...match[0]].length - 1;
				let rDelim, rLength, delimTotal = lLength, midDelimTotal = 0;
				const endReg = match[0][0] === '*' ? this.rules.inline.emStrongRDelimAst : this.rules.inline.emStrongRDelimUnd;
				endReg.lastIndex = 0;
				// Clip maskedSrc to same section of string as src (move to lexer?)
				maskedSrc = maskedSrc.slice(-1 * src.length + lLength);
				while ((match = endReg.exec(maskedSrc)) != null) {
					rDelim = match[1] || match[2] || match[3] || match[4] || match[5] || match[6];
					if (!rDelim)
						continue; // skip single * in __abc*abc__
					rLength = [...rDelim].length;
					if (match[3] || match[4]) { // found another Left Delim
						delimTotal += rLength;
						continue;
					}
					else if (match[5] || match[6]) { // either Left or Right Delim
						if (lLength % 3 && !((lLength + rLength) % 3)) {
							midDelimTotal += rLength;
							continue; // CommonMark Emphasis Rules 9-10
						}
					}
					delimTotal -= rLength;
					if (delimTotal > 0)
						continue; // Haven't found enough closing delimiters
					// Remove extra characters. *a*** -> *a*
					rLength = Math.min(rLength, rLength + delimTotal + midDelimTotal);
					// char length can be >1 for unicode characters;
					const lastCharLength = [...match[0]][0].length;
					const raw = src.slice(0, lLength + match.index + lastCharLength + rLength);
					// Create `em` if smallest delimiter has odd char count. *a***
					if (Math.min(lLength, rLength) % 2) {
						const text = raw.slice(1, -1);
						return {
							type: 'em',
							raw,
							text,
							tokens: this.lexer.inlineTokens(text),
						};
					}
					// Create 'strong' if smallest delimiter has even char count. **a***
					const text = raw.slice(2, -2);
					return {
						type: 'strong',
						raw,
						text,
						tokens: this.lexer.inlineTokens(text),
					};
				}
			}
		}
		codespan(src) {
			const cap = this.rules.inline.code.exec(src);
			if (cap) {
				let text = cap[2].replace(/\n/g, ' ');
				const hasNonSpaceChars = /[^ ]/.test(text);
				const hasSpaceCharsOnBothEnds = /^ /.test(text) && / $/.test(text);
				if (hasNonSpaceChars && hasSpaceCharsOnBothEnds) {
					text = text.substring(1, text.length - 1);
				}
				text = escape$1(text, true);
				return {
					type: 'codespan',
					raw: cap[0],
					text,
				};
			}
		}
		br(src) {
			const cap = this.rules.inline.br.exec(src);
			if (cap) {
				return {
					type: 'br',
					raw: cap[0],
				};
			}
		}
		del(src) {
			const cap = this.rules.inline.del.exec(src);
			if (cap) {
				return {
					type: 'del',
					raw: cap[0],
					text: cap[2],
					tokens: this.lexer.inlineTokens(cap[2]),
				};
			}
		}
		autolink(src) {
			const cap = this.rules.inline.autolink.exec(src);
			if (cap) {
				let text, href;
				if (cap[2] === '@') {
					text = escape$1(cap[1]);
					href = 'mailto:' + text;
				}
				else {
					text = escape$1(cap[1]);
					href = text;
				}
				return {
					type: 'link',
					raw: cap[0],
					text,
					href,
					tokens: [
						{
							type: 'text',
							raw: text,
							text,
						},
					],
				};
			}
		}
		url(src) {
			let cap;
			if (cap = this.rules.inline.url.exec(src)) {
				let text, href;
				if (cap[2] === '@') {
					text = escape$1(cap[0]);
					href = 'mailto:' + text;
				}
				else {
					// do extended autolink path validation
					let prevCapZero;
					do {
						prevCapZero = cap[0];
						cap[0] = this.rules.inline._backpedal.exec(cap[0])?.[0] ?? '';
					} while (prevCapZero !== cap[0]);
					text = escape$1(cap[0]);
					if (cap[1] === 'www.') {
						href = 'http://' + cap[0];
					}
					else {
						href = cap[0];
					}
				}
				return {
					type: 'link',
					raw: cap[0],
					text,
					href,
					tokens: [
						{
							type: 'text',
							raw: text,
							text,
						},
					],
				};
			}
		}
		inlineText(src) {
			const cap = this.rules.inline.text.exec(src);
			if (cap) {
				let text;
				if (this.lexer.state.inRawBlock) {
					text = cap[0];
				}
				else {
					text = escape$1(cap[0]);
				}
				return {
					type: 'text',
					raw: cap[0],
					text,
				};
			}
		}
	}

	/**
	 * Block-Level Grammar
	 */
	const newline = /^(?: *(?:\n|$))+/;
	const blockCode = /^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/;
	const fences = /^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/;
	const hr = /^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/;
	const heading = /^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/;
	const bullet = /(?:[*+-]|\d{1,9}[.)])/;
	const lheading = edit(/^(?!bull |blockCode|fences|blockquote|heading|html)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html))+?)\n {0,3}(=+|-+) *(?:\n+|$)/)
		.replace(/bull/g, bullet) // lists can interrupt
		.replace(/blockCode/g, / {4}/) // indented code blocks can interrupt
		.replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/) // fenced code blocks can interrupt
		.replace(/blockquote/g, / {0,3}>/) // blockquote can interrupt
		.replace(/heading/g, / {0,3}#{1,6}/) // ATX heading can interrupt
		.replace(/html/g, / {0,3}<[^\n>]+>\n/) // block html can interrupt
		.getRegex();
	const _paragraph = /^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/;
	const blockText = /^[^\n]+/;
	const _blockLabel = /(?!\s*\])(?:\\.|[^\[\]\\])+/;
	const def = edit(/^ {0,3}\[(label)\]: *(?:\n *)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/)
		.replace('label', _blockLabel)
		.replace('title', /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/)
		.getRegex();
	const list = edit(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/)
		.replace(/bull/g, bullet)
		.getRegex();
	const _tag = 'address|article|aside|base|basefont|blockquote|body|caption'
		+ '|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption'
		+ '|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe'
		+ '|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option'
		+ '|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title'
		+ '|tr|track|ul';
	const _comment = /<!--(?:-?>|[\s\S]*?(?:-->|$))/;
	const html = edit('^ {0,3}(?:' // optional indentation
		+ '<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)' // (1)
		+ '|comment[^\\n]*(\\n+|$)' // (2)
		+ '|<\\?[\\s\\S]*?(?:\\?>\\n*|$)' // (3)
		+ '|<![A-Z][\\s\\S]*?(?:>\\n*|$)' // (4)
		+ '|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)' // (5)
		+ '|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n *)+\\n|$)' // (6)
		+ '|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)' // (7) open tag
		+ '|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)' // (7) closing tag
		+ ')', 'i')
		.replace('comment', _comment)
		.replace('tag', _tag)
		.replace('attribute', / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/)
		.getRegex();
	const paragraph = edit(_paragraph)
		.replace('hr', hr)
		.replace('heading', ' {0,3}#{1,6}(?:\\s|$)')
		.replace('|lheading', '') // setext headings don't interrupt commonmark paragraphs
		.replace('|table', '')
		.replace('blockquote', ' {0,3}>')
		.replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n')
		.replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt
		.replace('html', '</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)')
		.replace('tag', _tag) // pars can be interrupted by type (6) html blocks
		.getRegex();
	const blockquote = edit(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/)
		.replace('paragraph', paragraph)
		.getRegex();
	/**
	 * Normal Block Grammar
	 */
	const blockNormal = {
		blockquote,
		code: blockCode,
		def,
		fences,
		heading,
		hr,
		html,
		lheading,
		list,
		newline,
		paragraph,
		table: noopTest,
		text: blockText,
	};
	/**
	 * GFM Block Grammar
	 */
	const gfmTable = edit('^ *([^\\n ].*)\\n' // Header
		+ ' {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)' // Align
		+ '(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)') // Cells
		.replace('hr', hr)
		.replace('heading', ' {0,3}#{1,6}(?:\\s|$)')
		.replace('blockquote', ' {0,3}>')
		.replace('code', ' {4}[^\\n]')
		.replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n')
		.replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt
		.replace('html', '</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)')
		.replace('tag', _tag) // tables can be interrupted by type (6) html blocks
		.getRegex();
	const blockGfm = {
		...blockNormal,
		table: gfmTable,
		paragraph: edit(_paragraph)
			.replace('hr', hr)
			.replace('heading', ' {0,3}#{1,6}(?:\\s|$)')
			.replace('|lheading', '') // setext headings don't interrupt commonmark paragraphs
			.replace('table', gfmTable) // interrupt paragraphs with table
			.replace('blockquote', ' {0,3}>')
			.replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n')
			.replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt
			.replace('html', '</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)')
			.replace('tag', _tag) // pars can be interrupted by type (6) html blocks
			.getRegex(),
	};
	/**
	 * Pedantic grammar (original John Gruber's loose markdown specification)
	 */
	const blockPedantic = {
		...blockNormal,
		html: edit('^ *(?:comment *(?:\\n|\\s*$)'
			+ '|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)' // closed tag
			+ '|<tag(?:"[^"]*"|\'[^\']*\'|\\s[^\'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))')
			.replace('comment', _comment)
			.replace(/tag/g, '(?!(?:'
				+ 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub'
				+ '|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)'
				+ '\\b)\\w+(?!:|[^\\w\\s@]*@)\\b')
			.getRegex(),
		def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,
		heading: /^(#{1,6})(.*)(?:\n+|$)/,
		fences: noopTest, // fences not supported
		lheading: /^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,
		paragraph: edit(_paragraph)
			.replace('hr', hr)
			.replace('heading', ' *#{1,6} *[^\n]')
			.replace('lheading', lheading)
			.replace('|table', '')
			.replace('blockquote', ' {0,3}>')
			.replace('|fences', '')
			.replace('|list', '')
			.replace('|html', '')
			.replace('|tag', '')
			.getRegex(),
	};
	/**
	 * Inline-Level Grammar
	 */
	const escape = /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/;
	const inlineCode = /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/;
	const br = /^( {2,}|\\)\n(?!\s*$)/;
	const inlineText = /^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/;
	// list of unicode punctuation marks, plus any missing characters from CommonMark spec
	const _punctuation = '\\p{P}\\p{S}';
	const punctuation = edit(/^((?![*_])[\spunctuation])/, 'u')
		.replace(/punctuation/g, _punctuation).getRegex();
	// sequences em should skip over [title](link), `code`, <html>
	const blockSkip = /\[[^[\]]*?\]\([^\(\)]*?\)|`[^`]*?`|<[^<>]*?>/g;
	const emStrongLDelim = edit(/^(?:\*+(?:((?!\*)[punct])|[^\s*]))|^_+(?:((?!_)[punct])|([^\s_]))/, 'u')
		.replace(/punct/g, _punctuation)
		.getRegex();
	const emStrongRDelimAst = edit('^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)' // Skip orphan inside strong
		+ '|[^*]+(?=[^*])' // Consume to delim
		+ '|(?!\\*)[punct](\\*+)(?=[\\s]|$)' // (1) #*** can only be a Right Delimiter
		+ '|[^punct\\s](\\*+)(?!\\*)(?=[punct\\s]|$)' // (2) a***#, a*** can only be a Right Delimiter
		+ '|(?!\\*)[punct\\s](\\*+)(?=[^punct\\s])' // (3) #***a, ***a can only be Left Delimiter
		+ '|[\\s](\\*+)(?!\\*)(?=[punct])' // (4) ***# can only be Left Delimiter
		+ '|(?!\\*)[punct](\\*+)(?!\\*)(?=[punct])' // (5) #***# can be either Left or Right Delimiter
		+ '|[^punct\\s](\\*+)(?=[^punct\\s])', 'gu') // (6) a***a can be either Left or Right Delimiter
		.replace(/punct/g, _punctuation)
		.getRegex();
	// (6) Not allowed for _
	const emStrongRDelimUnd = edit('^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)' // Skip orphan inside strong
		+ '|[^_]+(?=[^_])' // Consume to delim
		+ '|(?!_)[punct](_+)(?=[\\s]|$)' // (1) #___ can only be a Right Delimiter
		+ '|[^punct\\s](_+)(?!_)(?=[punct\\s]|$)' // (2) a___#, a___ can only be a Right Delimiter
		+ '|(?!_)[punct\\s](_+)(?=[^punct\\s])' // (3) #___a, ___a can only be Left Delimiter
		+ '|[\\s](_+)(?!_)(?=[punct])' // (4) ___# can only be Left Delimiter
		+ '|(?!_)[punct](_+)(?!_)(?=[punct])', 'gu') // (5) #___# can be either Left or Right Delimiter
		.replace(/punct/g, _punctuation)
		.getRegex();
	const anyPunctuation = edit(/\\([punct])/, 'gu')
		.replace(/punct/g, _punctuation)
		.getRegex();
	const autolink = edit(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/)
		.replace('scheme', /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/)
		.replace('email', /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/)
		.getRegex();
	const _inlineComment = edit(_comment).replace('(?:-->|$)', '-->').getRegex();
	const tag = edit('^comment'
		+ '|^</[a-zA-Z][\\w:-]*\\s*>' // self-closing tag
		+ '|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>' // open tag
		+ '|^<\\?[\\s\\S]*?\\?>' // processing instruction, e.g. <?php ?>
		+ '|^<![a-zA-Z]+\\s[\\s\\S]*?>' // declaration, e.g. <!DOCTYPE html>
		+ '|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>') // CDATA section
		.replace('comment', _inlineComment)
		.replace('attribute', /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/)
		.getRegex();
	const _inlineLabel = /(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/;
	const link = edit(/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/)
		.replace('label', _inlineLabel)
		.replace('href', /<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/)
		.replace('title', /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/)
		.getRegex();
	const reflink = edit(/^!?\[(label)\]\[(ref)\]/)
		.replace('label', _inlineLabel)
		.replace('ref', _blockLabel)
		.getRegex();
	const nolink = edit(/^!?\[(ref)\](?:\[\])?/)
		.replace('ref', _blockLabel)
		.getRegex();
	const reflinkSearch = edit('reflink|nolink(?!\\()', 'g')
		.replace('reflink', reflink)
		.replace('nolink', nolink)
		.getRegex();
	/**
	 * Normal Inline Grammar
	 */
	const inlineNormal = {
		_backpedal: noopTest, // only used for GFM url
		anyPunctuation,
		autolink,
		blockSkip,
		br,
		code: inlineCode,
		del: noopTest,
		emStrongLDelim,
		emStrongRDelimAst,
		emStrongRDelimUnd,
		escape,
		link,
		nolink,
		punctuation,
		reflink,
		reflinkSearch,
		tag,
		text: inlineText,
		url: noopTest,
	};
	/**
	 * Pedantic Inline Grammar
	 */
	const inlinePedantic = {
		...inlineNormal,
		link: edit(/^!?\[(label)\]\((.*?)\)/)
			.replace('label', _inlineLabel)
			.getRegex(),
		reflink: edit(/^!?\[(label)\]\s*\[([^\]]*)\]/)
			.replace('label', _inlineLabel)
			.getRegex(),
	};
	/**
	 * GFM Inline Grammar
	 */
	const inlineGfm = {
		...inlineNormal,
		escape: edit(escape).replace('])', '~|])').getRegex(),
		url: edit(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/, 'i')
			.replace('email', /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/)
			.getRegex(),
		_backpedal: /(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,
		del: /^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/,
		text: /^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/,
	};
	/**
	 * GFM + Line Breaks Inline Grammar
	 */
	const inlineBreaks = {
		...inlineGfm,
		br: edit(br).replace('{2,}', '*').getRegex(),
		text: edit(inlineGfm.text)
			.replace('\\b_', '\\b_| {2,}\\n')
			.replace(/\{2,\}/g, '*')
			.getRegex(),
	};
	/**
	 * exports
	 */
	const block = {
		normal: blockNormal,
		gfm: blockGfm,
		pedantic: blockPedantic,
	};
	const inline = {
		normal: inlineNormal,
		gfm: inlineGfm,
		breaks: inlineBreaks,
		pedantic: inlinePedantic,
	};

	/**
	 * Block Lexer
	 */
	class _Lexer {
		tokens;
		options;
		state;
		tokenizer;
		inlineQueue;
		constructor(options) {
			// TokenList cannot be created in one go
			this.tokens = [];
			this.tokens.links = Object.create(null);
			this.options = options || exports.defaults;
			this.options.tokenizer = this.options.tokenizer || new _Tokenizer();
			this.tokenizer = this.options.tokenizer;
			this.tokenizer.options = this.options;
			this.tokenizer.lexer = this;
			this.inlineQueue = [];
			this.state = {
				inLink: false,
				inRawBlock: false,
				top: true,
			};
			const rules = {
				block: block.normal,
				inline: inline.normal,
			};
			if (this.options.pedantic) {
				rules.block = block.pedantic;
				rules.inline = inline.pedantic;
			}
			else if (this.options.gfm) {
				rules.block = block.gfm;
				if (this.options.breaks) {
					rules.inline = inline.breaks;
				}
				else {
					rules.inline = inline.gfm;
				}
			}
			this.tokenizer.rules = rules;
		}
		/**
		 * Expose Rules
		 */
		static get rules() {
			return {
				block,
				inline,
			};
		}
		/**
		 * Static Lex Method
		 */
		static lex(src, options) {
			const lexer = new _Lexer(options);
			return lexer.lex(src);
		}
		/**
		 * Static Lex Inline Method
		 */
		static lexInline(src, options) {
			const lexer = new _Lexer(options);
			return lexer.inlineTokens(src);
		}
		/**
		 * Preprocessing
		 */
		lex(src) {
			src = src
				.replace(/\r\n|\r/g, '\n');
			this.blockTokens(src, this.tokens);
			for (let i = 0; i < this.inlineQueue.length; i++) {
				const next = this.inlineQueue[i];
				this.inlineTokens(next.src, next.tokens);
			}
			this.inlineQueue = [];
			return this.tokens;
		}
		blockTokens(src, tokens = [], lastParagraphClipped = false) {
			if (this.options.pedantic) {
				src = src.replace(/\t/g, '    ').replace(/^ +$/gm, '');
			}
			else {
				src = src.replace(/^( *)(\t+)/gm, (_, leading, tabs) => {
					return leading + '    '.repeat(tabs.length);
				});
			}
			let token;
			let lastToken;
			let cutSrc;
			while (src) {
				if (this.options.extensions
					&& this.options.extensions.block
					&& this.options.extensions.block.some((extTokenizer) => {
						if (token = extTokenizer.call({ lexer: this }, src, tokens)) {
							src = src.substring(token.raw.length);
							tokens.push(token);
							return true;
						}
						return false;
					})) {
					continue;
				}
				// newline
				if (token = this.tokenizer.space(src)) {
					src = src.substring(token.raw.length);
					if (token.raw.length === 1 && tokens.length > 0) {
						// if there's a single \n as a spacer, it's terminating the last line,
						// so move it there so that we don't get unnecessary paragraph tags
						tokens[tokens.length - 1].raw += '\n';
					}
					else {
						tokens.push(token);
					}
					continue;
				}
				// code
				if (token = this.tokenizer.code(src)) {
					src = src.substring(token.raw.length);
					lastToken = tokens[tokens.length - 1];
					// An indented code block cannot interrupt a paragraph.
					if (lastToken && (lastToken.type === 'paragraph' || lastToken.type === 'text')) {
						lastToken.raw += '\n' + token.raw;
						lastToken.text += '\n' + token.text;
						this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;
					}
					else {
						tokens.push(token);
					}
					continue;
				}
				// fences
				if (token = this.tokenizer.fences(src)) {
					src = src.substring(token.raw.length);
					tokens.push(token);
					continue;
				}
				// heading
				if (token = this.tokenizer.heading(src)) {
					src = src.substring(token.raw.length);
					tokens.push(token);
					continue;
				}
				// hr
				if (token = this.tokenizer.hr(src)) {
					src = src.substring(token.raw.length);
					tokens.push(token);
					continue;
				}
				// blockquote
				if (token = this.tokenizer.blockquote(src)) {
					src = src.substring(token.raw.length);
					tokens.push(token);
					continue;
				}
				// list
				if (token = this.tokenizer.list(src)) {
					src = src.substring(token.raw.length);
					tokens.push(token);
					continue;
				}
				// html
				if (token = this.tokenizer.html(src)) {
					src = src.substring(token.raw.length);
					tokens.push(token);
					continue;
				}
				// def
				if (token = this.tokenizer.def(src)) {
					src = src.substring(token.raw.length);
					lastToken = tokens[tokens.length - 1];
					if (lastToken && (lastToken.type === 'paragraph' || lastToken.type === 'text')) {
						lastToken.raw += '\n' + token.raw;
						lastToken.text += '\n' + token.raw;
						this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;
					}
					else if (!this.tokens.links[token.tag]) {
						this.tokens.links[token.tag] = {
							href: token.href,
							title: token.title,
						};
					}
					continue;
				}
				// table (gfm)
				if (token = this.tokenizer.table(src)) {
					src = src.substring(token.raw.length);
					tokens.push(token);
					continue;
				}
				// lheading
				if (token = this.tokenizer.lheading(src)) {
					src = src.substring(token.raw.length);
					tokens.push(token);
					continue;
				}
				// top-level paragraph
				// prevent paragraph consuming extensions by clipping 'src' to extension start
				cutSrc = src;
				if (this.options.extensions && this.options.extensions.startBlock) {
					let startIndex = Infinity;
					const tempSrc = src.slice(1);
					let tempStart;
					this.options.extensions.startBlock.forEach((getStartIndex) => {
						tempStart = getStartIndex.call({ lexer: this }, tempSrc);
						if (typeof tempStart === 'number' && tempStart >= 0) {
							startIndex = Math.min(startIndex, tempStart);
						}
					});
					if (startIndex < Infinity && startIndex >= 0) {
						cutSrc = src.substring(0, startIndex + 1);
					}
				}
				if (this.state.top && (token = this.tokenizer.paragraph(cutSrc))) {
					lastToken = tokens[tokens.length - 1];
					if (lastParagraphClipped && lastToken?.type === 'paragraph') {
						lastToken.raw += '\n' + token.raw;
						lastToken.text += '\n' + token.text;
						this.inlineQueue.pop();
						this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;
					}
					else {
						tokens.push(token);
					}
					lastParagraphClipped = (cutSrc.length !== src.length);
					src = src.substring(token.raw.length);
					continue;
				}
				// text
				if (token = this.tokenizer.text(src)) {
					src = src.substring(token.raw.length);
					lastToken = tokens[tokens.length - 1];
					if (lastToken && lastToken.type === 'text') {
						lastToken.raw += '\n' + token.raw;
						lastToken.text += '\n' + token.text;
						this.inlineQueue.pop();
						this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;
					}
					else {
						tokens.push(token);
					}
					continue;
				}
				if (src) {
					const errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0);
					if (this.options.silent) {
						console.error(errMsg);
						break;
					}
					else {
						throw new Error(errMsg);
					}
				}
			}
			this.state.top = true;
			return tokens;
		}
		inline(src, tokens = []) {
			this.inlineQueue.push({ src, tokens });
			return tokens;
		}
		/**
		 * Lexing/Compiling
		 */
		inlineTokens(src, tokens = []) {
			let token, lastToken, cutSrc;
			// String with links masked to avoid interference with em and strong
			let maskedSrc = src;
			let match;
			let keepPrevChar, prevChar;
			// Mask out reflinks
			if (this.tokens.links) {
				const links = Object.keys(this.tokens.links);
				if (links.length > 0) {
					while ((match = this.tokenizer.rules.inline.reflinkSearch.exec(maskedSrc)) != null) {
						if (links.includes(match[0].slice(match[0].lastIndexOf('[') + 1, -1))) {
							maskedSrc = maskedSrc.slice(0, match.index) + '[' + 'a'.repeat(match[0].length - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex);
						}
					}
				}
			}
			// Mask out other blocks
			while ((match = this.tokenizer.rules.inline.blockSkip.exec(maskedSrc)) != null) {
				maskedSrc = maskedSrc.slice(0, match.index) + '[' + 'a'.repeat(match[0].length - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);
			}
			// Mask out escaped characters
			while ((match = this.tokenizer.rules.inline.anyPunctuation.exec(maskedSrc)) != null) {
				maskedSrc = maskedSrc.slice(0, match.index) + '++' + maskedSrc.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);
			}
			while (src) {
				if (!keepPrevChar) {
					prevChar = '';
				}
				keepPrevChar = false;
				// extensions
				if (this.options.extensions
					&& this.options.extensions.inline
					&& this.options.extensions.inline.some((extTokenizer) => {
						if (token = extTokenizer.call({ lexer: this }, src, tokens)) {
							src = src.substring(token.raw.length);
							tokens.push(token);
							return true;
						}
						return false;
					})) {
					continue;
				}
				// escape
				if (token = this.tokenizer.escape(src)) {
					src = src.substring(token.raw.length);
					tokens.push(token);
					continue;
				}
				// tag
				if (token = this.tokenizer.tag(src)) {
					src = src.substring(token.raw.length);
					lastToken = tokens[tokens.length - 1];
					if (lastToken && token.type === 'text' && lastToken.type === 'text') {
						lastToken.raw += token.raw;
						lastToken.text += token.text;
					}
					else {
						tokens.push(token);
					}
					continue;
				}
				// link
				if (token = this.tokenizer.link(src)) {
					src = src.substring(token.raw.length);
					tokens.push(token);
					continue;
				}
				// reflink, nolink
				if (token = this.tokenizer.reflink(src, this.tokens.links)) {
					src = src.substring(token.raw.length);
					lastToken = tokens[tokens.length - 1];
					if (lastToken && token.type === 'text' && lastToken.type === 'text') {
						lastToken.raw += token.raw;
						lastToken.text += token.text;
					}
					else {
						tokens.push(token);
					}
					continue;
				}
				// em & strong
				if (token = this.tokenizer.emStrong(src, maskedSrc, prevChar)) {
					src = src.substring(token.raw.length);
					tokens.push(token);
					continue;
				}
				// code
				if (token = this.tokenizer.codespan(src)) {
					src = src.substring(token.raw.length);
					tokens.push(token);
					continue;
				}
				// br
				if (token = this.tokenizer.br(src)) {
					src = src.substring(token.raw.length);
					tokens.push(token);
					continue;
				}
				// del (gfm)
				if (token = this.tokenizer.del(src)) {
					src = src.substring(token.raw.length);
					tokens.push(token);
					continue;
				}
				// autolink
				if (token = this.tokenizer.autolink(src)) {
					src = src.substring(token.raw.length);
					tokens.push(token);
					continue;
				}
				// url (gfm)
				if (!this.state.inLink && (token = this.tokenizer.url(src))) {
					src = src.substring(token.raw.length);
					tokens.push(token);
					continue;
				}
				// text
				// prevent inlineText consuming extensions by clipping 'src' to extension start
				cutSrc = src;
				if (this.options.extensions && this.options.extensions.startInline) {
					let startIndex = Infinity;
					const tempSrc = src.slice(1);
					let tempStart;
					this.options.extensions.startInline.forEach((getStartIndex) => {
						tempStart = getStartIndex.call({ lexer: this }, tempSrc);
						if (typeof tempStart === 'number' && tempStart >= 0) {
							startIndex = Math.min(startIndex, tempStart);
						}
					});
					if (startIndex < Infinity && startIndex >= 0) {
						cutSrc = src.substring(0, startIndex + 1);
					}
				}
				if (token = this.tokenizer.inlineText(cutSrc)) {
					src = src.substring(token.raw.length);
					if (token.raw.slice(-1) !== '_') { // Track prevChar before string of ____ started
						prevChar = token.raw.slice(-1);
					}
					keepPrevChar = true;
					lastToken = tokens[tokens.length - 1];
					if (lastToken && lastToken.type === 'text') {
						lastToken.raw += token.raw;
						lastToken.text += token.text;
					}
					else {
						tokens.push(token);
					}
					continue;
				}
				if (src) {
					const errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0);
					if (this.options.silent) {
						console.error(errMsg);
						break;
					}
					else {
						throw new Error(errMsg);
					}
				}
			}
			return tokens;
		}
	}

	/**
	 * Renderer
	 */
	class _Renderer {
		options;
		parser; // set by the parser
		constructor(options) {
			this.options = options || exports.defaults;
		}
		space(token) {
			return '';
		}
		code({ text, lang, escaped }) {
			const langString = (lang || '').match(/^\S*/)?.[0];
			const code = text.replace(/\n$/, '') + '\n';
			if (!langString) {
				return '<pre><code>'
					+ (escaped ? code : escape$1(code, true))
					+ '</code></pre>\n';
			}
			return '<pre><code class="language-'
				+ escape$1(langString)
				+ '">'
				+ (escaped ? code : escape$1(code, true))
				+ '</code></pre>\n';
		}
		blockquote({ tokens }) {
			const body = this.parser.parse(tokens);
			return `<blockquote>\n${body}</blockquote>\n`;
		}
		html({ text }) {
			return text;
		}
		heading({ tokens, depth }) {
			return `<h${depth}>${this.parser.parseInline(tokens)}</h${depth}>\n`;
		}
		hr(token) {
			return '<hr>\n';
		}
		list(token) {
			const ordered = token.ordered;
			const start = token.start;
			let body = '';
			for (let j = 0; j < token.items.length; j++) {
				const item = token.items[j];
				body += this.listitem(item);
			}
			const type = ordered ? 'ol' : 'ul';
			const startAttr = (ordered && start !== 1) ? (' start="' + start + '"') : '';
			return '<' + type + startAttr + '>\n' + body + '</' + type + '>\n';
		}
		listitem(item) {
			let itemBody = '';
			if (item.task) {
				const checkbox = this.checkbox({ checked: !!item.checked });
				if (item.loose) {
					if (item.tokens.length > 0 && item.tokens[0].type === 'paragraph') {
						item.tokens[0].text = checkbox + ' ' + item.tokens[0].text;
						if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === 'text') {
							item.tokens[0].tokens[0].text = checkbox + ' ' + item.tokens[0].tokens[0].text;
						}
					}
					else {
						item.tokens.unshift({
							type: 'text',
							raw: checkbox + ' ',
							text: checkbox + ' ',
						});
					}
				}
				else {
					itemBody += checkbox + ' ';
				}
			}
			itemBody += this.parser.parse(item.tokens, !!item.loose);
			return `<li>${itemBody}</li>\n`;
		}
		checkbox({ checked }) {
			return '<input '
				+ (checked ? 'checked="" ' : '')
				+ 'disabled="" type="checkbox">';
		}
		paragraph({ tokens }) {
			return `<p>${this.parser.parseInline(tokens)}</p>\n`;
		}
		table(token) {
			let header = '';
			// header
			let cell = '';
			for (let j = 0; j < token.header.length; j++) {
				cell += this.tablecell(token.header[j]);
			}
			header += this.tablerow({ text: cell });
			let body = '';
			for (let j = 0; j < token.rows.length; j++) {
				const row = token.rows[j];
				cell = '';
				for (let k = 0; k < row.length; k++) {
					cell += this.tablecell(row[k]);
				}
				body += this.tablerow({ text: cell });
			}
			if (body)
				body = `<tbody>${body}</tbody>`;
			return '<table>\n'
				+ '<thead>\n'
				+ header
				+ '</thead>\n'
				+ body
				+ '</table>\n';
		}
		tablerow({ text }) {
			return `<tr>\n${text}</tr>\n`;
		}
		tablecell(token) {
			const content = this.parser.parseInline(token.tokens);
			const type = token.header ? 'th' : 'td';
			const tag = token.align
				? `<${type} align="${token.align}">`
				: `<${type}>`;
			return tag + content + `</${type}>\n`;
		}
		/**
		 * span level renderer
		 */
		strong({ tokens }) {
			return `<strong>${this.parser.parseInline(tokens)}</strong>`;
		}
		em({ tokens }) {
			return `<em>${this.parser.parseInline(tokens)}</em>`;
		}
		codespan({ text }) {
			return `<code>${text}</code>`;
		}
		br(token) {
			return '<br>';
		}
		del({ tokens }) {
			return `<del>${this.parser.parseInline(tokens)}</del>`;
		}
		link({ href, title, tokens }) {
			const text = this.parser.parseInline(tokens);
			const cleanHref = cleanUrl(href);
			if (cleanHref === null) {
				return text;
			}
			href = cleanHref;
			let out = '<a href="' + href + '"';
			if (title) {
				out += ' title="' + title + '"';
			}
			out += '>' + text + '</a>';
			return out;
		}
		image({ href, title, text }) {
			const cleanHref = cleanUrl(href);
			if (cleanHref === null) {
				return text;
			}
			href = cleanHref;
			let out = `<img src="${href}" alt="${text}"`;
			if (title) {
				out += ` title="${title}"`;
			}
			out += '>';
			return out;
		}
		text(token) {
			return 'tokens' in token && token.tokens ? this.parser.parseInline(token.tokens) : token.text;
		}
	}

	/**
	 * TextRenderer
	 * returns only the textual part of the token
	 */
	class _TextRenderer {
		// no need for block level renderers
		strong({ text }) {
			return text;
		}
		em({ text }) {
			return text;
		}
		codespan({ text }) {
			return text;
		}
		del({ text }) {
			return text;
		}
		html({ text }) {
			return text;
		}
		text({ text }) {
			return text;
		}
		link({ text }) {
			return '' + text;
		}
		image({ text }) {
			return '' + text;
		}
		br() {
			return '';
		}
	}

	/**
	 * Parsing & Compiling
	 */
	class _Parser {
		options;
		renderer;
		textRenderer;
		constructor(options) {
			this.options = options || exports.defaults;
			this.options.renderer = this.options.renderer || new _Renderer();
			this.renderer = this.options.renderer;
			this.renderer.options = this.options;
			this.renderer.parser = this;
			this.textRenderer = new _TextRenderer();
		}
		/**
		 * Static Parse Method
		 */
		static parse(tokens, options) {
			const parser = new _Parser(options);
			return parser.parse(tokens);
		}
		/**
		 * Static Parse Inline Method
		 */
		static parseInline(tokens, options) {
			const parser = new _Parser(options);
			return parser.parseInline(tokens);
		}
		/**
		 * Parse Loop
		 */
		parse(tokens, top = true) {
			let out = '';
			for (let i = 0; i < tokens.length; i++) {
				const anyToken = tokens[i];
				// Run any renderer extensions
				if (this.options.extensions && this.options.extensions.renderers && this.options.extensions.renderers[anyToken.type]) {
					const genericToken = anyToken;
					const ret = this.options.extensions.renderers[genericToken.type].call({ parser: this }, genericToken);
					if (ret !== false || !['space', 'hr', 'heading', 'code', 'table', 'blockquote', 'list', 'html', 'paragraph', 'text'].includes(genericToken.type)) {
						out += ret || '';
						continue;
					}
				}
				const token = anyToken;
				switch (token.type) {
					case 'space': {
						out += this.renderer.space(token);
						continue;
					}
					case 'hr': {
						out += this.renderer.hr(token);
						continue;
					}
					case 'heading': {
						out += this.renderer.heading(token);
						continue;
					}
					case 'code': {
						out += this.renderer.code(token);
						continue;
					}
					case 'table': {
						out += this.renderer.table(token);
						continue;
					}
					case 'blockquote': {
						out += this.renderer.blockquote(token);
						continue;
					}
					case 'list': {
						out += this.renderer.list(token);
						continue;
					}
					case 'html': {
						out += this.renderer.html(token);
						continue;
					}
					case 'paragraph': {
						out += this.renderer.paragraph(token);
						continue;
					}
					case 'text': {
						let textToken = token;
						let body = this.renderer.text(textToken);
						while (i + 1 < tokens.length && tokens[i + 1].type === 'text') {
							textToken = tokens[++i];
							body += '\n' + this.renderer.text(textToken);
						}
						if (top) {
							out += this.renderer.paragraph({
								type: 'paragraph',
								raw: body,
								text: body,
								tokens: [{ type: 'text', raw: body, text: body }],
							});
						}
						else {
							out += body;
						}
						continue;
					}
					default: {
						const errMsg = 'Token with "' + token.type + '" type was not found.';
						if (this.options.silent) {
							console.error(errMsg);
							return '';
						}
						else {
							throw new Error(errMsg);
						}
					}
				}
			}
			return out;
		}
		/**
		 * Parse Inline Tokens
		 */
		parseInline(tokens, renderer) {
			renderer = renderer || this.renderer;
			let out = '';
			for (let i = 0; i < tokens.length; i++) {
				const anyToken = tokens[i];
				// Run any renderer extensions
				if (this.options.extensions && this.options.extensions.renderers && this.options.extensions.renderers[anyToken.type]) {
					const ret = this.options.extensions.renderers[anyToken.type].call({ parser: this }, anyToken);
					if (ret !== false || !['escape', 'html', 'link', 'image', 'strong', 'em', 'codespan', 'br', 'del', 'text'].includes(anyToken.type)) {
						out += ret || '';
						continue;
					}
				}
				const token = anyToken;
				switch (token.type) {
					case 'escape': {
						out += renderer.text(token);
						break;
					}
					case 'html': {
						out += renderer.html(token);
						break;
					}
					case 'link': {
						out += renderer.link(token);
						break;
					}
					case 'image': {
						out += renderer.image(token);
						break;
					}
					case 'strong': {
						out += renderer.strong(token);
						break;
					}
					case 'em': {
						out += renderer.em(token);
						break;
					}
					case 'codespan': {
						out += renderer.codespan(token);
						break;
					}
					case 'br': {
						out += renderer.br(token);
						break;
					}
					case 'del': {
						out += renderer.del(token);
						break;
					}
					case 'text': {
						out += renderer.text(token);
						break;
					}
					default: {
						const errMsg = 'Token with "' + token.type + '" type was not found.';
						if (this.options.silent) {
							console.error(errMsg);
							return '';
						}
						else {
							throw new Error(errMsg);
						}
					}
				}
			}
			return out;
		}
	}

	class _Hooks {
		options;
		constructor(options) {
			this.options = options || exports.defaults;
		}
		static passThroughHooks = new Set([
			'preprocess',
			'postprocess',
			'processAllTokens',
		]);
		/**
		 * Process markdown before marked
		 */
		preprocess(markdown) {
			return markdown;
		}
		/**
		 * Process HTML after marked is finished
		 */
		postprocess(html) {
			return html;
		}
		/**
		 * Process all tokens before walk tokens
		 */
		processAllTokens(tokens) {
			return tokens;
		}
	}

	class Marked {
		defaults = _getDefaults();
		options = this.setOptions;
		parse = this.parseMarkdown(_Lexer.lex, _Parser.parse);
		parseInline = this.parseMarkdown(_Lexer.lexInline, _Parser.parseInline);
		Parser = _Parser;
		Renderer = _Renderer;
		TextRenderer = _TextRenderer;
		Lexer = _Lexer;
		Tokenizer = _Tokenizer;
		Hooks = _Hooks;
		constructor(...args) {
			this.use(...args);
		}
		/**
		 * Run callback for every token
		 */
		walkTokens(tokens, callback) {
			let values = [];
			for (const token of tokens) {
				values = values.concat(callback.call(this, token));
				switch (token.type) {
					case 'table': {
						const tableToken = token;
						for (const cell of tableToken.header) {
							values = values.concat(this.walkTokens(cell.tokens, callback));
						}
						for (const row of tableToken.rows) {
							for (const cell of row) {
								values = values.concat(this.walkTokens(cell.tokens, callback));
							}
						}
						break;
					}
					case 'list': {
						const listToken = token;
						values = values.concat(this.walkTokens(listToken.items, callback));
						break;
					}
					default: {
						const genericToken = token;
						if (this.defaults.extensions?.childTokens?.[genericToken.type]) {
							this.defaults.extensions.childTokens[genericToken.type].forEach((childTokens) => {
								const tokens = genericToken[childTokens].flat(Infinity);
								values = values.concat(this.walkTokens(tokens, callback));
							});
						}
						else if (genericToken.tokens) {
							values = values.concat(this.walkTokens(genericToken.tokens, callback));
						}
					}
				}
			}
			return values;
		}
		use(...args) {
			const extensions = this.defaults.extensions || { renderers: {}, childTokens: {} };
			args.forEach((pack) => {
				// copy options to new object
				const opts = { ...pack };
				// set async to true if it was set to true before
				opts.async = this.defaults.async || opts.async || false;
				// ==-- Parse "addon" extensions --== //
				if (pack.extensions) {
					pack.extensions.forEach((ext) => {
						if (!ext.name) {
							throw new Error('extension name required');
						}
						if ('renderer' in ext) { // Renderer extensions
							const prevRenderer = extensions.renderers[ext.name];
							if (prevRenderer) {
								// Replace extension with func to run new extension but fall back if false
								extensions.renderers[ext.name] = function (...args) {
									let ret = ext.renderer.apply(this, args);
									if (ret === false) {
										ret = prevRenderer.apply(this, args);
									}
									return ret;
								};
							}
							else {
								extensions.renderers[ext.name] = ext.renderer;
							}
						}
						if ('tokenizer' in ext) { // Tokenizer Extensions
							if (!ext.level || (ext.level !== 'block' && ext.level !== 'inline')) {
								throw new Error("extension level must be 'block' or 'inline'");
							}
							const extLevel = extensions[ext.level];
							if (extLevel) {
								extLevel.unshift(ext.tokenizer);
							}
							else {
								extensions[ext.level] = [ext.tokenizer];
							}
							if (ext.start) { // Function to check for start of token
								if (ext.level === 'block') {
									if (extensions.startBlock) {
										extensions.startBlock.push(ext.start);
									}
									else {
										extensions.startBlock = [ext.start];
									}
								}
								else if (ext.level === 'inline') {
									if (extensions.startInline) {
										extensions.startInline.push(ext.start);
									}
									else {
										extensions.startInline = [ext.start];
									}
								}
							}
						}
						if ('childTokens' in ext && ext.childTokens) { // Child tokens to be visited by walkTokens
							extensions.childTokens[ext.name] = ext.childTokens;
						}
					});
					opts.extensions = extensions;
				}
				// ==-- Parse "overwrite" extensions --== //
				if (pack.renderer) {
					const renderer = this.defaults.renderer || new _Renderer(this.defaults);
					for (const prop in pack.renderer) {
						if (!(prop in renderer)) {
							throw new Error(`renderer '${prop}' does not exist`);
						}
						if (['options', 'parser'].includes(prop)) {
							// ignore options property
							continue;
						}
						const rendererProp = prop;
						const rendererFunc = pack.renderer[rendererProp];
						const prevRenderer = renderer[rendererProp];
						// Replace renderer with func to run extension, but fall back if false
						renderer[rendererProp] = (...args) => {
							let ret = rendererFunc.apply(renderer, args);
							if (ret === false) {
								ret = prevRenderer.apply(renderer, args);
							}
							return ret || '';
						};
					}
					opts.renderer = renderer;
				}
				if (pack.tokenizer) {
					const tokenizer = this.defaults.tokenizer || new _Tokenizer(this.defaults);
					for (const prop in pack.tokenizer) {
						if (!(prop in tokenizer)) {
							throw new Error(`tokenizer '${prop}' does not exist`);
						}
						if (['options', 'rules', 'lexer'].includes(prop)) {
							// ignore options, rules, and lexer properties
							continue;
						}
						const tokenizerProp = prop;
						const tokenizerFunc = pack.tokenizer[tokenizerProp];
						const prevTokenizer = tokenizer[tokenizerProp];
						// Replace tokenizer with func to run extension, but fall back if false
						// @ts-expect-error cannot type tokenizer function dynamically
						tokenizer[tokenizerProp] = (...args) => {
							let ret = tokenizerFunc.apply(tokenizer, args);
							if (ret === false) {
								ret = prevTokenizer.apply(tokenizer, args);
							}
							return ret;
						};
					}
					opts.tokenizer = tokenizer;
				}
				// ==-- Parse Hooks extensions --== //
				if (pack.hooks) {
					const hooks = this.defaults.hooks || new _Hooks();
					for (const prop in pack.hooks) {
						if (!(prop in hooks)) {
							throw new Error(`hook '${prop}' does not exist`);
						}
						if (prop === 'options') {
							// ignore options property
							continue;
						}
						const hooksProp = prop;
						const hooksFunc = pack.hooks[hooksProp];
						const prevHook = hooks[hooksProp];
						if (_Hooks.passThroughHooks.has(prop)) {
							// @ts-expect-error cannot type hook function dynamically
							hooks[hooksProp] = (arg) => {
								if (this.defaults.async) {
									return Promise.resolve(hooksFunc.call(hooks, arg)).then(ret => {
										return prevHook.call(hooks, ret);
									});
								}
								const ret = hooksFunc.call(hooks, arg);
								return prevHook.call(hooks, ret);
							};
						}
						else {
							// @ts-expect-error cannot type hook function dynamically
							hooks[hooksProp] = (...args) => {
								let ret = hooksFunc.apply(hooks, args);
								if (ret === false) {
									ret = prevHook.apply(hooks, args);
								}
								return ret;
							};
						}
					}
					opts.hooks = hooks;
				}
				// ==-- Parse WalkTokens extensions --== //
				if (pack.walkTokens) {
					const walkTokens = this.defaults.walkTokens;
					const packWalktokens = pack.walkTokens;
					opts.walkTokens = function (token) {
						let values = [];
						values.push(packWalktokens.call(this, token));
						if (walkTokens) {
							values = values.concat(walkTokens.call(this, token));
						}
						return values;
					};
				}
				this.defaults = { ...this.defaults, ...opts };
			});
			return this;
		}
		setOptions(opt) {
			this.defaults = { ...this.defaults, ...opt };
			return this;
		}
		lexer(src, options) {
			return _Lexer.lex(src, options ?? this.defaults);
		}
		parser(tokens, options) {
			return _Parser.parse(tokens, options ?? this.defaults);
		}
		parseMarkdown(lexer, parser) {
			// eslint-disable-next-line @typescript-eslint/no-explicit-any
			const parse = (src, options) => {
				const origOpt = { ...options };
				const opt = { ...this.defaults, ...origOpt };
				const throwError = this.onError(!!opt.silent, !!opt.async);
				// throw error if an extension set async to true but parse was called with async: false
				if (this.defaults.async === true && origOpt.async === false) {
					return throwError(new Error('marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise.'));
				}
				// throw error in case of non string input
				if (typeof src === 'undefined' || src === null) {
					return throwError(new Error('marked(): input parameter is undefined or null'));
				}
				if (typeof src !== 'string') {
					return throwError(new Error('marked(): input parameter is of type '
						+ Object.prototype.toString.call(src) + ', string expected'));
				}
				if (opt.hooks) {
					opt.hooks.options = opt;
				}
				if (opt.async) {
					return Promise.resolve(opt.hooks ? opt.hooks.preprocess(src) : src)
						.then(src => lexer(src, opt))
						.then(tokens => opt.hooks ? opt.hooks.processAllTokens(tokens) : tokens)
						.then(tokens => opt.walkTokens ? Promise.all(this.walkTokens(tokens, opt.walkTokens)).then(() => tokens) : tokens)
						.then(tokens => parser(tokens, opt))
						.then(html => opt.hooks ? opt.hooks.postprocess(html) : html)
						.catch(throwError);
				}
				try {
					if (opt.hooks) {
						src = opt.hooks.preprocess(src);
					}
					let tokens = lexer(src, opt);
					if (opt.hooks) {
						tokens = opt.hooks.processAllTokens(tokens);
					}
					if (opt.walkTokens) {
						this.walkTokens(tokens, opt.walkTokens);
					}
					let html = parser(tokens, opt);
					if (opt.hooks) {
						html = opt.hooks.postprocess(html);
					}
					return html;
				}
				catch (e) {
					return throwError(e);
				}
			};
			return parse;
		}
		onError(silent, async) {
			return (e) => {
				e.message += '\nPlease report this to https://github.com/markedjs/marked.';
				if (silent) {
					const msg = '<p>An error occurred:</p><pre>'
						+ escape$1(e.message + '', true)
						+ '</pre>';
					if (async) {
						return Promise.resolve(msg);
					}
					return msg;
				}
				if (async) {
					return Promise.reject(e);
				}
				throw e;
			};
		}
	}

	const markedInstance = new Marked();
	function marked(src, opt) {
		return markedInstance.parse(src, opt);
	}
	/**
	 * Sets the default options.
	 *
	 * @param options Hash of options
	 */
	marked.options =
		marked.setOptions = function (options) {
			markedInstance.setOptions(options);
			marked.defaults = markedInstance.defaults;
			changeDefaults(marked.defaults);
			return marked;
		};
	/**
	 * Gets the original marked default options.
	 */
	marked.getDefaults = _getDefaults;
	marked.defaults = exports.defaults;
	/**
	 * Use Extension
	 */
	marked.use = function (...args) {
		markedInstance.use(...args);
		marked.defaults = markedInstance.defaults;
		changeDefaults(marked.defaults);
		return marked;
	};
	/**
	 * Run callback for every token
	 */
	marked.walkTokens = function (tokens, callback) {
		return markedInstance.walkTokens(tokens, callback);
	};
	/**
	 * Compiles markdown to HTML without enclosing `p` tag.
	 *
	 * @param src String of markdown source to be compiled
	 * @param options Hash of options
	 * @return String of compiled HTML
	 */
	marked.parseInline = markedInstance.parseInline;
	/**
	 * Expose
	 */
	marked.Parser = _Parser;
	marked.parser = _Parser.parse;
	marked.Renderer = _Renderer;
	marked.TextRenderer = _TextRenderer;
	marked.Lexer = _Lexer;
	marked.lexer = _Lexer.lex;
	marked.Tokenizer = _Tokenizer;
	marked.Hooks = _Hooks;
	marked.parse = marked;
	const options = marked.options;
	const setOptions = marked.setOptions;
	const use = marked.use;
	const walkTokens = marked.walkTokens;
	const parseInline = marked.parseInline;
	const parse = marked;
	const parser = _Parser.parse;
	const lexer = _Lexer.lex;

	exports.Hooks = _Hooks;
	exports.Lexer = _Lexer;
	exports.Marked = Marked;
	exports.Parser = _Parser;
	exports.Renderer = _Renderer;
	exports.TextRenderer = _TextRenderer;
	exports.Tokenizer = _Tokenizer;
	exports.getDefaults = _getDefaults;
	exports.lexer = lexer;
	exports.marked = marked;
	exports.options = options;
	exports.parse = parse;
	exports.parseInline = parseInline;
	exports.parser = parser;
	exports.setOptions = setOptions;
	exports.use = use;
	exports.walkTokens = walkTokens;
}));

// ESM-uncomment-begin
// })();
// export var Hooks = (__marked_exports.Hooks || exports.Hooks);
// export var Lexer = (__marked_exports.Lexer || exports.Lexer);
// export var Marked = (__marked_exports.Marked || exports.Marked);
// export var Parser = (__marked_exports.Parser || exports.Parser);
// export var Renderer = (__marked_exports.Renderer || exports.Renderer);
// export var TextRenderer = (__marked_exports.TextRenderer || exports.TextRenderer);
// export var Tokenizer = (__marked_exports.Tokenizer || exports.Tokenizer);
// export var defaults = (__marked_exports.defaults || exports.defaults);
// export var getDefaults = (__marked_exports.getDefaults || exports.getDefaults);
// export var lexer = (__marked_exports.lexer || exports.lexer);
// export var marked = (__marked_exports.marked || exports.marked);
// export var options = (__marked_exports.options || exports.options);
// export var parse = (__marked_exports.parse || exports.parse);
// export var parseInline = (__marked_exports.parseInline || exports.parseInline);
// export var parser = (__marked_exports.parser || exports.parser);
// export var setOptions = (__marked_exports.setOptions || exports.setOptions);
// export var use = (__marked_exports.use || exports.use);
// export var walkTokens = (__marked_exports.walkTokens || exports.walkTokens);
// ESM-uncomment-end

//# sourceMappingURL=marked.umd.js.map

define(__m[128/*vs/base/common/mime*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Mimes = void 0;
    exports.Mimes = Object.freeze({
        text: 'text/plain',
        binary: 'application/octet-stream',
        unknown: 'application/unknown',
        markdown: 'text/markdown',
        latex: 'text/latex',
        uriList: 'text/uri-list',
    });
});

define(__m[224/*vs/base/browser/dnd*/], __M([1/*require*/,0/*exports*/,128/*vs/base/common/mime*/]), function (require, exports, mime_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DataTransfers = void 0;
    // Common data transfers
    exports.DataTransfers = {
        /**
         * Application specific resource transfer type
         */
        RESOURCES: 'ResourceURLs',
        /**
         * Browser specific transfer type to download
         */
        DOWNLOAD_URL: 'DownloadURL',
        /**
         * Browser specific transfer type for files
         */
        FILES: 'Files',
        /**
         * Typically transfer type for copy/paste transfers.
         */
        TEXT: mime_1.Mimes.text,
        /**
         * Internal type used to pass around text/uri-list data.
         *
         * This is needed to work around https://bugs.chromium.org/p/chromium/issues/detail?id=239745.
         */
        INTERNAL_URI_LIST: 'application/vnd.code.uri-list',
    };
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[448/*vs/base/common/naturalLanguage/korean*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.getKoreanAltChars = getKoreanAltChars;
    // allow-any-unicode-comment-file
    /**
     * Gets alternative Korean characters for the character code. This will return the ascii
     * character code(s) that a Hangul character may have been input with using a qwerty layout.
     *
     * This only aims to cover modern (not archaic) Hangul syllables.
     *
     * @param code The character code to get alternate characters for
     */
    function getKoreanAltChars(code) {
        const result = disassembleKorean(code);
        if (result && result.length > 0) {
            return new Uint32Array(result);
        }
        return undefined;
    }
    let codeBufferLength = 0;
    const codeBuffer = new Uint32Array(10);
    function disassembleKorean(code) {
        codeBufferLength = 0;
        // Initial consonants (초성)
        getCodesFromArray(code, modernConsonants, 4352 /* HangulRangeStartCode.InitialConsonant */);
        if (codeBufferLength > 0) {
            return codeBuffer.subarray(0, codeBufferLength);
        }
        // Vowels (중성)
        getCodesFromArray(code, modernVowels, 4449 /* HangulRangeStartCode.Vowel */);
        if (codeBufferLength > 0) {
            return codeBuffer.subarray(0, codeBufferLength);
        }
        // Final consonants (종성)
        getCodesFromArray(code, modernFinalConsonants, 4520 /* HangulRangeStartCode.FinalConsonant */);
        if (codeBufferLength > 0) {
            return codeBuffer.subarray(0, codeBufferLength);
        }
        // Hangul Compatibility Jamo
        getCodesFromArray(code, compatibilityJamo, 12593 /* HangulRangeStartCode.CompatibilityJamo */);
        if (codeBufferLength) {
            return codeBuffer.subarray(0, codeBufferLength);
        }
        // Hangul Syllables
        if (code >= 0xAC00 && code <= 0xD7A3) {
            const hangulIndex = code - 0xAC00;
            const vowelAndFinalConsonantProduct = hangulIndex % 588;
            // 0-based starting at 0x1100
            const initialConsonantIndex = Math.floor(hangulIndex / 588);
            // 0-based starting at 0x1161
            const vowelIndex = Math.floor(vowelAndFinalConsonantProduct / 28);
            // 0-based starting at 0x11A8
            // Subtract 1 as the standard algorithm uses the 0 index to represent no
            // final consonant
            const finalConsonantIndex = vowelAndFinalConsonantProduct % 28 - 1;
            if (initialConsonantIndex < modernConsonants.length) {
                getCodesFromArray(initialConsonantIndex, modernConsonants, 0);
            }
            else if (4352 /* HangulRangeStartCode.InitialConsonant */ + initialConsonantIndex - 12593 /* HangulRangeStartCode.CompatibilityJamo */ < compatibilityJamo.length) {
                getCodesFromArray(4352 /* HangulRangeStartCode.InitialConsonant */ + initialConsonantIndex, compatibilityJamo, 12593 /* HangulRangeStartCode.CompatibilityJamo */);
            }
            if (vowelIndex < modernVowels.length) {
                getCodesFromArray(vowelIndex, modernVowels, 0);
            }
            else if (4449 /* HangulRangeStartCode.Vowel */ + vowelIndex - 12593 /* HangulRangeStartCode.CompatibilityJamo */ < compatibilityJamo.length) {
                getCodesFromArray(4449 /* HangulRangeStartCode.Vowel */ + vowelIndex - 12593 /* HangulRangeStartCode.CompatibilityJamo */, compatibilityJamo, 12593 /* HangulRangeStartCode.CompatibilityJamo */);
            }
            if (finalConsonantIndex >= 0) {
                if (finalConsonantIndex < modernFinalConsonants.length) {
                    getCodesFromArray(finalConsonantIndex, modernFinalConsonants, 0);
                }
                else if (4520 /* HangulRangeStartCode.FinalConsonant */ + finalConsonantIndex - 12593 /* HangulRangeStartCode.CompatibilityJamo */ < compatibilityJamo.length) {
                    getCodesFromArray(4520 /* HangulRangeStartCode.FinalConsonant */ + finalConsonantIndex - 12593 /* HangulRangeStartCode.CompatibilityJamo */, compatibilityJamo, 12593 /* HangulRangeStartCode.CompatibilityJamo */);
                }
            }
            if (codeBufferLength > 0) {
                return codeBuffer.subarray(0, codeBufferLength);
            }
        }
        return undefined;
    }
    function getCodesFromArray(code, array, arrayStartIndex) {
        // Verify the code is within the array's range
        if (code >= arrayStartIndex && code < arrayStartIndex + array.length) {
            addCodesToBuffer(array[code - arrayStartIndex]);
        }
    }
    function addCodesToBuffer(codes) {
        // NUL is ignored, this is used for archaic characters to avoid using a Map
        // for the data
        if (codes === 0 /* AsciiCode.NUL */) {
            return;
        }
        // Number stored in format: OptionalThirdCode << 16 | OptionalSecondCode << 8 | Code
        codeBuffer[codeBufferLength++] = codes & 0xFF;
        if (codes >> 8) {
            codeBuffer[codeBufferLength++] = (codes >> 8) & 0xFF;
        }
        if (codes >> 16) {
            codeBuffer[codeBufferLength++] = (codes >> 16) & 0xFF;
        }
    }
    /**
     * Hangul Jamo - Modern consonants #1
     *
     * Range U+1100..U+1112
     *
     * |        | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | A | B | C | D | E | F |
     * |--------|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
     * | U+110x | ᄀ | ᄁ | ᄂ | ᄃ | ᄄ | ᄅ | ᄆ | ᄇ | ᄈ | ᄉ | ᄊ | ᄋ | ᄌ | ᄍ | ᄎ | ᄏ |
     * | U+111x | ᄐ | ᄑ | ᄒ |
     */
    const modernConsonants = new Uint8Array([
        114 /* AsciiCode.r */, // ㄱ
        82 /* AsciiCode.R */, // ㄲ
        115 /* AsciiCode.s */, // ㄴ
        101 /* AsciiCode.e */, // ㄷ
        69 /* AsciiCode.E */, // ㄸ
        102 /* AsciiCode.f */, // ㄹ
        97 /* AsciiCode.a */, // ㅁ
        113 /* AsciiCode.q */, // ㅂ
        81 /* AsciiCode.Q */, // ㅃ
        116 /* AsciiCode.t */, // ㅅ
        84 /* AsciiCode.T */, // ㅆ
        100 /* AsciiCode.d */, // ㅇ
        119 /* AsciiCode.w */, // ㅈ
        87 /* AsciiCode.W */, // ㅉ
        99 /* AsciiCode.c */, // ㅊ
        122 /* AsciiCode.z */, // ㅋ
        120 /* AsciiCode.x */, // ㅌ
        118 /* AsciiCode.v */, // ㅍ
        103 /* AsciiCode.g */, // ㅎ
    ]);
    /**
     * Hangul Jamo - Modern Vowels
     *
     * Range U+1161..U+1175
     *
     * |        | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | A | B | C | D | E | F |
     * |--------|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
     * | U+116x |   | ᅡ | ᅢ | ᅣ | ᅤ | ᅥ | ᅦ | ᅧ | ᅨ | ᅩ | ᅪ | ᅫ | ᅬ | ᅭ | ᅮ | ᅯ |
     * | U+117x | ᅰ | ᅱ | ᅲ | ᅳ | ᅴ | ᅵ |
     */
    const modernVowels = new Uint16Array([
        107 /* AsciiCode.k */, //  -> ㅏ
        111 /* AsciiCode.o */, //  -> ㅐ
        105 /* AsciiCode.i */, //  -> ㅑ
        79 /* AsciiCode.O */, //  -> ㅒ
        106 /* AsciiCode.j */, //  -> ㅓ
        112 /* AsciiCode.p */, //  -> ㅔ
        117 /* AsciiCode.u */, //  -> ㅕ
        80 /* AsciiCode.P */, //  -> ㅖ
        104 /* AsciiCode.h */, //  -> ㅗ
        27496 /* AsciiCodeCombo.hk */, //  -> ㅘ
        28520 /* AsciiCodeCombo.ho */, //  -> ㅙ
        27752 /* AsciiCodeCombo.hl */, //  -> ㅚ
        121 /* AsciiCode.y */, //  -> ㅛ
        110 /* AsciiCode.n */, //  -> ㅜ
        27246 /* AsciiCodeCombo.nj */, //  -> ㅝ
        28782 /* AsciiCodeCombo.np */, //  -> ㅞ
        27758 /* AsciiCodeCombo.nl */, //  -> ㅟ
        98 /* AsciiCode.b */, //  -> ㅠ
        109 /* AsciiCode.m */, //  -> ㅡ
        27757 /* AsciiCodeCombo.ml */, //  -> ㅢ
        108 /* AsciiCode.l */, //  -> ㅣ
    ]);
    /**
     * Hangul Jamo - Modern Consonants #2
     *
     * Range U+11A8..U+11C2
     *
     * |        | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | A | B | C | D | E | F |
     * |--------|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
     * | U+11Ax |   |   |   |   |   |   |   |   | ᆨ | ᆩ | ᆪ | ᆫ | ᆬ | ᆭ | ᆮ | ᆯ |
     * | U+11Bx | ᆰ | ᆱ | ᆲ | ᆳ | ᆴ | ᆵ | ᆶ | ᆷ | ᆸ | ᆹ | ᆺ | ᆻ | ᆼ | ᆽ | ᆾ | ᆿ |
     * | U+11Cx | ᇀ | ᇁ | ᇂ |
     */
    const modernFinalConsonants = new Uint16Array([
        114 /* AsciiCode.r */, // ㄱ
        82 /* AsciiCode.R */, // ㄲ
        29810 /* AsciiCodeCombo.rt */, // ㄳ
        115 /* AsciiCode.s */, // ㄴ
        30579 /* AsciiCodeCombo.sw */, // ㄵ
        26483 /* AsciiCodeCombo.sg */, // ㄶ
        101 /* AsciiCode.e */, // ㄷ
        102 /* AsciiCode.f */, // ㄹ
        29286 /* AsciiCodeCombo.fr */, // ㄺ
        24934 /* AsciiCodeCombo.fa */, // ㄻ
        29030 /* AsciiCodeCombo.fq */, // ㄼ
        29798 /* AsciiCodeCombo.ft */, // ㄽ
        30822 /* AsciiCodeCombo.fx */, // ㄾ
        30310 /* AsciiCodeCombo.fv */, // ㄿ
        26470 /* AsciiCodeCombo.fg */, // ㅀ
        97 /* AsciiCode.a */, // ㅁ
        113 /* AsciiCode.q */, // ㅂ
        29809 /* AsciiCodeCombo.qt */, // ㅄ
        116 /* AsciiCode.t */, // ㅅ
        84 /* AsciiCode.T */, // ㅆ
        100 /* AsciiCode.d */, // ㅇ
        119 /* AsciiCode.w */, // ㅈ
        99 /* AsciiCode.c */, // ㅊ
        122 /* AsciiCode.z */, // ㅋ
        120 /* AsciiCode.x */, // ㅌ
        118 /* AsciiCode.v */, // ㅍ
        103 /* AsciiCode.g */, // ㅎ
    ]);
    /**
     * Hangul Compatibility Jamo
     *
     * Range U+3131..U+318F
     *
     * This includes range includes archaic jamo which we don't consider, these are
     * given the NUL character code in order to be ignored.
     *
     * |        | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | A | B | C | D | E | F |
     * |--------|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
     * | U+313x |   | ㄱ | ㄲ | ㄳ | ㄴ | ㄵ | ㄶ | ㄷ | ㄸ | ㄹ | ㄺ | ㄻ | ㄼ | ㄽ | ㄾ | ㄿ |
     * | U+314x | ㅀ | ㅁ | ㅂ | ㅃ | ㅄ | ㅅ | ㅆ | ㅇ | ㅈ | ㅉ | ㅊ | ㅋ | ㅌ | ㅍ | ㅎ | ㅏ |
     * | U+315x | ㅐ | ㅑ | ㅒ | ㅓ | ㅔ | ㅕ | ㅖ | ㅗ | ㅘ | ㅙ | ㅚ | ㅛ | ㅜ | ㅝ | ㅞ | ㅟ |
     * | U+316x | ㅠ | ㅡ | ㅢ | ㅣ | HF | ㅥ | ㅦ | ㅧ | ㅨ | ㅩ | ㅪ | ㅫ | ㅬ | ㅭ | ㅮ | ㅯ |
     * | U+317x | ㅰ | ㅱ | ㅲ | ㅳ | ㅴ | ㅵ | ㅶ | ㅷ | ㅸ | ㅹ | ㅺ | ㅻ | ㅼ | ㅽ | ㅾ | ㅿ |
     * | U+318x | ㆀ | ㆁ | ㆂ | ㆃ | ㆄ | ㆅ | ㆆ | ㆇ | ㆈ | ㆉ | ㆊ | ㆋ | ㆌ | ㆍ | ㆎ |
     */
    const compatibilityJamo = new Uint16Array([
        114 /* AsciiCode.r */, // ㄱ
        82 /* AsciiCode.R */, // ㄲ
        29810 /* AsciiCodeCombo.rt */, // ㄳ
        115 /* AsciiCode.s */, // ㄴ
        30579 /* AsciiCodeCombo.sw */, // ㄵ
        26483 /* AsciiCodeCombo.sg */, // ㄶ
        101 /* AsciiCode.e */, // ㄷ
        69 /* AsciiCode.E */, // ㄸ
        102 /* AsciiCode.f */, // ㄹ
        29286 /* AsciiCodeCombo.fr */, // ㄺ
        24934 /* AsciiCodeCombo.fa */, // ㄻ
        29030 /* AsciiCodeCombo.fq */, // ㄼ
        29798 /* AsciiCodeCombo.ft */, // ㄽ
        30822 /* AsciiCodeCombo.fx */, // ㄾ
        30310 /* AsciiCodeCombo.fv */, // ㄿ
        26470 /* AsciiCodeCombo.fg */, // ㅀ
        97 /* AsciiCode.a */, // ㅁ
        113 /* AsciiCode.q */, // ㅂ
        81 /* AsciiCode.Q */, // ㅃ
        29809 /* AsciiCodeCombo.qt */, // ㅄ
        116 /* AsciiCode.t */, // ㅅ
        84 /* AsciiCode.T */, // ㅆ
        100 /* AsciiCode.d */, // ㅇ
        119 /* AsciiCode.w */, // ㅈ
        87 /* AsciiCode.W */, // ㅉ
        99 /* AsciiCode.c */, // ㅊ
        122 /* AsciiCode.z */, // ㅋ
        120 /* AsciiCode.x */, // ㅌ
        118 /* AsciiCode.v */, // ㅍ
        103 /* AsciiCode.g */, // ㅎ
        107 /* AsciiCode.k */, // ㅏ
        111 /* AsciiCode.o */, // ㅐ
        105 /* AsciiCode.i */, // ㅑ
        79 /* AsciiCode.O */, // ㅒ
        106 /* AsciiCode.j */, // ㅓ
        112 /* AsciiCode.p */, // ㅔ
        117 /* AsciiCode.u */, // ㅕ
        80 /* AsciiCode.P */, // ㅖ
        104 /* AsciiCode.h */, // ㅗ
        27496 /* AsciiCodeCombo.hk */, // ㅘ
        28520 /* AsciiCodeCombo.ho */, // ㅙ
        27752 /* AsciiCodeCombo.hl */, // ㅚ
        121 /* AsciiCode.y */, // ㅛ
        110 /* AsciiCode.n */, // ㅜ
        27246 /* AsciiCodeCombo.nj */, // ㅝ
        28782 /* AsciiCodeCombo.np */, // ㅞ
        27758 /* AsciiCodeCombo.nl */, // ㅟ
        98 /* AsciiCode.b */, // ㅠ
        109 /* AsciiCode.m */, // ㅡ
        27757 /* AsciiCodeCombo.ml */, // ㅢ
        108 /* AsciiCode.l */, // ㅣ
        // HF: Hangul Filler (everything after this is archaic)
        // ㅥ
        // ㅦ
        // ㅧ
        // ㅨ
        // ㅩ
        // ㅪ
        // ㅫ
        // ㅬ
        // ㅮ
        // ㅯ
        // ㅰ
        // ㅱ
        // ㅲ
        // ㅳ
        // ㅴ
        // ㅵ
        // ㅶ
        // ㅷ
        // ㅸ
        // ㅹ
        // ㅺ
        // ㅻ
        // ㅼ
        // ㅽ
        // ㅾ
        // ㅿ
        // ㆀ
        // ㆁ
        // ㆂ
        // ㆃ
        // ㆄ
        // ㆅ
        // ㆆ
        // ㆇ
        // ㆈ
        // ㆉ
        // ㆊ
        // ㆋ
        // ㆌ
        // ㆍ
        // ㆎ
    ]);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[449/*vs/base/common/navigator*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ArrayNavigator = void 0;
    class ArrayNavigator {
        constructor(items, start = 0, end = items.length, index = start - 1) {
            this.items = items;
            this.start = start;
            this.end = end;
            this.index = index;
        }
        current() {
            if (this.index === this.start - 1 || this.index === this.end) {
                return null;
            }
            return this.items[this.index];
        }
        next() {
            this.index = Math.min(this.index + 1, this.end);
            return this.current();
        }
        previous() {
            this.index = Math.max(this.index - 1, this.start - 1);
            return this.current();
        }
        first() {
            this.index = this.start;
            return this.current();
        }
        last() {
            this.index = this.end - 1;
            return this.current();
        }
    }
    exports.ArrayNavigator = ArrayNavigator;
});

define(__m[450/*vs/base/common/history*/], __M([1/*require*/,0/*exports*/,449/*vs/base/common/navigator*/]), function (require, exports, navigator_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.HistoryNavigator = void 0;
    class HistoryNavigator {
        constructor(history = [], limit = 10) {
            this._initialize(history);
            this._limit = limit;
            this._onChange();
        }
        getHistory() {
            return this._elements;
        }
        add(t) {
            this._history.delete(t);
            this._history.add(t);
            this._onChange();
        }
        next() {
            // This will navigate past the end of the last element, and in that case the input should be cleared
            return this._navigator.next();
        }
        previous() {
            if (this._currentPosition() !== 0) {
                return this._navigator.previous();
            }
            return null;
        }
        current() {
            return this._navigator.current();
        }
        first() {
            return this._navigator.first();
        }
        last() {
            return this._navigator.last();
        }
        isLast() {
            return this._currentPosition() >= this._elements.length - 1;
        }
        isNowhere() {
            return this._navigator.current() === null;
        }
        has(t) {
            return this._history.has(t);
        }
        _onChange() {
            this._reduceToLimit();
            const elements = this._elements;
            this._navigator = new navigator_1.ArrayNavigator(elements, 0, elements.length, elements.length);
        }
        _reduceToLimit() {
            const data = this._elements;
            if (data.length > this._limit) {
                this._initialize(data.slice(data.length - this._limit));
            }
        }
        _currentPosition() {
            const currentElement = this._navigator.current();
            if (!currentElement) {
                return -1;
            }
            return this._elements.indexOf(currentElement);
        }
        _initialize(history) {
            this._history = new Set();
            for (const entry of history) {
                this._history.add(entry);
            }
        }
        get _elements() {
            const elements = [];
            this._history.forEach(e => elements.push(e));
            return elements;
        }
    }
    exports.HistoryNavigator = HistoryNavigator;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[141/*vs/base/common/numbers*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SlidingWindowAverage = exports.MovingAverage = void 0;
    exports.clamp = clamp;
    function clamp(value, min, max) {
        return Math.min(Math.max(value, min), max);
    }
    class MovingAverage {
        constructor() {
            this._n = 1;
            this._val = 0;
        }
        update(value) {
            this._val = this._val + (value - this._val) / this._n;
            this._n += 1;
            return this._val;
        }
        get value() {
            return this._val;
        }
    }
    exports.MovingAverage = MovingAverage;
    class SlidingWindowAverage {
        constructor(size) {
            this._n = 0;
            this._val = 0;
            this._values = [];
            this._index = 0;
            this._sum = 0;
            this._values = new Array(size);
            this._values.fill(0, 0, size);
        }
        update(value) {
            const oldValue = this._values[this._index];
            this._values[this._index] = value;
            this._index = (this._index + 1) % this._values.length;
            this._sum -= oldValue;
            this._sum += value;
            if (this._n < this._values.length) {
                this._n += 1;
            }
            this._val = this._sum / this._n;
            return this._val;
        }
        get value() {
            return this._val;
        }
    }
    exports.SlidingWindowAverage = SlidingWindowAverage;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[161/*vs/base/common/observableInternal/debugName*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DebugNameData = void 0;
    exports.getDebugName = getDebugName;
    exports.getFunctionName = getFunctionName;
    class DebugNameData {
        constructor(owner, debugNameSource, referenceFn) {
            this.owner = owner;
            this.debugNameSource = debugNameSource;
            this.referenceFn = referenceFn;
        }
        getDebugName(target) {
            return getDebugName(target, this);
        }
    }
    exports.DebugNameData = DebugNameData;
    const countPerName = new Map();
    const cachedDebugName = new WeakMap();
    function getDebugName(target, data) {
        const cached = cachedDebugName.get(target);
        if (cached) {
            return cached;
        }
        const dbgName = computeDebugName(target, data);
        if (dbgName) {
            let count = countPerName.get(dbgName) ?? 0;
            count++;
            countPerName.set(dbgName, count);
            const result = count === 1 ? dbgName : `${dbgName}#${count}`;
            cachedDebugName.set(target, result);
            return result;
        }
        return undefined;
    }
    function computeDebugName(self, data) {
        const cached = cachedDebugName.get(self);
        if (cached) {
            return cached;
        }
        const ownerStr = data.owner ? formatOwner(data.owner) + `.` : '';
        let result;
        const debugNameSource = data.debugNameSource;
        if (debugNameSource !== undefined) {
            if (typeof debugNameSource === 'function') {
                result = debugNameSource();
                if (result !== undefined) {
                    return ownerStr + result;
                }
            }
            else {
                return ownerStr + debugNameSource;
            }
        }
        const referenceFn = data.referenceFn;
        if (referenceFn !== undefined) {
            result = getFunctionName(referenceFn);
            if (result !== undefined) {
                return ownerStr + result;
            }
        }
        if (data.owner !== undefined) {
            const key = findKey(data.owner, self);
            if (key !== undefined) {
                return ownerStr + key;
            }
        }
        return undefined;
    }
    function findKey(obj, value) {
        for (const key in obj) {
            if (obj[key] === value) {
                return key;
            }
        }
        return undefined;
    }
    const countPerClassName = new Map();
    const ownerId = new WeakMap();
    function formatOwner(owner) {
        const id = ownerId.get(owner);
        if (id) {
            return id;
        }
        const className = getClassName(owner);
        let count = countPerClassName.get(className) ?? 0;
        count++;
        countPerClassName.set(className, count);
        const result = count === 1 ? className : `${className}#${count}`;
        ownerId.set(owner, result);
        return result;
    }
    function getClassName(obj) {
        const ctor = obj.constructor;
        if (ctor) {
            return ctor.name;
        }
        return 'Object';
    }
    function getFunctionName(fn) {
        const fnSrc = fn.toString();
        // Pattern: /** @description ... */
        const regexp = /\/\*\*\s*@description\s*([^*]*)\*\//;
        const match = regexp.exec(fnSrc);
        const result = match ? match[1] : undefined;
        return result?.trim();
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[162/*vs/base/common/observableInternal/logging*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ConsoleObservableLogger = void 0;
    exports.setLogger = setLogger;
    exports.getLogger = getLogger;
    let globalObservableLogger;
    function setLogger(logger) {
        globalObservableLogger = logger;
    }
    function getLogger() {
        return globalObservableLogger;
    }
    class ConsoleObservableLogger {
        constructor() {
            this.indentation = 0;
            this.changedObservablesSets = new WeakMap();
        }
        textToConsoleArgs(text) {
            return consoleTextToArgs([
                normalText(repeat('|  ', this.indentation)),
                text,
            ]);
        }
        formatInfo(info) {
            if (!info.hadValue) {
                return [
                    normalText(` `),
                    styled(formatValue(info.newValue, 60), {
                        color: 'green',
                    }),
                    normalText(` (initial)`),
                ];
            }
            return info.didChange
                ? [
                    normalText(` `),
                    styled(formatValue(info.oldValue, 70), {
                        color: 'red',
                        strikeThrough: true,
                    }),
                    normalText(` `),
                    styled(formatValue(info.newValue, 60), {
                        color: 'green',
                    }),
                ]
                : [normalText(` (unchanged)`)];
        }
        handleObservableChanged(observable, info) {
            console.log(...this.textToConsoleArgs([
                formatKind('observable value changed'),
                styled(observable.debugName, { color: 'BlueViolet' }),
                ...this.formatInfo(info),
            ]));
        }
        formatChanges(changes) {
            if (changes.size === 0) {
                return undefined;
            }
            return styled(' (changed deps: ' +
                [...changes].map((o) => o.debugName).join(', ') +
                ')', { color: 'gray' });
        }
        handleDerivedCreated(derived) {
            const existingHandleChange = derived.handleChange;
            this.changedObservablesSets.set(derived, new Set());
            derived.handleChange = (observable, change) => {
                this.changedObservablesSets.get(derived).add(observable);
                return existingHandleChange.apply(derived, [observable, change]);
            };
        }
        handleDerivedRecomputed(derived, info) {
            const changedObservables = this.changedObservablesSets.get(derived);
            console.log(...this.textToConsoleArgs([
                formatKind('derived recomputed'),
                styled(derived.debugName, { color: 'BlueViolet' }),
                ...this.formatInfo(info),
                this.formatChanges(changedObservables),
                { data: [{ fn: derived._debugNameData.referenceFn ?? derived._computeFn }] }
            ]));
            changedObservables.clear();
        }
        handleFromEventObservableTriggered(observable, info) {
            console.log(...this.textToConsoleArgs([
                formatKind('observable from event triggered'),
                styled(observable.debugName, { color: 'BlueViolet' }),
                ...this.formatInfo(info),
                { data: [{ fn: observable._getValue }] }
            ]));
        }
        handleAutorunCreated(autorun) {
            const existingHandleChange = autorun.handleChange;
            this.changedObservablesSets.set(autorun, new Set());
            autorun.handleChange = (observable, change) => {
                this.changedObservablesSets.get(autorun).add(observable);
                return existingHandleChange.apply(autorun, [observable, change]);
            };
        }
        handleAutorunTriggered(autorun) {
            const changedObservables = this.changedObservablesSets.get(autorun);
            console.log(...this.textToConsoleArgs([
                formatKind('autorun'),
                styled(autorun.debugName, { color: 'BlueViolet' }),
                this.formatChanges(changedObservables),
                { data: [{ fn: autorun._debugNameData.referenceFn ?? autorun._runFn }] }
            ]));
            changedObservables.clear();
            this.indentation++;
        }
        handleAutorunFinished(autorun) {
            this.indentation--;
        }
        handleBeginTransaction(transaction) {
            let transactionName = transaction.getDebugName();
            if (transactionName === undefined) {
                transactionName = '';
            }
            console.log(...this.textToConsoleArgs([
                formatKind('transaction'),
                styled(transactionName, { color: 'BlueViolet' }),
                { data: [{ fn: transaction._fn }] }
            ]));
            this.indentation++;
        }
        handleEndTransaction() {
            this.indentation--;
        }
    }
    exports.ConsoleObservableLogger = ConsoleObservableLogger;
    function consoleTextToArgs(text) {
        const styles = new Array();
        const data = [];
        let firstArg = '';
        function process(t) {
            if ('length' in t) {
                for (const item of t) {
                    if (item) {
                        process(item);
                    }
                }
            }
            else if ('text' in t) {
                firstArg += `%c${t.text}`;
                styles.push(t.style);
                if (t.data) {
                    data.push(...t.data);
                }
            }
            else if ('data' in t) {
                data.push(...t.data);
            }
        }
        process(text);
        const result = [firstArg, ...styles];
        result.push(...data);
        return result;
    }
    function normalText(text) {
        return styled(text, { color: 'black' });
    }
    function formatKind(kind) {
        return styled(padStr(`${kind}: `, 10), { color: 'black', bold: true });
    }
    function styled(text, options = {
        color: 'black',
    }) {
        function objToCss(styleObj) {
            return Object.entries(styleObj).reduce((styleString, [propName, propValue]) => {
                return `${styleString}${propName}:${propValue};`;
            }, '');
        }
        const style = {
            color: options.color,
        };
        if (options.strikeThrough) {
            style['text-decoration'] = 'line-through';
        }
        if (options.bold) {
            style['font-weight'] = 'bold';
        }
        return {
            text,
            style: objToCss(style),
        };
    }
    function formatValue(value, availableLen) {
        switch (typeof value) {
            case 'number':
                return '' + value;
            case 'string':
                if (value.length + 2 <= availableLen) {
                    return `"${value}"`;
                }
                return `"${value.substr(0, availableLen - 7)}"+...`;
            case 'boolean':
                return value ? 'true' : 'false';
            case 'undefined':
                return 'undefined';
            case 'object':
                if (value === null) {
                    return 'null';
                }
                if (Array.isArray(value)) {
                    return formatArray(value, availableLen);
                }
                return formatObject(value, availableLen);
            case 'symbol':
                return value.toString();
            case 'function':
                return `[[Function${value.name ? ' ' + value.name : ''}]]`;
            default:
                return '' + value;
        }
    }
    function formatArray(value, availableLen) {
        let result = '[ ';
        let first = true;
        for (const val of value) {
            if (!first) {
                result += ', ';
            }
            if (result.length - 5 > availableLen) {
                result += '...';
                break;
            }
            first = false;
            result += `${formatValue(val, availableLen - result.length)}`;
        }
        result += ' ]';
        return result;
    }
    function formatObject(value, availableLen) {
        let result = '{ ';
        let first = true;
        for (const [key, val] of Object.entries(value)) {
            if (!first) {
                result += ', ';
            }
            if (result.length - 5 > availableLen) {
                result += '...';
                break;
            }
            first = false;
            result += `${key}: ${formatValue(val, availableLen - result.length)}`;
        }
        result += ' }';
        return result;
    }
    function repeat(str, count) {
        let result = '';
        for (let i = 1; i <= count; i++) {
            result += str;
        }
        return result;
    }
    function padStr(str, length) {
        while (str.length < length) {
            str += ' ';
        }
        return str;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[299/*vs/base/common/observableInternal/autorun*/], __M([1/*require*/,0/*exports*/,90/*vs/base/common/assert*/,2/*vs/base/common/lifecycle*/,161/*vs/base/common/observableInternal/debugName*/,162/*vs/base/common/observableInternal/logging*/]), function (require, exports, assert_1, lifecycle_1, debugName_1, logging_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AutorunObserver = void 0;
    exports.autorun = autorun;
    exports.autorunOpts = autorunOpts;
    exports.autorunHandleChanges = autorunHandleChanges;
    exports.autorunWithStoreHandleChanges = autorunWithStoreHandleChanges;
    exports.autorunWithStore = autorunWithStore;
    /**
     * Runs immediately and whenever a transaction ends and an observed observable changed.
     * {@link fn} should start with a JS Doc using `@description` to name the autorun.
     */
    function autorun(fn) {
        return new AutorunObserver(new debugName_1.DebugNameData(undefined, undefined, fn), fn, undefined, undefined);
    }
    /**
     * Runs immediately and whenever a transaction ends and an observed observable changed.
     * {@link fn} should start with a JS Doc using `@description` to name the autorun.
     */
    function autorunOpts(options, fn) {
        return new AutorunObserver(new debugName_1.DebugNameData(options.owner, options.debugName, options.debugReferenceFn ?? fn), fn, undefined, undefined);
    }
    /**
     * Runs immediately and whenever a transaction ends and an observed observable changed.
     * {@link fn} should start with a JS Doc using `@description` to name the autorun.
     *
     * Use `createEmptyChangeSummary` to create a "change summary" that can collect the changes.
     * Use `handleChange` to add a reported change to the change summary.
     * The run function is given the last change summary.
     * The change summary is discarded after the run function was called.
     *
     * @see autorun
     */
    function autorunHandleChanges(options, fn) {
        return new AutorunObserver(new debugName_1.DebugNameData(options.owner, options.debugName, options.debugReferenceFn ?? fn), fn, options.createEmptyChangeSummary, options.handleChange);
    }
    /**
     * @see autorunHandleChanges (but with a disposable store that is cleared before the next run or on dispose)
     */
    function autorunWithStoreHandleChanges(options, fn) {
        const store = new lifecycle_1.DisposableStore();
        const disposable = autorunHandleChanges({
            owner: options.owner,
            debugName: options.debugName,
            debugReferenceFn: options.debugReferenceFn ?? fn,
            createEmptyChangeSummary: options.createEmptyChangeSummary,
            handleChange: options.handleChange,
        }, (reader, changeSummary) => {
            store.clear();
            fn(reader, changeSummary, store);
        });
        return (0, lifecycle_1.toDisposable)(() => {
            disposable.dispose();
            store.dispose();
        });
    }
    /**
     * @see autorun (but with a disposable store that is cleared before the next run or on dispose)
     */
    function autorunWithStore(fn) {
        const store = new lifecycle_1.DisposableStore();
        const disposable = autorunOpts({
            owner: undefined,
            debugName: undefined,
            debugReferenceFn: fn,
        }, reader => {
            store.clear();
            fn(reader, store);
        });
        return (0, lifecycle_1.toDisposable)(() => {
            disposable.dispose();
            store.dispose();
        });
    }
    class AutorunObserver {
        get debugName() {
            return this._debugNameData.getDebugName(this) ?? '(anonymous)';
        }
        constructor(_debugNameData, _runFn, createChangeSummary, _handleChange) {
            this._debugNameData = _debugNameData;
            this._runFn = _runFn;
            this.createChangeSummary = createChangeSummary;
            this._handleChange = _handleChange;
            this.state = 2 /* AutorunState.stale */;
            this.updateCount = 0;
            this.disposed = false;
            this.dependencies = new Set();
            this.dependenciesToBeRemoved = new Set();
            this.changeSummary = this.createChangeSummary?.();
            (0, logging_1.getLogger)()?.handleAutorunCreated(this);
            this._runIfNeeded();
            (0, lifecycle_1.trackDisposable)(this);
        }
        dispose() {
            this.disposed = true;
            for (const o of this.dependencies) {
                o.removeObserver(this);
            }
            this.dependencies.clear();
            (0, lifecycle_1.markAsDisposed)(this);
        }
        _runIfNeeded() {
            if (this.state === 3 /* AutorunState.upToDate */) {
                return;
            }
            const emptySet = this.dependenciesToBeRemoved;
            this.dependenciesToBeRemoved = this.dependencies;
            this.dependencies = emptySet;
            this.state = 3 /* AutorunState.upToDate */;
            const isDisposed = this.disposed;
            try {
                if (!isDisposed) {
                    (0, logging_1.getLogger)()?.handleAutorunTriggered(this);
                    const changeSummary = this.changeSummary;
                    this.changeSummary = this.createChangeSummary?.();
                    this._runFn(this, changeSummary);
                }
            }
            finally {
                if (!isDisposed) {
                    (0, logging_1.getLogger)()?.handleAutorunFinished(this);
                }
                // We don't want our observed observables to think that they are (not even temporarily) not being observed.
                // Thus, we only unsubscribe from observables that are definitely not read anymore.
                for (const o of this.dependenciesToBeRemoved) {
                    o.removeObserver(this);
                }
                this.dependenciesToBeRemoved.clear();
            }
        }
        toString() {
            return `Autorun<${this.debugName}>`;
        }
        // IObserver implementation
        beginUpdate() {
            if (this.state === 3 /* AutorunState.upToDate */) {
                this.state = 1 /* AutorunState.dependenciesMightHaveChanged */;
            }
            this.updateCount++;
        }
        endUpdate() {
            if (this.updateCount === 1) {
                do {
                    if (this.state === 1 /* AutorunState.dependenciesMightHaveChanged */) {
                        this.state = 3 /* AutorunState.upToDate */;
                        for (const d of this.dependencies) {
                            d.reportChanges();
                            if (this.state === 2 /* AutorunState.stale */) {
                                // The other dependencies will refresh on demand
                                break;
                            }
                        }
                    }
                    this._runIfNeeded();
                } while (this.state !== 3 /* AutorunState.upToDate */);
            }
            this.updateCount--;
            (0, assert_1.assertFn)(() => this.updateCount >= 0);
        }
        handlePossibleChange(observable) {
            if (this.state === 3 /* AutorunState.upToDate */ && this.dependencies.has(observable) && !this.dependenciesToBeRemoved.has(observable)) {
                this.state = 1 /* AutorunState.dependenciesMightHaveChanged */;
            }
        }
        handleChange(observable, change) {
            if (this.dependencies.has(observable) && !this.dependenciesToBeRemoved.has(observable)) {
                const shouldReact = this._handleChange ? this._handleChange({
                    changedObservable: observable,
                    change,
                    didChange: (o) => o === observable,
                }, this.changeSummary) : true;
                if (shouldReact) {
                    this.state = 2 /* AutorunState.stale */;
                }
            }
        }
        // IReader implementation
        readObservable(observable) {
            // In case the run action disposes the autorun
            if (this.disposed) {
                return observable.get();
            }
            observable.addObserver(this);
            const value = observable.get();
            this.dependencies.add(observable);
            this.dependenciesToBeRemoved.delete(observable);
            return value;
        }
    }
    exports.AutorunObserver = AutorunObserver;
    (function (autorun) {
        autorun.Observer = AutorunObserver;
    })(autorun || (exports.autorun = autorun = {}));
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[92/*vs/base/common/observableInternal/base*/], __M([1/*require*/,0/*exports*/,102/*vs/base/common/equals*/,161/*vs/base/common/observableInternal/debugName*/,162/*vs/base/common/observableInternal/logging*/]), function (require, exports, equals_1, debugName_1, logging_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DisposableObservableValue = exports.ObservableValue = exports.TransactionImpl = exports.BaseObservable = exports.ConvenientObservable = void 0;
    exports._setRecomputeInitiallyAndOnChange = _setRecomputeInitiallyAndOnChange;
    exports._setKeepObserved = _setKeepObserved;
    exports._setDerivedOpts = _setDerivedOpts;
    exports.transaction = transaction;
    exports.globalTransaction = globalTransaction;
    exports.asyncTransaction = asyncTransaction;
    exports.subtransaction = subtransaction;
    exports.observableValue = observableValue;
    exports.disposableObservableValue = disposableObservableValue;
    let _recomputeInitiallyAndOnChange;
    function _setRecomputeInitiallyAndOnChange(recomputeInitiallyAndOnChange) {
        _recomputeInitiallyAndOnChange = recomputeInitiallyAndOnChange;
    }
    let _keepObserved;
    function _setKeepObserved(keepObserved) {
        _keepObserved = keepObserved;
    }
    let _derived;
    /**
     * @internal
     * This is to allow splitting files.
    */
    function _setDerivedOpts(derived) {
        _derived = derived;
    }
    class ConvenientObservable {
        get TChange() { return null; }
        reportChanges() {
            this.get();
        }
        /** @sealed */
        read(reader) {
            if (reader) {
                return reader.readObservable(this);
            }
            else {
                return this.get();
            }
        }
        map(fnOrOwner, fnOrUndefined) {
            const owner = fnOrUndefined === undefined ? undefined : fnOrOwner;
            const fn = fnOrUndefined === undefined ? fnOrOwner : fnOrUndefined;
            return _derived({
                owner,
                debugName: () => {
                    const name = (0, debugName_1.getFunctionName)(fn);
                    if (name !== undefined) {
                        return name;
                    }
                    // regexp to match `x => x.y` or `x => x?.y` where x and y can be arbitrary identifiers (uses backref):
                    const regexp = /^\s*\(?\s*([a-zA-Z_$][a-zA-Z_$0-9]*)\s*\)?\s*=>\s*\1(?:\??)\.([a-zA-Z_$][a-zA-Z_$0-9]*)\s*$/;
                    const match = regexp.exec(fn.toString());
                    if (match) {
                        return `${this.debugName}.${match[2]}`;
                    }
                    if (!owner) {
                        return `${this.debugName} (mapped)`;
                    }
                    return undefined;
                },
                debugReferenceFn: fn,
            }, (reader) => fn(this.read(reader), reader));
        }
        /**
         * @sealed
         * Converts an observable of an observable value into a direct observable of the value.
        */
        flatten() {
            return _derived({
                owner: undefined,
                debugName: () => `${this.debugName} (flattened)`,
            }, (reader) => this.read(reader).read(reader));
        }
        recomputeInitiallyAndOnChange(store, handleValue) {
            store.add(_recomputeInitiallyAndOnChange(this, handleValue));
            return this;
        }
        /**
         * Ensures that this observable is observed. This keeps the cache alive.
         * However, in case of deriveds, it does not force eager evaluation (only when the value is read/get).
         * Use `recomputeInitiallyAndOnChange` for eager evaluation.
         */
        keepObserved(store) {
            store.add(_keepObserved(this));
            return this;
        }
    }
    exports.ConvenientObservable = ConvenientObservable;
    class BaseObservable extends ConvenientObservable {
        constructor() {
            super(...arguments);
            this.observers = new Set();
        }
        addObserver(observer) {
            const len = this.observers.size;
            this.observers.add(observer);
            if (len === 0) {
                this.onFirstObserverAdded();
            }
        }
        removeObserver(observer) {
            const deleted = this.observers.delete(observer);
            if (deleted && this.observers.size === 0) {
                this.onLastObserverRemoved();
            }
        }
        onFirstObserverAdded() { }
        onLastObserverRemoved() { }
    }
    exports.BaseObservable = BaseObservable;
    /**
     * Starts a transaction in which many observables can be changed at once.
     * {@link fn} should start with a JS Doc using `@description` to give the transaction a debug name.
     * Reaction run on demand or when the transaction ends.
     */
    function transaction(fn, getDebugName) {
        const tx = new TransactionImpl(fn, getDebugName);
        try {
            fn(tx);
        }
        finally {
            tx.finish();
        }
    }
    let _globalTransaction = undefined;
    function globalTransaction(fn) {
        if (_globalTransaction) {
            fn(_globalTransaction);
        }
        else {
            const tx = new TransactionImpl(fn, undefined);
            _globalTransaction = tx;
            try {
                fn(tx);
            }
            finally {
                tx.finish(); // During finish, more actions might be added to the transaction.
                // Which is why we only clear the global transaction after finish.
                _globalTransaction = undefined;
            }
        }
    }
    async function asyncTransaction(fn, getDebugName) {
        const tx = new TransactionImpl(fn, getDebugName);
        try {
            await fn(tx);
        }
        finally {
            tx.finish();
        }
    }
    /**
     * Allows to chain transactions.
     */
    function subtransaction(tx, fn, getDebugName) {
        if (!tx) {
            transaction(fn, getDebugName);
        }
        else {
            fn(tx);
        }
    }
    class TransactionImpl {
        constructor(_fn, _getDebugName) {
            this._fn = _fn;
            this._getDebugName = _getDebugName;
            this.updatingObservers = [];
            (0, logging_1.getLogger)()?.handleBeginTransaction(this);
        }
        getDebugName() {
            if (this._getDebugName) {
                return this._getDebugName();
            }
            return (0, debugName_1.getFunctionName)(this._fn);
        }
        updateObserver(observer, observable) {
            // When this gets called while finish is active, they will still get considered
            this.updatingObservers.push({ observer, observable });
            observer.beginUpdate(observable);
        }
        finish() {
            const updatingObservers = this.updatingObservers;
            for (let i = 0; i < updatingObservers.length; i++) {
                const { observer, observable } = updatingObservers[i];
                observer.endUpdate(observable);
            }
            // Prevent anyone from updating observers from now on.
            this.updatingObservers = null;
            (0, logging_1.getLogger)()?.handleEndTransaction();
        }
    }
    exports.TransactionImpl = TransactionImpl;
    function observableValue(nameOrOwner, initialValue) {
        let debugNameData;
        if (typeof nameOrOwner === 'string') {
            debugNameData = new debugName_1.DebugNameData(undefined, nameOrOwner, undefined);
        }
        else {
            debugNameData = new debugName_1.DebugNameData(nameOrOwner, undefined, undefined);
        }
        return new ObservableValue(debugNameData, initialValue, equals_1.strictEquals);
    }
    class ObservableValue extends BaseObservable {
        get debugName() {
            return this._debugNameData.getDebugName(this) ?? 'ObservableValue';
        }
        constructor(_debugNameData, initialValue, _equalityComparator) {
            super();
            this._debugNameData = _debugNameData;
            this._equalityComparator = _equalityComparator;
            this._value = initialValue;
        }
        get() {
            return this._value;
        }
        set(value, tx, change) {
            if (change === undefined && this._equalityComparator(this._value, value)) {
                return;
            }
            let _tx;
            if (!tx) {
                tx = _tx = new TransactionImpl(() => { }, () => `Setting ${this.debugName}`);
            }
            try {
                const oldValue = this._value;
                this._setValue(value);
                (0, logging_1.getLogger)()?.handleObservableChanged(this, { oldValue, newValue: value, change, didChange: true, hadValue: true });
                for (const observer of this.observers) {
                    tx.updateObserver(observer, this);
                    observer.handleChange(this, change);
                }
            }
            finally {
                if (_tx) {
                    _tx.finish();
                }
            }
        }
        toString() {
            return `${this.debugName}: ${this._value}`;
        }
        _setValue(newValue) {
            this._value = newValue;
        }
    }
    exports.ObservableValue = ObservableValue;
    /**
     * A disposable observable. When disposed, its value is also disposed.
     * When a new value is set, the previous value is disposed.
     */
    function disposableObservableValue(nameOrOwner, initialValue) {
        let debugNameData;
        if (typeof nameOrOwner === 'string') {
            debugNameData = new debugName_1.DebugNameData(undefined, nameOrOwner, undefined);
        }
        else {
            debugNameData = new debugName_1.DebugNameData(nameOrOwner, undefined, undefined);
        }
        return new DisposableObservableValue(debugNameData, initialValue, equals_1.strictEquals);
    }
    class DisposableObservableValue extends ObservableValue {
        _setValue(newValue) {
            if (this._value === newValue) {
                return;
            }
            if (this._value) {
                this._value.dispose();
            }
            this._value = newValue;
        }
        dispose() {
            this._value?.dispose();
        }
    }
    exports.DisposableObservableValue = DisposableObservableValue;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[65/*vs/base/common/observableInternal/derived*/], __M([1/*require*/,0/*exports*/,90/*vs/base/common/assert*/,102/*vs/base/common/equals*/,2/*vs/base/common/lifecycle*/,92/*vs/base/common/observableInternal/base*/,161/*vs/base/common/observableInternal/debugName*/,162/*vs/base/common/observableInternal/logging*/]), function (require, exports, assert_1, equals_1, lifecycle_1, base_1, debugName_1, logging_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DerivedWithSetter = exports.Derived = void 0;
    exports.derived = derived;
    exports.derivedWithSetter = derivedWithSetter;
    exports.derivedOpts = derivedOpts;
    exports.derivedHandleChanges = derivedHandleChanges;
    exports.derivedWithStore = derivedWithStore;
    exports.derivedDisposable = derivedDisposable;
    function derived(computeFnOrOwner, computeFn) {
        if (computeFn !== undefined) {
            return new Derived(new debugName_1.DebugNameData(computeFnOrOwner, undefined, computeFn), computeFn, undefined, undefined, undefined, equals_1.strictEquals);
        }
        return new Derived(new debugName_1.DebugNameData(undefined, undefined, computeFnOrOwner), computeFnOrOwner, undefined, undefined, undefined, equals_1.strictEquals);
    }
    function derivedWithSetter(owner, computeFn, setter) {
        return new DerivedWithSetter(new debugName_1.DebugNameData(owner, undefined, computeFn), computeFn, undefined, undefined, undefined, equals_1.strictEquals, setter);
    }
    function derivedOpts(options, computeFn) {
        return new Derived(new debugName_1.DebugNameData(options.owner, options.debugName, options.debugReferenceFn), computeFn, undefined, undefined, options.onLastObserverRemoved, options.equalsFn ?? equals_1.strictEquals);
    }
    (0, base_1._setDerivedOpts)(derivedOpts);
    /**
     * Represents an observable that is derived from other observables.
     * The value is only recomputed when absolutely needed.
     *
     * {@link computeFn} should start with a JS Doc using `@description` to name the derived.
     *
     * Use `createEmptyChangeSummary` to create a "change summary" that can collect the changes.
     * Use `handleChange` to add a reported change to the change summary.
     * The compute function is given the last change summary.
     * The change summary is discarded after the compute function was called.
     *
     * @see derived
     */
    function derivedHandleChanges(options, computeFn) {
        return new Derived(new debugName_1.DebugNameData(options.owner, options.debugName, undefined), computeFn, options.createEmptyChangeSummary, options.handleChange, undefined, options.equalityComparer ?? equals_1.strictEquals);
    }
    function derivedWithStore(computeFnOrOwner, computeFnOrUndefined) {
        let computeFn;
        let owner;
        if (computeFnOrUndefined === undefined) {
            computeFn = computeFnOrOwner;
            owner = undefined;
        }
        else {
            owner = computeFnOrOwner;
            computeFn = computeFnOrUndefined;
        }
        const store = new lifecycle_1.DisposableStore();
        return new Derived(new debugName_1.DebugNameData(owner, undefined, computeFn), r => {
            store.clear();
            return computeFn(r, store);
        }, undefined, undefined, () => store.dispose(), equals_1.strictEquals);
    }
    function derivedDisposable(computeFnOrOwner, computeFnOrUndefined) {
        let computeFn;
        let owner;
        if (computeFnOrUndefined === undefined) {
            computeFn = computeFnOrOwner;
            owner = undefined;
        }
        else {
            owner = computeFnOrOwner;
            computeFn = computeFnOrUndefined;
        }
        let store = undefined;
        return new Derived(new debugName_1.DebugNameData(owner, undefined, computeFn), r => {
            if (!store) {
                store = new lifecycle_1.DisposableStore();
            }
            else {
                store.clear();
            }
            const result = computeFn(r);
            if (result) {
                store.add(result);
            }
            return result;
        }, undefined, undefined, () => {
            if (store) {
                store.dispose();
                store = undefined;
            }
        }, equals_1.strictEquals);
    }
    class Derived extends base_1.BaseObservable {
        get debugName() {
            return this._debugNameData.getDebugName(this) ?? '(anonymous)';
        }
        constructor(_debugNameData, _computeFn, createChangeSummary, _handleChange, _handleLastObserverRemoved = undefined, _equalityComparator) {
            super();
            this._debugNameData = _debugNameData;
            this._computeFn = _computeFn;
            this.createChangeSummary = createChangeSummary;
            this._handleChange = _handleChange;
            this._handleLastObserverRemoved = _handleLastObserverRemoved;
            this._equalityComparator = _equalityComparator;
            this.state = 0 /* DerivedState.initial */;
            this.value = undefined;
            this.updateCount = 0;
            this.dependencies = new Set();
            this.dependenciesToBeRemoved = new Set();
            this.changeSummary = undefined;
            this.changeSummary = this.createChangeSummary?.();
            (0, logging_1.getLogger)()?.handleDerivedCreated(this);
        }
        onLastObserverRemoved() {
            /**
             * We are not tracking changes anymore, thus we have to assume
             * that our cache is invalid.
             */
            this.state = 0 /* DerivedState.initial */;
            this.value = undefined;
            for (const d of this.dependencies) {
                d.removeObserver(this);
            }
            this.dependencies.clear();
            this._handleLastObserverRemoved?.();
        }
        get() {
            if (this.observers.size === 0) {
                // Without observers, we don't know when to clean up stuff.
                // Thus, we don't cache anything to prevent memory leaks.
                const result = this._computeFn(this, this.createChangeSummary?.());
                // Clear new dependencies
                this.onLastObserverRemoved();
                return result;
            }
            else {
                do {
                    // We might not get a notification for a dependency that changed while it is updating,
                    // thus we also have to ask all our depedencies if they changed in this case.
                    if (this.state === 1 /* DerivedState.dependenciesMightHaveChanged */) {
                        for (const d of this.dependencies) {
                            /** might call {@link handleChange} indirectly, which could make us stale */
                            d.reportChanges();
                            if (this.state === 2 /* DerivedState.stale */) {
                                // The other dependencies will refresh on demand, so early break
                                break;
                            }
                        }
                    }
                    // We called report changes of all dependencies.
                    // If we are still not stale, we can assume to be up to date again.
                    if (this.state === 1 /* DerivedState.dependenciesMightHaveChanged */) {
                        this.state = 3 /* DerivedState.upToDate */;
                    }
                    this._recomputeIfNeeded();
                    // In case recomputation changed one of our dependencies, we need to recompute again.
                } while (this.state !== 3 /* DerivedState.upToDate */);
                return this.value;
            }
        }
        _recomputeIfNeeded() {
            if (this.state === 3 /* DerivedState.upToDate */) {
                return;
            }
            const emptySet = this.dependenciesToBeRemoved;
            this.dependenciesToBeRemoved = this.dependencies;
            this.dependencies = emptySet;
            const hadValue = this.state !== 0 /* DerivedState.initial */;
            const oldValue = this.value;
            this.state = 3 /* DerivedState.upToDate */;
            const changeSummary = this.changeSummary;
            this.changeSummary = this.createChangeSummary?.();
            try {
                /** might call {@link handleChange} indirectly, which could invalidate us */
                this.value = this._computeFn(this, changeSummary);
            }
            finally {
                // We don't want our observed observables to think that they are (not even temporarily) not being observed.
                // Thus, we only unsubscribe from observables that are definitely not read anymore.
                for (const o of this.dependenciesToBeRemoved) {
                    o.removeObserver(this);
                }
                this.dependenciesToBeRemoved.clear();
            }
            const didChange = hadValue && !(this._equalityComparator(oldValue, this.value));
            (0, logging_1.getLogger)()?.handleDerivedRecomputed(this, {
                oldValue,
                newValue: this.value,
                change: undefined,
                didChange,
                hadValue,
            });
            if (didChange) {
                for (const r of this.observers) {
                    r.handleChange(this, undefined);
                }
            }
        }
        toString() {
            return `LazyDerived<${this.debugName}>`;
        }
        // IObserver Implementation
        beginUpdate(_observable) {
            this.updateCount++;
            const propagateBeginUpdate = this.updateCount === 1;
            if (this.state === 3 /* DerivedState.upToDate */) {
                this.state = 1 /* DerivedState.dependenciesMightHaveChanged */;
                // If we propagate begin update, that will already signal a possible change.
                if (!propagateBeginUpdate) {
                    for (const r of this.observers) {
                        r.handlePossibleChange(this);
                    }
                }
            }
            if (propagateBeginUpdate) {
                for (const r of this.observers) {
                    r.beginUpdate(this); // This signals a possible change
                }
            }
        }
        endUpdate(_observable) {
            this.updateCount--;
            if (this.updateCount === 0) {
                // End update could change the observer list.
                const observers = [...this.observers];
                for (const r of observers) {
                    r.endUpdate(this);
                }
            }
            (0, assert_1.assertFn)(() => this.updateCount >= 0);
        }
        handlePossibleChange(observable) {
            // In all other states, observers already know that we might have changed.
            if (this.state === 3 /* DerivedState.upToDate */ && this.dependencies.has(observable) && !this.dependenciesToBeRemoved.has(observable)) {
                this.state = 1 /* DerivedState.dependenciesMightHaveChanged */;
                for (const r of this.observers) {
                    r.handlePossibleChange(this);
                }
            }
        }
        handleChange(observable, change) {
            if (this.dependencies.has(observable) && !this.dependenciesToBeRemoved.has(observable)) {
                const shouldReact = this._handleChange ? this._handleChange({
                    changedObservable: observable,
                    change,
                    didChange: (o) => o === observable,
                }, this.changeSummary) : true;
                const wasUpToDate = this.state === 3 /* DerivedState.upToDate */;
                if (shouldReact && (this.state === 1 /* DerivedState.dependenciesMightHaveChanged */ || wasUpToDate)) {
                    this.state = 2 /* DerivedState.stale */;
                    if (wasUpToDate) {
                        for (const r of this.observers) {
                            r.handlePossibleChange(this);
                        }
                    }
                }
            }
        }
        // IReader Implementation
        readObservable(observable) {
            // Subscribe before getting the value to enable caching
            observable.addObserver(this);
            /** This might call {@link handleChange} indirectly, which could invalidate us */
            const value = observable.get();
            // Which is why we only add the observable to the dependencies now.
            this.dependencies.add(observable);
            this.dependenciesToBeRemoved.delete(observable);
            return value;
        }
        addObserver(observer) {
            const shouldCallBeginUpdate = !this.observers.has(observer) && this.updateCount > 0;
            super.addObserver(observer);
            if (shouldCallBeginUpdate) {
                observer.beginUpdate(this);
            }
        }
        removeObserver(observer) {
            const shouldCallEndUpdate = this.observers.has(observer) && this.updateCount > 0;
            super.removeObserver(observer);
            if (shouldCallEndUpdate) {
                // Calling end update after removing the observer makes sure endUpdate cannot be called twice here.
                observer.endUpdate(this);
            }
        }
    }
    exports.Derived = Derived;
    class DerivedWithSetter extends Derived {
        constructor(debugNameData, computeFn, createChangeSummary, handleChange, handleLastObserverRemoved = undefined, equalityComparator, set) {
            super(debugNameData, computeFn, createChangeSummary, handleChange, handleLastObserverRemoved, equalityComparator);
            this.set = set;
        }
    }
    exports.DerivedWithSetter = DerivedWithSetter;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[451/*vs/base/common/observableInternal/lazyObservableValue*/], __M([1/*require*/,0/*exports*/,92/*vs/base/common/observableInternal/base*/]), function (require, exports, base_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.LazyObservableValue = void 0;
    /**
     * Holds off updating observers until the value is actually read.
    */
    class LazyObservableValue extends base_1.BaseObservable {
        get debugName() {
            return this._debugNameData.getDebugName(this) ?? 'LazyObservableValue';
        }
        constructor(_debugNameData, initialValue, _equalityComparator) {
            super();
            this._debugNameData = _debugNameData;
            this._equalityComparator = _equalityComparator;
            this._isUpToDate = true;
            this._deltas = [];
            this._updateCounter = 0;
            this._value = initialValue;
        }
        get() {
            this._update();
            return this._value;
        }
        _update() {
            if (this._isUpToDate) {
                return;
            }
            this._isUpToDate = true;
            if (this._deltas.length > 0) {
                for (const observer of this.observers) {
                    for (const change of this._deltas) {
                        observer.handleChange(this, change);
                    }
                }
                this._deltas.length = 0;
            }
            else {
                for (const observer of this.observers) {
                    observer.handleChange(this, undefined);
                }
            }
        }
        _beginUpdate() {
            this._updateCounter++;
            if (this._updateCounter === 1) {
                for (const observer of this.observers) {
                    observer.beginUpdate(this);
                }
            }
        }
        _endUpdate() {
            this._updateCounter--;
            if (this._updateCounter === 0) {
                this._update();
                // End update could change the observer list.
                const observers = [...this.observers];
                for (const r of observers) {
                    r.endUpdate(this);
                }
            }
        }
        addObserver(observer) {
            const shouldCallBeginUpdate = !this.observers.has(observer) && this._updateCounter > 0;
            super.addObserver(observer);
            if (shouldCallBeginUpdate) {
                observer.beginUpdate(this);
            }
        }
        removeObserver(observer) {
            const shouldCallEndUpdate = this.observers.has(observer) && this._updateCounter > 0;
            super.removeObserver(observer);
            if (shouldCallEndUpdate) {
                // Calling end update after removing the observer makes sure endUpdate cannot be called twice here.
                observer.endUpdate(this);
            }
        }
        set(value, tx, change) {
            if (change === undefined && this._equalityComparator(this._value, value)) {
                return;
            }
            let _tx;
            if (!tx) {
                tx = _tx = new base_1.TransactionImpl(() => { }, () => `Setting ${this.debugName}`);
            }
            try {
                this._isUpToDate = false;
                this._setValue(value);
                if (change !== undefined) {
                    this._deltas.push(change);
                }
                tx.updateObserver({
                    beginUpdate: () => this._beginUpdate(),
                    endUpdate: () => this._endUpdate(),
                    handleChange: (observable, change) => { },
                    handlePossibleChange: (observable) => { },
                }, this);
                if (this._updateCounter > 1) {
                    // We already started begin/end update, so we need to manually call handlePossibleChange
                    for (const observer of this.observers) {
                        observer.handlePossibleChange(this);
                    }
                }
            }
            finally {
                if (_tx) {
                    _tx.finish();
                }
            }
        }
        toString() {
            return `${this.debugName}: ${this._value}`;
        }
        _setValue(newValue) {
            this._value = newValue;
        }
    }
    exports.LazyObservableValue = LazyObservableValue;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[452/*vs/base/common/observableInternal/api*/], __M([1/*require*/,0/*exports*/,102/*vs/base/common/equals*/,92/*vs/base/common/observableInternal/base*/,161/*vs/base/common/observableInternal/debugName*/,451/*vs/base/common/observableInternal/lazyObservableValue*/]), function (require, exports, equals_1, base_1, debugName_1, lazyObservableValue_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.observableValueOpts = observableValueOpts;
    function observableValueOpts(options, initialValue) {
        if (options.lazy) {
            return new lazyObservableValue_1.LazyObservableValue(new debugName_1.DebugNameData(options.owner, options.debugName, undefined), initialValue, options.equalsFn ?? equals_1.strictEquals);
        }
        return new base_1.ObservableValue(new debugName_1.DebugNameData(options.owner, options.debugName, undefined), initialValue, options.equalsFn ?? equals_1.strictEquals);
    }
});

define(__m[453/*vs/base/common/observableInternal/promise*/], __M([1/*require*/,0/*exports*/,299/*vs/base/common/observableInternal/autorun*/,92/*vs/base/common/observableInternal/base*/,8/*vs/base/common/errors*/]), function (require, exports, autorun_1, base_1, errors_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.PromiseResult = exports.ObservablePromise = void 0;
    exports.waitForState = waitForState;
    /**
     * A promise whose state is observable.
     */
    class ObservablePromise {
        static fromFn(fn) {
            return new ObservablePromise(fn());
        }
        constructor(promise) {
            this._value = (0, base_1.observableValue)(this, undefined);
            /**
             * The current state of the promise.
             * Is `undefined` if the promise didn't resolve yet.
             */
            this.promiseResult = this._value;
            this.promise = promise.then(value => {
                (0, base_1.transaction)(tx => {
                    /** @description onPromiseResolved */
                    this._value.set(new PromiseResult(value, undefined), tx);
                });
                return value;
            }, error => {
                (0, base_1.transaction)(tx => {
                    /** @description onPromiseRejected */
                    this._value.set(new PromiseResult(undefined, error), tx);
                });
                throw error;
            });
        }
    }
    exports.ObservablePromise = ObservablePromise;
    class PromiseResult {
        constructor(
        /**
         * The value of the resolved promise.
         * Undefined if the promise rejected.
         */
        data, 
        /**
         * The error in case of a rejected promise.
         * Undefined if the promise resolved.
         */
        error) {
            this.data = data;
            this.error = error;
        }
    }
    exports.PromiseResult = PromiseResult;
    function waitForState(observable, predicate, isError, cancellationToken) {
        if (!predicate) {
            predicate = state => state !== null && state !== undefined;
        }
        return new Promise((resolve, reject) => {
            let isImmediateRun = true;
            let shouldDispose = false;
            const stateObs = observable.map(state => {
                /** @description waitForState.state */
                return {
                    isFinished: predicate(state),
                    error: isError ? isError(state) : false,
                    state
                };
            });
            const d = (0, autorun_1.autorun)(reader => {
                /** @description waitForState */
                const { isFinished, error, state } = stateObs.read(reader);
                if (isFinished || error) {
                    if (isImmediateRun) {
                        // The variable `d` is not initialized yet
                        shouldDispose = true;
                    }
                    else {
                        d.dispose();
                    }
                    if (error) {
                        reject(error === true ? state : error);
                    }
                    else {
                        resolve(state);
                    }
                }
            });
            if (cancellationToken) {
                const dc = cancellationToken.onCancellationRequested(() => {
                    d.dispose();
                    dc.dispose();
                    reject(new errors_1.CancellationError());
                });
                if (cancellationToken.isCancellationRequested) {
                    d.dispose();
                    dc.dispose();
                    reject(new errors_1.CancellationError());
                    return;
                }
            }
            isImmediateRun = false;
            if (shouldDispose) {
                d.dispose();
            }
        });
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[188/*vs/base/common/range*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Range = void 0;
    var Range;
    (function (Range) {
        /**
         * Returns the intersection between two ranges as a range itself.
         * Returns `{ start: 0, end: 0 }` if the intersection is empty.
         */
        function intersect(one, other) {
            if (one.start >= other.end || other.start >= one.end) {
                return { start: 0, end: 0 };
            }
            const start = Math.max(one.start, other.start);
            const end = Math.min(one.end, other.end);
            if (end - start <= 0) {
                return { start: 0, end: 0 };
            }
            return { start, end };
        }
        Range.intersect = intersect;
        function isEmpty(range) {
            return range.end - range.start <= 0;
        }
        Range.isEmpty = isEmpty;
        function intersects(one, other) {
            return !isEmpty(intersect(one, other));
        }
        Range.intersects = intersects;
        function relativeComplement(one, other) {
            const result = [];
            const first = { start: one.start, end: Math.min(other.start, one.end) };
            const second = { start: Math.max(other.end, one.start), end: one.end };
            if (!isEmpty(first)) {
                result.push(first);
            }
            if (!isEmpty(second)) {
                result.push(second);
            }
            return result;
        }
        Range.relativeComplement = relativeComplement;
    })(Range || (exports.Range = Range = {}));
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[454/*vs/base/browser/ui/list/rangeMap*/], __M([1/*require*/,0/*exports*/,188/*vs/base/common/range*/]), function (require, exports, range_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.RangeMap = void 0;
    exports.groupIntersect = groupIntersect;
    exports.shift = shift;
    exports.consolidate = consolidate;
    /**
     * Returns the intersection between a ranged group and a range.
     * Returns `[]` if the intersection is empty.
     */
    function groupIntersect(range, groups) {
        const result = [];
        for (const r of groups) {
            if (range.start >= r.range.end) {
                continue;
            }
            if (range.end < r.range.start) {
                break;
            }
            const intersection = range_1.Range.intersect(range, r.range);
            if (range_1.Range.isEmpty(intersection)) {
                continue;
            }
            result.push({
                range: intersection,
                size: r.size
            });
        }
        return result;
    }
    /**
     * Shifts a range by that `much`.
     */
    function shift({ start, end }, much) {
        return { start: start + much, end: end + much };
    }
    /**
     * Consolidates a collection of ranged groups.
     *
     * Consolidation is the process of merging consecutive ranged groups
     * that share the same `size`.
     */
    function consolidate(groups) {
        const result = [];
        let previousGroup = null;
        for (const group of groups) {
            const start = group.range.start;
            const end = group.range.end;
            const size = group.size;
            if (previousGroup && size === previousGroup.size) {
                previousGroup.range.end = end;
                continue;
            }
            previousGroup = { range: { start, end }, size };
            result.push(previousGroup);
        }
        return result;
    }
    /**
     * Concatenates several collections of ranged groups into a single
     * collection.
     */
    function concat(...groups) {
        return consolidate(groups.reduce((r, g) => r.concat(g), []));
    }
    class RangeMap {
        get paddingTop() {
            return this._paddingTop;
        }
        set paddingTop(paddingTop) {
            this._size = this._size + paddingTop - this._paddingTop;
            this._paddingTop = paddingTop;
        }
        constructor(topPadding) {
            this.groups = [];
            this._size = 0;
            this._paddingTop = 0;
            this._paddingTop = topPadding ?? 0;
            this._size = this._paddingTop;
        }
        splice(index, deleteCount, items = []) {
            const diff = items.length - deleteCount;
            const before = groupIntersect({ start: 0, end: index }, this.groups);
            const after = groupIntersect({ start: index + deleteCount, end: Number.POSITIVE_INFINITY }, this.groups)
                .map(g => ({ range: shift(g.range, diff), size: g.size }));
            const middle = items.map((item, i) => ({
                range: { start: index + i, end: index + i + 1 },
                size: item.size
            }));
            this.groups = concat(before, middle, after);
            this._size = this._paddingTop + this.groups.reduce((t, g) => t + (g.size * (g.range.end - g.range.start)), 0);
        }
        /**
         * Returns the number of items in the range map.
         */
        get count() {
            const len = this.groups.length;
            if (!len) {
                return 0;
            }
            return this.groups[len - 1].range.end;
        }
        /**
         * Returns the sum of the sizes of all items in the range map.
         */
        get size() {
            return this._size;
        }
        /**
         * Returns the index of the item at the given position.
         */
        indexAt(position) {
            if (position < 0) {
                return -1;
            }
            if (position < this._paddingTop) {
                return 0;
            }
            let index = 0;
            let size = this._paddingTop;
            for (const group of this.groups) {
                const count = group.range.end - group.range.start;
                const newSize = size + (count * group.size);
                if (position < newSize) {
                    return index + Math.floor((position - size) / group.size);
                }
                index += count;
                size = newSize;
            }
            return index;
        }
        /**
         * Returns the index of the item right after the item at the
         * index of the given position.
         */
        indexAfter(position) {
            return Math.min(this.indexAt(position) + 1, this.count);
        }
        /**
         * Returns the start position of the item at the given index.
         */
        positionAt(index) {
            if (index < 0) {
                return -1;
            }
            let position = 0;
            let count = 0;
            for (const group of this.groups) {
                const groupCount = group.range.end - group.range.start;
                const newCount = count + groupCount;
                if (index < newCount) {
                    return this._paddingTop + position + ((index - count) * group.size);
                }
                position += groupCount * group.size;
                count = newCount;
            }
            return -1;
        }
    }
    exports.RangeMap = RangeMap;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[54/*vs/base/common/stopwatch*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.StopWatch = void 0;
    const hasPerformanceNow = (globalThis.performance && typeof globalThis.performance.now === 'function');
    class StopWatch {
        static create(highResolution) {
            return new StopWatch(highResolution);
        }
        constructor(highResolution) {
            this._now = hasPerformanceNow && highResolution === false ? Date.now : globalThis.performance.now.bind(globalThis.performance);
            this._startTime = this._now();
            this._stopTime = -1;
        }
        stop() {
            this._stopTime = this._now();
        }
        reset() {
            this._startTime = this._now();
            this._stopTime = -1;
        }
        elapsed() {
            if (this._stopTime !== -1) {
                return this._stopTime - this._startTime;
            }
            return this._now() - this._startTime;
        }
    }
    exports.StopWatch = StopWatch;
});

define(__m[6/*vs/base/common/event*/], __M([1/*require*/,0/*exports*/,8/*vs/base/common/errors*/,127/*vs/base/common/functional*/,2/*vs/base/common/lifecycle*/,73/*vs/base/common/linkedList*/,54/*vs/base/common/stopwatch*/]), function (require, exports, errors_1, functional_1, lifecycle_1, linkedList_1, stopwatch_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Relay = exports.EventBufferer = exports.EventMultiplexer = exports.MicrotaskEmitter = exports.DebounceEmitter = exports.PauseableEmitter = exports.createEventDeliveryQueue = exports.Emitter = exports.ListenerRefusalError = exports.ListenerLeakError = exports.EventProfiling = exports.Event = void 0;
    // -----------------------------------------------------------------------------------------------------------------------
    // Uncomment the next line to print warnings whenever a listener is GC'ed without having been disposed. This is a LEAK.
    // -----------------------------------------------------------------------------------------------------------------------
    const _enableListenerGCedWarning = false;
    // -----------------------------------------------------------------------------------------------------------------------
    // Uncomment the next line to print warnings whenever an emitter with listeners is disposed. That is a sign of code smell.
    // -----------------------------------------------------------------------------------------------------------------------
    const _enableDisposeWithListenerWarning = false;
    // -----------------------------------------------------------------------------------------------------------------------
    // Uncomment the next line to print warnings whenever a snapshotted event is used repeatedly without cleanup.
    // See https://github.com/microsoft/vscode/issues/142851
    // -----------------------------------------------------------------------------------------------------------------------
    const _enableSnapshotPotentialLeakWarning = false;
    var Event;
    (function (Event) {
        Event.None = () => lifecycle_1.Disposable.None;
        function _addLeakageTraceLogic(options) {
            if (_enableSnapshotPotentialLeakWarning) {
                const { onDidAddListener: origListenerDidAdd } = options;
                const stack = Stacktrace.create();
                let count = 0;
                options.onDidAddListener = () => {
                    if (++count === 2) {
                        console.warn('snapshotted emitter LIKELY used public and SHOULD HAVE BEEN created with DisposableStore. snapshotted here');
                        stack.print();
                    }
                    origListenerDidAdd?.();
                };
            }
        }
        /**
         * Given an event, returns another event which debounces calls and defers the listeners to a later task via a shared
         * `setTimeout`. The event is converted into a signal (`Event<void>`) to avoid additional object creation as a
         * result of merging events and to try prevent race conditions that could arise when using related deferred and
         * non-deferred events.
         *
         * This is useful for deferring non-critical work (eg. general UI updates) to ensure it does not block critical work
         * (eg. latency of keypress to text rendered).
         *
         * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned
         * event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the
         * returned event causes this utility to leak a listener on the original event.
         *
         * @param event The event source for the new event.
         * @param disposable A disposable store to add the new EventEmitter to.
         */
        function defer(event, disposable) {
            return debounce(event, () => void 0, 0, undefined, true, undefined, disposable);
        }
        Event.defer = defer;
        /**
         * Given an event, returns another event which only fires once.
         *
         * @param event The event source for the new event.
         */
        function once(event) {
            return (listener, thisArgs = null, disposables) => {
                // we need this, in case the event fires during the listener call
                let didFire = false;
                let result = undefined;
                result = event(e => {
                    if (didFire) {
                        return;
                    }
                    else if (result) {
                        result.dispose();
                    }
                    else {
                        didFire = true;
                    }
                    return listener.call(thisArgs, e);
                }, null, disposables);
                if (didFire) {
                    result.dispose();
                }
                return result;
            };
        }
        Event.once = once;
        /**
         * Given an event, returns another event which only fires once, and only when the condition is met.
         *
         * @param event The event source for the new event.
         */
        function onceIf(event, condition) {
            return Event.once(Event.filter(event, condition));
        }
        Event.onceIf = onceIf;
        /**
         * Maps an event of one type into an event of another type using a mapping function, similar to how
         * `Array.prototype.map` works.
         *
         * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned
         * event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the
         * returned event causes this utility to leak a listener on the original event.
         *
         * @param event The event source for the new event.
         * @param map The mapping function.
         * @param disposable A disposable store to add the new EventEmitter to.
         */
        function map(event, map, disposable) {
            return snapshot((listener, thisArgs = null, disposables) => event(i => listener.call(thisArgs, map(i)), null, disposables), disposable);
        }
        Event.map = map;
        /**
         * Wraps an event in another event that performs some function on the event object before firing.
         *
         * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned
         * event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the
         * returned event causes this utility to leak a listener on the original event.
         *
         * @param event The event source for the new event.
         * @param each The function to perform on the event object.
         * @param disposable A disposable store to add the new EventEmitter to.
         */
        function forEach(event, each, disposable) {
            return snapshot((listener, thisArgs = null, disposables) => event(i => { each(i); listener.call(thisArgs, i); }, null, disposables), disposable);
        }
        Event.forEach = forEach;
        function filter(event, filter, disposable) {
            return snapshot((listener, thisArgs = null, disposables) => event(e => filter(e) && listener.call(thisArgs, e), null, disposables), disposable);
        }
        Event.filter = filter;
        /**
         * Given an event, returns the same event but typed as `Event<void>`.
         */
        function signal(event) {
            return event;
        }
        Event.signal = signal;
        function any(...events) {
            return (listener, thisArgs = null, disposables) => {
                const disposable = (0, lifecycle_1.combinedDisposable)(...events.map(event => event(e => listener.call(thisArgs, e))));
                return addAndReturnDisposable(disposable, disposables);
            };
        }
        Event.any = any;
        /**
         * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned
         * event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the
         * returned event causes this utility to leak a listener on the original event.
         */
        function reduce(event, merge, initial, disposable) {
            let output = initial;
            return map(event, e => {
                output = merge(output, e);
                return output;
            }, disposable);
        }
        Event.reduce = reduce;
        function snapshot(event, disposable) {
            let listener;
            const options = {
                onWillAddFirstListener() {
                    listener = event(emitter.fire, emitter);
                },
                onDidRemoveLastListener() {
                    listener?.dispose();
                }
            };
            if (!disposable) {
                _addLeakageTraceLogic(options);
            }
            const emitter = new Emitter(options);
            disposable?.add(emitter);
            return emitter.event;
        }
        /**
         * Adds the IDisposable to the store if it's set, and returns it. Useful to
         * Event function implementation.
         */
        function addAndReturnDisposable(d, store) {
            if (store instanceof Array) {
                store.push(d);
            }
            else if (store) {
                store.add(d);
            }
            return d;
        }
        function debounce(event, merge, delay = 100, leading = false, flushOnListenerRemove = false, leakWarningThreshold, disposable) {
            let subscription;
            let output = undefined;
            let handle = undefined;
            let numDebouncedCalls = 0;
            let doFire;
            const options = {
                leakWarningThreshold,
                onWillAddFirstListener() {
                    subscription = event(cur => {
                        numDebouncedCalls++;
                        output = merge(output, cur);
                        if (leading && !handle) {
                            emitter.fire(output);
                            output = undefined;
                        }
                        doFire = () => {
                            const _output = output;
                            output = undefined;
                            handle = undefined;
                            if (!leading || numDebouncedCalls > 1) {
                                emitter.fire(_output);
                            }
                            numDebouncedCalls = 0;
                        };
                        if (typeof delay === 'number') {
                            clearTimeout(handle);
                            handle = setTimeout(doFire, delay);
                        }
                        else {
                            if (handle === undefined) {
                                handle = 0;
                                queueMicrotask(doFire);
                            }
                        }
                    });
                },
                onWillRemoveListener() {
                    if (flushOnListenerRemove && numDebouncedCalls > 0) {
                        doFire?.();
                    }
                },
                onDidRemoveLastListener() {
                    doFire = undefined;
                    subscription.dispose();
                }
            };
            if (!disposable) {
                _addLeakageTraceLogic(options);
            }
            const emitter = new Emitter(options);
            disposable?.add(emitter);
            return emitter.event;
        }
        Event.debounce = debounce;
        /**
         * Debounces an event, firing after some delay (default=0) with an array of all event original objects.
         *
         * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned
         * event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the
         * returned event causes this utility to leak a listener on the original event.
         */
        function accumulate(event, delay = 0, disposable) {
            return Event.debounce(event, (last, e) => {
                if (!last) {
                    return [e];
                }
                last.push(e);
                return last;
            }, delay, undefined, true, undefined, disposable);
        }
        Event.accumulate = accumulate;
        /**
         * Filters an event such that some condition is _not_ met more than once in a row, effectively ensuring duplicate
         * event objects from different sources do not fire the same event object.
         *
         * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned
         * event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the
         * returned event causes this utility to leak a listener on the original event.
         *
         * @param event The event source for the new event.
         * @param equals The equality condition.
         * @param disposable A disposable store to add the new EventEmitter to.
         *
         * @example
         * ```
         * // Fire only one time when a single window is opened or focused
         * Event.latch(Event.any(onDidOpenWindow, onDidFocusWindow))
         * ```
         */
        function latch(event, equals = (a, b) => a === b, disposable) {
            let firstCall = true;
            let cache;
            return filter(event, value => {
                const shouldEmit = firstCall || !equals(value, cache);
                firstCall = false;
                cache = value;
                return shouldEmit;
            }, disposable);
        }
        Event.latch = latch;
        /**
         * Splits an event whose parameter is a union type into 2 separate events for each type in the union.
         *
         * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned
         * event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the
         * returned event causes this utility to leak a listener on the original event.
         *
         * @example
         * ```
         * const event = new EventEmitter<number | undefined>().event;
         * const [numberEvent, undefinedEvent] = Event.split(event, isUndefined);
         * ```
         *
         * @param event The event source for the new event.
         * @param isT A function that determines what event is of the first type.
         * @param disposable A disposable store to add the new EventEmitter to.
         */
        function split(event, isT, disposable) {
            return [
                Event.filter(event, isT, disposable),
                Event.filter(event, e => !isT(e), disposable),
            ];
        }
        Event.split = split;
        /**
         * Buffers an event until it has a listener attached.
         *
         * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned
         * event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the
         * returned event causes this utility to leak a listener on the original event.
         *
         * @param event The event source for the new event.
         * @param flushAfterTimeout Determines whether to flush the buffer after a timeout immediately or after a
         * `setTimeout` when the first event listener is added.
         * @param _buffer Internal: A source event array used for tests.
         *
         * @example
         * ```
         * // Start accumulating events, when the first listener is attached, flush
         * // the event after a timeout such that multiple listeners attached before
         * // the timeout would receive the event
         * this.onInstallExtension = Event.buffer(service.onInstallExtension, true);
         * ```
         */
        function buffer(event, flushAfterTimeout = false, _buffer = [], disposable) {
            let buffer = _buffer.slice();
            let listener = event(e => {
                if (buffer) {
                    buffer.push(e);
                }
                else {
                    emitter.fire(e);
                }
            });
            if (disposable) {
                disposable.add(listener);
            }
            const flush = () => {
                buffer?.forEach(e => emitter.fire(e));
                buffer = null;
            };
            const emitter = new Emitter({
                onWillAddFirstListener() {
                    if (!listener) {
                        listener = event(e => emitter.fire(e));
                        if (disposable) {
                            disposable.add(listener);
                        }
                    }
                },
                onDidAddFirstListener() {
                    if (buffer) {
                        if (flushAfterTimeout) {
                            setTimeout(flush);
                        }
                        else {
                            flush();
                        }
                    }
                },
                onDidRemoveLastListener() {
                    if (listener) {
                        listener.dispose();
                    }
                    listener = null;
                }
            });
            if (disposable) {
                disposable.add(emitter);
            }
            return emitter.event;
        }
        Event.buffer = buffer;
        /**
         * Wraps the event in an {@link IChainableEvent}, allowing a more functional programming style.
         *
         * @example
         * ```
         * // Normal
         * const onEnterPressNormal = Event.filter(
         *   Event.map(onKeyPress.event, e => new StandardKeyboardEvent(e)),
         *   e.keyCode === KeyCode.Enter
         * ).event;
         *
         * // Using chain
         * const onEnterPressChain = Event.chain(onKeyPress.event, $ => $
         *   .map(e => new StandardKeyboardEvent(e))
         *   .filter(e => e.keyCode === KeyCode.Enter)
         * );
         * ```
         */
        function chain(event, sythensize) {
            const fn = (listener, thisArgs, disposables) => {
                const cs = sythensize(new ChainableSynthesis());
                return event(function (value) {
                    const result = cs.evaluate(value);
                    if (result !== HaltChainable) {
                        listener.call(thisArgs, result);
                    }
                }, undefined, disposables);
            };
            return fn;
        }
        Event.chain = chain;
        const HaltChainable = Symbol('HaltChainable');
        class ChainableSynthesis {
            constructor() {
                this.steps = [];
            }
            map(fn) {
                this.steps.push(fn);
                return this;
            }
            forEach(fn) {
                this.steps.push(v => {
                    fn(v);
                    return v;
                });
                return this;
            }
            filter(fn) {
                this.steps.push(v => fn(v) ? v : HaltChainable);
                return this;
            }
            reduce(merge, initial) {
                let last = initial;
                this.steps.push(v => {
                    last = merge(last, v);
                    return last;
                });
                return this;
            }
            latch(equals = (a, b) => a === b) {
                let firstCall = true;
                let cache;
                this.steps.push(value => {
                    const shouldEmit = firstCall || !equals(value, cache);
                    firstCall = false;
                    cache = value;
                    return shouldEmit ? value : HaltChainable;
                });
                return this;
            }
            evaluate(value) {
                for (const step of this.steps) {
                    value = step(value);
                    if (value === HaltChainable) {
                        break;
                    }
                }
                return value;
            }
        }
        /**
         * Creates an {@link Event} from a node event emitter.
         */
        function fromNodeEventEmitter(emitter, eventName, map = id => id) {
            const fn = (...args) => result.fire(map(...args));
            const onFirstListenerAdd = () => emitter.on(eventName, fn);
            const onLastListenerRemove = () => emitter.removeListener(eventName, fn);
            const result = new Emitter({ onWillAddFirstListener: onFirstListenerAdd, onDidRemoveLastListener: onLastListenerRemove });
            return result.event;
        }
        Event.fromNodeEventEmitter = fromNodeEventEmitter;
        /**
         * Creates an {@link Event} from a DOM event emitter.
         */
        function fromDOMEventEmitter(emitter, eventName, map = id => id) {
            const fn = (...args) => result.fire(map(...args));
            const onFirstListenerAdd = () => emitter.addEventListener(eventName, fn);
            const onLastListenerRemove = () => emitter.removeEventListener(eventName, fn);
            const result = new Emitter({ onWillAddFirstListener: onFirstListenerAdd, onDidRemoveLastListener: onLastListenerRemove });
            return result.event;
        }
        Event.fromDOMEventEmitter = fromDOMEventEmitter;
        /**
         * Creates a promise out of an event, using the {@link Event.once} helper.
         */
        function toPromise(event) {
            return new Promise(resolve => once(event)(resolve));
        }
        Event.toPromise = toPromise;
        /**
         * Creates an event out of a promise that fires once when the promise is
         * resolved with the result of the promise or `undefined`.
         */
        function fromPromise(promise) {
            const result = new Emitter();
            promise.then(res => {
                result.fire(res);
            }, () => {
                result.fire(undefined);
            }).finally(() => {
                result.dispose();
            });
            return result.event;
        }
        Event.fromPromise = fromPromise;
        /**
         * A convenience function for forwarding an event to another emitter which
         * improves readability.
         *
         * This is similar to {@link Relay} but allows instantiating and forwarding
         * on a single line and also allows for multiple source events.
         * @param from The event to forward.
         * @param to The emitter to forward the event to.
         * @example
         * Event.forward(event, emitter);
         * // equivalent to
         * event(e => emitter.fire(e));
         * // equivalent to
         * event(emitter.fire, emitter);
         */
        function forward(from, to) {
            return from(e => to.fire(e));
        }
        Event.forward = forward;
        function runAndSubscribe(event, handler, initial) {
            handler(initial);
            return event(e => handler(e));
        }
        Event.runAndSubscribe = runAndSubscribe;
        class EmitterObserver {
            constructor(_observable, store) {
                this._observable = _observable;
                this._counter = 0;
                this._hasChanged = false;
                const options = {
                    onWillAddFirstListener: () => {
                        _observable.addObserver(this);
                        // Communicate to the observable that we received its current value and would like to be notified about future changes.
                        this._observable.reportChanges();
                    },
                    onDidRemoveLastListener: () => {
                        _observable.removeObserver(this);
                    }
                };
                if (!store) {
                    _addLeakageTraceLogic(options);
                }
                this.emitter = new Emitter(options);
                if (store) {
                    store.add(this.emitter);
                }
            }
            beginUpdate(_observable) {
                // assert(_observable === this.obs);
                this._counter++;
            }
            handlePossibleChange(_observable) {
                // assert(_observable === this.obs);
            }
            handleChange(_observable, _change) {
                // assert(_observable === this.obs);
                this._hasChanged = true;
            }
            endUpdate(_observable) {
                // assert(_observable === this.obs);
                this._counter--;
                if (this._counter === 0) {
                    this._observable.reportChanges();
                    if (this._hasChanged) {
                        this._hasChanged = false;
                        this.emitter.fire(this._observable.get());
                    }
                }
            }
        }
        /**
         * Creates an event emitter that is fired when the observable changes.
         * Each listeners subscribes to the emitter.
         */
        function fromObservable(obs, store) {
            const observer = new EmitterObserver(obs, store);
            return observer.emitter.event;
        }
        Event.fromObservable = fromObservable;
        /**
         * Each listener is attached to the observable directly.
         */
        function fromObservableLight(observable) {
            return (listener, thisArgs, disposables) => {
                let count = 0;
                let didChange = false;
                const observer = {
                    beginUpdate() {
                        count++;
                    },
                    endUpdate() {
                        count--;
                        if (count === 0) {
                            observable.reportChanges();
                            if (didChange) {
                                didChange = false;
                                listener.call(thisArgs);
                            }
                        }
                    },
                    handlePossibleChange() {
                        // noop
                    },
                    handleChange() {
                        didChange = true;
                    }
                };
                observable.addObserver(observer);
                observable.reportChanges();
                const disposable = {
                    dispose() {
                        observable.removeObserver(observer);
                    }
                };
                if (disposables instanceof lifecycle_1.DisposableStore) {
                    disposables.add(disposable);
                }
                else if (Array.isArray(disposables)) {
                    disposables.push(disposable);
                }
                return disposable;
            };
        }
        Event.fromObservableLight = fromObservableLight;
    })(Event || (exports.Event = Event = {}));
    class EventProfiling {
        static { this.all = new Set(); }
        static { this._idPool = 0; }
        constructor(name) {
            this.listenerCount = 0;
            this.invocationCount = 0;
            this.elapsedOverall = 0;
            this.durations = [];
            this.name = `${name}_${EventProfiling._idPool++}`;
            EventProfiling.all.add(this);
        }
        start(listenerCount) {
            this._stopWatch = new stopwatch_1.StopWatch();
            this.listenerCount = listenerCount;
        }
        stop() {
            if (this._stopWatch) {
                const elapsed = this._stopWatch.elapsed();
                this.durations.push(elapsed);
                this.elapsedOverall += elapsed;
                this.invocationCount += 1;
                this._stopWatch = undefined;
            }
        }
    }
    exports.EventProfiling = EventProfiling;
    let _globalLeakWarningThreshold = -1;
    class LeakageMonitor {
        static { this._idPool = 1; }
        constructor(_errorHandler, threshold, name = (LeakageMonitor._idPool++).toString(16).padStart(3, '0')) {
            this._errorHandler = _errorHandler;
            this.threshold = threshold;
            this.name = name;
            this._warnCountdown = 0;
        }
        dispose() {
            this._stacks?.clear();
        }
        check(stack, listenerCount) {
            const threshold = this.threshold;
            if (threshold <= 0 || listenerCount < threshold) {
                return undefined;
            }
            if (!this._stacks) {
                this._stacks = new Map();
            }
            const count = (this._stacks.get(stack.value) || 0);
            this._stacks.set(stack.value, count + 1);
            this._warnCountdown -= 1;
            if (this._warnCountdown <= 0) {
                // only warn on first exceed and then every time the limit
                // is exceeded by 50% again
                this._warnCountdown = threshold * 0.5;
                const [topStack, topCount] = this.getMostFrequentStack();
                const message = `[${this.name}] potential listener LEAK detected, having ${listenerCount} listeners already. MOST frequent listener (${topCount}):`;
                console.warn(message);
                console.warn(topStack);
                const error = new ListenerLeakError(message, topStack);
                this._errorHandler(error);
            }
            return () => {
                const count = (this._stacks.get(stack.value) || 0);
                this._stacks.set(stack.value, count - 1);
            };
        }
        getMostFrequentStack() {
            if (!this._stacks) {
                return undefined;
            }
            let topStack;
            let topCount = 0;
            for (const [stack, count] of this._stacks) {
                if (!topStack || topCount < count) {
                    topStack = [stack, count];
                    topCount = count;
                }
            }
            return topStack;
        }
    }
    class Stacktrace {
        static create() {
            const err = new Error();
            return new Stacktrace(err.stack ?? '');
        }
        constructor(value) {
            this.value = value;
        }
        print() {
            console.warn(this.value.split('\n').slice(2).join('\n'));
        }
    }
    // error that is logged when going over the configured listener threshold
    class ListenerLeakError extends Error {
        constructor(message, stack) {
            super(message);
            this.name = 'ListenerLeakError';
            this.stack = stack;
        }
    }
    exports.ListenerLeakError = ListenerLeakError;
    // SEVERE error that is logged when having gone way over the configured listener
    // threshold so that the emitter refuses to accept more listeners
    class ListenerRefusalError extends Error {
        constructor(message, stack) {
            super(message);
            this.name = 'ListenerRefusalError';
            this.stack = stack;
        }
    }
    exports.ListenerRefusalError = ListenerRefusalError;
    class UniqueContainer {
        constructor(value) {
            this.value = value;
        }
    }
    const compactionThreshold = 2;
    const forEachListener = (listeners, fn) => {
        if (listeners instanceof UniqueContainer) {
            fn(listeners);
        }
        else {
            for (let i = 0; i < listeners.length; i++) {
                const l = listeners[i];
                if (l) {
                    fn(l);
                }
            }
        }
    };
    let _listenerFinalizers;
    if (_enableListenerGCedWarning) {
        const leaks = [];
        setInterval(() => {
            if (leaks.length === 0) {
                return;
            }
            console.warn('[LEAKING LISTENERS] GC\'ed these listeners that were NOT yet disposed:');
            console.warn(leaks.join('\n'));
            leaks.length = 0;
        }, 3000);
        _listenerFinalizers = new FinalizationRegistry(heldValue => {
            if (typeof heldValue === 'string') {
                leaks.push(heldValue);
            }
        });
    }
    /**
     * The Emitter can be used to expose an Event to the public
     * to fire it from the insides.
     * Sample:
        class Document {
    
            private readonly _onDidChange = new Emitter<(value:string)=>any>();
    
            public onDidChange = this._onDidChange.event;
    
            // getter-style
            // get onDidChange(): Event<(value:string)=>any> {
            // 	return this._onDidChange.event;
            // }
    
            private _doIt() {
                //...
                this._onDidChange.fire(value);
            }
        }
     */
    class Emitter {
        constructor(options) {
            this._size = 0;
            this._options = options;
            this._leakageMon = (_globalLeakWarningThreshold > 0 || this._options?.leakWarningThreshold)
                ? new LeakageMonitor(options?.onListenerError ?? errors_1.onUnexpectedError, this._options?.leakWarningThreshold ?? _globalLeakWarningThreshold) :
                undefined;
            this._perfMon = this._options?._profName ? new EventProfiling(this._options._profName) : undefined;
            this._deliveryQueue = this._options?.deliveryQueue;
        }
        dispose() {
            if (!this._disposed) {
                this._disposed = true;
                // It is bad to have listeners at the time of disposing an emitter, it is worst to have listeners keep the emitter
                // alive via the reference that's embedded in their disposables. Therefore we loop over all remaining listeners and
                // unset their subscriptions/disposables. Looping and blaming remaining listeners is done on next tick because the
                // the following programming pattern is very popular:
                //
                // const someModel = this._disposables.add(new ModelObject()); // (1) create and register model
                // this._disposables.add(someModel.onDidChange(() => { ... }); // (2) subscribe and register model-event listener
                // ...later...
                // this._disposables.dispose(); disposes (1) then (2): don't warn after (1) but after the "overall dispose" is done
                if (this._deliveryQueue?.current === this) {
                    this._deliveryQueue.reset();
                }
                if (this._listeners) {
                    if (_enableDisposeWithListenerWarning) {
                        const listeners = this._listeners;
                        queueMicrotask(() => {
                            forEachListener(listeners, l => l.stack?.print());
                        });
                    }
                    this._listeners = undefined;
                    this._size = 0;
                }
                this._options?.onDidRemoveLastListener?.();
                this._leakageMon?.dispose();
            }
        }
        /**
         * For the public to allow to subscribe
         * to events from this Emitter
         */
        get event() {
            this._event ??= (callback, thisArgs, disposables) => {
                if (this._leakageMon && this._size > this._leakageMon.threshold ** 2) {
                    const message = `[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;
                    console.warn(message);
                    const tuple = this._leakageMon.getMostFrequentStack() ?? ['UNKNOWN stack', -1];
                    const error = new ListenerRefusalError(`${message}. HINT: Stack shows most frequent listener (${tuple[1]}-times)`, tuple[0]);
                    const errorHandler = this._options?.onListenerError || errors_1.onUnexpectedError;
                    errorHandler(error);
                    return lifecycle_1.Disposable.None;
                }
                if (this._disposed) {
                    // todo: should we warn if a listener is added to a disposed emitter? This happens often
                    return lifecycle_1.Disposable.None;
                }
                if (thisArgs) {
                    callback = callback.bind(thisArgs);
                }
                const contained = new UniqueContainer(callback);
                let removeMonitor;
                let stack;
                if (this._leakageMon && this._size >= Math.ceil(this._leakageMon.threshold * 0.2)) {
                    // check and record this emitter for potential leakage
                    contained.stack = Stacktrace.create();
                    removeMonitor = this._leakageMon.check(contained.stack, this._size + 1);
                }
                if (_enableDisposeWithListenerWarning) {
                    contained.stack = stack ?? Stacktrace.create();
                }
                if (!this._listeners) {
                    this._options?.onWillAddFirstListener?.(this);
                    this._listeners = contained;
                    this._options?.onDidAddFirstListener?.(this);
                }
                else if (this._listeners instanceof UniqueContainer) {
                    this._deliveryQueue ??= new EventDeliveryQueuePrivate();
                    this._listeners = [this._listeners, contained];
                }
                else {
                    this._listeners.push(contained);
                }
                this._size++;
                const result = (0, lifecycle_1.toDisposable)(() => {
                    _listenerFinalizers?.unregister(result);
                    removeMonitor?.();
                    this._removeListener(contained);
                });
                if (disposables instanceof lifecycle_1.DisposableStore) {
                    disposables.add(result);
                }
                else if (Array.isArray(disposables)) {
                    disposables.push(result);
                }
                if (_listenerFinalizers) {
                    const stack = new Error().stack.split('\n').slice(2, 3).join('\n').trim();
                    const match = /(file:|vscode-file:\/\/vscode-app)?(\/[^:]*:\d+:\d+)/.exec(stack);
                    _listenerFinalizers.register(result, match?.[2] ?? stack, result);
                }
                return result;
            };
            return this._event;
        }
        _removeListener(listener) {
            this._options?.onWillRemoveListener?.(this);
            if (!this._listeners) {
                return; // expected if a listener gets disposed
            }
            if (this._size === 1) {
                this._listeners = undefined;
                this._options?.onDidRemoveLastListener?.(this);
                this._size = 0;
                return;
            }
            // size > 1 which requires that listeners be a list:
            const listeners = this._listeners;
            const index = listeners.indexOf(listener);
            if (index === -1) {
                console.log('disposed?', this._disposed);
                console.log('size?', this._size);
                console.log('arr?', JSON.stringify(this._listeners));
                throw new Error('Attempted to dispose unknown listener');
            }
            this._size--;
            listeners[index] = undefined;
            const adjustDeliveryQueue = this._deliveryQueue.current === this;
            if (this._size * compactionThreshold <= listeners.length) {
                let n = 0;
                for (let i = 0; i < listeners.length; i++) {
                    if (listeners[i]) {
                        listeners[n++] = listeners[i];
                    }
                    else if (adjustDeliveryQueue) {
                        this._deliveryQueue.end--;
                        if (n < this._deliveryQueue.i) {
                            this._deliveryQueue.i--;
                        }
                    }
                }
                listeners.length = n;
            }
        }
        _deliver(listener, value) {
            if (!listener) {
                return;
            }
            const errorHandler = this._options?.onListenerError || errors_1.onUnexpectedError;
            if (!errorHandler) {
                listener.value(value);
                return;
            }
            try {
                listener.value(value);
            }
            catch (e) {
                errorHandler(e);
            }
        }
        /** Delivers items in the queue. Assumes the queue is ready to go. */
        _deliverQueue(dq) {
            const listeners = dq.current._listeners;
            while (dq.i < dq.end) {
                // important: dq.i is incremented before calling deliver() because it might reenter deliverQueue()
                this._deliver(listeners[dq.i++], dq.value);
            }
            dq.reset();
        }
        /**
         * To be kept private to fire an event to
         * subscribers
         */
        fire(event) {
            if (this._deliveryQueue?.current) {
                this._deliverQueue(this._deliveryQueue);
                this._perfMon?.stop(); // last fire() will have starting perfmon, stop it before starting the next dispatch
            }
            this._perfMon?.start(this._size);
            if (!this._listeners) {
                // no-op
            }
            else if (this._listeners instanceof UniqueContainer) {
                this._deliver(this._listeners, event);
            }
            else {
                const dq = this._deliveryQueue;
                dq.enqueue(this, event, this._listeners.length);
                this._deliverQueue(dq);
            }
            this._perfMon?.stop();
        }
        hasListeners() {
            return this._size > 0;
        }
    }
    exports.Emitter = Emitter;
    const createEventDeliveryQueue = () => new EventDeliveryQueuePrivate();
    exports.createEventDeliveryQueue = createEventDeliveryQueue;
    class EventDeliveryQueuePrivate {
        constructor() {
            /**
             * Index in current's listener list.
             */
            this.i = -1;
            /**
             * The last index in the listener's list to deliver.
             */
            this.end = 0;
        }
        enqueue(emitter, value, end) {
            this.i = 0;
            this.end = end;
            this.current = emitter;
            this.value = value;
        }
        reset() {
            this.i = this.end; // force any current emission loop to stop, mainly for during dispose
            this.current = undefined;
            this.value = undefined;
        }
    }
    class PauseableEmitter extends Emitter {
        constructor(options) {
            super(options);
            this._isPaused = 0;
            this._eventQueue = new linkedList_1.LinkedList();
            this._mergeFn = options?.merge;
        }
        pause() {
            this._isPaused++;
        }
        resume() {
            if (this._isPaused !== 0 && --this._isPaused === 0) {
                if (this._mergeFn) {
                    // use the merge function to create a single composite
                    // event. make a copy in case firing pauses this emitter
                    if (this._eventQueue.size > 0) {
                        const events = Array.from(this._eventQueue);
                        this._eventQueue.clear();
                        super.fire(this._mergeFn(events));
                    }
                }
                else {
                    // no merging, fire each event individually and test
                    // that this emitter isn't paused halfway through
                    while (!this._isPaused && this._eventQueue.size !== 0) {
                        super.fire(this._eventQueue.shift());
                    }
                }
            }
        }
        fire(event) {
            if (this._size) {
                if (this._isPaused !== 0) {
                    this._eventQueue.push(event);
                }
                else {
                    super.fire(event);
                }
            }
        }
    }
    exports.PauseableEmitter = PauseableEmitter;
    class DebounceEmitter extends PauseableEmitter {
        constructor(options) {
            super(options);
            this._delay = options.delay ?? 100;
        }
        fire(event) {
            if (!this._handle) {
                this.pause();
                this._handle = setTimeout(() => {
                    this._handle = undefined;
                    this.resume();
                }, this._delay);
            }
            super.fire(event);
        }
    }
    exports.DebounceEmitter = DebounceEmitter;
    /**
     * An emitter which queue all events and then process them at the
     * end of the event loop.
     */
    class MicrotaskEmitter extends Emitter {
        constructor(options) {
            super(options);
            this._queuedEvents = [];
            this._mergeFn = options?.merge;
        }
        fire(event) {
            if (!this.hasListeners()) {
                return;
            }
            this._queuedEvents.push(event);
            if (this._queuedEvents.length === 1) {
                queueMicrotask(() => {
                    if (this._mergeFn) {
                        super.fire(this._mergeFn(this._queuedEvents));
                    }
                    else {
                        this._queuedEvents.forEach(e => super.fire(e));
                    }
                    this._queuedEvents = [];
                });
            }
        }
    }
    exports.MicrotaskEmitter = MicrotaskEmitter;
    /**
     * An event emitter that multiplexes many events into a single event.
     *
     * @example Listen to the `onData` event of all `Thing`s, dynamically adding and removing `Thing`s
     * to the multiplexer as needed.
     *
     * ```typescript
     * const anythingDataMultiplexer = new EventMultiplexer<{ data: string }>();
     *
     * const thingListeners = DisposableMap<Thing, IDisposable>();
     *
     * thingService.onDidAddThing(thing => {
     *   thingListeners.set(thing, anythingDataMultiplexer.add(thing.onData);
     * });
     * thingService.onDidRemoveThing(thing => {
     *   thingListeners.deleteAndDispose(thing);
     * });
     *
     * anythingDataMultiplexer.event(e => {
     *   console.log('Something fired data ' + e.data)
     * });
     * ```
     */
    class EventMultiplexer {
        constructor() {
            this.hasListeners = false;
            this.events = [];
            this.emitter = new Emitter({
                onWillAddFirstListener: () => this.onFirstListenerAdd(),
                onDidRemoveLastListener: () => this.onLastListenerRemove()
            });
        }
        get event() {
            return this.emitter.event;
        }
        add(event) {
            const e = { event: event, listener: null };
            this.events.push(e);
            if (this.hasListeners) {
                this.hook(e);
            }
            const dispose = () => {
                if (this.hasListeners) {
                    this.unhook(e);
                }
                const idx = this.events.indexOf(e);
                this.events.splice(idx, 1);
            };
            return (0, lifecycle_1.toDisposable)((0, functional_1.createSingleCallFunction)(dispose));
        }
        onFirstListenerAdd() {
            this.hasListeners = true;
            this.events.forEach(e => this.hook(e));
        }
        onLastListenerRemove() {
            this.hasListeners = false;
            this.events.forEach(e => this.unhook(e));
        }
        hook(e) {
            e.listener = e.event(r => this.emitter.fire(r));
        }
        unhook(e) {
            e.listener?.dispose();
            e.listener = null;
        }
        dispose() {
            this.emitter.dispose();
            for (const e of this.events) {
                e.listener?.dispose();
            }
            this.events = [];
        }
    }
    exports.EventMultiplexer = EventMultiplexer;
    /**
     * The EventBufferer is useful in situations in which you want
     * to delay firing your events during some code.
     * You can wrap that code and be sure that the event will not
     * be fired during that wrap.
     *
     * ```
     * const emitter: Emitter;
     * const delayer = new EventDelayer();
     * const delayedEvent = delayer.wrapEvent(emitter.event);
     *
     * delayedEvent(console.log);
     *
     * delayer.bufferEvents(() => {
     *   emitter.fire(); // event will not be fired yet
     * });
     *
     * // event will only be fired at this point
     * ```
     */
    class EventBufferer {
        constructor() {
            this.data = [];
        }
        wrapEvent(event, reduce, initial) {
            return (listener, thisArgs, disposables) => {
                return event(i => {
                    const data = this.data[this.data.length - 1];
                    // Non-reduce scenario
                    if (!reduce) {
                        // Buffering case
                        if (data) {
                            data.buffers.push(() => listener.call(thisArgs, i));
                        }
                        else {
                            // Not buffering case
                            listener.call(thisArgs, i);
                        }
                        return;
                    }
                    // Reduce scenario
                    const reduceData = data;
                    // Not buffering case
                    if (!reduceData) {
                        // TODO: Is there a way to cache this reduce call for all listeners?
                        listener.call(thisArgs, reduce(initial, i));
                        return;
                    }
                    // Buffering case
                    reduceData.items ??= [];
                    reduceData.items.push(i);
                    if (reduceData.buffers.length === 0) {
                        // Include a single buffered function that will reduce all events when we're done buffering events
                        data.buffers.push(() => {
                            // cache the reduced result so that the value can be shared across all listeners
                            reduceData.reducedResult ??= initial
                                ? reduceData.items.reduce(reduce, initial)
                                : reduceData.items.reduce(reduce);
                            listener.call(thisArgs, reduceData.reducedResult);
                        });
                    }
                }, undefined, disposables);
            };
        }
        bufferEvents(fn) {
            const data = { buffers: new Array() };
            this.data.push(data);
            const r = fn();
            this.data.pop();
            data.buffers.forEach(flush => flush());
            return r;
        }
    }
    exports.EventBufferer = EventBufferer;
    /**
     * A Relay is an event forwarder which functions as a replugabble event pipe.
     * Once created, you can connect an input event to it and it will simply forward
     * events from that input event through its own `event` property. The `input`
     * can be changed at any point in time.
     */
    class Relay {
        constructor() {
            this.listening = false;
            this.inputEvent = Event.None;
            this.inputEventListener = lifecycle_1.Disposable.None;
            this.emitter = new Emitter({
                onDidAddFirstListener: () => {
                    this.listening = true;
                    this.inputEventListener = this.inputEvent(this.emitter.fire, this.emitter);
                },
                onDidRemoveLastListener: () => {
                    this.listening = false;
                    this.inputEventListener.dispose();
                }
            });
            this.event = this.emitter.event;
        }
        set input(event) {
            this.inputEvent = event;
            if (this.listening) {
                this.inputEventListener.dispose();
                this.inputEventListener = event(this.emitter.fire, this.emitter);
            }
        }
        dispose() {
            this.inputEventListener.dispose();
            this.emitter.dispose();
        }
    }
    exports.Relay = Relay;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[93/*vs/base/browser/event*/], __M([1/*require*/,0/*exports*/,6/*vs/base/common/event*/]), function (require, exports, event_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DomEmitter = void 0;
    class DomEmitter {
        get event() {
            return this.emitter.event;
        }
        constructor(element, type, useCapture) {
            const fn = (e) => this.emitter.fire(e);
            this.emitter = new event_1.Emitter({
                onWillAddFirstListener: () => element.addEventListener(type, fn, useCapture),
                onDidRemoveLastListener: () => element.removeEventListener(type, fn, useCapture)
            });
        }
        dispose() {
            this.emitter.dispose();
        }
    }
    exports.DomEmitter = DomEmitter;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[18/*vs/base/common/cancellation*/], __M([1/*require*/,0/*exports*/,6/*vs/base/common/event*/]), function (require, exports, event_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CancellationTokenSource = exports.CancellationToken = void 0;
    exports.cancelOnDispose = cancelOnDispose;
    const shortcutEvent = Object.freeze(function (callback, context) {
        const handle = setTimeout(callback.bind(context), 0);
        return { dispose() { clearTimeout(handle); } };
    });
    var CancellationToken;
    (function (CancellationToken) {
        function isCancellationToken(thing) {
            if (thing === CancellationToken.None || thing === CancellationToken.Cancelled) {
                return true;
            }
            if (thing instanceof MutableToken) {
                return true;
            }
            if (!thing || typeof thing !== 'object') {
                return false;
            }
            return typeof thing.isCancellationRequested === 'boolean'
                && typeof thing.onCancellationRequested === 'function';
        }
        CancellationToken.isCancellationToken = isCancellationToken;
        CancellationToken.None = Object.freeze({
            isCancellationRequested: false,
            onCancellationRequested: event_1.Event.None
        });
        CancellationToken.Cancelled = Object.freeze({
            isCancellationRequested: true,
            onCancellationRequested: shortcutEvent
        });
    })(CancellationToken || (exports.CancellationToken = CancellationToken = {}));
    class MutableToken {
        constructor() {
            this._isCancelled = false;
            this._emitter = null;
        }
        cancel() {
            if (!this._isCancelled) {
                this._isCancelled = true;
                if (this._emitter) {
                    this._emitter.fire(undefined);
                    this.dispose();
                }
            }
        }
        get isCancellationRequested() {
            return this._isCancelled;
        }
        get onCancellationRequested() {
            if (this._isCancelled) {
                return shortcutEvent;
            }
            if (!this._emitter) {
                this._emitter = new event_1.Emitter();
            }
            return this._emitter.event;
        }
        dispose() {
            if (this._emitter) {
                this._emitter.dispose();
                this._emitter = null;
            }
        }
    }
    class CancellationTokenSource {
        constructor(parent) {
            this._token = undefined;
            this._parentListener = undefined;
            this._parentListener = parent && parent.onCancellationRequested(this.cancel, this);
        }
        get token() {
            if (!this._token) {
                // be lazy and create the token only when
                // actually needed
                this._token = new MutableToken();
            }
            return this._token;
        }
        cancel() {
            if (!this._token) {
                // save an object by returning the default
                // cancelled token when cancellation happens
                // before someone asks for the token
                this._token = CancellationToken.Cancelled;
            }
            else if (this._token instanceof MutableToken) {
                // actually cancel
                this._token.cancel();
            }
        }
        dispose(cancel = false) {
            if (cancel) {
                this.cancel();
            }
            this._parentListener?.dispose();
            if (!this._token) {
                // ensure to initialize with an empty token if we had none
                this._token = CancellationToken.None;
            }
            else if (this._token instanceof MutableToken) {
                // actually dispose
                this._token.dispose();
            }
        }
    }
    exports.CancellationTokenSource = CancellationTokenSource;
    function cancelOnDispose(store) {
        const source = new CancellationTokenSource();
        store.add({ dispose() { source.cancel(); } });
        return source.token;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[300/*vs/base/common/ime*/], __M([1/*require*/,0/*exports*/,6/*vs/base/common/event*/]), function (require, exports, event_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.IME = exports.IMEImpl = void 0;
    class IMEImpl {
        constructor() {
            this._onDidChange = new event_1.Emitter();
            this.onDidChange = this._onDidChange.event;
            this._enabled = true;
        }
        get enabled() {
            return this._enabled;
        }
        /**
         * Enable IME
         */
        enable() {
            this._enabled = true;
            this._onDidChange.fire();
        }
        /**
         * Disable IME
         */
        disable() {
            this._enabled = false;
            this._onDidChange.fire();
        }
    }
    exports.IMEImpl = IMEImpl;
    exports.IME = new IMEImpl();
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[189/*vs/base/common/observableInternal/utils*/], __M([1/*require*/,0/*exports*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,92/*vs/base/common/observableInternal/base*/,161/*vs/base/common/observableInternal/debugName*/,65/*vs/base/common/observableInternal/derived*/,162/*vs/base/common/observableInternal/logging*/,102/*vs/base/common/equals*/]), function (require, exports, event_1, lifecycle_1, base_1, debugName_1, derived_1, logging_1, equals_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ValueWithChangeEventFromObservable = exports.KeepAliveObserver = exports.FromEventObservable = void 0;
    exports.constObservable = constObservable;
    exports.observableFromEvent = observableFromEvent;
    exports.observableFromEventOpts = observableFromEventOpts;
    exports.observableSignalFromEvent = observableSignalFromEvent;
    exports.observableSignal = observableSignal;
    exports.keepObserved = keepObserved;
    exports.recomputeInitiallyAndOnChange = recomputeInitiallyAndOnChange;
    exports.derivedObservableWithCache = derivedObservableWithCache;
    exports.derivedObservableWithWritableCache = derivedObservableWithWritableCache;
    exports.mapObservableArrayCached = mapObservableArrayCached;
    exports.observableFromValueWithChangeEvent = observableFromValueWithChangeEvent;
    exports.derivedConstOnceDefined = derivedConstOnceDefined;
    /**
     * Represents an efficient observable whose value never changes.
     */
    function constObservable(value) {
        return new ConstObservable(value);
    }
    class ConstObservable extends base_1.ConvenientObservable {
        constructor(value) {
            super();
            this.value = value;
        }
        get debugName() {
            return this.toString();
        }
        get() {
            return this.value;
        }
        addObserver(observer) {
            // NO OP
        }
        removeObserver(observer) {
            // NO OP
        }
        toString() {
            return `Const: ${this.value}`;
        }
    }
    function observableFromEvent(...args) {
        let owner;
        let event;
        let getValue;
        if (args.length === 3) {
            [owner, event, getValue] = args;
        }
        else {
            [event, getValue] = args;
        }
        return new FromEventObservable(new debugName_1.DebugNameData(owner, undefined, getValue), event, getValue, () => FromEventObservable.globalTransaction, equals_1.strictEquals);
    }
    function observableFromEventOpts(options, event, getValue) {
        return new FromEventObservable(new debugName_1.DebugNameData(options.owner, options.debugName, options.debugReferenceFn ?? getValue), event, getValue, () => FromEventObservable.globalTransaction, options.equalsFn ?? equals_1.strictEquals);
    }
    class FromEventObservable extends base_1.BaseObservable {
        constructor(_debugNameData, event, _getValue, _getTransaction, _equalityComparator) {
            super();
            this._debugNameData = _debugNameData;
            this.event = event;
            this._getValue = _getValue;
            this._getTransaction = _getTransaction;
            this._equalityComparator = _equalityComparator;
            this.hasValue = false;
            this.handleEvent = (args) => {
                const newValue = this._getValue(args);
                const oldValue = this.value;
                const didChange = !this.hasValue || !(this._equalityComparator(oldValue, newValue));
                let didRunTransaction = false;
                if (didChange) {
                    this.value = newValue;
                    if (this.hasValue) {
                        didRunTransaction = true;
                        (0, base_1.subtransaction)(this._getTransaction(), (tx) => {
                            (0, logging_1.getLogger)()?.handleFromEventObservableTriggered(this, { oldValue, newValue, change: undefined, didChange, hadValue: this.hasValue });
                            for (const o of this.observers) {
                                tx.updateObserver(o, this);
                                o.handleChange(this, undefined);
                            }
                        }, () => {
                            const name = this.getDebugName();
                            return 'Event fired' + (name ? `: ${name}` : '');
                        });
                    }
                    this.hasValue = true;
                }
                if (!didRunTransaction) {
                    (0, logging_1.getLogger)()?.handleFromEventObservableTriggered(this, { oldValue, newValue, change: undefined, didChange, hadValue: this.hasValue });
                }
            };
        }
        getDebugName() {
            return this._debugNameData.getDebugName(this);
        }
        get debugName() {
            const name = this.getDebugName();
            return 'From Event' + (name ? `: ${name}` : '');
        }
        onFirstObserverAdded() {
            this.subscription = this.event(this.handleEvent);
        }
        onLastObserverRemoved() {
            this.subscription.dispose();
            this.subscription = undefined;
            this.hasValue = false;
            this.value = undefined;
        }
        get() {
            if (this.subscription) {
                if (!this.hasValue) {
                    this.handleEvent(undefined);
                }
                return this.value;
            }
            else {
                // no cache, as there are no subscribers to keep it updated
                const value = this._getValue(undefined);
                return value;
            }
        }
    }
    exports.FromEventObservable = FromEventObservable;
    (function (observableFromEvent) {
        observableFromEvent.Observer = FromEventObservable;
        function batchEventsGlobally(tx, fn) {
            let didSet = false;
            if (FromEventObservable.globalTransaction === undefined) {
                FromEventObservable.globalTransaction = tx;
                didSet = true;
            }
            try {
                fn();
            }
            finally {
                if (didSet) {
                    FromEventObservable.globalTransaction = undefined;
                }
            }
        }
        observableFromEvent.batchEventsGlobally = batchEventsGlobally;
    })(observableFromEvent || (exports.observableFromEvent = observableFromEvent = {}));
    function observableSignalFromEvent(debugName, event) {
        return new FromEventObservableSignal(debugName, event);
    }
    class FromEventObservableSignal extends base_1.BaseObservable {
        constructor(debugName, event) {
            super();
            this.debugName = debugName;
            this.event = event;
            this.handleEvent = () => {
                (0, base_1.transaction)((tx) => {
                    for (const o of this.observers) {
                        tx.updateObserver(o, this);
                        o.handleChange(this, undefined);
                    }
                }, () => this.debugName);
            };
        }
        onFirstObserverAdded() {
            this.subscription = this.event(this.handleEvent);
        }
        onLastObserverRemoved() {
            this.subscription.dispose();
            this.subscription = undefined;
        }
        get() {
            // NO OP
        }
    }
    function observableSignal(debugNameOrOwner) {
        if (typeof debugNameOrOwner === 'string') {
            return new ObservableSignal(debugNameOrOwner);
        }
        else {
            return new ObservableSignal(undefined, debugNameOrOwner);
        }
    }
    class ObservableSignal extends base_1.BaseObservable {
        get debugName() {
            return new debugName_1.DebugNameData(this._owner, this._debugName, undefined).getDebugName(this) ?? 'Observable Signal';
        }
        toString() {
            return this.debugName;
        }
        constructor(_debugName, _owner) {
            super();
            this._debugName = _debugName;
            this._owner = _owner;
        }
        trigger(tx, change) {
            if (!tx) {
                (0, base_1.transaction)(tx => {
                    this.trigger(tx, change);
                }, () => `Trigger signal ${this.debugName}`);
                return;
            }
            for (const o of this.observers) {
                tx.updateObserver(o, this);
                o.handleChange(this, change);
            }
        }
        get() {
            // NO OP
        }
    }
    /**
     * This makes sure the observable is being observed and keeps its cache alive.
     */
    function keepObserved(observable) {
        const o = new KeepAliveObserver(false, undefined);
        observable.addObserver(o);
        return (0, lifecycle_1.toDisposable)(() => {
            observable.removeObserver(o);
        });
    }
    (0, base_1._setKeepObserved)(keepObserved);
    /**
     * This converts the given observable into an autorun.
     */
    function recomputeInitiallyAndOnChange(observable, handleValue) {
        const o = new KeepAliveObserver(true, handleValue);
        observable.addObserver(o);
        if (handleValue) {
            handleValue(observable.get());
        }
        else {
            observable.reportChanges();
        }
        return (0, lifecycle_1.toDisposable)(() => {
            observable.removeObserver(o);
        });
    }
    (0, base_1._setRecomputeInitiallyAndOnChange)(recomputeInitiallyAndOnChange);
    class KeepAliveObserver {
        constructor(_forceRecompute, _handleValue) {
            this._forceRecompute = _forceRecompute;
            this._handleValue = _handleValue;
            this._counter = 0;
        }
        beginUpdate(observable) {
            this._counter++;
        }
        endUpdate(observable) {
            this._counter--;
            if (this._counter === 0 && this._forceRecompute) {
                if (this._handleValue) {
                    this._handleValue(observable.get());
                }
                else {
                    observable.reportChanges();
                }
            }
        }
        handlePossibleChange(observable) {
            // NO OP
        }
        handleChange(observable, change) {
            // NO OP
        }
    }
    exports.KeepAliveObserver = KeepAliveObserver;
    function derivedObservableWithCache(owner, computeFn) {
        let lastValue = undefined;
        const observable = (0, derived_1.derivedOpts)({ owner, debugReferenceFn: computeFn }, reader => {
            lastValue = computeFn(reader, lastValue);
            return lastValue;
        });
        return observable;
    }
    function derivedObservableWithWritableCache(owner, computeFn) {
        let lastValue = undefined;
        const onChange = observableSignal('derivedObservableWithWritableCache');
        const observable = (0, derived_1.derived)(owner, reader => {
            onChange.read(reader);
            lastValue = computeFn(reader, lastValue);
            return lastValue;
        });
        return Object.assign(observable, {
            clearCache: (tx) => {
                lastValue = undefined;
                onChange.trigger(tx);
            },
            setCache: (newValue, tx) => {
                lastValue = newValue;
                onChange.trigger(tx);
            }
        });
    }
    /**
     * When the items array changes, referential equal items are not mapped again.
     */
    function mapObservableArrayCached(owner, items, map, keySelector) {
        let m = new ArrayMap(map, keySelector);
        const self = (0, derived_1.derivedOpts)({
            debugReferenceFn: map,
            owner,
            onLastObserverRemoved: () => {
                m.dispose();
                m = new ArrayMap(map);
            }
        }, (reader) => {
            m.setItems(items.read(reader));
            return m.getItems();
        });
        return self;
    }
    class ArrayMap {
        constructor(_map, _keySelector) {
            this._map = _map;
            this._keySelector = _keySelector;
            this._cache = new Map();
            this._items = [];
        }
        dispose() {
            this._cache.forEach(entry => entry.store.dispose());
            this._cache.clear();
        }
        setItems(items) {
            const newItems = [];
            const itemsToRemove = new Set(this._cache.keys());
            for (const item of items) {
                const key = this._keySelector ? this._keySelector(item) : item;
                let entry = this._cache.get(key);
                if (!entry) {
                    const store = new lifecycle_1.DisposableStore();
                    const out = this._map(item, store);
                    entry = { out, store };
                    this._cache.set(key, entry);
                }
                else {
                    itemsToRemove.delete(key);
                }
                newItems.push(entry.out);
            }
            for (const item of itemsToRemove) {
                const entry = this._cache.get(item);
                entry.store.dispose();
                this._cache.delete(item);
            }
            this._items = newItems;
        }
        getItems() {
            return this._items;
        }
    }
    class ValueWithChangeEventFromObservable {
        constructor(observable) {
            this.observable = observable;
        }
        get onDidChange() {
            return event_1.Event.fromObservableLight(this.observable);
        }
        get value() {
            return this.observable.get();
        }
    }
    exports.ValueWithChangeEventFromObservable = ValueWithChangeEventFromObservable;
    function observableFromValueWithChangeEvent(owner, value) {
        if (value instanceof ValueWithChangeEventFromObservable) {
            return value.observable;
        }
        return observableFromEvent(owner, value.onDidChange, () => value.value);
    }
    /**
     * Works like a derived.
     * However, if the value is not undefined, it is cached and will not be recomputed anymore.
     * In that case, the derived will unsubscribe from its dependencies.
    */
    function derivedConstOnceDefined(owner, fn) {
        return derivedObservableWithCache(owner, (reader, lastValue) => lastValue ?? fn(reader));
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[21/*vs/base/common/observable*/], __M([1/*require*/,0/*exports*/,92/*vs/base/common/observableInternal/base*/,65/*vs/base/common/observableInternal/derived*/,299/*vs/base/common/observableInternal/autorun*/,189/*vs/base/common/observableInternal/utils*/,453/*vs/base/common/observableInternal/promise*/,452/*vs/base/common/observableInternal/api*/,162/*vs/base/common/observableInternal/logging*/]), function (require, exports, base_1, derived_1, autorun_1, utils_1, promise_1, api_1, logging_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.observableValueOpts = exports.waitForState = exports.PromiseResult = exports.ObservablePromise = exports.observableSignalFromEvent = exports.observableSignal = exports.observableFromEvent = exports.recomputeInitiallyAndOnChange = exports.keepObserved = exports.derivedObservableWithWritableCache = exports.derivedObservableWithCache = exports.constObservable = exports.autorunWithStoreHandleChanges = exports.autorunOpts = exports.autorunWithStore = exports.autorunHandleChanges = exports.autorun = exports.derivedWithStore = exports.derivedHandleChanges = exports.derivedOpts = exports.derived = exports.subtransaction = exports.transaction = exports.disposableObservableValue = exports.observableValue = void 0;
    Object.defineProperty(exports, "observableValue", { enumerable: true, get: function () { return base_1.observableValue; } });
    Object.defineProperty(exports, "disposableObservableValue", { enumerable: true, get: function () { return base_1.disposableObservableValue; } });
    Object.defineProperty(exports, "transaction", { enumerable: true, get: function () { return base_1.transaction; } });
    Object.defineProperty(exports, "subtransaction", { enumerable: true, get: function () { return base_1.subtransaction; } });
    Object.defineProperty(exports, "derived", { enumerable: true, get: function () { return derived_1.derived; } });
    Object.defineProperty(exports, "derivedOpts", { enumerable: true, get: function () { return derived_1.derivedOpts; } });
    Object.defineProperty(exports, "derivedHandleChanges", { enumerable: true, get: function () { return derived_1.derivedHandleChanges; } });
    Object.defineProperty(exports, "derivedWithStore", { enumerable: true, get: function () { return derived_1.derivedWithStore; } });
    Object.defineProperty(exports, "autorun", { enumerable: true, get: function () { return autorun_1.autorun; } });
    Object.defineProperty(exports, "autorunHandleChanges", { enumerable: true, get: function () { return autorun_1.autorunHandleChanges; } });
    Object.defineProperty(exports, "autorunWithStore", { enumerable: true, get: function () { return autorun_1.autorunWithStore; } });
    Object.defineProperty(exports, "autorunOpts", { enumerable: true, get: function () { return autorun_1.autorunOpts; } });
    Object.defineProperty(exports, "autorunWithStoreHandleChanges", { enumerable: true, get: function () { return autorun_1.autorunWithStoreHandleChanges; } });
    Object.defineProperty(exports, "constObservable", { enumerable: true, get: function () { return utils_1.constObservable; } });
    Object.defineProperty(exports, "derivedObservableWithCache", { enumerable: true, get: function () { return utils_1.derivedObservableWithCache; } });
    Object.defineProperty(exports, "derivedObservableWithWritableCache", { enumerable: true, get: function () { return utils_1.derivedObservableWithWritableCache; } });
    Object.defineProperty(exports, "keepObserved", { enumerable: true, get: function () { return utils_1.keepObserved; } });
    Object.defineProperty(exports, "recomputeInitiallyAndOnChange", { enumerable: true, get: function () { return utils_1.recomputeInitiallyAndOnChange; } });
    Object.defineProperty(exports, "observableFromEvent", { enumerable: true, get: function () { return utils_1.observableFromEvent; } });
    Object.defineProperty(exports, "observableSignal", { enumerable: true, get: function () { return utils_1.observableSignal; } });
    Object.defineProperty(exports, "observableSignalFromEvent", { enumerable: true, get: function () { return utils_1.observableSignalFromEvent; } });
    Object.defineProperty(exports, "ObservablePromise", { enumerable: true, get: function () { return promise_1.ObservablePromise; } });
    Object.defineProperty(exports, "PromiseResult", { enumerable: true, get: function () { return promise_1.PromiseResult; } });
    Object.defineProperty(exports, "waitForState", { enumerable: true, get: function () { return promise_1.waitForState; } });
    Object.defineProperty(exports, "observableValueOpts", { enumerable: true, get: function () { return api_1.observableValueOpts; } });
    // Remove "//" in the next line to enable logging
    const enableLogging = false;
    if (enableLogging) {
        (0, logging_1.setLogger)(new logging_1.ConsoleObservableLogger());
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[163/*vs/base/common/scrollable*/], __M([1/*require*/,0/*exports*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/]), function (require, exports, event_1, lifecycle_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SmoothScrollingOperation = exports.SmoothScrollingUpdate = exports.Scrollable = exports.ScrollState = void 0;
    class ScrollState {
        constructor(_forceIntegerValues, width, scrollWidth, scrollLeft, height, scrollHeight, scrollTop) {
            this._forceIntegerValues = _forceIntegerValues;
            this._scrollStateBrand = undefined;
            if (this._forceIntegerValues) {
                width = width | 0;
                scrollWidth = scrollWidth | 0;
                scrollLeft = scrollLeft | 0;
                height = height | 0;
                scrollHeight = scrollHeight | 0;
                scrollTop = scrollTop | 0;
            }
            this.rawScrollLeft = scrollLeft; // before validation
            this.rawScrollTop = scrollTop; // before validation
            if (width < 0) {
                width = 0;
            }
            if (scrollLeft + width > scrollWidth) {
                scrollLeft = scrollWidth - width;
            }
            if (scrollLeft < 0) {
                scrollLeft = 0;
            }
            if (height < 0) {
                height = 0;
            }
            if (scrollTop + height > scrollHeight) {
                scrollTop = scrollHeight - height;
            }
            if (scrollTop < 0) {
                scrollTop = 0;
            }
            this.width = width;
            this.scrollWidth = scrollWidth;
            this.scrollLeft = scrollLeft;
            this.height = height;
            this.scrollHeight = scrollHeight;
            this.scrollTop = scrollTop;
        }
        equals(other) {
            return (this.rawScrollLeft === other.rawScrollLeft
                && this.rawScrollTop === other.rawScrollTop
                && this.width === other.width
                && this.scrollWidth === other.scrollWidth
                && this.scrollLeft === other.scrollLeft
                && this.height === other.height
                && this.scrollHeight === other.scrollHeight
                && this.scrollTop === other.scrollTop);
        }
        withScrollDimensions(update, useRawScrollPositions) {
            return new ScrollState(this._forceIntegerValues, (typeof update.width !== 'undefined' ? update.width : this.width), (typeof update.scrollWidth !== 'undefined' ? update.scrollWidth : this.scrollWidth), useRawScrollPositions ? this.rawScrollLeft : this.scrollLeft, (typeof update.height !== 'undefined' ? update.height : this.height), (typeof update.scrollHeight !== 'undefined' ? update.scrollHeight : this.scrollHeight), useRawScrollPositions ? this.rawScrollTop : this.scrollTop);
        }
        withScrollPosition(update) {
            return new ScrollState(this._forceIntegerValues, this.width, this.scrollWidth, (typeof update.scrollLeft !== 'undefined' ? update.scrollLeft : this.rawScrollLeft), this.height, this.scrollHeight, (typeof update.scrollTop !== 'undefined' ? update.scrollTop : this.rawScrollTop));
        }
        createScrollEvent(previous, inSmoothScrolling) {
            const widthChanged = (this.width !== previous.width);
            const scrollWidthChanged = (this.scrollWidth !== previous.scrollWidth);
            const scrollLeftChanged = (this.scrollLeft !== previous.scrollLeft);
            const heightChanged = (this.height !== previous.height);
            const scrollHeightChanged = (this.scrollHeight !== previous.scrollHeight);
            const scrollTopChanged = (this.scrollTop !== previous.scrollTop);
            return {
                inSmoothScrolling: inSmoothScrolling,
                oldWidth: previous.width,
                oldScrollWidth: previous.scrollWidth,
                oldScrollLeft: previous.scrollLeft,
                width: this.width,
                scrollWidth: this.scrollWidth,
                scrollLeft: this.scrollLeft,
                oldHeight: previous.height,
                oldScrollHeight: previous.scrollHeight,
                oldScrollTop: previous.scrollTop,
                height: this.height,
                scrollHeight: this.scrollHeight,
                scrollTop: this.scrollTop,
                widthChanged: widthChanged,
                scrollWidthChanged: scrollWidthChanged,
                scrollLeftChanged: scrollLeftChanged,
                heightChanged: heightChanged,
                scrollHeightChanged: scrollHeightChanged,
                scrollTopChanged: scrollTopChanged,
            };
        }
    }
    exports.ScrollState = ScrollState;
    class Scrollable extends lifecycle_1.Disposable {
        constructor(options) {
            super();
            this._scrollableBrand = undefined;
            this._onScroll = this._register(new event_1.Emitter());
            this.onScroll = this._onScroll.event;
            this._smoothScrollDuration = options.smoothScrollDuration;
            this._scheduleAtNextAnimationFrame = options.scheduleAtNextAnimationFrame;
            this._state = new ScrollState(options.forceIntegerValues, 0, 0, 0, 0, 0, 0);
            this._smoothScrolling = null;
        }
        dispose() {
            if (this._smoothScrolling) {
                this._smoothScrolling.dispose();
                this._smoothScrolling = null;
            }
            super.dispose();
        }
        setSmoothScrollDuration(smoothScrollDuration) {
            this._smoothScrollDuration = smoothScrollDuration;
        }
        validateScrollPosition(scrollPosition) {
            return this._state.withScrollPosition(scrollPosition);
        }
        getScrollDimensions() {
            return this._state;
        }
        setScrollDimensions(dimensions, useRawScrollPositions) {
            const newState = this._state.withScrollDimensions(dimensions, useRawScrollPositions);
            this._setState(newState, Boolean(this._smoothScrolling));
            // Validate outstanding animated scroll position target
            this._smoothScrolling?.acceptScrollDimensions(this._state);
        }
        /**
         * Returns the final scroll position that the instance will have once the smooth scroll animation concludes.
         * If no scroll animation is occurring, it will return the current scroll position instead.
         */
        getFutureScrollPosition() {
            if (this._smoothScrolling) {
                return this._smoothScrolling.to;
            }
            return this._state;
        }
        /**
         * Returns the current scroll position.
         * Note: This result might be an intermediate scroll position, as there might be an ongoing smooth scroll animation.
         */
        getCurrentScrollPosition() {
            return this._state;
        }
        setScrollPositionNow(update) {
            // no smooth scrolling requested
            const newState = this._state.withScrollPosition(update);
            // Terminate any outstanding smooth scrolling
            if (this._smoothScrolling) {
                this._smoothScrolling.dispose();
                this._smoothScrolling = null;
            }
            this._setState(newState, false);
        }
        setScrollPositionSmooth(update, reuseAnimation) {
            if (this._smoothScrollDuration === 0) {
                // Smooth scrolling not supported.
                return this.setScrollPositionNow(update);
            }
            if (this._smoothScrolling) {
                // Combine our pending scrollLeft/scrollTop with incoming scrollLeft/scrollTop
                update = {
                    scrollLeft: (typeof update.scrollLeft === 'undefined' ? this._smoothScrolling.to.scrollLeft : update.scrollLeft),
                    scrollTop: (typeof update.scrollTop === 'undefined' ? this._smoothScrolling.to.scrollTop : update.scrollTop)
                };
                // Validate `update`
                const validTarget = this._state.withScrollPosition(update);
                if (this._smoothScrolling.to.scrollLeft === validTarget.scrollLeft && this._smoothScrolling.to.scrollTop === validTarget.scrollTop) {
                    // No need to interrupt or extend the current animation since we're going to the same place
                    return;
                }
                let newSmoothScrolling;
                if (reuseAnimation) {
                    newSmoothScrolling = new SmoothScrollingOperation(this._smoothScrolling.from, validTarget, this._smoothScrolling.startTime, this._smoothScrolling.duration);
                }
                else {
                    newSmoothScrolling = this._smoothScrolling.combine(this._state, validTarget, this._smoothScrollDuration);
                }
                this._smoothScrolling.dispose();
                this._smoothScrolling = newSmoothScrolling;
            }
            else {
                // Validate `update`
                const validTarget = this._state.withScrollPosition(update);
                this._smoothScrolling = SmoothScrollingOperation.start(this._state, validTarget, this._smoothScrollDuration);
            }
            // Begin smooth scrolling animation
            this._smoothScrolling.animationFrameDisposable = this._scheduleAtNextAnimationFrame(() => {
                if (!this._smoothScrolling) {
                    return;
                }
                this._smoothScrolling.animationFrameDisposable = null;
                this._performSmoothScrolling();
            });
        }
        hasPendingScrollAnimation() {
            return Boolean(this._smoothScrolling);
        }
        _performSmoothScrolling() {
            if (!this._smoothScrolling) {
                return;
            }
            const update = this._smoothScrolling.tick();
            const newState = this._state.withScrollPosition(update);
            this._setState(newState, true);
            if (!this._smoothScrolling) {
                // Looks like someone canceled the smooth scrolling
                // from the scroll event handler
                return;
            }
            if (update.isDone) {
                this._smoothScrolling.dispose();
                this._smoothScrolling = null;
                return;
            }
            // Continue smooth scrolling animation
            this._smoothScrolling.animationFrameDisposable = this._scheduleAtNextAnimationFrame(() => {
                if (!this._smoothScrolling) {
                    return;
                }
                this._smoothScrolling.animationFrameDisposable = null;
                this._performSmoothScrolling();
            });
        }
        _setState(newState, inSmoothScrolling) {
            const oldState = this._state;
            if (oldState.equals(newState)) {
                // no change
                return;
            }
            this._state = newState;
            this._onScroll.fire(this._state.createScrollEvent(oldState, inSmoothScrolling));
        }
    }
    exports.Scrollable = Scrollable;
    class SmoothScrollingUpdate {
        constructor(scrollLeft, scrollTop, isDone) {
            this.scrollLeft = scrollLeft;
            this.scrollTop = scrollTop;
            this.isDone = isDone;
        }
    }
    exports.SmoothScrollingUpdate = SmoothScrollingUpdate;
    function createEaseOutCubic(from, to) {
        const delta = to - from;
        return function (completion) {
            return from + delta * easeOutCubic(completion);
        };
    }
    function createComposed(a, b, cut) {
        return function (completion) {
            if (completion < cut) {
                return a(completion / cut);
            }
            return b((completion - cut) / (1 - cut));
        };
    }
    class SmoothScrollingOperation {
        constructor(from, to, startTime, duration) {
            this.from = from;
            this.to = to;
            this.duration = duration;
            this.startTime = startTime;
            this.animationFrameDisposable = null;
            this._initAnimations();
        }
        _initAnimations() {
            this.scrollLeft = this._initAnimation(this.from.scrollLeft, this.to.scrollLeft, this.to.width);
            this.scrollTop = this._initAnimation(this.from.scrollTop, this.to.scrollTop, this.to.height);
        }
        _initAnimation(from, to, viewportSize) {
            const delta = Math.abs(from - to);
            if (delta > 2.5 * viewportSize) {
                let stop1, stop2;
                if (from < to) {
                    // scroll to 75% of the viewportSize
                    stop1 = from + 0.75 * viewportSize;
                    stop2 = to - 0.75 * viewportSize;
                }
                else {
                    stop1 = from - 0.75 * viewportSize;
                    stop2 = to + 0.75 * viewportSize;
                }
                return createComposed(createEaseOutCubic(from, stop1), createEaseOutCubic(stop2, to), 0.33);
            }
            return createEaseOutCubic(from, to);
        }
        dispose() {
            if (this.animationFrameDisposable !== null) {
                this.animationFrameDisposable.dispose();
                this.animationFrameDisposable = null;
            }
        }
        acceptScrollDimensions(state) {
            this.to = state.withScrollPosition(this.to);
            this._initAnimations();
        }
        tick() {
            return this._tick(Date.now());
        }
        _tick(now) {
            const completion = (now - this.startTime) / this.duration;
            if (completion < 1) {
                const newScrollLeft = this.scrollLeft(completion);
                const newScrollTop = this.scrollTop(completion);
                return new SmoothScrollingUpdate(newScrollLeft, newScrollTop, false);
            }
            return new SmoothScrollingUpdate(this.to.scrollLeft, this.to.scrollTop, true);
        }
        combine(from, to, duration) {
            return SmoothScrollingOperation.start(from, to, duration);
        }
        static start(from, to, duration) {
            // +10 / -10 : pretend the animation already started for a quicker response to a scroll request
            duration = duration + 10;
            const startTime = Date.now() - 10;
            return new SmoothScrollingOperation(from, to, startTime, duration);
        }
    }
    exports.SmoothScrollingOperation = SmoothScrollingOperation;
    function easeInCubic(t) {
        return Math.pow(t, 3);
    }
    function easeOutCubic(t) {
        return 1 - easeInCubic(1 - t);
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[11/*vs/base/common/strings*/], __M([1/*require*/,0/*exports*/,297/*vs/base/common/cache*/,98/*vs/base/common/lazy*/]), function (require, exports, cache_1, lazy_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.InvisibleCharacters = exports.AmbiguousCharacters = exports.noBreakWhitespace = exports.UTF8_BOM_CHARACTER = exports.UNUSUAL_LINE_TERMINATORS = exports.GraphemeIterator = exports.CodePointIterator = void 0;
    exports.isFalsyOrWhitespace = isFalsyOrWhitespace;
    exports.format = format;
    exports.htmlAttributeEncodeValue = htmlAttributeEncodeValue;
    exports.escape = escape;
    exports.escapeRegExpCharacters = escapeRegExpCharacters;
    exports.trim = trim;
    exports.ltrim = ltrim;
    exports.rtrim = rtrim;
    exports.convertSimple2RegExpPattern = convertSimple2RegExpPattern;
    exports.stripWildcards = stripWildcards;
    exports.createRegExp = createRegExp;
    exports.regExpLeadsToEndlessLoop = regExpLeadsToEndlessLoop;
    exports.splitLines = splitLines;
    exports.splitLinesIncludeSeparators = splitLinesIncludeSeparators;
    exports.firstNonWhitespaceIndex = firstNonWhitespaceIndex;
    exports.getLeadingWhitespace = getLeadingWhitespace;
    exports.lastNonWhitespaceIndex = lastNonWhitespaceIndex;
    exports.compare = compare;
    exports.compareSubstring = compareSubstring;
    exports.compareIgnoreCase = compareIgnoreCase;
    exports.compareSubstringIgnoreCase = compareSubstringIgnoreCase;
    exports.isAsciiDigit = isAsciiDigit;
    exports.isLowerAsciiLetter = isLowerAsciiLetter;
    exports.isUpperAsciiLetter = isUpperAsciiLetter;
    exports.equalsIgnoreCase = equalsIgnoreCase;
    exports.startsWithIgnoreCase = startsWithIgnoreCase;
    exports.commonPrefixLength = commonPrefixLength;
    exports.commonSuffixLength = commonSuffixLength;
    exports.isHighSurrogate = isHighSurrogate;
    exports.isLowSurrogate = isLowSurrogate;
    exports.computeCodePoint = computeCodePoint;
    exports.getNextCodePoint = getNextCodePoint;
    exports.nextCharLength = nextCharLength;
    exports.prevCharLength = prevCharLength;
    exports.getCharContainingOffset = getCharContainingOffset;
    exports.containsRTL = containsRTL;
    exports.isBasicASCII = isBasicASCII;
    exports.containsUnusualLineTerminators = containsUnusualLineTerminators;
    exports.isFullWidthCharacter = isFullWidthCharacter;
    exports.isEmojiImprecise = isEmojiImprecise;
    exports.startsWithUTF8BOM = startsWithUTF8BOM;
    exports.containsUppercaseCharacter = containsUppercaseCharacter;
    exports.singleLetterHash = singleLetterHash;
    exports.getLeftDeleteOffset = getLeftDeleteOffset;
    function isFalsyOrWhitespace(str) {
        if (!str || typeof str !== 'string') {
            return true;
        }
        return str.trim().length === 0;
    }
    const _formatRegexp = /{(\d+)}/g;
    /**
     * Helper to produce a string with a variable number of arguments. Insert variable segments
     * into the string using the {n} notation where N is the index of the argument following the string.
     * @param value string to which formatting is applied
     * @param args replacements for {n}-entries
     */
    function format(value, ...args) {
        if (args.length === 0) {
            return value;
        }
        return value.replace(_formatRegexp, function (match, group) {
            const idx = parseInt(group, 10);
            return isNaN(idx) || idx < 0 || idx >= args.length ?
                match :
                args[idx];
        });
    }
    /**
     * Encodes the given value so that it can be used as literal value in html attributes.
     *
     * In other words, computes `$val`, such that `attr` in `<div attr="$val" />` has the runtime value `value`.
     * This prevents XSS injection.
     */
    function htmlAttributeEncodeValue(value) {
        return value.replace(/[<>"'&]/g, ch => {
            switch (ch) {
                case '<': return '&lt;';
                case '>': return '&gt;';
                case '"': return '&quot;';
                case '\'': return '&apos;';
                case '&': return '&amp;';
            }
            return ch;
        });
    }
    /**
     * Converts HTML characters inside the string to use entities instead. Makes the string safe from
     * being used e.g. in HTMLElement.innerHTML.
     */
    function escape(html) {
        return html.replace(/[<>&]/g, function (match) {
            switch (match) {
                case '<': return '&lt;';
                case '>': return '&gt;';
                case '&': return '&amp;';
                default: return match;
            }
        });
    }
    /**
     * Escapes regular expression characters in a given string
     */
    function escapeRegExpCharacters(value) {
        return value.replace(/[\\\{\}\*\+\?\|\^\$\.\[\]\(\)]/g, '\\$&');
    }
    /**
     * Removes all occurrences of needle from the beginning and end of haystack.
     * @param haystack string to trim
     * @param needle the thing to trim (default is a blank)
     */
    function trim(haystack, needle = ' ') {
        const trimmed = ltrim(haystack, needle);
        return rtrim(trimmed, needle);
    }
    /**
     * Removes all occurrences of needle from the beginning of haystack.
     * @param haystack string to trim
     * @param needle the thing to trim
     */
    function ltrim(haystack, needle) {
        if (!haystack || !needle) {
            return haystack;
        }
        const needleLen = needle.length;
        if (needleLen === 0 || haystack.length === 0) {
            return haystack;
        }
        let offset = 0;
        while (haystack.indexOf(needle, offset) === offset) {
            offset = offset + needleLen;
        }
        return haystack.substring(offset);
    }
    /**
     * Removes all occurrences of needle from the end of haystack.
     * @param haystack string to trim
     * @param needle the thing to trim
     */
    function rtrim(haystack, needle) {
        if (!haystack || !needle) {
            return haystack;
        }
        const needleLen = needle.length, haystackLen = haystack.length;
        if (needleLen === 0 || haystackLen === 0) {
            return haystack;
        }
        let offset = haystackLen, idx = -1;
        while (true) {
            idx = haystack.lastIndexOf(needle, offset - 1);
            if (idx === -1 || idx + needleLen !== offset) {
                break;
            }
            if (idx === 0) {
                return '';
            }
            offset = idx;
        }
        return haystack.substring(0, offset);
    }
    function convertSimple2RegExpPattern(pattern) {
        return pattern.replace(/[\-\\\{\}\+\?\|\^\$\.\,\[\]\(\)\#\s]/g, '\\$&').replace(/[\*]/g, '.*');
    }
    function stripWildcards(pattern) {
        return pattern.replace(/\*/g, '');
    }
    function createRegExp(searchString, isRegex, options = {}) {
        if (!searchString) {
            throw new Error('Cannot create regex from empty string');
        }
        if (!isRegex) {
            searchString = escapeRegExpCharacters(searchString);
        }
        if (options.wholeWord) {
            if (!/\B/.test(searchString.charAt(0))) {
                searchString = '\\b' + searchString;
            }
            if (!/\B/.test(searchString.charAt(searchString.length - 1))) {
                searchString = searchString + '\\b';
            }
        }
        let modifiers = '';
        if (options.global) {
            modifiers += 'g';
        }
        if (!options.matchCase) {
            modifiers += 'i';
        }
        if (options.multiline) {
            modifiers += 'm';
        }
        if (options.unicode) {
            modifiers += 'u';
        }
        return new RegExp(searchString, modifiers);
    }
    function regExpLeadsToEndlessLoop(regexp) {
        // Exit early if it's one of these special cases which are meant to match
        // against an empty string
        if (regexp.source === '^' || regexp.source === '^$' || regexp.source === '$' || regexp.source === '^\\s*$') {
            return false;
        }
        // We check against an empty string. If the regular expression doesn't advance
        // (e.g. ends in an endless loop) it will match an empty string.
        const match = regexp.exec('');
        return !!(match && regexp.lastIndex === 0);
    }
    function splitLines(str) {
        return str.split(/\r\n|\r|\n/);
    }
    function splitLinesIncludeSeparators(str) {
        const linesWithSeparators = [];
        const splitLinesAndSeparators = str.split(/(\r\n|\r|\n)/);
        for (let i = 0; i < Math.ceil(splitLinesAndSeparators.length / 2); i++) {
            linesWithSeparators.push(splitLinesAndSeparators[2 * i] + (splitLinesAndSeparators[2 * i + 1] ?? ''));
        }
        return linesWithSeparators;
    }
    /**
     * Returns first index of the string that is not whitespace.
     * If string is empty or contains only whitespaces, returns -1
     */
    function firstNonWhitespaceIndex(str) {
        for (let i = 0, len = str.length; i < len; i++) {
            const chCode = str.charCodeAt(i);
            if (chCode !== 32 /* CharCode.Space */ && chCode !== 9 /* CharCode.Tab */) {
                return i;
            }
        }
        return -1;
    }
    /**
     * Returns the leading whitespace of the string.
     * If the string contains only whitespaces, returns entire string
     */
    function getLeadingWhitespace(str, start = 0, end = str.length) {
        for (let i = start; i < end; i++) {
            const chCode = str.charCodeAt(i);
            if (chCode !== 32 /* CharCode.Space */ && chCode !== 9 /* CharCode.Tab */) {
                return str.substring(start, i);
            }
        }
        return str.substring(start, end);
    }
    /**
     * Returns last index of the string that is not whitespace.
     * If string is empty or contains only whitespaces, returns -1
     */
    function lastNonWhitespaceIndex(str, startIndex = str.length - 1) {
        for (let i = startIndex; i >= 0; i--) {
            const chCode = str.charCodeAt(i);
            if (chCode !== 32 /* CharCode.Space */ && chCode !== 9 /* CharCode.Tab */) {
                return i;
            }
        }
        return -1;
    }
    function compare(a, b) {
        if (a < b) {
            return -1;
        }
        else if (a > b) {
            return 1;
        }
        else {
            return 0;
        }
    }
    function compareSubstring(a, b, aStart = 0, aEnd = a.length, bStart = 0, bEnd = b.length) {
        for (; aStart < aEnd && bStart < bEnd; aStart++, bStart++) {
            const codeA = a.charCodeAt(aStart);
            const codeB = b.charCodeAt(bStart);
            if (codeA < codeB) {
                return -1;
            }
            else if (codeA > codeB) {
                return 1;
            }
        }
        const aLen = aEnd - aStart;
        const bLen = bEnd - bStart;
        if (aLen < bLen) {
            return -1;
        }
        else if (aLen > bLen) {
            return 1;
        }
        return 0;
    }
    function compareIgnoreCase(a, b) {
        return compareSubstringIgnoreCase(a, b, 0, a.length, 0, b.length);
    }
    function compareSubstringIgnoreCase(a, b, aStart = 0, aEnd = a.length, bStart = 0, bEnd = b.length) {
        for (; aStart < aEnd && bStart < bEnd; aStart++, bStart++) {
            let codeA = a.charCodeAt(aStart);
            let codeB = b.charCodeAt(bStart);
            if (codeA === codeB) {
                // equal
                continue;
            }
            if (codeA >= 128 || codeB >= 128) {
                // not ASCII letters -> fallback to lower-casing strings
                return compareSubstring(a.toLowerCase(), b.toLowerCase(), aStart, aEnd, bStart, bEnd);
            }
            // mapper lower-case ascii letter onto upper-case varinats
            // [97-122] (lower ascii) --> [65-90] (upper ascii)
            if (isLowerAsciiLetter(codeA)) {
                codeA -= 32;
            }
            if (isLowerAsciiLetter(codeB)) {
                codeB -= 32;
            }
            // compare both code points
            const diff = codeA - codeB;
            if (diff === 0) {
                continue;
            }
            return diff;
        }
        const aLen = aEnd - aStart;
        const bLen = bEnd - bStart;
        if (aLen < bLen) {
            return -1;
        }
        else if (aLen > bLen) {
            return 1;
        }
        return 0;
    }
    function isAsciiDigit(code) {
        return code >= 48 /* CharCode.Digit0 */ && code <= 57 /* CharCode.Digit9 */;
    }
    function isLowerAsciiLetter(code) {
        return code >= 97 /* CharCode.a */ && code <= 122 /* CharCode.z */;
    }
    function isUpperAsciiLetter(code) {
        return code >= 65 /* CharCode.A */ && code <= 90 /* CharCode.Z */;
    }
    function equalsIgnoreCase(a, b) {
        return a.length === b.length && compareSubstringIgnoreCase(a, b) === 0;
    }
    function startsWithIgnoreCase(str, candidate) {
        const candidateLength = candidate.length;
        if (candidate.length > str.length) {
            return false;
        }
        return compareSubstringIgnoreCase(str, candidate, 0, candidateLength) === 0;
    }
    /**
     * @returns the length of the common prefix of the two strings.
     */
    function commonPrefixLength(a, b) {
        const len = Math.min(a.length, b.length);
        let i;
        for (i = 0; i < len; i++) {
            if (a.charCodeAt(i) !== b.charCodeAt(i)) {
                return i;
            }
        }
        return len;
    }
    /**
     * @returns the length of the common suffix of the two strings.
     */
    function commonSuffixLength(a, b) {
        const len = Math.min(a.length, b.length);
        let i;
        const aLastIndex = a.length - 1;
        const bLastIndex = b.length - 1;
        for (i = 0; i < len; i++) {
            if (a.charCodeAt(aLastIndex - i) !== b.charCodeAt(bLastIndex - i)) {
                return i;
            }
        }
        return len;
    }
    /**
     * See http://en.wikipedia.org/wiki/Surrogate_pair
     */
    function isHighSurrogate(charCode) {
        return (0xD800 <= charCode && charCode <= 0xDBFF);
    }
    /**
     * See http://en.wikipedia.org/wiki/Surrogate_pair
     */
    function isLowSurrogate(charCode) {
        return (0xDC00 <= charCode && charCode <= 0xDFFF);
    }
    /**
     * See http://en.wikipedia.org/wiki/Surrogate_pair
     */
    function computeCodePoint(highSurrogate, lowSurrogate) {
        return ((highSurrogate - 0xD800) << 10) + (lowSurrogate - 0xDC00) + 0x10000;
    }
    /**
     * get the code point that begins at offset `offset`
     */
    function getNextCodePoint(str, len, offset) {
        const charCode = str.charCodeAt(offset);
        if (isHighSurrogate(charCode) && offset + 1 < len) {
            const nextCharCode = str.charCodeAt(offset + 1);
            if (isLowSurrogate(nextCharCode)) {
                return computeCodePoint(charCode, nextCharCode);
            }
        }
        return charCode;
    }
    /**
     * get the code point that ends right before offset `offset`
     */
    function getPrevCodePoint(str, offset) {
        const charCode = str.charCodeAt(offset - 1);
        if (isLowSurrogate(charCode) && offset > 1) {
            const prevCharCode = str.charCodeAt(offset - 2);
            if (isHighSurrogate(prevCharCode)) {
                return computeCodePoint(prevCharCode, charCode);
            }
        }
        return charCode;
    }
    class CodePointIterator {
        get offset() {
            return this._offset;
        }
        constructor(str, offset = 0) {
            this._str = str;
            this._len = str.length;
            this._offset = offset;
        }
        setOffset(offset) {
            this._offset = offset;
        }
        prevCodePoint() {
            const codePoint = getPrevCodePoint(this._str, this._offset);
            this._offset -= (codePoint >= 65536 /* Constants.UNICODE_SUPPLEMENTARY_PLANE_BEGIN */ ? 2 : 1);
            return codePoint;
        }
        nextCodePoint() {
            const codePoint = getNextCodePoint(this._str, this._len, this._offset);
            this._offset += (codePoint >= 65536 /* Constants.UNICODE_SUPPLEMENTARY_PLANE_BEGIN */ ? 2 : 1);
            return codePoint;
        }
        eol() {
            return (this._offset >= this._len);
        }
    }
    exports.CodePointIterator = CodePointIterator;
    class GraphemeIterator {
        get offset() {
            return this._iterator.offset;
        }
        constructor(str, offset = 0) {
            this._iterator = new CodePointIterator(str, offset);
        }
        nextGraphemeLength() {
            const graphemeBreakTree = GraphemeBreakTree.getInstance();
            const iterator = this._iterator;
            const initialOffset = iterator.offset;
            let graphemeBreakType = graphemeBreakTree.getGraphemeBreakType(iterator.nextCodePoint());
            while (!iterator.eol()) {
                const offset = iterator.offset;
                const nextGraphemeBreakType = graphemeBreakTree.getGraphemeBreakType(iterator.nextCodePoint());
                if (breakBetweenGraphemeBreakType(graphemeBreakType, nextGraphemeBreakType)) {
                    // move iterator back
                    iterator.setOffset(offset);
                    break;
                }
                graphemeBreakType = nextGraphemeBreakType;
            }
            return (iterator.offset - initialOffset);
        }
        prevGraphemeLength() {
            const graphemeBreakTree = GraphemeBreakTree.getInstance();
            const iterator = this._iterator;
            const initialOffset = iterator.offset;
            let graphemeBreakType = graphemeBreakTree.getGraphemeBreakType(iterator.prevCodePoint());
            while (iterator.offset > 0) {
                const offset = iterator.offset;
                const prevGraphemeBreakType = graphemeBreakTree.getGraphemeBreakType(iterator.prevCodePoint());
                if (breakBetweenGraphemeBreakType(prevGraphemeBreakType, graphemeBreakType)) {
                    // move iterator back
                    iterator.setOffset(offset);
                    break;
                }
                graphemeBreakType = prevGraphemeBreakType;
            }
            return (initialOffset - iterator.offset);
        }
        eol() {
            return this._iterator.eol();
        }
    }
    exports.GraphemeIterator = GraphemeIterator;
    function nextCharLength(str, initialOffset) {
        const iterator = new GraphemeIterator(str, initialOffset);
        return iterator.nextGraphemeLength();
    }
    function prevCharLength(str, initialOffset) {
        const iterator = new GraphemeIterator(str, initialOffset);
        return iterator.prevGraphemeLength();
    }
    function getCharContainingOffset(str, offset) {
        if (offset > 0 && isLowSurrogate(str.charCodeAt(offset))) {
            offset--;
        }
        const endOffset = offset + nextCharLength(str, offset);
        const startOffset = endOffset - prevCharLength(str, endOffset);
        return [startOffset, endOffset];
    }
    let CONTAINS_RTL = undefined;
    function makeContainsRtl() {
        // Generated using https://github.com/alexdima/unicode-utils/blob/main/rtl-test.js
        return /(?:[\u05BE\u05C0\u05C3\u05C6\u05D0-\u05F4\u0608\u060B\u060D\u061B-\u064A\u066D-\u066F\u0671-\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u0710\u0712-\u072F\u074D-\u07A5\u07B1-\u07EA\u07F4\u07F5\u07FA\u07FE-\u0815\u081A\u0824\u0828\u0830-\u0858\u085E-\u088E\u08A0-\u08C9\u200F\uFB1D\uFB1F-\uFB28\uFB2A-\uFD3D\uFD50-\uFDC7\uFDF0-\uFDFC\uFE70-\uFEFC]|\uD802[\uDC00-\uDD1B\uDD20-\uDE00\uDE10-\uDE35\uDE40-\uDEE4\uDEEB-\uDF35\uDF40-\uDFFF]|\uD803[\uDC00-\uDD23\uDE80-\uDEA9\uDEAD-\uDF45\uDF51-\uDF81\uDF86-\uDFF6]|\uD83A[\uDC00-\uDCCF\uDD00-\uDD43\uDD4B-\uDFFF]|\uD83B[\uDC00-\uDEBB])/;
    }
    /**
     * Returns true if `str` contains any Unicode character that is classified as "R" or "AL".
     */
    function containsRTL(str) {
        if (!CONTAINS_RTL) {
            CONTAINS_RTL = makeContainsRtl();
        }
        return CONTAINS_RTL.test(str);
    }
    const IS_BASIC_ASCII = /^[\t\n\r\x20-\x7E]*$/;
    /**
     * Returns true if `str` contains only basic ASCII characters in the range 32 - 126 (including 32 and 126) or \n, \r, \t
     */
    function isBasicASCII(str) {
        return IS_BASIC_ASCII.test(str);
    }
    exports.UNUSUAL_LINE_TERMINATORS = /[\u2028\u2029]/; // LINE SEPARATOR (LS) or PARAGRAPH SEPARATOR (PS)
    /**
     * Returns true if `str` contains unusual line terminators, like LS or PS
     */
    function containsUnusualLineTerminators(str) {
        return exports.UNUSUAL_LINE_TERMINATORS.test(str);
    }
    function isFullWidthCharacter(charCode) {
        // Do a cheap trick to better support wrapping of wide characters, treat them as 2 columns
        // http://jrgraphix.net/research/unicode_blocks.php
        //          2E80 - 2EFF   CJK Radicals Supplement
        //          2F00 - 2FDF   Kangxi Radicals
        //          2FF0 - 2FFF   Ideographic Description Characters
        //          3000 - 303F   CJK Symbols and Punctuation
        //          3040 - 309F   Hiragana
        //          30A0 - 30FF   Katakana
        //          3100 - 312F   Bopomofo
        //          3130 - 318F   Hangul Compatibility Jamo
        //          3190 - 319F   Kanbun
        //          31A0 - 31BF   Bopomofo Extended
        //          31F0 - 31FF   Katakana Phonetic Extensions
        //          3200 - 32FF   Enclosed CJK Letters and Months
        //          3300 - 33FF   CJK Compatibility
        //          3400 - 4DBF   CJK Unified Ideographs Extension A
        //          4DC0 - 4DFF   Yijing Hexagram Symbols
        //          4E00 - 9FFF   CJK Unified Ideographs
        //          A000 - A48F   Yi Syllables
        //          A490 - A4CF   Yi Radicals
        //          AC00 - D7AF   Hangul Syllables
        // [IGNORE] D800 - DB7F   High Surrogates
        // [IGNORE] DB80 - DBFF   High Private Use Surrogates
        // [IGNORE] DC00 - DFFF   Low Surrogates
        // [IGNORE] E000 - F8FF   Private Use Area
        //          F900 - FAFF   CJK Compatibility Ideographs
        // [IGNORE] FB00 - FB4F   Alphabetic Presentation Forms
        // [IGNORE] FB50 - FDFF   Arabic Presentation Forms-A
        // [IGNORE] FE00 - FE0F   Variation Selectors
        // [IGNORE] FE20 - FE2F   Combining Half Marks
        // [IGNORE] FE30 - FE4F   CJK Compatibility Forms
        // [IGNORE] FE50 - FE6F   Small Form Variants
        // [IGNORE] FE70 - FEFF   Arabic Presentation Forms-B
        //          FF00 - FFEF   Halfwidth and Fullwidth Forms
        //               [https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms]
        //               of which FF01 - FF5E fullwidth ASCII of 21 to 7E
        // [IGNORE]    and FF65 - FFDC halfwidth of Katakana and Hangul
        // [IGNORE] FFF0 - FFFF   Specials
        return ((charCode >= 0x2E80 && charCode <= 0xD7AF)
            || (charCode >= 0xF900 && charCode <= 0xFAFF)
            || (charCode >= 0xFF01 && charCode <= 0xFF5E));
    }
    /**
     * A fast function (therefore imprecise) to check if code points are emojis.
     * Generated using https://github.com/alexdima/unicode-utils/blob/main/emoji-test.js
     */
    function isEmojiImprecise(x) {
        return ((x >= 0x1F1E6 && x <= 0x1F1FF) || (x === 8986) || (x === 8987) || (x === 9200)
            || (x === 9203) || (x >= 9728 && x <= 10175) || (x === 11088) || (x === 11093)
            || (x >= 127744 && x <= 128591) || (x >= 128640 && x <= 128764)
            || (x >= 128992 && x <= 129008) || (x >= 129280 && x <= 129535)
            || (x >= 129648 && x <= 129782));
    }
    // -- UTF-8 BOM
    exports.UTF8_BOM_CHARACTER = String.fromCharCode(65279 /* CharCode.UTF8_BOM */);
    function startsWithUTF8BOM(str) {
        return !!(str && str.length > 0 && str.charCodeAt(0) === 65279 /* CharCode.UTF8_BOM */);
    }
    function containsUppercaseCharacter(target, ignoreEscapedChars = false) {
        if (!target) {
            return false;
        }
        if (ignoreEscapedChars) {
            target = target.replace(/\\./g, '');
        }
        return target.toLowerCase() !== target;
    }
    /**
     * Produces 'a'-'z', followed by 'A'-'Z'... followed by 'a'-'z', etc.
     */
    function singleLetterHash(n) {
        const LETTERS_CNT = (90 /* CharCode.Z */ - 65 /* CharCode.A */ + 1);
        n = n % (2 * LETTERS_CNT);
        if (n < LETTERS_CNT) {
            return String.fromCharCode(97 /* CharCode.a */ + n);
        }
        return String.fromCharCode(65 /* CharCode.A */ + n - LETTERS_CNT);
    }
    function breakBetweenGraphemeBreakType(breakTypeA, breakTypeB) {
        // http://www.unicode.org/reports/tr29/#Grapheme_Cluster_Boundary_Rules
        // !!! Let's make the common case a bit faster
        if (breakTypeA === 0 /* GraphemeBreakType.Other */) {
            // see https://www.unicode.org/Public/13.0.0/ucd/auxiliary/GraphemeBreakTest-13.0.0d10.html#table
            return (breakTypeB !== 5 /* GraphemeBreakType.Extend */ && breakTypeB !== 7 /* GraphemeBreakType.SpacingMark */);
        }
        // Do not break between a CR and LF. Otherwise, break before and after controls.
        // GB3                                        CR × LF
        // GB4                       (Control | CR | LF) ÷
        // GB5                                           ÷ (Control | CR | LF)
        if (breakTypeA === 2 /* GraphemeBreakType.CR */) {
            if (breakTypeB === 3 /* GraphemeBreakType.LF */) {
                return false; // GB3
            }
        }
        if (breakTypeA === 4 /* GraphemeBreakType.Control */ || breakTypeA === 2 /* GraphemeBreakType.CR */ || breakTypeA === 3 /* GraphemeBreakType.LF */) {
            return true; // GB4
        }
        if (breakTypeB === 4 /* GraphemeBreakType.Control */ || breakTypeB === 2 /* GraphemeBreakType.CR */ || breakTypeB === 3 /* GraphemeBreakType.LF */) {
            return true; // GB5
        }
        // Do not break Hangul syllable sequences.
        // GB6                                         L × (L | V | LV | LVT)
        // GB7                                  (LV | V) × (V | T)
        // GB8                                 (LVT | T) × T
        if (breakTypeA === 8 /* GraphemeBreakType.L */) {
            if (breakTypeB === 8 /* GraphemeBreakType.L */ || breakTypeB === 9 /* GraphemeBreakType.V */ || breakTypeB === 11 /* GraphemeBreakType.LV */ || breakTypeB === 12 /* GraphemeBreakType.LVT */) {
                return false; // GB6
            }
        }
        if (breakTypeA === 11 /* GraphemeBreakType.LV */ || breakTypeA === 9 /* GraphemeBreakType.V */) {
            if (breakTypeB === 9 /* GraphemeBreakType.V */ || breakTypeB === 10 /* GraphemeBreakType.T */) {
                return false; // GB7
            }
        }
        if (breakTypeA === 12 /* GraphemeBreakType.LVT */ || breakTypeA === 10 /* GraphemeBreakType.T */) {
            if (breakTypeB === 10 /* GraphemeBreakType.T */) {
                return false; // GB8
            }
        }
        // Do not break before extending characters or ZWJ.
        // GB9                                           × (Extend | ZWJ)
        if (breakTypeB === 5 /* GraphemeBreakType.Extend */ || breakTypeB === 13 /* GraphemeBreakType.ZWJ */) {
            return false; // GB9
        }
        // The GB9a and GB9b rules only apply to extended grapheme clusters:
        // Do not break before SpacingMarks, or after Prepend characters.
        // GB9a                                          × SpacingMark
        // GB9b                                  Prepend ×
        if (breakTypeB === 7 /* GraphemeBreakType.SpacingMark */) {
            return false; // GB9a
        }
        if (breakTypeA === 1 /* GraphemeBreakType.Prepend */) {
            return false; // GB9b
        }
        // Do not break within emoji modifier sequences or emoji zwj sequences.
        // GB11    \p{Extended_Pictographic} Extend* ZWJ × \p{Extended_Pictographic}
        if (breakTypeA === 13 /* GraphemeBreakType.ZWJ */ && breakTypeB === 14 /* GraphemeBreakType.Extended_Pictographic */) {
            // Note: we are not implementing the rule entirely here to avoid introducing states
            return false; // GB11
        }
        // GB12                          sot (RI RI)* RI × RI
        // GB13                        [^RI] (RI RI)* RI × RI
        if (breakTypeA === 6 /* GraphemeBreakType.Regional_Indicator */ && breakTypeB === 6 /* GraphemeBreakType.Regional_Indicator */) {
            // Note: we are not implementing the rule entirely here to avoid introducing states
            return false; // GB12 & GB13
        }
        // GB999                                     Any ÷ Any
        return true;
    }
    class GraphemeBreakTree {
        static { this._INSTANCE = null; }
        static getInstance() {
            if (!GraphemeBreakTree._INSTANCE) {
                GraphemeBreakTree._INSTANCE = new GraphemeBreakTree();
            }
            return GraphemeBreakTree._INSTANCE;
        }
        constructor() {
            this._data = getGraphemeBreakRawData();
        }
        getGraphemeBreakType(codePoint) {
            // !!! Let's make 7bit ASCII a bit faster: 0..31
            if (codePoint < 32) {
                if (codePoint === 10 /* CharCode.LineFeed */) {
                    return 3 /* GraphemeBreakType.LF */;
                }
                if (codePoint === 13 /* CharCode.CarriageReturn */) {
                    return 2 /* GraphemeBreakType.CR */;
                }
                return 4 /* GraphemeBreakType.Control */;
            }
            // !!! Let's make 7bit ASCII a bit faster: 32..126
            if (codePoint < 127) {
                return 0 /* GraphemeBreakType.Other */;
            }
            const data = this._data;
            const nodeCount = data.length / 3;
            let nodeIndex = 1;
            while (nodeIndex <= nodeCount) {
                if (codePoint < data[3 * nodeIndex]) {
                    // go left
                    nodeIndex = 2 * nodeIndex;
                }
                else if (codePoint > data[3 * nodeIndex + 1]) {
                    // go right
                    nodeIndex = 2 * nodeIndex + 1;
                }
                else {
                    // hit
                    return data[3 * nodeIndex + 2];
                }
            }
            return 0 /* GraphemeBreakType.Other */;
        }
    }
    function getGraphemeBreakRawData() {
        // generated using https://github.com/alexdima/unicode-utils/blob/main/grapheme-break.js
        return JSON.parse('[0,0,0,51229,51255,12,44061,44087,12,127462,127487,6,7083,7085,5,47645,47671,12,54813,54839,12,128678,128678,14,3270,3270,5,9919,9923,14,45853,45879,12,49437,49463,12,53021,53047,12,71216,71218,7,128398,128399,14,129360,129374,14,2519,2519,5,4448,4519,9,9742,9742,14,12336,12336,14,44957,44983,12,46749,46775,12,48541,48567,12,50333,50359,12,52125,52151,12,53917,53943,12,69888,69890,5,73018,73018,5,127990,127990,14,128558,128559,14,128759,128760,14,129653,129655,14,2027,2035,5,2891,2892,7,3761,3761,5,6683,6683,5,8293,8293,4,9825,9826,14,9999,9999,14,43452,43453,5,44509,44535,12,45405,45431,12,46301,46327,12,47197,47223,12,48093,48119,12,48989,49015,12,49885,49911,12,50781,50807,12,51677,51703,12,52573,52599,12,53469,53495,12,54365,54391,12,65279,65279,4,70471,70472,7,72145,72147,7,119173,119179,5,127799,127818,14,128240,128244,14,128512,128512,14,128652,128652,14,128721,128722,14,129292,129292,14,129445,129450,14,129734,129743,14,1476,1477,5,2366,2368,7,2750,2752,7,3076,3076,5,3415,3415,5,4141,4144,5,6109,6109,5,6964,6964,5,7394,7400,5,9197,9198,14,9770,9770,14,9877,9877,14,9968,9969,14,10084,10084,14,43052,43052,5,43713,43713,5,44285,44311,12,44733,44759,12,45181,45207,12,45629,45655,12,46077,46103,12,46525,46551,12,46973,46999,12,47421,47447,12,47869,47895,12,48317,48343,12,48765,48791,12,49213,49239,12,49661,49687,12,50109,50135,12,50557,50583,12,51005,51031,12,51453,51479,12,51901,51927,12,52349,52375,12,52797,52823,12,53245,53271,12,53693,53719,12,54141,54167,12,54589,54615,12,55037,55063,12,69506,69509,5,70191,70193,5,70841,70841,7,71463,71467,5,72330,72342,5,94031,94031,5,123628,123631,5,127763,127765,14,127941,127941,14,128043,128062,14,128302,128317,14,128465,128467,14,128539,128539,14,128640,128640,14,128662,128662,14,128703,128703,14,128745,128745,14,129004,129007,14,129329,129330,14,129402,129402,14,129483,129483,14,129686,129704,14,130048,131069,14,173,173,4,1757,1757,1,2200,2207,5,2434,2435,7,2631,2632,5,2817,2817,5,3008,3008,5,3201,3201,5,3387,3388,5,3542,3542,5,3902,3903,7,4190,4192,5,6002,6003,5,6439,6440,5,6765,6770,7,7019,7027,5,7154,7155,7,8205,8205,13,8505,8505,14,9654,9654,14,9757,9757,14,9792,9792,14,9852,9853,14,9890,9894,14,9937,9937,14,9981,9981,14,10035,10036,14,11035,11036,14,42654,42655,5,43346,43347,7,43587,43587,5,44006,44007,7,44173,44199,12,44397,44423,12,44621,44647,12,44845,44871,12,45069,45095,12,45293,45319,12,45517,45543,12,45741,45767,12,45965,45991,12,46189,46215,12,46413,46439,12,46637,46663,12,46861,46887,12,47085,47111,12,47309,47335,12,47533,47559,12,47757,47783,12,47981,48007,12,48205,48231,12,48429,48455,12,48653,48679,12,48877,48903,12,49101,49127,12,49325,49351,12,49549,49575,12,49773,49799,12,49997,50023,12,50221,50247,12,50445,50471,12,50669,50695,12,50893,50919,12,51117,51143,12,51341,51367,12,51565,51591,12,51789,51815,12,52013,52039,12,52237,52263,12,52461,52487,12,52685,52711,12,52909,52935,12,53133,53159,12,53357,53383,12,53581,53607,12,53805,53831,12,54029,54055,12,54253,54279,12,54477,54503,12,54701,54727,12,54925,54951,12,55149,55175,12,68101,68102,5,69762,69762,7,70067,70069,7,70371,70378,5,70720,70721,7,71087,71087,5,71341,71341,5,71995,71996,5,72249,72249,7,72850,72871,5,73109,73109,5,118576,118598,5,121505,121519,5,127245,127247,14,127568,127569,14,127777,127777,14,127872,127891,14,127956,127967,14,128015,128016,14,128110,128172,14,128259,128259,14,128367,128368,14,128424,128424,14,128488,128488,14,128530,128532,14,128550,128551,14,128566,128566,14,128647,128647,14,128656,128656,14,128667,128673,14,128691,128693,14,128715,128715,14,128728,128732,14,128752,128752,14,128765,128767,14,129096,129103,14,129311,129311,14,129344,129349,14,129394,129394,14,129413,129425,14,129466,129471,14,129511,129535,14,129664,129666,14,129719,129722,14,129760,129767,14,917536,917631,5,13,13,2,1160,1161,5,1564,1564,4,1807,1807,1,2085,2087,5,2307,2307,7,2382,2383,7,2497,2500,5,2563,2563,7,2677,2677,5,2763,2764,7,2879,2879,5,2914,2915,5,3021,3021,5,3142,3144,5,3263,3263,5,3285,3286,5,3398,3400,7,3530,3530,5,3633,3633,5,3864,3865,5,3974,3975,5,4155,4156,7,4229,4230,5,5909,5909,7,6078,6085,7,6277,6278,5,6451,6456,7,6744,6750,5,6846,6846,5,6972,6972,5,7074,7077,5,7146,7148,7,7222,7223,5,7416,7417,5,8234,8238,4,8417,8417,5,9000,9000,14,9203,9203,14,9730,9731,14,9748,9749,14,9762,9763,14,9776,9783,14,9800,9811,14,9831,9831,14,9872,9873,14,9882,9882,14,9900,9903,14,9929,9933,14,9941,9960,14,9974,9974,14,9989,9989,14,10006,10006,14,10062,10062,14,10160,10160,14,11647,11647,5,12953,12953,14,43019,43019,5,43232,43249,5,43443,43443,5,43567,43568,7,43696,43696,5,43765,43765,7,44013,44013,5,44117,44143,12,44229,44255,12,44341,44367,12,44453,44479,12,44565,44591,12,44677,44703,12,44789,44815,12,44901,44927,12,45013,45039,12,45125,45151,12,45237,45263,12,45349,45375,12,45461,45487,12,45573,45599,12,45685,45711,12,45797,45823,12,45909,45935,12,46021,46047,12,46133,46159,12,46245,46271,12,46357,46383,12,46469,46495,12,46581,46607,12,46693,46719,12,46805,46831,12,46917,46943,12,47029,47055,12,47141,47167,12,47253,47279,12,47365,47391,12,47477,47503,12,47589,47615,12,47701,47727,12,47813,47839,12,47925,47951,12,48037,48063,12,48149,48175,12,48261,48287,12,48373,48399,12,48485,48511,12,48597,48623,12,48709,48735,12,48821,48847,12,48933,48959,12,49045,49071,12,49157,49183,12,49269,49295,12,49381,49407,12,49493,49519,12,49605,49631,12,49717,49743,12,49829,49855,12,49941,49967,12,50053,50079,12,50165,50191,12,50277,50303,12,50389,50415,12,50501,50527,12,50613,50639,12,50725,50751,12,50837,50863,12,50949,50975,12,51061,51087,12,51173,51199,12,51285,51311,12,51397,51423,12,51509,51535,12,51621,51647,12,51733,51759,12,51845,51871,12,51957,51983,12,52069,52095,12,52181,52207,12,52293,52319,12,52405,52431,12,52517,52543,12,52629,52655,12,52741,52767,12,52853,52879,12,52965,52991,12,53077,53103,12,53189,53215,12,53301,53327,12,53413,53439,12,53525,53551,12,53637,53663,12,53749,53775,12,53861,53887,12,53973,53999,12,54085,54111,12,54197,54223,12,54309,54335,12,54421,54447,12,54533,54559,12,54645,54671,12,54757,54783,12,54869,54895,12,54981,55007,12,55093,55119,12,55243,55291,10,66045,66045,5,68325,68326,5,69688,69702,5,69817,69818,5,69957,69958,7,70089,70092,5,70198,70199,5,70462,70462,5,70502,70508,5,70750,70750,5,70846,70846,7,71100,71101,5,71230,71230,7,71351,71351,5,71737,71738,5,72000,72000,7,72160,72160,5,72273,72278,5,72752,72758,5,72882,72883,5,73031,73031,5,73461,73462,7,94192,94193,7,119149,119149,7,121403,121452,5,122915,122916,5,126980,126980,14,127358,127359,14,127535,127535,14,127759,127759,14,127771,127771,14,127792,127793,14,127825,127867,14,127897,127899,14,127945,127945,14,127985,127986,14,128000,128007,14,128021,128021,14,128066,128100,14,128184,128235,14,128249,128252,14,128266,128276,14,128335,128335,14,128379,128390,14,128407,128419,14,128444,128444,14,128481,128481,14,128499,128499,14,128526,128526,14,128536,128536,14,128543,128543,14,128556,128556,14,128564,128564,14,128577,128580,14,128643,128645,14,128649,128649,14,128654,128654,14,128660,128660,14,128664,128664,14,128675,128675,14,128686,128689,14,128695,128696,14,128705,128709,14,128717,128719,14,128725,128725,14,128736,128741,14,128747,128748,14,128755,128755,14,128762,128762,14,128981,128991,14,129009,129023,14,129160,129167,14,129296,129304,14,129320,129327,14,129340,129342,14,129356,129356,14,129388,129392,14,129399,129400,14,129404,129407,14,129432,129442,14,129454,129455,14,129473,129474,14,129485,129487,14,129648,129651,14,129659,129660,14,129671,129679,14,129709,129711,14,129728,129730,14,129751,129753,14,129776,129782,14,917505,917505,4,917760,917999,5,10,10,3,127,159,4,768,879,5,1471,1471,5,1536,1541,1,1648,1648,5,1767,1768,5,1840,1866,5,2070,2073,5,2137,2139,5,2274,2274,1,2363,2363,7,2377,2380,7,2402,2403,5,2494,2494,5,2507,2508,7,2558,2558,5,2622,2624,7,2641,2641,5,2691,2691,7,2759,2760,5,2786,2787,5,2876,2876,5,2881,2884,5,2901,2902,5,3006,3006,5,3014,3016,7,3072,3072,5,3134,3136,5,3157,3158,5,3260,3260,5,3266,3266,5,3274,3275,7,3328,3329,5,3391,3392,7,3405,3405,5,3457,3457,5,3536,3537,7,3551,3551,5,3636,3642,5,3764,3772,5,3895,3895,5,3967,3967,7,3993,4028,5,4146,4151,5,4182,4183,7,4226,4226,5,4253,4253,5,4957,4959,5,5940,5940,7,6070,6070,7,6087,6088,7,6158,6158,4,6432,6434,5,6448,6449,7,6679,6680,5,6742,6742,5,6754,6754,5,6783,6783,5,6912,6915,5,6966,6970,5,6978,6978,5,7042,7042,7,7080,7081,5,7143,7143,7,7150,7150,7,7212,7219,5,7380,7392,5,7412,7412,5,8203,8203,4,8232,8232,4,8265,8265,14,8400,8412,5,8421,8432,5,8617,8618,14,9167,9167,14,9200,9200,14,9410,9410,14,9723,9726,14,9733,9733,14,9745,9745,14,9752,9752,14,9760,9760,14,9766,9766,14,9774,9774,14,9786,9786,14,9794,9794,14,9823,9823,14,9828,9828,14,9833,9850,14,9855,9855,14,9875,9875,14,9880,9880,14,9885,9887,14,9896,9897,14,9906,9916,14,9926,9927,14,9935,9935,14,9939,9939,14,9962,9962,14,9972,9972,14,9978,9978,14,9986,9986,14,9997,9997,14,10002,10002,14,10017,10017,14,10055,10055,14,10071,10071,14,10133,10135,14,10548,10549,14,11093,11093,14,12330,12333,5,12441,12442,5,42608,42610,5,43010,43010,5,43045,43046,5,43188,43203,7,43302,43309,5,43392,43394,5,43446,43449,5,43493,43493,5,43571,43572,7,43597,43597,7,43703,43704,5,43756,43757,5,44003,44004,7,44009,44010,7,44033,44059,12,44089,44115,12,44145,44171,12,44201,44227,12,44257,44283,12,44313,44339,12,44369,44395,12,44425,44451,12,44481,44507,12,44537,44563,12,44593,44619,12,44649,44675,12,44705,44731,12,44761,44787,12,44817,44843,12,44873,44899,12,44929,44955,12,44985,45011,12,45041,45067,12,45097,45123,12,45153,45179,12,45209,45235,12,45265,45291,12,45321,45347,12,45377,45403,12,45433,45459,12,45489,45515,12,45545,45571,12,45601,45627,12,45657,45683,12,45713,45739,12,45769,45795,12,45825,45851,12,45881,45907,12,45937,45963,12,45993,46019,12,46049,46075,12,46105,46131,12,46161,46187,12,46217,46243,12,46273,46299,12,46329,46355,12,46385,46411,12,46441,46467,12,46497,46523,12,46553,46579,12,46609,46635,12,46665,46691,12,46721,46747,12,46777,46803,12,46833,46859,12,46889,46915,12,46945,46971,12,47001,47027,12,47057,47083,12,47113,47139,12,47169,47195,12,47225,47251,12,47281,47307,12,47337,47363,12,47393,47419,12,47449,47475,12,47505,47531,12,47561,47587,12,47617,47643,12,47673,47699,12,47729,47755,12,47785,47811,12,47841,47867,12,47897,47923,12,47953,47979,12,48009,48035,12,48065,48091,12,48121,48147,12,48177,48203,12,48233,48259,12,48289,48315,12,48345,48371,12,48401,48427,12,48457,48483,12,48513,48539,12,48569,48595,12,48625,48651,12,48681,48707,12,48737,48763,12,48793,48819,12,48849,48875,12,48905,48931,12,48961,48987,12,49017,49043,12,49073,49099,12,49129,49155,12,49185,49211,12,49241,49267,12,49297,49323,12,49353,49379,12,49409,49435,12,49465,49491,12,49521,49547,12,49577,49603,12,49633,49659,12,49689,49715,12,49745,49771,12,49801,49827,12,49857,49883,12,49913,49939,12,49969,49995,12,50025,50051,12,50081,50107,12,50137,50163,12,50193,50219,12,50249,50275,12,50305,50331,12,50361,50387,12,50417,50443,12,50473,50499,12,50529,50555,12,50585,50611,12,50641,50667,12,50697,50723,12,50753,50779,12,50809,50835,12,50865,50891,12,50921,50947,12,50977,51003,12,51033,51059,12,51089,51115,12,51145,51171,12,51201,51227,12,51257,51283,12,51313,51339,12,51369,51395,12,51425,51451,12,51481,51507,12,51537,51563,12,51593,51619,12,51649,51675,12,51705,51731,12,51761,51787,12,51817,51843,12,51873,51899,12,51929,51955,12,51985,52011,12,52041,52067,12,52097,52123,12,52153,52179,12,52209,52235,12,52265,52291,12,52321,52347,12,52377,52403,12,52433,52459,12,52489,52515,12,52545,52571,12,52601,52627,12,52657,52683,12,52713,52739,12,52769,52795,12,52825,52851,12,52881,52907,12,52937,52963,12,52993,53019,12,53049,53075,12,53105,53131,12,53161,53187,12,53217,53243,12,53273,53299,12,53329,53355,12,53385,53411,12,53441,53467,12,53497,53523,12,53553,53579,12,53609,53635,12,53665,53691,12,53721,53747,12,53777,53803,12,53833,53859,12,53889,53915,12,53945,53971,12,54001,54027,12,54057,54083,12,54113,54139,12,54169,54195,12,54225,54251,12,54281,54307,12,54337,54363,12,54393,54419,12,54449,54475,12,54505,54531,12,54561,54587,12,54617,54643,12,54673,54699,12,54729,54755,12,54785,54811,12,54841,54867,12,54897,54923,12,54953,54979,12,55009,55035,12,55065,55091,12,55121,55147,12,55177,55203,12,65024,65039,5,65520,65528,4,66422,66426,5,68152,68154,5,69291,69292,5,69633,69633,5,69747,69748,5,69811,69814,5,69826,69826,5,69932,69932,7,70016,70017,5,70079,70080,7,70095,70095,5,70196,70196,5,70367,70367,5,70402,70403,7,70464,70464,5,70487,70487,5,70709,70711,7,70725,70725,7,70833,70834,7,70843,70844,7,70849,70849,7,71090,71093,5,71103,71104,5,71227,71228,7,71339,71339,5,71344,71349,5,71458,71461,5,71727,71735,5,71985,71989,7,71998,71998,5,72002,72002,7,72154,72155,5,72193,72202,5,72251,72254,5,72281,72283,5,72344,72345,5,72766,72766,7,72874,72880,5,72885,72886,5,73023,73029,5,73104,73105,5,73111,73111,5,92912,92916,5,94095,94098,5,113824,113827,4,119142,119142,7,119155,119162,4,119362,119364,5,121476,121476,5,122888,122904,5,123184,123190,5,125252,125258,5,127183,127183,14,127340,127343,14,127377,127386,14,127491,127503,14,127548,127551,14,127744,127756,14,127761,127761,14,127769,127769,14,127773,127774,14,127780,127788,14,127796,127797,14,127820,127823,14,127869,127869,14,127894,127895,14,127902,127903,14,127943,127943,14,127947,127950,14,127972,127972,14,127988,127988,14,127992,127994,14,128009,128011,14,128019,128019,14,128023,128041,14,128064,128064,14,128102,128107,14,128174,128181,14,128238,128238,14,128246,128247,14,128254,128254,14,128264,128264,14,128278,128299,14,128329,128330,14,128348,128359,14,128371,128377,14,128392,128393,14,128401,128404,14,128421,128421,14,128433,128434,14,128450,128452,14,128476,128478,14,128483,128483,14,128495,128495,14,128506,128506,14,128519,128520,14,128528,128528,14,128534,128534,14,128538,128538,14,128540,128542,14,128544,128549,14,128552,128555,14,128557,128557,14,128560,128563,14,128565,128565,14,128567,128576,14,128581,128591,14,128641,128642,14,128646,128646,14,128648,128648,14,128650,128651,14,128653,128653,14,128655,128655,14,128657,128659,14,128661,128661,14,128663,128663,14,128665,128666,14,128674,128674,14,128676,128677,14,128679,128685,14,128690,128690,14,128694,128694,14,128697,128702,14,128704,128704,14,128710,128714,14,128716,128716,14,128720,128720,14,128723,128724,14,128726,128727,14,128733,128735,14,128742,128744,14,128746,128746,14,128749,128751,14,128753,128754,14,128756,128758,14,128761,128761,14,128763,128764,14,128884,128895,14,128992,129003,14,129008,129008,14,129036,129039,14,129114,129119,14,129198,129279,14,129293,129295,14,129305,129310,14,129312,129319,14,129328,129328,14,129331,129338,14,129343,129343,14,129351,129355,14,129357,129359,14,129375,129387,14,129393,129393,14,129395,129398,14,129401,129401,14,129403,129403,14,129408,129412,14,129426,129431,14,129443,129444,14,129451,129453,14,129456,129465,14,129472,129472,14,129475,129482,14,129484,129484,14,129488,129510,14,129536,129647,14,129652,129652,14,129656,129658,14,129661,129663,14,129667,129670,14,129680,129685,14,129705,129708,14,129712,129718,14,129723,129727,14,129731,129733,14,129744,129750,14,129754,129759,14,129768,129775,14,129783,129791,14,917504,917504,4,917506,917535,4,917632,917759,4,918000,921599,4,0,9,4,11,12,4,14,31,4,169,169,14,174,174,14,1155,1159,5,1425,1469,5,1473,1474,5,1479,1479,5,1552,1562,5,1611,1631,5,1750,1756,5,1759,1764,5,1770,1773,5,1809,1809,5,1958,1968,5,2045,2045,5,2075,2083,5,2089,2093,5,2192,2193,1,2250,2273,5,2275,2306,5,2362,2362,5,2364,2364,5,2369,2376,5,2381,2381,5,2385,2391,5,2433,2433,5,2492,2492,5,2495,2496,7,2503,2504,7,2509,2509,5,2530,2531,5,2561,2562,5,2620,2620,5,2625,2626,5,2635,2637,5,2672,2673,5,2689,2690,5,2748,2748,5,2753,2757,5,2761,2761,7,2765,2765,5,2810,2815,5,2818,2819,7,2878,2878,5,2880,2880,7,2887,2888,7,2893,2893,5,2903,2903,5,2946,2946,5,3007,3007,7,3009,3010,7,3018,3020,7,3031,3031,5,3073,3075,7,3132,3132,5,3137,3140,7,3146,3149,5,3170,3171,5,3202,3203,7,3262,3262,7,3264,3265,7,3267,3268,7,3271,3272,7,3276,3277,5,3298,3299,5,3330,3331,7,3390,3390,5,3393,3396,5,3402,3404,7,3406,3406,1,3426,3427,5,3458,3459,7,3535,3535,5,3538,3540,5,3544,3550,7,3570,3571,7,3635,3635,7,3655,3662,5,3763,3763,7,3784,3789,5,3893,3893,5,3897,3897,5,3953,3966,5,3968,3972,5,3981,3991,5,4038,4038,5,4145,4145,7,4153,4154,5,4157,4158,5,4184,4185,5,4209,4212,5,4228,4228,7,4237,4237,5,4352,4447,8,4520,4607,10,5906,5908,5,5938,5939,5,5970,5971,5,6068,6069,5,6071,6077,5,6086,6086,5,6089,6099,5,6155,6157,5,6159,6159,5,6313,6313,5,6435,6438,7,6441,6443,7,6450,6450,5,6457,6459,5,6681,6682,7,6741,6741,7,6743,6743,7,6752,6752,5,6757,6764,5,6771,6780,5,6832,6845,5,6847,6862,5,6916,6916,7,6965,6965,5,6971,6971,7,6973,6977,7,6979,6980,7,7040,7041,5,7073,7073,7,7078,7079,7,7082,7082,7,7142,7142,5,7144,7145,5,7149,7149,5,7151,7153,5,7204,7211,7,7220,7221,7,7376,7378,5,7393,7393,7,7405,7405,5,7415,7415,7,7616,7679,5,8204,8204,5,8206,8207,4,8233,8233,4,8252,8252,14,8288,8292,4,8294,8303,4,8413,8416,5,8418,8420,5,8482,8482,14,8596,8601,14,8986,8987,14,9096,9096,14,9193,9196,14,9199,9199,14,9201,9202,14,9208,9210,14,9642,9643,14,9664,9664,14,9728,9729,14,9732,9732,14,9735,9741,14,9743,9744,14,9746,9746,14,9750,9751,14,9753,9756,14,9758,9759,14,9761,9761,14,9764,9765,14,9767,9769,14,9771,9773,14,9775,9775,14,9784,9785,14,9787,9791,14,9793,9793,14,9795,9799,14,9812,9822,14,9824,9824,14,9827,9827,14,9829,9830,14,9832,9832,14,9851,9851,14,9854,9854,14,9856,9861,14,9874,9874,14,9876,9876,14,9878,9879,14,9881,9881,14,9883,9884,14,9888,9889,14,9895,9895,14,9898,9899,14,9904,9905,14,9917,9918,14,9924,9925,14,9928,9928,14,9934,9934,14,9936,9936,14,9938,9938,14,9940,9940,14,9961,9961,14,9963,9967,14,9970,9971,14,9973,9973,14,9975,9977,14,9979,9980,14,9982,9985,14,9987,9988,14,9992,9996,14,9998,9998,14,10000,10001,14,10004,10004,14,10013,10013,14,10024,10024,14,10052,10052,14,10060,10060,14,10067,10069,14,10083,10083,14,10085,10087,14,10145,10145,14,10175,10175,14,11013,11015,14,11088,11088,14,11503,11505,5,11744,11775,5,12334,12335,5,12349,12349,14,12951,12951,14,42607,42607,5,42612,42621,5,42736,42737,5,43014,43014,5,43043,43044,7,43047,43047,7,43136,43137,7,43204,43205,5,43263,43263,5,43335,43345,5,43360,43388,8,43395,43395,7,43444,43445,7,43450,43451,7,43454,43456,7,43561,43566,5,43569,43570,5,43573,43574,5,43596,43596,5,43644,43644,5,43698,43700,5,43710,43711,5,43755,43755,7,43758,43759,7,43766,43766,5,44005,44005,5,44008,44008,5,44012,44012,7,44032,44032,11,44060,44060,11,44088,44088,11,44116,44116,11,44144,44144,11,44172,44172,11,44200,44200,11,44228,44228,11,44256,44256,11,44284,44284,11,44312,44312,11,44340,44340,11,44368,44368,11,44396,44396,11,44424,44424,11,44452,44452,11,44480,44480,11,44508,44508,11,44536,44536,11,44564,44564,11,44592,44592,11,44620,44620,11,44648,44648,11,44676,44676,11,44704,44704,11,44732,44732,11,44760,44760,11,44788,44788,11,44816,44816,11,44844,44844,11,44872,44872,11,44900,44900,11,44928,44928,11,44956,44956,11,44984,44984,11,45012,45012,11,45040,45040,11,45068,45068,11,45096,45096,11,45124,45124,11,45152,45152,11,45180,45180,11,45208,45208,11,45236,45236,11,45264,45264,11,45292,45292,11,45320,45320,11,45348,45348,11,45376,45376,11,45404,45404,11,45432,45432,11,45460,45460,11,45488,45488,11,45516,45516,11,45544,45544,11,45572,45572,11,45600,45600,11,45628,45628,11,45656,45656,11,45684,45684,11,45712,45712,11,45740,45740,11,45768,45768,11,45796,45796,11,45824,45824,11,45852,45852,11,45880,45880,11,45908,45908,11,45936,45936,11,45964,45964,11,45992,45992,11,46020,46020,11,46048,46048,11,46076,46076,11,46104,46104,11,46132,46132,11,46160,46160,11,46188,46188,11,46216,46216,11,46244,46244,11,46272,46272,11,46300,46300,11,46328,46328,11,46356,46356,11,46384,46384,11,46412,46412,11,46440,46440,11,46468,46468,11,46496,46496,11,46524,46524,11,46552,46552,11,46580,46580,11,46608,46608,11,46636,46636,11,46664,46664,11,46692,46692,11,46720,46720,11,46748,46748,11,46776,46776,11,46804,46804,11,46832,46832,11,46860,46860,11,46888,46888,11,46916,46916,11,46944,46944,11,46972,46972,11,47000,47000,11,47028,47028,11,47056,47056,11,47084,47084,11,47112,47112,11,47140,47140,11,47168,47168,11,47196,47196,11,47224,47224,11,47252,47252,11,47280,47280,11,47308,47308,11,47336,47336,11,47364,47364,11,47392,47392,11,47420,47420,11,47448,47448,11,47476,47476,11,47504,47504,11,47532,47532,11,47560,47560,11,47588,47588,11,47616,47616,11,47644,47644,11,47672,47672,11,47700,47700,11,47728,47728,11,47756,47756,11,47784,47784,11,47812,47812,11,47840,47840,11,47868,47868,11,47896,47896,11,47924,47924,11,47952,47952,11,47980,47980,11,48008,48008,11,48036,48036,11,48064,48064,11,48092,48092,11,48120,48120,11,48148,48148,11,48176,48176,11,48204,48204,11,48232,48232,11,48260,48260,11,48288,48288,11,48316,48316,11,48344,48344,11,48372,48372,11,48400,48400,11,48428,48428,11,48456,48456,11,48484,48484,11,48512,48512,11,48540,48540,11,48568,48568,11,48596,48596,11,48624,48624,11,48652,48652,11,48680,48680,11,48708,48708,11,48736,48736,11,48764,48764,11,48792,48792,11,48820,48820,11,48848,48848,11,48876,48876,11,48904,48904,11,48932,48932,11,48960,48960,11,48988,48988,11,49016,49016,11,49044,49044,11,49072,49072,11,49100,49100,11,49128,49128,11,49156,49156,11,49184,49184,11,49212,49212,11,49240,49240,11,49268,49268,11,49296,49296,11,49324,49324,11,49352,49352,11,49380,49380,11,49408,49408,11,49436,49436,11,49464,49464,11,49492,49492,11,49520,49520,11,49548,49548,11,49576,49576,11,49604,49604,11,49632,49632,11,49660,49660,11,49688,49688,11,49716,49716,11,49744,49744,11,49772,49772,11,49800,49800,11,49828,49828,11,49856,49856,11,49884,49884,11,49912,49912,11,49940,49940,11,49968,49968,11,49996,49996,11,50024,50024,11,50052,50052,11,50080,50080,11,50108,50108,11,50136,50136,11,50164,50164,11,50192,50192,11,50220,50220,11,50248,50248,11,50276,50276,11,50304,50304,11,50332,50332,11,50360,50360,11,50388,50388,11,50416,50416,11,50444,50444,11,50472,50472,11,50500,50500,11,50528,50528,11,50556,50556,11,50584,50584,11,50612,50612,11,50640,50640,11,50668,50668,11,50696,50696,11,50724,50724,11,50752,50752,11,50780,50780,11,50808,50808,11,50836,50836,11,50864,50864,11,50892,50892,11,50920,50920,11,50948,50948,11,50976,50976,11,51004,51004,11,51032,51032,11,51060,51060,11,51088,51088,11,51116,51116,11,51144,51144,11,51172,51172,11,51200,51200,11,51228,51228,11,51256,51256,11,51284,51284,11,51312,51312,11,51340,51340,11,51368,51368,11,51396,51396,11,51424,51424,11,51452,51452,11,51480,51480,11,51508,51508,11,51536,51536,11,51564,51564,11,51592,51592,11,51620,51620,11,51648,51648,11,51676,51676,11,51704,51704,11,51732,51732,11,51760,51760,11,51788,51788,11,51816,51816,11,51844,51844,11,51872,51872,11,51900,51900,11,51928,51928,11,51956,51956,11,51984,51984,11,52012,52012,11,52040,52040,11,52068,52068,11,52096,52096,11,52124,52124,11,52152,52152,11,52180,52180,11,52208,52208,11,52236,52236,11,52264,52264,11,52292,52292,11,52320,52320,11,52348,52348,11,52376,52376,11,52404,52404,11,52432,52432,11,52460,52460,11,52488,52488,11,52516,52516,11,52544,52544,11,52572,52572,11,52600,52600,11,52628,52628,11,52656,52656,11,52684,52684,11,52712,52712,11,52740,52740,11,52768,52768,11,52796,52796,11,52824,52824,11,52852,52852,11,52880,52880,11,52908,52908,11,52936,52936,11,52964,52964,11,52992,52992,11,53020,53020,11,53048,53048,11,53076,53076,11,53104,53104,11,53132,53132,11,53160,53160,11,53188,53188,11,53216,53216,11,53244,53244,11,53272,53272,11,53300,53300,11,53328,53328,11,53356,53356,11,53384,53384,11,53412,53412,11,53440,53440,11,53468,53468,11,53496,53496,11,53524,53524,11,53552,53552,11,53580,53580,11,53608,53608,11,53636,53636,11,53664,53664,11,53692,53692,11,53720,53720,11,53748,53748,11,53776,53776,11,53804,53804,11,53832,53832,11,53860,53860,11,53888,53888,11,53916,53916,11,53944,53944,11,53972,53972,11,54000,54000,11,54028,54028,11,54056,54056,11,54084,54084,11,54112,54112,11,54140,54140,11,54168,54168,11,54196,54196,11,54224,54224,11,54252,54252,11,54280,54280,11,54308,54308,11,54336,54336,11,54364,54364,11,54392,54392,11,54420,54420,11,54448,54448,11,54476,54476,11,54504,54504,11,54532,54532,11,54560,54560,11,54588,54588,11,54616,54616,11,54644,54644,11,54672,54672,11,54700,54700,11,54728,54728,11,54756,54756,11,54784,54784,11,54812,54812,11,54840,54840,11,54868,54868,11,54896,54896,11,54924,54924,11,54952,54952,11,54980,54980,11,55008,55008,11,55036,55036,11,55064,55064,11,55092,55092,11,55120,55120,11,55148,55148,11,55176,55176,11,55216,55238,9,64286,64286,5,65056,65071,5,65438,65439,5,65529,65531,4,66272,66272,5,68097,68099,5,68108,68111,5,68159,68159,5,68900,68903,5,69446,69456,5,69632,69632,7,69634,69634,7,69744,69744,5,69759,69761,5,69808,69810,7,69815,69816,7,69821,69821,1,69837,69837,1,69927,69931,5,69933,69940,5,70003,70003,5,70018,70018,7,70070,70078,5,70082,70083,1,70094,70094,7,70188,70190,7,70194,70195,7,70197,70197,7,70206,70206,5,70368,70370,7,70400,70401,5,70459,70460,5,70463,70463,7,70465,70468,7,70475,70477,7,70498,70499,7,70512,70516,5,70712,70719,5,70722,70724,5,70726,70726,5,70832,70832,5,70835,70840,5,70842,70842,5,70845,70845,5,70847,70848,5,70850,70851,5,71088,71089,7,71096,71099,7,71102,71102,7,71132,71133,5,71219,71226,5,71229,71229,5,71231,71232,5,71340,71340,7,71342,71343,7,71350,71350,7,71453,71455,5,71462,71462,7,71724,71726,7,71736,71736,7,71984,71984,5,71991,71992,7,71997,71997,7,71999,71999,1,72001,72001,1,72003,72003,5,72148,72151,5,72156,72159,7,72164,72164,7,72243,72248,5,72250,72250,1,72263,72263,5,72279,72280,7,72324,72329,1,72343,72343,7,72751,72751,7,72760,72765,5,72767,72767,5,72873,72873,7,72881,72881,7,72884,72884,7,73009,73014,5,73020,73021,5,73030,73030,1,73098,73102,7,73107,73108,7,73110,73110,7,73459,73460,5,78896,78904,4,92976,92982,5,94033,94087,7,94180,94180,5,113821,113822,5,118528,118573,5,119141,119141,5,119143,119145,5,119150,119154,5,119163,119170,5,119210,119213,5,121344,121398,5,121461,121461,5,121499,121503,5,122880,122886,5,122907,122913,5,122918,122922,5,123566,123566,5,125136,125142,5,126976,126979,14,126981,127182,14,127184,127231,14,127279,127279,14,127344,127345,14,127374,127374,14,127405,127461,14,127489,127490,14,127514,127514,14,127538,127546,14,127561,127567,14,127570,127743,14,127757,127758,14,127760,127760,14,127762,127762,14,127766,127768,14,127770,127770,14,127772,127772,14,127775,127776,14,127778,127779,14,127789,127791,14,127794,127795,14,127798,127798,14,127819,127819,14,127824,127824,14,127868,127868,14,127870,127871,14,127892,127893,14,127896,127896,14,127900,127901,14,127904,127940,14,127942,127942,14,127944,127944,14,127946,127946,14,127951,127955,14,127968,127971,14,127973,127984,14,127987,127987,14,127989,127989,14,127991,127991,14,127995,127999,5,128008,128008,14,128012,128014,14,128017,128018,14,128020,128020,14,128022,128022,14,128042,128042,14,128063,128063,14,128065,128065,14,128101,128101,14,128108,128109,14,128173,128173,14,128182,128183,14,128236,128237,14,128239,128239,14,128245,128245,14,128248,128248,14,128253,128253,14,128255,128258,14,128260,128263,14,128265,128265,14,128277,128277,14,128300,128301,14,128326,128328,14,128331,128334,14,128336,128347,14,128360,128366,14,128369,128370,14,128378,128378,14,128391,128391,14,128394,128397,14,128400,128400,14,128405,128406,14,128420,128420,14,128422,128423,14,128425,128432,14,128435,128443,14,128445,128449,14,128453,128464,14,128468,128475,14,128479,128480,14,128482,128482,14,128484,128487,14,128489,128494,14,128496,128498,14,128500,128505,14,128507,128511,14,128513,128518,14,128521,128525,14,128527,128527,14,128529,128529,14,128533,128533,14,128535,128535,14,128537,128537,14]');
    }
    //#endregion
    /**
     * Computes the offset after performing a left delete on the given string,
     * while considering unicode grapheme/emoji rules.
    */
    function getLeftDeleteOffset(offset, str) {
        if (offset === 0) {
            return 0;
        }
        // Try to delete emoji part.
        const emojiOffset = getOffsetBeforeLastEmojiComponent(offset, str);
        if (emojiOffset !== undefined) {
            return emojiOffset;
        }
        // Otherwise, just skip a single code point.
        const iterator = new CodePointIterator(str, offset);
        iterator.prevCodePoint();
        return iterator.offset;
    }
    function getOffsetBeforeLastEmojiComponent(initialOffset, str) {
        // See https://www.unicode.org/reports/tr51/tr51-14.html#EBNF_and_Regex for the
        // structure of emojis.
        const iterator = new CodePointIterator(str, initialOffset);
        let codePoint = iterator.prevCodePoint();
        // Skip modifiers
        while ((isEmojiModifier(codePoint) || codePoint === 65039 /* CodePoint.emojiVariantSelector */ || codePoint === 8419 /* CodePoint.enclosingKeyCap */)) {
            if (iterator.offset === 0) {
                // Cannot skip modifier, no preceding emoji base.
                return undefined;
            }
            codePoint = iterator.prevCodePoint();
        }
        // Expect base emoji
        if (!isEmojiImprecise(codePoint)) {
            // Unexpected code point, not a valid emoji.
            return undefined;
        }
        let resultOffset = iterator.offset;
        if (resultOffset > 0) {
            // Skip optional ZWJ code points that combine multiple emojis.
            // In theory, we should check if that ZWJ actually combines multiple emojis
            // to prevent deleting ZWJs in situations we didn't account for.
            const optionalZwjCodePoint = iterator.prevCodePoint();
            if (optionalZwjCodePoint === 8205 /* CodePoint.zwj */) {
                resultOffset = iterator.offset;
            }
        }
        return resultOffset;
    }
    function isEmojiModifier(codePoint) {
        return 0x1F3FB <= codePoint && codePoint <= 0x1F3FF;
    }
    exports.noBreakWhitespace = '\xa0';
    class AmbiguousCharacters {
        static { this.ambiguousCharacterData = new lazy_1.Lazy(() => {
            // Generated using https://github.com/hediet/vscode-unicode-data
            // Stored as key1, value1, key2, value2, ...
            return JSON.parse('{\"_common\":[8232,32,8233,32,5760,32,8192,32,8193,32,8194,32,8195,32,8196,32,8197,32,8198,32,8200,32,8201,32,8202,32,8287,32,8199,32,8239,32,2042,95,65101,95,65102,95,65103,95,8208,45,8209,45,8210,45,65112,45,1748,45,8259,45,727,45,8722,45,10134,45,11450,45,1549,44,1643,44,8218,44,184,44,42233,44,894,59,2307,58,2691,58,1417,58,1795,58,1796,58,5868,58,65072,58,6147,58,6153,58,8282,58,1475,58,760,58,42889,58,8758,58,720,58,42237,58,451,33,11601,33,660,63,577,63,2429,63,5038,63,42731,63,119149,46,8228,46,1793,46,1794,46,42510,46,68176,46,1632,46,1776,46,42232,46,1373,96,65287,96,8219,96,8242,96,1370,96,1523,96,8175,96,65344,96,900,96,8189,96,8125,96,8127,96,8190,96,697,96,884,96,712,96,714,96,715,96,756,96,699,96,701,96,700,96,702,96,42892,96,1497,96,2036,96,2037,96,5194,96,5836,96,94033,96,94034,96,65339,91,10088,40,10098,40,12308,40,64830,40,65341,93,10089,41,10099,41,12309,41,64831,41,10100,123,119060,123,10101,125,65342,94,8270,42,1645,42,8727,42,66335,42,5941,47,8257,47,8725,47,8260,47,9585,47,10187,47,10744,47,119354,47,12755,47,12339,47,11462,47,20031,47,12035,47,65340,92,65128,92,8726,92,10189,92,10741,92,10745,92,119311,92,119355,92,12756,92,20022,92,12034,92,42872,38,708,94,710,94,5869,43,10133,43,66203,43,8249,60,10094,60,706,60,119350,60,5176,60,5810,60,5120,61,11840,61,12448,61,42239,61,8250,62,10095,62,707,62,119351,62,5171,62,94015,62,8275,126,732,126,8128,126,8764,126,65372,124,65293,45,120784,50,120794,50,120804,50,120814,50,120824,50,130034,50,42842,50,423,50,1000,50,42564,50,5311,50,42735,50,119302,51,120785,51,120795,51,120805,51,120815,51,120825,51,130035,51,42923,51,540,51,439,51,42858,51,11468,51,1248,51,94011,51,71882,51,120786,52,120796,52,120806,52,120816,52,120826,52,130036,52,5070,52,71855,52,120787,53,120797,53,120807,53,120817,53,120827,53,130037,53,444,53,71867,53,120788,54,120798,54,120808,54,120818,54,120828,54,130038,54,11474,54,5102,54,71893,54,119314,55,120789,55,120799,55,120809,55,120819,55,120829,55,130039,55,66770,55,71878,55,2819,56,2538,56,2666,56,125131,56,120790,56,120800,56,120810,56,120820,56,120830,56,130040,56,547,56,546,56,66330,56,2663,57,2920,57,2541,57,3437,57,120791,57,120801,57,120811,57,120821,57,120831,57,130041,57,42862,57,11466,57,71884,57,71852,57,71894,57,9082,97,65345,97,119834,97,119886,97,119938,97,119990,97,120042,97,120094,97,120146,97,120198,97,120250,97,120302,97,120354,97,120406,97,120458,97,593,97,945,97,120514,97,120572,97,120630,97,120688,97,120746,97,65313,65,119808,65,119860,65,119912,65,119964,65,120016,65,120068,65,120120,65,120172,65,120224,65,120276,65,120328,65,120380,65,120432,65,913,65,120488,65,120546,65,120604,65,120662,65,120720,65,5034,65,5573,65,42222,65,94016,65,66208,65,119835,98,119887,98,119939,98,119991,98,120043,98,120095,98,120147,98,120199,98,120251,98,120303,98,120355,98,120407,98,120459,98,388,98,5071,98,5234,98,5551,98,65314,66,8492,66,119809,66,119861,66,119913,66,120017,66,120069,66,120121,66,120173,66,120225,66,120277,66,120329,66,120381,66,120433,66,42932,66,914,66,120489,66,120547,66,120605,66,120663,66,120721,66,5108,66,5623,66,42192,66,66178,66,66209,66,66305,66,65347,99,8573,99,119836,99,119888,99,119940,99,119992,99,120044,99,120096,99,120148,99,120200,99,120252,99,120304,99,120356,99,120408,99,120460,99,7428,99,1010,99,11429,99,43951,99,66621,99,128844,67,71922,67,71913,67,65315,67,8557,67,8450,67,8493,67,119810,67,119862,67,119914,67,119966,67,120018,67,120174,67,120226,67,120278,67,120330,67,120382,67,120434,67,1017,67,11428,67,5087,67,42202,67,66210,67,66306,67,66581,67,66844,67,8574,100,8518,100,119837,100,119889,100,119941,100,119993,100,120045,100,120097,100,120149,100,120201,100,120253,100,120305,100,120357,100,120409,100,120461,100,1281,100,5095,100,5231,100,42194,100,8558,68,8517,68,119811,68,119863,68,119915,68,119967,68,120019,68,120071,68,120123,68,120175,68,120227,68,120279,68,120331,68,120383,68,120435,68,5024,68,5598,68,5610,68,42195,68,8494,101,65349,101,8495,101,8519,101,119838,101,119890,101,119942,101,120046,101,120098,101,120150,101,120202,101,120254,101,120306,101,120358,101,120410,101,120462,101,43826,101,1213,101,8959,69,65317,69,8496,69,119812,69,119864,69,119916,69,120020,69,120072,69,120124,69,120176,69,120228,69,120280,69,120332,69,120384,69,120436,69,917,69,120492,69,120550,69,120608,69,120666,69,120724,69,11577,69,5036,69,42224,69,71846,69,71854,69,66182,69,119839,102,119891,102,119943,102,119995,102,120047,102,120099,102,120151,102,120203,102,120255,102,120307,102,120359,102,120411,102,120463,102,43829,102,42905,102,383,102,7837,102,1412,102,119315,70,8497,70,119813,70,119865,70,119917,70,120021,70,120073,70,120125,70,120177,70,120229,70,120281,70,120333,70,120385,70,120437,70,42904,70,988,70,120778,70,5556,70,42205,70,71874,70,71842,70,66183,70,66213,70,66853,70,65351,103,8458,103,119840,103,119892,103,119944,103,120048,103,120100,103,120152,103,120204,103,120256,103,120308,103,120360,103,120412,103,120464,103,609,103,7555,103,397,103,1409,103,119814,71,119866,71,119918,71,119970,71,120022,71,120074,71,120126,71,120178,71,120230,71,120282,71,120334,71,120386,71,120438,71,1292,71,5056,71,5107,71,42198,71,65352,104,8462,104,119841,104,119945,104,119997,104,120049,104,120101,104,120153,104,120205,104,120257,104,120309,104,120361,104,120413,104,120465,104,1211,104,1392,104,5058,104,65320,72,8459,72,8460,72,8461,72,119815,72,119867,72,119919,72,120023,72,120179,72,120231,72,120283,72,120335,72,120387,72,120439,72,919,72,120494,72,120552,72,120610,72,120668,72,120726,72,11406,72,5051,72,5500,72,42215,72,66255,72,731,105,9075,105,65353,105,8560,105,8505,105,8520,105,119842,105,119894,105,119946,105,119998,105,120050,105,120102,105,120154,105,120206,105,120258,105,120310,105,120362,105,120414,105,120466,105,120484,105,618,105,617,105,953,105,8126,105,890,105,120522,105,120580,105,120638,105,120696,105,120754,105,1110,105,42567,105,1231,105,43893,105,5029,105,71875,105,65354,106,8521,106,119843,106,119895,106,119947,106,119999,106,120051,106,120103,106,120155,106,120207,106,120259,106,120311,106,120363,106,120415,106,120467,106,1011,106,1112,106,65322,74,119817,74,119869,74,119921,74,119973,74,120025,74,120077,74,120129,74,120181,74,120233,74,120285,74,120337,74,120389,74,120441,74,42930,74,895,74,1032,74,5035,74,5261,74,42201,74,119844,107,119896,107,119948,107,120000,107,120052,107,120104,107,120156,107,120208,107,120260,107,120312,107,120364,107,120416,107,120468,107,8490,75,65323,75,119818,75,119870,75,119922,75,119974,75,120026,75,120078,75,120130,75,120182,75,120234,75,120286,75,120338,75,120390,75,120442,75,922,75,120497,75,120555,75,120613,75,120671,75,120729,75,11412,75,5094,75,5845,75,42199,75,66840,75,1472,108,8739,73,9213,73,65512,73,1633,108,1777,73,66336,108,125127,108,120783,73,120793,73,120803,73,120813,73,120823,73,130033,73,65321,73,8544,73,8464,73,8465,73,119816,73,119868,73,119920,73,120024,73,120128,73,120180,73,120232,73,120284,73,120336,73,120388,73,120440,73,65356,108,8572,73,8467,108,119845,108,119897,108,119949,108,120001,108,120053,108,120105,73,120157,73,120209,73,120261,73,120313,73,120365,73,120417,73,120469,73,448,73,120496,73,120554,73,120612,73,120670,73,120728,73,11410,73,1030,73,1216,73,1493,108,1503,108,1575,108,126464,108,126592,108,65166,108,65165,108,1994,108,11599,73,5825,73,42226,73,93992,73,66186,124,66313,124,119338,76,8556,76,8466,76,119819,76,119871,76,119923,76,120027,76,120079,76,120131,76,120183,76,120235,76,120287,76,120339,76,120391,76,120443,76,11472,76,5086,76,5290,76,42209,76,93974,76,71843,76,71858,76,66587,76,66854,76,65325,77,8559,77,8499,77,119820,77,119872,77,119924,77,120028,77,120080,77,120132,77,120184,77,120236,77,120288,77,120340,77,120392,77,120444,77,924,77,120499,77,120557,77,120615,77,120673,77,120731,77,1018,77,11416,77,5047,77,5616,77,5846,77,42207,77,66224,77,66321,77,119847,110,119899,110,119951,110,120003,110,120055,110,120107,110,120159,110,120211,110,120263,110,120315,110,120367,110,120419,110,120471,110,1400,110,1404,110,65326,78,8469,78,119821,78,119873,78,119925,78,119977,78,120029,78,120081,78,120185,78,120237,78,120289,78,120341,78,120393,78,120445,78,925,78,120500,78,120558,78,120616,78,120674,78,120732,78,11418,78,42208,78,66835,78,3074,111,3202,111,3330,111,3458,111,2406,111,2662,111,2790,111,3046,111,3174,111,3302,111,3430,111,3664,111,3792,111,4160,111,1637,111,1781,111,65359,111,8500,111,119848,111,119900,111,119952,111,120056,111,120108,111,120160,111,120212,111,120264,111,120316,111,120368,111,120420,111,120472,111,7439,111,7441,111,43837,111,959,111,120528,111,120586,111,120644,111,120702,111,120760,111,963,111,120532,111,120590,111,120648,111,120706,111,120764,111,11423,111,4351,111,1413,111,1505,111,1607,111,126500,111,126564,111,126596,111,65259,111,65260,111,65258,111,65257,111,1726,111,64428,111,64429,111,64427,111,64426,111,1729,111,64424,111,64425,111,64423,111,64422,111,1749,111,3360,111,4125,111,66794,111,71880,111,71895,111,66604,111,1984,79,2534,79,2918,79,12295,79,70864,79,71904,79,120782,79,120792,79,120802,79,120812,79,120822,79,130032,79,65327,79,119822,79,119874,79,119926,79,119978,79,120030,79,120082,79,120134,79,120186,79,120238,79,120290,79,120342,79,120394,79,120446,79,927,79,120502,79,120560,79,120618,79,120676,79,120734,79,11422,79,1365,79,11604,79,4816,79,2848,79,66754,79,42227,79,71861,79,66194,79,66219,79,66564,79,66838,79,9076,112,65360,112,119849,112,119901,112,119953,112,120005,112,120057,112,120109,112,120161,112,120213,112,120265,112,120317,112,120369,112,120421,112,120473,112,961,112,120530,112,120544,112,120588,112,120602,112,120646,112,120660,112,120704,112,120718,112,120762,112,120776,112,11427,112,65328,80,8473,80,119823,80,119875,80,119927,80,119979,80,120031,80,120083,80,120187,80,120239,80,120291,80,120343,80,120395,80,120447,80,929,80,120504,80,120562,80,120620,80,120678,80,120736,80,11426,80,5090,80,5229,80,42193,80,66197,80,119850,113,119902,113,119954,113,120006,113,120058,113,120110,113,120162,113,120214,113,120266,113,120318,113,120370,113,120422,113,120474,113,1307,113,1379,113,1382,113,8474,81,119824,81,119876,81,119928,81,119980,81,120032,81,120084,81,120188,81,120240,81,120292,81,120344,81,120396,81,120448,81,11605,81,119851,114,119903,114,119955,114,120007,114,120059,114,120111,114,120163,114,120215,114,120267,114,120319,114,120371,114,120423,114,120475,114,43847,114,43848,114,7462,114,11397,114,43905,114,119318,82,8475,82,8476,82,8477,82,119825,82,119877,82,119929,82,120033,82,120189,82,120241,82,120293,82,120345,82,120397,82,120449,82,422,82,5025,82,5074,82,66740,82,5511,82,42211,82,94005,82,65363,115,119852,115,119904,115,119956,115,120008,115,120060,115,120112,115,120164,115,120216,115,120268,115,120320,115,120372,115,120424,115,120476,115,42801,115,445,115,1109,115,43946,115,71873,115,66632,115,65331,83,119826,83,119878,83,119930,83,119982,83,120034,83,120086,83,120138,83,120190,83,120242,83,120294,83,120346,83,120398,83,120450,83,1029,83,1359,83,5077,83,5082,83,42210,83,94010,83,66198,83,66592,83,119853,116,119905,116,119957,116,120009,116,120061,116,120113,116,120165,116,120217,116,120269,116,120321,116,120373,116,120425,116,120477,116,8868,84,10201,84,128872,84,65332,84,119827,84,119879,84,119931,84,119983,84,120035,84,120087,84,120139,84,120191,84,120243,84,120295,84,120347,84,120399,84,120451,84,932,84,120507,84,120565,84,120623,84,120681,84,120739,84,11430,84,5026,84,42196,84,93962,84,71868,84,66199,84,66225,84,66325,84,119854,117,119906,117,119958,117,120010,117,120062,117,120114,117,120166,117,120218,117,120270,117,120322,117,120374,117,120426,117,120478,117,42911,117,7452,117,43854,117,43858,117,651,117,965,117,120534,117,120592,117,120650,117,120708,117,120766,117,1405,117,66806,117,71896,117,8746,85,8899,85,119828,85,119880,85,119932,85,119984,85,120036,85,120088,85,120140,85,120192,85,120244,85,120296,85,120348,85,120400,85,120452,85,1357,85,4608,85,66766,85,5196,85,42228,85,94018,85,71864,85,8744,118,8897,118,65366,118,8564,118,119855,118,119907,118,119959,118,120011,118,120063,118,120115,118,120167,118,120219,118,120271,118,120323,118,120375,118,120427,118,120479,118,7456,118,957,118,120526,118,120584,118,120642,118,120700,118,120758,118,1141,118,1496,118,71430,118,43945,118,71872,118,119309,86,1639,86,1783,86,8548,86,119829,86,119881,86,119933,86,119985,86,120037,86,120089,86,120141,86,120193,86,120245,86,120297,86,120349,86,120401,86,120453,86,1140,86,11576,86,5081,86,5167,86,42719,86,42214,86,93960,86,71840,86,66845,86,623,119,119856,119,119908,119,119960,119,120012,119,120064,119,120116,119,120168,119,120220,119,120272,119,120324,119,120376,119,120428,119,120480,119,7457,119,1121,119,1309,119,1377,119,71434,119,71438,119,71439,119,43907,119,71919,87,71910,87,119830,87,119882,87,119934,87,119986,87,120038,87,120090,87,120142,87,120194,87,120246,87,120298,87,120350,87,120402,87,120454,87,1308,87,5043,87,5076,87,42218,87,5742,120,10539,120,10540,120,10799,120,65368,120,8569,120,119857,120,119909,120,119961,120,120013,120,120065,120,120117,120,120169,120,120221,120,120273,120,120325,120,120377,120,120429,120,120481,120,5441,120,5501,120,5741,88,9587,88,66338,88,71916,88,65336,88,8553,88,119831,88,119883,88,119935,88,119987,88,120039,88,120091,88,120143,88,120195,88,120247,88,120299,88,120351,88,120403,88,120455,88,42931,88,935,88,120510,88,120568,88,120626,88,120684,88,120742,88,11436,88,11613,88,5815,88,42219,88,66192,88,66228,88,66327,88,66855,88,611,121,7564,121,65369,121,119858,121,119910,121,119962,121,120014,121,120066,121,120118,121,120170,121,120222,121,120274,121,120326,121,120378,121,120430,121,120482,121,655,121,7935,121,43866,121,947,121,8509,121,120516,121,120574,121,120632,121,120690,121,120748,121,1199,121,4327,121,71900,121,65337,89,119832,89,119884,89,119936,89,119988,89,120040,89,120092,89,120144,89,120196,89,120248,89,120300,89,120352,89,120404,89,120456,89,933,89,978,89,120508,89,120566,89,120624,89,120682,89,120740,89,11432,89,1198,89,5033,89,5053,89,42220,89,94019,89,71844,89,66226,89,119859,122,119911,122,119963,122,120015,122,120067,122,120119,122,120171,122,120223,122,120275,122,120327,122,120379,122,120431,122,120483,122,7458,122,43923,122,71876,122,66293,90,71909,90,65338,90,8484,90,8488,90,119833,90,119885,90,119937,90,119989,90,120041,90,120197,90,120249,90,120301,90,120353,90,120405,90,120457,90,918,90,120493,90,120551,90,120609,90,120667,90,120725,90,5059,90,42204,90,71849,90,65282,34,65284,36,65285,37,65286,38,65290,42,65291,43,65294,46,65295,47,65296,48,65297,49,65298,50,65299,51,65300,52,65301,53,65302,54,65303,55,65304,56,65305,57,65308,60,65309,61,65310,62,65312,64,65316,68,65318,70,65319,71,65324,76,65329,81,65330,82,65333,85,65334,86,65335,87,65343,95,65346,98,65348,100,65350,102,65355,107,65357,109,65358,110,65361,113,65362,114,65364,116,65365,117,65367,119,65370,122,65371,123,65373,125,119846,109],\"_default\":[160,32,8211,45,65374,126,65306,58,65281,33,8216,96,8217,96,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],\"cs\":[65374,126,65306,58,65281,33,8216,96,8217,96,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,1093,120,1061,88,1091,121,1059,89,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],\"de\":[65374,126,65306,58,65281,33,8216,96,8217,96,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,1093,120,1061,88,1091,121,1059,89,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],\"es\":[8211,45,65374,126,65306,58,65281,33,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],\"fr\":[65374,126,65306,58,65281,33,8216,96,8245,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],\"it\":[160,32,8211,45,65374,126,65306,58,65281,33,8216,96,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],\"ja\":[8211,45,65306,58,65281,33,8216,96,8217,96,8245,96,180,96,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65283,35,65292,44,65307,59],\"ko\":[8211,45,65374,126,65306,58,65281,33,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],\"pl\":[65374,126,65306,58,65281,33,8216,96,8217,96,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],\"pt-BR\":[65374,126,65306,58,65281,33,8216,96,8217,96,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],\"qps-ploc\":[160,32,8211,45,65374,126,65306,58,65281,33,8216,96,8217,96,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],\"ru\":[65374,126,65306,58,65281,33,8216,96,8217,96,8245,96,180,96,12494,47,305,105,921,73,1009,112,215,120,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],\"tr\":[160,32,8211,45,65374,126,65306,58,65281,33,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],\"zh-hans\":[65374,126,65306,58,65281,33,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65288,40,65289,41],\"zh-hant\":[8211,45,65374,126,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65283,35,65307,59]}');
        }); }
        static { this.cache = new cache_1.LRUCachedFunction({ getCacheKey: JSON.stringify }, (locales) => {
            function arrayToMap(arr) {
                const result = new Map();
                for (let i = 0; i < arr.length; i += 2) {
                    result.set(arr[i], arr[i + 1]);
                }
                return result;
            }
            function mergeMaps(map1, map2) {
                const result = new Map(map1);
                for (const [key, value] of map2) {
                    result.set(key, value);
                }
                return result;
            }
            function intersectMaps(map1, map2) {
                if (!map1) {
                    return map2;
                }
                const result = new Map();
                for (const [key, value] of map1) {
                    if (map2.has(key)) {
                        result.set(key, value);
                    }
                }
                return result;
            }
            const data = this.ambiguousCharacterData.value;
            let filteredLocales = locales.filter((l) => !l.startsWith('_') && l in data);
            if (filteredLocales.length === 0) {
                filteredLocales = ['_default'];
            }
            let languageSpecificMap = undefined;
            for (const locale of filteredLocales) {
                const map = arrayToMap(data[locale]);
                languageSpecificMap = intersectMaps(languageSpecificMap, map);
            }
            const commonMap = arrayToMap(data['_common']);
            const map = mergeMaps(commonMap, languageSpecificMap);
            return new AmbiguousCharacters(map);
        }); }
        static getInstance(locales) {
            return AmbiguousCharacters.cache.get(Array.from(locales));
        }
        static { this._locales = new lazy_1.Lazy(() => Object.keys(AmbiguousCharacters.ambiguousCharacterData.value).filter((k) => !k.startsWith('_'))); }
        static getLocales() {
            return AmbiguousCharacters._locales.value;
        }
        constructor(confusableDictionary) {
            this.confusableDictionary = confusableDictionary;
        }
        isAmbiguous(codePoint) {
            return this.confusableDictionary.has(codePoint);
        }
        /**
         * Returns the non basic ASCII code point that the given code point can be confused,
         * or undefined if such code point does note exist.
         */
        getPrimaryConfusable(codePoint) {
            return this.confusableDictionary.get(codePoint);
        }
        getConfusableCodePoints() {
            return new Set(this.confusableDictionary.keys());
        }
    }
    exports.AmbiguousCharacters = AmbiguousCharacters;
    class InvisibleCharacters {
        static getRawData() {
            // Generated using https://github.com/hediet/vscode-unicode-data
            return JSON.parse('[9,10,11,12,13,32,127,160,173,847,1564,4447,4448,6068,6069,6155,6156,6157,6158,7355,7356,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8203,8204,8205,8206,8207,8234,8235,8236,8237,8238,8239,8287,8288,8289,8290,8291,8292,8293,8294,8295,8296,8297,8298,8299,8300,8301,8302,8303,10240,12288,12644,65024,65025,65026,65027,65028,65029,65030,65031,65032,65033,65034,65035,65036,65037,65038,65039,65279,65440,65520,65521,65522,65523,65524,65525,65526,65527,65528,65532,78844,119155,119156,119157,119158,119159,119160,119161,119162,917504,917505,917506,917507,917508,917509,917510,917511,917512,917513,917514,917515,917516,917517,917518,917519,917520,917521,917522,917523,917524,917525,917526,917527,917528,917529,917530,917531,917532,917533,917534,917535,917536,917537,917538,917539,917540,917541,917542,917543,917544,917545,917546,917547,917548,917549,917550,917551,917552,917553,917554,917555,917556,917557,917558,917559,917560,917561,917562,917563,917564,917565,917566,917567,917568,917569,917570,917571,917572,917573,917574,917575,917576,917577,917578,917579,917580,917581,917582,917583,917584,917585,917586,917587,917588,917589,917590,917591,917592,917593,917594,917595,917596,917597,917598,917599,917600,917601,917602,917603,917604,917605,917606,917607,917608,917609,917610,917611,917612,917613,917614,917615,917616,917617,917618,917619,917620,917621,917622,917623,917624,917625,917626,917627,917628,917629,917630,917631,917760,917761,917762,917763,917764,917765,917766,917767,917768,917769,917770,917771,917772,917773,917774,917775,917776,917777,917778,917779,917780,917781,917782,917783,917784,917785,917786,917787,917788,917789,917790,917791,917792,917793,917794,917795,917796,917797,917798,917799,917800,917801,917802,917803,917804,917805,917806,917807,917808,917809,917810,917811,917812,917813,917814,917815,917816,917817,917818,917819,917820,917821,917822,917823,917824,917825,917826,917827,917828,917829,917830,917831,917832,917833,917834,917835,917836,917837,917838,917839,917840,917841,917842,917843,917844,917845,917846,917847,917848,917849,917850,917851,917852,917853,917854,917855,917856,917857,917858,917859,917860,917861,917862,917863,917864,917865,917866,917867,917868,917869,917870,917871,917872,917873,917874,917875,917876,917877,917878,917879,917880,917881,917882,917883,917884,917885,917886,917887,917888,917889,917890,917891,917892,917893,917894,917895,917896,917897,917898,917899,917900,917901,917902,917903,917904,917905,917906,917907,917908,917909,917910,917911,917912,917913,917914,917915,917916,917917,917918,917919,917920,917921,917922,917923,917924,917925,917926,917927,917928,917929,917930,917931,917932,917933,917934,917935,917936,917937,917938,917939,917940,917941,917942,917943,917944,917945,917946,917947,917948,917949,917950,917951,917952,917953,917954,917955,917956,917957,917958,917959,917960,917961,917962,917963,917964,917965,917966,917967,917968,917969,917970,917971,917972,917973,917974,917975,917976,917977,917978,917979,917980,917981,917982,917983,917984,917985,917986,917987,917988,917989,917990,917991,917992,917993,917994,917995,917996,917997,917998,917999]');
        }
        static { this._data = undefined; }
        static getData() {
            if (!this._data) {
                this._data = new Set(InvisibleCharacters.getRawData());
            }
            return this._data;
        }
        static isInvisibleCharacter(codePoint) {
            return InvisibleCharacters.getData().has(codePoint);
        }
        static get codePoints() {
            return InvisibleCharacters.getData();
        }
    }
    exports.InvisibleCharacters = InvisibleCharacters;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[82/*vs/base/common/filters*/], __M([1/*require*/,0/*exports*/,45/*vs/base/common/map*/,448/*vs/base/common/naturalLanguage/korean*/,11/*vs/base/common/strings*/]), function (require, exports, map_1, korean_1, strings) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.FuzzyScoreOptions = exports.FuzzyScore = exports.matchesPrefix = exports.matchesStrictPrefix = void 0;
    exports.or = or;
    exports.matchesContiguousSubString = matchesContiguousSubString;
    exports.matchesSubString = matchesSubString;
    exports.isUpper = isUpper;
    exports.matchesCamelCase = matchesCamelCase;
    exports.matchesWords = matchesWords;
    exports.matchesFuzzy = matchesFuzzy;
    exports.matchesFuzzy2 = matchesFuzzy2;
    exports.anyScore = anyScore;
    exports.createMatches = createMatches;
    exports.isPatternInWord = isPatternInWord;
    exports.fuzzyScore = fuzzyScore;
    exports.fuzzyScoreGracefulAggressive = fuzzyScoreGracefulAggressive;
    // Combined filters
    /**
     * @returns A filter which combines the provided set
     * of filters with an or. The *first* filters that
     * matches defined the return value of the returned
     * filter.
     */
    function or(...filter) {
        return function (word, wordToMatchAgainst) {
            for (let i = 0, len = filter.length; i < len; i++) {
                const match = filter[i](word, wordToMatchAgainst);
                if (match) {
                    return match;
                }
            }
            return null;
        };
    }
    // Prefix
    exports.matchesStrictPrefix = _matchesPrefix.bind(undefined, false);
    exports.matchesPrefix = _matchesPrefix.bind(undefined, true);
    function _matchesPrefix(ignoreCase, word, wordToMatchAgainst) {
        if (!wordToMatchAgainst || wordToMatchAgainst.length < word.length) {
            return null;
        }
        let matches;
        if (ignoreCase) {
            matches = strings.startsWithIgnoreCase(wordToMatchAgainst, word);
        }
        else {
            matches = wordToMatchAgainst.indexOf(word) === 0;
        }
        if (!matches) {
            return null;
        }
        return word.length > 0 ? [{ start: 0, end: word.length }] : [];
    }
    // Contiguous Substring
    function matchesContiguousSubString(word, wordToMatchAgainst) {
        const index = wordToMatchAgainst.toLowerCase().indexOf(word.toLowerCase());
        if (index === -1) {
            return null;
        }
        return [{ start: index, end: index + word.length }];
    }
    // Substring
    function matchesSubString(word, wordToMatchAgainst) {
        return _matchesSubString(word.toLowerCase(), wordToMatchAgainst.toLowerCase(), 0, 0);
    }
    function _matchesSubString(word, wordToMatchAgainst, i, j) {
        if (i === word.length) {
            return [];
        }
        else if (j === wordToMatchAgainst.length) {
            return null;
        }
        else {
            if (word[i] === wordToMatchAgainst[j]) {
                let result = null;
                if (result = _matchesSubString(word, wordToMatchAgainst, i + 1, j + 1)) {
                    return join({ start: j, end: j + 1 }, result);
                }
                return null;
            }
            return _matchesSubString(word, wordToMatchAgainst, i, j + 1);
        }
    }
    // CamelCase
    function isLower(code) {
        return 97 /* CharCode.a */ <= code && code <= 122 /* CharCode.z */;
    }
    function isUpper(code) {
        return 65 /* CharCode.A */ <= code && code <= 90 /* CharCode.Z */;
    }
    function isNumber(code) {
        return 48 /* CharCode.Digit0 */ <= code && code <= 57 /* CharCode.Digit9 */;
    }
    function isWhitespace(code) {
        return (code === 32 /* CharCode.Space */
            || code === 9 /* CharCode.Tab */
            || code === 10 /* CharCode.LineFeed */
            || code === 13 /* CharCode.CarriageReturn */);
    }
    const wordSeparators = new Set();
    // These are chosen as natural word separators based on writen text.
    // It is a subset of the word separators used by the monaco editor.
    '()[]{}<>`\'"-/;:,.?!'
        .split('')
        .forEach(s => wordSeparators.add(s.charCodeAt(0)));
    function isWordSeparator(code) {
        return isWhitespace(code) || wordSeparators.has(code);
    }
    function charactersMatch(codeA, codeB) {
        return (codeA === codeB) || (isWordSeparator(codeA) && isWordSeparator(codeB));
    }
    const alternateCharsCache = new Map();
    /**
     * Gets alternative codes to the character code passed in. This comes in the
     * form of an array of character codes, all of which must match _in order_ to
     * successfully match.
     *
     * @param code The character code to check.
     */
    function getAlternateCodes(code) {
        if (alternateCharsCache.has(code)) {
            return alternateCharsCache.get(code);
        }
        // NOTE: This function is written in such a way that it can be extended in
        // the future, but right now the return type takes into account it's only
        // supported by a single "alt codes provider".
        // `ArrayLike<ArrayLike<number>>` is a more appropriate type if changed.
        let result;
        const codes = (0, korean_1.getKoreanAltChars)(code);
        if (codes) {
            result = codes;
        }
        alternateCharsCache.set(code, result);
        return result;
    }
    function isAlphanumeric(code) {
        return isLower(code) || isUpper(code) || isNumber(code);
    }
    function join(head, tail) {
        if (tail.length === 0) {
            tail = [head];
        }
        else if (head.end === tail[0].start) {
            tail[0].start = head.start;
        }
        else {
            tail.unshift(head);
        }
        return tail;
    }
    function nextAnchor(camelCaseWord, start) {
        for (let i = start; i < camelCaseWord.length; i++) {
            const c = camelCaseWord.charCodeAt(i);
            if (isUpper(c) || isNumber(c) || (i > 0 && !isAlphanumeric(camelCaseWord.charCodeAt(i - 1)))) {
                return i;
            }
        }
        return camelCaseWord.length;
    }
    function _matchesCamelCase(word, camelCaseWord, i, j) {
        if (i === word.length) {
            return [];
        }
        else if (j === camelCaseWord.length) {
            return null;
        }
        else if (word[i] !== camelCaseWord[j].toLowerCase()) {
            return null;
        }
        else {
            let result = null;
            let nextUpperIndex = j + 1;
            result = _matchesCamelCase(word, camelCaseWord, i + 1, j + 1);
            while (!result && (nextUpperIndex = nextAnchor(camelCaseWord, nextUpperIndex)) < camelCaseWord.length) {
                result = _matchesCamelCase(word, camelCaseWord, i + 1, nextUpperIndex);
                nextUpperIndex++;
            }
            return result === null ? null : join({ start: j, end: j + 1 }, result);
        }
    }
    // Heuristic to avoid computing camel case matcher for words that don't
    // look like camelCaseWords.
    function analyzeCamelCaseWord(word) {
        let upper = 0, lower = 0, alpha = 0, numeric = 0, code = 0;
        for (let i = 0; i < word.length; i++) {
            code = word.charCodeAt(i);
            if (isUpper(code)) {
                upper++;
            }
            if (isLower(code)) {
                lower++;
            }
            if (isAlphanumeric(code)) {
                alpha++;
            }
            if (isNumber(code)) {
                numeric++;
            }
        }
        const upperPercent = upper / word.length;
        const lowerPercent = lower / word.length;
        const alphaPercent = alpha / word.length;
        const numericPercent = numeric / word.length;
        return { upperPercent, lowerPercent, alphaPercent, numericPercent };
    }
    function isUpperCaseWord(analysis) {
        const { upperPercent, lowerPercent } = analysis;
        return lowerPercent === 0 && upperPercent > 0.6;
    }
    function isCamelCaseWord(analysis) {
        const { upperPercent, lowerPercent, alphaPercent, numericPercent } = analysis;
        return lowerPercent > 0.2 && upperPercent < 0.8 && alphaPercent > 0.6 && numericPercent < 0.2;
    }
    // Heuristic to avoid computing camel case matcher for words that don't
    // look like camel case patterns.
    function isCamelCasePattern(word) {
        let upper = 0, lower = 0, code = 0, whitespace = 0;
        for (let i = 0; i < word.length; i++) {
            code = word.charCodeAt(i);
            if (isUpper(code)) {
                upper++;
            }
            if (isLower(code)) {
                lower++;
            }
            if (isWhitespace(code)) {
                whitespace++;
            }
        }
        if ((upper === 0 || lower === 0) && whitespace === 0) {
            return word.length <= 30;
        }
        else {
            return upper <= 5;
        }
    }
    function matchesCamelCase(word, camelCaseWord) {
        if (!camelCaseWord) {
            return null;
        }
        camelCaseWord = camelCaseWord.trim();
        if (camelCaseWord.length === 0) {
            return null;
        }
        if (!isCamelCasePattern(word)) {
            return null;
        }
        // TODO: Consider removing this check
        if (camelCaseWord.length > 60) {
            camelCaseWord = camelCaseWord.substring(0, 60);
        }
        const analysis = analyzeCamelCaseWord(camelCaseWord);
        if (!isCamelCaseWord(analysis)) {
            if (!isUpperCaseWord(analysis)) {
                return null;
            }
            camelCaseWord = camelCaseWord.toLowerCase();
        }
        let result = null;
        let i = 0;
        word = word.toLowerCase();
        while (i < camelCaseWord.length && (result = _matchesCamelCase(word, camelCaseWord, 0, i)) === null) {
            i = nextAnchor(camelCaseWord, i + 1);
        }
        return result;
    }
    // Matches beginning of words supporting non-ASCII languages
    // If `contiguous` is true then matches word with beginnings of the words in the target. E.g. "pul" will match "Git: Pull"
    // Otherwise also matches sub string of the word with beginnings of the words in the target. E.g. "gp" or "g p" will match "Git: Pull"
    // Useful in cases where the target is words (e.g. command labels)
    function matchesWords(word, target, contiguous = false) {
        if (!target || target.length === 0) {
            return null;
        }
        let result = null;
        let targetIndex = 0;
        word = word.toLowerCase();
        target = target.toLowerCase();
        while (targetIndex < target.length) {
            result = _matchesWords(word, target, 0, targetIndex, contiguous);
            if (result !== null) {
                break;
            }
            targetIndex = nextWord(target, targetIndex + 1);
        }
        return result;
    }
    function _matchesWords(word, target, wordIndex, targetIndex, contiguous) {
        let targetIndexOffset = 0;
        if (wordIndex === word.length) {
            return [];
        }
        else if (targetIndex === target.length) {
            return null;
        }
        else if (!charactersMatch(word.charCodeAt(wordIndex), target.charCodeAt(targetIndex))) {
            // Verify alternate characters before exiting
            const altChars = getAlternateCodes(word.charCodeAt(wordIndex));
            if (!altChars) {
                return null;
            }
            for (let k = 0; k < altChars.length; k++) {
                if (!charactersMatch(altChars[k], target.charCodeAt(targetIndex + k))) {
                    return null;
                }
            }
            targetIndexOffset += altChars.length - 1;
        }
        let result = null;
        let nextWordIndex = targetIndex + targetIndexOffset + 1;
        result = _matchesWords(word, target, wordIndex + 1, nextWordIndex, contiguous);
        if (!contiguous) {
            while (!result && (nextWordIndex = nextWord(target, nextWordIndex)) < target.length) {
                result = _matchesWords(word, target, wordIndex + 1, nextWordIndex, contiguous);
                nextWordIndex++;
            }
        }
        if (!result) {
            return null;
        }
        // If the characters don't exactly match, then they must be word separators (see charactersMatch(...)).
        // We don't want to include this in the matches but we don't want to throw the target out all together so we return `result`.
        if (word.charCodeAt(wordIndex) !== target.charCodeAt(targetIndex)) {
            // Verify alternate characters before exiting
            const altChars = getAlternateCodes(word.charCodeAt(wordIndex));
            if (!altChars) {
                return result;
            }
            for (let k = 0; k < altChars.length; k++) {
                if (altChars[k] !== target.charCodeAt(targetIndex + k)) {
                    return result;
                }
            }
        }
        return join({ start: targetIndex, end: targetIndex + targetIndexOffset + 1 }, result);
    }
    function nextWord(word, start) {
        for (let i = start; i < word.length; i++) {
            if (isWordSeparator(word.charCodeAt(i)) ||
                (i > 0 && isWordSeparator(word.charCodeAt(i - 1)))) {
                return i;
            }
        }
        return word.length;
    }
    // Fuzzy
    const fuzzyContiguousFilter = or(exports.matchesPrefix, matchesCamelCase, matchesContiguousSubString);
    const fuzzySeparateFilter = or(exports.matchesPrefix, matchesCamelCase, matchesSubString);
    const fuzzyRegExpCache = new map_1.LRUCache(10000); // bounded to 10000 elements
    function matchesFuzzy(word, wordToMatchAgainst, enableSeparateSubstringMatching = false) {
        if (typeof word !== 'string' || typeof wordToMatchAgainst !== 'string') {
            return null; // return early for invalid input
        }
        // Form RegExp for wildcard matches
        let regexp = fuzzyRegExpCache.get(word);
        if (!regexp) {
            regexp = new RegExp(strings.convertSimple2RegExpPattern(word), 'i');
            fuzzyRegExpCache.set(word, regexp);
        }
        // RegExp Filter
        const match = regexp.exec(wordToMatchAgainst);
        if (match) {
            return [{ start: match.index, end: match.index + match[0].length }];
        }
        // Default Filter
        return enableSeparateSubstringMatching ? fuzzySeparateFilter(word, wordToMatchAgainst) : fuzzyContiguousFilter(word, wordToMatchAgainst);
    }
    /**
     * Match pattern against word in a fuzzy way. As in IntelliSense and faster and more
     * powerful than `matchesFuzzy`
     */
    function matchesFuzzy2(pattern, word) {
        const score = fuzzyScore(pattern, pattern.toLowerCase(), 0, word, word.toLowerCase(), 0, { firstMatchCanBeWeak: true, boostFullMatch: true });
        return score ? createMatches(score) : null;
    }
    function anyScore(pattern, lowPattern, patternPos, word, lowWord, wordPos) {
        const max = Math.min(13, pattern.length);
        for (; patternPos < max; patternPos++) {
            const result = fuzzyScore(pattern, lowPattern, patternPos, word, lowWord, wordPos, { firstMatchCanBeWeak: true, boostFullMatch: true });
            if (result) {
                return result;
            }
        }
        return [0, wordPos];
    }
    //#region --- fuzzyScore ---
    function createMatches(score) {
        if (typeof score === 'undefined') {
            return [];
        }
        const res = [];
        const wordPos = score[1];
        for (let i = score.length - 1; i > 1; i--) {
            const pos = score[i] + wordPos;
            const last = res[res.length - 1];
            if (last && last.end === pos) {
                last.end = pos + 1;
            }
            else {
                res.push({ start: pos, end: pos + 1 });
            }
        }
        return res;
    }
    const _maxLen = 128;
    function initTable() {
        const table = [];
        const row = [];
        for (let i = 0; i <= _maxLen; i++) {
            row[i] = 0;
        }
        for (let i = 0; i <= _maxLen; i++) {
            table.push(row.slice(0));
        }
        return table;
    }
    function initArr(maxLen) {
        const row = [];
        for (let i = 0; i <= maxLen; i++) {
            row[i] = 0;
        }
        return row;
    }
    const _minWordMatchPos = initArr(2 * _maxLen); // min word position for a certain pattern position
    const _maxWordMatchPos = initArr(2 * _maxLen); // max word position for a certain pattern position
    const _diag = initTable(); // the length of a contiguous diagonal match
    const _table = initTable();
    const _arrows = initTable();
    const _debug = false;
    function printTable(table, pattern, patternLen, word, wordLen) {
        function pad(s, n, pad = ' ') {
            while (s.length < n) {
                s = pad + s;
            }
            return s;
        }
        let ret = ` |   |${word.split('').map(c => pad(c, 3)).join('|')}\n`;
        for (let i = 0; i <= patternLen; i++) {
            if (i === 0) {
                ret += ' |';
            }
            else {
                ret += `${pattern[i - 1]}|`;
            }
            ret += table[i].slice(0, wordLen + 1).map(n => pad(n.toString(), 3)).join('|') + '\n';
        }
        return ret;
    }
    function printTables(pattern, patternStart, word, wordStart) {
        pattern = pattern.substr(patternStart);
        word = word.substr(wordStart);
        console.log(printTable(_table, pattern, pattern.length, word, word.length));
        console.log(printTable(_arrows, pattern, pattern.length, word, word.length));
        console.log(printTable(_diag, pattern, pattern.length, word, word.length));
    }
    function isSeparatorAtPos(value, index) {
        if (index < 0 || index >= value.length) {
            return false;
        }
        const code = value.codePointAt(index);
        switch (code) {
            case 95 /* CharCode.Underline */:
            case 45 /* CharCode.Dash */:
            case 46 /* CharCode.Period */:
            case 32 /* CharCode.Space */:
            case 47 /* CharCode.Slash */:
            case 92 /* CharCode.Backslash */:
            case 39 /* CharCode.SingleQuote */:
            case 34 /* CharCode.DoubleQuote */:
            case 58 /* CharCode.Colon */:
            case 36 /* CharCode.DollarSign */:
            case 60 /* CharCode.LessThan */:
            case 62 /* CharCode.GreaterThan */:
            case 40 /* CharCode.OpenParen */:
            case 41 /* CharCode.CloseParen */:
            case 91 /* CharCode.OpenSquareBracket */:
            case 93 /* CharCode.CloseSquareBracket */:
            case 123 /* CharCode.OpenCurlyBrace */:
            case 125 /* CharCode.CloseCurlyBrace */:
                return true;
            case undefined:
                return false;
            default:
                if (strings.isEmojiImprecise(code)) {
                    return true;
                }
                return false;
        }
    }
    function isWhitespaceAtPos(value, index) {
        if (index < 0 || index >= value.length) {
            return false;
        }
        const code = value.charCodeAt(index);
        switch (code) {
            case 32 /* CharCode.Space */:
            case 9 /* CharCode.Tab */:
                return true;
            default:
                return false;
        }
    }
    function isUpperCaseAtPos(pos, word, wordLow) {
        return word[pos] !== wordLow[pos];
    }
    function isPatternInWord(patternLow, patternPos, patternLen, wordLow, wordPos, wordLen, fillMinWordPosArr = false) {
        while (patternPos < patternLen && wordPos < wordLen) {
            if (patternLow[patternPos] === wordLow[wordPos]) {
                if (fillMinWordPosArr) {
                    // Remember the min word position for each pattern position
                    _minWordMatchPos[patternPos] = wordPos;
                }
                patternPos += 1;
            }
            wordPos += 1;
        }
        return patternPos === patternLen; // pattern must be exhausted
    }
    var FuzzyScore;
    (function (FuzzyScore) {
        /**
         * No matches and value `-100`
         */
        FuzzyScore.Default = ([-100, 0]);
        function isDefault(score) {
            return !score || (score.length === 2 && score[0] === -100 && score[1] === 0);
        }
        FuzzyScore.isDefault = isDefault;
    })(FuzzyScore || (exports.FuzzyScore = FuzzyScore = {}));
    class FuzzyScoreOptions {
        static { this.default = { boostFullMatch: true, firstMatchCanBeWeak: false }; }
        constructor(firstMatchCanBeWeak, boostFullMatch) {
            this.firstMatchCanBeWeak = firstMatchCanBeWeak;
            this.boostFullMatch = boostFullMatch;
        }
    }
    exports.FuzzyScoreOptions = FuzzyScoreOptions;
    function fuzzyScore(pattern, patternLow, patternStart, word, wordLow, wordStart, options = FuzzyScoreOptions.default) {
        const patternLen = pattern.length > _maxLen ? _maxLen : pattern.length;
        const wordLen = word.length > _maxLen ? _maxLen : word.length;
        if (patternStart >= patternLen || wordStart >= wordLen || (patternLen - patternStart) > (wordLen - wordStart)) {
            return undefined;
        }
        // Run a simple check if the characters of pattern occur
        // (in order) at all in word. If that isn't the case we
        // stop because no match will be possible
        if (!isPatternInWord(patternLow, patternStart, patternLen, wordLow, wordStart, wordLen, true)) {
            return undefined;
        }
        // Find the max matching word position for each pattern position
        // NOTE: the min matching word position was filled in above, in the `isPatternInWord` call
        _fillInMaxWordMatchPos(patternLen, wordLen, patternStart, wordStart, patternLow, wordLow);
        let row = 1;
        let column = 1;
        let patternPos = patternStart;
        let wordPos = wordStart;
        const hasStrongFirstMatch = [false];
        // There will be a match, fill in tables
        for (row = 1, patternPos = patternStart; patternPos < patternLen; row++, patternPos++) {
            // Reduce search space to possible matching word positions and to possible access from next row
            const minWordMatchPos = _minWordMatchPos[patternPos];
            const maxWordMatchPos = _maxWordMatchPos[patternPos];
            const nextMaxWordMatchPos = (patternPos + 1 < patternLen ? _maxWordMatchPos[patternPos + 1] : wordLen);
            for (column = minWordMatchPos - wordStart + 1, wordPos = minWordMatchPos; wordPos < nextMaxWordMatchPos; column++, wordPos++) {
                let score = Number.MIN_SAFE_INTEGER;
                let canComeDiag = false;
                if (wordPos <= maxWordMatchPos) {
                    score = _doScore(pattern, patternLow, patternPos, patternStart, word, wordLow, wordPos, wordLen, wordStart, _diag[row - 1][column - 1] === 0, hasStrongFirstMatch);
                }
                let diagScore = 0;
                if (score !== Number.MAX_SAFE_INTEGER) {
                    canComeDiag = true;
                    diagScore = score + _table[row - 1][column - 1];
                }
                const canComeLeft = wordPos > minWordMatchPos;
                const leftScore = canComeLeft ? _table[row][column - 1] + (_diag[row][column - 1] > 0 ? -5 : 0) : 0; // penalty for a gap start
                const canComeLeftLeft = wordPos > minWordMatchPos + 1 && _diag[row][column - 1] > 0;
                const leftLeftScore = canComeLeftLeft ? _table[row][column - 2] + (_diag[row][column - 2] > 0 ? -5 : 0) : 0; // penalty for a gap start
                if (canComeLeftLeft && (!canComeLeft || leftLeftScore >= leftScore) && (!canComeDiag || leftLeftScore >= diagScore)) {
                    // always prefer choosing left left to jump over a diagonal because that means a match is earlier in the word
                    _table[row][column] = leftLeftScore;
                    _arrows[row][column] = 3 /* Arrow.LeftLeft */;
                    _diag[row][column] = 0;
                }
                else if (canComeLeft && (!canComeDiag || leftScore >= diagScore)) {
                    // always prefer choosing left since that means a match is earlier in the word
                    _table[row][column] = leftScore;
                    _arrows[row][column] = 2 /* Arrow.Left */;
                    _diag[row][column] = 0;
                }
                else if (canComeDiag) {
                    _table[row][column] = diagScore;
                    _arrows[row][column] = 1 /* Arrow.Diag */;
                    _diag[row][column] = _diag[row - 1][column - 1] + 1;
                }
                else {
                    throw new Error(`not possible`);
                }
            }
        }
        if (_debug) {
            printTables(pattern, patternStart, word, wordStart);
        }
        if (!hasStrongFirstMatch[0] && !options.firstMatchCanBeWeak) {
            return undefined;
        }
        row--;
        column--;
        const result = [_table[row][column], wordStart];
        let backwardsDiagLength = 0;
        let maxMatchColumn = 0;
        while (row >= 1) {
            // Find the column where we go diagonally up
            let diagColumn = column;
            do {
                const arrow = _arrows[row][diagColumn];
                if (arrow === 3 /* Arrow.LeftLeft */) {
                    diagColumn = diagColumn - 2;
                }
                else if (arrow === 2 /* Arrow.Left */) {
                    diagColumn = diagColumn - 1;
                }
                else {
                    // found the diagonal
                    break;
                }
            } while (diagColumn >= 1);
            // Overturn the "forwards" decision if keeping the "backwards" diagonal would give a better match
            if (backwardsDiagLength > 1 // only if we would have a contiguous match of 3 characters
                && patternLow[patternStart + row - 1] === wordLow[wordStart + column - 1] // only if we can do a contiguous match diagonally
                && !isUpperCaseAtPos(diagColumn + wordStart - 1, word, wordLow) // only if the forwards chose diagonal is not an uppercase
                && backwardsDiagLength + 1 > _diag[row][diagColumn] // only if our contiguous match would be longer than the "forwards" contiguous match
            ) {
                diagColumn = column;
            }
            if (diagColumn === column) {
                // this is a contiguous match
                backwardsDiagLength++;
            }
            else {
                backwardsDiagLength = 1;
            }
            if (!maxMatchColumn) {
                // remember the last matched column
                maxMatchColumn = diagColumn;
            }
            row--;
            column = diagColumn - 1;
            result.push(column);
        }
        if (wordLen - wordStart === patternLen && options.boostFullMatch) {
            // the word matches the pattern with all characters!
            // giving the score a total match boost (to come up ahead other words)
            result[0] += 2;
        }
        // Add 1 penalty for each skipped character in the word
        const skippedCharsCount = maxMatchColumn - patternLen;
        result[0] -= skippedCharsCount;
        return result;
    }
    function _fillInMaxWordMatchPos(patternLen, wordLen, patternStart, wordStart, patternLow, wordLow) {
        let patternPos = patternLen - 1;
        let wordPos = wordLen - 1;
        while (patternPos >= patternStart && wordPos >= wordStart) {
            if (patternLow[patternPos] === wordLow[wordPos]) {
                _maxWordMatchPos[patternPos] = wordPos;
                patternPos--;
            }
            wordPos--;
        }
    }
    function _doScore(pattern, patternLow, patternPos, patternStart, word, wordLow, wordPos, wordLen, wordStart, newMatchStart, outFirstMatchStrong) {
        if (patternLow[patternPos] !== wordLow[wordPos]) {
            return Number.MIN_SAFE_INTEGER;
        }
        let score = 1;
        let isGapLocation = false;
        if (wordPos === (patternPos - patternStart)) {
            // common prefix: `foobar <-> foobaz`
            //                            ^^^^^
            score = pattern[patternPos] === word[wordPos] ? 7 : 5;
        }
        else if (isUpperCaseAtPos(wordPos, word, wordLow) && (wordPos === 0 || !isUpperCaseAtPos(wordPos - 1, word, wordLow))) {
            // hitting upper-case: `foo <-> forOthers`
            //                              ^^ ^
            score = pattern[patternPos] === word[wordPos] ? 7 : 5;
            isGapLocation = true;
        }
        else if (isSeparatorAtPos(wordLow, wordPos) && (wordPos === 0 || !isSeparatorAtPos(wordLow, wordPos - 1))) {
            // hitting a separator: `. <-> foo.bar`
            //                                ^
            score = 5;
        }
        else if (isSeparatorAtPos(wordLow, wordPos - 1) || isWhitespaceAtPos(wordLow, wordPos - 1)) {
            // post separator: `foo <-> bar_foo`
            //                              ^^^
            score = 5;
            isGapLocation = true;
        }
        if (score > 1 && patternPos === patternStart) {
            outFirstMatchStrong[0] = true;
        }
        if (!isGapLocation) {
            isGapLocation = isUpperCaseAtPos(wordPos, word, wordLow) || isSeparatorAtPos(wordLow, wordPos - 1) || isWhitespaceAtPos(wordLow, wordPos - 1);
        }
        //
        if (patternPos === patternStart) { // first character in pattern
            if (wordPos > wordStart) {
                // the first pattern character would match a word character that is not at the word start
                // so introduce a penalty to account for the gap preceding this match
                score -= isGapLocation ? 3 : 5;
            }
        }
        else {
            if (newMatchStart) {
                // this would be the beginning of a new match (i.e. there would be a gap before this location)
                score += isGapLocation ? 2 : 0;
            }
            else {
                // this is part of a contiguous match, so give it a slight bonus, but do so only if it would not be a preferred gap location
                score += isGapLocation ? 0 : 1;
            }
        }
        if (wordPos + 1 === wordLen) {
            // we always penalize gaps, but this gives unfair advantages to a match that would match the last character in the word
            // so pretend there is a gap after the last character in the word to normalize things
            score -= isGapLocation ? 3 : 5;
        }
        return score;
    }
    //#endregion
    //#region --- graceful ---
    function fuzzyScoreGracefulAggressive(pattern, lowPattern, patternPos, word, lowWord, wordPos, options) {
        return fuzzyScoreWithPermutations(pattern, lowPattern, patternPos, word, lowWord, wordPos, true, options);
    }
    function fuzzyScoreWithPermutations(pattern, lowPattern, patternPos, word, lowWord, wordPos, aggressive, options) {
        let top = fuzzyScore(pattern, lowPattern, patternPos, word, lowWord, wordPos, options);
        if (top && !aggressive) {
            // when using the original pattern yield a result we`
            // return it unless we are aggressive and try to find
            // a better alignment, e.g. `cno` -> `^co^ns^ole` or `^c^o^nsole`.
            return top;
        }
        if (pattern.length >= 3) {
            // When the pattern is long enough then try a few (max 7)
            // permutations of the pattern to find a better match. The
            // permutations only swap neighbouring characters, e.g
            // `cnoso` becomes `conso`, `cnsoo`, `cnoos`.
            const tries = Math.min(7, pattern.length - 1);
            for (let movingPatternPos = patternPos + 1; movingPatternPos < tries; movingPatternPos++) {
                const newPattern = nextTypoPermutation(pattern, movingPatternPos);
                if (newPattern) {
                    const candidate = fuzzyScore(newPattern, newPattern.toLowerCase(), patternPos, word, lowWord, wordPos, options);
                    if (candidate) {
                        candidate[0] -= 3; // permutation penalty
                        if (!top || candidate[0] > top[0]) {
                            top = candidate;
                        }
                    }
                }
            }
        }
        return top;
    }
    function nextTypoPermutation(pattern, patternPos) {
        if (patternPos + 1 >= pattern.length) {
            return undefined;
        }
        const swap1 = pattern[patternPos];
        const swap2 = pattern[patternPos + 1];
        if (swap1 === swap2) {
            return undefined;
        }
        return pattern.slice(0, patternPos)
            + swap2
            + swap1
            + pattern.slice(patternPos + 2);
    }
});
//#endregion

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[129/*vs/base/common/hash*/], __M([1/*require*/,0/*exports*/,11/*vs/base/common/strings*/]), function (require, exports, strings) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.StringSHA1 = void 0;
    exports.hash = hash;
    exports.doHash = doHash;
    exports.numberHash = numberHash;
    exports.stringHash = stringHash;
    exports.toHexString = toHexString;
    /**
     * Return a hash value for an object.
     */
    function hash(obj) {
        return doHash(obj, 0);
    }
    function doHash(obj, hashVal) {
        switch (typeof obj) {
            case 'object':
                if (obj === null) {
                    return numberHash(349, hashVal);
                }
                else if (Array.isArray(obj)) {
                    return arrayHash(obj, hashVal);
                }
                return objectHash(obj, hashVal);
            case 'string':
                return stringHash(obj, hashVal);
            case 'boolean':
                return booleanHash(obj, hashVal);
            case 'number':
                return numberHash(obj, hashVal);
            case 'undefined':
                return numberHash(937, hashVal);
            default:
                return numberHash(617, hashVal);
        }
    }
    function numberHash(val, initialHashVal) {
        return (((initialHashVal << 5) - initialHashVal) + val) | 0; // hashVal * 31 + ch, keep as int32
    }
    function booleanHash(b, initialHashVal) {
        return numberHash(b ? 433 : 863, initialHashVal);
    }
    function stringHash(s, hashVal) {
        hashVal = numberHash(149417, hashVal);
        for (let i = 0, length = s.length; i < length; i++) {
            hashVal = numberHash(s.charCodeAt(i), hashVal);
        }
        return hashVal;
    }
    function arrayHash(arr, initialHashVal) {
        initialHashVal = numberHash(104579, initialHashVal);
        return arr.reduce((hashVal, item) => doHash(item, hashVal), initialHashVal);
    }
    function objectHash(obj, initialHashVal) {
        initialHashVal = numberHash(181387, initialHashVal);
        return Object.keys(obj).sort().reduce((hashVal, key) => {
            hashVal = stringHash(key, hashVal);
            return doHash(obj[key], hashVal);
        }, initialHashVal);
    }
    function leftRotate(value, bits, totalBits = 32) {
        // delta + bits = totalBits
        const delta = totalBits - bits;
        // All ones, expect `delta` zeros aligned to the right
        const mask = ~((1 << delta) - 1);
        // Join (value left-shifted `bits` bits) with (masked value right-shifted `delta` bits)
        return ((value << bits) | ((mask & value) >>> delta)) >>> 0;
    }
    function fill(dest, index = 0, count = dest.byteLength, value = 0) {
        for (let i = 0; i < count; i++) {
            dest[index + i] = value;
        }
    }
    function leftPad(value, length, char = '0') {
        while (value.length < length) {
            value = char + value;
        }
        return value;
    }
    function toHexString(bufferOrValue, bitsize = 32) {
        if (bufferOrValue instanceof ArrayBuffer) {
            return Array.from(new Uint8Array(bufferOrValue)).map(b => b.toString(16).padStart(2, '0')).join('');
        }
        return leftPad((bufferOrValue >>> 0).toString(16), bitsize / 4);
    }
    /**
     * A SHA1 implementation that works with strings and does not allocate.
     */
    class StringSHA1 {
        static { this._bigBlock32 = new DataView(new ArrayBuffer(320)); } // 80 * 4 = 320
        constructor() {
            this._h0 = 0x67452301;
            this._h1 = 0xEFCDAB89;
            this._h2 = 0x98BADCFE;
            this._h3 = 0x10325476;
            this._h4 = 0xC3D2E1F0;
            this._buff = new Uint8Array(64 /* SHA1Constant.BLOCK_SIZE */ + 3 /* to fit any utf-8 */);
            this._buffDV = new DataView(this._buff.buffer);
            this._buffLen = 0;
            this._totalLen = 0;
            this._leftoverHighSurrogate = 0;
            this._finished = false;
        }
        update(str) {
            const strLen = str.length;
            if (strLen === 0) {
                return;
            }
            const buff = this._buff;
            let buffLen = this._buffLen;
            let leftoverHighSurrogate = this._leftoverHighSurrogate;
            let charCode;
            let offset;
            if (leftoverHighSurrogate !== 0) {
                charCode = leftoverHighSurrogate;
                offset = -1;
                leftoverHighSurrogate = 0;
            }
            else {
                charCode = str.charCodeAt(0);
                offset = 0;
            }
            while (true) {
                let codePoint = charCode;
                if (strings.isHighSurrogate(charCode)) {
                    if (offset + 1 < strLen) {
                        const nextCharCode = str.charCodeAt(offset + 1);
                        if (strings.isLowSurrogate(nextCharCode)) {
                            offset++;
                            codePoint = strings.computeCodePoint(charCode, nextCharCode);
                        }
                        else {
                            // illegal => unicode replacement character
                            codePoint = 65533 /* SHA1Constant.UNICODE_REPLACEMENT */;
                        }
                    }
                    else {
                        // last character is a surrogate pair
                        leftoverHighSurrogate = charCode;
                        break;
                    }
                }
                else if (strings.isLowSurrogate(charCode)) {
                    // illegal => unicode replacement character
                    codePoint = 65533 /* SHA1Constant.UNICODE_REPLACEMENT */;
                }
                buffLen = this._push(buff, buffLen, codePoint);
                offset++;
                if (offset < strLen) {
                    charCode = str.charCodeAt(offset);
                }
                else {
                    break;
                }
            }
            this._buffLen = buffLen;
            this._leftoverHighSurrogate = leftoverHighSurrogate;
        }
        _push(buff, buffLen, codePoint) {
            if (codePoint < 0x0080) {
                buff[buffLen++] = codePoint;
            }
            else if (codePoint < 0x0800) {
                buff[buffLen++] = 0b11000000 | ((codePoint & 0b00000000000000000000011111000000) >>> 6);
                buff[buffLen++] = 0b10000000 | ((codePoint & 0b00000000000000000000000000111111) >>> 0);
            }
            else if (codePoint < 0x10000) {
                buff[buffLen++] = 0b11100000 | ((codePoint & 0b00000000000000001111000000000000) >>> 12);
                buff[buffLen++] = 0b10000000 | ((codePoint & 0b00000000000000000000111111000000) >>> 6);
                buff[buffLen++] = 0b10000000 | ((codePoint & 0b00000000000000000000000000111111) >>> 0);
            }
            else {
                buff[buffLen++] = 0b11110000 | ((codePoint & 0b00000000000111000000000000000000) >>> 18);
                buff[buffLen++] = 0b10000000 | ((codePoint & 0b00000000000000111111000000000000) >>> 12);
                buff[buffLen++] = 0b10000000 | ((codePoint & 0b00000000000000000000111111000000) >>> 6);
                buff[buffLen++] = 0b10000000 | ((codePoint & 0b00000000000000000000000000111111) >>> 0);
            }
            if (buffLen >= 64 /* SHA1Constant.BLOCK_SIZE */) {
                this._step();
                buffLen -= 64 /* SHA1Constant.BLOCK_SIZE */;
                this._totalLen += 64 /* SHA1Constant.BLOCK_SIZE */;
                // take last 3 in case of UTF8 overflow
                buff[0] = buff[64 /* SHA1Constant.BLOCK_SIZE */ + 0];
                buff[1] = buff[64 /* SHA1Constant.BLOCK_SIZE */ + 1];
                buff[2] = buff[64 /* SHA1Constant.BLOCK_SIZE */ + 2];
            }
            return buffLen;
        }
        digest() {
            if (!this._finished) {
                this._finished = true;
                if (this._leftoverHighSurrogate) {
                    // illegal => unicode replacement character
                    this._leftoverHighSurrogate = 0;
                    this._buffLen = this._push(this._buff, this._buffLen, 65533 /* SHA1Constant.UNICODE_REPLACEMENT */);
                }
                this._totalLen += this._buffLen;
                this._wrapUp();
            }
            return toHexString(this._h0) + toHexString(this._h1) + toHexString(this._h2) + toHexString(this._h3) + toHexString(this._h4);
        }
        _wrapUp() {
            this._buff[this._buffLen++] = 0x80;
            fill(this._buff, this._buffLen);
            if (this._buffLen > 56) {
                this._step();
                fill(this._buff);
            }
            // this will fit because the mantissa can cover up to 52 bits
            const ml = 8 * this._totalLen;
            this._buffDV.setUint32(56, Math.floor(ml / 4294967296), false);
            this._buffDV.setUint32(60, ml % 4294967296, false);
            this._step();
        }
        _step() {
            const bigBlock32 = StringSHA1._bigBlock32;
            const data = this._buffDV;
            for (let j = 0; j < 64 /* 16*4 */; j += 4) {
                bigBlock32.setUint32(j, data.getUint32(j, false), false);
            }
            for (let j = 64; j < 320 /* 80*4 */; j += 4) {
                bigBlock32.setUint32(j, leftRotate((bigBlock32.getUint32(j - 12, false) ^ bigBlock32.getUint32(j - 32, false) ^ bigBlock32.getUint32(j - 56, false) ^ bigBlock32.getUint32(j - 64, false)), 1), false);
            }
            let a = this._h0;
            let b = this._h1;
            let c = this._h2;
            let d = this._h3;
            let e = this._h4;
            let f, k;
            let temp;
            for (let j = 0; j < 80; j++) {
                if (j < 20) {
                    f = (b & c) | ((~b) & d);
                    k = 0x5A827999;
                }
                else if (j < 40) {
                    f = b ^ c ^ d;
                    k = 0x6ED9EBA1;
                }
                else if (j < 60) {
                    f = (b & c) | (b & d) | (c & d);
                    k = 0x8F1BBCDC;
                }
                else {
                    f = b ^ c ^ d;
                    k = 0xCA62C1D6;
                }
                temp = (leftRotate(a, 5) + f + e + k + bigBlock32.getUint32(j * 4, false)) & 0xffffffff;
                e = d;
                d = c;
                c = leftRotate(b, 30);
                b = a;
                a = temp;
            }
            this._h0 = (this._h0 + a) & 0xffffffff;
            this._h1 = (this._h1 + b) & 0xffffffff;
            this._h2 = (this._h2 + c) & 0xffffffff;
            this._h3 = (this._h3 + d) & 0xffffffff;
            this._h4 = (this._h4 + e) & 0xffffffff;
        }
    }
    exports.StringSHA1 = StringSHA1;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[190/*vs/base/common/diff/diff*/], __M([1/*require*/,0/*exports*/,444/*vs/base/common/diff/diffChange*/,129/*vs/base/common/hash*/]), function (require, exports, diffChange_1, hash_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.LcsDiff = exports.StringDiffSequence = void 0;
    exports.stringDiff = stringDiff;
    class StringDiffSequence {
        constructor(source) {
            this.source = source;
        }
        getElements() {
            const source = this.source;
            const characters = new Int32Array(source.length);
            for (let i = 0, len = source.length; i < len; i++) {
                characters[i] = source.charCodeAt(i);
            }
            return characters;
        }
    }
    exports.StringDiffSequence = StringDiffSequence;
    function stringDiff(original, modified, pretty) {
        return new LcsDiff(new StringDiffSequence(original), new StringDiffSequence(modified)).ComputeDiff(pretty).changes;
    }
    //
    // The code below has been ported from a C# implementation in VS
    //
    class Debug {
        static Assert(condition, message) {
            if (!condition) {
                throw new Error(message);
            }
        }
    }
    class MyArray {
        /**
         * Copies a range of elements from an Array starting at the specified source index and pastes
         * them to another Array starting at the specified destination index. The length and the indexes
         * are specified as 64-bit integers.
         * sourceArray:
         *		The Array that contains the data to copy.
         * sourceIndex:
         *		A 64-bit integer that represents the index in the sourceArray at which copying begins.
         * destinationArray:
         *		The Array that receives the data.
         * destinationIndex:
         *		A 64-bit integer that represents the index in the destinationArray at which storing begins.
         * length:
         *		A 64-bit integer that represents the number of elements to copy.
         */
        static Copy(sourceArray, sourceIndex, destinationArray, destinationIndex, length) {
            for (let i = 0; i < length; i++) {
                destinationArray[destinationIndex + i] = sourceArray[sourceIndex + i];
            }
        }
        static Copy2(sourceArray, sourceIndex, destinationArray, destinationIndex, length) {
            for (let i = 0; i < length; i++) {
                destinationArray[destinationIndex + i] = sourceArray[sourceIndex + i];
            }
        }
    }
    /**
     * A utility class which helps to create the set of DiffChanges from
     * a difference operation. This class accepts original DiffElements and
     * modified DiffElements that are involved in a particular change. The
     * MarkNextChange() method can be called to mark the separation between
     * distinct changes. At the end, the Changes property can be called to retrieve
     * the constructed changes.
     */
    class DiffChangeHelper {
        /**
         * Constructs a new DiffChangeHelper for the given DiffSequences.
         */
        constructor() {
            this.m_changes = [];
            this.m_originalStart = 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */;
            this.m_modifiedStart = 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */;
            this.m_originalCount = 0;
            this.m_modifiedCount = 0;
        }
        /**
         * Marks the beginning of the next change in the set of differences.
         */
        MarkNextChange() {
            // Only add to the list if there is something to add
            if (this.m_originalCount > 0 || this.m_modifiedCount > 0) {
                // Add the new change to our list
                this.m_changes.push(new diffChange_1.DiffChange(this.m_originalStart, this.m_originalCount, this.m_modifiedStart, this.m_modifiedCount));
            }
            // Reset for the next change
            this.m_originalCount = 0;
            this.m_modifiedCount = 0;
            this.m_originalStart = 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */;
            this.m_modifiedStart = 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */;
        }
        /**
         * Adds the original element at the given position to the elements
         * affected by the current change. The modified index gives context
         * to the change position with respect to the original sequence.
         * @param originalIndex The index of the original element to add.
         * @param modifiedIndex The index of the modified element that provides corresponding position in the modified sequence.
         */
        AddOriginalElement(originalIndex, modifiedIndex) {
            // The 'true' start index is the smallest of the ones we've seen
            this.m_originalStart = Math.min(this.m_originalStart, originalIndex);
            this.m_modifiedStart = Math.min(this.m_modifiedStart, modifiedIndex);
            this.m_originalCount++;
        }
        /**
         * Adds the modified element at the given position to the elements
         * affected by the current change. The original index gives context
         * to the change position with respect to the modified sequence.
         * @param originalIndex The index of the original element that provides corresponding position in the original sequence.
         * @param modifiedIndex The index of the modified element to add.
         */
        AddModifiedElement(originalIndex, modifiedIndex) {
            // The 'true' start index is the smallest of the ones we've seen
            this.m_originalStart = Math.min(this.m_originalStart, originalIndex);
            this.m_modifiedStart = Math.min(this.m_modifiedStart, modifiedIndex);
            this.m_modifiedCount++;
        }
        /**
         * Retrieves all of the changes marked by the class.
         */
        getChanges() {
            if (this.m_originalCount > 0 || this.m_modifiedCount > 0) {
                // Finish up on whatever is left
                this.MarkNextChange();
            }
            return this.m_changes;
        }
        /**
         * Retrieves all of the changes marked by the class in the reverse order
         */
        getReverseChanges() {
            if (this.m_originalCount > 0 || this.m_modifiedCount > 0) {
                // Finish up on whatever is left
                this.MarkNextChange();
            }
            this.m_changes.reverse();
            return this.m_changes;
        }
    }
    /**
     * An implementation of the difference algorithm described in
     * "An O(ND) Difference Algorithm and its variations" by Eugene W. Myers
     */
    class LcsDiff {
        /**
         * Constructs the DiffFinder
         */
        constructor(originalSequence, modifiedSequence, continueProcessingPredicate = null) {
            this.ContinueProcessingPredicate = continueProcessingPredicate;
            this._originalSequence = originalSequence;
            this._modifiedSequence = modifiedSequence;
            const [originalStringElements, originalElementsOrHash, originalHasStrings] = LcsDiff._getElements(originalSequence);
            const [modifiedStringElements, modifiedElementsOrHash, modifiedHasStrings] = LcsDiff._getElements(modifiedSequence);
            this._hasStrings = (originalHasStrings && modifiedHasStrings);
            this._originalStringElements = originalStringElements;
            this._originalElementsOrHash = originalElementsOrHash;
            this._modifiedStringElements = modifiedStringElements;
            this._modifiedElementsOrHash = modifiedElementsOrHash;
            this.m_forwardHistory = [];
            this.m_reverseHistory = [];
        }
        static _isStringArray(arr) {
            return (arr.length > 0 && typeof arr[0] === 'string');
        }
        static _getElements(sequence) {
            const elements = sequence.getElements();
            if (LcsDiff._isStringArray(elements)) {
                const hashes = new Int32Array(elements.length);
                for (let i = 0, len = elements.length; i < len; i++) {
                    hashes[i] = (0, hash_1.stringHash)(elements[i], 0);
                }
                return [elements, hashes, true];
            }
            if (elements instanceof Int32Array) {
                return [[], elements, false];
            }
            return [[], new Int32Array(elements), false];
        }
        ElementsAreEqual(originalIndex, newIndex) {
            if (this._originalElementsOrHash[originalIndex] !== this._modifiedElementsOrHash[newIndex]) {
                return false;
            }
            return (this._hasStrings ? this._originalStringElements[originalIndex] === this._modifiedStringElements[newIndex] : true);
        }
        ElementsAreStrictEqual(originalIndex, newIndex) {
            if (!this.ElementsAreEqual(originalIndex, newIndex)) {
                return false;
            }
            const originalElement = LcsDiff._getStrictElement(this._originalSequence, originalIndex);
            const modifiedElement = LcsDiff._getStrictElement(this._modifiedSequence, newIndex);
            return (originalElement === modifiedElement);
        }
        static _getStrictElement(sequence, index) {
            if (typeof sequence.getStrictElement === 'function') {
                return sequence.getStrictElement(index);
            }
            return null;
        }
        OriginalElementsAreEqual(index1, index2) {
            if (this._originalElementsOrHash[index1] !== this._originalElementsOrHash[index2]) {
                return false;
            }
            return (this._hasStrings ? this._originalStringElements[index1] === this._originalStringElements[index2] : true);
        }
        ModifiedElementsAreEqual(index1, index2) {
            if (this._modifiedElementsOrHash[index1] !== this._modifiedElementsOrHash[index2]) {
                return false;
            }
            return (this._hasStrings ? this._modifiedStringElements[index1] === this._modifiedStringElements[index2] : true);
        }
        ComputeDiff(pretty) {
            return this._ComputeDiff(0, this._originalElementsOrHash.length - 1, 0, this._modifiedElementsOrHash.length - 1, pretty);
        }
        /**
         * Computes the differences between the original and modified input
         * sequences on the bounded range.
         * @returns An array of the differences between the two input sequences.
         */
        _ComputeDiff(originalStart, originalEnd, modifiedStart, modifiedEnd, pretty) {
            const quitEarlyArr = [false];
            let changes = this.ComputeDiffRecursive(originalStart, originalEnd, modifiedStart, modifiedEnd, quitEarlyArr);
            if (pretty) {
                // We have to clean up the computed diff to be more intuitive
                // but it turns out this cannot be done correctly until the entire set
                // of diffs have been computed
                changes = this.PrettifyChanges(changes);
            }
            return {
                quitEarly: quitEarlyArr[0],
                changes: changes
            };
        }
        /**
         * Private helper method which computes the differences on the bounded range
         * recursively.
         * @returns An array of the differences between the two input sequences.
         */
        ComputeDiffRecursive(originalStart, originalEnd, modifiedStart, modifiedEnd, quitEarlyArr) {
            quitEarlyArr[0] = false;
            // Find the start of the differences
            while (originalStart <= originalEnd && modifiedStart <= modifiedEnd && this.ElementsAreEqual(originalStart, modifiedStart)) {
                originalStart++;
                modifiedStart++;
            }
            // Find the end of the differences
            while (originalEnd >= originalStart && modifiedEnd >= modifiedStart && this.ElementsAreEqual(originalEnd, modifiedEnd)) {
                originalEnd--;
                modifiedEnd--;
            }
            // In the special case where we either have all insertions or all deletions or the sequences are identical
            if (originalStart > originalEnd || modifiedStart > modifiedEnd) {
                let changes;
                if (modifiedStart <= modifiedEnd) {
                    Debug.Assert(originalStart === originalEnd + 1, 'originalStart should only be one more than originalEnd');
                    // All insertions
                    changes = [
                        new diffChange_1.DiffChange(originalStart, 0, modifiedStart, modifiedEnd - modifiedStart + 1)
                    ];
                }
                else if (originalStart <= originalEnd) {
                    Debug.Assert(modifiedStart === modifiedEnd + 1, 'modifiedStart should only be one more than modifiedEnd');
                    // All deletions
                    changes = [
                        new diffChange_1.DiffChange(originalStart, originalEnd - originalStart + 1, modifiedStart, 0)
                    ];
                }
                else {
                    Debug.Assert(originalStart === originalEnd + 1, 'originalStart should only be one more than originalEnd');
                    Debug.Assert(modifiedStart === modifiedEnd + 1, 'modifiedStart should only be one more than modifiedEnd');
                    // Identical sequences - No differences
                    changes = [];
                }
                return changes;
            }
            // This problem can be solved using the Divide-And-Conquer technique.
            const midOriginalArr = [0];
            const midModifiedArr = [0];
            const result = this.ComputeRecursionPoint(originalStart, originalEnd, modifiedStart, modifiedEnd, midOriginalArr, midModifiedArr, quitEarlyArr);
            const midOriginal = midOriginalArr[0];
            const midModified = midModifiedArr[0];
            if (result !== null) {
                // Result is not-null when there was enough memory to compute the changes while
                // searching for the recursion point
                return result;
            }
            else if (!quitEarlyArr[0]) {
                // We can break the problem down recursively by finding the changes in the
                // First Half:   (originalStart, modifiedStart) to (midOriginal, midModified)
                // Second Half:  (midOriginal + 1, minModified + 1) to (originalEnd, modifiedEnd)
                // NOTE: ComputeDiff() is inclusive, therefore the second range starts on the next point
                const leftChanges = this.ComputeDiffRecursive(originalStart, midOriginal, modifiedStart, midModified, quitEarlyArr);
                let rightChanges = [];
                if (!quitEarlyArr[0]) {
                    rightChanges = this.ComputeDiffRecursive(midOriginal + 1, originalEnd, midModified + 1, modifiedEnd, quitEarlyArr);
                }
                else {
                    // We didn't have time to finish the first half, so we don't have time to compute this half.
                    // Consider the entire rest of the sequence different.
                    rightChanges = [
                        new diffChange_1.DiffChange(midOriginal + 1, originalEnd - (midOriginal + 1) + 1, midModified + 1, modifiedEnd - (midModified + 1) + 1)
                    ];
                }
                return this.ConcatenateChanges(leftChanges, rightChanges);
            }
            // If we hit here, we quit early, and so can't return anything meaningful
            return [
                new diffChange_1.DiffChange(originalStart, originalEnd - originalStart + 1, modifiedStart, modifiedEnd - modifiedStart + 1)
            ];
        }
        WALKTRACE(diagonalForwardBase, diagonalForwardStart, diagonalForwardEnd, diagonalForwardOffset, diagonalReverseBase, diagonalReverseStart, diagonalReverseEnd, diagonalReverseOffset, forwardPoints, reversePoints, originalIndex, originalEnd, midOriginalArr, modifiedIndex, modifiedEnd, midModifiedArr, deltaIsEven, quitEarlyArr) {
            let forwardChanges = null;
            let reverseChanges = null;
            // First, walk backward through the forward diagonals history
            let changeHelper = new DiffChangeHelper();
            let diagonalMin = diagonalForwardStart;
            let diagonalMax = diagonalForwardEnd;
            let diagonalRelative = (midOriginalArr[0] - midModifiedArr[0]) - diagonalForwardOffset;
            let lastOriginalIndex = -1073741824 /* Constants.MIN_SAFE_SMALL_INTEGER */;
            let historyIndex = this.m_forwardHistory.length - 1;
            do {
                // Get the diagonal index from the relative diagonal number
                const diagonal = diagonalRelative + diagonalForwardBase;
                // Figure out where we came from
                if (diagonal === diagonalMin || (diagonal < diagonalMax && forwardPoints[diagonal - 1] < forwardPoints[diagonal + 1])) {
                    // Vertical line (the element is an insert)
                    originalIndex = forwardPoints[diagonal + 1];
                    modifiedIndex = originalIndex - diagonalRelative - diagonalForwardOffset;
                    if (originalIndex < lastOriginalIndex) {
                        changeHelper.MarkNextChange();
                    }
                    lastOriginalIndex = originalIndex;
                    changeHelper.AddModifiedElement(originalIndex + 1, modifiedIndex);
                    diagonalRelative = (diagonal + 1) - diagonalForwardBase; //Setup for the next iteration
                }
                else {
                    // Horizontal line (the element is a deletion)
                    originalIndex = forwardPoints[diagonal - 1] + 1;
                    modifiedIndex = originalIndex - diagonalRelative - diagonalForwardOffset;
                    if (originalIndex < lastOriginalIndex) {
                        changeHelper.MarkNextChange();
                    }
                    lastOriginalIndex = originalIndex - 1;
                    changeHelper.AddOriginalElement(originalIndex, modifiedIndex + 1);
                    diagonalRelative = (diagonal - 1) - diagonalForwardBase; //Setup for the next iteration
                }
                if (historyIndex >= 0) {
                    forwardPoints = this.m_forwardHistory[historyIndex];
                    diagonalForwardBase = forwardPoints[0]; //We stored this in the first spot
                    diagonalMin = 1;
                    diagonalMax = forwardPoints.length - 1;
                }
            } while (--historyIndex >= -1);
            // Ironically, we get the forward changes as the reverse of the
            // order we added them since we technically added them backwards
            forwardChanges = changeHelper.getReverseChanges();
            if (quitEarlyArr[0]) {
                // TODO: Calculate a partial from the reverse diagonals.
                //       For now, just assume everything after the midOriginal/midModified point is a diff
                let originalStartPoint = midOriginalArr[0] + 1;
                let modifiedStartPoint = midModifiedArr[0] + 1;
                if (forwardChanges !== null && forwardChanges.length > 0) {
                    const lastForwardChange = forwardChanges[forwardChanges.length - 1];
                    originalStartPoint = Math.max(originalStartPoint, lastForwardChange.getOriginalEnd());
                    modifiedStartPoint = Math.max(modifiedStartPoint, lastForwardChange.getModifiedEnd());
                }
                reverseChanges = [
                    new diffChange_1.DiffChange(originalStartPoint, originalEnd - originalStartPoint + 1, modifiedStartPoint, modifiedEnd - modifiedStartPoint + 1)
                ];
            }
            else {
                // Now walk backward through the reverse diagonals history
                changeHelper = new DiffChangeHelper();
                diagonalMin = diagonalReverseStart;
                diagonalMax = diagonalReverseEnd;
                diagonalRelative = (midOriginalArr[0] - midModifiedArr[0]) - diagonalReverseOffset;
                lastOriginalIndex = 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */;
                historyIndex = (deltaIsEven) ? this.m_reverseHistory.length - 1 : this.m_reverseHistory.length - 2;
                do {
                    // Get the diagonal index from the relative diagonal number
                    const diagonal = diagonalRelative + diagonalReverseBase;
                    // Figure out where we came from
                    if (diagonal === diagonalMin || (diagonal < diagonalMax && reversePoints[diagonal - 1] >= reversePoints[diagonal + 1])) {
                        // Horizontal line (the element is a deletion))
                        originalIndex = reversePoints[diagonal + 1] - 1;
                        modifiedIndex = originalIndex - diagonalRelative - diagonalReverseOffset;
                        if (originalIndex > lastOriginalIndex) {
                            changeHelper.MarkNextChange();
                        }
                        lastOriginalIndex = originalIndex + 1;
                        changeHelper.AddOriginalElement(originalIndex + 1, modifiedIndex + 1);
                        diagonalRelative = (diagonal + 1) - diagonalReverseBase; //Setup for the next iteration
                    }
                    else {
                        // Vertical line (the element is an insertion)
                        originalIndex = reversePoints[diagonal - 1];
                        modifiedIndex = originalIndex - diagonalRelative - diagonalReverseOffset;
                        if (originalIndex > lastOriginalIndex) {
                            changeHelper.MarkNextChange();
                        }
                        lastOriginalIndex = originalIndex;
                        changeHelper.AddModifiedElement(originalIndex + 1, modifiedIndex + 1);
                        diagonalRelative = (diagonal - 1) - diagonalReverseBase; //Setup for the next iteration
                    }
                    if (historyIndex >= 0) {
                        reversePoints = this.m_reverseHistory[historyIndex];
                        diagonalReverseBase = reversePoints[0]; //We stored this in the first spot
                        diagonalMin = 1;
                        diagonalMax = reversePoints.length - 1;
                    }
                } while (--historyIndex >= -1);
                // There are cases where the reverse history will find diffs that
                // are correct, but not intuitive, so we need shift them.
                reverseChanges = changeHelper.getChanges();
            }
            return this.ConcatenateChanges(forwardChanges, reverseChanges);
        }
        /**
         * Given the range to compute the diff on, this method finds the point:
         * (midOriginal, midModified)
         * that exists in the middle of the LCS of the two sequences and
         * is the point at which the LCS problem may be broken down recursively.
         * This method will try to keep the LCS trace in memory. If the LCS recursion
         * point is calculated and the full trace is available in memory, then this method
         * will return the change list.
         * @param originalStart The start bound of the original sequence range
         * @param originalEnd The end bound of the original sequence range
         * @param modifiedStart The start bound of the modified sequence range
         * @param modifiedEnd The end bound of the modified sequence range
         * @param midOriginal The middle point of the original sequence range
         * @param midModified The middle point of the modified sequence range
         * @returns The diff changes, if available, otherwise null
         */
        ComputeRecursionPoint(originalStart, originalEnd, modifiedStart, modifiedEnd, midOriginalArr, midModifiedArr, quitEarlyArr) {
            let originalIndex = 0, modifiedIndex = 0;
            let diagonalForwardStart = 0, diagonalForwardEnd = 0;
            let diagonalReverseStart = 0, diagonalReverseEnd = 0;
            // To traverse the edit graph and produce the proper LCS, our actual
            // start position is just outside the given boundary
            originalStart--;
            modifiedStart--;
            // We set these up to make the compiler happy, but they will
            // be replaced before we return with the actual recursion point
            midOriginalArr[0] = 0;
            midModifiedArr[0] = 0;
            // Clear out the history
            this.m_forwardHistory = [];
            this.m_reverseHistory = [];
            // Each cell in the two arrays corresponds to a diagonal in the edit graph.
            // The integer value in the cell represents the originalIndex of the furthest
            // reaching point found so far that ends in that diagonal.
            // The modifiedIndex can be computed mathematically from the originalIndex and the diagonal number.
            const maxDifferences = (originalEnd - originalStart) + (modifiedEnd - modifiedStart);
            const numDiagonals = maxDifferences + 1;
            const forwardPoints = new Int32Array(numDiagonals);
            const reversePoints = new Int32Array(numDiagonals);
            // diagonalForwardBase: Index into forwardPoints of the diagonal which passes through (originalStart, modifiedStart)
            // diagonalReverseBase: Index into reversePoints of the diagonal which passes through (originalEnd, modifiedEnd)
            const diagonalForwardBase = (modifiedEnd - modifiedStart);
            const diagonalReverseBase = (originalEnd - originalStart);
            // diagonalForwardOffset: Geometric offset which allows modifiedIndex to be computed from originalIndex and the
            //    diagonal number (relative to diagonalForwardBase)
            // diagonalReverseOffset: Geometric offset which allows modifiedIndex to be computed from originalIndex and the
            //    diagonal number (relative to diagonalReverseBase)
            const diagonalForwardOffset = (originalStart - modifiedStart);
            const diagonalReverseOffset = (originalEnd - modifiedEnd);
            // delta: The difference between the end diagonal and the start diagonal. This is used to relate diagonal numbers
            //   relative to the start diagonal with diagonal numbers relative to the end diagonal.
            // The Even/Oddn-ness of this delta is important for determining when we should check for overlap
            const delta = diagonalReverseBase - diagonalForwardBase;
            const deltaIsEven = (delta % 2 === 0);
            // Here we set up the start and end points as the furthest points found so far
            // in both the forward and reverse directions, respectively
            forwardPoints[diagonalForwardBase] = originalStart;
            reversePoints[diagonalReverseBase] = originalEnd;
            // Remember if we quit early, and thus need to do a best-effort result instead of a real result.
            quitEarlyArr[0] = false;
            // A couple of points:
            // --With this method, we iterate on the number of differences between the two sequences.
            //   The more differences there actually are, the longer this will take.
            // --Also, as the number of differences increases, we have to search on diagonals further
            //   away from the reference diagonal (which is diagonalForwardBase for forward, diagonalReverseBase for reverse).
            // --We extend on even diagonals (relative to the reference diagonal) only when numDifferences
            //   is even and odd diagonals only when numDifferences is odd.
            for (let numDifferences = 1; numDifferences <= (maxDifferences / 2) + 1; numDifferences++) {
                let furthestOriginalIndex = 0;
                let furthestModifiedIndex = 0;
                // Run the algorithm in the forward direction
                diagonalForwardStart = this.ClipDiagonalBound(diagonalForwardBase - numDifferences, numDifferences, diagonalForwardBase, numDiagonals);
                diagonalForwardEnd = this.ClipDiagonalBound(diagonalForwardBase + numDifferences, numDifferences, diagonalForwardBase, numDiagonals);
                for (let diagonal = diagonalForwardStart; diagonal <= diagonalForwardEnd; diagonal += 2) {
                    // STEP 1: We extend the furthest reaching point in the present diagonal
                    // by looking at the diagonals above and below and picking the one whose point
                    // is further away from the start point (originalStart, modifiedStart)
                    if (diagonal === diagonalForwardStart || (diagonal < diagonalForwardEnd && forwardPoints[diagonal - 1] < forwardPoints[diagonal + 1])) {
                        originalIndex = forwardPoints[diagonal + 1];
                    }
                    else {
                        originalIndex = forwardPoints[diagonal - 1] + 1;
                    }
                    modifiedIndex = originalIndex - (diagonal - diagonalForwardBase) - diagonalForwardOffset;
                    // Save the current originalIndex so we can test for false overlap in step 3
                    const tempOriginalIndex = originalIndex;
                    // STEP 2: We can continue to extend the furthest reaching point in the present diagonal
                    // so long as the elements are equal.
                    while (originalIndex < originalEnd && modifiedIndex < modifiedEnd && this.ElementsAreEqual(originalIndex + 1, modifiedIndex + 1)) {
                        originalIndex++;
                        modifiedIndex++;
                    }
                    forwardPoints[diagonal] = originalIndex;
                    if (originalIndex + modifiedIndex > furthestOriginalIndex + furthestModifiedIndex) {
                        furthestOriginalIndex = originalIndex;
                        furthestModifiedIndex = modifiedIndex;
                    }
                    // STEP 3: If delta is odd (overlap first happens on forward when delta is odd)
                    // and diagonal is in the range of reverse diagonals computed for numDifferences-1
                    // (the previous iteration; we haven't computed reverse diagonals for numDifferences yet)
                    // then check for overlap.
                    if (!deltaIsEven && Math.abs(diagonal - diagonalReverseBase) <= (numDifferences - 1)) {
                        if (originalIndex >= reversePoints[diagonal]) {
                            midOriginalArr[0] = originalIndex;
                            midModifiedArr[0] = modifiedIndex;
                            if (tempOriginalIndex <= reversePoints[diagonal] && 1447 /* LocalConstants.MaxDifferencesHistory */ > 0 && numDifferences <= (1447 /* LocalConstants.MaxDifferencesHistory */ + 1)) {
                                // BINGO! We overlapped, and we have the full trace in memory!
                                return this.WALKTRACE(diagonalForwardBase, diagonalForwardStart, diagonalForwardEnd, diagonalForwardOffset, diagonalReverseBase, diagonalReverseStart, diagonalReverseEnd, diagonalReverseOffset, forwardPoints, reversePoints, originalIndex, originalEnd, midOriginalArr, modifiedIndex, modifiedEnd, midModifiedArr, deltaIsEven, quitEarlyArr);
                            }
                            else {
                                // Either false overlap, or we didn't have enough memory for the full trace
                                // Just return the recursion point
                                return null;
                            }
                        }
                    }
                }
                // Check to see if we should be quitting early, before moving on to the next iteration.
                const matchLengthOfLongest = ((furthestOriginalIndex - originalStart) + (furthestModifiedIndex - modifiedStart) - numDifferences) / 2;
                if (this.ContinueProcessingPredicate !== null && !this.ContinueProcessingPredicate(furthestOriginalIndex, matchLengthOfLongest)) {
                    // We can't finish, so skip ahead to generating a result from what we have.
                    quitEarlyArr[0] = true;
                    // Use the furthest distance we got in the forward direction.
                    midOriginalArr[0] = furthestOriginalIndex;
                    midModifiedArr[0] = furthestModifiedIndex;
                    if (matchLengthOfLongest > 0 && 1447 /* LocalConstants.MaxDifferencesHistory */ > 0 && numDifferences <= (1447 /* LocalConstants.MaxDifferencesHistory */ + 1)) {
                        // Enough of the history is in memory to walk it backwards
                        return this.WALKTRACE(diagonalForwardBase, diagonalForwardStart, diagonalForwardEnd, diagonalForwardOffset, diagonalReverseBase, diagonalReverseStart, diagonalReverseEnd, diagonalReverseOffset, forwardPoints, reversePoints, originalIndex, originalEnd, midOriginalArr, modifiedIndex, modifiedEnd, midModifiedArr, deltaIsEven, quitEarlyArr);
                    }
                    else {
                        // We didn't actually remember enough of the history.
                        //Since we are quitting the diff early, we need to shift back the originalStart and modified start
                        //back into the boundary limits since we decremented their value above beyond the boundary limit.
                        originalStart++;
                        modifiedStart++;
                        return [
                            new diffChange_1.DiffChange(originalStart, originalEnd - originalStart + 1, modifiedStart, modifiedEnd - modifiedStart + 1)
                        ];
                    }
                }
                // Run the algorithm in the reverse direction
                diagonalReverseStart = this.ClipDiagonalBound(diagonalReverseBase - numDifferences, numDifferences, diagonalReverseBase, numDiagonals);
                diagonalReverseEnd = this.ClipDiagonalBound(diagonalReverseBase + numDifferences, numDifferences, diagonalReverseBase, numDiagonals);
                for (let diagonal = diagonalReverseStart; diagonal <= diagonalReverseEnd; diagonal += 2) {
                    // STEP 1: We extend the furthest reaching point in the present diagonal
                    // by looking at the diagonals above and below and picking the one whose point
                    // is further away from the start point (originalEnd, modifiedEnd)
                    if (diagonal === diagonalReverseStart || (diagonal < diagonalReverseEnd && reversePoints[diagonal - 1] >= reversePoints[diagonal + 1])) {
                        originalIndex = reversePoints[diagonal + 1] - 1;
                    }
                    else {
                        originalIndex = reversePoints[diagonal - 1];
                    }
                    modifiedIndex = originalIndex - (diagonal - diagonalReverseBase) - diagonalReverseOffset;
                    // Save the current originalIndex so we can test for false overlap
                    const tempOriginalIndex = originalIndex;
                    // STEP 2: We can continue to extend the furthest reaching point in the present diagonal
                    // as long as the elements are equal.
                    while (originalIndex > originalStart && modifiedIndex > modifiedStart && this.ElementsAreEqual(originalIndex, modifiedIndex)) {
                        originalIndex--;
                        modifiedIndex--;
                    }
                    reversePoints[diagonal] = originalIndex;
                    // STEP 4: If delta is even (overlap first happens on reverse when delta is even)
                    // and diagonal is in the range of forward diagonals computed for numDifferences
                    // then check for overlap.
                    if (deltaIsEven && Math.abs(diagonal - diagonalForwardBase) <= numDifferences) {
                        if (originalIndex <= forwardPoints[diagonal]) {
                            midOriginalArr[0] = originalIndex;
                            midModifiedArr[0] = modifiedIndex;
                            if (tempOriginalIndex >= forwardPoints[diagonal] && 1447 /* LocalConstants.MaxDifferencesHistory */ > 0 && numDifferences <= (1447 /* LocalConstants.MaxDifferencesHistory */ + 1)) {
                                // BINGO! We overlapped, and we have the full trace in memory!
                                return this.WALKTRACE(diagonalForwardBase, diagonalForwardStart, diagonalForwardEnd, diagonalForwardOffset, diagonalReverseBase, diagonalReverseStart, diagonalReverseEnd, diagonalReverseOffset, forwardPoints, reversePoints, originalIndex, originalEnd, midOriginalArr, modifiedIndex, modifiedEnd, midModifiedArr, deltaIsEven, quitEarlyArr);
                            }
                            else {
                                // Either false overlap, or we didn't have enough memory for the full trace
                                // Just return the recursion point
                                return null;
                            }
                        }
                    }
                }
                // Save current vectors to history before the next iteration
                if (numDifferences <= 1447 /* LocalConstants.MaxDifferencesHistory */) {
                    // We are allocating space for one extra int, which we fill with
                    // the index of the diagonal base index
                    let temp = new Int32Array(diagonalForwardEnd - diagonalForwardStart + 2);
                    temp[0] = diagonalForwardBase - diagonalForwardStart + 1;
                    MyArray.Copy2(forwardPoints, diagonalForwardStart, temp, 1, diagonalForwardEnd - diagonalForwardStart + 1);
                    this.m_forwardHistory.push(temp);
                    temp = new Int32Array(diagonalReverseEnd - diagonalReverseStart + 2);
                    temp[0] = diagonalReverseBase - diagonalReverseStart + 1;
                    MyArray.Copy2(reversePoints, diagonalReverseStart, temp, 1, diagonalReverseEnd - diagonalReverseStart + 1);
                    this.m_reverseHistory.push(temp);
                }
            }
            // If we got here, then we have the full trace in history. We just have to convert it to a change list
            // NOTE: This part is a bit messy
            return this.WALKTRACE(diagonalForwardBase, diagonalForwardStart, diagonalForwardEnd, diagonalForwardOffset, diagonalReverseBase, diagonalReverseStart, diagonalReverseEnd, diagonalReverseOffset, forwardPoints, reversePoints, originalIndex, originalEnd, midOriginalArr, modifiedIndex, modifiedEnd, midModifiedArr, deltaIsEven, quitEarlyArr);
        }
        /**
         * Shifts the given changes to provide a more intuitive diff.
         * While the first element in a diff matches the first element after the diff,
         * we shift the diff down.
         *
         * @param changes The list of changes to shift
         * @returns The shifted changes
         */
        PrettifyChanges(changes) {
            // Shift all the changes down first
            for (let i = 0; i < changes.length; i++) {
                const change = changes[i];
                const originalStop = (i < changes.length - 1) ? changes[i + 1].originalStart : this._originalElementsOrHash.length;
                const modifiedStop = (i < changes.length - 1) ? changes[i + 1].modifiedStart : this._modifiedElementsOrHash.length;
                const checkOriginal = change.originalLength > 0;
                const checkModified = change.modifiedLength > 0;
                while (change.originalStart + change.originalLength < originalStop
                    && change.modifiedStart + change.modifiedLength < modifiedStop
                    && (!checkOriginal || this.OriginalElementsAreEqual(change.originalStart, change.originalStart + change.originalLength))
                    && (!checkModified || this.ModifiedElementsAreEqual(change.modifiedStart, change.modifiedStart + change.modifiedLength))) {
                    const startStrictEqual = this.ElementsAreStrictEqual(change.originalStart, change.modifiedStart);
                    const endStrictEqual = this.ElementsAreStrictEqual(change.originalStart + change.originalLength, change.modifiedStart + change.modifiedLength);
                    if (endStrictEqual && !startStrictEqual) {
                        // moving the change down would create an equal change, but the elements are not strict equal
                        break;
                    }
                    change.originalStart++;
                    change.modifiedStart++;
                }
                const mergedChangeArr = [null];
                if (i < changes.length - 1 && this.ChangesOverlap(changes[i], changes[i + 1], mergedChangeArr)) {
                    changes[i] = mergedChangeArr[0];
                    changes.splice(i + 1, 1);
                    i--;
                    continue;
                }
            }
            // Shift changes back up until we hit empty or whitespace-only lines
            for (let i = changes.length - 1; i >= 0; i--) {
                const change = changes[i];
                let originalStop = 0;
                let modifiedStop = 0;
                if (i > 0) {
                    const prevChange = changes[i - 1];
                    originalStop = prevChange.originalStart + prevChange.originalLength;
                    modifiedStop = prevChange.modifiedStart + prevChange.modifiedLength;
                }
                const checkOriginal = change.originalLength > 0;
                const checkModified = change.modifiedLength > 0;
                let bestDelta = 0;
                let bestScore = this._boundaryScore(change.originalStart, change.originalLength, change.modifiedStart, change.modifiedLength);
                for (let delta = 1;; delta++) {
                    const originalStart = change.originalStart - delta;
                    const modifiedStart = change.modifiedStart - delta;
                    if (originalStart < originalStop || modifiedStart < modifiedStop) {
                        break;
                    }
                    if (checkOriginal && !this.OriginalElementsAreEqual(originalStart, originalStart + change.originalLength)) {
                        break;
                    }
                    if (checkModified && !this.ModifiedElementsAreEqual(modifiedStart, modifiedStart + change.modifiedLength)) {
                        break;
                    }
                    const touchingPreviousChange = (originalStart === originalStop && modifiedStart === modifiedStop);
                    const score = ((touchingPreviousChange ? 5 : 0)
                        + this._boundaryScore(originalStart, change.originalLength, modifiedStart, change.modifiedLength));
                    if (score > bestScore) {
                        bestScore = score;
                        bestDelta = delta;
                    }
                }
                change.originalStart -= bestDelta;
                change.modifiedStart -= bestDelta;
                const mergedChangeArr = [null];
                if (i > 0 && this.ChangesOverlap(changes[i - 1], changes[i], mergedChangeArr)) {
                    changes[i - 1] = mergedChangeArr[0];
                    changes.splice(i, 1);
                    i++;
                    continue;
                }
            }
            // There could be multiple longest common substrings.
            // Give preference to the ones containing longer lines
            if (this._hasStrings) {
                for (let i = 1, len = changes.length; i < len; i++) {
                    const aChange = changes[i - 1];
                    const bChange = changes[i];
                    const matchedLength = bChange.originalStart - aChange.originalStart - aChange.originalLength;
                    const aOriginalStart = aChange.originalStart;
                    const bOriginalEnd = bChange.originalStart + bChange.originalLength;
                    const abOriginalLength = bOriginalEnd - aOriginalStart;
                    const aModifiedStart = aChange.modifiedStart;
                    const bModifiedEnd = bChange.modifiedStart + bChange.modifiedLength;
                    const abModifiedLength = bModifiedEnd - aModifiedStart;
                    // Avoid wasting a lot of time with these searches
                    if (matchedLength < 5 && abOriginalLength < 20 && abModifiedLength < 20) {
                        const t = this._findBetterContiguousSequence(aOriginalStart, abOriginalLength, aModifiedStart, abModifiedLength, matchedLength);
                        if (t) {
                            const [originalMatchStart, modifiedMatchStart] = t;
                            if (originalMatchStart !== aChange.originalStart + aChange.originalLength || modifiedMatchStart !== aChange.modifiedStart + aChange.modifiedLength) {
                                // switch to another sequence that has a better score
                                aChange.originalLength = originalMatchStart - aChange.originalStart;
                                aChange.modifiedLength = modifiedMatchStart - aChange.modifiedStart;
                                bChange.originalStart = originalMatchStart + matchedLength;
                                bChange.modifiedStart = modifiedMatchStart + matchedLength;
                                bChange.originalLength = bOriginalEnd - bChange.originalStart;
                                bChange.modifiedLength = bModifiedEnd - bChange.modifiedStart;
                            }
                        }
                    }
                }
            }
            return changes;
        }
        _findBetterContiguousSequence(originalStart, originalLength, modifiedStart, modifiedLength, desiredLength) {
            if (originalLength < desiredLength || modifiedLength < desiredLength) {
                return null;
            }
            const originalMax = originalStart + originalLength - desiredLength + 1;
            const modifiedMax = modifiedStart + modifiedLength - desiredLength + 1;
            let bestScore = 0;
            let bestOriginalStart = 0;
            let bestModifiedStart = 0;
            for (let i = originalStart; i < originalMax; i++) {
                for (let j = modifiedStart; j < modifiedMax; j++) {
                    const score = this._contiguousSequenceScore(i, j, desiredLength);
                    if (score > 0 && score > bestScore) {
                        bestScore = score;
                        bestOriginalStart = i;
                        bestModifiedStart = j;
                    }
                }
            }
            if (bestScore > 0) {
                return [bestOriginalStart, bestModifiedStart];
            }
            return null;
        }
        _contiguousSequenceScore(originalStart, modifiedStart, length) {
            let score = 0;
            for (let l = 0; l < length; l++) {
                if (!this.ElementsAreEqual(originalStart + l, modifiedStart + l)) {
                    return 0;
                }
                score += this._originalStringElements[originalStart + l].length;
            }
            return score;
        }
        _OriginalIsBoundary(index) {
            if (index <= 0 || index >= this._originalElementsOrHash.length - 1) {
                return true;
            }
            return (this._hasStrings && /^\s*$/.test(this._originalStringElements[index]));
        }
        _OriginalRegionIsBoundary(originalStart, originalLength) {
            if (this._OriginalIsBoundary(originalStart) || this._OriginalIsBoundary(originalStart - 1)) {
                return true;
            }
            if (originalLength > 0) {
                const originalEnd = originalStart + originalLength;
                if (this._OriginalIsBoundary(originalEnd - 1) || this._OriginalIsBoundary(originalEnd)) {
                    return true;
                }
            }
            return false;
        }
        _ModifiedIsBoundary(index) {
            if (index <= 0 || index >= this._modifiedElementsOrHash.length - 1) {
                return true;
            }
            return (this._hasStrings && /^\s*$/.test(this._modifiedStringElements[index]));
        }
        _ModifiedRegionIsBoundary(modifiedStart, modifiedLength) {
            if (this._ModifiedIsBoundary(modifiedStart) || this._ModifiedIsBoundary(modifiedStart - 1)) {
                return true;
            }
            if (modifiedLength > 0) {
                const modifiedEnd = modifiedStart + modifiedLength;
                if (this._ModifiedIsBoundary(modifiedEnd - 1) || this._ModifiedIsBoundary(modifiedEnd)) {
                    return true;
                }
            }
            return false;
        }
        _boundaryScore(originalStart, originalLength, modifiedStart, modifiedLength) {
            const originalScore = (this._OriginalRegionIsBoundary(originalStart, originalLength) ? 1 : 0);
            const modifiedScore = (this._ModifiedRegionIsBoundary(modifiedStart, modifiedLength) ? 1 : 0);
            return (originalScore + modifiedScore);
        }
        /**
         * Concatenates the two input DiffChange lists and returns the resulting
         * list.
         * @param The left changes
         * @param The right changes
         * @returns The concatenated list
         */
        ConcatenateChanges(left, right) {
            const mergedChangeArr = [];
            if (left.length === 0 || right.length === 0) {
                return (right.length > 0) ? right : left;
            }
            else if (this.ChangesOverlap(left[left.length - 1], right[0], mergedChangeArr)) {
                // Since we break the problem down recursively, it is possible that we
                // might recurse in the middle of a change thereby splitting it into
                // two changes. Here in the combining stage, we detect and fuse those
                // changes back together
                const result = new Array(left.length + right.length - 1);
                MyArray.Copy(left, 0, result, 0, left.length - 1);
                result[left.length - 1] = mergedChangeArr[0];
                MyArray.Copy(right, 1, result, left.length, right.length - 1);
                return result;
            }
            else {
                const result = new Array(left.length + right.length);
                MyArray.Copy(left, 0, result, 0, left.length);
                MyArray.Copy(right, 0, result, left.length, right.length);
                return result;
            }
        }
        /**
         * Returns true if the two changes overlap and can be merged into a single
         * change
         * @param left The left change
         * @param right The right change
         * @param mergedChange The merged change if the two overlap, null otherwise
         * @returns True if the two changes overlap
         */
        ChangesOverlap(left, right, mergedChangeArr) {
            Debug.Assert(left.originalStart <= right.originalStart, 'Left change is not less than or equal to right change');
            Debug.Assert(left.modifiedStart <= right.modifiedStart, 'Left change is not less than or equal to right change');
            if (left.originalStart + left.originalLength >= right.originalStart || left.modifiedStart + left.modifiedLength >= right.modifiedStart) {
                const originalStart = left.originalStart;
                let originalLength = left.originalLength;
                const modifiedStart = left.modifiedStart;
                let modifiedLength = left.modifiedLength;
                if (left.originalStart + left.originalLength >= right.originalStart) {
                    originalLength = right.originalStart + right.originalLength - left.originalStart;
                }
                if (left.modifiedStart + left.modifiedLength >= right.modifiedStart) {
                    modifiedLength = right.modifiedStart + right.modifiedLength - left.modifiedStart;
                }
                mergedChangeArr[0] = new diffChange_1.DiffChange(originalStart, originalLength, modifiedStart, modifiedLength);
                return true;
            }
            else {
                mergedChangeArr[0] = null;
                return false;
            }
        }
        /**
         * Helper method used to clip a diagonal index to the range of valid
         * diagonals. This also decides whether or not the diagonal index,
         * if it exceeds the boundary, should be clipped to the boundary or clipped
         * one inside the boundary depending on the Even/Odd status of the boundary
         * and numDifferences.
         * @param diagonal The index of the diagonal to clip.
         * @param numDifferences The current number of differences being iterated upon.
         * @param diagonalBaseIndex The base reference diagonal.
         * @param numDiagonals The total number of diagonals.
         * @returns The clipped diagonal index.
         */
        ClipDiagonalBound(diagonal, numDifferences, diagonalBaseIndex, numDiagonals) {
            if (diagonal >= 0 && diagonal < numDiagonals) {
                // Nothing to clip, its in range
                return diagonal;
            }
            // diagonalsBelow: The number of diagonals below the reference diagonal
            // diagonalsAbove: The number of diagonals above the reference diagonal
            const diagonalsBelow = diagonalBaseIndex;
            const diagonalsAbove = numDiagonals - diagonalBaseIndex - 1;
            const diffEven = (numDifferences % 2 === 0);
            if (diagonal < 0) {
                const lowerBoundEven = (diagonalsBelow % 2 === 0);
                return (diffEven === lowerBoundEven) ? 0 : 1;
            }
            else {
                const upperBoundEven = (diagonalsAbove % 2 === 0);
                return (diffEven === upperBoundEven) ? numDiagonals - 1 : numDiagonals - 2;
            }
        }
    }
    exports.LcsDiff = LcsDiff;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[455/*vs/base/common/search*/], __M([1/*require*/,0/*exports*/,11/*vs/base/common/strings*/]), function (require, exports, strings) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.buildReplaceStringWithCasePreserved = buildReplaceStringWithCasePreserved;
    function buildReplaceStringWithCasePreserved(matches, pattern) {
        if (matches && (matches[0] !== '')) {
            const containsHyphens = validateSpecificSpecialCharacter(matches, pattern, '-');
            const containsUnderscores = validateSpecificSpecialCharacter(matches, pattern, '_');
            if (containsHyphens && !containsUnderscores) {
                return buildReplaceStringForSpecificSpecialCharacter(matches, pattern, '-');
            }
            else if (!containsHyphens && containsUnderscores) {
                return buildReplaceStringForSpecificSpecialCharacter(matches, pattern, '_');
            }
            if (matches[0].toUpperCase() === matches[0]) {
                return pattern.toUpperCase();
            }
            else if (matches[0].toLowerCase() === matches[0]) {
                return pattern.toLowerCase();
            }
            else if (strings.containsUppercaseCharacter(matches[0][0]) && pattern.length > 0) {
                return pattern[0].toUpperCase() + pattern.substr(1);
            }
            else if (matches[0][0].toUpperCase() !== matches[0][0] && pattern.length > 0) {
                return pattern[0].toLowerCase() + pattern.substr(1);
            }
            else {
                // we don't understand its pattern yet.
                return pattern;
            }
        }
        else {
            return pattern;
        }
    }
    function validateSpecificSpecialCharacter(matches, pattern, specialCharacter) {
        const doesContainSpecialCharacter = matches[0].indexOf(specialCharacter) !== -1 && pattern.indexOf(specialCharacter) !== -1;
        return doesContainSpecialCharacter && matches[0].split(specialCharacter).length === pattern.split(specialCharacter).length;
    }
    function buildReplaceStringForSpecificSpecialCharacter(matches, pattern, specialCharacter) {
        const splitPatternAtSpecialCharacter = pattern.split(specialCharacter);
        const splitMatchAtSpecialCharacter = matches[0].split(specialCharacter);
        let replaceString = '';
        splitPatternAtSpecialCharacter.forEach((splitValue, index) => {
            replaceString += buildReplaceStringWithCasePreserved([splitMatchAtSpecialCharacter[index]], splitValue) + specialCharacter;
        });
        return replaceString.slice(0, -1);
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[111/*vs/base/common/severity*/], __M([1/*require*/,0/*exports*/,11/*vs/base/common/strings*/]), function (require, exports, strings) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var Severity;
    (function (Severity) {
        Severity[Severity["Ignore"] = 0] = "Ignore";
        Severity[Severity["Info"] = 1] = "Info";
        Severity[Severity["Warning"] = 2] = "Warning";
        Severity[Severity["Error"] = 3] = "Error";
    })(Severity || (Severity = {}));
    (function (Severity) {
        const _error = 'error';
        const _warning = 'warning';
        const _warn = 'warn';
        const _info = 'info';
        const _ignore = 'ignore';
        /**
         * Parses 'error', 'warning', 'warn', 'info' in call casings
         * and falls back to ignore.
         */
        function fromValue(value) {
            if (!value) {
                return Severity.Ignore;
            }
            if (strings.equalsIgnoreCase(_error, value)) {
                return Severity.Error;
            }
            if (strings.equalsIgnoreCase(_warning, value) || strings.equalsIgnoreCase(_warn, value)) {
                return Severity.Warning;
            }
            if (strings.equalsIgnoreCase(_info, value)) {
                return Severity.Info;
            }
            return Severity.Ignore;
        }
        Severity.fromValue = fromValue;
        function toString(severity) {
            switch (severity) {
                case Severity.Error: return _error;
                case Severity.Warning: return _warning;
                case Severity.Info: return _info;
                default: return _ignore;
            }
        }
        Severity.toString = toString;
    })(Severity || (Severity = {}));
    exports.default = Severity;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[301/*vs/base/common/symbols*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MicrotaskDelay = void 0;
    /**
     * Can be passed into the Delayed to defer using a microtask
     * */
    exports.MicrotaskDelay = Symbol('MicrotaskDelay');
});

define(__m[225/*vs/base/common/ternarySearchTree*/], __M([1/*require*/,0/*exports*/,11/*vs/base/common/strings*/]), function (require, exports, strings_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.TernarySearchTree = exports.UriIterator = exports.PathIterator = exports.ConfigKeysIterator = exports.StringIterator = void 0;
    class StringIterator {
        constructor() {
            this._value = '';
            this._pos = 0;
        }
        reset(key) {
            this._value = key;
            this._pos = 0;
            return this;
        }
        next() {
            this._pos += 1;
            return this;
        }
        hasNext() {
            return this._pos < this._value.length - 1;
        }
        cmp(a) {
            const aCode = a.charCodeAt(0);
            const thisCode = this._value.charCodeAt(this._pos);
            return aCode - thisCode;
        }
        value() {
            return this._value[this._pos];
        }
    }
    exports.StringIterator = StringIterator;
    class ConfigKeysIterator {
        constructor(_caseSensitive = true) {
            this._caseSensitive = _caseSensitive;
        }
        reset(key) {
            this._value = key;
            this._from = 0;
            this._to = 0;
            return this.next();
        }
        hasNext() {
            return this._to < this._value.length;
        }
        next() {
            // this._data = key.split(/[\\/]/).filter(s => !!s);
            this._from = this._to;
            let justSeps = true;
            for (; this._to < this._value.length; this._to++) {
                const ch = this._value.charCodeAt(this._to);
                if (ch === 46 /* CharCode.Period */) {
                    if (justSeps) {
                        this._from++;
                    }
                    else {
                        break;
                    }
                }
                else {
                    justSeps = false;
                }
            }
            return this;
        }
        cmp(a) {
            return this._caseSensitive
                ? (0, strings_1.compareSubstring)(a, this._value, 0, a.length, this._from, this._to)
                : (0, strings_1.compareSubstringIgnoreCase)(a, this._value, 0, a.length, this._from, this._to);
        }
        value() {
            return this._value.substring(this._from, this._to);
        }
    }
    exports.ConfigKeysIterator = ConfigKeysIterator;
    class PathIterator {
        constructor(_splitOnBackslash = true, _caseSensitive = true) {
            this._splitOnBackslash = _splitOnBackslash;
            this._caseSensitive = _caseSensitive;
        }
        reset(key) {
            this._from = 0;
            this._to = 0;
            this._value = key;
            this._valueLen = key.length;
            for (let pos = key.length - 1; pos >= 0; pos--, this._valueLen--) {
                const ch = this._value.charCodeAt(pos);
                if (!(ch === 47 /* CharCode.Slash */ || this._splitOnBackslash && ch === 92 /* CharCode.Backslash */)) {
                    break;
                }
            }
            return this.next();
        }
        hasNext() {
            return this._to < this._valueLen;
        }
        next() {
            // this._data = key.split(/[\\/]/).filter(s => !!s);
            this._from = this._to;
            let justSeps = true;
            for (; this._to < this._valueLen; this._to++) {
                const ch = this._value.charCodeAt(this._to);
                if (ch === 47 /* CharCode.Slash */ || this._splitOnBackslash && ch === 92 /* CharCode.Backslash */) {
                    if (justSeps) {
                        this._from++;
                    }
                    else {
                        break;
                    }
                }
                else {
                    justSeps = false;
                }
            }
            return this;
        }
        cmp(a) {
            return this._caseSensitive
                ? (0, strings_1.compareSubstring)(a, this._value, 0, a.length, this._from, this._to)
                : (0, strings_1.compareSubstringIgnoreCase)(a, this._value, 0, a.length, this._from, this._to);
        }
        value() {
            return this._value.substring(this._from, this._to);
        }
    }
    exports.PathIterator = PathIterator;
    class UriIterator {
        constructor(_ignorePathCasing, _ignoreQueryAndFragment) {
            this._ignorePathCasing = _ignorePathCasing;
            this._ignoreQueryAndFragment = _ignoreQueryAndFragment;
            this._states = [];
            this._stateIdx = 0;
        }
        reset(key) {
            this._value = key;
            this._states = [];
            if (this._value.scheme) {
                this._states.push(1 /* UriIteratorState.Scheme */);
            }
            if (this._value.authority) {
                this._states.push(2 /* UriIteratorState.Authority */);
            }
            if (this._value.path) {
                this._pathIterator = new PathIterator(false, !this._ignorePathCasing(key));
                this._pathIterator.reset(key.path);
                if (this._pathIterator.value()) {
                    this._states.push(3 /* UriIteratorState.Path */);
                }
            }
            if (!this._ignoreQueryAndFragment(key)) {
                if (this._value.query) {
                    this._states.push(4 /* UriIteratorState.Query */);
                }
                if (this._value.fragment) {
                    this._states.push(5 /* UriIteratorState.Fragment */);
                }
            }
            this._stateIdx = 0;
            return this;
        }
        next() {
            if (this._states[this._stateIdx] === 3 /* UriIteratorState.Path */ && this._pathIterator.hasNext()) {
                this._pathIterator.next();
            }
            else {
                this._stateIdx += 1;
            }
            return this;
        }
        hasNext() {
            return (this._states[this._stateIdx] === 3 /* UriIteratorState.Path */ && this._pathIterator.hasNext())
                || this._stateIdx < this._states.length - 1;
        }
        cmp(a) {
            if (this._states[this._stateIdx] === 1 /* UriIteratorState.Scheme */) {
                return (0, strings_1.compareIgnoreCase)(a, this._value.scheme);
            }
            else if (this._states[this._stateIdx] === 2 /* UriIteratorState.Authority */) {
                return (0, strings_1.compareIgnoreCase)(a, this._value.authority);
            }
            else if (this._states[this._stateIdx] === 3 /* UriIteratorState.Path */) {
                return this._pathIterator.cmp(a);
            }
            else if (this._states[this._stateIdx] === 4 /* UriIteratorState.Query */) {
                return (0, strings_1.compare)(a, this._value.query);
            }
            else if (this._states[this._stateIdx] === 5 /* UriIteratorState.Fragment */) {
                return (0, strings_1.compare)(a, this._value.fragment);
            }
            throw new Error();
        }
        value() {
            if (this._states[this._stateIdx] === 1 /* UriIteratorState.Scheme */) {
                return this._value.scheme;
            }
            else if (this._states[this._stateIdx] === 2 /* UriIteratorState.Authority */) {
                return this._value.authority;
            }
            else if (this._states[this._stateIdx] === 3 /* UriIteratorState.Path */) {
                return this._pathIterator.value();
            }
            else if (this._states[this._stateIdx] === 4 /* UriIteratorState.Query */) {
                return this._value.query;
            }
            else if (this._states[this._stateIdx] === 5 /* UriIteratorState.Fragment */) {
                return this._value.fragment;
            }
            throw new Error();
        }
    }
    exports.UriIterator = UriIterator;
    class TernarySearchTreeNode {
        constructor() {
            this.height = 1;
        }
        rotateLeft() {
            const tmp = this.right;
            this.right = tmp.left;
            tmp.left = this;
            this.updateHeight();
            tmp.updateHeight();
            return tmp;
        }
        rotateRight() {
            const tmp = this.left;
            this.left = tmp.right;
            tmp.right = this;
            this.updateHeight();
            tmp.updateHeight();
            return tmp;
        }
        updateHeight() {
            this.height = 1 + Math.max(this.heightLeft, this.heightRight);
        }
        balanceFactor() {
            return this.heightRight - this.heightLeft;
        }
        get heightLeft() {
            return this.left?.height ?? 0;
        }
        get heightRight() {
            return this.right?.height ?? 0;
        }
    }
    class TernarySearchTree {
        static forUris(ignorePathCasing = () => false, ignoreQueryAndFragment = () => false) {
            return new TernarySearchTree(new UriIterator(ignorePathCasing, ignoreQueryAndFragment));
        }
        static forStrings() {
            return new TernarySearchTree(new StringIterator());
        }
        static forConfigKeys() {
            return new TernarySearchTree(new ConfigKeysIterator());
        }
        constructor(segments) {
            this._iter = segments;
        }
        clear() {
            this._root = undefined;
        }
        set(key, element) {
            const iter = this._iter.reset(key);
            let node;
            if (!this._root) {
                this._root = new TernarySearchTreeNode();
                this._root.segment = iter.value();
            }
            const stack = [];
            // find insert_node
            node = this._root;
            while (true) {
                const val = iter.cmp(node.segment);
                if (val > 0) {
                    // left
                    if (!node.left) {
                        node.left = new TernarySearchTreeNode();
                        node.left.segment = iter.value();
                    }
                    stack.push([-1 /* Dir.Left */, node]);
                    node = node.left;
                }
                else if (val < 0) {
                    // right
                    if (!node.right) {
                        node.right = new TernarySearchTreeNode();
                        node.right.segment = iter.value();
                    }
                    stack.push([1 /* Dir.Right */, node]);
                    node = node.right;
                }
                else if (iter.hasNext()) {
                    // mid
                    iter.next();
                    if (!node.mid) {
                        node.mid = new TernarySearchTreeNode();
                        node.mid.segment = iter.value();
                    }
                    stack.push([0 /* Dir.Mid */, node]);
                    node = node.mid;
                }
                else {
                    break;
                }
            }
            // set value
            const oldElement = node.value;
            node.value = element;
            node.key = key;
            // balance
            for (let i = stack.length - 1; i >= 0; i--) {
                const node = stack[i][1];
                node.updateHeight();
                const bf = node.balanceFactor();
                if (bf < -1 || bf > 1) {
                    // needs rotate
                    const d1 = stack[i][0];
                    const d2 = stack[i + 1][0];
                    if (d1 === 1 /* Dir.Right */ && d2 === 1 /* Dir.Right */) {
                        //right, right -> rotate left
                        stack[i][1] = node.rotateLeft();
                    }
                    else if (d1 === -1 /* Dir.Left */ && d2 === -1 /* Dir.Left */) {
                        // left, left -> rotate right
                        stack[i][1] = node.rotateRight();
                    }
                    else if (d1 === 1 /* Dir.Right */ && d2 === -1 /* Dir.Left */) {
                        // right, left -> double rotate right, left
                        node.right = stack[i + 1][1] = stack[i + 1][1].rotateRight();
                        stack[i][1] = node.rotateLeft();
                    }
                    else if (d1 === -1 /* Dir.Left */ && d2 === 1 /* Dir.Right */) {
                        // left, right -> double rotate left, right
                        node.left = stack[i + 1][1] = stack[i + 1][1].rotateLeft();
                        stack[i][1] = node.rotateRight();
                    }
                    else {
                        throw new Error();
                    }
                    // patch path to parent
                    if (i > 0) {
                        switch (stack[i - 1][0]) {
                            case -1 /* Dir.Left */:
                                stack[i - 1][1].left = stack[i][1];
                                break;
                            case 1 /* Dir.Right */:
                                stack[i - 1][1].right = stack[i][1];
                                break;
                            case 0 /* Dir.Mid */:
                                stack[i - 1][1].mid = stack[i][1];
                                break;
                        }
                    }
                    else {
                        this._root = stack[0][1];
                    }
                }
            }
            return oldElement;
        }
        get(key) {
            return this._getNode(key)?.value;
        }
        _getNode(key) {
            const iter = this._iter.reset(key);
            let node = this._root;
            while (node) {
                const val = iter.cmp(node.segment);
                if (val > 0) {
                    // left
                    node = node.left;
                }
                else if (val < 0) {
                    // right
                    node = node.right;
                }
                else if (iter.hasNext()) {
                    // mid
                    iter.next();
                    node = node.mid;
                }
                else {
                    break;
                }
            }
            return node;
        }
        has(key) {
            const node = this._getNode(key);
            return !(node?.value === undefined && node?.mid === undefined);
        }
        delete(key) {
            return this._delete(key, false);
        }
        deleteSuperstr(key) {
            return this._delete(key, true);
        }
        _delete(key, superStr) {
            const iter = this._iter.reset(key);
            const stack = [];
            let node = this._root;
            // find node
            while (node) {
                const val = iter.cmp(node.segment);
                if (val > 0) {
                    // left
                    stack.push([-1 /* Dir.Left */, node]);
                    node = node.left;
                }
                else if (val < 0) {
                    // right
                    stack.push([1 /* Dir.Right */, node]);
                    node = node.right;
                }
                else if (iter.hasNext()) {
                    // mid
                    iter.next();
                    stack.push([0 /* Dir.Mid */, node]);
                    node = node.mid;
                }
                else {
                    break;
                }
            }
            if (!node) {
                // node not found
                return;
            }
            if (superStr) {
                // removing children, reset height
                node.left = undefined;
                node.mid = undefined;
                node.right = undefined;
                node.height = 1;
            }
            else {
                // removing element
                node.key = undefined;
                node.value = undefined;
            }
            // BST node removal
            if (!node.mid && !node.value) {
                if (node.left && node.right) {
                    // full node
                    // replace deleted-node with the min-node of the right branch.
                    // If there is no true min-node leave things as they are
                    const min = this._min(node.right);
                    if (min.key) {
                        const { key, value, segment } = min;
                        this._delete(min.key, false);
                        node.key = key;
                        node.value = value;
                        node.segment = segment;
                    }
                }
                else {
                    // empty or half empty
                    const newChild = node.left ?? node.right;
                    if (stack.length > 0) {
                        const [dir, parent] = stack[stack.length - 1];
                        switch (dir) {
                            case -1 /* Dir.Left */:
                                parent.left = newChild;
                                break;
                            case 0 /* Dir.Mid */:
                                parent.mid = newChild;
                                break;
                            case 1 /* Dir.Right */:
                                parent.right = newChild;
                                break;
                        }
                    }
                    else {
                        this._root = newChild;
                    }
                }
            }
            // AVL balance
            for (let i = stack.length - 1; i >= 0; i--) {
                const node = stack[i][1];
                node.updateHeight();
                const bf = node.balanceFactor();
                if (bf > 1) {
                    // right heavy
                    if (node.right.balanceFactor() >= 0) {
                        // right, right -> rotate left
                        stack[i][1] = node.rotateLeft();
                    }
                    else {
                        // right, left -> double rotate
                        node.right = node.right.rotateRight();
                        stack[i][1] = node.rotateLeft();
                    }
                }
                else if (bf < -1) {
                    // left heavy
                    if (node.left.balanceFactor() <= 0) {
                        // left, left -> rotate right
                        stack[i][1] = node.rotateRight();
                    }
                    else {
                        // left, right -> double rotate
                        node.left = node.left.rotateLeft();
                        stack[i][1] = node.rotateRight();
                    }
                }
                // patch path to parent
                if (i > 0) {
                    switch (stack[i - 1][0]) {
                        case -1 /* Dir.Left */:
                            stack[i - 1][1].left = stack[i][1];
                            break;
                        case 1 /* Dir.Right */:
                            stack[i - 1][1].right = stack[i][1];
                            break;
                        case 0 /* Dir.Mid */:
                            stack[i - 1][1].mid = stack[i][1];
                            break;
                    }
                }
                else {
                    this._root = stack[0][1];
                }
            }
        }
        _min(node) {
            while (node.left) {
                node = node.left;
            }
            return node;
        }
        findSubstr(key) {
            const iter = this._iter.reset(key);
            let node = this._root;
            let candidate = undefined;
            while (node) {
                const val = iter.cmp(node.segment);
                if (val > 0) {
                    // left
                    node = node.left;
                }
                else if (val < 0) {
                    // right
                    node = node.right;
                }
                else if (iter.hasNext()) {
                    // mid
                    iter.next();
                    candidate = node.value || candidate;
                    node = node.mid;
                }
                else {
                    break;
                }
            }
            return node && node.value || candidate;
        }
        findSuperstr(key) {
            return this._findSuperstrOrElement(key, false);
        }
        _findSuperstrOrElement(key, allowValue) {
            const iter = this._iter.reset(key);
            let node = this._root;
            while (node) {
                const val = iter.cmp(node.segment);
                if (val > 0) {
                    // left
                    node = node.left;
                }
                else if (val < 0) {
                    // right
                    node = node.right;
                }
                else if (iter.hasNext()) {
                    // mid
                    iter.next();
                    node = node.mid;
                }
                else {
                    // collect
                    if (!node.mid) {
                        if (allowValue) {
                            return node.value;
                        }
                        else {
                            return undefined;
                        }
                    }
                    else {
                        return this._entries(node.mid);
                    }
                }
            }
            return undefined;
        }
        forEach(callback) {
            for (const [key, value] of this) {
                callback(value, key);
            }
        }
        *[Symbol.iterator]() {
            yield* this._entries(this._root);
        }
        _entries(node) {
            const result = [];
            this._dfsEntries(node, result);
            return result[Symbol.iterator]();
        }
        _dfsEntries(node, bucket) {
            // DFS
            if (!node) {
                return;
            }
            if (node.left) {
                this._dfsEntries(node.left, bucket);
            }
            if (node.value) {
                bucket.push([node.key, node.value]);
            }
            if (node.mid) {
                this._dfsEntries(node.mid, bucket);
            }
            if (node.right) {
                this._dfsEntries(node.right, bucket);
            }
        }
    }
    exports.TernarySearchTree = TernarySearchTree;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[456/*vs/base/common/tfIdf*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.TfIdfCalculator = void 0;
    exports.normalizeTfIdfScores = normalizeTfIdfScores;
    function countMapFrom(values) {
        const map = new Map();
        for (const value of values) {
            map.set(value, (map.get(value) ?? 0) + 1);
        }
        return map;
    }
    /**
     * Implementation of tf-idf (term frequency-inverse document frequency) for a set of
     * documents where each document contains one or more chunks of text.
     * Each document is identified by a key, and the score for each document is computed
     * by taking the max score over all the chunks in the document.
     */
    class TfIdfCalculator {
        constructor() {
            /**
             * Total number of chunks
             */
            this.chunkCount = 0;
            this.chunkOccurrences = new Map();
            this.documents = new Map();
        }
        calculateScores(query, token) {
            const embedding = this.computeEmbedding(query);
            const idfCache = new Map();
            const scores = [];
            // For each document, generate one score
            for (const [key, doc] of this.documents) {
                if (token.isCancellationRequested) {
                    return [];
                }
                for (const chunk of doc.chunks) {
                    const score = this.computeSimilarityScore(chunk, embedding, idfCache);
                    if (score > 0) {
                        scores.push({ key, score });
                    }
                }
            }
            return scores;
        }
        /**
         * Count how many times each term (word) appears in a string.
         */
        static termFrequencies(input) {
            return countMapFrom(TfIdfCalculator.splitTerms(input));
        }
        /**
         * Break a string into terms (words).
         */
        static *splitTerms(input) {
            const normalize = (word) => word.toLowerCase();
            // Only match on words that are at least 3 characters long and start with a letter
            for (const [word] of input.matchAll(/\b\p{Letter}[\p{Letter}\d]{2,}\b/gu)) {
                yield normalize(word);
                const camelParts = word.replace(/([a-z])([A-Z])/g, '$1 $2').split(/\s+/g);
                if (camelParts.length > 1) {
                    for (const part of camelParts) {
                        // Require at least 3 letters in the parts of a camel case word
                        if (part.length > 2 && /\p{Letter}{3,}/gu.test(part)) {
                            yield normalize(part);
                        }
                    }
                }
            }
        }
        updateDocuments(documents) {
            for (const { key } of documents) {
                this.deleteDocument(key);
            }
            for (const doc of documents) {
                const chunks = [];
                for (const text of doc.textChunks) {
                    // TODO: See if we can compute the tf lazily
                    // The challenge is that we need to also update the `chunkOccurrences`
                    // and all of those updates need to get flushed before the real TF-IDF of
                    // anything is computed.
                    const tf = TfIdfCalculator.termFrequencies(text);
                    // Update occurrences list
                    for (const term of tf.keys()) {
                        this.chunkOccurrences.set(term, (this.chunkOccurrences.get(term) ?? 0) + 1);
                    }
                    chunks.push({ text, tf });
                }
                this.chunkCount += chunks.length;
                this.documents.set(doc.key, { chunks });
            }
            return this;
        }
        deleteDocument(key) {
            const doc = this.documents.get(key);
            if (!doc) {
                return;
            }
            this.documents.delete(key);
            this.chunkCount -= doc.chunks.length;
            // Update term occurrences for the document
            for (const chunk of doc.chunks) {
                for (const term of chunk.tf.keys()) {
                    const currentOccurrences = this.chunkOccurrences.get(term);
                    if (typeof currentOccurrences === 'number') {
                        const newOccurrences = currentOccurrences - 1;
                        if (newOccurrences <= 0) {
                            this.chunkOccurrences.delete(term);
                        }
                        else {
                            this.chunkOccurrences.set(term, newOccurrences);
                        }
                    }
                }
            }
        }
        computeSimilarityScore(chunk, queryEmbedding, idfCache) {
            // Compute the dot product between the chunk's embedding and the query embedding
            // Note that the chunk embedding is computed lazily on a per-term basis.
            // This lets us skip a large number of calculations because the majority
            // of chunks do not share any terms with the query.
            let sum = 0;
            for (const [term, termTfidf] of Object.entries(queryEmbedding)) {
                const chunkTf = chunk.tf.get(term);
                if (!chunkTf) {
                    // Term does not appear in chunk so it has no contribution
                    continue;
                }
                let chunkIdf = idfCache.get(term);
                if (typeof chunkIdf !== 'number') {
                    chunkIdf = this.computeIdf(term);
                    idfCache.set(term, chunkIdf);
                }
                const chunkTfidf = chunkTf * chunkIdf;
                sum += chunkTfidf * termTfidf;
            }
            return sum;
        }
        computeEmbedding(input) {
            const tf = TfIdfCalculator.termFrequencies(input);
            return this.computeTfidf(tf);
        }
        computeIdf(term) {
            const chunkOccurrences = this.chunkOccurrences.get(term) ?? 0;
            return chunkOccurrences > 0
                ? Math.log((this.chunkCount + 1) / chunkOccurrences)
                : 0;
        }
        computeTfidf(termFrequencies) {
            const embedding = Object.create(null);
            for (const [word, occurrences] of termFrequencies) {
                const idf = this.computeIdf(word);
                if (idf > 0) {
                    embedding[word] = occurrences * idf;
                }
            }
            return embedding;
        }
    }
    exports.TfIdfCalculator = TfIdfCalculator;
    /**
     * Normalize the scores to be between 0 and 1 and sort them decending.
     * @param scores array of scores from {@link TfIdfCalculator.calculateScores}
     * @returns normalized scores
     */
    function normalizeTfIdfScores(scores) {
        // copy of scores
        const result = scores.slice(0);
        // sort descending
        result.sort((a, b) => b.score - a.score);
        // normalize
        const max = result[0]?.score ?? 0;
        if (max > 0) {
            for (const score of result) {
                score.score /= max;
            }
        }
        return result;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[19/*vs/base/common/types*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.isString = isString;
    exports.isObject = isObject;
    exports.isTypedArray = isTypedArray;
    exports.isNumber = isNumber;
    exports.isIterable = isIterable;
    exports.isBoolean = isBoolean;
    exports.isUndefined = isUndefined;
    exports.isDefined = isDefined;
    exports.isUndefinedOrNull = isUndefinedOrNull;
    exports.assertType = assertType;
    exports.assertIsDefined = assertIsDefined;
    exports.isFunction = isFunction;
    exports.validateConstraints = validateConstraints;
    exports.validateConstraint = validateConstraint;
    /**
     * @returns whether the provided parameter is a JavaScript String or not.
     */
    function isString(str) {
        return (typeof str === 'string');
    }
    /**
     * @returns whether the provided parameter is of type `object` but **not**
     *	`null`, an `array`, a `regexp`, nor a `date`.
     */
    function isObject(obj) {
        // The method can't do a type cast since there are type (like strings) which
        // are subclasses of any put not positvely matched by the function. Hence type
        // narrowing results in wrong results.
        return typeof obj === 'object'
            && obj !== null
            && !Array.isArray(obj)
            && !(obj instanceof RegExp)
            && !(obj instanceof Date);
    }
    /**
     * @returns whether the provided parameter is of type `Buffer` or Uint8Array dervived type
     */
    function isTypedArray(obj) {
        const TypedArray = Object.getPrototypeOf(Uint8Array);
        return typeof obj === 'object'
            && obj instanceof TypedArray;
    }
    /**
     * In **contrast** to just checking `typeof` this will return `false` for `NaN`.
     * @returns whether the provided parameter is a JavaScript Number or not.
     */
    function isNumber(obj) {
        return (typeof obj === 'number' && !isNaN(obj));
    }
    /**
     * @returns whether the provided parameter is an Iterable, casting to the given generic
     */
    function isIterable(obj) {
        return !!obj && typeof obj[Symbol.iterator] === 'function';
    }
    /**
     * @returns whether the provided parameter is a JavaScript Boolean or not.
     */
    function isBoolean(obj) {
        return (obj === true || obj === false);
    }
    /**
     * @returns whether the provided parameter is undefined.
     */
    function isUndefined(obj) {
        return (typeof obj === 'undefined');
    }
    /**
     * @returns whether the provided parameter is defined.
     */
    function isDefined(arg) {
        return !isUndefinedOrNull(arg);
    }
    /**
     * @returns whether the provided parameter is undefined or null.
     */
    function isUndefinedOrNull(obj) {
        return (isUndefined(obj) || obj === null);
    }
    function assertType(condition, type) {
        if (!condition) {
            throw new Error(type ? `Unexpected type, expected '${type}'` : 'Unexpected type');
        }
    }
    /**
     * Asserts that the argument passed in is neither undefined nor null.
     */
    function assertIsDefined(arg) {
        if (isUndefinedOrNull(arg)) {
            throw new Error('Assertion Failed: argument is undefined or null');
        }
        return arg;
    }
    /**
     * @returns whether the provided parameter is a JavaScript Function or not.
     */
    function isFunction(obj) {
        return (typeof obj === 'function');
    }
    function validateConstraints(args, constraints) {
        const len = Math.min(args.length, constraints.length);
        for (let i = 0; i < len; i++) {
            validateConstraint(args[i], constraints[i]);
        }
    }
    function validateConstraint(arg, constraint) {
        if (isString(constraint)) {
            if (typeof arg !== constraint) {
                throw new Error(`argument does not match constraint: typeof ${constraint}`);
            }
        }
        else if (isFunction(constraint)) {
            try {
                if (arg instanceof constraint) {
                    return;
                }
            }
            catch {
                // ignore
            }
            if (!isUndefinedOrNull(arg) && arg.constructor === constraint) {
                return;
            }
            if (constraint.length === 1 && constraint.call(undefined, arg) === true) {
                return;
            }
            throw new Error(`argument does not match one of these constraints: arg instanceof constraint, arg.constructor === constraint, nor constraint(arg) === true`);
        }
    }
});

define(__m[191/*vs/base/common/codiconsUtil*/], __M([1/*require*/,0/*exports*/,19/*vs/base/common/types*/]), function (require, exports, types_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.register = register;
    exports.getCodiconFontCharacters = getCodiconFontCharacters;
    const _codiconFontCharacters = Object.create(null);
    function register(id, fontCharacter) {
        if ((0, types_1.isString)(fontCharacter)) {
            const val = _codiconFontCharacters[fontCharacter];
            if (val === undefined) {
                throw new Error(`${id} references an unknown codicon: ${fontCharacter}`);
            }
            fontCharacter = val;
        }
        _codiconFontCharacters[id] = fontCharacter;
        return { id };
    }
    /**
     * Only to be used by the iconRegistry.
     */
    function getCodiconFontCharacters() {
        return _codiconFontCharacters;
    }
});

define(__m[457/*vs/base/common/codiconsLibrary*/], __M([1/*require*/,0/*exports*/,191/*vs/base/common/codiconsUtil*/]), function (require, exports, codiconsUtil_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.codiconsLibrary = void 0;
    // This file is automatically generated by (microsoft/vscode-codicons)/scripts/export-to-ts.js
    // Please don't edit it, as your changes will be overwritten.
    // Instead, add mappings to codiconsDerived in codicons.ts.
    exports.codiconsLibrary = {
        add: (0, codiconsUtil_1.register)('add', 0xea60),
        plus: (0, codiconsUtil_1.register)('plus', 0xea60),
        gistNew: (0, codiconsUtil_1.register)('gist-new', 0xea60),
        repoCreate: (0, codiconsUtil_1.register)('repo-create', 0xea60),
        lightbulb: (0, codiconsUtil_1.register)('lightbulb', 0xea61),
        lightBulb: (0, codiconsUtil_1.register)('light-bulb', 0xea61),
        repo: (0, codiconsUtil_1.register)('repo', 0xea62),
        repoDelete: (0, codiconsUtil_1.register)('repo-delete', 0xea62),
        gistFork: (0, codiconsUtil_1.register)('gist-fork', 0xea63),
        repoForked: (0, codiconsUtil_1.register)('repo-forked', 0xea63),
        gitPullRequest: (0, codiconsUtil_1.register)('git-pull-request', 0xea64),
        gitPullRequestAbandoned: (0, codiconsUtil_1.register)('git-pull-request-abandoned', 0xea64),
        recordKeys: (0, codiconsUtil_1.register)('record-keys', 0xea65),
        keyboard: (0, codiconsUtil_1.register)('keyboard', 0xea65),
        tag: (0, codiconsUtil_1.register)('tag', 0xea66),
        gitPullRequestLabel: (0, codiconsUtil_1.register)('git-pull-request-label', 0xea66),
        tagAdd: (0, codiconsUtil_1.register)('tag-add', 0xea66),
        tagRemove: (0, codiconsUtil_1.register)('tag-remove', 0xea66),
        person: (0, codiconsUtil_1.register)('person', 0xea67),
        personFollow: (0, codiconsUtil_1.register)('person-follow', 0xea67),
        personOutline: (0, codiconsUtil_1.register)('person-outline', 0xea67),
        personFilled: (0, codiconsUtil_1.register)('person-filled', 0xea67),
        gitBranch: (0, codiconsUtil_1.register)('git-branch', 0xea68),
        gitBranchCreate: (0, codiconsUtil_1.register)('git-branch-create', 0xea68),
        gitBranchDelete: (0, codiconsUtil_1.register)('git-branch-delete', 0xea68),
        sourceControl: (0, codiconsUtil_1.register)('source-control', 0xea68),
        mirror: (0, codiconsUtil_1.register)('mirror', 0xea69),
        mirrorPublic: (0, codiconsUtil_1.register)('mirror-public', 0xea69),
        star: (0, codiconsUtil_1.register)('star', 0xea6a),
        starAdd: (0, codiconsUtil_1.register)('star-add', 0xea6a),
        starDelete: (0, codiconsUtil_1.register)('star-delete', 0xea6a),
        starEmpty: (0, codiconsUtil_1.register)('star-empty', 0xea6a),
        comment: (0, codiconsUtil_1.register)('comment', 0xea6b),
        commentAdd: (0, codiconsUtil_1.register)('comment-add', 0xea6b),
        alert: (0, codiconsUtil_1.register)('alert', 0xea6c),
        warning: (0, codiconsUtil_1.register)('warning', 0xea6c),
        search: (0, codiconsUtil_1.register)('search', 0xea6d),
        searchSave: (0, codiconsUtil_1.register)('search-save', 0xea6d),
        logOut: (0, codiconsUtil_1.register)('log-out', 0xea6e),
        signOut: (0, codiconsUtil_1.register)('sign-out', 0xea6e),
        logIn: (0, codiconsUtil_1.register)('log-in', 0xea6f),
        signIn: (0, codiconsUtil_1.register)('sign-in', 0xea6f),
        eye: (0, codiconsUtil_1.register)('eye', 0xea70),
        eyeUnwatch: (0, codiconsUtil_1.register)('eye-unwatch', 0xea70),
        eyeWatch: (0, codiconsUtil_1.register)('eye-watch', 0xea70),
        circleFilled: (0, codiconsUtil_1.register)('circle-filled', 0xea71),
        primitiveDot: (0, codiconsUtil_1.register)('primitive-dot', 0xea71),
        closeDirty: (0, codiconsUtil_1.register)('close-dirty', 0xea71),
        debugBreakpoint: (0, codiconsUtil_1.register)('debug-breakpoint', 0xea71),
        debugBreakpointDisabled: (0, codiconsUtil_1.register)('debug-breakpoint-disabled', 0xea71),
        debugHint: (0, codiconsUtil_1.register)('debug-hint', 0xea71),
        terminalDecorationSuccess: (0, codiconsUtil_1.register)('terminal-decoration-success', 0xea71),
        primitiveSquare: (0, codiconsUtil_1.register)('primitive-square', 0xea72),
        edit: (0, codiconsUtil_1.register)('edit', 0xea73),
        pencil: (0, codiconsUtil_1.register)('pencil', 0xea73),
        info: (0, codiconsUtil_1.register)('info', 0xea74),
        issueOpened: (0, codiconsUtil_1.register)('issue-opened', 0xea74),
        gistPrivate: (0, codiconsUtil_1.register)('gist-private', 0xea75),
        gitForkPrivate: (0, codiconsUtil_1.register)('git-fork-private', 0xea75),
        lock: (0, codiconsUtil_1.register)('lock', 0xea75),
        mirrorPrivate: (0, codiconsUtil_1.register)('mirror-private', 0xea75),
        close: (0, codiconsUtil_1.register)('close', 0xea76),
        removeClose: (0, codiconsUtil_1.register)('remove-close', 0xea76),
        x: (0, codiconsUtil_1.register)('x', 0xea76),
        repoSync: (0, codiconsUtil_1.register)('repo-sync', 0xea77),
        sync: (0, codiconsUtil_1.register)('sync', 0xea77),
        clone: (0, codiconsUtil_1.register)('clone', 0xea78),
        desktopDownload: (0, codiconsUtil_1.register)('desktop-download', 0xea78),
        beaker: (0, codiconsUtil_1.register)('beaker', 0xea79),
        microscope: (0, codiconsUtil_1.register)('microscope', 0xea79),
        vm: (0, codiconsUtil_1.register)('vm', 0xea7a),
        deviceDesktop: (0, codiconsUtil_1.register)('device-desktop', 0xea7a),
        file: (0, codiconsUtil_1.register)('file', 0xea7b),
        fileText: (0, codiconsUtil_1.register)('file-text', 0xea7b),
        more: (0, codiconsUtil_1.register)('more', 0xea7c),
        ellipsis: (0, codiconsUtil_1.register)('ellipsis', 0xea7c),
        kebabHorizontal: (0, codiconsUtil_1.register)('kebab-horizontal', 0xea7c),
        mailReply: (0, codiconsUtil_1.register)('mail-reply', 0xea7d),
        reply: (0, codiconsUtil_1.register)('reply', 0xea7d),
        organization: (0, codiconsUtil_1.register)('organization', 0xea7e),
        organizationFilled: (0, codiconsUtil_1.register)('organization-filled', 0xea7e),
        organizationOutline: (0, codiconsUtil_1.register)('organization-outline', 0xea7e),
        newFile: (0, codiconsUtil_1.register)('new-file', 0xea7f),
        fileAdd: (0, codiconsUtil_1.register)('file-add', 0xea7f),
        newFolder: (0, codiconsUtil_1.register)('new-folder', 0xea80),
        fileDirectoryCreate: (0, codiconsUtil_1.register)('file-directory-create', 0xea80),
        trash: (0, codiconsUtil_1.register)('trash', 0xea81),
        trashcan: (0, codiconsUtil_1.register)('trashcan', 0xea81),
        history: (0, codiconsUtil_1.register)('history', 0xea82),
        clock: (0, codiconsUtil_1.register)('clock', 0xea82),
        folder: (0, codiconsUtil_1.register)('folder', 0xea83),
        fileDirectory: (0, codiconsUtil_1.register)('file-directory', 0xea83),
        symbolFolder: (0, codiconsUtil_1.register)('symbol-folder', 0xea83),
        logoGithub: (0, codiconsUtil_1.register)('logo-github', 0xea84),
        markGithub: (0, codiconsUtil_1.register)('mark-github', 0xea84),
        github: (0, codiconsUtil_1.register)('github', 0xea84),
        terminal: (0, codiconsUtil_1.register)('terminal', 0xea85),
        console: (0, codiconsUtil_1.register)('console', 0xea85),
        repl: (0, codiconsUtil_1.register)('repl', 0xea85),
        zap: (0, codiconsUtil_1.register)('zap', 0xea86),
        symbolEvent: (0, codiconsUtil_1.register)('symbol-event', 0xea86),
        error: (0, codiconsUtil_1.register)('error', 0xea87),
        stop: (0, codiconsUtil_1.register)('stop', 0xea87),
        variable: (0, codiconsUtil_1.register)('variable', 0xea88),
        symbolVariable: (0, codiconsUtil_1.register)('symbol-variable', 0xea88),
        array: (0, codiconsUtil_1.register)('array', 0xea8a),
        symbolArray: (0, codiconsUtil_1.register)('symbol-array', 0xea8a),
        symbolModule: (0, codiconsUtil_1.register)('symbol-module', 0xea8b),
        symbolPackage: (0, codiconsUtil_1.register)('symbol-package', 0xea8b),
        symbolNamespace: (0, codiconsUtil_1.register)('symbol-namespace', 0xea8b),
        symbolObject: (0, codiconsUtil_1.register)('symbol-object', 0xea8b),
        symbolMethod: (0, codiconsUtil_1.register)('symbol-method', 0xea8c),
        symbolFunction: (0, codiconsUtil_1.register)('symbol-function', 0xea8c),
        symbolConstructor: (0, codiconsUtil_1.register)('symbol-constructor', 0xea8c),
        symbolBoolean: (0, codiconsUtil_1.register)('symbol-boolean', 0xea8f),
        symbolNull: (0, codiconsUtil_1.register)('symbol-null', 0xea8f),
        symbolNumeric: (0, codiconsUtil_1.register)('symbol-numeric', 0xea90),
        symbolNumber: (0, codiconsUtil_1.register)('symbol-number', 0xea90),
        symbolStructure: (0, codiconsUtil_1.register)('symbol-structure', 0xea91),
        symbolStruct: (0, codiconsUtil_1.register)('symbol-struct', 0xea91),
        symbolParameter: (0, codiconsUtil_1.register)('symbol-parameter', 0xea92),
        symbolTypeParameter: (0, codiconsUtil_1.register)('symbol-type-parameter', 0xea92),
        symbolKey: (0, codiconsUtil_1.register)('symbol-key', 0xea93),
        symbolText: (0, codiconsUtil_1.register)('symbol-text', 0xea93),
        symbolReference: (0, codiconsUtil_1.register)('symbol-reference', 0xea94),
        goToFile: (0, codiconsUtil_1.register)('go-to-file', 0xea94),
        symbolEnum: (0, codiconsUtil_1.register)('symbol-enum', 0xea95),
        symbolValue: (0, codiconsUtil_1.register)('symbol-value', 0xea95),
        symbolRuler: (0, codiconsUtil_1.register)('symbol-ruler', 0xea96),
        symbolUnit: (0, codiconsUtil_1.register)('symbol-unit', 0xea96),
        activateBreakpoints: (0, codiconsUtil_1.register)('activate-breakpoints', 0xea97),
        archive: (0, codiconsUtil_1.register)('archive', 0xea98),
        arrowBoth: (0, codiconsUtil_1.register)('arrow-both', 0xea99),
        arrowDown: (0, codiconsUtil_1.register)('arrow-down', 0xea9a),
        arrowLeft: (0, codiconsUtil_1.register)('arrow-left', 0xea9b),
        arrowRight: (0, codiconsUtil_1.register)('arrow-right', 0xea9c),
        arrowSmallDown: (0, codiconsUtil_1.register)('arrow-small-down', 0xea9d),
        arrowSmallLeft: (0, codiconsUtil_1.register)('arrow-small-left', 0xea9e),
        arrowSmallRight: (0, codiconsUtil_1.register)('arrow-small-right', 0xea9f),
        arrowSmallUp: (0, codiconsUtil_1.register)('arrow-small-up', 0xeaa0),
        arrowUp: (0, codiconsUtil_1.register)('arrow-up', 0xeaa1),
        bell: (0, codiconsUtil_1.register)('bell', 0xeaa2),
        bold: (0, codiconsUtil_1.register)('bold', 0xeaa3),
        book: (0, codiconsUtil_1.register)('book', 0xeaa4),
        bookmark: (0, codiconsUtil_1.register)('bookmark', 0xeaa5),
        debugBreakpointConditionalUnverified: (0, codiconsUtil_1.register)('debug-breakpoint-conditional-unverified', 0xeaa6),
        debugBreakpointConditional: (0, codiconsUtil_1.register)('debug-breakpoint-conditional', 0xeaa7),
        debugBreakpointConditionalDisabled: (0, codiconsUtil_1.register)('debug-breakpoint-conditional-disabled', 0xeaa7),
        debugBreakpointDataUnverified: (0, codiconsUtil_1.register)('debug-breakpoint-data-unverified', 0xeaa8),
        debugBreakpointData: (0, codiconsUtil_1.register)('debug-breakpoint-data', 0xeaa9),
        debugBreakpointDataDisabled: (0, codiconsUtil_1.register)('debug-breakpoint-data-disabled', 0xeaa9),
        debugBreakpointLogUnverified: (0, codiconsUtil_1.register)('debug-breakpoint-log-unverified', 0xeaaa),
        debugBreakpointLog: (0, codiconsUtil_1.register)('debug-breakpoint-log', 0xeaab),
        debugBreakpointLogDisabled: (0, codiconsUtil_1.register)('debug-breakpoint-log-disabled', 0xeaab),
        briefcase: (0, codiconsUtil_1.register)('briefcase', 0xeaac),
        broadcast: (0, codiconsUtil_1.register)('broadcast', 0xeaad),
        browser: (0, codiconsUtil_1.register)('browser', 0xeaae),
        bug: (0, codiconsUtil_1.register)('bug', 0xeaaf),
        calendar: (0, codiconsUtil_1.register)('calendar', 0xeab0),
        caseSensitive: (0, codiconsUtil_1.register)('case-sensitive', 0xeab1),
        check: (0, codiconsUtil_1.register)('check', 0xeab2),
        checklist: (0, codiconsUtil_1.register)('checklist', 0xeab3),
        chevronDown: (0, codiconsUtil_1.register)('chevron-down', 0xeab4),
        chevronLeft: (0, codiconsUtil_1.register)('chevron-left', 0xeab5),
        chevronRight: (0, codiconsUtil_1.register)('chevron-right', 0xeab6),
        chevronUp: (0, codiconsUtil_1.register)('chevron-up', 0xeab7),
        chromeClose: (0, codiconsUtil_1.register)('chrome-close', 0xeab8),
        chromeMaximize: (0, codiconsUtil_1.register)('chrome-maximize', 0xeab9),
        chromeMinimize: (0, codiconsUtil_1.register)('chrome-minimize', 0xeaba),
        chromeRestore: (0, codiconsUtil_1.register)('chrome-restore', 0xeabb),
        circleOutline: (0, codiconsUtil_1.register)('circle-outline', 0xeabc),
        circle: (0, codiconsUtil_1.register)('circle', 0xeabc),
        debugBreakpointUnverified: (0, codiconsUtil_1.register)('debug-breakpoint-unverified', 0xeabc),
        terminalDecorationIncomplete: (0, codiconsUtil_1.register)('terminal-decoration-incomplete', 0xeabc),
        circleSlash: (0, codiconsUtil_1.register)('circle-slash', 0xeabd),
        circuitBoard: (0, codiconsUtil_1.register)('circuit-board', 0xeabe),
        clearAll: (0, codiconsUtil_1.register)('clear-all', 0xeabf),
        clippy: (0, codiconsUtil_1.register)('clippy', 0xeac0),
        closeAll: (0, codiconsUtil_1.register)('close-all', 0xeac1),
        cloudDownload: (0, codiconsUtil_1.register)('cloud-download', 0xeac2),
        cloudUpload: (0, codiconsUtil_1.register)('cloud-upload', 0xeac3),
        code: (0, codiconsUtil_1.register)('code', 0xeac4),
        collapseAll: (0, codiconsUtil_1.register)('collapse-all', 0xeac5),
        colorMode: (0, codiconsUtil_1.register)('color-mode', 0xeac6),
        commentDiscussion: (0, codiconsUtil_1.register)('comment-discussion', 0xeac7),
        creditCard: (0, codiconsUtil_1.register)('credit-card', 0xeac9),
        dash: (0, codiconsUtil_1.register)('dash', 0xeacc),
        dashboard: (0, codiconsUtil_1.register)('dashboard', 0xeacd),
        database: (0, codiconsUtil_1.register)('database', 0xeace),
        debugContinue: (0, codiconsUtil_1.register)('debug-continue', 0xeacf),
        debugDisconnect: (0, codiconsUtil_1.register)('debug-disconnect', 0xead0),
        debugPause: (0, codiconsUtil_1.register)('debug-pause', 0xead1),
        debugRestart: (0, codiconsUtil_1.register)('debug-restart', 0xead2),
        debugStart: (0, codiconsUtil_1.register)('debug-start', 0xead3),
        debugStepInto: (0, codiconsUtil_1.register)('debug-step-into', 0xead4),
        debugStepOut: (0, codiconsUtil_1.register)('debug-step-out', 0xead5),
        debugStepOver: (0, codiconsUtil_1.register)('debug-step-over', 0xead6),
        debugStop: (0, codiconsUtil_1.register)('debug-stop', 0xead7),
        debug: (0, codiconsUtil_1.register)('debug', 0xead8),
        deviceCameraVideo: (0, codiconsUtil_1.register)('device-camera-video', 0xead9),
        deviceCamera: (0, codiconsUtil_1.register)('device-camera', 0xeada),
        deviceMobile: (0, codiconsUtil_1.register)('device-mobile', 0xeadb),
        diffAdded: (0, codiconsUtil_1.register)('diff-added', 0xeadc),
        diffIgnored: (0, codiconsUtil_1.register)('diff-ignored', 0xeadd),
        diffModified: (0, codiconsUtil_1.register)('diff-modified', 0xeade),
        diffRemoved: (0, codiconsUtil_1.register)('diff-removed', 0xeadf),
        diffRenamed: (0, codiconsUtil_1.register)('diff-renamed', 0xeae0),
        diff: (0, codiconsUtil_1.register)('diff', 0xeae1),
        diffSidebyside: (0, codiconsUtil_1.register)('diff-sidebyside', 0xeae1),
        discard: (0, codiconsUtil_1.register)('discard', 0xeae2),
        editorLayout: (0, codiconsUtil_1.register)('editor-layout', 0xeae3),
        emptyWindow: (0, codiconsUtil_1.register)('empty-window', 0xeae4),
        exclude: (0, codiconsUtil_1.register)('exclude', 0xeae5),
        extensions: (0, codiconsUtil_1.register)('extensions', 0xeae6),
        eyeClosed: (0, codiconsUtil_1.register)('eye-closed', 0xeae7),
        fileBinary: (0, codiconsUtil_1.register)('file-binary', 0xeae8),
        fileCode: (0, codiconsUtil_1.register)('file-code', 0xeae9),
        fileMedia: (0, codiconsUtil_1.register)('file-media', 0xeaea),
        filePdf: (0, codiconsUtil_1.register)('file-pdf', 0xeaeb),
        fileSubmodule: (0, codiconsUtil_1.register)('file-submodule', 0xeaec),
        fileSymlinkDirectory: (0, codiconsUtil_1.register)('file-symlink-directory', 0xeaed),
        fileSymlinkFile: (0, codiconsUtil_1.register)('file-symlink-file', 0xeaee),
        fileZip: (0, codiconsUtil_1.register)('file-zip', 0xeaef),
        files: (0, codiconsUtil_1.register)('files', 0xeaf0),
        filter: (0, codiconsUtil_1.register)('filter', 0xeaf1),
        flame: (0, codiconsUtil_1.register)('flame', 0xeaf2),
        foldDown: (0, codiconsUtil_1.register)('fold-down', 0xeaf3),
        foldUp: (0, codiconsUtil_1.register)('fold-up', 0xeaf4),
        fold: (0, codiconsUtil_1.register)('fold', 0xeaf5),
        folderActive: (0, codiconsUtil_1.register)('folder-active', 0xeaf6),
        folderOpened: (0, codiconsUtil_1.register)('folder-opened', 0xeaf7),
        gear: (0, codiconsUtil_1.register)('gear', 0xeaf8),
        gift: (0, codiconsUtil_1.register)('gift', 0xeaf9),
        gistSecret: (0, codiconsUtil_1.register)('gist-secret', 0xeafa),
        gist: (0, codiconsUtil_1.register)('gist', 0xeafb),
        gitCommit: (0, codiconsUtil_1.register)('git-commit', 0xeafc),
        gitCompare: (0, codiconsUtil_1.register)('git-compare', 0xeafd),
        compareChanges: (0, codiconsUtil_1.register)('compare-changes', 0xeafd),
        gitMerge: (0, codiconsUtil_1.register)('git-merge', 0xeafe),
        githubAction: (0, codiconsUtil_1.register)('github-action', 0xeaff),
        githubAlt: (0, codiconsUtil_1.register)('github-alt', 0xeb00),
        globe: (0, codiconsUtil_1.register)('globe', 0xeb01),
        grabber: (0, codiconsUtil_1.register)('grabber', 0xeb02),
        graph: (0, codiconsUtil_1.register)('graph', 0xeb03),
        gripper: (0, codiconsUtil_1.register)('gripper', 0xeb04),
        heart: (0, codiconsUtil_1.register)('heart', 0xeb05),
        home: (0, codiconsUtil_1.register)('home', 0xeb06),
        horizontalRule: (0, codiconsUtil_1.register)('horizontal-rule', 0xeb07),
        hubot: (0, codiconsUtil_1.register)('hubot', 0xeb08),
        inbox: (0, codiconsUtil_1.register)('inbox', 0xeb09),
        issueReopened: (0, codiconsUtil_1.register)('issue-reopened', 0xeb0b),
        issues: (0, codiconsUtil_1.register)('issues', 0xeb0c),
        italic: (0, codiconsUtil_1.register)('italic', 0xeb0d),
        jersey: (0, codiconsUtil_1.register)('jersey', 0xeb0e),
        json: (0, codiconsUtil_1.register)('json', 0xeb0f),
        kebabVertical: (0, codiconsUtil_1.register)('kebab-vertical', 0xeb10),
        key: (0, codiconsUtil_1.register)('key', 0xeb11),
        law: (0, codiconsUtil_1.register)('law', 0xeb12),
        lightbulbAutofix: (0, codiconsUtil_1.register)('lightbulb-autofix', 0xeb13),
        linkExternal: (0, codiconsUtil_1.register)('link-external', 0xeb14),
        link: (0, codiconsUtil_1.register)('link', 0xeb15),
        listOrdered: (0, codiconsUtil_1.register)('list-ordered', 0xeb16),
        listUnordered: (0, codiconsUtil_1.register)('list-unordered', 0xeb17),
        liveShare: (0, codiconsUtil_1.register)('live-share', 0xeb18),
        loading: (0, codiconsUtil_1.register)('loading', 0xeb19),
        location: (0, codiconsUtil_1.register)('location', 0xeb1a),
        mailRead: (0, codiconsUtil_1.register)('mail-read', 0xeb1b),
        mail: (0, codiconsUtil_1.register)('mail', 0xeb1c),
        markdown: (0, codiconsUtil_1.register)('markdown', 0xeb1d),
        megaphone: (0, codiconsUtil_1.register)('megaphone', 0xeb1e),
        mention: (0, codiconsUtil_1.register)('mention', 0xeb1f),
        milestone: (0, codiconsUtil_1.register)('milestone', 0xeb20),
        gitPullRequestMilestone: (0, codiconsUtil_1.register)('git-pull-request-milestone', 0xeb20),
        mortarBoard: (0, codiconsUtil_1.register)('mortar-board', 0xeb21),
        move: (0, codiconsUtil_1.register)('move', 0xeb22),
        multipleWindows: (0, codiconsUtil_1.register)('multiple-windows', 0xeb23),
        mute: (0, codiconsUtil_1.register)('mute', 0xeb24),
        noNewline: (0, codiconsUtil_1.register)('no-newline', 0xeb25),
        note: (0, codiconsUtil_1.register)('note', 0xeb26),
        octoface: (0, codiconsUtil_1.register)('octoface', 0xeb27),
        openPreview: (0, codiconsUtil_1.register)('open-preview', 0xeb28),
        package: (0, codiconsUtil_1.register)('package', 0xeb29),
        paintcan: (0, codiconsUtil_1.register)('paintcan', 0xeb2a),
        pin: (0, codiconsUtil_1.register)('pin', 0xeb2b),
        play: (0, codiconsUtil_1.register)('play', 0xeb2c),
        run: (0, codiconsUtil_1.register)('run', 0xeb2c),
        plug: (0, codiconsUtil_1.register)('plug', 0xeb2d),
        preserveCase: (0, codiconsUtil_1.register)('preserve-case', 0xeb2e),
        preview: (0, codiconsUtil_1.register)('preview', 0xeb2f),
        project: (0, codiconsUtil_1.register)('project', 0xeb30),
        pulse: (0, codiconsUtil_1.register)('pulse', 0xeb31),
        question: (0, codiconsUtil_1.register)('question', 0xeb32),
        quote: (0, codiconsUtil_1.register)('quote', 0xeb33),
        radioTower: (0, codiconsUtil_1.register)('radio-tower', 0xeb34),
        reactions: (0, codiconsUtil_1.register)('reactions', 0xeb35),
        references: (0, codiconsUtil_1.register)('references', 0xeb36),
        refresh: (0, codiconsUtil_1.register)('refresh', 0xeb37),
        regex: (0, codiconsUtil_1.register)('regex', 0xeb38),
        remoteExplorer: (0, codiconsUtil_1.register)('remote-explorer', 0xeb39),
        remote: (0, codiconsUtil_1.register)('remote', 0xeb3a),
        remove: (0, codiconsUtil_1.register)('remove', 0xeb3b),
        replaceAll: (0, codiconsUtil_1.register)('replace-all', 0xeb3c),
        replace: (0, codiconsUtil_1.register)('replace', 0xeb3d),
        repoClone: (0, codiconsUtil_1.register)('repo-clone', 0xeb3e),
        repoForcePush: (0, codiconsUtil_1.register)('repo-force-push', 0xeb3f),
        repoPull: (0, codiconsUtil_1.register)('repo-pull', 0xeb40),
        repoPush: (0, codiconsUtil_1.register)('repo-push', 0xeb41),
        report: (0, codiconsUtil_1.register)('report', 0xeb42),
        requestChanges: (0, codiconsUtil_1.register)('request-changes', 0xeb43),
        rocket: (0, codiconsUtil_1.register)('rocket', 0xeb44),
        rootFolderOpened: (0, codiconsUtil_1.register)('root-folder-opened', 0xeb45),
        rootFolder: (0, codiconsUtil_1.register)('root-folder', 0xeb46),
        rss: (0, codiconsUtil_1.register)('rss', 0xeb47),
        ruby: (0, codiconsUtil_1.register)('ruby', 0xeb48),
        saveAll: (0, codiconsUtil_1.register)('save-all', 0xeb49),
        saveAs: (0, codiconsUtil_1.register)('save-as', 0xeb4a),
        save: (0, codiconsUtil_1.register)('save', 0xeb4b),
        screenFull: (0, codiconsUtil_1.register)('screen-full', 0xeb4c),
        screenNormal: (0, codiconsUtil_1.register)('screen-normal', 0xeb4d),
        searchStop: (0, codiconsUtil_1.register)('search-stop', 0xeb4e),
        server: (0, codiconsUtil_1.register)('server', 0xeb50),
        settingsGear: (0, codiconsUtil_1.register)('settings-gear', 0xeb51),
        settings: (0, codiconsUtil_1.register)('settings', 0xeb52),
        shield: (0, codiconsUtil_1.register)('shield', 0xeb53),
        smiley: (0, codiconsUtil_1.register)('smiley', 0xeb54),
        sortPrecedence: (0, codiconsUtil_1.register)('sort-precedence', 0xeb55),
        splitHorizontal: (0, codiconsUtil_1.register)('split-horizontal', 0xeb56),
        splitVertical: (0, codiconsUtil_1.register)('split-vertical', 0xeb57),
        squirrel: (0, codiconsUtil_1.register)('squirrel', 0xeb58),
        starFull: (0, codiconsUtil_1.register)('star-full', 0xeb59),
        starHalf: (0, codiconsUtil_1.register)('star-half', 0xeb5a),
        symbolClass: (0, codiconsUtil_1.register)('symbol-class', 0xeb5b),
        symbolColor: (0, codiconsUtil_1.register)('symbol-color', 0xeb5c),
        symbolConstant: (0, codiconsUtil_1.register)('symbol-constant', 0xeb5d),
        symbolEnumMember: (0, codiconsUtil_1.register)('symbol-enum-member', 0xeb5e),
        symbolField: (0, codiconsUtil_1.register)('symbol-field', 0xeb5f),
        symbolFile: (0, codiconsUtil_1.register)('symbol-file', 0xeb60),
        symbolInterface: (0, codiconsUtil_1.register)('symbol-interface', 0xeb61),
        symbolKeyword: (0, codiconsUtil_1.register)('symbol-keyword', 0xeb62),
        symbolMisc: (0, codiconsUtil_1.register)('symbol-misc', 0xeb63),
        symbolOperator: (0, codiconsUtil_1.register)('symbol-operator', 0xeb64),
        symbolProperty: (0, codiconsUtil_1.register)('symbol-property', 0xeb65),
        wrench: (0, codiconsUtil_1.register)('wrench', 0xeb65),
        wrenchSubaction: (0, codiconsUtil_1.register)('wrench-subaction', 0xeb65),
        symbolSnippet: (0, codiconsUtil_1.register)('symbol-snippet', 0xeb66),
        tasklist: (0, codiconsUtil_1.register)('tasklist', 0xeb67),
        telescope: (0, codiconsUtil_1.register)('telescope', 0xeb68),
        textSize: (0, codiconsUtil_1.register)('text-size', 0xeb69),
        threeBars: (0, codiconsUtil_1.register)('three-bars', 0xeb6a),
        thumbsdown: (0, codiconsUtil_1.register)('thumbsdown', 0xeb6b),
        thumbsup: (0, codiconsUtil_1.register)('thumbsup', 0xeb6c),
        tools: (0, codiconsUtil_1.register)('tools', 0xeb6d),
        triangleDown: (0, codiconsUtil_1.register)('triangle-down', 0xeb6e),
        triangleLeft: (0, codiconsUtil_1.register)('triangle-left', 0xeb6f),
        triangleRight: (0, codiconsUtil_1.register)('triangle-right', 0xeb70),
        triangleUp: (0, codiconsUtil_1.register)('triangle-up', 0xeb71),
        twitter: (0, codiconsUtil_1.register)('twitter', 0xeb72),
        unfold: (0, codiconsUtil_1.register)('unfold', 0xeb73),
        unlock: (0, codiconsUtil_1.register)('unlock', 0xeb74),
        unmute: (0, codiconsUtil_1.register)('unmute', 0xeb75),
        unverified: (0, codiconsUtil_1.register)('unverified', 0xeb76),
        verified: (0, codiconsUtil_1.register)('verified', 0xeb77),
        versions: (0, codiconsUtil_1.register)('versions', 0xeb78),
        vmActive: (0, codiconsUtil_1.register)('vm-active', 0xeb79),
        vmOutline: (0, codiconsUtil_1.register)('vm-outline', 0xeb7a),
        vmRunning: (0, codiconsUtil_1.register)('vm-running', 0xeb7b),
        watch: (0, codiconsUtil_1.register)('watch', 0xeb7c),
        whitespace: (0, codiconsUtil_1.register)('whitespace', 0xeb7d),
        wholeWord: (0, codiconsUtil_1.register)('whole-word', 0xeb7e),
        window: (0, codiconsUtil_1.register)('window', 0xeb7f),
        wordWrap: (0, codiconsUtil_1.register)('word-wrap', 0xeb80),
        zoomIn: (0, codiconsUtil_1.register)('zoom-in', 0xeb81),
        zoomOut: (0, codiconsUtil_1.register)('zoom-out', 0xeb82),
        listFilter: (0, codiconsUtil_1.register)('list-filter', 0xeb83),
        listFlat: (0, codiconsUtil_1.register)('list-flat', 0xeb84),
        listSelection: (0, codiconsUtil_1.register)('list-selection', 0xeb85),
        selection: (0, codiconsUtil_1.register)('selection', 0xeb85),
        listTree: (0, codiconsUtil_1.register)('list-tree', 0xeb86),
        debugBreakpointFunctionUnverified: (0, codiconsUtil_1.register)('debug-breakpoint-function-unverified', 0xeb87),
        debugBreakpointFunction: (0, codiconsUtil_1.register)('debug-breakpoint-function', 0xeb88),
        debugBreakpointFunctionDisabled: (0, codiconsUtil_1.register)('debug-breakpoint-function-disabled', 0xeb88),
        debugStackframeActive: (0, codiconsUtil_1.register)('debug-stackframe-active', 0xeb89),
        circleSmallFilled: (0, codiconsUtil_1.register)('circle-small-filled', 0xeb8a),
        debugStackframeDot: (0, codiconsUtil_1.register)('debug-stackframe-dot', 0xeb8a),
        terminalDecorationMark: (0, codiconsUtil_1.register)('terminal-decoration-mark', 0xeb8a),
        debugStackframe: (0, codiconsUtil_1.register)('debug-stackframe', 0xeb8b),
        debugStackframeFocused: (0, codiconsUtil_1.register)('debug-stackframe-focused', 0xeb8b),
        debugBreakpointUnsupported: (0, codiconsUtil_1.register)('debug-breakpoint-unsupported', 0xeb8c),
        symbolString: (0, codiconsUtil_1.register)('symbol-string', 0xeb8d),
        debugReverseContinue: (0, codiconsUtil_1.register)('debug-reverse-continue', 0xeb8e),
        debugStepBack: (0, codiconsUtil_1.register)('debug-step-back', 0xeb8f),
        debugRestartFrame: (0, codiconsUtil_1.register)('debug-restart-frame', 0xeb90),
        debugAlt: (0, codiconsUtil_1.register)('debug-alt', 0xeb91),
        callIncoming: (0, codiconsUtil_1.register)('call-incoming', 0xeb92),
        callOutgoing: (0, codiconsUtil_1.register)('call-outgoing', 0xeb93),
        menu: (0, codiconsUtil_1.register)('menu', 0xeb94),
        expandAll: (0, codiconsUtil_1.register)('expand-all', 0xeb95),
        feedback: (0, codiconsUtil_1.register)('feedback', 0xeb96),
        gitPullRequestReviewer: (0, codiconsUtil_1.register)('git-pull-request-reviewer', 0xeb96),
        groupByRefType: (0, codiconsUtil_1.register)('group-by-ref-type', 0xeb97),
        ungroupByRefType: (0, codiconsUtil_1.register)('ungroup-by-ref-type', 0xeb98),
        account: (0, codiconsUtil_1.register)('account', 0xeb99),
        gitPullRequestAssignee: (0, codiconsUtil_1.register)('git-pull-request-assignee', 0xeb99),
        bellDot: (0, codiconsUtil_1.register)('bell-dot', 0xeb9a),
        debugConsole: (0, codiconsUtil_1.register)('debug-console', 0xeb9b),
        library: (0, codiconsUtil_1.register)('library', 0xeb9c),
        output: (0, codiconsUtil_1.register)('output', 0xeb9d),
        runAll: (0, codiconsUtil_1.register)('run-all', 0xeb9e),
        syncIgnored: (0, codiconsUtil_1.register)('sync-ignored', 0xeb9f),
        pinned: (0, codiconsUtil_1.register)('pinned', 0xeba0),
        githubInverted: (0, codiconsUtil_1.register)('github-inverted', 0xeba1),
        serverProcess: (0, codiconsUtil_1.register)('server-process', 0xeba2),
        serverEnvironment: (0, codiconsUtil_1.register)('server-environment', 0xeba3),
        pass: (0, codiconsUtil_1.register)('pass', 0xeba4),
        issueClosed: (0, codiconsUtil_1.register)('issue-closed', 0xeba4),
        stopCircle: (0, codiconsUtil_1.register)('stop-circle', 0xeba5),
        playCircle: (0, codiconsUtil_1.register)('play-circle', 0xeba6),
        record: (0, codiconsUtil_1.register)('record', 0xeba7),
        debugAltSmall: (0, codiconsUtil_1.register)('debug-alt-small', 0xeba8),
        vmConnect: (0, codiconsUtil_1.register)('vm-connect', 0xeba9),
        cloud: (0, codiconsUtil_1.register)('cloud', 0xebaa),
        merge: (0, codiconsUtil_1.register)('merge', 0xebab),
        export: (0, codiconsUtil_1.register)('export', 0xebac),
        graphLeft: (0, codiconsUtil_1.register)('graph-left', 0xebad),
        magnet: (0, codiconsUtil_1.register)('magnet', 0xebae),
        notebook: (0, codiconsUtil_1.register)('notebook', 0xebaf),
        redo: (0, codiconsUtil_1.register)('redo', 0xebb0),
        checkAll: (0, codiconsUtil_1.register)('check-all', 0xebb1),
        pinnedDirty: (0, codiconsUtil_1.register)('pinned-dirty', 0xebb2),
        passFilled: (0, codiconsUtil_1.register)('pass-filled', 0xebb3),
        circleLargeFilled: (0, codiconsUtil_1.register)('circle-large-filled', 0xebb4),
        circleLarge: (0, codiconsUtil_1.register)('circle-large', 0xebb5),
        circleLargeOutline: (0, codiconsUtil_1.register)('circle-large-outline', 0xebb5),
        combine: (0, codiconsUtil_1.register)('combine', 0xebb6),
        gather: (0, codiconsUtil_1.register)('gather', 0xebb6),
        table: (0, codiconsUtil_1.register)('table', 0xebb7),
        variableGroup: (0, codiconsUtil_1.register)('variable-group', 0xebb8),
        typeHierarchy: (0, codiconsUtil_1.register)('type-hierarchy', 0xebb9),
        typeHierarchySub: (0, codiconsUtil_1.register)('type-hierarchy-sub', 0xebba),
        typeHierarchySuper: (0, codiconsUtil_1.register)('type-hierarchy-super', 0xebbb),
        gitPullRequestCreate: (0, codiconsUtil_1.register)('git-pull-request-create', 0xebbc),
        runAbove: (0, codiconsUtil_1.register)('run-above', 0xebbd),
        runBelow: (0, codiconsUtil_1.register)('run-below', 0xebbe),
        notebookTemplate: (0, codiconsUtil_1.register)('notebook-template', 0xebbf),
        debugRerun: (0, codiconsUtil_1.register)('debug-rerun', 0xebc0),
        workspaceTrusted: (0, codiconsUtil_1.register)('workspace-trusted', 0xebc1),
        workspaceUntrusted: (0, codiconsUtil_1.register)('workspace-untrusted', 0xebc2),
        workspaceUnknown: (0, codiconsUtil_1.register)('workspace-unknown', 0xebc3),
        terminalCmd: (0, codiconsUtil_1.register)('terminal-cmd', 0xebc4),
        terminalDebian: (0, codiconsUtil_1.register)('terminal-debian', 0xebc5),
        terminalLinux: (0, codiconsUtil_1.register)('terminal-linux', 0xebc6),
        terminalPowershell: (0, codiconsUtil_1.register)('terminal-powershell', 0xebc7),
        terminalTmux: (0, codiconsUtil_1.register)('terminal-tmux', 0xebc8),
        terminalUbuntu: (0, codiconsUtil_1.register)('terminal-ubuntu', 0xebc9),
        terminalBash: (0, codiconsUtil_1.register)('terminal-bash', 0xebca),
        arrowSwap: (0, codiconsUtil_1.register)('arrow-swap', 0xebcb),
        copy: (0, codiconsUtil_1.register)('copy', 0xebcc),
        personAdd: (0, codiconsUtil_1.register)('person-add', 0xebcd),
        filterFilled: (0, codiconsUtil_1.register)('filter-filled', 0xebce),
        wand: (0, codiconsUtil_1.register)('wand', 0xebcf),
        debugLineByLine: (0, codiconsUtil_1.register)('debug-line-by-line', 0xebd0),
        inspect: (0, codiconsUtil_1.register)('inspect', 0xebd1),
        layers: (0, codiconsUtil_1.register)('layers', 0xebd2),
        layersDot: (0, codiconsUtil_1.register)('layers-dot', 0xebd3),
        layersActive: (0, codiconsUtil_1.register)('layers-active', 0xebd4),
        compass: (0, codiconsUtil_1.register)('compass', 0xebd5),
        compassDot: (0, codiconsUtil_1.register)('compass-dot', 0xebd6),
        compassActive: (0, codiconsUtil_1.register)('compass-active', 0xebd7),
        azure: (0, codiconsUtil_1.register)('azure', 0xebd8),
        issueDraft: (0, codiconsUtil_1.register)('issue-draft', 0xebd9),
        gitPullRequestClosed: (0, codiconsUtil_1.register)('git-pull-request-closed', 0xebda),
        gitPullRequestDraft: (0, codiconsUtil_1.register)('git-pull-request-draft', 0xebdb),
        debugAll: (0, codiconsUtil_1.register)('debug-all', 0xebdc),
        debugCoverage: (0, codiconsUtil_1.register)('debug-coverage', 0xebdd),
        runErrors: (0, codiconsUtil_1.register)('run-errors', 0xebde),
        folderLibrary: (0, codiconsUtil_1.register)('folder-library', 0xebdf),
        debugContinueSmall: (0, codiconsUtil_1.register)('debug-continue-small', 0xebe0),
        beakerStop: (0, codiconsUtil_1.register)('beaker-stop', 0xebe1),
        graphLine: (0, codiconsUtil_1.register)('graph-line', 0xebe2),
        graphScatter: (0, codiconsUtil_1.register)('graph-scatter', 0xebe3),
        pieChart: (0, codiconsUtil_1.register)('pie-chart', 0xebe4),
        bracket: (0, codiconsUtil_1.register)('bracket', 0xeb0f),
        bracketDot: (0, codiconsUtil_1.register)('bracket-dot', 0xebe5),
        bracketError: (0, codiconsUtil_1.register)('bracket-error', 0xebe6),
        lockSmall: (0, codiconsUtil_1.register)('lock-small', 0xebe7),
        azureDevops: (0, codiconsUtil_1.register)('azure-devops', 0xebe8),
        verifiedFilled: (0, codiconsUtil_1.register)('verified-filled', 0xebe9),
        newline: (0, codiconsUtil_1.register)('newline', 0xebea),
        layout: (0, codiconsUtil_1.register)('layout', 0xebeb),
        layoutActivitybarLeft: (0, codiconsUtil_1.register)('layout-activitybar-left', 0xebec),
        layoutActivitybarRight: (0, codiconsUtil_1.register)('layout-activitybar-right', 0xebed),
        layoutPanelLeft: (0, codiconsUtil_1.register)('layout-panel-left', 0xebee),
        layoutPanelCenter: (0, codiconsUtil_1.register)('layout-panel-center', 0xebef),
        layoutPanelJustify: (0, codiconsUtil_1.register)('layout-panel-justify', 0xebf0),
        layoutPanelRight: (0, codiconsUtil_1.register)('layout-panel-right', 0xebf1),
        layoutPanel: (0, codiconsUtil_1.register)('layout-panel', 0xebf2),
        layoutSidebarLeft: (0, codiconsUtil_1.register)('layout-sidebar-left', 0xebf3),
        layoutSidebarRight: (0, codiconsUtil_1.register)('layout-sidebar-right', 0xebf4),
        layoutStatusbar: (0, codiconsUtil_1.register)('layout-statusbar', 0xebf5),
        layoutMenubar: (0, codiconsUtil_1.register)('layout-menubar', 0xebf6),
        layoutCentered: (0, codiconsUtil_1.register)('layout-centered', 0xebf7),
        target: (0, codiconsUtil_1.register)('target', 0xebf8),
        indent: (0, codiconsUtil_1.register)('indent', 0xebf9),
        recordSmall: (0, codiconsUtil_1.register)('record-small', 0xebfa),
        errorSmall: (0, codiconsUtil_1.register)('error-small', 0xebfb),
        terminalDecorationError: (0, codiconsUtil_1.register)('terminal-decoration-error', 0xebfb),
        arrowCircleDown: (0, codiconsUtil_1.register)('arrow-circle-down', 0xebfc),
        arrowCircleLeft: (0, codiconsUtil_1.register)('arrow-circle-left', 0xebfd),
        arrowCircleRight: (0, codiconsUtil_1.register)('arrow-circle-right', 0xebfe),
        arrowCircleUp: (0, codiconsUtil_1.register)('arrow-circle-up', 0xebff),
        layoutSidebarRightOff: (0, codiconsUtil_1.register)('layout-sidebar-right-off', 0xec00),
        layoutPanelOff: (0, codiconsUtil_1.register)('layout-panel-off', 0xec01),
        layoutSidebarLeftOff: (0, codiconsUtil_1.register)('layout-sidebar-left-off', 0xec02),
        blank: (0, codiconsUtil_1.register)('blank', 0xec03),
        heartFilled: (0, codiconsUtil_1.register)('heart-filled', 0xec04),
        map: (0, codiconsUtil_1.register)('map', 0xec05),
        mapHorizontal: (0, codiconsUtil_1.register)('map-horizontal', 0xec05),
        foldHorizontal: (0, codiconsUtil_1.register)('fold-horizontal', 0xec05),
        mapFilled: (0, codiconsUtil_1.register)('map-filled', 0xec06),
        mapHorizontalFilled: (0, codiconsUtil_1.register)('map-horizontal-filled', 0xec06),
        foldHorizontalFilled: (0, codiconsUtil_1.register)('fold-horizontal-filled', 0xec06),
        circleSmall: (0, codiconsUtil_1.register)('circle-small', 0xec07),
        bellSlash: (0, codiconsUtil_1.register)('bell-slash', 0xec08),
        bellSlashDot: (0, codiconsUtil_1.register)('bell-slash-dot', 0xec09),
        commentUnresolved: (0, codiconsUtil_1.register)('comment-unresolved', 0xec0a),
        gitPullRequestGoToChanges: (0, codiconsUtil_1.register)('git-pull-request-go-to-changes', 0xec0b),
        gitPullRequestNewChanges: (0, codiconsUtil_1.register)('git-pull-request-new-changes', 0xec0c),
        searchFuzzy: (0, codiconsUtil_1.register)('search-fuzzy', 0xec0d),
        commentDraft: (0, codiconsUtil_1.register)('comment-draft', 0xec0e),
        send: (0, codiconsUtil_1.register)('send', 0xec0f),
        sparkle: (0, codiconsUtil_1.register)('sparkle', 0xec10),
        insert: (0, codiconsUtil_1.register)('insert', 0xec11),
        mic: (0, codiconsUtil_1.register)('mic', 0xec12),
        thumbsdownFilled: (0, codiconsUtil_1.register)('thumbsdown-filled', 0xec13),
        thumbsupFilled: (0, codiconsUtil_1.register)('thumbsup-filled', 0xec14),
        coffee: (0, codiconsUtil_1.register)('coffee', 0xec15),
        snake: (0, codiconsUtil_1.register)('snake', 0xec16),
        game: (0, codiconsUtil_1.register)('game', 0xec17),
        vr: (0, codiconsUtil_1.register)('vr', 0xec18),
        chip: (0, codiconsUtil_1.register)('chip', 0xec19),
        piano: (0, codiconsUtil_1.register)('piano', 0xec1a),
        music: (0, codiconsUtil_1.register)('music', 0xec1b),
        micFilled: (0, codiconsUtil_1.register)('mic-filled', 0xec1c),
        repoFetch: (0, codiconsUtil_1.register)('repo-fetch', 0xec1d),
        copilot: (0, codiconsUtil_1.register)('copilot', 0xec1e),
        lightbulbSparkle: (0, codiconsUtil_1.register)('lightbulb-sparkle', 0xec1f),
        robot: (0, codiconsUtil_1.register)('robot', 0xec20),
        sparkleFilled: (0, codiconsUtil_1.register)('sparkle-filled', 0xec21),
        diffSingle: (0, codiconsUtil_1.register)('diff-single', 0xec22),
        diffMultiple: (0, codiconsUtil_1.register)('diff-multiple', 0xec23),
        surroundWith: (0, codiconsUtil_1.register)('surround-with', 0xec24),
        share: (0, codiconsUtil_1.register)('share', 0xec25),
        gitStash: (0, codiconsUtil_1.register)('git-stash', 0xec26),
        gitStashApply: (0, codiconsUtil_1.register)('git-stash-apply', 0xec27),
        gitStashPop: (0, codiconsUtil_1.register)('git-stash-pop', 0xec28),
        vscode: (0, codiconsUtil_1.register)('vscode', 0xec29),
        vscodeInsiders: (0, codiconsUtil_1.register)('vscode-insiders', 0xec2a),
        codeOss: (0, codiconsUtil_1.register)('code-oss', 0xec2b),
        runCoverage: (0, codiconsUtil_1.register)('run-coverage', 0xec2c),
        runAllCoverage: (0, codiconsUtil_1.register)('run-all-coverage', 0xec2d),
        coverage: (0, codiconsUtil_1.register)('coverage', 0xec2e),
        githubProject: (0, codiconsUtil_1.register)('github-project', 0xec2f),
        mapVertical: (0, codiconsUtil_1.register)('map-vertical', 0xec30),
        foldVertical: (0, codiconsUtil_1.register)('fold-vertical', 0xec30),
        mapVerticalFilled: (0, codiconsUtil_1.register)('map-vertical-filled', 0xec31),
        foldVerticalFilled: (0, codiconsUtil_1.register)('fold-vertical-filled', 0xec31),
        goToSearch: (0, codiconsUtil_1.register)('go-to-search', 0xec32),
        percentage: (0, codiconsUtil_1.register)('percentage', 0xec33),
        sortPercentage: (0, codiconsUtil_1.register)('sort-percentage', 0xec33),
        attach: (0, codiconsUtil_1.register)('attach', 0xec34),
    };
});

define(__m[26/*vs/base/common/codicons*/], __M([1/*require*/,0/*exports*/,191/*vs/base/common/codiconsUtil*/,457/*vs/base/common/codiconsLibrary*/]), function (require, exports, codiconsUtil_1, codiconsLibrary_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Codicon = exports.codiconsDerived = void 0;
    /**
     * Derived icons, that could become separate icons.
     * These mappings should be moved into the mapping file in the vscode-codicons repo at some point.
     */
    exports.codiconsDerived = {
        dialogError: (0, codiconsUtil_1.register)('dialog-error', 'error'),
        dialogWarning: (0, codiconsUtil_1.register)('dialog-warning', 'warning'),
        dialogInfo: (0, codiconsUtil_1.register)('dialog-info', 'info'),
        dialogClose: (0, codiconsUtil_1.register)('dialog-close', 'close'),
        treeItemExpanded: (0, codiconsUtil_1.register)('tree-item-expanded', 'chevron-down'), // collapsed is done with rotation
        treeFilterOnTypeOn: (0, codiconsUtil_1.register)('tree-filter-on-type-on', 'list-filter'),
        treeFilterOnTypeOff: (0, codiconsUtil_1.register)('tree-filter-on-type-off', 'list-selection'),
        treeFilterClear: (0, codiconsUtil_1.register)('tree-filter-clear', 'close'),
        treeItemLoading: (0, codiconsUtil_1.register)('tree-item-loading', 'loading'),
        menuSelection: (0, codiconsUtil_1.register)('menu-selection', 'check'),
        menuSubmenu: (0, codiconsUtil_1.register)('menu-submenu', 'chevron-right'),
        menuBarMore: (0, codiconsUtil_1.register)('menubar-more', 'more'),
        scrollbarButtonLeft: (0, codiconsUtil_1.register)('scrollbar-button-left', 'triangle-left'),
        scrollbarButtonRight: (0, codiconsUtil_1.register)('scrollbar-button-right', 'triangle-right'),
        scrollbarButtonUp: (0, codiconsUtil_1.register)('scrollbar-button-up', 'triangle-up'),
        scrollbarButtonDown: (0, codiconsUtil_1.register)('scrollbar-button-down', 'triangle-down'),
        toolBarMore: (0, codiconsUtil_1.register)('toolbar-more', 'more'),
        quickInputBack: (0, codiconsUtil_1.register)('quick-input-back', 'arrow-left'),
        dropDownButton: (0, codiconsUtil_1.register)('drop-down-button', 0xeab4),
        symbolCustomColor: (0, codiconsUtil_1.register)('symbol-customcolor', 0xeb5c),
        exportIcon: (0, codiconsUtil_1.register)('export', 0xebac),
        workspaceUnspecified: (0, codiconsUtil_1.register)('workspace-unspecified', 0xebc3),
        newLine: (0, codiconsUtil_1.register)('newline', 0xebea),
        thumbsDownFilled: (0, codiconsUtil_1.register)('thumbsdown-filled', 0xec13),
        thumbsUpFilled: (0, codiconsUtil_1.register)('thumbsup-filled', 0xec14),
        gitFetch: (0, codiconsUtil_1.register)('git-fetch', 0xec1d),
        lightbulbSparkleAutofix: (0, codiconsUtil_1.register)('lightbulb-sparkle-autofix', 0xec1f),
        debugBreakpointPending: (0, codiconsUtil_1.register)('debug-breakpoint-pending', 0xebd9),
    };
    /**
     * The Codicon library is a set of default icons that are built-in in VS Code.
     *
     * In the product (outside of base) Codicons should only be used as defaults. In order to have all icons in VS Code
     * themeable, component should define new, UI component specific icons using `iconRegistry.registerIcon`.
     * In that call a Codicon can be named as default.
     */
    exports.Codicon = {
        ...codiconsLibrary_1.codiconsLibrary,
        ...exports.codiconsDerived
    };
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[60/*vs/base/common/objects*/], __M([1/*require*/,0/*exports*/,19/*vs/base/common/types*/]), function (require, exports, types_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.deepClone = deepClone;
    exports.deepFreeze = deepFreeze;
    exports.cloneAndChange = cloneAndChange;
    exports.mixin = mixin;
    exports.equals = equals;
    exports.getAllPropertyNames = getAllPropertyNames;
    exports.getAllMethodNames = getAllMethodNames;
    exports.createProxyObject = createProxyObject;
    function deepClone(obj) {
        if (!obj || typeof obj !== 'object') {
            return obj;
        }
        if (obj instanceof RegExp) {
            return obj;
        }
        const result = Array.isArray(obj) ? [] : {};
        Object.entries(obj).forEach(([key, value]) => {
            result[key] = value && typeof value === 'object' ? deepClone(value) : value;
        });
        return result;
    }
    function deepFreeze(obj) {
        if (!obj || typeof obj !== 'object') {
            return obj;
        }
        const stack = [obj];
        while (stack.length > 0) {
            const obj = stack.shift();
            Object.freeze(obj);
            for (const key in obj) {
                if (_hasOwnProperty.call(obj, key)) {
                    const prop = obj[key];
                    if (typeof prop === 'object' && !Object.isFrozen(prop) && !(0, types_1.isTypedArray)(prop)) {
                        stack.push(prop);
                    }
                }
            }
        }
        return obj;
    }
    const _hasOwnProperty = Object.prototype.hasOwnProperty;
    function cloneAndChange(obj, changer) {
        return _cloneAndChange(obj, changer, new Set());
    }
    function _cloneAndChange(obj, changer, seen) {
        if ((0, types_1.isUndefinedOrNull)(obj)) {
            return obj;
        }
        const changed = changer(obj);
        if (typeof changed !== 'undefined') {
            return changed;
        }
        if (Array.isArray(obj)) {
            const r1 = [];
            for (const e of obj) {
                r1.push(_cloneAndChange(e, changer, seen));
            }
            return r1;
        }
        if ((0, types_1.isObject)(obj)) {
            if (seen.has(obj)) {
                throw new Error('Cannot clone recursive data-structure');
            }
            seen.add(obj);
            const r2 = {};
            for (const i2 in obj) {
                if (_hasOwnProperty.call(obj, i2)) {
                    r2[i2] = _cloneAndChange(obj[i2], changer, seen);
                }
            }
            seen.delete(obj);
            return r2;
        }
        return obj;
    }
    /**
     * Copies all properties of source into destination. The optional parameter "overwrite" allows to control
     * if existing properties on the destination should be overwritten or not. Defaults to true (overwrite).
     */
    function mixin(destination, source, overwrite = true) {
        if (!(0, types_1.isObject)(destination)) {
            return source;
        }
        if ((0, types_1.isObject)(source)) {
            Object.keys(source).forEach(key => {
                if (key in destination) {
                    if (overwrite) {
                        if ((0, types_1.isObject)(destination[key]) && (0, types_1.isObject)(source[key])) {
                            mixin(destination[key], source[key], overwrite);
                        }
                        else {
                            destination[key] = source[key];
                        }
                    }
                }
                else {
                    destination[key] = source[key];
                }
            });
        }
        return destination;
    }
    function equals(one, other) {
        if (one === other) {
            return true;
        }
        if (one === null || one === undefined || other === null || other === undefined) {
            return false;
        }
        if (typeof one !== typeof other) {
            return false;
        }
        if (typeof one !== 'object') {
            return false;
        }
        if ((Array.isArray(one)) !== (Array.isArray(other))) {
            return false;
        }
        let i;
        let key;
        if (Array.isArray(one)) {
            if (one.length !== other.length) {
                return false;
            }
            for (i = 0; i < one.length; i++) {
                if (!equals(one[i], other[i])) {
                    return false;
                }
            }
        }
        else {
            const oneKeys = [];
            for (key in one) {
                oneKeys.push(key);
            }
            oneKeys.sort();
            const otherKeys = [];
            for (key in other) {
                otherKeys.push(key);
            }
            otherKeys.sort();
            if (!equals(oneKeys, otherKeys)) {
                return false;
            }
            for (i = 0; i < oneKeys.length; i++) {
                if (!equals(one[oneKeys[i]], other[oneKeys[i]])) {
                    return false;
                }
            }
        }
        return true;
    }
    function getAllPropertyNames(obj) {
        let res = [];
        while (Object.prototype !== obj) {
            res = res.concat(Object.getOwnPropertyNames(obj));
            obj = Object.getPrototypeOf(obj);
        }
        return res;
    }
    function getAllMethodNames(obj) {
        const methods = [];
        for (const prop of getAllPropertyNames(obj)) {
            if (typeof obj[prop] === 'function') {
                methods.push(prop);
            }
        }
        return methods;
    }
    function createProxyObject(methodNames, invoke) {
        const createProxyMethod = (method) => {
            return function () {
                const args = Array.prototype.slice.call(arguments, 0);
                return invoke(method, args);
            };
        };
        const result = {};
        for (const methodName of methodNames) {
            result[methodName] = createProxyMethod(methodName);
        }
        return result;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[30/*vs/base/common/themables*/], __M([1/*require*/,0/*exports*/,26/*vs/base/common/codicons*/]), function (require, exports, codicons_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ThemeIcon = exports.ThemeColor = void 0;
    var ThemeColor;
    (function (ThemeColor) {
        function isThemeColor(obj) {
            return obj && typeof obj === 'object' && typeof obj.id === 'string';
        }
        ThemeColor.isThemeColor = isThemeColor;
    })(ThemeColor || (exports.ThemeColor = ThemeColor = {}));
    var ThemeIcon;
    (function (ThemeIcon) {
        ThemeIcon.iconNameSegment = '[A-Za-z0-9]+';
        ThemeIcon.iconNameExpression = '[A-Za-z0-9-]+';
        ThemeIcon.iconModifierExpression = '~[A-Za-z]+';
        ThemeIcon.iconNameCharacter = '[A-Za-z0-9~-]';
        const ThemeIconIdRegex = new RegExp(`^(${ThemeIcon.iconNameExpression})(${ThemeIcon.iconModifierExpression})?$`);
        function asClassNameArray(icon) {
            const match = ThemeIconIdRegex.exec(icon.id);
            if (!match) {
                return asClassNameArray(codicons_1.Codicon.error);
            }
            const [, id, modifier] = match;
            const classNames = ['codicon', 'codicon-' + id];
            if (modifier) {
                classNames.push('codicon-modifier-' + modifier.substring(1));
            }
            return classNames;
        }
        ThemeIcon.asClassNameArray = asClassNameArray;
        function asClassName(icon) {
            return asClassNameArray(icon).join(' ');
        }
        ThemeIcon.asClassName = asClassName;
        function asCSSSelector(icon) {
            return '.' + asClassNameArray(icon).join('.');
        }
        ThemeIcon.asCSSSelector = asCSSSelector;
        function isThemeIcon(obj) {
            return obj && typeof obj === 'object' && typeof obj.id === 'string' && (typeof obj.color === 'undefined' || ThemeColor.isThemeColor(obj.color));
        }
        ThemeIcon.isThemeIcon = isThemeIcon;
        const _regexFromString = new RegExp(`^\\$\\((${ThemeIcon.iconNameExpression}(?:${ThemeIcon.iconModifierExpression})?)\\)$`);
        function fromString(str) {
            const match = _regexFromString.exec(str);
            if (!match) {
                return undefined;
            }
            const [, name] = match;
            return { id: name };
        }
        ThemeIcon.fromString = fromString;
        function fromId(id) {
            return { id };
        }
        ThemeIcon.fromId = fromId;
        function modify(icon, modifier) {
            let id = icon.id;
            const tildeIndex = id.lastIndexOf('~');
            if (tildeIndex !== -1) {
                id = id.substring(0, tildeIndex);
            }
            if (modifier) {
                id = `${id}~${modifier}`;
            }
            return { id };
        }
        ThemeIcon.modify = modify;
        function getModifier(icon) {
            const tildeIndex = icon.id.lastIndexOf('~');
            if (tildeIndex !== -1) {
                return icon.id.substring(tildeIndex + 1);
            }
            return undefined;
        }
        ThemeIcon.getModifier = getModifier;
        function isEqual(ti1, ti2) {
            return ti1.id === ti2.id && ti1.color?.id === ti2.color?.id;
        }
        ThemeIcon.isEqual = isEqual;
    })(ThemeIcon || (exports.ThemeIcon = ThemeIcon = {}));
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[142/*vs/base/common/iconLabels*/], __M([1/*require*/,0/*exports*/,82/*vs/base/common/filters*/,11/*vs/base/common/strings*/,30/*vs/base/common/themables*/]), function (require, exports, filters_1, strings_1, themables_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.escapeIcons = escapeIcons;
    exports.markdownEscapeEscapedIcons = markdownEscapeEscapedIcons;
    exports.stripIcons = stripIcons;
    exports.getCodiconAriaLabel = getCodiconAriaLabel;
    exports.parseLabelWithIcons = parseLabelWithIcons;
    exports.matchesFuzzyIconAware = matchesFuzzyIconAware;
    const iconStartMarker = '$(';
    const iconsRegex = new RegExp(`\\$\\(${themables_1.ThemeIcon.iconNameExpression}(?:${themables_1.ThemeIcon.iconModifierExpression})?\\)`, 'g'); // no capturing groups
    const escapeIconsRegex = new RegExp(`(\\\\)?${iconsRegex.source}`, 'g');
    function escapeIcons(text) {
        return text.replace(escapeIconsRegex, (match, escaped) => escaped ? match : `\\${match}`);
    }
    const markdownEscapedIconsRegex = new RegExp(`\\\\${iconsRegex.source}`, 'g');
    function markdownEscapeEscapedIcons(text) {
        // Need to add an extra \ for escaping in markdown
        return text.replace(markdownEscapedIconsRegex, match => `\\${match}`);
    }
    const stripIconsRegex = new RegExp(`(\\s)?(\\\\)?${iconsRegex.source}(\\s)?`, 'g');
    /**
     * Takes a label with icons (`$(iconId)xyz`)  and strips the icons out (`xyz`)
     */
    function stripIcons(text) {
        if (text.indexOf(iconStartMarker) === -1) {
            return text;
        }
        return text.replace(stripIconsRegex, (match, preWhitespace, escaped, postWhitespace) => escaped ? match : preWhitespace || postWhitespace || '');
    }
    /**
     * Takes a label with icons (`$(iconId)xyz`), removes the icon syntax adds whitespace so that screen readers can read the text better.
     */
    function getCodiconAriaLabel(text) {
        if (!text) {
            return '';
        }
        return text.replace(/\$\((.*?)\)/g, (_match, codiconName) => ` ${codiconName} `).trim();
    }
    const _parseIconsRegex = new RegExp(`\\$\\(${themables_1.ThemeIcon.iconNameCharacter}+\\)`, 'g');
    /**
     * Takes a label with icons (`abc $(iconId)xyz`) and returns the text (`abc xyz`) and the offsets of the icons (`[3]`)
     */
    function parseLabelWithIcons(input) {
        _parseIconsRegex.lastIndex = 0;
        let text = '';
        const iconOffsets = [];
        let iconsOffset = 0;
        while (true) {
            const pos = _parseIconsRegex.lastIndex;
            const match = _parseIconsRegex.exec(input);
            const chars = input.substring(pos, match?.index);
            if (chars.length > 0) {
                text += chars;
                for (let i = 0; i < chars.length; i++) {
                    iconOffsets.push(iconsOffset);
                }
            }
            if (!match) {
                break;
            }
            iconsOffset += match[0].length;
        }
        return { text, iconOffsets };
    }
    function matchesFuzzyIconAware(query, target, enableSeparateSubstringMatching = false) {
        const { text, iconOffsets } = target;
        // Return early if there are no icon markers in the word to match against
        if (!iconOffsets || iconOffsets.length === 0) {
            return (0, filters_1.matchesFuzzy)(query, text, enableSeparateSubstringMatching);
        }
        // Trim the word to match against because it could have leading
        // whitespace now if the word started with an icon
        const wordToMatchAgainstWithoutIconsTrimmed = (0, strings_1.ltrim)(text, ' ');
        const leadingWhitespaceOffset = text.length - wordToMatchAgainstWithoutIconsTrimmed.length;
        // match on value without icon
        const matches = (0, filters_1.matchesFuzzy)(query, wordToMatchAgainstWithoutIconsTrimmed, enableSeparateSubstringMatching);
        // Map matches back to offsets with icon and trimming
        if (matches) {
            for (const match of matches) {
                const iconOffset = iconOffsets[match.start + leadingWhitespaceOffset] /* icon offsets at index */ + leadingWhitespaceOffset /* overall leading whitespace offset */;
                match.start += iconOffset;
                match.end += iconOffset;
            }
        }
        return matches;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[192/*vs/base/common/uint*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.toUint8 = toUint8;
    exports.toUint32 = toUint32;
    function toUint8(v) {
        if (v < 0) {
            return 0;
        }
        if (v > 255 /* Constants.MAX_UINT_8 */) {
            return 255 /* Constants.MAX_UINT_8 */;
        }
        return v | 0;
    }
    function toUint32(v) {
        if (v < 0) {
            return 0;
        }
        if (v > 4294967295 /* Constants.MAX_UINT_32 */) {
            return 4294967295 /* Constants.MAX_UINT_32 */;
        }
        return v | 0;
    }
});

define(__m[193/*vs/base/common/uuid*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.generateUuid = void 0;
    exports.generateUuid = (function () {
        // use `randomUUID` if possible
        if (typeof crypto === 'object' && typeof crypto.randomUUID === 'function') {
            return crypto.randomUUID.bind(crypto);
        }
        // use `randomValues` if possible
        let getRandomValues;
        if (typeof crypto === 'object' && typeof crypto.getRandomValues === 'function') {
            getRandomValues = crypto.getRandomValues.bind(crypto);
        }
        else {
            getRandomValues = function (bucket) {
                for (let i = 0; i < bucket.length; i++) {
                    bucket[i] = Math.floor(Math.random() * 256);
                }
                return bucket;
            };
        }
        // prep-work
        const _data = new Uint8Array(16);
        const _hex = [];
        for (let i = 0; i < 256; i++) {
            _hex.push(i.toString(16).padStart(2, '0'));
        }
        return function generateUuid() {
            // get data
            getRandomValues(_data);
            // set version bits
            _data[6] = (_data[6] & 0x0f) | 0x40;
            _data[8] = (_data[8] & 0x3f) | 0x80;
            // print as string
            let i = 0;
            let result = '';
            result += _hex[_data[i++]];
            result += _hex[_data[i++]];
            result += _hex[_data[i++]];
            result += _hex[_data[i++]];
            result += '-';
            result += _hex[_data[i++]];
            result += _hex[_data[i++]];
            result += '-';
            result += _hex[_data[i++]];
            result += _hex[_data[i++]];
            result += '-';
            result += _hex[_data[i++]];
            result += _hex[_data[i++]];
            result += '-';
            result += _hex[_data[i++]];
            result += _hex[_data[i++]];
            result += _hex[_data[i++]];
            result += _hex[_data[i++]];
            result += _hex[_data[i++]];
            result += _hex[_data[i++]];
            return result;
        };
    })();
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[194/*vs/base/common/dataTransfer*/], __M([1/*require*/,0/*exports*/,13/*vs/base/common/arrays*/,53/*vs/base/common/iterator*/,193/*vs/base/common/uuid*/]), function (require, exports, arrays_1, iterator_1, uuid_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.UriList = exports.VSDataTransfer = void 0;
    exports.createStringDataTransferItem = createStringDataTransferItem;
    exports.createFileDataTransferItem = createFileDataTransferItem;
    exports.matchesMimeType = matchesMimeType;
    function createStringDataTransferItem(stringOrPromise) {
        return {
            asString: async () => stringOrPromise,
            asFile: () => undefined,
            value: typeof stringOrPromise === 'string' ? stringOrPromise : undefined,
        };
    }
    function createFileDataTransferItem(fileName, uri, data) {
        const file = { id: (0, uuid_1.generateUuid)(), name: fileName, uri, data };
        return {
            asString: async () => '',
            asFile: () => file,
            value: undefined,
        };
    }
    class VSDataTransfer {
        constructor() {
            this._entries = new Map();
        }
        get size() {
            let size = 0;
            for (const _ of this._entries) {
                size++;
            }
            return size;
        }
        has(mimeType) {
            return this._entries.has(this.toKey(mimeType));
        }
        matches(pattern) {
            const mimes = [...this._entries.keys()];
            if (iterator_1.Iterable.some(this, ([_, item]) => item.asFile())) {
                mimes.push('files');
            }
            return matchesMimeType_normalized(normalizeMimeType(pattern), mimes);
        }
        get(mimeType) {
            return this._entries.get(this.toKey(mimeType))?.[0];
        }
        /**
         * Add a new entry to this data transfer.
         *
         * This does not replace existing entries for `mimeType`.
         */
        append(mimeType, value) {
            const existing = this._entries.get(mimeType);
            if (existing) {
                existing.push(value);
            }
            else {
                this._entries.set(this.toKey(mimeType), [value]);
            }
        }
        /**
         * Set the entry for a given mime type.
         *
         * This replaces all existing entries for `mimeType`.
         */
        replace(mimeType, value) {
            this._entries.set(this.toKey(mimeType), [value]);
        }
        /**
         * Remove all entries for `mimeType`.
         */
        delete(mimeType) {
            this._entries.delete(this.toKey(mimeType));
        }
        /**
         * Iterate over all `[mime, item]` pairs in this data transfer.
         *
         * There may be multiple entries for each mime type.
         */
        *[Symbol.iterator]() {
            for (const [mine, items] of this._entries) {
                for (const item of items) {
                    yield [mine, item];
                }
            }
        }
        toKey(mimeType) {
            return normalizeMimeType(mimeType);
        }
    }
    exports.VSDataTransfer = VSDataTransfer;
    function normalizeMimeType(mimeType) {
        return mimeType.toLowerCase();
    }
    function matchesMimeType(pattern, mimeTypes) {
        return matchesMimeType_normalized(normalizeMimeType(pattern), mimeTypes.map(normalizeMimeType));
    }
    function matchesMimeType_normalized(normalizedPattern, normalizedMimeTypes) {
        // Anything wildcard
        if (normalizedPattern === '*/*') {
            return normalizedMimeTypes.length > 0;
        }
        // Exact match
        if (normalizedMimeTypes.includes(normalizedPattern)) {
            return true;
        }
        // Wildcard, such as `image/*`
        const wildcard = normalizedPattern.match(/^([a-z]+)\/([a-z]+|\*)$/i);
        if (!wildcard) {
            return false;
        }
        const [_, type, subtype] = wildcard;
        if (subtype === '*') {
            return normalizedMimeTypes.some(mime => mime.startsWith(type + '/'));
        }
        return false;
    }
    exports.UriList = Object.freeze({
        // http://amundsen.com/hypermedia/urilist/
        create: (entries) => {
            return (0, arrays_1.distinct)(entries.map(x => x.toString())).join('\r\n');
        },
        split: (str) => {
            return str.split('\r\n');
        },
        parse: (str) => {
            return exports.UriList.split(str).filter(value => !value.startsWith('#'));
        }
    });
});

define(__m[302/*vs/css!vs/base/browser/ui/actionbar/actionbar*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[458/*vs/css!vs/base/browser/ui/aria/aria*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[459/*vs/css!vs/base/browser/ui/button/button*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[460/*vs/css!vs/base/browser/ui/codicons/codicon/codicon*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[461/*vs/css!vs/base/browser/ui/codicons/codicon/codicon-modifiers*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[195/*vs/base/browser/ui/codicons/codiconStyles*/], __M([1/*require*/,0/*exports*/,460/*vs/css!vs/base/browser/ui/codicons/codicon/codicon*/,461/*vs/css!vs/base/browser/ui/codicons/codicon/codicon-modifiers*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
});

define(__m[462/*vs/css!vs/base/browser/ui/contextview/contextview*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[463/*vs/css!vs/base/browser/ui/countBadge/countBadge*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[303/*vs/css!vs/base/browser/ui/dropdown/dropdown*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[304/*vs/css!vs/base/browser/ui/findinput/findInput*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[464/*vs/css!vs/base/browser/ui/hover/hoverWidget*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[465/*vs/css!vs/base/browser/ui/iconLabel/iconlabel*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[466/*vs/css!vs/base/browser/ui/inputbox/inputBox*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[467/*vs/css!vs/base/browser/ui/keybindingLabel/keybindingLabel*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[305/*vs/css!vs/base/browser/ui/list/list*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[468/*vs/css!vs/base/browser/ui/mouseCursor/mouseCursor*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[226/*vs/base/browser/ui/mouseCursor/mouseCursor*/], __M([1/*require*/,0/*exports*/,468/*vs/css!vs/base/browser/ui/mouseCursor/mouseCursor*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MOUSE_CURSOR_TEXT_CSS_CLASS_NAME = void 0;
    exports.MOUSE_CURSOR_TEXT_CSS_CLASS_NAME = `monaco-mouse-cursor-text`;
});

define(__m[469/*vs/css!vs/base/browser/ui/progressbar/progressbar*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[470/*vs/css!vs/base/browser/ui/sash/sash*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[471/*vs/css!vs/base/browser/ui/scrollbar/media/scrollbars*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[472/*vs/css!vs/base/browser/ui/selectBox/selectBox*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[473/*vs/css!vs/base/browser/ui/selectBox/selectBoxCustom*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[474/*vs/css!vs/base/browser/ui/splitview/splitview*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[475/*vs/css!vs/base/browser/ui/table/table*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[476/*vs/css!vs/base/browser/ui/toggle/toggle*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[477/*vs/css!vs/base/browser/ui/toolbar/toolbar*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[478/*vs/css!vs/base/browser/ui/tree/media/tree*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[479/*vs/css!vs/editor/browser/controller/textAreaHandler*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[480/*vs/css!vs/editor/browser/services/hoverService/hover*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[481/*vs/css!vs/editor/browser/viewParts/blockDecorations/blockDecorations*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[482/*vs/css!vs/editor/browser/viewParts/currentLineHighlight/currentLineHighlight*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[483/*vs/css!vs/editor/browser/viewParts/decorations/decorations*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[484/*vs/css!vs/editor/browser/viewParts/glyphMargin/glyphMargin*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[485/*vs/css!vs/editor/browser/viewParts/indentGuides/indentGuides*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[486/*vs/css!vs/editor/browser/viewParts/lineNumbers/lineNumbers*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[487/*vs/css!vs/editor/browser/viewParts/lines/viewLines*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[488/*vs/css!vs/editor/browser/viewParts/linesDecorations/linesDecorations*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[489/*vs/css!vs/editor/browser/viewParts/margin/margin*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[490/*vs/css!vs/editor/browser/viewParts/marginDecorations/marginDecorations*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[491/*vs/css!vs/editor/browser/viewParts/minimap/minimap*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[492/*vs/css!vs/editor/browser/viewParts/overlayWidgets/overlayWidgets*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[493/*vs/css!vs/editor/browser/viewParts/rulers/rulers*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[494/*vs/css!vs/editor/browser/viewParts/scrollDecoration/scrollDecoration*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[495/*vs/css!vs/editor/browser/viewParts/selections/selections*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[496/*vs/css!vs/editor/browser/viewParts/viewCursors/viewCursors*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[497/*vs/css!vs/editor/browser/viewParts/whitespace/whitespace*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[498/*vs/css!vs/editor/browser/widget/codeEditor/editor*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[499/*vs/css!vs/editor/browser/widget/diffEditor/components/accessibleDiffViewer*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[500/*vs/css!vs/editor/browser/widget/diffEditor/style*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[501/*vs/css!vs/editor/browser/widget/markdownRenderer/browser/renderedMarkdown*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[502/*vs/css!vs/editor/browser/widget/multiDiffEditor/style*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[503/*vs/css!vs/editor/contrib/anchorSelect/browser/anchorSelect*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[504/*vs/css!vs/editor/contrib/bracketMatching/browser/bracketMatching*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[505/*vs/css!vs/editor/contrib/codeAction/browser/lightBulbWidget*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[506/*vs/css!vs/editor/contrib/codelens/browser/codelensWidget*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[227/*vs/css!vs/editor/contrib/colorPicker/browser/colorPicker*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[507/*vs/css!vs/editor/contrib/dnd/browser/dnd*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[508/*vs/css!vs/editor/contrib/dropOrPasteInto/browser/postEditWidget*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[509/*vs/css!vs/editor/contrib/find/browser/findOptionsWidget*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[510/*vs/css!vs/editor/contrib/find/browser/findWidget*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[511/*vs/css!vs/editor/contrib/folding/browser/folding*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[512/*vs/css!vs/editor/contrib/gotoError/browser/media/gotoErrorWidget*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[513/*vs/css!vs/editor/contrib/gotoSymbol/browser/link/goToDefinitionAtPosition*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[514/*vs/css!vs/editor/contrib/gotoSymbol/browser/peek/referencesWidget*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[196/*vs/css!vs/editor/contrib/hover/browser/hover*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[515/*vs/css!vs/editor/contrib/inPlaceReplace/browser/inPlaceReplace*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[516/*vs/css!vs/editor/contrib/inlineCompletions/browser/hintsWidget/inlineCompletionsHintsWidget*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[517/*vs/css!vs/editor/contrib/inlineCompletions/browser/view/ghostTextView*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[518/*vs/css!vs/editor/contrib/inlineEdit/browser/inlineEdit*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[519/*vs/css!vs/editor/contrib/inlineEdit/browser/inlineEditHintsWidget*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[520/*vs/css!vs/editor/contrib/inlineEdit/browser/inlineEditSideBySideWidget*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[521/*vs/css!vs/editor/contrib/inlineEdits/browser/inlineEditsWidget*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[522/*vs/css!vs/editor/contrib/inlineProgress/browser/inlineProgressWidget*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[523/*vs/css!vs/editor/contrib/linkedEditing/browser/linkedEditing*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[524/*vs/css!vs/editor/contrib/links/browser/links*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[525/*vs/css!vs/editor/contrib/message/browser/messageController*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[526/*vs/css!vs/editor/contrib/parameterHints/browser/parameterHints*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[527/*vs/css!vs/editor/contrib/peekView/browser/media/peekViewWidget*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[528/*vs/css!vs/editor/contrib/placeholderText/browser/placeholderText*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[529/*vs/css!vs/editor/contrib/rename/browser/renameWidget*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[530/*vs/css!vs/editor/contrib/snippet/browser/snippetSession*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[531/*vs/css!vs/editor/contrib/stickyScroll/browser/stickyScroll*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[532/*vs/css!vs/editor/contrib/suggest/browser/media/suggest*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[533/*vs/css!vs/editor/contrib/symbolIcons/browser/symbolIcons*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[534/*vs/css!vs/editor/contrib/unicodeHighlighter/browser/bannerController*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[535/*vs/css!vs/editor/contrib/unicodeHighlighter/browser/unicodeHighlighter*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[536/*vs/css!vs/editor/contrib/wordHighlighter/browser/highlightDecorations*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[537/*vs/css!vs/editor/contrib/zoneWidget/browser/zoneWidget*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[538/*vs/css!vs/editor/standalone/browser/iPadShowKeyboard/iPadShowKeyboard*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[539/*vs/css!vs/editor/standalone/browser/inspectTokens/inspectTokens*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[540/*vs/css!vs/editor/standalone/browser/quickInput/standaloneQuickInput*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[541/*vs/css!vs/editor/standalone/browser/standalone-tokens*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[306/*vs/css!vs/platform/actionWidget/browser/actionWidget*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[542/*vs/css!vs/platform/actions/browser/menuEntryActionViewItem*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[543/*vs/css!vs/platform/opener/browser/link*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[228/*vs/css!vs/platform/quickinput/browser/media/quickInput*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
define(__m[544/*vs/css!vs/platform/severityIcon/browser/media/severityIcon*/], __M([10/*vs/css!vs/editor/editor.main*/]), {});
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[74/*vs/editor/browser/config/domFontInfo*/], __M([1/*require*/,0/*exports*/,39/*vs/base/browser/fastDomNode*/]), function (require, exports, fastDomNode_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.applyFontInfo = applyFontInfo;
    function applyFontInfo(domNode, fontInfo) {
        if (domNode instanceof fastDomNode_1.FastDomNode) {
            domNode.setFontFamily(fontInfo.getMassagedFontFamily());
            domNode.setFontWeight(fontInfo.fontWeight);
            domNode.setFontSize(fontInfo.fontSize);
            domNode.setFontFeatureSettings(fontInfo.fontFeatureSettings);
            domNode.setFontVariationSettings(fontInfo.fontVariationSettings);
            domNode.setLineHeight(fontInfo.lineHeight);
            domNode.setLetterSpacing(fontInfo.letterSpacing);
        }
        else {
            domNode.style.fontFamily = fontInfo.getMassagedFontFamily();
            domNode.style.fontWeight = fontInfo.fontWeight;
            domNode.style.fontSize = fontInfo.fontSize + 'px';
            domNode.style.fontFeatureSettings = fontInfo.fontFeatureSettings;
            domNode.style.fontVariationSettings = fontInfo.fontVariationSettings;
            domNode.style.lineHeight = fontInfo.lineHeight + 'px';
            domNode.style.letterSpacing = fontInfo.letterSpacing + 'px';
        }
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[545/*vs/editor/browser/config/charWidthReader*/], __M([1/*require*/,0/*exports*/,74/*vs/editor/browser/config/domFontInfo*/]), function (require, exports, domFontInfo_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CharWidthRequest = void 0;
    exports.readCharWidths = readCharWidths;
    class CharWidthRequest {
        constructor(chr, type) {
            this.chr = chr;
            this.type = type;
            this.width = 0;
        }
        fulfill(width) {
            this.width = width;
        }
    }
    exports.CharWidthRequest = CharWidthRequest;
    class DomCharWidthReader {
        constructor(bareFontInfo, requests) {
            this._bareFontInfo = bareFontInfo;
            this._requests = requests;
            this._container = null;
            this._testElements = null;
        }
        read(targetWindow) {
            // Create a test container with all these test elements
            this._createDomElements();
            // Add the container to the DOM
            targetWindow.document.body.appendChild(this._container);
            // Read character widths
            this._readFromDomElements();
            // Remove the container from the DOM
            this._container?.remove();
            this._container = null;
            this._testElements = null;
        }
        _createDomElements() {
            const container = document.createElement('div');
            container.style.position = 'absolute';
            container.style.top = '-50000px';
            container.style.width = '50000px';
            const regularDomNode = document.createElement('div');
            (0, domFontInfo_1.applyFontInfo)(regularDomNode, this._bareFontInfo);
            container.appendChild(regularDomNode);
            const boldDomNode = document.createElement('div');
            (0, domFontInfo_1.applyFontInfo)(boldDomNode, this._bareFontInfo);
            boldDomNode.style.fontWeight = 'bold';
            container.appendChild(boldDomNode);
            const italicDomNode = document.createElement('div');
            (0, domFontInfo_1.applyFontInfo)(italicDomNode, this._bareFontInfo);
            italicDomNode.style.fontStyle = 'italic';
            container.appendChild(italicDomNode);
            const testElements = [];
            for (const request of this._requests) {
                let parent;
                if (request.type === 0 /* CharWidthRequestType.Regular */) {
                    parent = regularDomNode;
                }
                if (request.type === 2 /* CharWidthRequestType.Bold */) {
                    parent = boldDomNode;
                }
                if (request.type === 1 /* CharWidthRequestType.Italic */) {
                    parent = italicDomNode;
                }
                parent.appendChild(document.createElement('br'));
                const testElement = document.createElement('span');
                DomCharWidthReader._render(testElement, request);
                parent.appendChild(testElement);
                testElements.push(testElement);
            }
            this._container = container;
            this._testElements = testElements;
        }
        static _render(testElement, request) {
            if (request.chr === ' ') {
                let htmlString = '\u00a0';
                // Repeat character 256 (2^8) times
                for (let i = 0; i < 8; i++) {
                    htmlString += htmlString;
                }
                testElement.innerText = htmlString;
            }
            else {
                let testString = request.chr;
                // Repeat character 256 (2^8) times
                for (let i = 0; i < 8; i++) {
                    testString += testString;
                }
                testElement.textContent = testString;
            }
        }
        _readFromDomElements() {
            for (let i = 0, len = this._requests.length; i < len; i++) {
                const request = this._requests[i];
                const testElement = this._testElements[i];
                request.fulfill(testElement.offsetWidth / 256);
            }
        }
    }
    function readCharWidths(targetWindow, bareFontInfo, requests) {
        const reader = new DomCharWidthReader(bareFontInfo, requests);
        reader.read(targetWindow);
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[546/*vs/editor/browser/config/migrateOptions*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.EditorSettingMigration = void 0;
    exports.migrateOptions = migrateOptions;
    class EditorSettingMigration {
        static { this.items = []; }
        constructor(key, migrate) {
            this.key = key;
            this.migrate = migrate;
        }
        apply(options) {
            const value = EditorSettingMigration._read(options, this.key);
            const read = (key) => EditorSettingMigration._read(options, key);
            const write = (key, value) => EditorSettingMigration._write(options, key, value);
            this.migrate(value, read, write);
        }
        static _read(source, key) {
            if (typeof source === 'undefined') {
                return undefined;
            }
            const firstDotIndex = key.indexOf('.');
            if (firstDotIndex >= 0) {
                const firstSegment = key.substring(0, firstDotIndex);
                return this._read(source[firstSegment], key.substring(firstDotIndex + 1));
            }
            return source[key];
        }
        static _write(target, key, value) {
            const firstDotIndex = key.indexOf('.');
            if (firstDotIndex >= 0) {
                const firstSegment = key.substring(0, firstDotIndex);
                target[firstSegment] = target[firstSegment] || {};
                this._write(target[firstSegment], key.substring(firstDotIndex + 1), value);
                return;
            }
            target[key] = value;
        }
    }
    exports.EditorSettingMigration = EditorSettingMigration;
    function registerEditorSettingMigration(key, migrate) {
        EditorSettingMigration.items.push(new EditorSettingMigration(key, migrate));
    }
    function registerSimpleEditorSettingMigration(key, values) {
        registerEditorSettingMigration(key, (value, read, write) => {
            if (typeof value !== 'undefined') {
                for (const [oldValue, newValue] of values) {
                    if (value === oldValue) {
                        write(key, newValue);
                        return;
                    }
                }
            }
        });
    }
    /**
     * Compatibility with old options
     */
    function migrateOptions(options) {
        EditorSettingMigration.items.forEach(migration => migration.apply(options));
    }
    registerSimpleEditorSettingMigration('wordWrap', [[true, 'on'], [false, 'off']]);
    registerSimpleEditorSettingMigration('lineNumbers', [[true, 'on'], [false, 'off']]);
    registerSimpleEditorSettingMigration('cursorBlinking', [['visible', 'solid']]);
    registerSimpleEditorSettingMigration('renderWhitespace', [[true, 'boundary'], [false, 'none']]);
    registerSimpleEditorSettingMigration('renderLineHighlight', [[true, 'line'], [false, 'none']]);
    registerSimpleEditorSettingMigration('acceptSuggestionOnEnter', [[true, 'on'], [false, 'off']]);
    registerSimpleEditorSettingMigration('tabCompletion', [[false, 'off'], [true, 'onlySnippets']]);
    registerSimpleEditorSettingMigration('hover', [[true, { enabled: true }], [false, { enabled: false }]]);
    registerSimpleEditorSettingMigration('parameterHints', [[true, { enabled: true }], [false, { enabled: false }]]);
    registerSimpleEditorSettingMigration('autoIndent', [[false, 'advanced'], [true, 'full']]);
    registerSimpleEditorSettingMigration('matchBrackets', [[true, 'always'], [false, 'never']]);
    registerSimpleEditorSettingMigration('renderFinalNewline', [[true, 'on'], [false, 'off']]);
    registerSimpleEditorSettingMigration('cursorSmoothCaretAnimation', [[true, 'on'], [false, 'off']]);
    registerSimpleEditorSettingMigration('occurrencesHighlight', [[true, 'singleFile'], [false, 'off']]);
    registerSimpleEditorSettingMigration('wordBasedSuggestions', [[true, 'matchingDocuments'], [false, 'off']]);
    registerEditorSettingMigration('autoClosingBrackets', (value, read, write) => {
        if (value === false) {
            write('autoClosingBrackets', 'never');
            if (typeof read('autoClosingQuotes') === 'undefined') {
                write('autoClosingQuotes', 'never');
            }
            if (typeof read('autoSurround') === 'undefined') {
                write('autoSurround', 'never');
            }
        }
    });
    registerEditorSettingMigration('renderIndentGuides', (value, read, write) => {
        if (typeof value !== 'undefined') {
            write('renderIndentGuides', undefined);
            if (typeof read('guides.indentation') === 'undefined') {
                write('guides.indentation', !!value);
            }
        }
    });
    registerEditorSettingMigration('highlightActiveIndentGuide', (value, read, write) => {
        if (typeof value !== 'undefined') {
            write('highlightActiveIndentGuide', undefined);
            if (typeof read('guides.highlightActiveIndentation') === 'undefined') {
                write('guides.highlightActiveIndentation', !!value);
            }
        }
    });
    const suggestFilteredTypesMapping = {
        method: 'showMethods',
        function: 'showFunctions',
        constructor: 'showConstructors',
        deprecated: 'showDeprecated',
        field: 'showFields',
        variable: 'showVariables',
        class: 'showClasses',
        struct: 'showStructs',
        interface: 'showInterfaces',
        module: 'showModules',
        property: 'showProperties',
        event: 'showEvents',
        operator: 'showOperators',
        unit: 'showUnits',
        value: 'showValues',
        constant: 'showConstants',
        enum: 'showEnums',
        enumMember: 'showEnumMembers',
        keyword: 'showKeywords',
        text: 'showWords',
        color: 'showColors',
        file: 'showFiles',
        reference: 'showReferences',
        folder: 'showFolders',
        typeParameter: 'showTypeParameters',
        snippet: 'showSnippets',
    };
    registerEditorSettingMigration('suggest.filteredTypes', (value, read, write) => {
        if (value && typeof value === 'object') {
            for (const entry of Object.entries(suggestFilteredTypesMapping)) {
                const v = value[entry[0]];
                if (v === false) {
                    if (typeof read(`suggest.${entry[1]}`) === 'undefined') {
                        write(`suggest.${entry[1]}`, false);
                    }
                }
            }
            write('suggest.filteredTypes', undefined);
        }
    });
    registerEditorSettingMigration('quickSuggestions', (input, read, write) => {
        if (typeof input === 'boolean') {
            const value = input ? 'on' : 'off';
            const newValue = { comments: value, strings: value, other: value };
            write('quickSuggestions', newValue);
        }
    });
    // Sticky Scroll
    registerEditorSettingMigration('experimental.stickyScroll.enabled', (value, read, write) => {
        if (typeof value === 'boolean') {
            write('experimental.stickyScroll.enabled', undefined);
            if (typeof read('stickyScroll.enabled') === 'undefined') {
                write('stickyScroll.enabled', value);
            }
        }
    });
    registerEditorSettingMigration('experimental.stickyScroll.maxLineCount', (value, read, write) => {
        if (typeof value === 'number') {
            write('experimental.stickyScroll.maxLineCount', undefined);
            if (typeof read('stickyScroll.maxLineCount') === 'undefined') {
                write('stickyScroll.maxLineCount', value);
            }
        }
    });
    // Code Actions on Save
    registerEditorSettingMigration('codeActionsOnSave', (value, read, write) => {
        if (value && typeof value === 'object') {
            let toBeModified = false;
            const newValue = {};
            for (const entry of Object.entries(value)) {
                if (typeof entry[1] === 'boolean') {
                    toBeModified = true;
                    newValue[entry[0]] = entry[1] ? 'explicit' : 'never';
                }
                else {
                    newValue[entry[0]] = entry[1];
                }
            }
            if (toBeModified) {
                write(`codeActionsOnSave`, newValue);
            }
        }
    });
    // Migrate Quick Fix Settings
    registerEditorSettingMigration('codeActionWidget.includeNearbyQuickfixes', (value, read, write) => {
        if (typeof value === 'boolean') {
            write('codeActionWidget.includeNearbyQuickfixes', undefined);
            if (typeof read('codeActionWidget.includeNearbyQuickFixes') === 'undefined') {
                write('codeActionWidget.includeNearbyQuickFixes', value);
            }
        }
    });
    // Migrate the lightbulb settings
    registerEditorSettingMigration('lightbulb.enabled', (value, read, write) => {
        if (typeof value === 'boolean') {
            write('lightbulb.enabled', value ? undefined : 'off');
        }
    });
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[229/*vs/editor/browser/config/tabFocus*/], __M([1/*require*/,0/*exports*/,6/*vs/base/common/event*/]), function (require, exports, event_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.TabFocus = void 0;
    class TabFocusImpl {
        constructor() {
            this._tabFocus = false;
            this._onDidChangeTabFocus = new event_1.Emitter();
            this.onDidChangeTabFocus = this._onDidChangeTabFocus.event;
        }
        getTabFocusMode() {
            return this._tabFocus;
        }
        setTabFocusMode(tabFocusMode) {
            this._tabFocus = tabFocusMode;
            this._onDidChangeTabFocus.fire(this._tabFocus);
        }
    }
    /**
     * Control what pressing Tab does.
     * If it is false, pressing Tab or Shift-Tab will be handled by the editor.
     * If it is true, pressing Tab or Shift-Tab will move the browser focus.
     * Defaults to false.
     */
    exports.TabFocus = new TabFocusImpl();
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[143/*vs/editor/browser/stableEditorScroll*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.StableEditorScrollState = void 0;
    class StableEditorScrollState {
        static capture(editor) {
            if (editor.getScrollTop() === 0 || editor.hasPendingScrollAnimation()) {
                // Never mess with the scroll top if the editor is at the top of the file or if there is a pending scroll animation
                return new StableEditorScrollState(editor.getScrollTop(), editor.getContentHeight(), null, 0, null);
            }
            let visiblePosition = null;
            let visiblePositionScrollDelta = 0;
            const visibleRanges = editor.getVisibleRanges();
            if (visibleRanges.length > 0) {
                visiblePosition = visibleRanges[0].getStartPosition();
                const visiblePositionScrollTop = editor.getTopForPosition(visiblePosition.lineNumber, visiblePosition.column);
                visiblePositionScrollDelta = editor.getScrollTop() - visiblePositionScrollTop;
            }
            return new StableEditorScrollState(editor.getScrollTop(), editor.getContentHeight(), visiblePosition, visiblePositionScrollDelta, editor.getPosition());
        }
        constructor(_initialScrollTop, _initialContentHeight, _visiblePosition, _visiblePositionScrollDelta, _cursorPosition) {
            this._initialScrollTop = _initialScrollTop;
            this._initialContentHeight = _initialContentHeight;
            this._visiblePosition = _visiblePosition;
            this._visiblePositionScrollDelta = _visiblePositionScrollDelta;
            this._cursorPosition = _cursorPosition;
        }
        restore(editor) {
            if (this._initialContentHeight === editor.getContentHeight() && this._initialScrollTop === editor.getScrollTop()) {
                // The editor's content height and scroll top haven't changed, so we don't need to do anything
                return;
            }
            if (this._visiblePosition) {
                const visiblePositionScrollTop = editor.getTopForPosition(this._visiblePosition.lineNumber, this._visiblePosition.column);
                editor.setScrollTop(visiblePositionScrollTop + this._visiblePositionScrollDelta);
            }
        }
        restoreRelativeVerticalPositionOfCursor(editor) {
            if (this._initialContentHeight === editor.getContentHeight() && this._initialScrollTop === editor.getScrollTop()) {
                // The editor's content height and scroll top haven't changed, so we don't need to do anything
                return;
            }
            const currentCursorPosition = editor.getPosition();
            if (!this._cursorPosition || !currentCursorPosition) {
                return;
            }
            const offset = editor.getTopForLineNumber(currentCursorPosition.lineNumber) - editor.getTopForLineNumber(this._cursorPosition.lineNumber);
            editor.setScrollTop(editor.getScrollTop() + offset, 1 /* ScrollType.Immediate */);
        }
    }
    exports.StableEditorScrollState = StableEditorScrollState;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[164/*vs/editor/browser/view/renderingContext*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.VisibleRanges = exports.HorizontalPosition = exports.FloatHorizontalRange = exports.HorizontalRange = exports.LineVisibleRanges = exports.RenderingContext = exports.RestrictedRenderingContext = void 0;
    class RestrictedRenderingContext {
        constructor(viewLayout, viewportData) {
            this._restrictedRenderingContextBrand = undefined;
            this._viewLayout = viewLayout;
            this.viewportData = viewportData;
            this.scrollWidth = this._viewLayout.getScrollWidth();
            this.scrollHeight = this._viewLayout.getScrollHeight();
            this.visibleRange = this.viewportData.visibleRange;
            this.bigNumbersDelta = this.viewportData.bigNumbersDelta;
            const vInfo = this._viewLayout.getCurrentViewport();
            this.scrollTop = vInfo.top;
            this.scrollLeft = vInfo.left;
            this.viewportWidth = vInfo.width;
            this.viewportHeight = vInfo.height;
        }
        getScrolledTopFromAbsoluteTop(absoluteTop) {
            return absoluteTop - this.scrollTop;
        }
        getVerticalOffsetForLineNumber(lineNumber, includeViewZones) {
            return this._viewLayout.getVerticalOffsetForLineNumber(lineNumber, includeViewZones);
        }
        getVerticalOffsetAfterLineNumber(lineNumber, includeViewZones) {
            return this._viewLayout.getVerticalOffsetAfterLineNumber(lineNumber, includeViewZones);
        }
        getDecorationsInViewport() {
            return this.viewportData.getDecorationsInViewport();
        }
    }
    exports.RestrictedRenderingContext = RestrictedRenderingContext;
    class RenderingContext extends RestrictedRenderingContext {
        constructor(viewLayout, viewportData, viewLines) {
            super(viewLayout, viewportData);
            this._renderingContextBrand = undefined;
            this._viewLines = viewLines;
        }
        linesVisibleRangesForRange(range, includeNewLines) {
            return this._viewLines.linesVisibleRangesForRange(range, includeNewLines);
        }
        visibleRangeForPosition(position) {
            return this._viewLines.visibleRangeForPosition(position);
        }
    }
    exports.RenderingContext = RenderingContext;
    class LineVisibleRanges {
        constructor(outsideRenderedLine, lineNumber, ranges, 
        /**
         * Indicates if the requested range does not end in this line, but continues on the next line.
         */
        continuesOnNextLine) {
            this.outsideRenderedLine = outsideRenderedLine;
            this.lineNumber = lineNumber;
            this.ranges = ranges;
            this.continuesOnNextLine = continuesOnNextLine;
        }
    }
    exports.LineVisibleRanges = LineVisibleRanges;
    class HorizontalRange {
        static from(ranges) {
            const result = new Array(ranges.length);
            for (let i = 0, len = ranges.length; i < len; i++) {
                const range = ranges[i];
                result[i] = new HorizontalRange(range.left, range.width);
            }
            return result;
        }
        constructor(left, width) {
            this._horizontalRangeBrand = undefined;
            this.left = Math.round(left);
            this.width = Math.round(width);
        }
        toString() {
            return `[${this.left},${this.width}]`;
        }
    }
    exports.HorizontalRange = HorizontalRange;
    class FloatHorizontalRange {
        constructor(left, width) {
            this._floatHorizontalRangeBrand = undefined;
            this.left = left;
            this.width = width;
        }
        toString() {
            return `[${this.left},${this.width}]`;
        }
        static compare(a, b) {
            return a.left - b.left;
        }
    }
    exports.FloatHorizontalRange = FloatHorizontalRange;
    class HorizontalPosition {
        constructor(outsideRenderedLine, left) {
            this.outsideRenderedLine = outsideRenderedLine;
            this.originalLeft = left;
            this.left = Math.round(this.originalLeft);
        }
    }
    exports.HorizontalPosition = HorizontalPosition;
    class VisibleRanges {
        constructor(outsideRenderedLine, ranges) {
            this.outsideRenderedLine = outsideRenderedLine;
            this.ranges = ranges;
        }
    }
    exports.VisibleRanges = VisibleRanges;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[547/*vs/editor/browser/viewParts/lines/domReadingContext*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DomReadingContext = void 0;
    class DomReadingContext {
        get didDomLayout() {
            return this._didDomLayout;
        }
        readClientRect() {
            if (!this._clientRectRead) {
                this._clientRectRead = true;
                const rect = this._domNode.getBoundingClientRect();
                this.markDidDomLayout();
                this._clientRectDeltaLeft = rect.left;
                this._clientRectScale = rect.width / this._domNode.offsetWidth;
            }
        }
        get clientRectDeltaLeft() {
            if (!this._clientRectRead) {
                this.readClientRect();
            }
            return this._clientRectDeltaLeft;
        }
        get clientRectScale() {
            if (!this._clientRectRead) {
                this.readClientRect();
            }
            return this._clientRectScale;
        }
        constructor(_domNode, endNode) {
            this._domNode = _domNode;
            this.endNode = endNode;
            this._didDomLayout = false;
            this._clientRectDeltaLeft = 0;
            this._clientRectScale = 1;
            this._clientRectRead = false;
        }
        markDidDomLayout() {
            this._didDomLayout = true;
        }
    }
    exports.DomReadingContext = DomReadingContext;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[548/*vs/editor/browser/viewParts/lines/rangeUtil*/], __M([1/*require*/,0/*exports*/,164/*vs/editor/browser/view/renderingContext*/]), function (require, exports, renderingContext_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.RangeUtil = void 0;
    class RangeUtil {
        static _createRange() {
            if (!this._handyReadyRange) {
                this._handyReadyRange = document.createRange();
            }
            return this._handyReadyRange;
        }
        static _detachRange(range, endNode) {
            // Move range out of the span node, IE doesn't like having many ranges in
            // the same spot and will act badly for lines containing dashes ('-')
            range.selectNodeContents(endNode);
        }
        static _readClientRects(startElement, startOffset, endElement, endOffset, endNode) {
            const range = this._createRange();
            try {
                range.setStart(startElement, startOffset);
                range.setEnd(endElement, endOffset);
                return range.getClientRects();
            }
            catch (e) {
                // This is life ...
                return null;
            }
            finally {
                this._detachRange(range, endNode);
            }
        }
        static _mergeAdjacentRanges(ranges) {
            if (ranges.length === 1) {
                // There is nothing to merge
                return ranges;
            }
            ranges.sort(renderingContext_1.FloatHorizontalRange.compare);
            const result = [];
            let resultLen = 0;
            let prev = ranges[0];
            for (let i = 1, len = ranges.length; i < len; i++) {
                const range = ranges[i];
                if (prev.left + prev.width + 0.9 /* account for browser's rounding errors*/ >= range.left) {
                    prev.width = Math.max(prev.width, range.left + range.width - prev.left);
                }
                else {
                    result[resultLen++] = prev;
                    prev = range;
                }
            }
            result[resultLen++] = prev;
            return result;
        }
        static _createHorizontalRangesFromClientRects(clientRects, clientRectDeltaLeft, clientRectScale) {
            if (!clientRects || clientRects.length === 0) {
                return null;
            }
            // We go through FloatHorizontalRange because it has been observed in bi-di text
            // that the clientRects are not coming in sorted from the browser
            const result = [];
            for (let i = 0, len = clientRects.length; i < len; i++) {
                const clientRect = clientRects[i];
                result[i] = new renderingContext_1.FloatHorizontalRange(Math.max(0, (clientRect.left - clientRectDeltaLeft) / clientRectScale), clientRect.width / clientRectScale);
            }
            return this._mergeAdjacentRanges(result);
        }
        static readHorizontalRanges(domNode, startChildIndex, startOffset, endChildIndex, endOffset, context) {
            // Panic check
            const min = 0;
            const max = domNode.children.length - 1;
            if (min > max) {
                return null;
            }
            startChildIndex = Math.min(max, Math.max(min, startChildIndex));
            endChildIndex = Math.min(max, Math.max(min, endChildIndex));
            if (startChildIndex === endChildIndex && startOffset === endOffset && startOffset === 0 && !domNode.children[startChildIndex].firstChild) {
                // We must find the position at the beginning of a <span>
                // To cover cases of empty <span>s, avoid using a range and use the <span>'s bounding box
                const clientRects = domNode.children[startChildIndex].getClientRects();
                context.markDidDomLayout();
                return this._createHorizontalRangesFromClientRects(clientRects, context.clientRectDeltaLeft, context.clientRectScale);
            }
            // If crossing over to a span only to select offset 0, then use the previous span's maximum offset
            // Chrome is buggy and doesn't handle 0 offsets well sometimes.
            if (startChildIndex !== endChildIndex) {
                if (endChildIndex > 0 && endOffset === 0) {
                    endChildIndex--;
                    endOffset = 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */;
                }
            }
            let startElement = domNode.children[startChildIndex].firstChild;
            let endElement = domNode.children[endChildIndex].firstChild;
            if (!startElement || !endElement) {
                // When having an empty <span> (without any text content), try to move to the previous <span>
                if (!startElement && startOffset === 0 && startChildIndex > 0) {
                    startElement = domNode.children[startChildIndex - 1].firstChild;
                    startOffset = 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */;
                }
                if (!endElement && endOffset === 0 && endChildIndex > 0) {
                    endElement = domNode.children[endChildIndex - 1].firstChild;
                    endOffset = 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */;
                }
            }
            if (!startElement || !endElement) {
                return null;
            }
            startOffset = Math.min(startElement.textContent.length, Math.max(0, startOffset));
            endOffset = Math.min(endElement.textContent.length, Math.max(0, endOffset));
            const clientRects = this._readClientRects(startElement, startOffset, endElement, endOffset, context.endNode);
            context.markDidDomLayout();
            return this._createHorizontalRangesFromClientRects(clientRects, context.clientRectDeltaLeft, context.clientRectScale);
        }
    }
    exports.RangeUtil = RangeUtil;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[307/*vs/editor/browser/viewParts/minimap/minimapCharSheet*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.getCharIndex = exports.allCharCodes = void 0;
    exports.allCharCodes = (() => {
        const v = [];
        for (let i = 32 /* Constants.START_CH_CODE */; i <= 126 /* Constants.END_CH_CODE */; i++) {
            v.push(i);
        }
        v.push(65533 /* Constants.UNKNOWN_CODE */);
        return v;
    })();
    const getCharIndex = (chCode, fontScale) => {
        chCode -= 32 /* Constants.START_CH_CODE */;
        if (chCode < 0 || chCode > 96 /* Constants.CHAR_COUNT */) {
            if (fontScale <= 2) {
                // for smaller scales, we can get away with using any ASCII character...
                return (chCode + 96 /* Constants.CHAR_COUNT */) % 96 /* Constants.CHAR_COUNT */;
            }
            return 96 /* Constants.CHAR_COUNT */ - 1; // unknown symbol
        }
        return chCode;
    };
    exports.getCharIndex = getCharIndex;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[549/*vs/editor/browser/viewParts/minimap/minimapCharRenderer*/], __M([1/*require*/,0/*exports*/,307/*vs/editor/browser/viewParts/minimap/minimapCharSheet*/,192/*vs/base/common/uint*/]), function (require, exports, minimapCharSheet_1, uint_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MinimapCharRenderer = void 0;
    class MinimapCharRenderer {
        constructor(charData, scale) {
            this.scale = scale;
            this._minimapCharRendererBrand = undefined;
            this.charDataNormal = MinimapCharRenderer.soften(charData, 12 / 15);
            this.charDataLight = MinimapCharRenderer.soften(charData, 50 / 60);
        }
        static soften(input, ratio) {
            const result = new Uint8ClampedArray(input.length);
            for (let i = 0, len = input.length; i < len; i++) {
                result[i] = (0, uint_1.toUint8)(input[i] * ratio);
            }
            return result;
        }
        renderChar(target, dx, dy, chCode, color, foregroundAlpha, backgroundColor, backgroundAlpha, fontScale, useLighterFont, force1pxHeight) {
            const charWidth = 1 /* Constants.BASE_CHAR_WIDTH */ * this.scale;
            const charHeight = 2 /* Constants.BASE_CHAR_HEIGHT */ * this.scale;
            const renderHeight = (force1pxHeight ? 1 : charHeight);
            if (dx + charWidth > target.width || dy + renderHeight > target.height) {
                console.warn('bad render request outside image data');
                return;
            }
            const charData = useLighterFont ? this.charDataLight : this.charDataNormal;
            const charIndex = (0, minimapCharSheet_1.getCharIndex)(chCode, fontScale);
            const destWidth = target.width * 4 /* Constants.RGBA_CHANNELS_CNT */;
            const backgroundR = backgroundColor.r;
            const backgroundG = backgroundColor.g;
            const backgroundB = backgroundColor.b;
            const deltaR = color.r - backgroundR;
            const deltaG = color.g - backgroundG;
            const deltaB = color.b - backgroundB;
            const destAlpha = Math.max(foregroundAlpha, backgroundAlpha);
            const dest = target.data;
            let sourceOffset = charIndex * charWidth * charHeight;
            let row = dy * destWidth + dx * 4 /* Constants.RGBA_CHANNELS_CNT */;
            for (let y = 0; y < renderHeight; y++) {
                let column = row;
                for (let x = 0; x < charWidth; x++) {
                    const c = (charData[sourceOffset++] / 255) * (foregroundAlpha / 255);
                    dest[column++] = backgroundR + deltaR * c;
                    dest[column++] = backgroundG + deltaG * c;
                    dest[column++] = backgroundB + deltaB * c;
                    dest[column++] = destAlpha;
                }
                row += destWidth;
            }
        }
        blockRenderChar(target, dx, dy, color, foregroundAlpha, backgroundColor, backgroundAlpha, force1pxHeight) {
            const charWidth = 1 /* Constants.BASE_CHAR_WIDTH */ * this.scale;
            const charHeight = 2 /* Constants.BASE_CHAR_HEIGHT */ * this.scale;
            const renderHeight = (force1pxHeight ? 1 : charHeight);
            if (dx + charWidth > target.width || dy + renderHeight > target.height) {
                console.warn('bad render request outside image data');
                return;
            }
            const destWidth = target.width * 4 /* Constants.RGBA_CHANNELS_CNT */;
            const c = 0.5 * (foregroundAlpha / 255);
            const backgroundR = backgroundColor.r;
            const backgroundG = backgroundColor.g;
            const backgroundB = backgroundColor.b;
            const deltaR = color.r - backgroundR;
            const deltaG = color.g - backgroundG;
            const deltaB = color.b - backgroundB;
            const colorR = backgroundR + deltaR * c;
            const colorG = backgroundG + deltaG * c;
            const colorB = backgroundB + deltaB * c;
            const destAlpha = Math.max(foregroundAlpha, backgroundAlpha);
            const dest = target.data;
            let row = dy * destWidth + dx * 4 /* Constants.RGBA_CHANNELS_CNT */;
            for (let y = 0; y < renderHeight; y++) {
                let column = row;
                for (let x = 0; x < charWidth; x++) {
                    dest[column++] = colorR;
                    dest[column++] = colorG;
                    dest[column++] = colorB;
                    dest[column++] = destAlpha;
                }
                row += destWidth;
            }
        }
    }
    exports.MinimapCharRenderer = MinimapCharRenderer;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[550/*vs/editor/browser/viewParts/minimap/minimapPreBaked*/], __M([1/*require*/,0/*exports*/,127/*vs/base/common/functional*/]), function (require, exports, functional_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.prebakedMiniMaps = void 0;
    const charTable = {
        '0': 0,
        '1': 1,
        '2': 2,
        '3': 3,
        '4': 4,
        '5': 5,
        '6': 6,
        '7': 7,
        '8': 8,
        '9': 9,
        A: 10,
        B: 11,
        C: 12,
        D: 13,
        E: 14,
        F: 15
    };
    const decodeData = (str) => {
        const output = new Uint8ClampedArray(str.length / 2);
        for (let i = 0; i < str.length; i += 2) {
            output[i >> 1] = (charTable[str[i]] << 4) | (charTable[str[i + 1]] & 0xF);
        }
        return output;
    };
    /*
    const encodeData = (data: Uint8ClampedArray, length: string) => {
        const chars = '0123456789ABCDEF';
        let output = '';
        for (let i = 0; i < data.length; i++) {
            output += chars[data[i] >> 4] + chars[data[i] & 0xf];
        }
        return output;
    };
    */
    /**
     * Map of minimap scales to prebaked sample data at those scales. We don't
     * sample much larger data, because then font family becomes visible, which
     * is use-configurable.
     */
    exports.prebakedMiniMaps = {
        1: (0, functional_1.createSingleCallFunction)(() => decodeData('0000511D6300CF609C709645A78432005642574171487021003C451900274D35D762755E8B629C5BA856AF57BA649530C167D1512A272A3F6038604460398526BCA2A968DB6F8957C768BE5FBE2FB467CF5D8D5B795DC7625B5DFF50DE64C466DB2FC47CD860A65E9A2EB96CB54CE06DA763AB2EA26860524D3763536601005116008177A8705E53AB738E6A982F88BAA35B5F5B626D9C636B449B737E5B7B678598869A662F6B5B8542706C704C80736A607578685B70594A49715A4522E792')),
        2: (0, functional_1.createSingleCallFunction)(() => decodeData('000000000000000055394F383D2800008B8B1F210002000081B1CBCBCC820000847AAF6B9AAF2119BE08B8881AD60000A44FD07DCCF107015338130C00000000385972265F390B406E2437634B4B48031B12B8A0847000001E15B29A402F0000000000004B33460B00007A752C2A0000000000004D3900000084394B82013400ABA5CFC7AD9C0302A45A3E5A98AB000089A43382D97900008BA54AA087A70A0248A6A7AE6DBE0000BF6F94987EA40A01A06DCFA7A7A9030496C32F77891D0000A99FB1A0AFA80603B29AB9CA75930D010C0948354D3900000C0948354F37460D0028BE673D8400000000AF9D7B6E00002B007AA8933400007AA642675C2700007984CFB9C3985B768772A8A6B7B20000CAAECAAFC4B700009F94A6009F840009D09F9BA4CA9C0000CC8FC76DC87F0000C991C472A2000000A894A48CA7B501079BA2C9C69BA20000B19A5D3FA89000005CA6009DA2960901B0A7F0669FB200009D009E00B7890000DAD0F5D092820000D294D4C48BD10000B5A7A4A3B1A50402CAB6CBA6A2000000B5A7A4A3B1A8044FCDADD19D9CB00000B7778F7B8AAE0803C9AB5D3F5D3F00009EA09EA0BAB006039EA0989A8C7900009B9EF4D6B7C00000A9A7816CACA80000ABAC84705D3F000096DA635CDC8C00006F486F266F263D4784006124097B00374F6D2D6D2D6D4A3A95872322000000030000000000008D8939130000000000002E22A5C9CBC70600AB25C0B5C9B400061A2DB04CA67001082AA6BEBEBFC606002321DACBC19E03087AA08B6768380000282FBAC0B8CA7A88AD25BBA5A29900004C396C5894A6000040485A6E356E9442A32CD17EADA70000B4237923628600003E2DE9C1D7B500002F25BBA5A2990000231DB6AFB4A804023025C0B5CAB588062B2CBDBEC0C706882435A75CA20000002326BD6A82A908048B4B9A5A668000002423A09CB4BB060025259C9D8A7900001C1FCAB2C7C700002A2A9387ABA200002626A4A47D6E9D14333163A0C87500004B6F9C2D643A257049364936493647358A34438355497F1A0000A24C1D590000D38DFFBDD4CD3126'))
    };
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[551/*vs/editor/browser/viewParts/minimap/minimapCharRendererFactory*/], __M([1/*require*/,0/*exports*/,549/*vs/editor/browser/viewParts/minimap/minimapCharRenderer*/,307/*vs/editor/browser/viewParts/minimap/minimapCharSheet*/,550/*vs/editor/browser/viewParts/minimap/minimapPreBaked*/,192/*vs/base/common/uint*/]), function (require, exports, minimapCharRenderer_1, minimapCharSheet_1, minimapPreBaked_1, uint_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MinimapCharRendererFactory = void 0;
    /**
     * Creates character renderers. It takes a 'scale' that determines how large
     * characters should be drawn. Using this, it draws data into a canvas and
     * then downsamples the characters as necessary for the current display.
     * This makes rendering more efficient, rather than drawing a full (tiny)
     * font, or downsampling in real-time.
     */
    class MinimapCharRendererFactory {
        /**
         * Creates a new character renderer factory with the given scale.
         */
        static create(scale, fontFamily) {
            // renderers are immutable. By default we'll 'create' a new minimap
            // character renderer whenever we switch editors, no need to do extra work.
            if (this.lastCreated && scale === this.lastCreated.scale && fontFamily === this.lastFontFamily) {
                return this.lastCreated;
            }
            let factory;
            if (minimapPreBaked_1.prebakedMiniMaps[scale]) {
                factory = new minimapCharRenderer_1.MinimapCharRenderer(minimapPreBaked_1.prebakedMiniMaps[scale](), scale);
            }
            else {
                factory = MinimapCharRendererFactory.createFromSampleData(MinimapCharRendererFactory.createSampleData(fontFamily).data, scale);
            }
            this.lastFontFamily = fontFamily;
            this.lastCreated = factory;
            return factory;
        }
        /**
         * Creates the font sample data, writing to a canvas.
         */
        static createSampleData(fontFamily) {
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            canvas.style.height = `${16 /* Constants.SAMPLED_CHAR_HEIGHT */}px`;
            canvas.height = 16 /* Constants.SAMPLED_CHAR_HEIGHT */;
            canvas.width = 96 /* Constants.CHAR_COUNT */ * 10 /* Constants.SAMPLED_CHAR_WIDTH */;
            canvas.style.width = 96 /* Constants.CHAR_COUNT */ * 10 /* Constants.SAMPLED_CHAR_WIDTH */ + 'px';
            ctx.fillStyle = '#ffffff';
            ctx.font = `bold ${16 /* Constants.SAMPLED_CHAR_HEIGHT */}px ${fontFamily}`;
            ctx.textBaseline = 'middle';
            let x = 0;
            for (const code of minimapCharSheet_1.allCharCodes) {
                ctx.fillText(String.fromCharCode(code), x, 16 /* Constants.SAMPLED_CHAR_HEIGHT */ / 2);
                x += 10 /* Constants.SAMPLED_CHAR_WIDTH */;
            }
            return ctx.getImageData(0, 0, 96 /* Constants.CHAR_COUNT */ * 10 /* Constants.SAMPLED_CHAR_WIDTH */, 16 /* Constants.SAMPLED_CHAR_HEIGHT */);
        }
        /**
         * Creates a character renderer from the canvas sample data.
         */
        static createFromSampleData(source, scale) {
            const expectedLength = 16 /* Constants.SAMPLED_CHAR_HEIGHT */ * 10 /* Constants.SAMPLED_CHAR_WIDTH */ * 4 /* Constants.RGBA_CHANNELS_CNT */ * 96 /* Constants.CHAR_COUNT */;
            if (source.length !== expectedLength) {
                throw new Error('Unexpected source in MinimapCharRenderer');
            }
            const charData = MinimapCharRendererFactory._downsample(source, scale);
            return new minimapCharRenderer_1.MinimapCharRenderer(charData, scale);
        }
        static _downsampleChar(source, sourceOffset, dest, destOffset, scale) {
            const width = 1 /* Constants.BASE_CHAR_WIDTH */ * scale;
            const height = 2 /* Constants.BASE_CHAR_HEIGHT */ * scale;
            let targetIndex = destOffset;
            let brightest = 0;
            // This is essentially an ad-hoc rescaling algorithm. Standard approaches
            // like bicubic interpolation are awesome for scaling between image sizes,
            // but don't work so well when scaling to very small pixel values, we end
            // up with blurry, indistinct forms.
            //
            // The approach taken here is simply mapping each source pixel to the target
            // pixels, and taking the weighted values for all pixels in each, and then
            // averaging them out. Finally we apply an intensity boost in _downsample,
            // since when scaling to the smallest pixel sizes there's more black space
            // which causes characters to be much less distinct.
            for (let y = 0; y < height; y++) {
                // 1. For this destination pixel, get the source pixels we're sampling
                // from (x1, y1) to the next pixel (x2, y2)
                const sourceY1 = (y / height) * 16 /* Constants.SAMPLED_CHAR_HEIGHT */;
                const sourceY2 = ((y + 1) / height) * 16 /* Constants.SAMPLED_CHAR_HEIGHT */;
                for (let x = 0; x < width; x++) {
                    const sourceX1 = (x / width) * 10 /* Constants.SAMPLED_CHAR_WIDTH */;
                    const sourceX2 = ((x + 1) / width) * 10 /* Constants.SAMPLED_CHAR_WIDTH */;
                    // 2. Sample all of them, summing them up and weighting them. Similar
                    // to bilinear interpolation.
                    let value = 0;
                    let samples = 0;
                    for (let sy = sourceY1; sy < sourceY2; sy++) {
                        const sourceRow = sourceOffset + Math.floor(sy) * 3840 /* Constants.RGBA_SAMPLED_ROW_WIDTH */;
                        const yBalance = 1 - (sy - Math.floor(sy));
                        for (let sx = sourceX1; sx < sourceX2; sx++) {
                            const xBalance = 1 - (sx - Math.floor(sx));
                            const sourceIndex = sourceRow + Math.floor(sx) * 4 /* Constants.RGBA_CHANNELS_CNT */;
                            const weight = xBalance * yBalance;
                            samples += weight;
                            value += ((source[sourceIndex] * source[sourceIndex + 3]) / 255) * weight;
                        }
                    }
                    const final = value / samples;
                    brightest = Math.max(brightest, final);
                    dest[targetIndex++] = (0, uint_1.toUint8)(final);
                }
            }
            return brightest;
        }
        static _downsample(data, scale) {
            const pixelsPerCharacter = 2 /* Constants.BASE_CHAR_HEIGHT */ * scale * 1 /* Constants.BASE_CHAR_WIDTH */ * scale;
            const resultLen = pixelsPerCharacter * 96 /* Constants.CHAR_COUNT */;
            const result = new Uint8ClampedArray(resultLen);
            let resultOffset = 0;
            let sourceOffset = 0;
            let brightest = 0;
            for (let charIndex = 0; charIndex < 96 /* Constants.CHAR_COUNT */; charIndex++) {
                brightest = Math.max(brightest, this._downsampleChar(data, sourceOffset, result, resultOffset, scale));
                resultOffset += pixelsPerCharacter;
                sourceOffset += 10 /* Constants.SAMPLED_CHAR_WIDTH */ * 4 /* Constants.RGBA_CHANNELS_CNT */;
            }
            if (brightest > 0) {
                const adjust = 255 / brightest;
                for (let i = 0; i < resultLen; i++) {
                    result[i] *= adjust;
                }
            }
            return result;
        }
    }
    exports.MinimapCharRendererFactory = MinimapCharRendererFactory;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[552/*vs/editor/browser/widget/diffEditor/delegatingEditorImpl*/], __M([1/*require*/,0/*exports*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/]), function (require, exports, event_1, lifecycle_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DelegatingEditor = void 0;
    class DelegatingEditor extends lifecycle_1.Disposable {
        constructor() {
            super(...arguments);
            this._id = ++DelegatingEditor.idCounter;
            this._onDidDispose = this._register(new event_1.Emitter());
            this.onDidDispose = this._onDidDispose.event;
            // #endregion
        }
        static { this.idCounter = 0; }
        getId() { return this.getEditorType() + ':v2:' + this._id; }
        // #region editorBrowser.IDiffEditor: Delegating to modified Editor
        getVisibleColumnFromPosition(position) {
            return this._targetEditor.getVisibleColumnFromPosition(position);
        }
        getPosition() {
            return this._targetEditor.getPosition();
        }
        setPosition(position, source = 'api') {
            this._targetEditor.setPosition(position, source);
        }
        revealLine(lineNumber, scrollType = 0 /* ScrollType.Smooth */) {
            this._targetEditor.revealLine(lineNumber, scrollType);
        }
        revealLineInCenter(lineNumber, scrollType = 0 /* ScrollType.Smooth */) {
            this._targetEditor.revealLineInCenter(lineNumber, scrollType);
        }
        revealLineInCenterIfOutsideViewport(lineNumber, scrollType = 0 /* ScrollType.Smooth */) {
            this._targetEditor.revealLineInCenterIfOutsideViewport(lineNumber, scrollType);
        }
        revealLineNearTop(lineNumber, scrollType = 0 /* ScrollType.Smooth */) {
            this._targetEditor.revealLineNearTop(lineNumber, scrollType);
        }
        revealPosition(position, scrollType = 0 /* ScrollType.Smooth */) {
            this._targetEditor.revealPosition(position, scrollType);
        }
        revealPositionInCenter(position, scrollType = 0 /* ScrollType.Smooth */) {
            this._targetEditor.revealPositionInCenter(position, scrollType);
        }
        revealPositionInCenterIfOutsideViewport(position, scrollType = 0 /* ScrollType.Smooth */) {
            this._targetEditor.revealPositionInCenterIfOutsideViewport(position, scrollType);
        }
        revealPositionNearTop(position, scrollType = 0 /* ScrollType.Smooth */) {
            this._targetEditor.revealPositionNearTop(position, scrollType);
        }
        getSelection() {
            return this._targetEditor.getSelection();
        }
        getSelections() {
            return this._targetEditor.getSelections();
        }
        setSelection(something, source = 'api') {
            this._targetEditor.setSelection(something, source);
        }
        setSelections(ranges, source = 'api') {
            this._targetEditor.setSelections(ranges, source);
        }
        revealLines(startLineNumber, endLineNumber, scrollType = 0 /* ScrollType.Smooth */) {
            this._targetEditor.revealLines(startLineNumber, endLineNumber, scrollType);
        }
        revealLinesInCenter(startLineNumber, endLineNumber, scrollType = 0 /* ScrollType.Smooth */) {
            this._targetEditor.revealLinesInCenter(startLineNumber, endLineNumber, scrollType);
        }
        revealLinesInCenterIfOutsideViewport(startLineNumber, endLineNumber, scrollType = 0 /* ScrollType.Smooth */) {
            this._targetEditor.revealLinesInCenterIfOutsideViewport(startLineNumber, endLineNumber, scrollType);
        }
        revealLinesNearTop(startLineNumber, endLineNumber, scrollType = 0 /* ScrollType.Smooth */) {
            this._targetEditor.revealLinesNearTop(startLineNumber, endLineNumber, scrollType);
        }
        revealRange(range, scrollType = 0 /* ScrollType.Smooth */, revealVerticalInCenter = false, revealHorizontal = true) {
            this._targetEditor.revealRange(range, scrollType, revealVerticalInCenter, revealHorizontal);
        }
        revealRangeInCenter(range, scrollType = 0 /* ScrollType.Smooth */) {
            this._targetEditor.revealRangeInCenter(range, scrollType);
        }
        revealRangeInCenterIfOutsideViewport(range, scrollType = 0 /* ScrollType.Smooth */) {
            this._targetEditor.revealRangeInCenterIfOutsideViewport(range, scrollType);
        }
        revealRangeNearTop(range, scrollType = 0 /* ScrollType.Smooth */) {
            this._targetEditor.revealRangeNearTop(range, scrollType);
        }
        revealRangeNearTopIfOutsideViewport(range, scrollType = 0 /* ScrollType.Smooth */) {
            this._targetEditor.revealRangeNearTopIfOutsideViewport(range, scrollType);
        }
        revealRangeAtTop(range, scrollType = 0 /* ScrollType.Smooth */) {
            this._targetEditor.revealRangeAtTop(range, scrollType);
        }
        getSupportedActions() {
            return this._targetEditor.getSupportedActions();
        }
        focus() {
            this._targetEditor.focus();
        }
        trigger(source, handlerId, payload) {
            this._targetEditor.trigger(source, handlerId, payload);
        }
        createDecorationsCollection(decorations) {
            return this._targetEditor.createDecorationsCollection(decorations);
        }
        changeDecorations(callback) {
            return this._targetEditor.changeDecorations(callback);
        }
    }
    exports.DelegatingEditor = DelegatingEditor;
});

define(__m[553/*vs/editor/browser/widget/multiDiffEditor/objectPool*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ObjectPool = void 0;
    class ObjectPool {
        constructor(_create) {
            this._create = _create;
            this._unused = new Set();
            this._used = new Set();
            this._itemData = new Map();
        }
        getUnusedObj(data) {
            let obj;
            if (this._unused.size === 0) {
                obj = this._create(data);
                this._itemData.set(obj, data);
            }
            else {
                const values = [...this._unused.values()];
                obj = values.find(obj => this._itemData.get(obj).getId() === data.getId()) ?? values[0];
                this._unused.delete(obj);
                this._itemData.set(obj, data);
                obj.setData(data);
            }
            this._used.add(obj);
            return {
                object: obj,
                dispose: () => {
                    this._used.delete(obj);
                    if (this._unused.size > 5) {
                        obj.dispose();
                    }
                    else {
                        this._unused.add(obj);
                    }
                }
            };
        }
        dispose() {
            for (const obj of this._used) {
                obj.dispose();
            }
            for (const obj of this._unused) {
                obj.dispose();
            }
            this._used.clear();
            this._unused.clear();
        }
    }
    exports.ObjectPool = ObjectPool;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[308/*vs/editor/common/config/diffEditor*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.diffEditorDefaultOptions = void 0;
    exports.diffEditorDefaultOptions = {
        enableSplitViewResizing: true,
        splitViewDefaultRatio: 0.5,
        renderSideBySide: true,
        renderMarginRevertIcon: true,
        renderGutterMenu: true,
        maxComputationTime: 5000,
        maxFileSize: 50,
        ignoreTrimWhitespace: true,
        renderIndicators: true,
        originalEditable: false,
        diffCodeLens: false,
        renderOverviewRuler: true,
        diffWordWrap: 'inherit',
        diffAlgorithm: 'advanced',
        accessibilityVerbose: false,
        experimental: {
            showMoves: false,
            showEmptyDecorations: true,
            useTrueInlineView: false,
        },
        hideUnchangedRegions: {
            enabled: false,
            contextLineCount: 3,
            minimumLineCount: 3,
            revealLineCount: 20,
        },
        isInEmbeddedEditor: false,
        onlyShowAccessibleDiffViewer: false,
        renderSideBySideInlineBreakpoint: 900,
        useInlineViewWhenSpaceIsLimited: true,
        compactMode: false,
    };
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[165/*vs/editor/common/config/editorZoom*/], __M([1/*require*/,0/*exports*/,6/*vs/base/common/event*/]), function (require, exports, event_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.EditorZoom = void 0;
    exports.EditorZoom = new class {
        constructor() {
            this._zoomLevel = 0;
            this._onDidChangeZoomLevel = new event_1.Emitter();
            this.onDidChangeZoomLevel = this._onDidChangeZoomLevel.event;
        }
        getZoomLevel() {
            return this._zoomLevel;
        }
        setZoomLevel(zoomLevel) {
            zoomLevel = Math.min(Math.max(-5, zoomLevel), 20);
            if (this._zoomLevel === zoomLevel) {
                return;
            }
            this._zoomLevel = zoomLevel;
            this._onDidChangeZoomLevel.fire(this._zoomLevel);
        }
    };
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[144/*vs/editor/common/core/characterClassifier*/], __M([1/*require*/,0/*exports*/,192/*vs/base/common/uint*/]), function (require, exports, uint_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CharacterSet = exports.CharacterClassifier = void 0;
    /**
     * A fast character classifier that uses a compact array for ASCII values.
     */
    class CharacterClassifier {
        constructor(_defaultValue) {
            const defaultValue = (0, uint_1.toUint8)(_defaultValue);
            this._defaultValue = defaultValue;
            this._asciiMap = CharacterClassifier._createAsciiMap(defaultValue);
            this._map = new Map();
        }
        static _createAsciiMap(defaultValue) {
            const asciiMap = new Uint8Array(256);
            asciiMap.fill(defaultValue);
            return asciiMap;
        }
        set(charCode, _value) {
            const value = (0, uint_1.toUint8)(_value);
            if (charCode >= 0 && charCode < 256) {
                this._asciiMap[charCode] = value;
            }
            else {
                this._map.set(charCode, value);
            }
        }
        get(charCode) {
            if (charCode >= 0 && charCode < 256) {
                return this._asciiMap[charCode];
            }
            else {
                return (this._map.get(charCode) || this._defaultValue);
            }
        }
        clear() {
            this._asciiMap.fill(this._defaultValue);
            this._map.clear();
        }
    }
    exports.CharacterClassifier = CharacterClassifier;
    class CharacterSet {
        constructor() {
            this._actual = new CharacterClassifier(0 /* Boolean.False */);
        }
        add(charCode) {
            this._actual.set(charCode, 1 /* Boolean.True */);
        }
        has(charCode) {
            return (this._actual.get(charCode) === 1 /* Boolean.True */);
        }
        clear() {
            return this._actual.clear();
        }
    }
    exports.CharacterSet = CharacterSet;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[94/*vs/editor/common/core/cursorColumns*/], __M([1/*require*/,0/*exports*/,11/*vs/base/common/strings*/]), function (require, exports, strings) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CursorColumns = void 0;
    /**
     * A column in a position is the gap between two adjacent characters. The methods here
     * work with a concept called "visible column". A visible column is a very rough approximation
     * of the horizontal screen position of a column. For example, using a tab size of 4:
     * ```txt
     * |<TAB>|<TAB>|T|ext
     * |     |     | \---- column = 4, visible column = 9
     * |     |     \------ column = 3, visible column = 8
     * |     \------------ column = 2, visible column = 4
     * \------------------ column = 1, visible column = 0
     * ```
     *
     * **NOTE**: Visual columns do not work well for RTL text or variable-width fonts or characters.
     *
     * **NOTE**: These methods work and make sense both on the model and on the view model.
     */
    class CursorColumns {
        static _nextVisibleColumn(codePoint, visibleColumn, tabSize) {
            if (codePoint === 9 /* CharCode.Tab */) {
                return CursorColumns.nextRenderTabStop(visibleColumn, tabSize);
            }
            if (strings.isFullWidthCharacter(codePoint) || strings.isEmojiImprecise(codePoint)) {
                return visibleColumn + 2;
            }
            return visibleColumn + 1;
        }
        /**
         * Returns a visible column from a column.
         * @see {@link CursorColumns}
         */
        static visibleColumnFromColumn(lineContent, column, tabSize) {
            const textLen = Math.min(column - 1, lineContent.length);
            const text = lineContent.substring(0, textLen);
            const iterator = new strings.GraphemeIterator(text);
            let result = 0;
            while (!iterator.eol()) {
                const codePoint = strings.getNextCodePoint(text, textLen, iterator.offset);
                iterator.nextGraphemeLength();
                result = this._nextVisibleColumn(codePoint, result, tabSize);
            }
            return result;
        }
        /**
         * Returns a column from a visible column.
         * @see {@link CursorColumns}
         */
        static columnFromVisibleColumn(lineContent, visibleColumn, tabSize) {
            if (visibleColumn <= 0) {
                return 1;
            }
            const lineContentLength = lineContent.length;
            const iterator = new strings.GraphemeIterator(lineContent);
            let beforeVisibleColumn = 0;
            let beforeColumn = 1;
            while (!iterator.eol()) {
                const codePoint = strings.getNextCodePoint(lineContent, lineContentLength, iterator.offset);
                iterator.nextGraphemeLength();
                const afterVisibleColumn = this._nextVisibleColumn(codePoint, beforeVisibleColumn, tabSize);
                const afterColumn = iterator.offset + 1;
                if (afterVisibleColumn >= visibleColumn) {
                    const beforeDelta = visibleColumn - beforeVisibleColumn;
                    const afterDelta = afterVisibleColumn - visibleColumn;
                    if (afterDelta < beforeDelta) {
                        return afterColumn;
                    }
                    else {
                        return beforeColumn;
                    }
                }
                beforeVisibleColumn = afterVisibleColumn;
                beforeColumn = afterColumn;
            }
            // walked the entire string
            return lineContentLength + 1;
        }
        /**
         * ATTENTION: This works with 0-based columns (as opposed to the regular 1-based columns)
         * @see {@link CursorColumns}
         */
        static nextRenderTabStop(visibleColumn, tabSize) {
            return visibleColumn + tabSize - visibleColumn % tabSize;
        }
        /**
         * ATTENTION: This works with 0-based columns (as opposed to the regular 1-based columns)
         * @see {@link CursorColumns}
         */
        static nextIndentTabStop(visibleColumn, indentSize) {
            return visibleColumn + indentSize - visibleColumn % indentSize;
        }
        /**
         * ATTENTION: This works with 0-based columns (as opposed to the regular 1-based columns)
         * @see {@link CursorColumns}
         */
        static prevRenderTabStop(column, tabSize) {
            return Math.max(0, column - 1 - (column - 1) % tabSize);
        }
        /**
         * ATTENTION: This works with 0-based columns (as opposed to the regular 1-based columns)
         * @see {@link CursorColumns}
         */
        static prevIndentTabStop(column, indentSize) {
            return Math.max(0, column - 1 - (column - 1) % indentSize);
        }
    }
    exports.CursorColumns = CursorColumns;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[145/*vs/editor/common/core/eolCounter*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.countEOL = countEOL;
    function countEOL(text) {
        let eolCount = 0;
        let firstLineLength = 0;
        let lastLineStart = 0;
        let eol = 0 /* StringEOL.Unknown */;
        for (let i = 0, len = text.length; i < len; i++) {
            const chr = text.charCodeAt(i);
            if (chr === 13 /* CharCode.CarriageReturn */) {
                if (eolCount === 0) {
                    firstLineLength = i;
                }
                eolCount++;
                if (i + 1 < len && text.charCodeAt(i + 1) === 10 /* CharCode.LineFeed */) {
                    // \r\n... case
                    eol |= 2 /* StringEOL.CRLF */;
                    i++; // skip \n
                }
                else {
                    // \r... case
                    eol |= 3 /* StringEOL.Invalid */;
                }
                lastLineStart = i + 1;
            }
            else if (chr === 10 /* CharCode.LineFeed */) {
                // \n... case
                eol |= 1 /* StringEOL.LF */;
                if (eolCount === 0) {
                    firstLineLength = i;
                }
                eolCount++;
                lastLineStart = i + 1;
            }
        }
        if (eolCount === 0) {
            firstLineLength = text.length;
        }
        return [eolCount, firstLineLength, text.length - lastLineStart, eol];
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[230/*vs/editor/common/core/indentation*/], __M([1/*require*/,0/*exports*/,11/*vs/base/common/strings*/,94/*vs/editor/common/core/cursorColumns*/]), function (require, exports, strings, cursorColumns_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.normalizeIndentation = normalizeIndentation;
    function _normalizeIndentationFromWhitespace(str, indentSize, insertSpaces) {
        let spacesCnt = 0;
        for (let i = 0; i < str.length; i++) {
            if (str.charAt(i) === '\t') {
                spacesCnt = cursorColumns_1.CursorColumns.nextIndentTabStop(spacesCnt, indentSize);
            }
            else {
                spacesCnt++;
            }
        }
        let result = '';
        if (!insertSpaces) {
            const tabsCnt = Math.floor(spacesCnt / indentSize);
            spacesCnt = spacesCnt % indentSize;
            for (let i = 0; i < tabsCnt; i++) {
                result += '\t';
            }
        }
        for (let i = 0; i < spacesCnt; i++) {
            result += ' ';
        }
        return result;
    }
    function normalizeIndentation(str, indentSize, insertSpaces) {
        let firstNonWhitespaceIndex = strings.firstNonWhitespaceIndex(str);
        if (firstNonWhitespaceIndex === -1) {
            firstNonWhitespaceIndex = str.length;
        }
        return _normalizeIndentationFromWhitespace(str.substring(0, firstNonWhitespaceIndex), indentSize, insertSpaces) + str.substring(firstNonWhitespaceIndex);
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[68/*vs/editor/common/core/offsetRange*/], __M([1/*require*/,0/*exports*/,8/*vs/base/common/errors*/]), function (require, exports, errors_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.OffsetRangeSet = exports.OffsetRange = void 0;
    /**
     * A range of offsets (0-based).
    */
    class OffsetRange {
        static addRange(range, sortedRanges) {
            let i = 0;
            while (i < sortedRanges.length && sortedRanges[i].endExclusive < range.start) {
                i++;
            }
            let j = i;
            while (j < sortedRanges.length && sortedRanges[j].start <= range.endExclusive) {
                j++;
            }
            if (i === j) {
                sortedRanges.splice(i, 0, range);
            }
            else {
                const start = Math.min(range.start, sortedRanges[i].start);
                const end = Math.max(range.endExclusive, sortedRanges[j - 1].endExclusive);
                sortedRanges.splice(i, j - i, new OffsetRange(start, end));
            }
        }
        static tryCreate(start, endExclusive) {
            if (start > endExclusive) {
                return undefined;
            }
            return new OffsetRange(start, endExclusive);
        }
        static ofLength(length) {
            return new OffsetRange(0, length);
        }
        static ofStartAndLength(start, length) {
            return new OffsetRange(start, start + length);
        }
        constructor(start, endExclusive) {
            this.start = start;
            this.endExclusive = endExclusive;
            if (start > endExclusive) {
                throw new errors_1.BugIndicatingError(`Invalid range: ${this.toString()}`);
            }
        }
        get isEmpty() {
            return this.start === this.endExclusive;
        }
        delta(offset) {
            return new OffsetRange(this.start + offset, this.endExclusive + offset);
        }
        deltaStart(offset) {
            return new OffsetRange(this.start + offset, this.endExclusive);
        }
        deltaEnd(offset) {
            return new OffsetRange(this.start, this.endExclusive + offset);
        }
        get length() {
            return this.endExclusive - this.start;
        }
        toString() {
            return `[${this.start}, ${this.endExclusive})`;
        }
        contains(offset) {
            return this.start <= offset && offset < this.endExclusive;
        }
        /**
         * for all numbers n: range1.contains(n) or range2.contains(n) => range1.join(range2).contains(n)
         * The joined range is the smallest range that contains both ranges.
         */
        join(other) {
            return new OffsetRange(Math.min(this.start, other.start), Math.max(this.endExclusive, other.endExclusive));
        }
        /**
         * for all numbers n: range1.contains(n) and range2.contains(n) <=> range1.intersect(range2).contains(n)
         *
         * The resulting range is empty if the ranges do not intersect, but touch.
         * If the ranges don't even touch, the result is undefined.
         */
        intersect(other) {
            const start = Math.max(this.start, other.start);
            const end = Math.min(this.endExclusive, other.endExclusive);
            if (start <= end) {
                return new OffsetRange(start, end);
            }
            return undefined;
        }
        intersects(other) {
            const start = Math.max(this.start, other.start);
            const end = Math.min(this.endExclusive, other.endExclusive);
            return start < end;
        }
        isBefore(other) {
            return this.endExclusive <= other.start;
        }
        isAfter(other) {
            return this.start >= other.endExclusive;
        }
        slice(arr) {
            return arr.slice(this.start, this.endExclusive);
        }
        substring(str) {
            return str.substring(this.start, this.endExclusive);
        }
        /**
         * Returns the given value if it is contained in this instance, otherwise the closest value that is contained.
         * The range must not be empty.
         */
        clip(value) {
            if (this.isEmpty) {
                throw new errors_1.BugIndicatingError(`Invalid clipping range: ${this.toString()}`);
            }
            return Math.max(this.start, Math.min(this.endExclusive - 1, value));
        }
        /**
         * Returns `r := value + k * length` such that `r` is contained in this range.
         * The range must not be empty.
         *
         * E.g. `[5, 10).clipCyclic(10) === 5`, `[5, 10).clipCyclic(11) === 6` and `[5, 10).clipCyclic(4) === 9`.
         */
        clipCyclic(value) {
            if (this.isEmpty) {
                throw new errors_1.BugIndicatingError(`Invalid clipping range: ${this.toString()}`);
            }
            if (value < this.start) {
                return this.endExclusive - ((this.start - value) % this.length);
            }
            if (value >= this.endExclusive) {
                return this.start + ((value - this.start) % this.length);
            }
            return value;
        }
        forEach(f) {
            for (let i = this.start; i < this.endExclusive; i++) {
                f(i);
            }
        }
    }
    exports.OffsetRange = OffsetRange;
    class OffsetRangeSet {
        constructor() {
            this._sortedRanges = [];
        }
        addRange(range) {
            let i = 0;
            while (i < this._sortedRanges.length && this._sortedRanges[i].endExclusive < range.start) {
                i++;
            }
            let j = i;
            while (j < this._sortedRanges.length && this._sortedRanges[j].start <= range.endExclusive) {
                j++;
            }
            if (i === j) {
                this._sortedRanges.splice(i, 0, range);
            }
            else {
                const start = Math.min(range.start, this._sortedRanges[i].start);
                const end = Math.max(range.endExclusive, this._sortedRanges[j - 1].endExclusive);
                this._sortedRanges.splice(i, j - i, new OffsetRange(start, end));
            }
        }
        toString() {
            return this._sortedRanges.map(r => r.toString()).join(', ');
        }
        /**
         * Returns of there is a value that is contained in this instance and the given range.
         */
        intersectsStrict(other) {
            // TODO use binary search
            let i = 0;
            while (i < this._sortedRanges.length && this._sortedRanges[i].endExclusive <= other.start) {
                i++;
            }
            return i < this._sortedRanges.length && this._sortedRanges[i].start < other.endExclusive;
        }
        intersectWithRange(other) {
            // TODO use binary search + slice
            const result = new OffsetRangeSet();
            for (const range of this._sortedRanges) {
                const intersection = range.intersect(other);
                if (intersection) {
                    result.addRange(intersection);
                }
            }
            return result;
        }
        intersectWithRangeLength(other) {
            return this.intersectWithRange(other).length;
        }
        get length() {
            return this._sortedRanges.reduce((prev, cur) => prev + cur.length, 0);
        }
    }
    exports.OffsetRangeSet = OffsetRangeSet;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[9/*vs/editor/common/core/position*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Position = void 0;
    /**
     * A position in the editor.
     */
    class Position {
        constructor(lineNumber, column) {
            this.lineNumber = lineNumber;
            this.column = column;
        }
        /**
         * Create a new position from this position.
         *
         * @param newLineNumber new line number
         * @param newColumn new column
         */
        with(newLineNumber = this.lineNumber, newColumn = this.column) {
            if (newLineNumber === this.lineNumber && newColumn === this.column) {
                return this;
            }
            else {
                return new Position(newLineNumber, newColumn);
            }
        }
        /**
         * Derive a new position from this position.
         *
         * @param deltaLineNumber line number delta
         * @param deltaColumn column delta
         */
        delta(deltaLineNumber = 0, deltaColumn = 0) {
            return this.with(this.lineNumber + deltaLineNumber, this.column + deltaColumn);
        }
        /**
         * Test if this position equals other position
         */
        equals(other) {
            return Position.equals(this, other);
        }
        /**
         * Test if position `a` equals position `b`
         */
        static equals(a, b) {
            if (!a && !b) {
                return true;
            }
            return (!!a &&
                !!b &&
                a.lineNumber === b.lineNumber &&
                a.column === b.column);
        }
        /**
         * Test if this position is before other position.
         * If the two positions are equal, the result will be false.
         */
        isBefore(other) {
            return Position.isBefore(this, other);
        }
        /**
         * Test if position `a` is before position `b`.
         * If the two positions are equal, the result will be false.
         */
        static isBefore(a, b) {
            if (a.lineNumber < b.lineNumber) {
                return true;
            }
            if (b.lineNumber < a.lineNumber) {
                return false;
            }
            return a.column < b.column;
        }
        /**
         * Test if this position is before other position.
         * If the two positions are equal, the result will be true.
         */
        isBeforeOrEqual(other) {
            return Position.isBeforeOrEqual(this, other);
        }
        /**
         * Test if position `a` is before position `b`.
         * If the two positions are equal, the result will be true.
         */
        static isBeforeOrEqual(a, b) {
            if (a.lineNumber < b.lineNumber) {
                return true;
            }
            if (b.lineNumber < a.lineNumber) {
                return false;
            }
            return a.column <= b.column;
        }
        /**
         * A function that compares positions, useful for sorting
         */
        static compare(a, b) {
            const aLineNumber = a.lineNumber | 0;
            const bLineNumber = b.lineNumber | 0;
            if (aLineNumber === bLineNumber) {
                const aColumn = a.column | 0;
                const bColumn = b.column | 0;
                return aColumn - bColumn;
            }
            return aLineNumber - bLineNumber;
        }
        /**
         * Clone this position.
         */
        clone() {
            return new Position(this.lineNumber, this.column);
        }
        /**
         * Convert to a human-readable representation.
         */
        toString() {
            return '(' + this.lineNumber + ',' + this.column + ')';
        }
        // ---
        /**
         * Create a `Position` from an `IPosition`.
         */
        static lift(pos) {
            return new Position(pos.lineNumber, pos.column);
        }
        /**
         * Test if `obj` is an `IPosition`.
         */
        static isIPosition(obj) {
            return (obj
                && (typeof obj.lineNumber === 'number')
                && (typeof obj.column === 'number'));
        }
        toJSON() {
            return {
                lineNumber: this.lineNumber,
                column: this.column
            };
        }
    }
    exports.Position = Position;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[309/*vs/editor/browser/view/viewUserInputEvents*/], __M([1/*require*/,0/*exports*/,9/*vs/editor/common/core/position*/]), function (require, exports, position_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ViewUserInputEvents = void 0;
    class ViewUserInputEvents {
        constructor(coordinatesConverter) {
            this.onKeyDown = null;
            this.onKeyUp = null;
            this.onContextMenu = null;
            this.onMouseMove = null;
            this.onMouseLeave = null;
            this.onMouseDown = null;
            this.onMouseUp = null;
            this.onMouseDrag = null;
            this.onMouseDrop = null;
            this.onMouseDropCanceled = null;
            this.onMouseWheel = null;
            this._coordinatesConverter = coordinatesConverter;
        }
        emitKeyDown(e) {
            this.onKeyDown?.(e);
        }
        emitKeyUp(e) {
            this.onKeyUp?.(e);
        }
        emitContextMenu(e) {
            this.onContextMenu?.(this._convertViewToModelMouseEvent(e));
        }
        emitMouseMove(e) {
            this.onMouseMove?.(this._convertViewToModelMouseEvent(e));
        }
        emitMouseLeave(e) {
            this.onMouseLeave?.(this._convertViewToModelMouseEvent(e));
        }
        emitMouseDown(e) {
            this.onMouseDown?.(this._convertViewToModelMouseEvent(e));
        }
        emitMouseUp(e) {
            this.onMouseUp?.(this._convertViewToModelMouseEvent(e));
        }
        emitMouseDrag(e) {
            this.onMouseDrag?.(this._convertViewToModelMouseEvent(e));
        }
        emitMouseDrop(e) {
            this.onMouseDrop?.(this._convertViewToModelMouseEvent(e));
        }
        emitMouseDropCanceled() {
            this.onMouseDropCanceled?.();
        }
        emitMouseWheel(e) {
            this.onMouseWheel?.(e);
        }
        _convertViewToModelMouseEvent(e) {
            if (e.target) {
                return {
                    event: e.event,
                    target: this._convertViewToModelMouseTarget(e.target)
                };
            }
            return e;
        }
        _convertViewToModelMouseTarget(target) {
            return ViewUserInputEvents.convertViewToModelMouseTarget(target, this._coordinatesConverter);
        }
        static convertViewToModelMouseTarget(target, coordinatesConverter) {
            const result = { ...target };
            if (result.position) {
                result.position = coordinatesConverter.convertViewPositionToModelPosition(result.position);
            }
            if (result.range) {
                result.range = coordinatesConverter.convertViewRangeToModelRange(result.range);
            }
            if (result.type === 5 /* MouseTargetType.GUTTER_VIEW_ZONE */ || result.type === 8 /* MouseTargetType.CONTENT_VIEW_ZONE */) {
                result.detail = this.convertViewToModelViewZoneData(result.detail, coordinatesConverter);
            }
            return result;
        }
        static convertViewToModelViewZoneData(data, coordinatesConverter) {
            return {
                viewZoneId: data.viewZoneId,
                positionBefore: data.positionBefore ? coordinatesConverter.convertViewPositionToModelPosition(data.positionBefore) : data.positionBefore,
                positionAfter: data.positionAfter ? coordinatesConverter.convertViewPositionToModelPosition(data.positionAfter) : data.positionAfter,
                position: coordinatesConverter.convertViewPositionToModelPosition(data.position),
                afterLineNumber: coordinatesConverter.convertViewPositionToModelPosition(new position_1.Position(data.afterLineNumber, 1)).lineNumber,
            };
        }
    }
    exports.ViewUserInputEvents = ViewUserInputEvents;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[4/*vs/editor/common/core/range*/], __M([1/*require*/,0/*exports*/,9/*vs/editor/common/core/position*/]), function (require, exports, position_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Range = void 0;
    /**
     * A range in the editor. (startLineNumber,startColumn) is <= (endLineNumber,endColumn)
     */
    class Range {
        constructor(startLineNumber, startColumn, endLineNumber, endColumn) {
            if ((startLineNumber > endLineNumber) || (startLineNumber === endLineNumber && startColumn > endColumn)) {
                this.startLineNumber = endLineNumber;
                this.startColumn = endColumn;
                this.endLineNumber = startLineNumber;
                this.endColumn = startColumn;
            }
            else {
                this.startLineNumber = startLineNumber;
                this.startColumn = startColumn;
                this.endLineNumber = endLineNumber;
                this.endColumn = endColumn;
            }
        }
        /**
         * Test if this range is empty.
         */
        isEmpty() {
            return Range.isEmpty(this);
        }
        /**
         * Test if `range` is empty.
         */
        static isEmpty(range) {
            return (range.startLineNumber === range.endLineNumber && range.startColumn === range.endColumn);
        }
        /**
         * Test if position is in this range. If the position is at the edges, will return true.
         */
        containsPosition(position) {
            return Range.containsPosition(this, position);
        }
        /**
         * Test if `position` is in `range`. If the position is at the edges, will return true.
         */
        static containsPosition(range, position) {
            if (position.lineNumber < range.startLineNumber || position.lineNumber > range.endLineNumber) {
                return false;
            }
            if (position.lineNumber === range.startLineNumber && position.column < range.startColumn) {
                return false;
            }
            if (position.lineNumber === range.endLineNumber && position.column > range.endColumn) {
                return false;
            }
            return true;
        }
        /**
         * Test if `position` is in `range`. If the position is at the edges, will return false.
         * @internal
         */
        static strictContainsPosition(range, position) {
            if (position.lineNumber < range.startLineNumber || position.lineNumber > range.endLineNumber) {
                return false;
            }
            if (position.lineNumber === range.startLineNumber && position.column <= range.startColumn) {
                return false;
            }
            if (position.lineNumber === range.endLineNumber && position.column >= range.endColumn) {
                return false;
            }
            return true;
        }
        /**
         * Test if range is in this range. If the range is equal to this range, will return true.
         */
        containsRange(range) {
            return Range.containsRange(this, range);
        }
        /**
         * Test if `otherRange` is in `range`. If the ranges are equal, will return true.
         */
        static containsRange(range, otherRange) {
            if (otherRange.startLineNumber < range.startLineNumber || otherRange.endLineNumber < range.startLineNumber) {
                return false;
            }
            if (otherRange.startLineNumber > range.endLineNumber || otherRange.endLineNumber > range.endLineNumber) {
                return false;
            }
            if (otherRange.startLineNumber === range.startLineNumber && otherRange.startColumn < range.startColumn) {
                return false;
            }
            if (otherRange.endLineNumber === range.endLineNumber && otherRange.endColumn > range.endColumn) {
                return false;
            }
            return true;
        }
        /**
         * Test if `range` is strictly in this range. `range` must start after and end before this range for the result to be true.
         */
        strictContainsRange(range) {
            return Range.strictContainsRange(this, range);
        }
        /**
         * Test if `otherRange` is strictly in `range` (must start after, and end before). If the ranges are equal, will return false.
         */
        static strictContainsRange(range, otherRange) {
            if (otherRange.startLineNumber < range.startLineNumber || otherRange.endLineNumber < range.startLineNumber) {
                return false;
            }
            if (otherRange.startLineNumber > range.endLineNumber || otherRange.endLineNumber > range.endLineNumber) {
                return false;
            }
            if (otherRange.startLineNumber === range.startLineNumber && otherRange.startColumn <= range.startColumn) {
                return false;
            }
            if (otherRange.endLineNumber === range.endLineNumber && otherRange.endColumn >= range.endColumn) {
                return false;
            }
            return true;
        }
        /**
         * A reunion of the two ranges.
         * The smallest position will be used as the start point, and the largest one as the end point.
         */
        plusRange(range) {
            return Range.plusRange(this, range);
        }
        /**
         * A reunion of the two ranges.
         * The smallest position will be used as the start point, and the largest one as the end point.
         */
        static plusRange(a, b) {
            let startLineNumber;
            let startColumn;
            let endLineNumber;
            let endColumn;
            if (b.startLineNumber < a.startLineNumber) {
                startLineNumber = b.startLineNumber;
                startColumn = b.startColumn;
            }
            else if (b.startLineNumber === a.startLineNumber) {
                startLineNumber = b.startLineNumber;
                startColumn = Math.min(b.startColumn, a.startColumn);
            }
            else {
                startLineNumber = a.startLineNumber;
                startColumn = a.startColumn;
            }
            if (b.endLineNumber > a.endLineNumber) {
                endLineNumber = b.endLineNumber;
                endColumn = b.endColumn;
            }
            else if (b.endLineNumber === a.endLineNumber) {
                endLineNumber = b.endLineNumber;
                endColumn = Math.max(b.endColumn, a.endColumn);
            }
            else {
                endLineNumber = a.endLineNumber;
                endColumn = a.endColumn;
            }
            return new Range(startLineNumber, startColumn, endLineNumber, endColumn);
        }
        /**
         * A intersection of the two ranges.
         */
        intersectRanges(range) {
            return Range.intersectRanges(this, range);
        }
        /**
         * A intersection of the two ranges.
         */
        static intersectRanges(a, b) {
            let resultStartLineNumber = a.startLineNumber;
            let resultStartColumn = a.startColumn;
            let resultEndLineNumber = a.endLineNumber;
            let resultEndColumn = a.endColumn;
            const otherStartLineNumber = b.startLineNumber;
            const otherStartColumn = b.startColumn;
            const otherEndLineNumber = b.endLineNumber;
            const otherEndColumn = b.endColumn;
            if (resultStartLineNumber < otherStartLineNumber) {
                resultStartLineNumber = otherStartLineNumber;
                resultStartColumn = otherStartColumn;
            }
            else if (resultStartLineNumber === otherStartLineNumber) {
                resultStartColumn = Math.max(resultStartColumn, otherStartColumn);
            }
            if (resultEndLineNumber > otherEndLineNumber) {
                resultEndLineNumber = otherEndLineNumber;
                resultEndColumn = otherEndColumn;
            }
            else if (resultEndLineNumber === otherEndLineNumber) {
                resultEndColumn = Math.min(resultEndColumn, otherEndColumn);
            }
            // Check if selection is now empty
            if (resultStartLineNumber > resultEndLineNumber) {
                return null;
            }
            if (resultStartLineNumber === resultEndLineNumber && resultStartColumn > resultEndColumn) {
                return null;
            }
            return new Range(resultStartLineNumber, resultStartColumn, resultEndLineNumber, resultEndColumn);
        }
        /**
         * Test if this range equals other.
         */
        equalsRange(other) {
            return Range.equalsRange(this, other);
        }
        /**
         * Test if range `a` equals `b`.
         */
        static equalsRange(a, b) {
            if (!a && !b) {
                return true;
            }
            return (!!a &&
                !!b &&
                a.startLineNumber === b.startLineNumber &&
                a.startColumn === b.startColumn &&
                a.endLineNumber === b.endLineNumber &&
                a.endColumn === b.endColumn);
        }
        /**
         * Return the end position (which will be after or equal to the start position)
         */
        getEndPosition() {
            return Range.getEndPosition(this);
        }
        /**
         * Return the end position (which will be after or equal to the start position)
         */
        static getEndPosition(range) {
            return new position_1.Position(range.endLineNumber, range.endColumn);
        }
        /**
         * Return the start position (which will be before or equal to the end position)
         */
        getStartPosition() {
            return Range.getStartPosition(this);
        }
        /**
         * Return the start position (which will be before or equal to the end position)
         */
        static getStartPosition(range) {
            return new position_1.Position(range.startLineNumber, range.startColumn);
        }
        /**
         * Transform to a user presentable string representation.
         */
        toString() {
            return '[' + this.startLineNumber + ',' + this.startColumn + ' -> ' + this.endLineNumber + ',' + this.endColumn + ']';
        }
        /**
         * Create a new range using this range's start position, and using endLineNumber and endColumn as the end position.
         */
        setEndPosition(endLineNumber, endColumn) {
            return new Range(this.startLineNumber, this.startColumn, endLineNumber, endColumn);
        }
        /**
         * Create a new range using this range's end position, and using startLineNumber and startColumn as the start position.
         */
        setStartPosition(startLineNumber, startColumn) {
            return new Range(startLineNumber, startColumn, this.endLineNumber, this.endColumn);
        }
        /**
         * Create a new empty range using this range's start position.
         */
        collapseToStart() {
            return Range.collapseToStart(this);
        }
        /**
         * Create a new empty range using this range's start position.
         */
        static collapseToStart(range) {
            return new Range(range.startLineNumber, range.startColumn, range.startLineNumber, range.startColumn);
        }
        /**
         * Create a new empty range using this range's end position.
         */
        collapseToEnd() {
            return Range.collapseToEnd(this);
        }
        /**
         * Create a new empty range using this range's end position.
         */
        static collapseToEnd(range) {
            return new Range(range.endLineNumber, range.endColumn, range.endLineNumber, range.endColumn);
        }
        /**
         * Moves the range by the given amount of lines.
         */
        delta(lineCount) {
            return new Range(this.startLineNumber + lineCount, this.startColumn, this.endLineNumber + lineCount, this.endColumn);
        }
        // ---
        static fromPositions(start, end = start) {
            return new Range(start.lineNumber, start.column, end.lineNumber, end.column);
        }
        static lift(range) {
            if (!range) {
                return null;
            }
            return new Range(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn);
        }
        /**
         * Test if `obj` is an `IRange`.
         */
        static isIRange(obj) {
            return (obj
                && (typeof obj.startLineNumber === 'number')
                && (typeof obj.startColumn === 'number')
                && (typeof obj.endLineNumber === 'number')
                && (typeof obj.endColumn === 'number'));
        }
        /**
         * Test if the two ranges are touching in any way.
         */
        static areIntersectingOrTouching(a, b) {
            // Check if `a` is before `b`
            if (a.endLineNumber < b.startLineNumber || (a.endLineNumber === b.startLineNumber && a.endColumn < b.startColumn)) {
                return false;
            }
            // Check if `b` is before `a`
            if (b.endLineNumber < a.startLineNumber || (b.endLineNumber === a.startLineNumber && b.endColumn < a.startColumn)) {
                return false;
            }
            // These ranges must intersect
            return true;
        }
        /**
         * Test if the two ranges are intersecting. If the ranges are touching it returns true.
         */
        static areIntersecting(a, b) {
            // Check if `a` is before `b`
            if (a.endLineNumber < b.startLineNumber || (a.endLineNumber === b.startLineNumber && a.endColumn <= b.startColumn)) {
                return false;
            }
            // Check if `b` is before `a`
            if (b.endLineNumber < a.startLineNumber || (b.endLineNumber === a.startLineNumber && b.endColumn <= a.startColumn)) {
                return false;
            }
            // These ranges must intersect
            return true;
        }
        /**
         * A function that compares ranges, useful for sorting ranges
         * It will first compare ranges on the startPosition and then on the endPosition
         */
        static compareRangesUsingStarts(a, b) {
            if (a && b) {
                const aStartLineNumber = a.startLineNumber | 0;
                const bStartLineNumber = b.startLineNumber | 0;
                if (aStartLineNumber === bStartLineNumber) {
                    const aStartColumn = a.startColumn | 0;
                    const bStartColumn = b.startColumn | 0;
                    if (aStartColumn === bStartColumn) {
                        const aEndLineNumber = a.endLineNumber | 0;
                        const bEndLineNumber = b.endLineNumber | 0;
                        if (aEndLineNumber === bEndLineNumber) {
                            const aEndColumn = a.endColumn | 0;
                            const bEndColumn = b.endColumn | 0;
                            return aEndColumn - bEndColumn;
                        }
                        return aEndLineNumber - bEndLineNumber;
                    }
                    return aStartColumn - bStartColumn;
                }
                return aStartLineNumber - bStartLineNumber;
            }
            const aExists = (a ? 1 : 0);
            const bExists = (b ? 1 : 0);
            return aExists - bExists;
        }
        /**
         * A function that compares ranges, useful for sorting ranges
         * It will first compare ranges on the endPosition and then on the startPosition
         */
        static compareRangesUsingEnds(a, b) {
            if (a.endLineNumber === b.endLineNumber) {
                if (a.endColumn === b.endColumn) {
                    if (a.startLineNumber === b.startLineNumber) {
                        return a.startColumn - b.startColumn;
                    }
                    return a.startLineNumber - b.startLineNumber;
                }
                return a.endColumn - b.endColumn;
            }
            return a.endLineNumber - b.endLineNumber;
        }
        /**
         * Test if the range spans multiple lines.
         */
        static spansMultipleLines(range) {
            return range.endLineNumber > range.startLineNumber;
        }
        toJSON() {
            return this;
        }
    }
    exports.Range = Range;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[310/*vs/editor/browser/controller/textAreaState*/], __M([1/*require*/,0/*exports*/,11/*vs/base/common/strings*/,4/*vs/editor/common/core/range*/]), function (require, exports, strings, range_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.PagedScreenReaderStrategy = exports.TextAreaState = exports._debugComposition = void 0;
    exports._debugComposition = false;
    class TextAreaState {
        static { this.EMPTY = new TextAreaState('', 0, 0, null, undefined); }
        constructor(value, 
        /** the offset where selection starts inside `value` */
        selectionStart, 
        /** the offset where selection ends inside `value` */
        selectionEnd, 
        /** the editor range in the view coordinate system that matches the selection inside `value` */
        selection, 
        /** the visible line count (wrapped, not necessarily matching \n characters) for the text in `value` before `selectionStart` */
        newlineCountBeforeSelection) {
            this.value = value;
            this.selectionStart = selectionStart;
            this.selectionEnd = selectionEnd;
            this.selection = selection;
            this.newlineCountBeforeSelection = newlineCountBeforeSelection;
        }
        toString() {
            return `[ <${this.value}>, selectionStart: ${this.selectionStart}, selectionEnd: ${this.selectionEnd}]`;
        }
        static readFromTextArea(textArea, previousState) {
            const value = textArea.getValue();
            const selectionStart = textArea.getSelectionStart();
            const selectionEnd = textArea.getSelectionEnd();
            let newlineCountBeforeSelection = undefined;
            if (previousState) {
                const valueBeforeSelectionStart = value.substring(0, selectionStart);
                const previousValueBeforeSelectionStart = previousState.value.substring(0, previousState.selectionStart);
                if (valueBeforeSelectionStart === previousValueBeforeSelectionStart) {
                    newlineCountBeforeSelection = previousState.newlineCountBeforeSelection;
                }
            }
            return new TextAreaState(value, selectionStart, selectionEnd, null, newlineCountBeforeSelection);
        }
        collapseSelection() {
            if (this.selectionStart === this.value.length) {
                return this;
            }
            return new TextAreaState(this.value, this.value.length, this.value.length, null, undefined);
        }
        writeToTextArea(reason, textArea, select) {
            if (exports._debugComposition) {
                console.log(`writeToTextArea ${reason}: ${this.toString()}`);
            }
            textArea.setValue(reason, this.value);
            if (select) {
                textArea.setSelectionRange(reason, this.selectionStart, this.selectionEnd);
            }
        }
        deduceEditorPosition(offset) {
            if (offset <= this.selectionStart) {
                const str = this.value.substring(offset, this.selectionStart);
                return this._finishDeduceEditorPosition(this.selection?.getStartPosition() ?? null, str, -1);
            }
            if (offset >= this.selectionEnd) {
                const str = this.value.substring(this.selectionEnd, offset);
                return this._finishDeduceEditorPosition(this.selection?.getEndPosition() ?? null, str, 1);
            }
            const str1 = this.value.substring(this.selectionStart, offset);
            if (str1.indexOf(String.fromCharCode(8230)) === -1) {
                return this._finishDeduceEditorPosition(this.selection?.getStartPosition() ?? null, str1, 1);
            }
            const str2 = this.value.substring(offset, this.selectionEnd);
            return this._finishDeduceEditorPosition(this.selection?.getEndPosition() ?? null, str2, -1);
        }
        _finishDeduceEditorPosition(anchor, deltaText, signum) {
            let lineFeedCnt = 0;
            let lastLineFeedIndex = -1;
            while ((lastLineFeedIndex = deltaText.indexOf('\n', lastLineFeedIndex + 1)) !== -1) {
                lineFeedCnt++;
            }
            return [anchor, signum * deltaText.length, lineFeedCnt];
        }
        static deduceInput(previousState, currentState, couldBeEmojiInput) {
            if (!previousState) {
                // This is the EMPTY state
                return {
                    text: '',
                    replacePrevCharCnt: 0,
                    replaceNextCharCnt: 0,
                    positionDelta: 0
                };
            }
            if (exports._debugComposition) {
                console.log('------------------------deduceInput');
                console.log(`PREVIOUS STATE: ${previousState.toString()}`);
                console.log(`CURRENT STATE: ${currentState.toString()}`);
            }
            const prefixLength = Math.min(strings.commonPrefixLength(previousState.value, currentState.value), previousState.selectionStart, currentState.selectionStart);
            const suffixLength = Math.min(strings.commonSuffixLength(previousState.value, currentState.value), previousState.value.length - previousState.selectionEnd, currentState.value.length - currentState.selectionEnd);
            const previousValue = previousState.value.substring(prefixLength, previousState.value.length - suffixLength);
            const currentValue = currentState.value.substring(prefixLength, currentState.value.length - suffixLength);
            const previousSelectionStart = previousState.selectionStart - prefixLength;
            const previousSelectionEnd = previousState.selectionEnd - prefixLength;
            const currentSelectionStart = currentState.selectionStart - prefixLength;
            const currentSelectionEnd = currentState.selectionEnd - prefixLength;
            if (exports._debugComposition) {
                console.log(`AFTER DIFFING PREVIOUS STATE: <${previousValue}>, selectionStart: ${previousSelectionStart}, selectionEnd: ${previousSelectionEnd}`);
                console.log(`AFTER DIFFING CURRENT STATE: <${currentValue}>, selectionStart: ${currentSelectionStart}, selectionEnd: ${currentSelectionEnd}`);
            }
            if (currentSelectionStart === currentSelectionEnd) {
                // no current selection
                const replacePreviousCharacters = (previousState.selectionStart - prefixLength);
                if (exports._debugComposition) {
                    console.log(`REMOVE PREVIOUS: ${replacePreviousCharacters} chars`);
                }
                return {
                    text: currentValue,
                    replacePrevCharCnt: replacePreviousCharacters,
                    replaceNextCharCnt: 0,
                    positionDelta: 0
                };
            }
            // there is a current selection => composition case
            const replacePreviousCharacters = previousSelectionEnd - previousSelectionStart;
            return {
                text: currentValue,
                replacePrevCharCnt: replacePreviousCharacters,
                replaceNextCharCnt: 0,
                positionDelta: 0
            };
        }
        static deduceAndroidCompositionInput(previousState, currentState) {
            if (!previousState) {
                // This is the EMPTY state
                return {
                    text: '',
                    replacePrevCharCnt: 0,
                    replaceNextCharCnt: 0,
                    positionDelta: 0
                };
            }
            if (exports._debugComposition) {
                console.log('------------------------deduceAndroidCompositionInput');
                console.log(`PREVIOUS STATE: ${previousState.toString()}`);
                console.log(`CURRENT STATE: ${currentState.toString()}`);
            }
            if (previousState.value === currentState.value) {
                return {
                    text: '',
                    replacePrevCharCnt: 0,
                    replaceNextCharCnt: 0,
                    positionDelta: currentState.selectionEnd - previousState.selectionEnd
                };
            }
            const prefixLength = Math.min(strings.commonPrefixLength(previousState.value, currentState.value), previousState.selectionEnd);
            const suffixLength = Math.min(strings.commonSuffixLength(previousState.value, currentState.value), previousState.value.length - previousState.selectionEnd);
            const previousValue = previousState.value.substring(prefixLength, previousState.value.length - suffixLength);
            const currentValue = currentState.value.substring(prefixLength, currentState.value.length - suffixLength);
            const previousSelectionStart = previousState.selectionStart - prefixLength;
            const previousSelectionEnd = previousState.selectionEnd - prefixLength;
            const currentSelectionStart = currentState.selectionStart - prefixLength;
            const currentSelectionEnd = currentState.selectionEnd - prefixLength;
            if (exports._debugComposition) {
                console.log(`AFTER DIFFING PREVIOUS STATE: <${previousValue}>, selectionStart: ${previousSelectionStart}, selectionEnd: ${previousSelectionEnd}`);
                console.log(`AFTER DIFFING CURRENT STATE: <${currentValue}>, selectionStart: ${currentSelectionStart}, selectionEnd: ${currentSelectionEnd}`);
            }
            return {
                text: currentValue,
                replacePrevCharCnt: previousSelectionEnd,
                replaceNextCharCnt: previousValue.length - previousSelectionEnd,
                positionDelta: currentSelectionEnd - currentValue.length
            };
        }
    }
    exports.TextAreaState = TextAreaState;
    class PagedScreenReaderStrategy {
        static _getPageOfLine(lineNumber, linesPerPage) {
            return Math.floor((lineNumber - 1) / linesPerPage);
        }
        static _getRangeForPage(page, linesPerPage) {
            const offset = page * linesPerPage;
            const startLineNumber = offset + 1;
            const endLineNumber = offset + linesPerPage;
            return new range_1.Range(startLineNumber, 1, endLineNumber + 1, 1);
        }
        static fromEditorSelection(model, selection, linesPerPage, trimLongText) {
            // Chromium handles very poorly text even of a few thousand chars
            // Cut text to avoid stalling the entire UI
            const LIMIT_CHARS = 500;
            const selectionStartPage = PagedScreenReaderStrategy._getPageOfLine(selection.startLineNumber, linesPerPage);
            const selectionStartPageRange = PagedScreenReaderStrategy._getRangeForPage(selectionStartPage, linesPerPage);
            const selectionEndPage = PagedScreenReaderStrategy._getPageOfLine(selection.endLineNumber, linesPerPage);
            const selectionEndPageRange = PagedScreenReaderStrategy._getRangeForPage(selectionEndPage, linesPerPage);
            let pretextRange = selectionStartPageRange.intersectRanges(new range_1.Range(1, 1, selection.startLineNumber, selection.startColumn));
            if (trimLongText && model.getValueLengthInRange(pretextRange, 1 /* EndOfLinePreference.LF */) > LIMIT_CHARS) {
                const pretextStart = model.modifyPosition(pretextRange.getEndPosition(), -LIMIT_CHARS);
                pretextRange = range_1.Range.fromPositions(pretextStart, pretextRange.getEndPosition());
            }
            const pretext = model.getValueInRange(pretextRange, 1 /* EndOfLinePreference.LF */);
            const lastLine = model.getLineCount();
            const lastLineMaxColumn = model.getLineMaxColumn(lastLine);
            let posttextRange = selectionEndPageRange.intersectRanges(new range_1.Range(selection.endLineNumber, selection.endColumn, lastLine, lastLineMaxColumn));
            if (trimLongText && model.getValueLengthInRange(posttextRange, 1 /* EndOfLinePreference.LF */) > LIMIT_CHARS) {
                const posttextEnd = model.modifyPosition(posttextRange.getStartPosition(), LIMIT_CHARS);
                posttextRange = range_1.Range.fromPositions(posttextRange.getStartPosition(), posttextEnd);
            }
            const posttext = model.getValueInRange(posttextRange, 1 /* EndOfLinePreference.LF */);
            let text;
            if (selectionStartPage === selectionEndPage || selectionStartPage + 1 === selectionEndPage) {
                // take full selection
                text = model.getValueInRange(selection, 1 /* EndOfLinePreference.LF */);
            }
            else {
                const selectionRange1 = selectionStartPageRange.intersectRanges(selection);
                const selectionRange2 = selectionEndPageRange.intersectRanges(selection);
                text = (model.getValueInRange(selectionRange1, 1 /* EndOfLinePreference.LF */)
                    + String.fromCharCode(8230)
                    + model.getValueInRange(selectionRange2, 1 /* EndOfLinePreference.LF */));
            }
            if (trimLongText && text.length > 2 * LIMIT_CHARS) {
                text = text.substring(0, LIMIT_CHARS) + String.fromCharCode(8230) + text.substring(text.length - LIMIT_CHARS, text.length);
            }
            return new TextAreaState(pretext + text + posttext, pretext.length, pretext.length + text.length, selection, pretextRange.endLineNumber - pretextRange.startLineNumber);
        }
    }
    exports.PagedScreenReaderStrategy = PagedScreenReaderStrategy;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[75/*vs/editor/common/core/editOperation*/], __M([1/*require*/,0/*exports*/,4/*vs/editor/common/core/range*/]), function (require, exports, range_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.EditOperation = void 0;
    class EditOperation {
        static insert(position, text) {
            return {
                range: new range_1.Range(position.lineNumber, position.column, position.lineNumber, position.column),
                text: text,
                forceMoveMarkers: true
            };
        }
        static delete(range) {
            return {
                range: range,
                text: null
            };
        }
        static replace(range, text) {
            return {
                range: range,
                text: text
            };
        }
        static replaceMove(range, text) {
            return {
                range: range,
                text: text,
                forceMoveMarkers: true
            };
        }
    }
    exports.EditOperation = EditOperation;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[554/*vs/editor/common/commands/trimTrailingWhitespaceCommand*/], __M([1/*require*/,0/*exports*/,11/*vs/base/common/strings*/,75/*vs/editor/common/core/editOperation*/,4/*vs/editor/common/core/range*/]), function (require, exports, strings, editOperation_1, range_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.TrimTrailingWhitespaceCommand = void 0;
    exports.trimTrailingWhitespace = trimTrailingWhitespace;
    class TrimTrailingWhitespaceCommand {
        constructor(selection, cursors, trimInRegexesAndStrings) {
            this._selection = selection;
            this._cursors = cursors;
            this._selectionId = null;
            this._trimInRegexesAndStrings = trimInRegexesAndStrings;
        }
        getEditOperations(model, builder) {
            const ops = trimTrailingWhitespace(model, this._cursors, this._trimInRegexesAndStrings);
            for (let i = 0, len = ops.length; i < len; i++) {
                const op = ops[i];
                builder.addEditOperation(op.range, op.text);
            }
            this._selectionId = builder.trackSelection(this._selection);
        }
        computeCursorState(model, helper) {
            return helper.getTrackedSelection(this._selectionId);
        }
    }
    exports.TrimTrailingWhitespaceCommand = TrimTrailingWhitespaceCommand;
    /**
     * Generate commands for trimming trailing whitespace on a model and ignore lines on which cursors are sitting.
     */
    function trimTrailingWhitespace(model, cursors, trimInRegexesAndStrings) {
        // Sort cursors ascending
        cursors.sort((a, b) => {
            if (a.lineNumber === b.lineNumber) {
                return a.column - b.column;
            }
            return a.lineNumber - b.lineNumber;
        });
        // Reduce multiple cursors on the same line and only keep the last one on the line
        for (let i = cursors.length - 2; i >= 0; i--) {
            if (cursors[i].lineNumber === cursors[i + 1].lineNumber) {
                // Remove cursor at `i`
                cursors.splice(i, 1);
            }
        }
        const r = [];
        let rLen = 0;
        let cursorIndex = 0;
        const cursorLen = cursors.length;
        for (let lineNumber = 1, lineCount = model.getLineCount(); lineNumber <= lineCount; lineNumber++) {
            const lineContent = model.getLineContent(lineNumber);
            const maxLineColumn = lineContent.length + 1;
            let minEditColumn = 0;
            if (cursorIndex < cursorLen && cursors[cursorIndex].lineNumber === lineNumber) {
                minEditColumn = cursors[cursorIndex].column;
                cursorIndex++;
                if (minEditColumn === maxLineColumn) {
                    // The cursor is at the end of the line => no edits for sure on this line
                    continue;
                }
            }
            if (lineContent.length === 0) {
                continue;
            }
            const lastNonWhitespaceIndex = strings.lastNonWhitespaceIndex(lineContent);
            let fromColumn = 0;
            if (lastNonWhitespaceIndex === -1) {
                // Entire line is whitespace
                fromColumn = 1;
            }
            else if (lastNonWhitespaceIndex !== lineContent.length - 1) {
                // There is trailing whitespace
                fromColumn = lastNonWhitespaceIndex + 2;
            }
            else {
                // There is no trailing whitespace
                continue;
            }
            if (!trimInRegexesAndStrings) {
                if (!model.tokenization.hasAccurateTokensForLine(lineNumber)) {
                    // We don't want to force line tokenization, as that can be expensive, but we also don't want to trim
                    // trailing whitespace in lines that are not tokenized yet, as that can be wrong and trim whitespace from
                    // lines that the user requested we don't. So we bail out if the tokens are not accurate for this line.
                    continue;
                }
                const lineTokens = model.tokenization.getLineTokens(lineNumber);
                const fromColumnType = lineTokens.getStandardTokenType(lineTokens.findTokenIndexAtOffset(fromColumn));
                if (fromColumnType === 2 /* StandardTokenType.String */ || fromColumnType === 3 /* StandardTokenType.RegEx */) {
                    continue;
                }
            }
            fromColumn = Math.max(minEditColumn, fromColumn);
            r[rLen++] = editOperation_1.EditOperation.delete(new range_1.Range(lineNumber, fromColumn, lineNumber, maxLineColumn));
        }
        return r;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[55/*vs/editor/common/core/lineRange*/], __M([1/*require*/,0/*exports*/,8/*vs/base/common/errors*/,68/*vs/editor/common/core/offsetRange*/,4/*vs/editor/common/core/range*/,67/*vs/base/common/arraysFind*/]), function (require, exports, errors_1, offsetRange_1, range_1, arraysFind_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.LineRangeSet = exports.LineRange = void 0;
    /**
     * A range of lines (1-based).
     */
    class LineRange {
        static fromRangeInclusive(range) {
            return new LineRange(range.startLineNumber, range.endLineNumber + 1);
        }
        /**
         * @param lineRanges An array of sorted line ranges.
         */
        static joinMany(lineRanges) {
            if (lineRanges.length === 0) {
                return [];
            }
            let result = new LineRangeSet(lineRanges[0].slice());
            for (let i = 1; i < lineRanges.length; i++) {
                result = result.getUnion(new LineRangeSet(lineRanges[i].slice()));
            }
            return result.ranges;
        }
        static join(lineRanges) {
            if (lineRanges.length === 0) {
                throw new errors_1.BugIndicatingError('lineRanges cannot be empty');
            }
            let startLineNumber = lineRanges[0].startLineNumber;
            let endLineNumberExclusive = lineRanges[0].endLineNumberExclusive;
            for (let i = 1; i < lineRanges.length; i++) {
                startLineNumber = Math.min(startLineNumber, lineRanges[i].startLineNumber);
                endLineNumberExclusive = Math.max(endLineNumberExclusive, lineRanges[i].endLineNumberExclusive);
            }
            return new LineRange(startLineNumber, endLineNumberExclusive);
        }
        static ofLength(startLineNumber, length) {
            return new LineRange(startLineNumber, startLineNumber + length);
        }
        /**
         * @internal
         */
        static deserialize(lineRange) {
            return new LineRange(lineRange[0], lineRange[1]);
        }
        constructor(startLineNumber, endLineNumberExclusive) {
            if (startLineNumber > endLineNumberExclusive) {
                throw new errors_1.BugIndicatingError(`startLineNumber ${startLineNumber} cannot be after endLineNumberExclusive ${endLineNumberExclusive}`);
            }
            this.startLineNumber = startLineNumber;
            this.endLineNumberExclusive = endLineNumberExclusive;
        }
        /**
         * Indicates if this line range contains the given line number.
         */
        contains(lineNumber) {
            return this.startLineNumber <= lineNumber && lineNumber < this.endLineNumberExclusive;
        }
        /**
         * Indicates if this line range is empty.
         */
        get isEmpty() {
            return this.startLineNumber === this.endLineNumberExclusive;
        }
        /**
         * Moves this line range by the given offset of line numbers.
         */
        delta(offset) {
            return new LineRange(this.startLineNumber + offset, this.endLineNumberExclusive + offset);
        }
        deltaLength(offset) {
            return new LineRange(this.startLineNumber, this.endLineNumberExclusive + offset);
        }
        /**
         * The number of lines this line range spans.
         */
        get length() {
            return this.endLineNumberExclusive - this.startLineNumber;
        }
        /**
         * Creates a line range that combines this and the given line range.
         */
        join(other) {
            return new LineRange(Math.min(this.startLineNumber, other.startLineNumber), Math.max(this.endLineNumberExclusive, other.endLineNumberExclusive));
        }
        toString() {
            return `[${this.startLineNumber},${this.endLineNumberExclusive})`;
        }
        /**
         * The resulting range is empty if the ranges do not intersect, but touch.
         * If the ranges don't even touch, the result is undefined.
         */
        intersect(other) {
            const startLineNumber = Math.max(this.startLineNumber, other.startLineNumber);
            const endLineNumberExclusive = Math.min(this.endLineNumberExclusive, other.endLineNumberExclusive);
            if (startLineNumber <= endLineNumberExclusive) {
                return new LineRange(startLineNumber, endLineNumberExclusive);
            }
            return undefined;
        }
        intersectsStrict(other) {
            return this.startLineNumber < other.endLineNumberExclusive && other.startLineNumber < this.endLineNumberExclusive;
        }
        overlapOrTouch(other) {
            return this.startLineNumber <= other.endLineNumberExclusive && other.startLineNumber <= this.endLineNumberExclusive;
        }
        equals(b) {
            return this.startLineNumber === b.startLineNumber && this.endLineNumberExclusive === b.endLineNumberExclusive;
        }
        toInclusiveRange() {
            if (this.isEmpty) {
                return null;
            }
            return new range_1.Range(this.startLineNumber, 1, this.endLineNumberExclusive - 1, Number.MAX_SAFE_INTEGER);
        }
        /**
         * @deprecated Using this function is discouraged because it might lead to bugs: The end position is not guaranteed to be a valid position!
        */
        toExclusiveRange() {
            return new range_1.Range(this.startLineNumber, 1, this.endLineNumberExclusive, 1);
        }
        mapToLineArray(f) {
            const result = [];
            for (let lineNumber = this.startLineNumber; lineNumber < this.endLineNumberExclusive; lineNumber++) {
                result.push(f(lineNumber));
            }
            return result;
        }
        forEach(f) {
            for (let lineNumber = this.startLineNumber; lineNumber < this.endLineNumberExclusive; lineNumber++) {
                f(lineNumber);
            }
        }
        /**
         * @internal
         */
        serialize() {
            return [this.startLineNumber, this.endLineNumberExclusive];
        }
        includes(lineNumber) {
            return this.startLineNumber <= lineNumber && lineNumber < this.endLineNumberExclusive;
        }
        /**
         * Converts this 1-based line range to a 0-based offset range (subtracts 1!).
         * @internal
         */
        toOffsetRange() {
            return new offsetRange_1.OffsetRange(this.startLineNumber - 1, this.endLineNumberExclusive - 1);
        }
    }
    exports.LineRange = LineRange;
    class LineRangeSet {
        constructor(
        /**
         * Sorted by start line number.
         * No two line ranges are touching or intersecting.
         */
        _normalizedRanges = []) {
            this._normalizedRanges = _normalizedRanges;
        }
        get ranges() {
            return this._normalizedRanges;
        }
        addRange(range) {
            if (range.length === 0) {
                return;
            }
            // Idea: Find joinRange such that:
            // replaceRange = _normalizedRanges.replaceRange(joinRange, range.joinAll(joinRange.map(idx => this._normalizedRanges[idx])))
            // idx of first element that touches range or that is after range
            const joinRangeStartIdx = (0, arraysFind_1.findFirstIdxMonotonousOrArrLen)(this._normalizedRanges, r => r.endLineNumberExclusive >= range.startLineNumber);
            // idx of element after { last element that touches range or that is before range }
            const joinRangeEndIdxExclusive = (0, arraysFind_1.findLastIdxMonotonous)(this._normalizedRanges, r => r.startLineNumber <= range.endLineNumberExclusive) + 1;
            if (joinRangeStartIdx === joinRangeEndIdxExclusive) {
                // If there is no element that touches range, then joinRangeStartIdx === joinRangeEndIdxExclusive and that value is the index of the element after range
                this._normalizedRanges.splice(joinRangeStartIdx, 0, range);
            }
            else if (joinRangeStartIdx === joinRangeEndIdxExclusive - 1) {
                // Else, there is an element that touches range and in this case it is both the first and last element. Thus we can replace it
                const joinRange = this._normalizedRanges[joinRangeStartIdx];
                this._normalizedRanges[joinRangeStartIdx] = joinRange.join(range);
            }
            else {
                // First and last element are different - we need to replace the entire range
                const joinRange = this._normalizedRanges[joinRangeStartIdx].join(this._normalizedRanges[joinRangeEndIdxExclusive - 1]).join(range);
                this._normalizedRanges.splice(joinRangeStartIdx, joinRangeEndIdxExclusive - joinRangeStartIdx, joinRange);
            }
        }
        contains(lineNumber) {
            const rangeThatStartsBeforeEnd = (0, arraysFind_1.findLastMonotonous)(this._normalizedRanges, r => r.startLineNumber <= lineNumber);
            return !!rangeThatStartsBeforeEnd && rangeThatStartsBeforeEnd.endLineNumberExclusive > lineNumber;
        }
        intersects(range) {
            const rangeThatStartsBeforeEnd = (0, arraysFind_1.findLastMonotonous)(this._normalizedRanges, r => r.startLineNumber < range.endLineNumberExclusive);
            return !!rangeThatStartsBeforeEnd && rangeThatStartsBeforeEnd.endLineNumberExclusive > range.startLineNumber;
        }
        getUnion(other) {
            if (this._normalizedRanges.length === 0) {
                return other;
            }
            if (other._normalizedRanges.length === 0) {
                return this;
            }
            const result = [];
            let i1 = 0;
            let i2 = 0;
            let current = null;
            while (i1 < this._normalizedRanges.length || i2 < other._normalizedRanges.length) {
                let next = null;
                if (i1 < this._normalizedRanges.length && i2 < other._normalizedRanges.length) {
                    const lineRange1 = this._normalizedRanges[i1];
                    const lineRange2 = other._normalizedRanges[i2];
                    if (lineRange1.startLineNumber < lineRange2.startLineNumber) {
                        next = lineRange1;
                        i1++;
                    }
                    else {
                        next = lineRange2;
                        i2++;
                    }
                }
                else if (i1 < this._normalizedRanges.length) {
                    next = this._normalizedRanges[i1];
                    i1++;
                }
                else {
                    next = other._normalizedRanges[i2];
                    i2++;
                }
                if (current === null) {
                    current = next;
                }
                else {
                    if (current.endLineNumberExclusive >= next.startLineNumber) {
                        // merge
                        current = new LineRange(current.startLineNumber, Math.max(current.endLineNumberExclusive, next.endLineNumberExclusive));
                    }
                    else {
                        // push
                        result.push(current);
                        current = next;
                    }
                }
            }
            if (current !== null) {
                result.push(current);
            }
            return new LineRangeSet(result);
        }
        /**
         * Subtracts all ranges in this set from `range` and returns the result.
         */
        subtractFrom(range) {
            // idx of first element that touches range or that is after range
            const joinRangeStartIdx = (0, arraysFind_1.findFirstIdxMonotonousOrArrLen)(this._normalizedRanges, r => r.endLineNumberExclusive >= range.startLineNumber);
            // idx of element after { last element that touches range or that is before range }
            const joinRangeEndIdxExclusive = (0, arraysFind_1.findLastIdxMonotonous)(this._normalizedRanges, r => r.startLineNumber <= range.endLineNumberExclusive) + 1;
            if (joinRangeStartIdx === joinRangeEndIdxExclusive) {
                return new LineRangeSet([range]);
            }
            const result = [];
            let startLineNumber = range.startLineNumber;
            for (let i = joinRangeStartIdx; i < joinRangeEndIdxExclusive; i++) {
                const r = this._normalizedRanges[i];
                if (r.startLineNumber > startLineNumber) {
                    result.push(new LineRange(startLineNumber, r.startLineNumber));
                }
                startLineNumber = r.endLineNumberExclusive;
            }
            if (startLineNumber < range.endLineNumberExclusive) {
                result.push(new LineRange(startLineNumber, range.endLineNumberExclusive));
            }
            return new LineRangeSet(result);
        }
        toString() {
            return this._normalizedRanges.map(r => r.toString()).join(', ');
        }
        getIntersection(other) {
            const result = [];
            let i1 = 0;
            let i2 = 0;
            while (i1 < this._normalizedRanges.length && i2 < other._normalizedRanges.length) {
                const r1 = this._normalizedRanges[i1];
                const r2 = other._normalizedRanges[i2];
                const i = r1.intersect(r2);
                if (i && !i.isEmpty) {
                    result.push(i);
                }
                if (r1.endLineNumberExclusive < r2.endLineNumberExclusive) {
                    i1++;
                }
                else {
                    i2++;
                }
            }
            return new LineRangeSet(result);
        }
        getWithDelta(value) {
            return new LineRangeSet(this._normalizedRanges.map(r => r.delta(value)));
        }
    }
    exports.LineRangeSet = LineRangeSet;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[311/*vs/editor/common/core/rgba*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.RGBA8 = void 0;
    /**
     * A very VM friendly rgba datastructure.
     * Please don't touch unless you take a look at the IR.
     */
    class RGBA8 {
        static { this.Empty = new RGBA8(0, 0, 0, 0); }
        constructor(r, g, b, a) {
            this._rgba8Brand = undefined;
            this.r = RGBA8._clamp(r);
            this.g = RGBA8._clamp(g);
            this.b = RGBA8._clamp(b);
            this.a = RGBA8._clamp(a);
        }
        equals(other) {
            return (this.r === other.r
                && this.g === other.g
                && this.b === other.b
                && this.a === other.a);
        }
        static _clamp(c) {
            if (c < 0) {
                return 0;
            }
            if (c > 255) {
                return 255;
            }
            return c | 0;
        }
    }
    exports.RGBA8 = RGBA8;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[23/*vs/editor/common/core/selection*/], __M([1/*require*/,0/*exports*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/]), function (require, exports, position_1, range_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Selection = void 0;
    /**
     * A selection in the editor.
     * The selection is a range that has an orientation.
     */
    class Selection extends range_1.Range {
        constructor(selectionStartLineNumber, selectionStartColumn, positionLineNumber, positionColumn) {
            super(selectionStartLineNumber, selectionStartColumn, positionLineNumber, positionColumn);
            this.selectionStartLineNumber = selectionStartLineNumber;
            this.selectionStartColumn = selectionStartColumn;
            this.positionLineNumber = positionLineNumber;
            this.positionColumn = positionColumn;
        }
        /**
         * Transform to a human-readable representation.
         */
        toString() {
            return '[' + this.selectionStartLineNumber + ',' + this.selectionStartColumn + ' -> ' + this.positionLineNumber + ',' + this.positionColumn + ']';
        }
        /**
         * Test if equals other selection.
         */
        equalsSelection(other) {
            return (Selection.selectionsEqual(this, other));
        }
        /**
         * Test if the two selections are equal.
         */
        static selectionsEqual(a, b) {
            return (a.selectionStartLineNumber === b.selectionStartLineNumber &&
                a.selectionStartColumn === b.selectionStartColumn &&
                a.positionLineNumber === b.positionLineNumber &&
                a.positionColumn === b.positionColumn);
        }
        /**
         * Get directions (LTR or RTL).
         */
        getDirection() {
            if (this.selectionStartLineNumber === this.startLineNumber && this.selectionStartColumn === this.startColumn) {
                return 0 /* SelectionDirection.LTR */;
            }
            return 1 /* SelectionDirection.RTL */;
        }
        /**
         * Create a new selection with a different `positionLineNumber` and `positionColumn`.
         */
        setEndPosition(endLineNumber, endColumn) {
            if (this.getDirection() === 0 /* SelectionDirection.LTR */) {
                return new Selection(this.startLineNumber, this.startColumn, endLineNumber, endColumn);
            }
            return new Selection(endLineNumber, endColumn, this.startLineNumber, this.startColumn);
        }
        /**
         * Get the position at `positionLineNumber` and `positionColumn`.
         */
        getPosition() {
            return new position_1.Position(this.positionLineNumber, this.positionColumn);
        }
        /**
         * Get the position at the start of the selection.
        */
        getSelectionStart() {
            return new position_1.Position(this.selectionStartLineNumber, this.selectionStartColumn);
        }
        /**
         * Create a new selection with a different `selectionStartLineNumber` and `selectionStartColumn`.
         */
        setStartPosition(startLineNumber, startColumn) {
            if (this.getDirection() === 0 /* SelectionDirection.LTR */) {
                return new Selection(startLineNumber, startColumn, this.endLineNumber, this.endColumn);
            }
            return new Selection(this.endLineNumber, this.endColumn, startLineNumber, startColumn);
        }
        // ----
        /**
         * Create a `Selection` from one or two positions
         */
        static fromPositions(start, end = start) {
            return new Selection(start.lineNumber, start.column, end.lineNumber, end.column);
        }
        /**
         * Creates a `Selection` from a range, given a direction.
         */
        static fromRange(range, direction) {
            if (direction === 0 /* SelectionDirection.LTR */) {
                return new Selection(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn);
            }
            else {
                return new Selection(range.endLineNumber, range.endColumn, range.startLineNumber, range.startColumn);
            }
        }
        /**
         * Create a `Selection` from an `ISelection`.
         */
        static liftSelection(sel) {
            return new Selection(sel.selectionStartLineNumber, sel.selectionStartColumn, sel.positionLineNumber, sel.positionColumn);
        }
        /**
         * `a` equals `b`.
         */
        static selectionsArrEqual(a, b) {
            if (a && !b || !a && b) {
                return false;
            }
            if (!a && !b) {
                return true;
            }
            if (a.length !== b.length) {
                return false;
            }
            for (let i = 0, len = a.length; i < len; i++) {
                if (!this.selectionsEqual(a[i], b[i])) {
                    return false;
                }
            }
            return true;
        }
        /**
         * Test if `obj` is an `ISelection`.
         */
        static isISelection(obj) {
            return (obj
                && (typeof obj.selectionStartLineNumber === 'number')
                && (typeof obj.selectionStartColumn === 'number')
                && (typeof obj.positionLineNumber === 'number')
                && (typeof obj.positionColumn === 'number'));
        }
        /**
         * Create with a direction.
         */
        static createWithDirection(startLineNumber, startColumn, endLineNumber, endColumn, direction) {
            if (direction === 0 /* SelectionDirection.LTR */) {
                return new Selection(startLineNumber, startColumn, endLineNumber, endColumn);
            }
            return new Selection(endLineNumber, endColumn, startLineNumber, startColumn);
        }
    }
    exports.Selection = Selection;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[112/*vs/editor/browser/observableCodeEditor*/], __M([1/*require*/,0/*exports*/,102/*vs/base/common/equals*/,2/*vs/base/common/lifecycle*/,21/*vs/base/common/observable*/,92/*vs/base/common/observableInternal/base*/,65/*vs/base/common/observableInternal/derived*/,23/*vs/editor/common/core/selection*/]), function (require, exports, equals_1, lifecycle_1, observable_1, base_1, derived_1, selection_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ObservableCodeEditor = void 0;
    exports.observableCodeEditor = observableCodeEditor;
    exports.reactToChange = reactToChange;
    exports.reactToChangeWithStore = reactToChangeWithStore;
    /**
     * Returns a facade for the code editor that provides observables for various states/events.
    */
    function observableCodeEditor(editor) {
        return ObservableCodeEditor.get(editor);
    }
    class ObservableCodeEditor extends lifecycle_1.Disposable {
        static { this._map = new Map(); }
        /**
         * Make sure that editor is not disposed yet!
        */
        static get(editor) {
            let result = ObservableCodeEditor._map.get(editor);
            if (!result) {
                result = new ObservableCodeEditor(editor);
                ObservableCodeEditor._map.set(editor, result);
                const d = editor.onDidDispose(() => {
                    const item = ObservableCodeEditor._map.get(editor);
                    if (item) {
                        ObservableCodeEditor._map.delete(editor);
                        item.dispose();
                        d.dispose();
                    }
                });
            }
            return result;
        }
        _beginUpdate() {
            this._updateCounter++;
            if (this._updateCounter === 1) {
                this._currentTransaction = new base_1.TransactionImpl(() => {
                    /** @description Update editor state */
                });
            }
        }
        _endUpdate() {
            this._updateCounter--;
            if (this._updateCounter === 0) {
                const t = this._currentTransaction;
                this._currentTransaction = undefined;
                t.finish();
            }
        }
        constructor(editor) {
            super();
            this.editor = editor;
            this._updateCounter = 0;
            this._currentTransaction = undefined;
            this._model = (0, observable_1.observableValue)(this, this.editor.getModel());
            this.model = this._model;
            this.isReadonly = (0, observable_1.observableFromEvent)(this, this.editor.onDidChangeConfiguration, () => this.editor.getOption(92 /* EditorOption.readOnly */));
            this._versionId = (0, observable_1.observableValueOpts)({ owner: this, lazy: true }, this.editor.getModel()?.getVersionId() ?? null);
            this.versionId = this._versionId;
            this._selections = (0, observable_1.observableValueOpts)({ owner: this, equalsFn: (0, equals_1.equalsIfDefined)((0, equals_1.itemsEquals)(selection_1.Selection.selectionsEqual)), lazy: true }, this.editor.getSelections() ?? null);
            this.selections = this._selections;
            this.isFocused = (0, observable_1.observableFromEvent)(this, e => {
                const d1 = this.editor.onDidFocusEditorWidget(e);
                const d2 = this.editor.onDidBlurEditorWidget(e);
                return {
                    dispose() {
                        d1.dispose();
                        d2.dispose();
                    }
                };
            }, () => this.editor.hasWidgetFocus());
            this.value = (0, derived_1.derivedWithSetter)(this, reader => { this.versionId.read(reader); return this.model.read(reader)?.getValue() ?? ''; }, (value, tx) => {
                const model = this.model.get();
                if (model !== null) {
                    if (value !== model.getValue()) {
                        model.setValue(value);
                    }
                }
            });
            this.valueIsEmpty = (0, observable_1.derived)(this, reader => { this.versionId.read(reader); return this.editor.getModel()?.getValueLength() === 0; });
            this.cursorSelection = (0, observable_1.derivedOpts)({ owner: this, equalsFn: (0, equals_1.equalsIfDefined)(selection_1.Selection.selectionsEqual) }, reader => this.selections.read(reader)?.[0] ?? null);
            this.onDidType = (0, observable_1.observableSignal)(this);
            this.scrollTop = (0, observable_1.observableFromEvent)(this.editor.onDidScrollChange, () => this.editor.getScrollTop());
            this.scrollLeft = (0, observable_1.observableFromEvent)(this.editor.onDidScrollChange, () => this.editor.getScrollLeft());
            this.layoutInfo = (0, observable_1.observableFromEvent)(this.editor.onDidLayoutChange, () => this.editor.getLayoutInfo());
            this.layoutInfoContentLeft = this.layoutInfo.map(l => l.contentLeft);
            this.layoutInfoDecorationsLeft = this.layoutInfo.map(l => l.decorationsLeft);
            this.contentWidth = (0, observable_1.observableFromEvent)(this.editor.onDidContentSizeChange, () => this.editor.getContentWidth());
            this._overlayWidgetCounter = 0;
            this._register(this.editor.onBeginUpdate(() => this._beginUpdate()));
            this._register(this.editor.onEndUpdate(() => this._endUpdate()));
            this._register(this.editor.onDidChangeModel(() => {
                this._beginUpdate();
                try {
                    this._model.set(this.editor.getModel(), this._currentTransaction);
                    this._forceUpdate();
                }
                finally {
                    this._endUpdate();
                }
            }));
            this._register(this.editor.onDidType((e) => {
                this._beginUpdate();
                try {
                    this._forceUpdate();
                    this.onDidType.trigger(this._currentTransaction, e);
                }
                finally {
                    this._endUpdate();
                }
            }));
            this._register(this.editor.onDidChangeModelContent(e => {
                this._beginUpdate();
                try {
                    this._versionId.set(this.editor.getModel()?.getVersionId() ?? null, this._currentTransaction, e);
                    this._forceUpdate();
                }
                finally {
                    this._endUpdate();
                }
            }));
            this._register(this.editor.onDidChangeCursorSelection(e => {
                this._beginUpdate();
                try {
                    this._selections.set(this.editor.getSelections(), this._currentTransaction, e);
                    this._forceUpdate();
                }
                finally {
                    this._endUpdate();
                }
            }));
        }
        forceUpdate(cb) {
            this._beginUpdate();
            try {
                this._forceUpdate();
                if (!cb) {
                    return undefined;
                }
                return cb(this._currentTransaction);
            }
            finally {
                this._endUpdate();
            }
        }
        _forceUpdate() {
            this._beginUpdate();
            try {
                this._model.set(this.editor.getModel(), this._currentTransaction);
                this._versionId.set(this.editor.getModel()?.getVersionId() ?? null, this._currentTransaction, undefined);
                this._selections.set(this.editor.getSelections(), this._currentTransaction, undefined);
            }
            finally {
                this._endUpdate();
            }
        }
        getOption(id) {
            return (0, observable_1.observableFromEvent)(this, cb => this.editor.onDidChangeConfiguration(e => {
                if (e.hasChanged(id)) {
                    cb(undefined);
                }
            }), () => this.editor.getOption(id));
        }
        setDecorations(decorations) {
            const d = new lifecycle_1.DisposableStore();
            const decorationsCollection = this.editor.createDecorationsCollection();
            d.add((0, observable_1.autorunOpts)({ owner: this, debugName: () => `Apply decorations from ${decorations.debugName}` }, reader => {
                const d = decorations.read(reader);
                decorationsCollection.set(d);
            }));
            d.add({
                dispose: () => {
                    decorationsCollection.clear();
                }
            });
            return d;
        }
        createOverlayWidget(widget) {
            const overlayWidgetId = 'observableOverlayWidget' + (this._overlayWidgetCounter++);
            const w = {
                getDomNode: () => widget.domNode,
                getPosition: () => widget.position.get(),
                getId: () => overlayWidgetId,
                allowEditorOverflow: widget.allowEditorOverflow,
                getMinContentWidthInPx: () => widget.minContentWidthInPx.get(),
            };
            this.editor.addOverlayWidget(w);
            const d = (0, observable_1.autorun)(reader => {
                widget.position.read(reader);
                widget.minContentWidthInPx.read(reader);
                this.editor.layoutOverlayWidget(w);
            });
            return (0, lifecycle_1.toDisposable)(() => {
                d.dispose();
                this.editor.removeOverlayWidget(w);
            });
        }
    }
    exports.ObservableCodeEditor = ObservableCodeEditor;
    function reactToChange(observable, cb) {
        return (0, observable_1.autorunWithStoreHandleChanges)({
            createEmptyChangeSummary: () => ({ deltas: [], didChange: false }),
            handleChange: (context, changeSummary) => {
                if (context.didChange(observable)) {
                    const e = context.change;
                    if (e !== undefined) {
                        changeSummary.deltas.push(e);
                    }
                    changeSummary.didChange = true;
                }
                return true;
            },
        }, (reader, changeSummary) => {
            const value = observable.read(reader);
            if (changeSummary.didChange) {
                cb(value, changeSummary.deltas);
            }
        });
    }
    function reactToChangeWithStore(observable, cb) {
        const store = new lifecycle_1.DisposableStore();
        const disposable = reactToChange(observable, (value, deltas) => {
            store.clear();
            cb(value, deltas, store);
        });
        return {
            dispose() {
                disposable.dispose();
                store.dispose();
            }
        };
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[146/*vs/editor/common/commands/replaceCommand*/], __M([1/*require*/,0/*exports*/,23/*vs/editor/common/core/selection*/]), function (require, exports, selection_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ReplaceCommandThatPreservesSelection = exports.ReplaceCommandWithOffsetCursorState = exports.ReplaceCommandWithoutChangingPosition = exports.ReplaceCommandThatSelectsText = exports.ReplaceCommand = void 0;
    class ReplaceCommand {
        constructor(range, text, insertsAutoWhitespace = false) {
            this._range = range;
            this._text = text;
            this.insertsAutoWhitespace = insertsAutoWhitespace;
        }
        getEditOperations(model, builder) {
            builder.addTrackedEditOperation(this._range, this._text);
        }
        computeCursorState(model, helper) {
            const inverseEditOperations = helper.getInverseEditOperations();
            const srcRange = inverseEditOperations[0].range;
            return selection_1.Selection.fromPositions(srcRange.getEndPosition());
        }
    }
    exports.ReplaceCommand = ReplaceCommand;
    class ReplaceCommandThatSelectsText {
        constructor(range, text) {
            this._range = range;
            this._text = text;
        }
        getEditOperations(model, builder) {
            builder.addTrackedEditOperation(this._range, this._text);
        }
        computeCursorState(model, helper) {
            const inverseEditOperations = helper.getInverseEditOperations();
            const srcRange = inverseEditOperations[0].range;
            return selection_1.Selection.fromRange(srcRange, 0 /* SelectionDirection.LTR */);
        }
    }
    exports.ReplaceCommandThatSelectsText = ReplaceCommandThatSelectsText;
    class ReplaceCommandWithoutChangingPosition {
        constructor(range, text, insertsAutoWhitespace = false) {
            this._range = range;
            this._text = text;
            this.insertsAutoWhitespace = insertsAutoWhitespace;
        }
        getEditOperations(model, builder) {
            builder.addTrackedEditOperation(this._range, this._text);
        }
        computeCursorState(model, helper) {
            const inverseEditOperations = helper.getInverseEditOperations();
            const srcRange = inverseEditOperations[0].range;
            return selection_1.Selection.fromPositions(srcRange.getStartPosition());
        }
    }
    exports.ReplaceCommandWithoutChangingPosition = ReplaceCommandWithoutChangingPosition;
    class ReplaceCommandWithOffsetCursorState {
        constructor(range, text, lineNumberDeltaOffset, columnDeltaOffset, insertsAutoWhitespace = false) {
            this._range = range;
            this._text = text;
            this._columnDeltaOffset = columnDeltaOffset;
            this._lineNumberDeltaOffset = lineNumberDeltaOffset;
            this.insertsAutoWhitespace = insertsAutoWhitespace;
        }
        getEditOperations(model, builder) {
            builder.addTrackedEditOperation(this._range, this._text);
        }
        computeCursorState(model, helper) {
            const inverseEditOperations = helper.getInverseEditOperations();
            const srcRange = inverseEditOperations[0].range;
            return selection_1.Selection.fromPositions(srcRange.getEndPosition().delta(this._lineNumberDeltaOffset, this._columnDeltaOffset));
        }
    }
    exports.ReplaceCommandWithOffsetCursorState = ReplaceCommandWithOffsetCursorState;
    class ReplaceCommandThatPreservesSelection {
        constructor(editRange, text, initialSelection, forceMoveMarkers = false) {
            this._range = editRange;
            this._text = text;
            this._initialSelection = initialSelection;
            this._forceMoveMarkers = forceMoveMarkers;
            this._selectionId = null;
        }
        getEditOperations(model, builder) {
            builder.addTrackedEditOperation(this._range, this._text, this._forceMoveMarkers);
            this._selectionId = builder.trackSelection(this._initialSelection);
        }
        computeCursorState(model, helper) {
            return helper.getTrackedSelection(this._selectionId);
        }
    }
    exports.ReplaceCommandThatPreservesSelection = ReplaceCommandThatPreservesSelection;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[312/*vs/editor/common/commands/surroundSelectionCommand*/], __M([1/*require*/,0/*exports*/,4/*vs/editor/common/core/range*/,23/*vs/editor/common/core/selection*/]), function (require, exports, range_1, selection_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CompositionSurroundSelectionCommand = exports.SurroundSelectionCommand = void 0;
    class SurroundSelectionCommand {
        constructor(range, charBeforeSelection, charAfterSelection) {
            this._range = range;
            this._charBeforeSelection = charBeforeSelection;
            this._charAfterSelection = charAfterSelection;
        }
        getEditOperations(model, builder) {
            builder.addTrackedEditOperation(new range_1.Range(this._range.startLineNumber, this._range.startColumn, this._range.startLineNumber, this._range.startColumn), this._charBeforeSelection);
            builder.addTrackedEditOperation(new range_1.Range(this._range.endLineNumber, this._range.endColumn, this._range.endLineNumber, this._range.endColumn), this._charAfterSelection);
        }
        computeCursorState(model, helper) {
            const inverseEditOperations = helper.getInverseEditOperations();
            const firstOperationRange = inverseEditOperations[0].range;
            const secondOperationRange = inverseEditOperations[1].range;
            return new selection_1.Selection(firstOperationRange.endLineNumber, firstOperationRange.endColumn, secondOperationRange.endLineNumber, secondOperationRange.endColumn - this._charAfterSelection.length);
        }
    }
    exports.SurroundSelectionCommand = SurroundSelectionCommand;
    /**
     * A surround selection command that runs after composition finished.
     */
    class CompositionSurroundSelectionCommand {
        constructor(_position, _text, _charAfter) {
            this._position = _position;
            this._text = _text;
            this._charAfter = _charAfter;
        }
        getEditOperations(model, builder) {
            builder.addTrackedEditOperation(new range_1.Range(this._position.lineNumber, this._position.column, this._position.lineNumber, this._position.column), this._text + this._charAfter);
        }
        computeCursorState(model, helper) {
            const inverseEditOperations = helper.getInverseEditOperations();
            const opRange = inverseEditOperations[0].range;
            return new selection_1.Selection(opRange.endLineNumber, opRange.startColumn, opRange.endLineNumber, opRange.endColumn - this._charAfter.length);
        }
    }
    exports.CompositionSurroundSelectionCommand = CompositionSurroundSelectionCommand;
});

define(__m[113/*vs/editor/common/core/textLength*/], __M([1/*require*/,0/*exports*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/]), function (require, exports, position_1, range_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.TextLength = void 0;
    /**
     * Represents a non-negative length of text in terms of line and column count.
    */
    class TextLength {
        static { this.zero = new TextLength(0, 0); }
        static betweenPositions(position1, position2) {
            if (position1.lineNumber === position2.lineNumber) {
                return new TextLength(0, position2.column - position1.column);
            }
            else {
                return new TextLength(position2.lineNumber - position1.lineNumber, position2.column - 1);
            }
        }
        static ofRange(range) {
            return TextLength.betweenPositions(range.getStartPosition(), range.getEndPosition());
        }
        static ofText(text) {
            let line = 0;
            let column = 0;
            for (const c of text) {
                if (c === '\n') {
                    line++;
                    column = 0;
                }
                else {
                    column++;
                }
            }
            return new TextLength(line, column);
        }
        constructor(lineCount, columnCount) {
            this.lineCount = lineCount;
            this.columnCount = columnCount;
        }
        isGreaterThanOrEqualTo(other) {
            if (this.lineCount !== other.lineCount) {
                return this.lineCount > other.lineCount;
            }
            return this.columnCount >= other.columnCount;
        }
        createRange(startPosition) {
            if (this.lineCount === 0) {
                return new range_1.Range(startPosition.lineNumber, startPosition.column, startPosition.lineNumber, startPosition.column + this.columnCount);
            }
            else {
                return new range_1.Range(startPosition.lineNumber, startPosition.column, startPosition.lineNumber + this.lineCount, this.columnCount + 1);
            }
        }
        addToPosition(position) {
            if (this.lineCount === 0) {
                return new position_1.Position(position.lineNumber, position.column + this.columnCount);
            }
            else {
                return new position_1.Position(position.lineNumber + this.lineCount, this.columnCount + 1);
            }
        }
        toString() {
            return `${this.lineCount},${this.columnCount}`;
        }
    }
    exports.TextLength = TextLength;
});

define(__m[555/*vs/editor/common/core/positionToOffset*/], __M([1/*require*/,0/*exports*/,68/*vs/editor/common/core/offsetRange*/,113/*vs/editor/common/core/textLength*/]), function (require, exports, offsetRange_1, textLength_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.PositionOffsetTransformer = void 0;
    class PositionOffsetTransformer {
        constructor(text) {
            this.text = text;
            this.lineStartOffsetByLineIdx = [];
            this.lineStartOffsetByLineIdx.push(0);
            for (let i = 0; i < text.length; i++) {
                if (text.charAt(i) === '\n') {
                    this.lineStartOffsetByLineIdx.push(i + 1);
                }
            }
        }
        getOffset(position) {
            return this.lineStartOffsetByLineIdx[position.lineNumber - 1] + position.column - 1;
        }
        getOffsetRange(range) {
            return new offsetRange_1.OffsetRange(this.getOffset(range.getStartPosition()), this.getOffset(range.getEndPosition()));
        }
        get textLength() {
            const lineIdx = this.lineStartOffsetByLineIdx.length - 1;
            return new textLength_1.TextLength(lineIdx, this.text.length - this.lineStartOffsetByLineIdx[lineIdx]);
        }
    }
    exports.PositionOffsetTransformer = PositionOffsetTransformer;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[104/*vs/editor/common/core/textEdit*/], __M([1/*require*/,0/*exports*/,90/*vs/base/common/assert*/,8/*vs/base/common/errors*/,9/*vs/editor/common/core/position*/,555/*vs/editor/common/core/positionToOffset*/,4/*vs/editor/common/core/range*/,113/*vs/editor/common/core/textLength*/]), function (require, exports, assert_1, errors_1, position_1, positionToOffset_1, range_1, textLength_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.StringText = exports.AbstractText = exports.SingleTextEdit = exports.TextEdit = void 0;
    class TextEdit {
        constructor(edits) {
            this.edits = edits;
            (0, assert_1.assertFn)(() => (0, assert_1.checkAdjacentItems)(edits, (a, b) => a.range.getEndPosition().isBeforeOrEqual(b.range.getStartPosition())));
        }
        apply(text) {
            let result = '';
            let lastEditEnd = new position_1.Position(1, 1);
            for (const edit of this.edits) {
                const editRange = edit.range;
                const editStart = editRange.getStartPosition();
                const editEnd = editRange.getEndPosition();
                const r = rangeFromPositions(lastEditEnd, editStart);
                if (!r.isEmpty()) {
                    result += text.getValueOfRange(r);
                }
                result += edit.text;
                lastEditEnd = editEnd;
            }
            const r = rangeFromPositions(lastEditEnd, text.endPositionExclusive);
            if (!r.isEmpty()) {
                result += text.getValueOfRange(r);
            }
            return result;
        }
        applyToString(str) {
            const strText = new StringText(str);
            return this.apply(strText);
        }
        getNewRanges() {
            const newRanges = [];
            let previousEditEndLineNumber = 0;
            let lineOffset = 0;
            let columnOffset = 0;
            for (const edit of this.edits) {
                const textLength = textLength_1.TextLength.ofText(edit.text);
                const newRangeStart = position_1.Position.lift({
                    lineNumber: edit.range.startLineNumber + lineOffset,
                    column: edit.range.startColumn + (edit.range.startLineNumber === previousEditEndLineNumber ? columnOffset : 0)
                });
                const newRange = textLength.createRange(newRangeStart);
                newRanges.push(newRange);
                lineOffset = newRange.endLineNumber - edit.range.endLineNumber;
                columnOffset = newRange.endColumn - edit.range.endColumn;
                previousEditEndLineNumber = edit.range.endLineNumber;
            }
            return newRanges;
        }
    }
    exports.TextEdit = TextEdit;
    class SingleTextEdit {
        constructor(range, text) {
            this.range = range;
            this.text = text;
        }
        toSingleEditOperation() {
            return {
                range: this.range,
                text: this.text,
            };
        }
    }
    exports.SingleTextEdit = SingleTextEdit;
    function rangeFromPositions(start, end) {
        if (start.lineNumber === end.lineNumber && start.column === Number.MAX_SAFE_INTEGER) {
            return range_1.Range.fromPositions(end, end);
        }
        else if (!start.isBeforeOrEqual(end)) {
            throw new errors_1.BugIndicatingError('start must be before end');
        }
        return new range_1.Range(start.lineNumber, start.column, end.lineNumber, end.column);
    }
    class AbstractText {
        get endPositionExclusive() {
            return this.length.addToPosition(new position_1.Position(1, 1));
        }
    }
    exports.AbstractText = AbstractText;
    class StringText extends AbstractText {
        constructor(value) {
            super();
            this.value = value;
            this._t = new positionToOffset_1.PositionOffsetTransformer(this.value);
        }
        getValueOfRange(range) {
            return this._t.getOffsetRange(range).substring(this.value);
        }
        get length() {
            return this._t.textLength;
        }
    }
    exports.StringText = StringText;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[197/*vs/editor/common/core/textModelDefaults*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.EDITOR_MODEL_DEFAULTS = void 0;
    exports.EDITOR_MODEL_DEFAULTS = {
        tabSize: 4,
        indentSize: 4,
        insertSpaces: true,
        detectIndentation: true,
        trimAutoWhitespace: true,
        largeFileOptimizations: true,
        bracketPairColorizationOptions: {
            enabled: true,
            independentColorPoolPerBracketType: false,
        },
    };
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[166/*vs/editor/common/core/wordCharacterClassifier*/], __M([1/*require*/,0/*exports*/,45/*vs/base/common/map*/,144/*vs/editor/common/core/characterClassifier*/]), function (require, exports, map_1, characterClassifier_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.WordCharacterClassifier = void 0;
    exports.getMapForWordSeparators = getMapForWordSeparators;
    class WordCharacterClassifier extends characterClassifier_1.CharacterClassifier {
        constructor(wordSeparators, intlSegmenterLocales) {
            super(0 /* WordCharacterClass.Regular */);
            this._segmenter = null;
            this._cachedLine = null;
            this._cachedSegments = [];
            this.intlSegmenterLocales = intlSegmenterLocales;
            if (this.intlSegmenterLocales.length > 0) {
                this._segmenter = new Intl.Segmenter(this.intlSegmenterLocales, { granularity: 'word' });
            }
            else {
                this._segmenter = null;
            }
            for (let i = 0, len = wordSeparators.length; i < len; i++) {
                this.set(wordSeparators.charCodeAt(i), 2 /* WordCharacterClass.WordSeparator */);
            }
            this.set(32 /* CharCode.Space */, 1 /* WordCharacterClass.Whitespace */);
            this.set(9 /* CharCode.Tab */, 1 /* WordCharacterClass.Whitespace */);
        }
        findPrevIntlWordBeforeOrAtOffset(line, offset) {
            let candidate = null;
            for (const segment of this._getIntlSegmenterWordsOnLine(line)) {
                if (segment.index > offset) {
                    break;
                }
                candidate = segment;
            }
            return candidate;
        }
        findNextIntlWordAtOrAfterOffset(lineContent, offset) {
            for (const segment of this._getIntlSegmenterWordsOnLine(lineContent)) {
                if (segment.index < offset) {
                    continue;
                }
                return segment;
            }
            return null;
        }
        _getIntlSegmenterWordsOnLine(line) {
            if (!this._segmenter) {
                return [];
            }
            // Check if the line has changed from the previous call
            if (this._cachedLine === line) {
                return this._cachedSegments;
            }
            // Update the cache with the new line
            this._cachedLine = line;
            this._cachedSegments = this._filterWordSegments(this._segmenter.segment(line));
            return this._cachedSegments;
        }
        _filterWordSegments(segments) {
            const result = [];
            for (const segment of segments) {
                if (this._isWordLike(segment)) {
                    result.push(segment);
                }
            }
            return result;
        }
        _isWordLike(segment) {
            if (segment.isWordLike) {
                return true;
            }
            return false;
        }
    }
    exports.WordCharacterClassifier = WordCharacterClassifier;
    const wordClassifierCache = new map_1.LRUCache(10);
    function getMapForWordSeparators(wordSeparators, intlSegmenterLocales) {
        const key = `${wordSeparators}/${intlSegmenterLocales.join(',')}`;
        let result = wordClassifierCache.get(key);
        if (!result) {
            result = new WordCharacterClassifier(wordSeparators, intlSegmenterLocales);
            wordClassifierCache.set(key, result);
        }
        return result;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[147/*vs/editor/common/core/wordHelper*/], __M([1/*require*/,0/*exports*/,53/*vs/base/common/iterator*/,73/*vs/base/common/linkedList*/]), function (require, exports, iterator_1, linkedList_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DEFAULT_WORD_REGEXP = exports.USUAL_WORD_SEPARATORS = void 0;
    exports.ensureValidWordDefinition = ensureValidWordDefinition;
    exports.getWordAtText = getWordAtText;
    exports.USUAL_WORD_SEPARATORS = '`~!@#$%^&*()-=+[{]}\\|;:\'",.<>/?';
    /**
     * Create a word definition regular expression based on default word separators.
     * Optionally provide allowed separators that should be included in words.
     *
     * The default would look like this:
     * /(-?\d*\.\d\w*)|([^\`\~\!\@\#\$\%\^\&\*\(\)\-\=\+\[\{\]\}\\\|\;\:\'\"\,\.\<\>\/\?\s]+)/g
     */
    function createWordRegExp(allowInWords = '') {
        let source = '(-?\\d*\\.\\d\\w*)|([^';
        for (const sep of exports.USUAL_WORD_SEPARATORS) {
            if (allowInWords.indexOf(sep) >= 0) {
                continue;
            }
            source += '\\' + sep;
        }
        source += '\\s]+)';
        return new RegExp(source, 'g');
    }
    // catches numbers (including floating numbers) in the first group, and alphanum in the second
    exports.DEFAULT_WORD_REGEXP = createWordRegExp();
    function ensureValidWordDefinition(wordDefinition) {
        let result = exports.DEFAULT_WORD_REGEXP;
        if (wordDefinition && (wordDefinition instanceof RegExp)) {
            if (!wordDefinition.global) {
                let flags = 'g';
                if (wordDefinition.ignoreCase) {
                    flags += 'i';
                }
                if (wordDefinition.multiline) {
                    flags += 'm';
                }
                if (wordDefinition.unicode) {
                    flags += 'u';
                }
                result = new RegExp(wordDefinition.source, flags);
            }
            else {
                result = wordDefinition;
            }
        }
        result.lastIndex = 0;
        return result;
    }
    const _defaultConfig = new linkedList_1.LinkedList();
    _defaultConfig.unshift({
        maxLen: 1000,
        windowSize: 15,
        timeBudget: 150
    });
    function getWordAtText(column, wordDefinition, text, textOffset, config) {
        // Ensure the regex has the 'g' flag, otherwise this will loop forever
        wordDefinition = ensureValidWordDefinition(wordDefinition);
        if (!config) {
            config = iterator_1.Iterable.first(_defaultConfig);
        }
        if (text.length > config.maxLen) {
            // don't throw strings that long at the regexp
            // but use a sub-string in which a word must occur
            let start = column - config.maxLen / 2;
            if (start < 0) {
                start = 0;
            }
            else {
                textOffset += start;
            }
            text = text.substring(start, column + config.maxLen / 2);
            return getWordAtText(column, wordDefinition, text, textOffset, config);
        }
        const t1 = Date.now();
        const pos = column - 1 - textOffset;
        let prevRegexIndex = -1;
        let match = null;
        for (let i = 1;; i++) {
            // check time budget
            if (Date.now() - t1 >= config.timeBudget) {
                break;
            }
            // reset the index at which the regexp should start matching, also know where it
            // should stop so that subsequent search don't repeat previous searches
            const regexIndex = pos - config.windowSize * i;
            wordDefinition.lastIndex = Math.max(0, regexIndex);
            const thisMatch = _findRegexMatchEnclosingPosition(wordDefinition, text, pos, prevRegexIndex);
            if (!thisMatch && match) {
                // stop: we have something
                break;
            }
            match = thisMatch;
            // stop: searched at start
            if (regexIndex <= 0) {
                break;
            }
            prevRegexIndex = regexIndex;
        }
        if (match) {
            const result = {
                word: match[0],
                startColumn: textOffset + 1 + match.index,
                endColumn: textOffset + 1 + match.index + match[0].length
            };
            wordDefinition.lastIndex = 0;
            return result;
        }
        return null;
    }
    function _findRegexMatchEnclosingPosition(wordDefinition, text, pos, stopPos) {
        let match;
        while (match = wordDefinition.exec(text)) {
            const matchIndex = match.index || 0;
            if (matchIndex <= pos && wordDefinition.lastIndex >= pos) {
                return match;
            }
            else if (stopPos > 0 && matchIndex > stopPos) {
                return null;
            }
        }
        return null;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[313/*vs/editor/common/cursor/cursorAtomicMoveOperations*/], __M([1/*require*/,0/*exports*/,94/*vs/editor/common/core/cursorColumns*/]), function (require, exports, cursorColumns_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AtomicTabMoveOperations = void 0;
    class AtomicTabMoveOperations {
        /**
         * Get the visible column at the position. If we get to a non-whitespace character first
         * or past the end of string then return -1.
         *
         * **Note** `position` and the return value are 0-based.
         */
        static whitespaceVisibleColumn(lineContent, position, tabSize) {
            const lineLength = lineContent.length;
            let visibleColumn = 0;
            let prevTabStopPosition = -1;
            let prevTabStopVisibleColumn = -1;
            for (let i = 0; i < lineLength; i++) {
                if (i === position) {
                    return [prevTabStopPosition, prevTabStopVisibleColumn, visibleColumn];
                }
                if (visibleColumn % tabSize === 0) {
                    prevTabStopPosition = i;
                    prevTabStopVisibleColumn = visibleColumn;
                }
                const chCode = lineContent.charCodeAt(i);
                switch (chCode) {
                    case 32 /* CharCode.Space */:
                        visibleColumn += 1;
                        break;
                    case 9 /* CharCode.Tab */:
                        // Skip to the next multiple of tabSize.
                        visibleColumn = cursorColumns_1.CursorColumns.nextRenderTabStop(visibleColumn, tabSize);
                        break;
                    default:
                        return [-1, -1, -1];
                }
            }
            if (position === lineLength) {
                return [prevTabStopPosition, prevTabStopVisibleColumn, visibleColumn];
            }
            return [-1, -1, -1];
        }
        /**
         * Return the position that should result from a move left, right or to the
         * nearest tab, if atomic tabs are enabled. Left and right are used for the
         * arrow key movements, nearest is used for mouse selection. It returns
         * -1 if atomic tabs are not relevant and you should fall back to normal
         * behaviour.
         *
         * **Note**: `position` and the return value are 0-based.
         */
        static atomicPosition(lineContent, position, tabSize, direction) {
            const lineLength = lineContent.length;
            // Get the 0-based visible column corresponding to the position, or return
            // -1 if it is not in the initial whitespace.
            const [prevTabStopPosition, prevTabStopVisibleColumn, visibleColumn] = AtomicTabMoveOperations.whitespaceVisibleColumn(lineContent, position, tabSize);
            if (visibleColumn === -1) {
                return -1;
            }
            // Is the output left or right of the current position. The case for nearest
            // where it is the same as the current position is handled in the switch.
            let left;
            switch (direction) {
                case 0 /* Direction.Left */:
                    left = true;
                    break;
                case 1 /* Direction.Right */:
                    left = false;
                    break;
                case 2 /* Direction.Nearest */:
                    // The code below assumes the output position is either left or right
                    // of the input position. If it is the same, return immediately.
                    if (visibleColumn % tabSize === 0) {
                        return position;
                    }
                    // Go to the nearest indentation.
                    left = visibleColumn % tabSize <= (tabSize / 2);
                    break;
            }
            // If going left, we can just use the info about the last tab stop position and
            // last tab stop visible column that we computed in the first walk over the whitespace.
            if (left) {
                if (prevTabStopPosition === -1) {
                    return -1;
                }
                // If the direction is left, we need to keep scanning right to ensure
                // that targetVisibleColumn + tabSize is before non-whitespace.
                // This is so that when we press left at the end of a partial
                // indentation it only goes one character. For example '      foo' with
                // tabSize 4, should jump from position 6 to position 5, not 4.
                let currentVisibleColumn = prevTabStopVisibleColumn;
                for (let i = prevTabStopPosition; i < lineLength; ++i) {
                    if (currentVisibleColumn === prevTabStopVisibleColumn + tabSize) {
                        // It is a full indentation.
                        return prevTabStopPosition;
                    }
                    const chCode = lineContent.charCodeAt(i);
                    switch (chCode) {
                        case 32 /* CharCode.Space */:
                            currentVisibleColumn += 1;
                            break;
                        case 9 /* CharCode.Tab */:
                            currentVisibleColumn = cursorColumns_1.CursorColumns.nextRenderTabStop(currentVisibleColumn, tabSize);
                            break;
                        default:
                            return -1;
                    }
                }
                if (currentVisibleColumn === prevTabStopVisibleColumn + tabSize) {
                    return prevTabStopPosition;
                }
                // It must have been a partial indentation.
                return -1;
            }
            // We are going right.
            const targetVisibleColumn = cursorColumns_1.CursorColumns.nextRenderTabStop(visibleColumn, tabSize);
            // We can just continue from where whitespaceVisibleColumn got to.
            let currentVisibleColumn = visibleColumn;
            for (let i = position; i < lineLength; i++) {
                if (currentVisibleColumn === targetVisibleColumn) {
                    return i;
                }
                const chCode = lineContent.charCodeAt(i);
                switch (chCode) {
                    case 32 /* CharCode.Space */:
                        currentVisibleColumn += 1;
                        break;
                    case 9 /* CharCode.Tab */:
                        currentVisibleColumn = cursorColumns_1.CursorColumns.nextRenderTabStop(currentVisibleColumn, tabSize);
                        break;
                    default:
                        return -1;
                }
            }
            // This condition handles when the target column is at the end of the line.
            if (currentVisibleColumn === targetVisibleColumn) {
                return lineLength;
            }
            return -1;
        }
    }
    exports.AtomicTabMoveOperations = AtomicTabMoveOperations;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[556/*vs/editor/common/cursor/cursorContext*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CursorContext = void 0;
    class CursorContext {
        constructor(model, viewModel, coordinatesConverter, cursorConfig) {
            this._cursorContextBrand = undefined;
            this.model = model;
            this.viewModel = viewModel;
            this.coordinatesConverter = coordinatesConverter;
            this.cursorConfig = cursorConfig;
        }
    }
    exports.CursorContext = CursorContext;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[167/*vs/editor/common/diff/defaultLinesDiffComputer/algorithms/diffAlgorithm*/], __M([1/*require*/,0/*exports*/,13/*vs/base/common/arrays*/,8/*vs/base/common/errors*/,68/*vs/editor/common/core/offsetRange*/]), function (require, exports, arrays_1, errors_1, offsetRange_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DateTimeout = exports.InfiniteTimeout = exports.OffsetPair = exports.SequenceDiff = exports.DiffAlgorithmResult = void 0;
    class DiffAlgorithmResult {
        static trivial(seq1, seq2) {
            return new DiffAlgorithmResult([new SequenceDiff(offsetRange_1.OffsetRange.ofLength(seq1.length), offsetRange_1.OffsetRange.ofLength(seq2.length))], false);
        }
        static trivialTimedOut(seq1, seq2) {
            return new DiffAlgorithmResult([new SequenceDiff(offsetRange_1.OffsetRange.ofLength(seq1.length), offsetRange_1.OffsetRange.ofLength(seq2.length))], true);
        }
        constructor(diffs, 
        /**
         * Indicates if the time out was reached.
         * In that case, the diffs might be an approximation and the user should be asked to rerun the diff with more time.
         */
        hitTimeout) {
            this.diffs = diffs;
            this.hitTimeout = hitTimeout;
        }
    }
    exports.DiffAlgorithmResult = DiffAlgorithmResult;
    class SequenceDiff {
        static invert(sequenceDiffs, doc1Length) {
            const result = [];
            (0, arrays_1.forEachAdjacent)(sequenceDiffs, (a, b) => {
                result.push(SequenceDiff.fromOffsetPairs(a ? a.getEndExclusives() : OffsetPair.zero, b ? b.getStarts() : new OffsetPair(doc1Length, (a ? a.seq2Range.endExclusive - a.seq1Range.endExclusive : 0) + doc1Length)));
            });
            return result;
        }
        static fromOffsetPairs(start, endExclusive) {
            return new SequenceDiff(new offsetRange_1.OffsetRange(start.offset1, endExclusive.offset1), new offsetRange_1.OffsetRange(start.offset2, endExclusive.offset2));
        }
        static assertSorted(sequenceDiffs) {
            let last = undefined;
            for (const cur of sequenceDiffs) {
                if (last) {
                    if (!(last.seq1Range.endExclusive <= cur.seq1Range.start && last.seq2Range.endExclusive <= cur.seq2Range.start)) {
                        throw new errors_1.BugIndicatingError('Sequence diffs must be sorted');
                    }
                }
                last = cur;
            }
        }
        constructor(seq1Range, seq2Range) {
            this.seq1Range = seq1Range;
            this.seq2Range = seq2Range;
        }
        swap() {
            return new SequenceDiff(this.seq2Range, this.seq1Range);
        }
        toString() {
            return `${this.seq1Range} <-> ${this.seq2Range}`;
        }
        join(other) {
            return new SequenceDiff(this.seq1Range.join(other.seq1Range), this.seq2Range.join(other.seq2Range));
        }
        delta(offset) {
            if (offset === 0) {
                return this;
            }
            return new SequenceDiff(this.seq1Range.delta(offset), this.seq2Range.delta(offset));
        }
        deltaStart(offset) {
            if (offset === 0) {
                return this;
            }
            return new SequenceDiff(this.seq1Range.deltaStart(offset), this.seq2Range.deltaStart(offset));
        }
        deltaEnd(offset) {
            if (offset === 0) {
                return this;
            }
            return new SequenceDiff(this.seq1Range.deltaEnd(offset), this.seq2Range.deltaEnd(offset));
        }
        intersect(other) {
            const i1 = this.seq1Range.intersect(other.seq1Range);
            const i2 = this.seq2Range.intersect(other.seq2Range);
            if (!i1 || !i2) {
                return undefined;
            }
            return new SequenceDiff(i1, i2);
        }
        getStarts() {
            return new OffsetPair(this.seq1Range.start, this.seq2Range.start);
        }
        getEndExclusives() {
            return new OffsetPair(this.seq1Range.endExclusive, this.seq2Range.endExclusive);
        }
    }
    exports.SequenceDiff = SequenceDiff;
    class OffsetPair {
        static { this.zero = new OffsetPair(0, 0); }
        static { this.max = new OffsetPair(Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER); }
        constructor(offset1, offset2) {
            this.offset1 = offset1;
            this.offset2 = offset2;
        }
        toString() {
            return `${this.offset1} <-> ${this.offset2}`;
        }
        delta(offset) {
            if (offset === 0) {
                return this;
            }
            return new OffsetPair(this.offset1 + offset, this.offset2 + offset);
        }
        equals(other) {
            return this.offset1 === other.offset1 && this.offset2 === other.offset2;
        }
    }
    exports.OffsetPair = OffsetPair;
    class InfiniteTimeout {
        static { this.instance = new InfiniteTimeout(); }
        isValid() {
            return true;
        }
    }
    exports.InfiniteTimeout = InfiniteTimeout;
    class DateTimeout {
        constructor(timeout) {
            this.timeout = timeout;
            this.startTime = Date.now();
            this.valid = true;
            if (timeout <= 0) {
                throw new errors_1.BugIndicatingError('timeout must be positive');
            }
        }
        // Recommendation: Set a log-point `{this.disable()}` in the body
        isValid() {
            const valid = Date.now() - this.startTime < this.timeout;
            if (!valid && this.valid) {
                this.valid = false; // timeout reached
                // eslint-disable-next-line no-debugger
                debugger; // WARNING: Most likely debugging caused the timeout. Call `this.disable()` to continue without timing out.
            }
            return this.valid;
        }
    }
    exports.DateTimeout = DateTimeout;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[314/*vs/editor/common/diff/defaultLinesDiffComputer/algorithms/myersDiffAlgorithm*/], __M([1/*require*/,0/*exports*/,68/*vs/editor/common/core/offsetRange*/,167/*vs/editor/common/diff/defaultLinesDiffComputer/algorithms/diffAlgorithm*/]), function (require, exports, offsetRange_1, diffAlgorithm_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MyersDiffAlgorithm = void 0;
    /**
     * An O(ND) diff algorithm that has a quadratic space worst-case complexity.
    */
    class MyersDiffAlgorithm {
        compute(seq1, seq2, timeout = diffAlgorithm_1.InfiniteTimeout.instance) {
            // These are common special cases.
            // The early return improves performance dramatically.
            if (seq1.length === 0 || seq2.length === 0) {
                return diffAlgorithm_1.DiffAlgorithmResult.trivial(seq1, seq2);
            }
            const seqX = seq1; // Text on the x axis
            const seqY = seq2; // Text on the y axis
            function getXAfterSnake(x, y) {
                while (x < seqX.length && y < seqY.length && seqX.getElement(x) === seqY.getElement(y)) {
                    x++;
                    y++;
                }
                return x;
            }
            let d = 0;
            // V[k]: X value of longest d-line that ends in diagonal k.
            // d-line: path from (0,0) to (x,y) that uses exactly d non-diagonals.
            // diagonal k: Set of points (x,y) with x-y = k.
            // k=1 -> (1,0),(2,1)
            const V = new FastInt32Array();
            V.set(0, getXAfterSnake(0, 0));
            const paths = new FastArrayNegativeIndices();
            paths.set(0, V.get(0) === 0 ? null : new SnakePath(null, 0, 0, V.get(0)));
            let k = 0;
            loop: while (true) {
                d++;
                if (!timeout.isValid()) {
                    return diffAlgorithm_1.DiffAlgorithmResult.trivialTimedOut(seqX, seqY);
                }
                // The paper has `for (k = -d; k <= d; k += 2)`, but we can ignore diagonals that cannot influence the result.
                const lowerBound = -Math.min(d, seqY.length + (d % 2));
                const upperBound = Math.min(d, seqX.length + (d % 2));
                for (k = lowerBound; k <= upperBound; k += 2) {
                    let step = 0;
                    // We can use the X values of (d-1)-lines to compute X value of the longest d-lines.
                    const maxXofDLineTop = k === upperBound ? -1 : V.get(k + 1); // We take a vertical non-diagonal (add a symbol in seqX)
                    const maxXofDLineLeft = k === lowerBound ? -1 : V.get(k - 1) + 1; // We take a horizontal non-diagonal (+1 x) (delete a symbol in seqX)
                    step++;
                    const x = Math.min(Math.max(maxXofDLineTop, maxXofDLineLeft), seqX.length);
                    const y = x - k;
                    step++;
                    if (x > seqX.length || y > seqY.length) {
                        // This diagonal is irrelevant for the result.
                        // TODO: Don't pay the cost for this in the next iteration.
                        continue;
                    }
                    const newMaxX = getXAfterSnake(x, y);
                    V.set(k, newMaxX);
                    const lastPath = x === maxXofDLineTop ? paths.get(k + 1) : paths.get(k - 1);
                    paths.set(k, newMaxX !== x ? new SnakePath(lastPath, x, y, newMaxX - x) : lastPath);
                    if (V.get(k) === seqX.length && V.get(k) - k === seqY.length) {
                        break loop;
                    }
                }
            }
            let path = paths.get(k);
            const result = [];
            let lastAligningPosS1 = seqX.length;
            let lastAligningPosS2 = seqY.length;
            while (true) {
                const endX = path ? path.x + path.length : 0;
                const endY = path ? path.y + path.length : 0;
                if (endX !== lastAligningPosS1 || endY !== lastAligningPosS2) {
                    result.push(new diffAlgorithm_1.SequenceDiff(new offsetRange_1.OffsetRange(endX, lastAligningPosS1), new offsetRange_1.OffsetRange(endY, lastAligningPosS2)));
                }
                if (!path) {
                    break;
                }
                lastAligningPosS1 = path.x;
                lastAligningPosS2 = path.y;
                path = path.prev;
            }
            result.reverse();
            return new diffAlgorithm_1.DiffAlgorithmResult(result, false);
        }
    }
    exports.MyersDiffAlgorithm = MyersDiffAlgorithm;
    class SnakePath {
        constructor(prev, x, y, length) {
            this.prev = prev;
            this.x = x;
            this.y = y;
            this.length = length;
        }
    }
    /**
     * An array that supports fast negative indices.
    */
    class FastInt32Array {
        constructor() {
            this.positiveArr = new Int32Array(10);
            this.negativeArr = new Int32Array(10);
        }
        get(idx) {
            if (idx < 0) {
                idx = -idx - 1;
                return this.negativeArr[idx];
            }
            else {
                return this.positiveArr[idx];
            }
        }
        set(idx, value) {
            if (idx < 0) {
                idx = -idx - 1;
                if (idx >= this.negativeArr.length) {
                    const arr = this.negativeArr;
                    this.negativeArr = new Int32Array(arr.length * 2);
                    this.negativeArr.set(arr);
                }
                this.negativeArr[idx] = value;
            }
            else {
                if (idx >= this.positiveArr.length) {
                    const arr = this.positiveArr;
                    this.positiveArr = new Int32Array(arr.length * 2);
                    this.positiveArr.set(arr);
                }
                this.positiveArr[idx] = value;
            }
        }
    }
    /**
     * An array that supports fast negative indices.
    */
    class FastArrayNegativeIndices {
        constructor() {
            this.positiveArr = [];
            this.negativeArr = [];
        }
        get(idx) {
            if (idx < 0) {
                idx = -idx - 1;
                return this.negativeArr[idx];
            }
            else {
                return this.positiveArr[idx];
            }
        }
        set(idx, value) {
            if (idx < 0) {
                idx = -idx - 1;
                this.negativeArr[idx] = value;
            }
            else {
                this.positiveArr[idx] = value;
            }
        }
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[315/*vs/editor/common/diff/defaultLinesDiffComputer/heuristicSequenceOptimizations*/], __M([1/*require*/,0/*exports*/,13/*vs/base/common/arrays*/,68/*vs/editor/common/core/offsetRange*/,167/*vs/editor/common/diff/defaultLinesDiffComputer/algorithms/diffAlgorithm*/]), function (require, exports, arrays_1, offsetRange_1, diffAlgorithm_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.optimizeSequenceDiffs = optimizeSequenceDiffs;
    exports.removeShortMatches = removeShortMatches;
    exports.extendDiffsToEntireWordIfAppropriate = extendDiffsToEntireWordIfAppropriate;
    exports.removeVeryShortMatchingLinesBetweenDiffs = removeVeryShortMatchingLinesBetweenDiffs;
    exports.removeVeryShortMatchingTextBetweenLongDiffs = removeVeryShortMatchingTextBetweenLongDiffs;
    function optimizeSequenceDiffs(sequence1, sequence2, sequenceDiffs) {
        let result = sequenceDiffs;
        result = joinSequenceDiffsByShifting(sequence1, sequence2, result);
        // Sometimes, calling this function twice improves the result.
        // Uncomment the second invocation and run the tests to see the difference.
        result = joinSequenceDiffsByShifting(sequence1, sequence2, result);
        result = shiftSequenceDiffs(sequence1, sequence2, result);
        return result;
    }
    /**
     * This function fixes issues like this:
     * ```
     * import { Baz, Bar } from "foo";
     * ```
     * <->
     * ```
     * import { Baz, Bar, Foo } from "foo";
     * ```
     * Computed diff: [ {Add "," after Bar}, {Add "Foo " after space} }
     * Improved diff: [{Add ", Foo" after Bar}]
     */
    function joinSequenceDiffsByShifting(sequence1, sequence2, sequenceDiffs) {
        if (sequenceDiffs.length === 0) {
            return sequenceDiffs;
        }
        const result = [];
        result.push(sequenceDiffs[0]);
        // First move them all to the left as much as possible and join them if possible
        for (let i = 1; i < sequenceDiffs.length; i++) {
            const prevResult = result[result.length - 1];
            let cur = sequenceDiffs[i];
            if (cur.seq1Range.isEmpty || cur.seq2Range.isEmpty) {
                const length = cur.seq1Range.start - prevResult.seq1Range.endExclusive;
                let d;
                for (d = 1; d <= length; d++) {
                    if (sequence1.getElement(cur.seq1Range.start - d) !== sequence1.getElement(cur.seq1Range.endExclusive - d) ||
                        sequence2.getElement(cur.seq2Range.start - d) !== sequence2.getElement(cur.seq2Range.endExclusive - d)) {
                        break;
                    }
                }
                d--;
                if (d === length) {
                    // Merge previous and current diff
                    result[result.length - 1] = new diffAlgorithm_1.SequenceDiff(new offsetRange_1.OffsetRange(prevResult.seq1Range.start, cur.seq1Range.endExclusive - length), new offsetRange_1.OffsetRange(prevResult.seq2Range.start, cur.seq2Range.endExclusive - length));
                    continue;
                }
                cur = cur.delta(-d);
            }
            result.push(cur);
        }
        const result2 = [];
        // Then move them all to the right and join them again if possible
        for (let i = 0; i < result.length - 1; i++) {
            const nextResult = result[i + 1];
            let cur = result[i];
            if (cur.seq1Range.isEmpty || cur.seq2Range.isEmpty) {
                const length = nextResult.seq1Range.start - cur.seq1Range.endExclusive;
                let d;
                for (d = 0; d < length; d++) {
                    if (!sequence1.isStronglyEqual(cur.seq1Range.start + d, cur.seq1Range.endExclusive + d) ||
                        !sequence2.isStronglyEqual(cur.seq2Range.start + d, cur.seq2Range.endExclusive + d)) {
                        break;
                    }
                }
                if (d === length) {
                    // Merge previous and current diff, write to result!
                    result[i + 1] = new diffAlgorithm_1.SequenceDiff(new offsetRange_1.OffsetRange(cur.seq1Range.start + length, nextResult.seq1Range.endExclusive), new offsetRange_1.OffsetRange(cur.seq2Range.start + length, nextResult.seq2Range.endExclusive));
                    continue;
                }
                if (d > 0) {
                    cur = cur.delta(d);
                }
            }
            result2.push(cur);
        }
        if (result.length > 0) {
            result2.push(result[result.length - 1]);
        }
        return result2;
    }
    // align character level diffs at whitespace characters
    // import { IBar } from "foo";
    // import { I[Arr, I]Bar } from "foo";
    // ->
    // import { [IArr, ]IBar } from "foo";
    // import { ITransaction, observableValue, transaction } from 'vs/base/common/observable';
    // import { ITransaction, observable[FromEvent, observable]Value, transaction } from 'vs/base/common/observable';
    // ->
    // import { ITransaction, [observableFromEvent, ]observableValue, transaction } from 'vs/base/common/observable';
    // collectBrackets(level + 1, levelPerBracketType);
    // collectBrackets(level + 1, levelPerBracket[ + 1, levelPerBracket]Type);
    // ->
    // collectBrackets(level + 1, [levelPerBracket + 1, ]levelPerBracketType);
    function shiftSequenceDiffs(sequence1, sequence2, sequenceDiffs) {
        if (!sequence1.getBoundaryScore || !sequence2.getBoundaryScore) {
            return sequenceDiffs;
        }
        for (let i = 0; i < sequenceDiffs.length; i++) {
            const prevDiff = (i > 0 ? sequenceDiffs[i - 1] : undefined);
            const diff = sequenceDiffs[i];
            const nextDiff = (i + 1 < sequenceDiffs.length ? sequenceDiffs[i + 1] : undefined);
            const seq1ValidRange = new offsetRange_1.OffsetRange(prevDiff ? prevDiff.seq1Range.endExclusive + 1 : 0, nextDiff ? nextDiff.seq1Range.start - 1 : sequence1.length);
            const seq2ValidRange = new offsetRange_1.OffsetRange(prevDiff ? prevDiff.seq2Range.endExclusive + 1 : 0, nextDiff ? nextDiff.seq2Range.start - 1 : sequence2.length);
            if (diff.seq1Range.isEmpty) {
                sequenceDiffs[i] = shiftDiffToBetterPosition(diff, sequence1, sequence2, seq1ValidRange, seq2ValidRange);
            }
            else if (diff.seq2Range.isEmpty) {
                sequenceDiffs[i] = shiftDiffToBetterPosition(diff.swap(), sequence2, sequence1, seq2ValidRange, seq1ValidRange).swap();
            }
        }
        return sequenceDiffs;
    }
    function shiftDiffToBetterPosition(diff, sequence1, sequence2, seq1ValidRange, seq2ValidRange) {
        const maxShiftLimit = 100; // To prevent performance issues
        // don't touch previous or next!
        let deltaBefore = 1;
        while (diff.seq1Range.start - deltaBefore >= seq1ValidRange.start &&
            diff.seq2Range.start - deltaBefore >= seq2ValidRange.start &&
            sequence2.isStronglyEqual(diff.seq2Range.start - deltaBefore, diff.seq2Range.endExclusive - deltaBefore) && deltaBefore < maxShiftLimit) {
            deltaBefore++;
        }
        deltaBefore--;
        let deltaAfter = 0;
        while (diff.seq1Range.start + deltaAfter < seq1ValidRange.endExclusive &&
            diff.seq2Range.endExclusive + deltaAfter < seq2ValidRange.endExclusive &&
            sequence2.isStronglyEqual(diff.seq2Range.start + deltaAfter, diff.seq2Range.endExclusive + deltaAfter) && deltaAfter < maxShiftLimit) {
            deltaAfter++;
        }
        if (deltaBefore === 0 && deltaAfter === 0) {
            return diff;
        }
        // Visualize `[sequence1.text, diff.seq1Range.start + deltaAfter]`
        // and `[sequence2.text, diff.seq2Range.start + deltaAfter, diff.seq2Range.endExclusive + deltaAfter]`
        let bestDelta = 0;
        let bestScore = -1;
        // find best scored delta
        for (let delta = -deltaBefore; delta <= deltaAfter; delta++) {
            const seq2OffsetStart = diff.seq2Range.start + delta;
            const seq2OffsetEndExclusive = diff.seq2Range.endExclusive + delta;
            const seq1Offset = diff.seq1Range.start + delta;
            const score = sequence1.getBoundaryScore(seq1Offset) + sequence2.getBoundaryScore(seq2OffsetStart) + sequence2.getBoundaryScore(seq2OffsetEndExclusive);
            if (score > bestScore) {
                bestScore = score;
                bestDelta = delta;
            }
        }
        return diff.delta(bestDelta);
    }
    function removeShortMatches(sequence1, sequence2, sequenceDiffs) {
        const result = [];
        for (const s of sequenceDiffs) {
            const last = result[result.length - 1];
            if (!last) {
                result.push(s);
                continue;
            }
            if (s.seq1Range.start - last.seq1Range.endExclusive <= 2 || s.seq2Range.start - last.seq2Range.endExclusive <= 2) {
                result[result.length - 1] = new diffAlgorithm_1.SequenceDiff(last.seq1Range.join(s.seq1Range), last.seq2Range.join(s.seq2Range));
            }
            else {
                result.push(s);
            }
        }
        return result;
    }
    function extendDiffsToEntireWordIfAppropriate(sequence1, sequence2, sequenceDiffs) {
        const equalMappings = diffAlgorithm_1.SequenceDiff.invert(sequenceDiffs, sequence1.length);
        const additional = [];
        let lastPoint = new diffAlgorithm_1.OffsetPair(0, 0);
        function scanWord(pair, equalMapping) {
            if (pair.offset1 < lastPoint.offset1 || pair.offset2 < lastPoint.offset2) {
                return;
            }
            const w1 = sequence1.findWordContaining(pair.offset1);
            const w2 = sequence2.findWordContaining(pair.offset2);
            if (!w1 || !w2) {
                return;
            }
            let w = new diffAlgorithm_1.SequenceDiff(w1, w2);
            const equalPart = w.intersect(equalMapping);
            let equalChars1 = equalPart.seq1Range.length;
            let equalChars2 = equalPart.seq2Range.length;
            // The words do not touch previous equals mappings, as we would have processed them already.
            // But they might touch the next ones.
            while (equalMappings.length > 0) {
                const next = equalMappings[0];
                const intersects = next.seq1Range.intersects(w.seq1Range) || next.seq2Range.intersects(w.seq2Range);
                if (!intersects) {
                    break;
                }
                const v1 = sequence1.findWordContaining(next.seq1Range.start);
                const v2 = sequence2.findWordContaining(next.seq2Range.start);
                // Because there is an intersection, we know that the words are not empty.
                const v = new diffAlgorithm_1.SequenceDiff(v1, v2);
                const equalPart = v.intersect(next);
                equalChars1 += equalPart.seq1Range.length;
                equalChars2 += equalPart.seq2Range.length;
                w = w.join(v);
                if (w.seq1Range.endExclusive >= next.seq1Range.endExclusive) {
                    // The word extends beyond the next equal mapping.
                    equalMappings.shift();
                }
                else {
                    break;
                }
            }
            if (equalChars1 + equalChars2 < (w.seq1Range.length + w.seq2Range.length) * 2 / 3) {
                additional.push(w);
            }
            lastPoint = w.getEndExclusives();
        }
        while (equalMappings.length > 0) {
            const next = equalMappings.shift();
            if (next.seq1Range.isEmpty) {
                continue;
            }
            scanWord(next.getStarts(), next);
            // The equal parts are not empty, so -1 gives us a character that is equal in both parts.
            scanWord(next.getEndExclusives().delta(-1), next);
        }
        const merged = mergeSequenceDiffs(sequenceDiffs, additional);
        return merged;
    }
    function mergeSequenceDiffs(sequenceDiffs1, sequenceDiffs2) {
        const result = [];
        while (sequenceDiffs1.length > 0 || sequenceDiffs2.length > 0) {
            const sd1 = sequenceDiffs1[0];
            const sd2 = sequenceDiffs2[0];
            let next;
            if (sd1 && (!sd2 || sd1.seq1Range.start < sd2.seq1Range.start)) {
                next = sequenceDiffs1.shift();
            }
            else {
                next = sequenceDiffs2.shift();
            }
            if (result.length > 0 && result[result.length - 1].seq1Range.endExclusive >= next.seq1Range.start) {
                result[result.length - 1] = result[result.length - 1].join(next);
            }
            else {
                result.push(next);
            }
        }
        return result;
    }
    function removeVeryShortMatchingLinesBetweenDiffs(sequence1, _sequence2, sequenceDiffs) {
        let diffs = sequenceDiffs;
        if (diffs.length === 0) {
            return diffs;
        }
        let counter = 0;
        let shouldRepeat;
        do {
            shouldRepeat = false;
            const result = [
                diffs[0]
            ];
            for (let i = 1; i < diffs.length; i++) {
                const cur = diffs[i];
                const lastResult = result[result.length - 1];
                function shouldJoinDiffs(before, after) {
                    const unchangedRange = new offsetRange_1.OffsetRange(lastResult.seq1Range.endExclusive, cur.seq1Range.start);
                    const unchangedText = sequence1.getText(unchangedRange);
                    const unchangedTextWithoutWs = unchangedText.replace(/\s/g, '');
                    if (unchangedTextWithoutWs.length <= 4
                        && (before.seq1Range.length + before.seq2Range.length > 5 || after.seq1Range.length + after.seq2Range.length > 5)) {
                        return true;
                    }
                    return false;
                }
                const shouldJoin = shouldJoinDiffs(lastResult, cur);
                if (shouldJoin) {
                    shouldRepeat = true;
                    result[result.length - 1] = result[result.length - 1].join(cur);
                }
                else {
                    result.push(cur);
                }
            }
            diffs = result;
        } while (counter++ < 10 && shouldRepeat);
        return diffs;
    }
    function removeVeryShortMatchingTextBetweenLongDiffs(sequence1, sequence2, sequenceDiffs) {
        let diffs = sequenceDiffs;
        if (diffs.length === 0) {
            return diffs;
        }
        let counter = 0;
        let shouldRepeat;
        do {
            shouldRepeat = false;
            const result = [
                diffs[0]
            ];
            for (let i = 1; i < diffs.length; i++) {
                const cur = diffs[i];
                const lastResult = result[result.length - 1];
                function shouldJoinDiffs(before, after) {
                    const unchangedRange = new offsetRange_1.OffsetRange(lastResult.seq1Range.endExclusive, cur.seq1Range.start);
                    const unchangedLineCount = sequence1.countLinesIn(unchangedRange);
                    if (unchangedLineCount > 5 || unchangedRange.length > 500) {
                        return false;
                    }
                    const unchangedText = sequence1.getText(unchangedRange).trim();
                    if (unchangedText.length > 20 || unchangedText.split(/\r\n|\r|\n/).length > 1) {
                        return false;
                    }
                    const beforeLineCount1 = sequence1.countLinesIn(before.seq1Range);
                    const beforeSeq1Length = before.seq1Range.length;
                    const beforeLineCount2 = sequence2.countLinesIn(before.seq2Range);
                    const beforeSeq2Length = before.seq2Range.length;
                    const afterLineCount1 = sequence1.countLinesIn(after.seq1Range);
                    const afterSeq1Length = after.seq1Range.length;
                    const afterLineCount2 = sequence2.countLinesIn(after.seq2Range);
                    const afterSeq2Length = after.seq2Range.length;
                    // TODO: Maybe a neural net can be used to derive the result from these numbers
                    const max = 2 * 40 + 50;
                    function cap(v) {
                        return Math.min(v, max);
                    }
                    if (Math.pow(Math.pow(cap(beforeLineCount1 * 40 + beforeSeq1Length), 1.5) + Math.pow(cap(beforeLineCount2 * 40 + beforeSeq2Length), 1.5), 1.5)
                        + Math.pow(Math.pow(cap(afterLineCount1 * 40 + afterSeq1Length), 1.5) + Math.pow(cap(afterLineCount2 * 40 + afterSeq2Length), 1.5), 1.5) > ((max ** 1.5) ** 1.5) * 1.3) {
                        return true;
                    }
                    return false;
                }
                const shouldJoin = shouldJoinDiffs(lastResult, cur);
                if (shouldJoin) {
                    shouldRepeat = true;
                    result[result.length - 1] = result[result.length - 1].join(cur);
                }
                else {
                    result.push(cur);
                }
            }
            diffs = result;
        } while (counter++ < 10 && shouldRepeat);
        const newDiffs = [];
        // Remove short suffixes/prefixes
        (0, arrays_1.forEachWithNeighbors)(diffs, (prev, cur, next) => {
            let newDiff = cur;
            function shouldMarkAsChanged(text) {
                return text.length > 0 && text.trim().length <= 3 && cur.seq1Range.length + cur.seq2Range.length > 100;
            }
            const fullRange1 = sequence1.extendToFullLines(cur.seq1Range);
            const prefix = sequence1.getText(new offsetRange_1.OffsetRange(fullRange1.start, cur.seq1Range.start));
            if (shouldMarkAsChanged(prefix)) {
                newDiff = newDiff.deltaStart(-prefix.length);
            }
            const suffix = sequence1.getText(new offsetRange_1.OffsetRange(cur.seq1Range.endExclusive, fullRange1.endExclusive));
            if (shouldMarkAsChanged(suffix)) {
                newDiff = newDiff.deltaEnd(suffix.length);
            }
            const availableSpace = diffAlgorithm_1.SequenceDiff.fromOffsetPairs(prev ? prev.getEndExclusives() : diffAlgorithm_1.OffsetPair.zero, next ? next.getStarts() : diffAlgorithm_1.OffsetPair.max);
            const result = newDiff.intersect(availableSpace);
            if (newDiffs.length > 0 && result.getStarts().equals(newDiffs[newDiffs.length - 1].getEndExclusives())) {
                newDiffs[newDiffs.length - 1] = newDiffs[newDiffs.length - 1].join(result);
            }
            else {
                newDiffs.push(result);
            }
        });
        return newDiffs;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[557/*vs/editor/common/diff/defaultLinesDiffComputer/lineSequence*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.LineSequence = void 0;
    class LineSequence {
        constructor(trimmedHash, lines) {
            this.trimmedHash = trimmedHash;
            this.lines = lines;
        }
        getElement(offset) {
            return this.trimmedHash[offset];
        }
        get length() {
            return this.trimmedHash.length;
        }
        getBoundaryScore(length) {
            const indentationBefore = length === 0 ? 0 : getIndentation(this.lines[length - 1]);
            const indentationAfter = length === this.lines.length ? 0 : getIndentation(this.lines[length]);
            return 1000 - (indentationBefore + indentationAfter);
        }
        getText(range) {
            return this.lines.slice(range.start, range.endExclusive).join('\n');
        }
        isStronglyEqual(offset1, offset2) {
            return this.lines[offset1] === this.lines[offset2];
        }
    }
    exports.LineSequence = LineSequence;
    function getIndentation(str) {
        let i = 0;
        while (i < str.length && (str.charCodeAt(i) === 32 /* CharCode.Space */ || str.charCodeAt(i) === 9 /* CharCode.Tab */)) {
            i++;
        }
        return i;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[231/*vs/editor/common/diff/defaultLinesDiffComputer/utils*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.LineRangeFragment = exports.Array2D = void 0;
    exports.isSpace = isSpace;
    class Array2D {
        constructor(width, height) {
            this.width = width;
            this.height = height;
            this.array = [];
            this.array = new Array(width * height);
        }
        get(x, y) {
            return this.array[x + y * this.width];
        }
        set(x, y, value) {
            this.array[x + y * this.width] = value;
        }
    }
    exports.Array2D = Array2D;
    function isSpace(charCode) {
        return charCode === 32 /* CharCode.Space */ || charCode === 9 /* CharCode.Tab */;
    }
    class LineRangeFragment {
        static { this.chrKeys = new Map(); }
        static getKey(chr) {
            let key = this.chrKeys.get(chr);
            if (key === undefined) {
                key = this.chrKeys.size;
                this.chrKeys.set(chr, key);
            }
            return key;
        }
        constructor(range, lines, source) {
            this.range = range;
            this.lines = lines;
            this.source = source;
            this.histogram = [];
            let counter = 0;
            for (let i = range.startLineNumber - 1; i < range.endLineNumberExclusive - 1; i++) {
                const line = lines[i];
                for (let j = 0; j < line.length; j++) {
                    counter++;
                    const chr = line[j];
                    const key = LineRangeFragment.getKey(chr);
                    this.histogram[key] = (this.histogram[key] || 0) + 1;
                }
                counter++;
                const key = LineRangeFragment.getKey('\n');
                this.histogram[key] = (this.histogram[key] || 0) + 1;
            }
            this.totalCount = counter;
        }
        computeSimilarity(other) {
            let sumDifferences = 0;
            const maxLength = Math.max(this.histogram.length, other.histogram.length);
            for (let i = 0; i < maxLength; i++) {
                sumDifferences += Math.abs((this.histogram[i] ?? 0) - (other.histogram[i] ?? 0));
            }
            return 1 - (sumDifferences / (this.totalCount + other.totalCount));
        }
    }
    exports.LineRangeFragment = LineRangeFragment;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[558/*vs/editor/common/diff/defaultLinesDiffComputer/algorithms/dynamicProgrammingDiffing*/], __M([1/*require*/,0/*exports*/,68/*vs/editor/common/core/offsetRange*/,167/*vs/editor/common/diff/defaultLinesDiffComputer/algorithms/diffAlgorithm*/,231/*vs/editor/common/diff/defaultLinesDiffComputer/utils*/]), function (require, exports, offsetRange_1, diffAlgorithm_1, utils_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DynamicProgrammingDiffing = void 0;
    /**
     * A O(MN) diffing algorithm that supports a score function.
     * The algorithm can be improved by processing the 2d array diagonally.
    */
    class DynamicProgrammingDiffing {
        compute(sequence1, sequence2, timeout = diffAlgorithm_1.InfiniteTimeout.instance, equalityScore) {
            if (sequence1.length === 0 || sequence2.length === 0) {
                return diffAlgorithm_1.DiffAlgorithmResult.trivial(sequence1, sequence2);
            }
            /**
             * lcsLengths.get(i, j): Length of the longest common subsequence of sequence1.substring(0, i + 1) and sequence2.substring(0, j + 1).
             */
            const lcsLengths = new utils_1.Array2D(sequence1.length, sequence2.length);
            const directions = new utils_1.Array2D(sequence1.length, sequence2.length);
            const lengths = new utils_1.Array2D(sequence1.length, sequence2.length);
            // ==== Initializing lcsLengths ====
            for (let s1 = 0; s1 < sequence1.length; s1++) {
                for (let s2 = 0; s2 < sequence2.length; s2++) {
                    if (!timeout.isValid()) {
                        return diffAlgorithm_1.DiffAlgorithmResult.trivialTimedOut(sequence1, sequence2);
                    }
                    const horizontalLen = s1 === 0 ? 0 : lcsLengths.get(s1 - 1, s2);
                    const verticalLen = s2 === 0 ? 0 : lcsLengths.get(s1, s2 - 1);
                    let extendedSeqScore;
                    if (sequence1.getElement(s1) === sequence2.getElement(s2)) {
                        if (s1 === 0 || s2 === 0) {
                            extendedSeqScore = 0;
                        }
                        else {
                            extendedSeqScore = lcsLengths.get(s1 - 1, s2 - 1);
                        }
                        if (s1 > 0 && s2 > 0 && directions.get(s1 - 1, s2 - 1) === 3) {
                            // Prefer consecutive diagonals
                            extendedSeqScore += lengths.get(s1 - 1, s2 - 1);
                        }
                        extendedSeqScore += (equalityScore ? equalityScore(s1, s2) : 1);
                    }
                    else {
                        extendedSeqScore = -1;
                    }
                    const newValue = Math.max(horizontalLen, verticalLen, extendedSeqScore);
                    if (newValue === extendedSeqScore) {
                        // Prefer diagonals
                        const prevLen = s1 > 0 && s2 > 0 ? lengths.get(s1 - 1, s2 - 1) : 0;
                        lengths.set(s1, s2, prevLen + 1);
                        directions.set(s1, s2, 3);
                    }
                    else if (newValue === horizontalLen) {
                        lengths.set(s1, s2, 0);
                        directions.set(s1, s2, 1);
                    }
                    else if (newValue === verticalLen) {
                        lengths.set(s1, s2, 0);
                        directions.set(s1, s2, 2);
                    }
                    lcsLengths.set(s1, s2, newValue);
                }
            }
            // ==== Backtracking ====
            const result = [];
            let lastAligningPosS1 = sequence1.length;
            let lastAligningPosS2 = sequence2.length;
            function reportDecreasingAligningPositions(s1, s2) {
                if (s1 + 1 !== lastAligningPosS1 || s2 + 1 !== lastAligningPosS2) {
                    result.push(new diffAlgorithm_1.SequenceDiff(new offsetRange_1.OffsetRange(s1 + 1, lastAligningPosS1), new offsetRange_1.OffsetRange(s2 + 1, lastAligningPosS2)));
                }
                lastAligningPosS1 = s1;
                lastAligningPosS2 = s2;
            }
            let s1 = sequence1.length - 1;
            let s2 = sequence2.length - 1;
            while (s1 >= 0 && s2 >= 0) {
                if (directions.get(s1, s2) === 3) {
                    reportDecreasingAligningPositions(s1, s2);
                    s1--;
                    s2--;
                }
                else {
                    if (directions.get(s1, s2) === 1) {
                        s1--;
                    }
                    else {
                        s2--;
                    }
                }
            }
            reportDecreasingAligningPositions(-1, -1);
            result.reverse();
            return new diffAlgorithm_1.DiffAlgorithmResult(result, false);
        }
    }
    exports.DynamicProgrammingDiffing = DynamicProgrammingDiffing;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[316/*vs/editor/common/diff/defaultLinesDiffComputer/linesSliceCharSequence*/], __M([1/*require*/,0/*exports*/,67/*vs/base/common/arraysFind*/,68/*vs/editor/common/core/offsetRange*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/,231/*vs/editor/common/diff/defaultLinesDiffComputer/utils*/]), function (require, exports, arraysFind_1, offsetRange_1, position_1, range_1, utils_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.LinesSliceCharSequence = void 0;
    class LinesSliceCharSequence {
        constructor(lines, range, considerWhitespaceChanges) {
            this.lines = lines;
            this.range = range;
            this.considerWhitespaceChanges = considerWhitespaceChanges;
            this.elements = [];
            this.firstElementOffsetByLineIdx = [];
            this.lineStartOffsets = [];
            this.trimmedWsLengthsByLineIdx = [];
            this.firstElementOffsetByLineIdx.push(0);
            for (let lineNumber = this.range.startLineNumber; lineNumber <= this.range.endLineNumber; lineNumber++) {
                let line = lines[lineNumber - 1];
                let lineStartOffset = 0;
                if (lineNumber === this.range.startLineNumber && this.range.startColumn > 1) {
                    lineStartOffset = this.range.startColumn - 1;
                    line = line.substring(lineStartOffset);
                }
                this.lineStartOffsets.push(lineStartOffset);
                let trimmedWsLength = 0;
                if (!considerWhitespaceChanges) {
                    const trimmedStartLine = line.trimStart();
                    trimmedWsLength = line.length - trimmedStartLine.length;
                    line = trimmedStartLine.trimEnd();
                }
                this.trimmedWsLengthsByLineIdx.push(trimmedWsLength);
                const lineLength = lineNumber === this.range.endLineNumber ? Math.min(this.range.endColumn - 1 - lineStartOffset - trimmedWsLength, line.length) : line.length;
                for (let i = 0; i < lineLength; i++) {
                    this.elements.push(line.charCodeAt(i));
                }
                if (lineNumber < this.range.endLineNumber) {
                    this.elements.push('\n'.charCodeAt(0));
                    this.firstElementOffsetByLineIdx.push(this.elements.length);
                }
            }
        }
        toString() {
            return `Slice: "${this.text}"`;
        }
        get text() {
            return this.getText(new offsetRange_1.OffsetRange(0, this.length));
        }
        getText(range) {
            return this.elements.slice(range.start, range.endExclusive).map(e => String.fromCharCode(e)).join('');
        }
        getElement(offset) {
            return this.elements[offset];
        }
        get length() {
            return this.elements.length;
        }
        getBoundaryScore(length) {
            //   a   b   c   ,           d   e   f
            // 11  0   0   12  15  6   13  0   0   11
            const prevCategory = getCategory(length > 0 ? this.elements[length - 1] : -1);
            const nextCategory = getCategory(length < this.elements.length ? this.elements[length] : -1);
            if (prevCategory === 7 /* CharBoundaryCategory.LineBreakCR */ && nextCategory === 8 /* CharBoundaryCategory.LineBreakLF */) {
                // don't break between \r and \n
                return 0;
            }
            if (prevCategory === 8 /* CharBoundaryCategory.LineBreakLF */) {
                // prefer the linebreak before the change
                return 150;
            }
            let score = 0;
            if (prevCategory !== nextCategory) {
                score += 10;
                if (prevCategory === 0 /* CharBoundaryCategory.WordLower */ && nextCategory === 1 /* CharBoundaryCategory.WordUpper */) {
                    score += 1;
                }
            }
            score += getCategoryBoundaryScore(prevCategory);
            score += getCategoryBoundaryScore(nextCategory);
            return score;
        }
        translateOffset(offset, preference = 'right') {
            // find smallest i, so that lineBreakOffsets[i] <= offset using binary search
            const i = (0, arraysFind_1.findLastIdxMonotonous)(this.firstElementOffsetByLineIdx, (value) => value <= offset);
            const lineOffset = offset - this.firstElementOffsetByLineIdx[i];
            return new position_1.Position(this.range.startLineNumber + i, 1 + this.lineStartOffsets[i] + lineOffset + ((lineOffset === 0 && preference === 'left') ? 0 : this.trimmedWsLengthsByLineIdx[i]));
        }
        translateRange(range) {
            const pos1 = this.translateOffset(range.start, 'right');
            const pos2 = this.translateOffset(range.endExclusive, 'left');
            if (pos2.isBefore(pos1)) {
                return range_1.Range.fromPositions(pos2, pos2);
            }
            return range_1.Range.fromPositions(pos1, pos2);
        }
        /**
         * Finds the word that contains the character at the given offset
         */
        findWordContaining(offset) {
            if (offset < 0 || offset >= this.elements.length) {
                return undefined;
            }
            if (!isWordChar(this.elements[offset])) {
                return undefined;
            }
            // find start
            let start = offset;
            while (start > 0 && isWordChar(this.elements[start - 1])) {
                start--;
            }
            // find end
            let end = offset;
            while (end < this.elements.length && isWordChar(this.elements[end])) {
                end++;
            }
            return new offsetRange_1.OffsetRange(start, end);
        }
        countLinesIn(range) {
            return this.translateOffset(range.endExclusive).lineNumber - this.translateOffset(range.start).lineNumber;
        }
        isStronglyEqual(offset1, offset2) {
            return this.elements[offset1] === this.elements[offset2];
        }
        extendToFullLines(range) {
            const start = (0, arraysFind_1.findLastMonotonous)(this.firstElementOffsetByLineIdx, x => x <= range.start) ?? 0;
            const end = (0, arraysFind_1.findFirstMonotonous)(this.firstElementOffsetByLineIdx, x => range.endExclusive <= x) ?? this.elements.length;
            return new offsetRange_1.OffsetRange(start, end);
        }
    }
    exports.LinesSliceCharSequence = LinesSliceCharSequence;
    function isWordChar(charCode) {
        return charCode >= 97 /* CharCode.a */ && charCode <= 122 /* CharCode.z */
            || charCode >= 65 /* CharCode.A */ && charCode <= 90 /* CharCode.Z */
            || charCode >= 48 /* CharCode.Digit0 */ && charCode <= 57 /* CharCode.Digit9 */;
    }
    const score = {
        [0 /* CharBoundaryCategory.WordLower */]: 0,
        [1 /* CharBoundaryCategory.WordUpper */]: 0,
        [2 /* CharBoundaryCategory.WordNumber */]: 0,
        [3 /* CharBoundaryCategory.End */]: 10,
        [4 /* CharBoundaryCategory.Other */]: 2,
        [5 /* CharBoundaryCategory.Separator */]: 30,
        [6 /* CharBoundaryCategory.Space */]: 3,
        [7 /* CharBoundaryCategory.LineBreakCR */]: 10,
        [8 /* CharBoundaryCategory.LineBreakLF */]: 10,
    };
    function getCategoryBoundaryScore(category) {
        return score[category];
    }
    function getCategory(charCode) {
        if (charCode === 10 /* CharCode.LineFeed */) {
            return 8 /* CharBoundaryCategory.LineBreakLF */;
        }
        else if (charCode === 13 /* CharCode.CarriageReturn */) {
            return 7 /* CharBoundaryCategory.LineBreakCR */;
        }
        else if ((0, utils_1.isSpace)(charCode)) {
            return 6 /* CharBoundaryCategory.Space */;
        }
        else if (charCode >= 97 /* CharCode.a */ && charCode <= 122 /* CharCode.z */) {
            return 0 /* CharBoundaryCategory.WordLower */;
        }
        else if (charCode >= 65 /* CharCode.A */ && charCode <= 90 /* CharCode.Z */) {
            return 1 /* CharBoundaryCategory.WordUpper */;
        }
        else if (charCode >= 48 /* CharCode.Digit0 */ && charCode <= 57 /* CharCode.Digit9 */) {
            return 2 /* CharBoundaryCategory.WordNumber */;
        }
        else if (charCode === -1) {
            return 3 /* CharBoundaryCategory.End */;
        }
        else if (charCode === 44 /* CharCode.Comma */ || charCode === 59 /* CharCode.Semicolon */) {
            return 5 /* CharBoundaryCategory.Separator */;
        }
        else {
            return 4 /* CharBoundaryCategory.Other */;
        }
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[232/*vs/editor/common/diff/linesDiffComputer*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MovedText = exports.LinesDiff = void 0;
    class LinesDiff {
        constructor(changes, 
        /**
         * Sorted by original line ranges.
         * The original line ranges and the modified line ranges must be disjoint (but can be touching).
         */
        moves, 
        /**
         * Indicates if the time out was reached.
         * In that case, the diffs might be an approximation and the user should be asked to rerun the diff with more time.
         */
        hitTimeout) {
            this.changes = changes;
            this.moves = moves;
            this.hitTimeout = hitTimeout;
        }
    }
    exports.LinesDiff = LinesDiff;
    class MovedText {
        constructor(lineRangeMapping, changes) {
            this.lineRangeMapping = lineRangeMapping;
            this.changes = changes;
        }
    }
    exports.MovedText = MovedText;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[105/*vs/editor/common/diff/rangeMapping*/], __M([1/*require*/,0/*exports*/,8/*vs/base/common/errors*/,55/*vs/editor/common/core/lineRange*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/,104/*vs/editor/common/core/textEdit*/]), function (require, exports, errors_1, lineRange_1, position_1, range_1, textEdit_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.RangeMapping = exports.DetailedLineRangeMapping = exports.LineRangeMapping = void 0;
    /**
     * Maps a line range in the original text model to a line range in the modified text model.
     */
    class LineRangeMapping {
        static inverse(mapping, originalLineCount, modifiedLineCount) {
            const result = [];
            let lastOriginalEndLineNumber = 1;
            let lastModifiedEndLineNumber = 1;
            for (const m of mapping) {
                const r = new LineRangeMapping(new lineRange_1.LineRange(lastOriginalEndLineNumber, m.original.startLineNumber), new lineRange_1.LineRange(lastModifiedEndLineNumber, m.modified.startLineNumber));
                if (!r.modified.isEmpty) {
                    result.push(r);
                }
                lastOriginalEndLineNumber = m.original.endLineNumberExclusive;
                lastModifiedEndLineNumber = m.modified.endLineNumberExclusive;
            }
            const r = new LineRangeMapping(new lineRange_1.LineRange(lastOriginalEndLineNumber, originalLineCount + 1), new lineRange_1.LineRange(lastModifiedEndLineNumber, modifiedLineCount + 1));
            if (!r.modified.isEmpty) {
                result.push(r);
            }
            return result;
        }
        static clip(mapping, originalRange, modifiedRange) {
            const result = [];
            for (const m of mapping) {
                const original = m.original.intersect(originalRange);
                const modified = m.modified.intersect(modifiedRange);
                if (original && !original.isEmpty && modified && !modified.isEmpty) {
                    result.push(new LineRangeMapping(original, modified));
                }
            }
            return result;
        }
        constructor(originalRange, modifiedRange) {
            this.original = originalRange;
            this.modified = modifiedRange;
        }
        toString() {
            return `{${this.original.toString()}->${this.modified.toString()}}`;
        }
        flip() {
            return new LineRangeMapping(this.modified, this.original);
        }
        join(other) {
            return new LineRangeMapping(this.original.join(other.original), this.modified.join(other.modified));
        }
        /**
         * This method assumes that the LineRangeMapping describes a valid diff!
         * I.e. if one range is empty, the other range cannot be the entire document.
         * It avoids various problems when the line range points to non-existing line-numbers.
        */
        toRangeMapping() {
            const origInclusiveRange = this.original.toInclusiveRange();
            const modInclusiveRange = this.modified.toInclusiveRange();
            if (origInclusiveRange && modInclusiveRange) {
                return new RangeMapping(origInclusiveRange, modInclusiveRange);
            }
            else if (this.original.startLineNumber === 1 || this.modified.startLineNumber === 1) {
                if (!(this.modified.startLineNumber === 1 && this.original.startLineNumber === 1)) {
                    // If one line range starts at 1, the other one must start at 1 as well.
                    throw new errors_1.BugIndicatingError('not a valid diff');
                }
                // Because one range is empty and both ranges start at line 1, none of the ranges can cover all lines.
                // Thus, `endLineNumberExclusive` is a valid line number.
                return new RangeMapping(new range_1.Range(this.original.startLineNumber, 1, this.original.endLineNumberExclusive, 1), new range_1.Range(this.modified.startLineNumber, 1, this.modified.endLineNumberExclusive, 1));
            }
            else {
                // We can assume here that both startLineNumbers are greater than 1.
                return new RangeMapping(new range_1.Range(this.original.startLineNumber - 1, Number.MAX_SAFE_INTEGER, this.original.endLineNumberExclusive - 1, Number.MAX_SAFE_INTEGER), new range_1.Range(this.modified.startLineNumber - 1, Number.MAX_SAFE_INTEGER, this.modified.endLineNumberExclusive - 1, Number.MAX_SAFE_INTEGER));
            }
        }
        /**
         * This method assumes that the LineRangeMapping describes a valid diff!
         * I.e. if one range is empty, the other range cannot be the entire document.
         * It avoids various problems when the line range points to non-existing line-numbers.
        */
        toRangeMapping2(original, modified) {
            if (isValidLineNumber(this.original.endLineNumberExclusive, original)
                && isValidLineNumber(this.modified.endLineNumberExclusive, modified)) {
                return new RangeMapping(new range_1.Range(this.original.startLineNumber, 1, this.original.endLineNumberExclusive, 1), new range_1.Range(this.modified.startLineNumber, 1, this.modified.endLineNumberExclusive, 1));
            }
            if (!this.original.isEmpty && !this.modified.isEmpty) {
                return new RangeMapping(range_1.Range.fromPositions(new position_1.Position(this.original.startLineNumber, 1), normalizePosition(new position_1.Position(this.original.endLineNumberExclusive - 1, Number.MAX_SAFE_INTEGER), original)), range_1.Range.fromPositions(new position_1.Position(this.modified.startLineNumber, 1), normalizePosition(new position_1.Position(this.modified.endLineNumberExclusive - 1, Number.MAX_SAFE_INTEGER), modified)));
            }
            if (this.original.startLineNumber > 1 && this.modified.startLineNumber > 1) {
                return new RangeMapping(range_1.Range.fromPositions(normalizePosition(new position_1.Position(this.original.startLineNumber - 1, Number.MAX_SAFE_INTEGER), original), normalizePosition(new position_1.Position(this.original.endLineNumberExclusive - 1, Number.MAX_SAFE_INTEGER), original)), range_1.Range.fromPositions(normalizePosition(new position_1.Position(this.modified.startLineNumber - 1, Number.MAX_SAFE_INTEGER), modified), normalizePosition(new position_1.Position(this.modified.endLineNumberExclusive - 1, Number.MAX_SAFE_INTEGER), modified)));
            }
            // Situation now: one range is empty and one range touches the last line and one range starts at line 1.
            // I don't think this can happen.
            throw new errors_1.BugIndicatingError();
        }
    }
    exports.LineRangeMapping = LineRangeMapping;
    function normalizePosition(position, content) {
        if (position.lineNumber < 1) {
            return new position_1.Position(1, 1);
        }
        if (position.lineNumber > content.length) {
            return new position_1.Position(content.length, content[content.length - 1].length + 1);
        }
        const line = content[position.lineNumber - 1];
        if (position.column > line.length + 1) {
            return new position_1.Position(position.lineNumber, line.length + 1);
        }
        return position;
    }
    function isValidLineNumber(lineNumber, lines) {
        return lineNumber >= 1 && lineNumber <= lines.length;
    }
    /**
     * Maps a line range in the original text model to a line range in the modified text model.
     * Also contains inner range mappings.
     */
    class DetailedLineRangeMapping extends LineRangeMapping {
        static fromRangeMappings(rangeMappings) {
            const originalRange = lineRange_1.LineRange.join(rangeMappings.map(r => lineRange_1.LineRange.fromRangeInclusive(r.originalRange)));
            const modifiedRange = lineRange_1.LineRange.join(rangeMappings.map(r => lineRange_1.LineRange.fromRangeInclusive(r.modifiedRange)));
            return new DetailedLineRangeMapping(originalRange, modifiedRange, rangeMappings);
        }
        constructor(originalRange, modifiedRange, innerChanges) {
            super(originalRange, modifiedRange);
            this.innerChanges = innerChanges;
        }
        flip() {
            return new DetailedLineRangeMapping(this.modified, this.original, this.innerChanges?.map(c => c.flip()));
        }
        withInnerChangesFromLineRanges() {
            return new DetailedLineRangeMapping(this.original, this.modified, [this.toRangeMapping()]);
        }
    }
    exports.DetailedLineRangeMapping = DetailedLineRangeMapping;
    /**
     * Maps a range in the original text model to a range in the modified text model.
     */
    class RangeMapping {
        static assertSorted(rangeMappings) {
            for (let i = 1; i < rangeMappings.length; i++) {
                const previous = rangeMappings[i - 1];
                const current = rangeMappings[i];
                if (!(previous.originalRange.getEndPosition().isBeforeOrEqual(current.originalRange.getStartPosition())
                    && previous.modifiedRange.getEndPosition().isBeforeOrEqual(current.modifiedRange.getStartPosition()))) {
                    throw new errors_1.BugIndicatingError('Range mappings must be sorted');
                }
            }
        }
        constructor(originalRange, modifiedRange) {
            this.originalRange = originalRange;
            this.modifiedRange = modifiedRange;
        }
        toString() {
            return `{${this.originalRange.toString()}->${this.modifiedRange.toString()}}`;
        }
        flip() {
            return new RangeMapping(this.modifiedRange, this.originalRange);
        }
        /**
         * Creates a single text edit that describes the change from the original to the modified text.
        */
        toTextEdit(modified) {
            const newText = modified.getValueOfRange(this.modifiedRange);
            return new textEdit_1.SingleTextEdit(this.originalRange, newText);
        }
    }
    exports.RangeMapping = RangeMapping;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[559/*vs/editor/common/diff/defaultLinesDiffComputer/computeMovedLines*/], __M([1/*require*/,0/*exports*/,167/*vs/editor/common/diff/defaultLinesDiffComputer/algorithms/diffAlgorithm*/,105/*vs/editor/common/diff/rangeMapping*/,13/*vs/base/common/arrays*/,67/*vs/base/common/arraysFind*/,45/*vs/base/common/map*/,55/*vs/editor/common/core/lineRange*/,316/*vs/editor/common/diff/defaultLinesDiffComputer/linesSliceCharSequence*/,231/*vs/editor/common/diff/defaultLinesDiffComputer/utils*/,314/*vs/editor/common/diff/defaultLinesDiffComputer/algorithms/myersDiffAlgorithm*/,4/*vs/editor/common/core/range*/]), function (require, exports, diffAlgorithm_1, rangeMapping_1, arrays_1, arraysFind_1, map_1, lineRange_1, linesSliceCharSequence_1, utils_1, myersDiffAlgorithm_1, range_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.computeMovedLines = computeMovedLines;
    function computeMovedLines(changes, originalLines, modifiedLines, hashedOriginalLines, hashedModifiedLines, timeout) {
        let { moves, excludedChanges } = computeMovesFromSimpleDeletionsToSimpleInsertions(changes, originalLines, modifiedLines, timeout);
        if (!timeout.isValid()) {
            return [];
        }
        const filteredChanges = changes.filter(c => !excludedChanges.has(c));
        const unchangedMoves = computeUnchangedMoves(filteredChanges, hashedOriginalLines, hashedModifiedLines, originalLines, modifiedLines, timeout);
        (0, arrays_1.pushMany)(moves, unchangedMoves);
        moves = joinCloseConsecutiveMoves(moves);
        // Ignore too short moves
        moves = moves.filter(current => {
            const lines = current.original.toOffsetRange().slice(originalLines).map(l => l.trim());
            const originalText = lines.join('\n');
            return originalText.length >= 15 && countWhere(lines, l => l.length >= 2) >= 2;
        });
        moves = removeMovesInSameDiff(changes, moves);
        return moves;
    }
    function countWhere(arr, predicate) {
        let count = 0;
        for (const t of arr) {
            if (predicate(t)) {
                count++;
            }
        }
        return count;
    }
    function computeMovesFromSimpleDeletionsToSimpleInsertions(changes, originalLines, modifiedLines, timeout) {
        const moves = [];
        const deletions = changes
            .filter(c => c.modified.isEmpty && c.original.length >= 3)
            .map(d => new utils_1.LineRangeFragment(d.original, originalLines, d));
        const insertions = new Set(changes
            .filter(c => c.original.isEmpty && c.modified.length >= 3)
            .map(d => new utils_1.LineRangeFragment(d.modified, modifiedLines, d)));
        const excludedChanges = new Set();
        for (const deletion of deletions) {
            let highestSimilarity = -1;
            let best;
            for (const insertion of insertions) {
                const similarity = deletion.computeSimilarity(insertion);
                if (similarity > highestSimilarity) {
                    highestSimilarity = similarity;
                    best = insertion;
                }
            }
            if (highestSimilarity > 0.90 && best) {
                insertions.delete(best);
                moves.push(new rangeMapping_1.LineRangeMapping(deletion.range, best.range));
                excludedChanges.add(deletion.source);
                excludedChanges.add(best.source);
            }
            if (!timeout.isValid()) {
                return { moves, excludedChanges };
            }
        }
        return { moves, excludedChanges };
    }
    function computeUnchangedMoves(changes, hashedOriginalLines, hashedModifiedLines, originalLines, modifiedLines, timeout) {
        const moves = [];
        const original3LineHashes = new map_1.SetMap();
        for (const change of changes) {
            for (let i = change.original.startLineNumber; i < change.original.endLineNumberExclusive - 2; i++) {
                const key = `${hashedOriginalLines[i - 1]}:${hashedOriginalLines[i + 1 - 1]}:${hashedOriginalLines[i + 2 - 1]}`;
                original3LineHashes.add(key, { range: new lineRange_1.LineRange(i, i + 3) });
            }
        }
        const possibleMappings = [];
        changes.sort((0, arrays_1.compareBy)(c => c.modified.startLineNumber, arrays_1.numberComparator));
        for (const change of changes) {
            let lastMappings = [];
            for (let i = change.modified.startLineNumber; i < change.modified.endLineNumberExclusive - 2; i++) {
                const key = `${hashedModifiedLines[i - 1]}:${hashedModifiedLines[i + 1 - 1]}:${hashedModifiedLines[i + 2 - 1]}`;
                const currentModifiedRange = new lineRange_1.LineRange(i, i + 3);
                const nextMappings = [];
                original3LineHashes.forEach(key, ({ range }) => {
                    for (const lastMapping of lastMappings) {
                        // does this match extend some last match?
                        if (lastMapping.originalLineRange.endLineNumberExclusive + 1 === range.endLineNumberExclusive &&
                            lastMapping.modifiedLineRange.endLineNumberExclusive + 1 === currentModifiedRange.endLineNumberExclusive) {
                            lastMapping.originalLineRange = new lineRange_1.LineRange(lastMapping.originalLineRange.startLineNumber, range.endLineNumberExclusive);
                            lastMapping.modifiedLineRange = new lineRange_1.LineRange(lastMapping.modifiedLineRange.startLineNumber, currentModifiedRange.endLineNumberExclusive);
                            nextMappings.push(lastMapping);
                            return;
                        }
                    }
                    const mapping = {
                        modifiedLineRange: currentModifiedRange,
                        originalLineRange: range,
                    };
                    possibleMappings.push(mapping);
                    nextMappings.push(mapping);
                });
                lastMappings = nextMappings;
            }
            if (!timeout.isValid()) {
                return [];
            }
        }
        possibleMappings.sort((0, arrays_1.reverseOrder)((0, arrays_1.compareBy)(m => m.modifiedLineRange.length, arrays_1.numberComparator)));
        const modifiedSet = new lineRange_1.LineRangeSet();
        const originalSet = new lineRange_1.LineRangeSet();
        for (const mapping of possibleMappings) {
            const diffOrigToMod = mapping.modifiedLineRange.startLineNumber - mapping.originalLineRange.startLineNumber;
            const modifiedSections = modifiedSet.subtractFrom(mapping.modifiedLineRange);
            const originalTranslatedSections = originalSet.subtractFrom(mapping.originalLineRange).getWithDelta(diffOrigToMod);
            const modifiedIntersectedSections = modifiedSections.getIntersection(originalTranslatedSections);
            for (const s of modifiedIntersectedSections.ranges) {
                if (s.length < 3) {
                    continue;
                }
                const modifiedLineRange = s;
                const originalLineRange = s.delta(-diffOrigToMod);
                moves.push(new rangeMapping_1.LineRangeMapping(originalLineRange, modifiedLineRange));
                modifiedSet.addRange(modifiedLineRange);
                originalSet.addRange(originalLineRange);
            }
        }
        moves.sort((0, arrays_1.compareBy)(m => m.original.startLineNumber, arrays_1.numberComparator));
        const monotonousChanges = new arraysFind_1.MonotonousArray(changes);
        for (let i = 0; i < moves.length; i++) {
            const move = moves[i];
            const firstTouchingChangeOrig = monotonousChanges.findLastMonotonous(c => c.original.startLineNumber <= move.original.startLineNumber);
            const firstTouchingChangeMod = (0, arraysFind_1.findLastMonotonous)(changes, c => c.modified.startLineNumber <= move.modified.startLineNumber);
            const linesAbove = Math.max(move.original.startLineNumber - firstTouchingChangeOrig.original.startLineNumber, move.modified.startLineNumber - firstTouchingChangeMod.modified.startLineNumber);
            const lastTouchingChangeOrig = monotonousChanges.findLastMonotonous(c => c.original.startLineNumber < move.original.endLineNumberExclusive);
            const lastTouchingChangeMod = (0, arraysFind_1.findLastMonotonous)(changes, c => c.modified.startLineNumber < move.modified.endLineNumberExclusive);
            const linesBelow = Math.max(lastTouchingChangeOrig.original.endLineNumberExclusive - move.original.endLineNumberExclusive, lastTouchingChangeMod.modified.endLineNumberExclusive - move.modified.endLineNumberExclusive);
            let extendToTop;
            for (extendToTop = 0; extendToTop < linesAbove; extendToTop++) {
                const origLine = move.original.startLineNumber - extendToTop - 1;
                const modLine = move.modified.startLineNumber - extendToTop - 1;
                if (origLine > originalLines.length || modLine > modifiedLines.length) {
                    break;
                }
                if (modifiedSet.contains(modLine) || originalSet.contains(origLine)) {
                    break;
                }
                if (!areLinesSimilar(originalLines[origLine - 1], modifiedLines[modLine - 1], timeout)) {
                    break;
                }
            }
            if (extendToTop > 0) {
                originalSet.addRange(new lineRange_1.LineRange(move.original.startLineNumber - extendToTop, move.original.startLineNumber));
                modifiedSet.addRange(new lineRange_1.LineRange(move.modified.startLineNumber - extendToTop, move.modified.startLineNumber));
            }
            let extendToBottom;
            for (extendToBottom = 0; extendToBottom < linesBelow; extendToBottom++) {
                const origLine = move.original.endLineNumberExclusive + extendToBottom;
                const modLine = move.modified.endLineNumberExclusive + extendToBottom;
                if (origLine > originalLines.length || modLine > modifiedLines.length) {
                    break;
                }
                if (modifiedSet.contains(modLine) || originalSet.contains(origLine)) {
                    break;
                }
                if (!areLinesSimilar(originalLines[origLine - 1], modifiedLines[modLine - 1], timeout)) {
                    break;
                }
            }
            if (extendToBottom > 0) {
                originalSet.addRange(new lineRange_1.LineRange(move.original.endLineNumberExclusive, move.original.endLineNumberExclusive + extendToBottom));
                modifiedSet.addRange(new lineRange_1.LineRange(move.modified.endLineNumberExclusive, move.modified.endLineNumberExclusive + extendToBottom));
            }
            if (extendToTop > 0 || extendToBottom > 0) {
                moves[i] = new rangeMapping_1.LineRangeMapping(new lineRange_1.LineRange(move.original.startLineNumber - extendToTop, move.original.endLineNumberExclusive + extendToBottom), new lineRange_1.LineRange(move.modified.startLineNumber - extendToTop, move.modified.endLineNumberExclusive + extendToBottom));
            }
        }
        return moves;
    }
    function areLinesSimilar(line1, line2, timeout) {
        if (line1.trim() === line2.trim()) {
            return true;
        }
        if (line1.length > 300 && line2.length > 300) {
            return false;
        }
        const myersDiffingAlgorithm = new myersDiffAlgorithm_1.MyersDiffAlgorithm();
        const result = myersDiffingAlgorithm.compute(new linesSliceCharSequence_1.LinesSliceCharSequence([line1], new range_1.Range(1, 1, 1, line1.length), false), new linesSliceCharSequence_1.LinesSliceCharSequence([line2], new range_1.Range(1, 1, 1, line2.length), false), timeout);
        let commonNonSpaceCharCount = 0;
        const inverted = diffAlgorithm_1.SequenceDiff.invert(result.diffs, line1.length);
        for (const seq of inverted) {
            seq.seq1Range.forEach(idx => {
                if (!(0, utils_1.isSpace)(line1.charCodeAt(idx))) {
                    commonNonSpaceCharCount++;
                }
            });
        }
        function countNonWsChars(str) {
            let count = 0;
            for (let i = 0; i < line1.length; i++) {
                if (!(0, utils_1.isSpace)(str.charCodeAt(i))) {
                    count++;
                }
            }
            return count;
        }
        const longerLineLength = countNonWsChars(line1.length > line2.length ? line1 : line2);
        const r = commonNonSpaceCharCount / longerLineLength > 0.6 && longerLineLength > 10;
        return r;
    }
    function joinCloseConsecutiveMoves(moves) {
        if (moves.length === 0) {
            return moves;
        }
        moves.sort((0, arrays_1.compareBy)(m => m.original.startLineNumber, arrays_1.numberComparator));
        const result = [moves[0]];
        for (let i = 1; i < moves.length; i++) {
            const last = result[result.length - 1];
            const current = moves[i];
            const originalDist = current.original.startLineNumber - last.original.endLineNumberExclusive;
            const modifiedDist = current.modified.startLineNumber - last.modified.endLineNumberExclusive;
            const currentMoveAfterLast = originalDist >= 0 && modifiedDist >= 0;
            if (currentMoveAfterLast && originalDist + modifiedDist <= 2) {
                result[result.length - 1] = last.join(current);
                continue;
            }
            result.push(current);
        }
        return result;
    }
    function removeMovesInSameDiff(changes, moves) {
        const changesMonotonous = new arraysFind_1.MonotonousArray(changes);
        moves = moves.filter(m => {
            const diffBeforeEndOfMoveOriginal = changesMonotonous.findLastMonotonous(c => c.original.startLineNumber < m.original.endLineNumberExclusive)
                || new rangeMapping_1.LineRangeMapping(new lineRange_1.LineRange(1, 1), new lineRange_1.LineRange(1, 1));
            const diffBeforeEndOfMoveModified = (0, arraysFind_1.findLastMonotonous)(changes, c => c.modified.startLineNumber < m.modified.endLineNumberExclusive);
            const differentDiffs = diffBeforeEndOfMoveOriginal !== diffBeforeEndOfMoveModified;
            return differentDiffs;
        });
        return moves;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[317/*vs/editor/common/diff/defaultLinesDiffComputer/defaultLinesDiffComputer*/], __M([1/*require*/,0/*exports*/,13/*vs/base/common/arrays*/,90/*vs/base/common/assert*/,55/*vs/editor/common/core/lineRange*/,68/*vs/editor/common/core/offsetRange*/,4/*vs/editor/common/core/range*/,167/*vs/editor/common/diff/defaultLinesDiffComputer/algorithms/diffAlgorithm*/,558/*vs/editor/common/diff/defaultLinesDiffComputer/algorithms/dynamicProgrammingDiffing*/,314/*vs/editor/common/diff/defaultLinesDiffComputer/algorithms/myersDiffAlgorithm*/,559/*vs/editor/common/diff/defaultLinesDiffComputer/computeMovedLines*/,315/*vs/editor/common/diff/defaultLinesDiffComputer/heuristicSequenceOptimizations*/,557/*vs/editor/common/diff/defaultLinesDiffComputer/lineSequence*/,316/*vs/editor/common/diff/defaultLinesDiffComputer/linesSliceCharSequence*/,232/*vs/editor/common/diff/linesDiffComputer*/,105/*vs/editor/common/diff/rangeMapping*/]), function (require, exports, arrays_1, assert_1, lineRange_1, offsetRange_1, range_1, diffAlgorithm_1, dynamicProgrammingDiffing_1, myersDiffAlgorithm_1, computeMovedLines_1, heuristicSequenceOptimizations_1, lineSequence_1, linesSliceCharSequence_1, linesDiffComputer_1, rangeMapping_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DefaultLinesDiffComputer = void 0;
    exports.lineRangeMappingFromRangeMappings = lineRangeMappingFromRangeMappings;
    exports.getLineRangeMapping = getLineRangeMapping;
    class DefaultLinesDiffComputer {
        constructor() {
            this.dynamicProgrammingDiffing = new dynamicProgrammingDiffing_1.DynamicProgrammingDiffing();
            this.myersDiffingAlgorithm = new myersDiffAlgorithm_1.MyersDiffAlgorithm();
        }
        computeDiff(originalLines, modifiedLines, options) {
            if (originalLines.length <= 1 && (0, arrays_1.equals)(originalLines, modifiedLines, (a, b) => a === b)) {
                return new linesDiffComputer_1.LinesDiff([], [], false);
            }
            if (originalLines.length === 1 && originalLines[0].length === 0 || modifiedLines.length === 1 && modifiedLines[0].length === 0) {
                return new linesDiffComputer_1.LinesDiff([
                    new rangeMapping_1.DetailedLineRangeMapping(new lineRange_1.LineRange(1, originalLines.length + 1), new lineRange_1.LineRange(1, modifiedLines.length + 1), [
                        new rangeMapping_1.RangeMapping(new range_1.Range(1, 1, originalLines.length, originalLines[originalLines.length - 1].length + 1), new range_1.Range(1, 1, modifiedLines.length, modifiedLines[modifiedLines.length - 1].length + 1))
                    ])
                ], [], false);
            }
            const timeout = options.maxComputationTimeMs === 0 ? diffAlgorithm_1.InfiniteTimeout.instance : new diffAlgorithm_1.DateTimeout(options.maxComputationTimeMs);
            const considerWhitespaceChanges = !options.ignoreTrimWhitespace;
            const perfectHashes = new Map();
            function getOrCreateHash(text) {
                let hash = perfectHashes.get(text);
                if (hash === undefined) {
                    hash = perfectHashes.size;
                    perfectHashes.set(text, hash);
                }
                return hash;
            }
            const originalLinesHashes = originalLines.map((l) => getOrCreateHash(l.trim()));
            const modifiedLinesHashes = modifiedLines.map((l) => getOrCreateHash(l.trim()));
            const sequence1 = new lineSequence_1.LineSequence(originalLinesHashes, originalLines);
            const sequence2 = new lineSequence_1.LineSequence(modifiedLinesHashes, modifiedLines);
            const lineAlignmentResult = (() => {
                if (sequence1.length + sequence2.length < 1700) {
                    // Use the improved algorithm for small files
                    return this.dynamicProgrammingDiffing.compute(sequence1, sequence2, timeout, (offset1, offset2) => originalLines[offset1] === modifiedLines[offset2]
                        ? modifiedLines[offset2].length === 0
                            ? 0.1
                            : 1 + Math.log(1 + modifiedLines[offset2].length)
                        : 0.99);
                }
                return this.myersDiffingAlgorithm.compute(sequence1, sequence2, timeout);
            })();
            let lineAlignments = lineAlignmentResult.diffs;
            let hitTimeout = lineAlignmentResult.hitTimeout;
            lineAlignments = (0, heuristicSequenceOptimizations_1.optimizeSequenceDiffs)(sequence1, sequence2, lineAlignments);
            lineAlignments = (0, heuristicSequenceOptimizations_1.removeVeryShortMatchingLinesBetweenDiffs)(sequence1, sequence2, lineAlignments);
            const alignments = [];
            const scanForWhitespaceChanges = (equalLinesCount) => {
                if (!considerWhitespaceChanges) {
                    return;
                }
                for (let i = 0; i < equalLinesCount; i++) {
                    const seq1Offset = seq1LastStart + i;
                    const seq2Offset = seq2LastStart + i;
                    if (originalLines[seq1Offset] !== modifiedLines[seq2Offset]) {
                        // This is because of whitespace changes, diff these lines
                        const characterDiffs = this.refineDiff(originalLines, modifiedLines, new diffAlgorithm_1.SequenceDiff(new offsetRange_1.OffsetRange(seq1Offset, seq1Offset + 1), new offsetRange_1.OffsetRange(seq2Offset, seq2Offset + 1)), timeout, considerWhitespaceChanges);
                        for (const a of characterDiffs.mappings) {
                            alignments.push(a);
                        }
                        if (characterDiffs.hitTimeout) {
                            hitTimeout = true;
                        }
                    }
                }
            };
            let seq1LastStart = 0;
            let seq2LastStart = 0;
            for (const diff of lineAlignments) {
                (0, assert_1.assertFn)(() => diff.seq1Range.start - seq1LastStart === diff.seq2Range.start - seq2LastStart);
                const equalLinesCount = diff.seq1Range.start - seq1LastStart;
                scanForWhitespaceChanges(equalLinesCount);
                seq1LastStart = diff.seq1Range.endExclusive;
                seq2LastStart = diff.seq2Range.endExclusive;
                const characterDiffs = this.refineDiff(originalLines, modifiedLines, diff, timeout, considerWhitespaceChanges);
                if (characterDiffs.hitTimeout) {
                    hitTimeout = true;
                }
                for (const a of characterDiffs.mappings) {
                    alignments.push(a);
                }
            }
            scanForWhitespaceChanges(originalLines.length - seq1LastStart);
            const changes = lineRangeMappingFromRangeMappings(alignments, originalLines, modifiedLines);
            let moves = [];
            if (options.computeMoves) {
                moves = this.computeMoves(changes, originalLines, modifiedLines, originalLinesHashes, modifiedLinesHashes, timeout, considerWhitespaceChanges);
            }
            // Make sure all ranges are valid
            (0, assert_1.assertFn)(() => {
                function validatePosition(pos, lines) {
                    if (pos.lineNumber < 1 || pos.lineNumber > lines.length) {
                        return false;
                    }
                    const line = lines[pos.lineNumber - 1];
                    if (pos.column < 1 || pos.column > line.length + 1) {
                        return false;
                    }
                    return true;
                }
                function validateRange(range, lines) {
                    if (range.startLineNumber < 1 || range.startLineNumber > lines.length + 1) {
                        return false;
                    }
                    if (range.endLineNumberExclusive < 1 || range.endLineNumberExclusive > lines.length + 1) {
                        return false;
                    }
                    return true;
                }
                for (const c of changes) {
                    if (!c.innerChanges) {
                        return false;
                    }
                    for (const ic of c.innerChanges) {
                        const valid = validatePosition(ic.modifiedRange.getStartPosition(), modifiedLines) && validatePosition(ic.modifiedRange.getEndPosition(), modifiedLines) &&
                            validatePosition(ic.originalRange.getStartPosition(), originalLines) && validatePosition(ic.originalRange.getEndPosition(), originalLines);
                        if (!valid) {
                            return false;
                        }
                    }
                    if (!validateRange(c.modified, modifiedLines) || !validateRange(c.original, originalLines)) {
                        return false;
                    }
                }
                return true;
            });
            return new linesDiffComputer_1.LinesDiff(changes, moves, hitTimeout);
        }
        computeMoves(changes, originalLines, modifiedLines, hashedOriginalLines, hashedModifiedLines, timeout, considerWhitespaceChanges) {
            const moves = (0, computeMovedLines_1.computeMovedLines)(changes, originalLines, modifiedLines, hashedOriginalLines, hashedModifiedLines, timeout);
            const movesWithDiffs = moves.map(m => {
                const moveChanges = this.refineDiff(originalLines, modifiedLines, new diffAlgorithm_1.SequenceDiff(m.original.toOffsetRange(), m.modified.toOffsetRange()), timeout, considerWhitespaceChanges);
                const mappings = lineRangeMappingFromRangeMappings(moveChanges.mappings, originalLines, modifiedLines, true);
                return new linesDiffComputer_1.MovedText(m, mappings);
            });
            return movesWithDiffs;
        }
        refineDiff(originalLines, modifiedLines, diff, timeout, considerWhitespaceChanges) {
            const lineRangeMapping = toLineRangeMapping(diff);
            const rangeMapping = lineRangeMapping.toRangeMapping2(originalLines, modifiedLines);
            const slice1 = new linesSliceCharSequence_1.LinesSliceCharSequence(originalLines, rangeMapping.originalRange, considerWhitespaceChanges);
            const slice2 = new linesSliceCharSequence_1.LinesSliceCharSequence(modifiedLines, rangeMapping.modifiedRange, considerWhitespaceChanges);
            const diffResult = slice1.length + slice2.length < 500
                ? this.dynamicProgrammingDiffing.compute(slice1, slice2, timeout)
                : this.myersDiffingAlgorithm.compute(slice1, slice2, timeout);
            const check = false;
            let diffs = diffResult.diffs;
            if (check) {
                diffAlgorithm_1.SequenceDiff.assertSorted(diffs);
            }
            diffs = (0, heuristicSequenceOptimizations_1.optimizeSequenceDiffs)(slice1, slice2, diffs);
            if (check) {
                diffAlgorithm_1.SequenceDiff.assertSorted(diffs);
            }
            diffs = (0, heuristicSequenceOptimizations_1.extendDiffsToEntireWordIfAppropriate)(slice1, slice2, diffs);
            if (check) {
                diffAlgorithm_1.SequenceDiff.assertSorted(diffs);
            }
            diffs = (0, heuristicSequenceOptimizations_1.removeShortMatches)(slice1, slice2, diffs);
            if (check) {
                diffAlgorithm_1.SequenceDiff.assertSorted(diffs);
            }
            diffs = (0, heuristicSequenceOptimizations_1.removeVeryShortMatchingTextBetweenLongDiffs)(slice1, slice2, diffs);
            if (check) {
                diffAlgorithm_1.SequenceDiff.assertSorted(diffs);
            }
            const result = diffs.map((d) => new rangeMapping_1.RangeMapping(slice1.translateRange(d.seq1Range), slice2.translateRange(d.seq2Range)));
            if (check) {
                rangeMapping_1.RangeMapping.assertSorted(result);
            }
            // Assert: result applied on original should be the same as diff applied to original
            return {
                mappings: result,
                hitTimeout: diffResult.hitTimeout,
            };
        }
    }
    exports.DefaultLinesDiffComputer = DefaultLinesDiffComputer;
    function lineRangeMappingFromRangeMappings(alignments, originalLines, modifiedLines, dontAssertStartLine = false) {
        const changes = [];
        for (const g of (0, arrays_1.groupAdjacentBy)(alignments.map(a => getLineRangeMapping(a, originalLines, modifiedLines)), (a1, a2) => a1.original.overlapOrTouch(a2.original)
            || a1.modified.overlapOrTouch(a2.modified))) {
            const first = g[0];
            const last = g[g.length - 1];
            changes.push(new rangeMapping_1.DetailedLineRangeMapping(first.original.join(last.original), first.modified.join(last.modified), g.map(a => a.innerChanges[0])));
        }
        (0, assert_1.assertFn)(() => {
            if (!dontAssertStartLine && changes.length > 0) {
                if (changes[0].modified.startLineNumber !== changes[0].original.startLineNumber) {
                    return false;
                }
                if (modifiedLines.length - changes[changes.length - 1].modified.endLineNumberExclusive !== originalLines.length - changes[changes.length - 1].original.endLineNumberExclusive) {
                    return false;
                }
            }
            return (0, assert_1.checkAdjacentItems)(changes, (m1, m2) => m2.original.startLineNumber - m1.original.endLineNumberExclusive === m2.modified.startLineNumber - m1.modified.endLineNumberExclusive &&
                // There has to be an unchanged line in between (otherwise both diffs should have been joined)
                m1.original.endLineNumberExclusive < m2.original.startLineNumber &&
                m1.modified.endLineNumberExclusive < m2.modified.startLineNumber);
        });
        return changes;
    }
    function getLineRangeMapping(rangeMapping, originalLines, modifiedLines) {
        let lineStartDelta = 0;
        let lineEndDelta = 0;
        // rangeMapping describes the edit that replaces `rangeMapping.originalRange` with `newText := getText(modifiedLines, rangeMapping.modifiedRange)`.
        // original: ]xxx \n <- this line is not modified
        // modified: ]xx  \n
        if (rangeMapping.modifiedRange.endColumn === 1 && rangeMapping.originalRange.endColumn === 1
            && rangeMapping.originalRange.startLineNumber + lineStartDelta <= rangeMapping.originalRange.endLineNumber
            && rangeMapping.modifiedRange.startLineNumber + lineStartDelta <= rangeMapping.modifiedRange.endLineNumber) {
            // We can only do this if the range is not empty yet
            lineEndDelta = -1;
        }
        // original: xxx[ \n <- this line is not modified
        // modified: xxx[ \n
        if (rangeMapping.modifiedRange.startColumn - 1 >= modifiedLines[rangeMapping.modifiedRange.startLineNumber - 1].length
            && rangeMapping.originalRange.startColumn - 1 >= originalLines[rangeMapping.originalRange.startLineNumber - 1].length
            && rangeMapping.originalRange.startLineNumber <= rangeMapping.originalRange.endLineNumber + lineEndDelta
            && rangeMapping.modifiedRange.startLineNumber <= rangeMapping.modifiedRange.endLineNumber + lineEndDelta) {
            // We can only do this if the range is not empty yet
            lineStartDelta = 1;
        }
        const originalLineRange = new lineRange_1.LineRange(rangeMapping.originalRange.startLineNumber + lineStartDelta, rangeMapping.originalRange.endLineNumber + 1 + lineEndDelta);
        const modifiedLineRange = new lineRange_1.LineRange(rangeMapping.modifiedRange.startLineNumber + lineStartDelta, rangeMapping.modifiedRange.endLineNumber + 1 + lineEndDelta);
        return new rangeMapping_1.DetailedLineRangeMapping(originalLineRange, modifiedLineRange, [rangeMapping]);
    }
    function toLineRangeMapping(sequenceDiff) {
        return new rangeMapping_1.LineRangeMapping(new lineRange_1.LineRange(sequenceDiff.seq1Range.start + 1, sequenceDiff.seq1Range.endExclusive + 1), new lineRange_1.LineRange(sequenceDiff.seq2Range.start + 1, sequenceDiff.seq2Range.endExclusive + 1));
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[560/*vs/editor/common/diff/legacyLinesDiffComputer*/], __M([1/*require*/,0/*exports*/,190/*vs/base/common/diff/diff*/,232/*vs/editor/common/diff/linesDiffComputer*/,105/*vs/editor/common/diff/rangeMapping*/,11/*vs/base/common/strings*/,4/*vs/editor/common/core/range*/,90/*vs/base/common/assert*/,55/*vs/editor/common/core/lineRange*/]), function (require, exports, diff_1, linesDiffComputer_1, rangeMapping_1, strings, range_1, assert_1, lineRange_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DiffComputer = exports.LegacyLinesDiffComputer = void 0;
    const MINIMUM_MATCHING_CHARACTER_LENGTH = 3;
    class LegacyLinesDiffComputer {
        computeDiff(originalLines, modifiedLines, options) {
            const diffComputer = new DiffComputer(originalLines, modifiedLines, {
                maxComputationTime: options.maxComputationTimeMs,
                shouldIgnoreTrimWhitespace: options.ignoreTrimWhitespace,
                shouldComputeCharChanges: true,
                shouldMakePrettyDiff: true,
                shouldPostProcessCharChanges: true,
            });
            const result = diffComputer.computeDiff();
            const changes = [];
            let lastChange = null;
            for (const c of result.changes) {
                let originalRange;
                if (c.originalEndLineNumber === 0) {
                    // Insertion
                    originalRange = new lineRange_1.LineRange(c.originalStartLineNumber + 1, c.originalStartLineNumber + 1);
                }
                else {
                    originalRange = new lineRange_1.LineRange(c.originalStartLineNumber, c.originalEndLineNumber + 1);
                }
                let modifiedRange;
                if (c.modifiedEndLineNumber === 0) {
                    // Deletion
                    modifiedRange = new lineRange_1.LineRange(c.modifiedStartLineNumber + 1, c.modifiedStartLineNumber + 1);
                }
                else {
                    modifiedRange = new lineRange_1.LineRange(c.modifiedStartLineNumber, c.modifiedEndLineNumber + 1);
                }
                let change = new rangeMapping_1.DetailedLineRangeMapping(originalRange, modifiedRange, c.charChanges?.map(c => new rangeMapping_1.RangeMapping(new range_1.Range(c.originalStartLineNumber, c.originalStartColumn, c.originalEndLineNumber, c.originalEndColumn), new range_1.Range(c.modifiedStartLineNumber, c.modifiedStartColumn, c.modifiedEndLineNumber, c.modifiedEndColumn))));
                if (lastChange) {
                    if (lastChange.modified.endLineNumberExclusive === change.modified.startLineNumber
                        || lastChange.original.endLineNumberExclusive === change.original.startLineNumber) {
                        // join touching diffs. Probably moving diffs up/down in the algorithm causes touching diffs.
                        change = new rangeMapping_1.DetailedLineRangeMapping(lastChange.original.join(change.original), lastChange.modified.join(change.modified), lastChange.innerChanges && change.innerChanges ?
                            lastChange.innerChanges.concat(change.innerChanges) : undefined);
                        changes.pop();
                    }
                }
                changes.push(change);
                lastChange = change;
            }
            (0, assert_1.assertFn)(() => {
                return (0, assert_1.checkAdjacentItems)(changes, (m1, m2) => m2.original.startLineNumber - m1.original.endLineNumberExclusive === m2.modified.startLineNumber - m1.modified.endLineNumberExclusive &&
                    // There has to be an unchanged line in between (otherwise both diffs should have been joined)
                    m1.original.endLineNumberExclusive < m2.original.startLineNumber &&
                    m1.modified.endLineNumberExclusive < m2.modified.startLineNumber);
            });
            return new linesDiffComputer_1.LinesDiff(changes, [], result.quitEarly);
        }
    }
    exports.LegacyLinesDiffComputer = LegacyLinesDiffComputer;
    function computeDiff(originalSequence, modifiedSequence, continueProcessingPredicate, pretty) {
        const diffAlgo = new diff_1.LcsDiff(originalSequence, modifiedSequence, continueProcessingPredicate);
        return diffAlgo.ComputeDiff(pretty);
    }
    class LineSequence {
        constructor(lines) {
            const startColumns = [];
            const endColumns = [];
            for (let i = 0, length = lines.length; i < length; i++) {
                startColumns[i] = getFirstNonBlankColumn(lines[i], 1);
                endColumns[i] = getLastNonBlankColumn(lines[i], 1);
            }
            this.lines = lines;
            this._startColumns = startColumns;
            this._endColumns = endColumns;
        }
        getElements() {
            const elements = [];
            for (let i = 0, len = this.lines.length; i < len; i++) {
                elements[i] = this.lines[i].substring(this._startColumns[i] - 1, this._endColumns[i] - 1);
            }
            return elements;
        }
        getStrictElement(index) {
            return this.lines[index];
        }
        getStartLineNumber(i) {
            return i + 1;
        }
        getEndLineNumber(i) {
            return i + 1;
        }
        createCharSequence(shouldIgnoreTrimWhitespace, startIndex, endIndex) {
            const charCodes = [];
            const lineNumbers = [];
            const columns = [];
            let len = 0;
            for (let index = startIndex; index <= endIndex; index++) {
                const lineContent = this.lines[index];
                const startColumn = (shouldIgnoreTrimWhitespace ? this._startColumns[index] : 1);
                const endColumn = (shouldIgnoreTrimWhitespace ? this._endColumns[index] : lineContent.length + 1);
                for (let col = startColumn; col < endColumn; col++) {
                    charCodes[len] = lineContent.charCodeAt(col - 1);
                    lineNumbers[len] = index + 1;
                    columns[len] = col;
                    len++;
                }
                if (!shouldIgnoreTrimWhitespace && index < endIndex) {
                    // Add \n if trim whitespace is not ignored
                    charCodes[len] = 10 /* CharCode.LineFeed */;
                    lineNumbers[len] = index + 1;
                    columns[len] = lineContent.length + 1;
                    len++;
                }
            }
            return new CharSequence(charCodes, lineNumbers, columns);
        }
    }
    class CharSequence {
        constructor(charCodes, lineNumbers, columns) {
            this._charCodes = charCodes;
            this._lineNumbers = lineNumbers;
            this._columns = columns;
        }
        toString() {
            return ('[' + this._charCodes.map((s, idx) => (s === 10 /* CharCode.LineFeed */ ? '\\n' : String.fromCharCode(s)) + `-(${this._lineNumbers[idx]},${this._columns[idx]})`).join(', ') + ']');
        }
        _assertIndex(index, arr) {
            if (index < 0 || index >= arr.length) {
                throw new Error(`Illegal index`);
            }
        }
        getElements() {
            return this._charCodes;
        }
        getStartLineNumber(i) {
            if (i > 0 && i === this._lineNumbers.length) {
                // the start line number of the element after the last element
                // is the end line number of the last element
                return this.getEndLineNumber(i - 1);
            }
            this._assertIndex(i, this._lineNumbers);
            return this._lineNumbers[i];
        }
        getEndLineNumber(i) {
            if (i === -1) {
                // the end line number of the element before the first element
                // is the start line number of the first element
                return this.getStartLineNumber(i + 1);
            }
            this._assertIndex(i, this._lineNumbers);
            if (this._charCodes[i] === 10 /* CharCode.LineFeed */) {
                return this._lineNumbers[i] + 1;
            }
            return this._lineNumbers[i];
        }
        getStartColumn(i) {
            if (i > 0 && i === this._columns.length) {
                // the start column of the element after the last element
                // is the end column of the last element
                return this.getEndColumn(i - 1);
            }
            this._assertIndex(i, this._columns);
            return this._columns[i];
        }
        getEndColumn(i) {
            if (i === -1) {
                // the end column of the element before the first element
                // is the start column of the first element
                return this.getStartColumn(i + 1);
            }
            this._assertIndex(i, this._columns);
            if (this._charCodes[i] === 10 /* CharCode.LineFeed */) {
                return 1;
            }
            return this._columns[i] + 1;
        }
    }
    class CharChange {
        constructor(originalStartLineNumber, originalStartColumn, originalEndLineNumber, originalEndColumn, modifiedStartLineNumber, modifiedStartColumn, modifiedEndLineNumber, modifiedEndColumn) {
            this.originalStartLineNumber = originalStartLineNumber;
            this.originalStartColumn = originalStartColumn;
            this.originalEndLineNumber = originalEndLineNumber;
            this.originalEndColumn = originalEndColumn;
            this.modifiedStartLineNumber = modifiedStartLineNumber;
            this.modifiedStartColumn = modifiedStartColumn;
            this.modifiedEndLineNumber = modifiedEndLineNumber;
            this.modifiedEndColumn = modifiedEndColumn;
        }
        static createFromDiffChange(diffChange, originalCharSequence, modifiedCharSequence) {
            const originalStartLineNumber = originalCharSequence.getStartLineNumber(diffChange.originalStart);
            const originalStartColumn = originalCharSequence.getStartColumn(diffChange.originalStart);
            const originalEndLineNumber = originalCharSequence.getEndLineNumber(diffChange.originalStart + diffChange.originalLength - 1);
            const originalEndColumn = originalCharSequence.getEndColumn(diffChange.originalStart + diffChange.originalLength - 1);
            const modifiedStartLineNumber = modifiedCharSequence.getStartLineNumber(diffChange.modifiedStart);
            const modifiedStartColumn = modifiedCharSequence.getStartColumn(diffChange.modifiedStart);
            const modifiedEndLineNumber = modifiedCharSequence.getEndLineNumber(diffChange.modifiedStart + diffChange.modifiedLength - 1);
            const modifiedEndColumn = modifiedCharSequence.getEndColumn(diffChange.modifiedStart + diffChange.modifiedLength - 1);
            return new CharChange(originalStartLineNumber, originalStartColumn, originalEndLineNumber, originalEndColumn, modifiedStartLineNumber, modifiedStartColumn, modifiedEndLineNumber, modifiedEndColumn);
        }
    }
    function postProcessCharChanges(rawChanges) {
        if (rawChanges.length <= 1) {
            return rawChanges;
        }
        const result = [rawChanges[0]];
        let prevChange = result[0];
        for (let i = 1, len = rawChanges.length; i < len; i++) {
            const currChange = rawChanges[i];
            const originalMatchingLength = currChange.originalStart - (prevChange.originalStart + prevChange.originalLength);
            const modifiedMatchingLength = currChange.modifiedStart - (prevChange.modifiedStart + prevChange.modifiedLength);
            // Both of the above should be equal, but the continueProcessingPredicate may prevent this from being true
            const matchingLength = Math.min(originalMatchingLength, modifiedMatchingLength);
            if (matchingLength < MINIMUM_MATCHING_CHARACTER_LENGTH) {
                // Merge the current change into the previous one
                prevChange.originalLength = (currChange.originalStart + currChange.originalLength) - prevChange.originalStart;
                prevChange.modifiedLength = (currChange.modifiedStart + currChange.modifiedLength) - prevChange.modifiedStart;
            }
            else {
                // Add the current change
                result.push(currChange);
                prevChange = currChange;
            }
        }
        return result;
    }
    class LineChange {
        constructor(originalStartLineNumber, originalEndLineNumber, modifiedStartLineNumber, modifiedEndLineNumber, charChanges) {
            this.originalStartLineNumber = originalStartLineNumber;
            this.originalEndLineNumber = originalEndLineNumber;
            this.modifiedStartLineNumber = modifiedStartLineNumber;
            this.modifiedEndLineNumber = modifiedEndLineNumber;
            this.charChanges = charChanges;
        }
        static createFromDiffResult(shouldIgnoreTrimWhitespace, diffChange, originalLineSequence, modifiedLineSequence, continueCharDiff, shouldComputeCharChanges, shouldPostProcessCharChanges) {
            let originalStartLineNumber;
            let originalEndLineNumber;
            let modifiedStartLineNumber;
            let modifiedEndLineNumber;
            let charChanges = undefined;
            if (diffChange.originalLength === 0) {
                originalStartLineNumber = originalLineSequence.getStartLineNumber(diffChange.originalStart) - 1;
                originalEndLineNumber = 0;
            }
            else {
                originalStartLineNumber = originalLineSequence.getStartLineNumber(diffChange.originalStart);
                originalEndLineNumber = originalLineSequence.getEndLineNumber(diffChange.originalStart + diffChange.originalLength - 1);
            }
            if (diffChange.modifiedLength === 0) {
                modifiedStartLineNumber = modifiedLineSequence.getStartLineNumber(diffChange.modifiedStart) - 1;
                modifiedEndLineNumber = 0;
            }
            else {
                modifiedStartLineNumber = modifiedLineSequence.getStartLineNumber(diffChange.modifiedStart);
                modifiedEndLineNumber = modifiedLineSequence.getEndLineNumber(diffChange.modifiedStart + diffChange.modifiedLength - 1);
            }
            if (shouldComputeCharChanges && diffChange.originalLength > 0 && diffChange.originalLength < 20 && diffChange.modifiedLength > 0 && diffChange.modifiedLength < 20 && continueCharDiff()) {
                // Compute character changes for diff chunks of at most 20 lines...
                const originalCharSequence = originalLineSequence.createCharSequence(shouldIgnoreTrimWhitespace, diffChange.originalStart, diffChange.originalStart + diffChange.originalLength - 1);
                const modifiedCharSequence = modifiedLineSequence.createCharSequence(shouldIgnoreTrimWhitespace, diffChange.modifiedStart, diffChange.modifiedStart + diffChange.modifiedLength - 1);
                if (originalCharSequence.getElements().length > 0 && modifiedCharSequence.getElements().length > 0) {
                    let rawChanges = computeDiff(originalCharSequence, modifiedCharSequence, continueCharDiff, true).changes;
                    if (shouldPostProcessCharChanges) {
                        rawChanges = postProcessCharChanges(rawChanges);
                    }
                    charChanges = [];
                    for (let i = 0, length = rawChanges.length; i < length; i++) {
                        charChanges.push(CharChange.createFromDiffChange(rawChanges[i], originalCharSequence, modifiedCharSequence));
                    }
                }
            }
            return new LineChange(originalStartLineNumber, originalEndLineNumber, modifiedStartLineNumber, modifiedEndLineNumber, charChanges);
        }
    }
    class DiffComputer {
        constructor(originalLines, modifiedLines, opts) {
            this.shouldComputeCharChanges = opts.shouldComputeCharChanges;
            this.shouldPostProcessCharChanges = opts.shouldPostProcessCharChanges;
            this.shouldIgnoreTrimWhitespace = opts.shouldIgnoreTrimWhitespace;
            this.shouldMakePrettyDiff = opts.shouldMakePrettyDiff;
            this.originalLines = originalLines;
            this.modifiedLines = modifiedLines;
            this.original = new LineSequence(originalLines);
            this.modified = new LineSequence(modifiedLines);
            this.continueLineDiff = createContinueProcessingPredicate(opts.maxComputationTime);
            this.continueCharDiff = createContinueProcessingPredicate(opts.maxComputationTime === 0 ? 0 : Math.min(opts.maxComputationTime, 5000)); // never run after 5s for character changes...
        }
        computeDiff() {
            if (this.original.lines.length === 1 && this.original.lines[0].length === 0) {
                // empty original => fast path
                if (this.modified.lines.length === 1 && this.modified.lines[0].length === 0) {
                    return {
                        quitEarly: false,
                        changes: []
                    };
                }
                return {
                    quitEarly: false,
                    changes: [{
                            originalStartLineNumber: 1,
                            originalEndLineNumber: 1,
                            modifiedStartLineNumber: 1,
                            modifiedEndLineNumber: this.modified.lines.length,
                            charChanges: undefined
                        }]
                };
            }
            if (this.modified.lines.length === 1 && this.modified.lines[0].length === 0) {
                // empty modified => fast path
                return {
                    quitEarly: false,
                    changes: [{
                            originalStartLineNumber: 1,
                            originalEndLineNumber: this.original.lines.length,
                            modifiedStartLineNumber: 1,
                            modifiedEndLineNumber: 1,
                            charChanges: undefined
                        }]
                };
            }
            const diffResult = computeDiff(this.original, this.modified, this.continueLineDiff, this.shouldMakePrettyDiff);
            const rawChanges = diffResult.changes;
            const quitEarly = diffResult.quitEarly;
            // The diff is always computed with ignoring trim whitespace
            // This ensures we get the prettiest diff
            if (this.shouldIgnoreTrimWhitespace) {
                const lineChanges = [];
                for (let i = 0, length = rawChanges.length; i < length; i++) {
                    lineChanges.push(LineChange.createFromDiffResult(this.shouldIgnoreTrimWhitespace, rawChanges[i], this.original, this.modified, this.continueCharDiff, this.shouldComputeCharChanges, this.shouldPostProcessCharChanges));
                }
                return {
                    quitEarly: quitEarly,
                    changes: lineChanges
                };
            }
            // Need to post-process and introduce changes where the trim whitespace is different
            // Note that we are looping starting at -1 to also cover the lines before the first change
            const result = [];
            let originalLineIndex = 0;
            let modifiedLineIndex = 0;
            for (let i = -1 /* !!!! */, len = rawChanges.length; i < len; i++) {
                const nextChange = (i + 1 < len ? rawChanges[i + 1] : null);
                const originalStop = (nextChange ? nextChange.originalStart : this.originalLines.length);
                const modifiedStop = (nextChange ? nextChange.modifiedStart : this.modifiedLines.length);
                while (originalLineIndex < originalStop && modifiedLineIndex < modifiedStop) {
                    const originalLine = this.originalLines[originalLineIndex];
                    const modifiedLine = this.modifiedLines[modifiedLineIndex];
                    if (originalLine !== modifiedLine) {
                        // These lines differ only in trim whitespace
                        // Check the leading whitespace
                        {
                            let originalStartColumn = getFirstNonBlankColumn(originalLine, 1);
                            let modifiedStartColumn = getFirstNonBlankColumn(modifiedLine, 1);
                            while (originalStartColumn > 1 && modifiedStartColumn > 1) {
                                const originalChar = originalLine.charCodeAt(originalStartColumn - 2);
                                const modifiedChar = modifiedLine.charCodeAt(modifiedStartColumn - 2);
                                if (originalChar !== modifiedChar) {
                                    break;
                                }
                                originalStartColumn--;
                                modifiedStartColumn--;
                            }
                            if (originalStartColumn > 1 || modifiedStartColumn > 1) {
                                this._pushTrimWhitespaceCharChange(result, originalLineIndex + 1, 1, originalStartColumn, modifiedLineIndex + 1, 1, modifiedStartColumn);
                            }
                        }
                        // Check the trailing whitespace
                        {
                            let originalEndColumn = getLastNonBlankColumn(originalLine, 1);
                            let modifiedEndColumn = getLastNonBlankColumn(modifiedLine, 1);
                            const originalMaxColumn = originalLine.length + 1;
                            const modifiedMaxColumn = modifiedLine.length + 1;
                            while (originalEndColumn < originalMaxColumn && modifiedEndColumn < modifiedMaxColumn) {
                                const originalChar = originalLine.charCodeAt(originalEndColumn - 1);
                                const modifiedChar = originalLine.charCodeAt(modifiedEndColumn - 1);
                                if (originalChar !== modifiedChar) {
                                    break;
                                }
                                originalEndColumn++;
                                modifiedEndColumn++;
                            }
                            if (originalEndColumn < originalMaxColumn || modifiedEndColumn < modifiedMaxColumn) {
                                this._pushTrimWhitespaceCharChange(result, originalLineIndex + 1, originalEndColumn, originalMaxColumn, modifiedLineIndex + 1, modifiedEndColumn, modifiedMaxColumn);
                            }
                        }
                    }
                    originalLineIndex++;
                    modifiedLineIndex++;
                }
                if (nextChange) {
                    // Emit the actual change
                    result.push(LineChange.createFromDiffResult(this.shouldIgnoreTrimWhitespace, nextChange, this.original, this.modified, this.continueCharDiff, this.shouldComputeCharChanges, this.shouldPostProcessCharChanges));
                    originalLineIndex += nextChange.originalLength;
                    modifiedLineIndex += nextChange.modifiedLength;
                }
            }
            return {
                quitEarly: quitEarly,
                changes: result
            };
        }
        _pushTrimWhitespaceCharChange(result, originalLineNumber, originalStartColumn, originalEndColumn, modifiedLineNumber, modifiedStartColumn, modifiedEndColumn) {
            if (this._mergeTrimWhitespaceCharChange(result, originalLineNumber, originalStartColumn, originalEndColumn, modifiedLineNumber, modifiedStartColumn, modifiedEndColumn)) {
                // Merged into previous
                return;
            }
            let charChanges = undefined;
            if (this.shouldComputeCharChanges) {
                charChanges = [new CharChange(originalLineNumber, originalStartColumn, originalLineNumber, originalEndColumn, modifiedLineNumber, modifiedStartColumn, modifiedLineNumber, modifiedEndColumn)];
            }
            result.push(new LineChange(originalLineNumber, originalLineNumber, modifiedLineNumber, modifiedLineNumber, charChanges));
        }
        _mergeTrimWhitespaceCharChange(result, originalLineNumber, originalStartColumn, originalEndColumn, modifiedLineNumber, modifiedStartColumn, modifiedEndColumn) {
            const len = result.length;
            if (len === 0) {
                return false;
            }
            const prevChange = result[len - 1];
            if (prevChange.originalEndLineNumber === 0 || prevChange.modifiedEndLineNumber === 0) {
                // Don't merge with inserts/deletes
                return false;
            }
            if (prevChange.originalEndLineNumber === originalLineNumber && prevChange.modifiedEndLineNumber === modifiedLineNumber) {
                if (this.shouldComputeCharChanges && prevChange.charChanges) {
                    prevChange.charChanges.push(new CharChange(originalLineNumber, originalStartColumn, originalLineNumber, originalEndColumn, modifiedLineNumber, modifiedStartColumn, modifiedLineNumber, modifiedEndColumn));
                }
                return true;
            }
            if (prevChange.originalEndLineNumber + 1 === originalLineNumber && prevChange.modifiedEndLineNumber + 1 === modifiedLineNumber) {
                prevChange.originalEndLineNumber = originalLineNumber;
                prevChange.modifiedEndLineNumber = modifiedLineNumber;
                if (this.shouldComputeCharChanges && prevChange.charChanges) {
                    prevChange.charChanges.push(new CharChange(originalLineNumber, originalStartColumn, originalLineNumber, originalEndColumn, modifiedLineNumber, modifiedStartColumn, modifiedLineNumber, modifiedEndColumn));
                }
                return true;
            }
            return false;
        }
    }
    exports.DiffComputer = DiffComputer;
    function getFirstNonBlankColumn(txt, defaultValue) {
        const r = strings.firstNonWhitespaceIndex(txt);
        if (r === -1) {
            return defaultValue;
        }
        return r + 1;
    }
    function getLastNonBlankColumn(txt, defaultValue) {
        const r = strings.lastNonWhitespaceIndex(txt);
        if (r === -1) {
            return defaultValue;
        }
        return r + 2;
    }
    function createContinueProcessingPredicate(maximumRuntime) {
        if (maximumRuntime === 0) {
            return () => true;
        }
        const startTime = Date.now();
        return () => {
            return Date.now() - startTime < maximumRuntime;
        };
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[561/*vs/editor/common/diff/linesDiffComputers*/], __M([1/*require*/,0/*exports*/,560/*vs/editor/common/diff/legacyLinesDiffComputer*/,317/*vs/editor/common/diff/defaultLinesDiffComputer/defaultLinesDiffComputer*/]), function (require, exports, legacyLinesDiffComputer_1, defaultLinesDiffComputer_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.linesDiffComputers = void 0;
    exports.linesDiffComputers = {
        getLegacy: () => new legacyLinesDiffComputer_1.LegacyLinesDiffComputer(),
        getDefault: () => new defaultLinesDiffComputer_1.DefaultLinesDiffComputer(),
    };
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[318/*vs/editor/common/editorAction*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.InternalEditorAction = void 0;
    class InternalEditorAction {
        constructor(id, label, alias, metadata, _precondition, _run, _contextKeyService) {
            this.id = id;
            this.label = label;
            this.alias = alias;
            this.metadata = metadata;
            this._precondition = _precondition;
            this._run = _run;
            this._contextKeyService = _contextKeyService;
        }
        isSupported() {
            return this._contextKeyService.contextMatchesRules(this._precondition);
        }
        run(args) {
            if (!this.isSupported()) {
                return Promise.resolve(undefined);
            }
            return this._run(args);
        }
    }
    exports.InternalEditorAction = InternalEditorAction;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[198/*vs/editor/common/editorCommon*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.EditorType = void 0;
    /**
     * The type of the `IEditor`.
     */
    exports.EditorType = {
        ICodeEditor: 'vs.editor.ICodeEditor',
        IDiffEditor: 'vs.editor.IDiffEditor'
    };
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[168/*vs/editor/browser/editorBrowser*/], __M([1/*require*/,0/*exports*/,198/*vs/editor/common/editorCommon*/]), function (require, exports, editorCommon) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.isCodeEditor = isCodeEditor;
    exports.isDiffEditor = isDiffEditor;
    exports.isCompositeEditor = isCompositeEditor;
    exports.getCodeEditor = getCodeEditor;
    /**
     *@internal
     */
    function isCodeEditor(thing) {
        if (thing && typeof thing.getEditorType === 'function') {
            return thing.getEditorType() === editorCommon.EditorType.ICodeEditor;
        }
        else {
            return false;
        }
    }
    /**
     *@internal
     */
    function isDiffEditor(thing) {
        if (thing && typeof thing.getEditorType === 'function') {
            return thing.getEditorType() === editorCommon.EditorType.IDiffEditor;
        }
        else {
            return false;
        }
    }
    /**
     *@internal
     */
    function isCompositeEditor(thing) {
        return !!thing
            && typeof thing === 'object'
            && typeof thing.onDidChangeActiveEditor === 'function';
    }
    /**
     *@internal
     */
    function getCodeEditor(thing) {
        if (isCodeEditor(thing)) {
            return thing;
        }
        if (isDiffEditor(thing)) {
            return thing.getModifiedEditor();
        }
        if (isCompositeEditor(thing) && isCodeEditor(thing.activeCodeEditor)) {
            return thing.activeCodeEditor;
        }
        return null;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[130/*vs/editor/common/editorFeatures*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.registerEditorFeature = registerEditorFeature;
    exports.getEditorFeatures = getEditorFeatures;
    const editorFeatures = [];
    /**
     * Registers an editor feature. Editor features will be instantiated only once, as soon as
     * the first code editor is instantiated.
     */
    function registerEditorFeature(ctor) {
        editorFeatures.push(ctor);
    }
    function getEditorFeatures() {
        return editorFeatures.slice(0);
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[562/*vs/editor/common/editorTheme*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.EditorTheme = void 0;
    class EditorTheme {
        get type() {
            return this._theme.type;
        }
        get value() {
            return this._theme;
        }
        constructor(theme) {
            this._theme = theme;
        }
        update(theme) {
            this._theme = theme;
        }
        getColor(color) {
            return this._theme.getColor(color);
        }
    }
    exports.EditorTheme = EditorTheme;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[148/*vs/editor/common/encodedTokenAttributes*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.TokenMetadata = void 0;
    /**
     */
    class TokenMetadata {
        static getLanguageId(metadata) {
            return (metadata & 255 /* MetadataConsts.LANGUAGEID_MASK */) >>> 0 /* MetadataConsts.LANGUAGEID_OFFSET */;
        }
        static getTokenType(metadata) {
            return (metadata & 768 /* MetadataConsts.TOKEN_TYPE_MASK */) >>> 8 /* MetadataConsts.TOKEN_TYPE_OFFSET */;
        }
        static containsBalancedBrackets(metadata) {
            return (metadata & 1024 /* MetadataConsts.BALANCED_BRACKETS_MASK */) !== 0;
        }
        static getFontStyle(metadata) {
            return (metadata & 30720 /* MetadataConsts.FONT_STYLE_MASK */) >>> 11 /* MetadataConsts.FONT_STYLE_OFFSET */;
        }
        static getForeground(metadata) {
            return (metadata & 16744448 /* MetadataConsts.FOREGROUND_MASK */) >>> 15 /* MetadataConsts.FOREGROUND_OFFSET */;
        }
        static getBackground(metadata) {
            return (metadata & 4278190080 /* MetadataConsts.BACKGROUND_MASK */) >>> 24 /* MetadataConsts.BACKGROUND_OFFSET */;
        }
        static getClassNameFromMetadata(metadata) {
            const foreground = this.getForeground(metadata);
            let className = 'mtk' + foreground;
            const fontStyle = this.getFontStyle(metadata);
            if (fontStyle & 1 /* FontStyle.Italic */) {
                className += ' mtki';
            }
            if (fontStyle & 2 /* FontStyle.Bold */) {
                className += ' mtkb';
            }
            if (fontStyle & 4 /* FontStyle.Underline */) {
                className += ' mtku';
            }
            if (fontStyle & 8 /* FontStyle.Strikethrough */) {
                className += ' mtks';
            }
            return className;
        }
        static getInlineStyleFromMetadata(metadata, colorMap) {
            const foreground = this.getForeground(metadata);
            const fontStyle = this.getFontStyle(metadata);
            let result = `color: ${colorMap[foreground]};`;
            if (fontStyle & 1 /* FontStyle.Italic */) {
                result += 'font-style: italic;';
            }
            if (fontStyle & 2 /* FontStyle.Bold */) {
                result += 'font-weight: bold;';
            }
            let textDecoration = '';
            if (fontStyle & 4 /* FontStyle.Underline */) {
                textDecoration += ' underline';
            }
            if (fontStyle & 8 /* FontStyle.Strikethrough */) {
                textDecoration += ' line-through';
            }
            if (textDecoration) {
                result += `text-decoration:${textDecoration};`;
            }
            return result;
        }
        static getPresentationFromMetadata(metadata) {
            const foreground = this.getForeground(metadata);
            const fontStyle = this.getFontStyle(metadata);
            return {
                foreground: foreground,
                italic: Boolean(fontStyle & 1 /* FontStyle.Italic */),
                bold: Boolean(fontStyle & 2 /* FontStyle.Bold */),
                underline: Boolean(fontStyle & 4 /* FontStyle.Underline */),
                strikethrough: Boolean(fontStyle & 8 /* FontStyle.Strikethrough */),
            };
        }
    }
    exports.TokenMetadata = TokenMetadata;
});

define(__m[563/*vs/editor/common/languages/defaultDocumentColorsComputer*/], __M([1/*require*/,0/*exports*/,33/*vs/base/common/color*/]), function (require, exports, color_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.computeDefaultDocumentColors = computeDefaultDocumentColors;
    function _parseCaptureGroups(captureGroups) {
        const values = [];
        for (const captureGroup of captureGroups) {
            const parsedNumber = Number(captureGroup);
            if (parsedNumber || parsedNumber === 0 && captureGroup.replace(/\s/g, '') !== '') {
                values.push(parsedNumber);
            }
        }
        return values;
    }
    function _toIColor(r, g, b, a) {
        return {
            red: r / 255,
            blue: b / 255,
            green: g / 255,
            alpha: a
        };
    }
    function _findRange(model, match) {
        const index = match.index;
        const length = match[0].length;
        if (!index) {
            return;
        }
        const startPosition = model.positionAt(index);
        const range = {
            startLineNumber: startPosition.lineNumber,
            startColumn: startPosition.column,
            endLineNumber: startPosition.lineNumber,
            endColumn: startPosition.column + length
        };
        return range;
    }
    function _findHexColorInformation(range, hexValue) {
        if (!range) {
            return;
        }
        const parsedHexColor = color_1.Color.Format.CSS.parseHex(hexValue);
        if (!parsedHexColor) {
            return;
        }
        return {
            range: range,
            color: _toIColor(parsedHexColor.rgba.r, parsedHexColor.rgba.g, parsedHexColor.rgba.b, parsedHexColor.rgba.a)
        };
    }
    function _findRGBColorInformation(range, matches, isAlpha) {
        if (!range || matches.length !== 1) {
            return;
        }
        const match = matches[0];
        const captureGroups = match.values();
        const parsedRegex = _parseCaptureGroups(captureGroups);
        return {
            range: range,
            color: _toIColor(parsedRegex[0], parsedRegex[1], parsedRegex[2], isAlpha ? parsedRegex[3] : 1)
        };
    }
    function _findHSLColorInformation(range, matches, isAlpha) {
        if (!range || matches.length !== 1) {
            return;
        }
        const match = matches[0];
        const captureGroups = match.values();
        const parsedRegex = _parseCaptureGroups(captureGroups);
        const colorEquivalent = new color_1.Color(new color_1.HSLA(parsedRegex[0], parsedRegex[1] / 100, parsedRegex[2] / 100, isAlpha ? parsedRegex[3] : 1));
        return {
            range: range,
            color: _toIColor(colorEquivalent.rgba.r, colorEquivalent.rgba.g, colorEquivalent.rgba.b, colorEquivalent.rgba.a)
        };
    }
    function _findMatches(model, regex) {
        if (typeof model === 'string') {
            return [...model.matchAll(regex)];
        }
        else {
            return model.findMatches(regex);
        }
    }
    function computeColors(model) {
        const result = [];
        // Early validation for RGB and HSL
        const initialValidationRegex = /\b(rgb|rgba|hsl|hsla)(\([0-9\s,.\%]*\))|(#)([A-Fa-f0-9]{3})\b|(#)([A-Fa-f0-9]{4})\b|(#)([A-Fa-f0-9]{6})\b|(#)([A-Fa-f0-9]{8})\b/gm;
        const initialValidationMatches = _findMatches(model, initialValidationRegex);
        // Potential colors have been found, validate the parameters
        if (initialValidationMatches.length > 0) {
            for (const initialMatch of initialValidationMatches) {
                const initialCaptureGroups = initialMatch.filter(captureGroup => captureGroup !== undefined);
                const colorScheme = initialCaptureGroups[1];
                const colorParameters = initialCaptureGroups[2];
                if (!colorParameters) {
                    continue;
                }
                let colorInformation;
                if (colorScheme === 'rgb') {
                    const regexParameters = /^\(\s*(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\s*,\s*(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\s*,\s*(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\s*\)$/gm;
                    colorInformation = _findRGBColorInformation(_findRange(model, initialMatch), _findMatches(colorParameters, regexParameters), false);
                }
                else if (colorScheme === 'rgba') {
                    const regexParameters = /^\(\s*(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\s*,\s*(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\s*,\s*(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\s*,\s*(0[.][0-9]+|[.][0-9]+|[01][.]|[01])\s*\)$/gm;
                    colorInformation = _findRGBColorInformation(_findRange(model, initialMatch), _findMatches(colorParameters, regexParameters), true);
                }
                else if (colorScheme === 'hsl') {
                    const regexParameters = /^\(\s*(36[0]|3[0-5][0-9]|[12][0-9][0-9]|[1-9]?[0-9])\s*,\s*(100|\d{1,2}[.]\d*|\d{1,2})%\s*,\s*(100|\d{1,2}[.]\d*|\d{1,2})%\s*\)$/gm;
                    colorInformation = _findHSLColorInformation(_findRange(model, initialMatch), _findMatches(colorParameters, regexParameters), false);
                }
                else if (colorScheme === 'hsla') {
                    const regexParameters = /^\(\s*(36[0]|3[0-5][0-9]|[12][0-9][0-9]|[1-9]?[0-9])\s*,\s*(100|\d{1,2}[.]\d*|\d{1,2})%\s*,\s*(100|\d{1,2}[.]\d*|\d{1,2})%\s*,\s*(0[.][0-9]+|[.][0-9]+|[01][.]|[01])\s*\)$/gm;
                    colorInformation = _findHSLColorInformation(_findRange(model, initialMatch), _findMatches(colorParameters, regexParameters), true);
                }
                else if (colorScheme === '#') {
                    colorInformation = _findHexColorInformation(_findRange(model, initialMatch), colorScheme + colorParameters);
                }
                if (colorInformation) {
                    result.push(colorInformation);
                }
            }
        }
        return result;
    }
    /**
     * Returns an array of all default document colors in the provided document
     */
    function computeDefaultDocumentColors(model) {
        if (!model || typeof model.getValue !== 'function' || typeof model.positionAt !== 'function') {
            // Unknown caller!
            return [];
        }
        return computeColors(model);
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[131/*vs/editor/common/languages/languageConfiguration*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AutoClosingPairs = exports.StandardAutoClosingPairConditional = exports.IndentAction = void 0;
    /**
     * Describes what to do with the indentation when pressing Enter.
     */
    var IndentAction;
    (function (IndentAction) {
        /**
         * Insert new line and copy the previous line's indentation.
         */
        IndentAction[IndentAction["None"] = 0] = "None";
        /**
         * Insert new line and indent once (relative to the previous line's indentation).
         */
        IndentAction[IndentAction["Indent"] = 1] = "Indent";
        /**
         * Insert two new lines:
         *  - the first one indented which will hold the cursor
         *  - the second one at the same indentation level
         */
        IndentAction[IndentAction["IndentOutdent"] = 2] = "IndentOutdent";
        /**
         * Insert new line and outdent once (relative to the previous line's indentation).
         */
        IndentAction[IndentAction["Outdent"] = 3] = "Outdent";
    })(IndentAction || (exports.IndentAction = IndentAction = {}));
    /**
     * @internal
     */
    class StandardAutoClosingPairConditional {
        constructor(source) {
            this._neutralCharacter = null;
            this._neutralCharacterSearched = false;
            this.open = source.open;
            this.close = source.close;
            // initially allowed in all tokens
            this._inString = true;
            this._inComment = true;
            this._inRegEx = true;
            if (Array.isArray(source.notIn)) {
                for (let i = 0, len = source.notIn.length; i < len; i++) {
                    const notIn = source.notIn[i];
                    switch (notIn) {
                        case 'string':
                            this._inString = false;
                            break;
                        case 'comment':
                            this._inComment = false;
                            break;
                        case 'regex':
                            this._inRegEx = false;
                            break;
                    }
                }
            }
        }
        isOK(standardToken) {
            switch (standardToken) {
                case 0 /* StandardTokenType.Other */:
                    return true;
                case 1 /* StandardTokenType.Comment */:
                    return this._inComment;
                case 2 /* StandardTokenType.String */:
                    return this._inString;
                case 3 /* StandardTokenType.RegEx */:
                    return this._inRegEx;
            }
        }
        shouldAutoClose(context, column) {
            // Always complete on empty line
            if (context.getTokenCount() === 0) {
                return true;
            }
            const tokenIndex = context.findTokenIndexAtOffset(column - 2);
            const standardTokenType = context.getStandardTokenType(tokenIndex);
            return this.isOK(standardTokenType);
        }
        _findNeutralCharacterInRange(fromCharCode, toCharCode) {
            for (let charCode = fromCharCode; charCode <= toCharCode; charCode++) {
                const character = String.fromCharCode(charCode);
                if (!this.open.includes(character) && !this.close.includes(character)) {
                    return character;
                }
            }
            return null;
        }
        /**
         * Find a character in the range [0-9a-zA-Z] that does not appear in the open or close
         */
        findNeutralCharacter() {
            if (!this._neutralCharacterSearched) {
                this._neutralCharacterSearched = true;
                if (!this._neutralCharacter) {
                    this._neutralCharacter = this._findNeutralCharacterInRange(48 /* CharCode.Digit0 */, 57 /* CharCode.Digit9 */);
                }
                if (!this._neutralCharacter) {
                    this._neutralCharacter = this._findNeutralCharacterInRange(97 /* CharCode.a */, 122 /* CharCode.z */);
                }
                if (!this._neutralCharacter) {
                    this._neutralCharacter = this._findNeutralCharacterInRange(65 /* CharCode.A */, 90 /* CharCode.Z */);
                }
            }
            return this._neutralCharacter;
        }
    }
    exports.StandardAutoClosingPairConditional = StandardAutoClosingPairConditional;
    /**
     * @internal
     */
    class AutoClosingPairs {
        constructor(autoClosingPairs) {
            this.autoClosingPairsOpenByStart = new Map();
            this.autoClosingPairsOpenByEnd = new Map();
            this.autoClosingPairsCloseByStart = new Map();
            this.autoClosingPairsCloseByEnd = new Map();
            this.autoClosingPairsCloseSingleChar = new Map();
            for (const pair of autoClosingPairs) {
                appendEntry(this.autoClosingPairsOpenByStart, pair.open.charAt(0), pair);
                appendEntry(this.autoClosingPairsOpenByEnd, pair.open.charAt(pair.open.length - 1), pair);
                appendEntry(this.autoClosingPairsCloseByStart, pair.close.charAt(0), pair);
                appendEntry(this.autoClosingPairsCloseByEnd, pair.close.charAt(pair.close.length - 1), pair);
                if (pair.close.length === 1 && pair.open.length === 1) {
                    appendEntry(this.autoClosingPairsCloseSingleChar, pair.close, pair);
                }
            }
        }
    }
    exports.AutoClosingPairs = AutoClosingPairs;
    function appendEntry(target, key, value) {
        if (target.has(key)) {
            target.get(key).push(value);
        }
        else {
            target.set(key, [value]);
        }
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[564/*vs/editor/common/languages/linkComputer*/], __M([1/*require*/,0/*exports*/,144/*vs/editor/common/core/characterClassifier*/]), function (require, exports, characterClassifier_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.LinkComputer = exports.StateMachine = void 0;
    exports.computeLinks = computeLinks;
    class Uint8Matrix {
        constructor(rows, cols, defaultValue) {
            const data = new Uint8Array(rows * cols);
            for (let i = 0, len = rows * cols; i < len; i++) {
                data[i] = defaultValue;
            }
            this._data = data;
            this.rows = rows;
            this.cols = cols;
        }
        get(row, col) {
            return this._data[row * this.cols + col];
        }
        set(row, col, value) {
            this._data[row * this.cols + col] = value;
        }
    }
    class StateMachine {
        constructor(edges) {
            let maxCharCode = 0;
            let maxState = 0 /* State.Invalid */;
            for (let i = 0, len = edges.length; i < len; i++) {
                const [from, chCode, to] = edges[i];
                if (chCode > maxCharCode) {
                    maxCharCode = chCode;
                }
                if (from > maxState) {
                    maxState = from;
                }
                if (to > maxState) {
                    maxState = to;
                }
            }
            maxCharCode++;
            maxState++;
            const states = new Uint8Matrix(maxState, maxCharCode, 0 /* State.Invalid */);
            for (let i = 0, len = edges.length; i < len; i++) {
                const [from, chCode, to] = edges[i];
                states.set(from, chCode, to);
            }
            this._states = states;
            this._maxCharCode = maxCharCode;
        }
        nextState(currentState, chCode) {
            if (chCode < 0 || chCode >= this._maxCharCode) {
                return 0 /* State.Invalid */;
            }
            return this._states.get(currentState, chCode);
        }
    }
    exports.StateMachine = StateMachine;
    // State machine for http:// or https:// or file://
    let _stateMachine = null;
    function getStateMachine() {
        if (_stateMachine === null) {
            _stateMachine = new StateMachine([
                [1 /* State.Start */, 104 /* CharCode.h */, 2 /* State.H */],
                [1 /* State.Start */, 72 /* CharCode.H */, 2 /* State.H */],
                [1 /* State.Start */, 102 /* CharCode.f */, 6 /* State.F */],
                [1 /* State.Start */, 70 /* CharCode.F */, 6 /* State.F */],
                [2 /* State.H */, 116 /* CharCode.t */, 3 /* State.HT */],
                [2 /* State.H */, 84 /* CharCode.T */, 3 /* State.HT */],
                [3 /* State.HT */, 116 /* CharCode.t */, 4 /* State.HTT */],
                [3 /* State.HT */, 84 /* CharCode.T */, 4 /* State.HTT */],
                [4 /* State.HTT */, 112 /* CharCode.p */, 5 /* State.HTTP */],
                [4 /* State.HTT */, 80 /* CharCode.P */, 5 /* State.HTTP */],
                [5 /* State.HTTP */, 115 /* CharCode.s */, 9 /* State.BeforeColon */],
                [5 /* State.HTTP */, 83 /* CharCode.S */, 9 /* State.BeforeColon */],
                [5 /* State.HTTP */, 58 /* CharCode.Colon */, 10 /* State.AfterColon */],
                [6 /* State.F */, 105 /* CharCode.i */, 7 /* State.FI */],
                [6 /* State.F */, 73 /* CharCode.I */, 7 /* State.FI */],
                [7 /* State.FI */, 108 /* CharCode.l */, 8 /* State.FIL */],
                [7 /* State.FI */, 76 /* CharCode.L */, 8 /* State.FIL */],
                [8 /* State.FIL */, 101 /* CharCode.e */, 9 /* State.BeforeColon */],
                [8 /* State.FIL */, 69 /* CharCode.E */, 9 /* State.BeforeColon */],
                [9 /* State.BeforeColon */, 58 /* CharCode.Colon */, 10 /* State.AfterColon */],
                [10 /* State.AfterColon */, 47 /* CharCode.Slash */, 11 /* State.AlmostThere */],
                [11 /* State.AlmostThere */, 47 /* CharCode.Slash */, 12 /* State.End */],
            ]);
        }
        return _stateMachine;
    }
    let _classifier = null;
    function getClassifier() {
        if (_classifier === null) {
            _classifier = new characterClassifier_1.CharacterClassifier(0 /* CharacterClass.None */);
            // allow-any-unicode-next-line
            const FORCE_TERMINATION_CHARACTERS = ' \t<>\'\"、。。、,.:;‘〈「『〔([{「」}])〕』」〉’`~…';
            for (let i = 0; i < FORCE_TERMINATION_CHARACTERS.length; i++) {
                _classifier.set(FORCE_TERMINATION_CHARACTERS.charCodeAt(i), 1 /* CharacterClass.ForceTermination */);
            }
            const CANNOT_END_WITH_CHARACTERS = '.,;:';
            for (let i = 0; i < CANNOT_END_WITH_CHARACTERS.length; i++) {
                _classifier.set(CANNOT_END_WITH_CHARACTERS.charCodeAt(i), 2 /* CharacterClass.CannotEndIn */);
            }
        }
        return _classifier;
    }
    class LinkComputer {
        static _createLink(classifier, line, lineNumber, linkBeginIndex, linkEndIndex) {
            // Do not allow to end link in certain characters...
            let lastIncludedCharIndex = linkEndIndex - 1;
            do {
                const chCode = line.charCodeAt(lastIncludedCharIndex);
                const chClass = classifier.get(chCode);
                if (chClass !== 2 /* CharacterClass.CannotEndIn */) {
                    break;
                }
                lastIncludedCharIndex--;
            } while (lastIncludedCharIndex > linkBeginIndex);
            // Handle links enclosed in parens, square brackets and curlys.
            if (linkBeginIndex > 0) {
                const charCodeBeforeLink = line.charCodeAt(linkBeginIndex - 1);
                const lastCharCodeInLink = line.charCodeAt(lastIncludedCharIndex);
                if ((charCodeBeforeLink === 40 /* CharCode.OpenParen */ && lastCharCodeInLink === 41 /* CharCode.CloseParen */)
                    || (charCodeBeforeLink === 91 /* CharCode.OpenSquareBracket */ && lastCharCodeInLink === 93 /* CharCode.CloseSquareBracket */)
                    || (charCodeBeforeLink === 123 /* CharCode.OpenCurlyBrace */ && lastCharCodeInLink === 125 /* CharCode.CloseCurlyBrace */)) {
                    // Do not end in ) if ( is before the link start
                    // Do not end in ] if [ is before the link start
                    // Do not end in } if { is before the link start
                    lastIncludedCharIndex--;
                }
            }
            return {
                range: {
                    startLineNumber: lineNumber,
                    startColumn: linkBeginIndex + 1,
                    endLineNumber: lineNumber,
                    endColumn: lastIncludedCharIndex + 2
                },
                url: line.substring(linkBeginIndex, lastIncludedCharIndex + 1)
            };
        }
        static computeLinks(model, stateMachine = getStateMachine()) {
            const classifier = getClassifier();
            const result = [];
            for (let i = 1, lineCount = model.getLineCount(); i <= lineCount; i++) {
                const line = model.getLineContent(i);
                const len = line.length;
                let j = 0;
                let linkBeginIndex = 0;
                let linkBeginChCode = 0;
                let state = 1 /* State.Start */;
                let hasOpenParens = false;
                let hasOpenSquareBracket = false;
                let inSquareBrackets = false;
                let hasOpenCurlyBracket = false;
                while (j < len) {
                    let resetStateMachine = false;
                    const chCode = line.charCodeAt(j);
                    if (state === 13 /* State.Accept */) {
                        let chClass;
                        switch (chCode) {
                            case 40 /* CharCode.OpenParen */:
                                hasOpenParens = true;
                                chClass = 0 /* CharacterClass.None */;
                                break;
                            case 41 /* CharCode.CloseParen */:
                                chClass = (hasOpenParens ? 0 /* CharacterClass.None */ : 1 /* CharacterClass.ForceTermination */);
                                break;
                            case 91 /* CharCode.OpenSquareBracket */:
                                inSquareBrackets = true;
                                hasOpenSquareBracket = true;
                                chClass = 0 /* CharacterClass.None */;
                                break;
                            case 93 /* CharCode.CloseSquareBracket */:
                                inSquareBrackets = false;
                                chClass = (hasOpenSquareBracket ? 0 /* CharacterClass.None */ : 1 /* CharacterClass.ForceTermination */);
                                break;
                            case 123 /* CharCode.OpenCurlyBrace */:
                                hasOpenCurlyBracket = true;
                                chClass = 0 /* CharacterClass.None */;
                                break;
                            case 125 /* CharCode.CloseCurlyBrace */:
                                chClass = (hasOpenCurlyBracket ? 0 /* CharacterClass.None */ : 1 /* CharacterClass.ForceTermination */);
                                break;
                            // The following three rules make it that ' or " or ` are allowed inside links
                            // only if the link is wrapped by some other quote character
                            case 39 /* CharCode.SingleQuote */:
                            case 34 /* CharCode.DoubleQuote */:
                            case 96 /* CharCode.BackTick */:
                                if (linkBeginChCode === chCode) {
                                    chClass = 1 /* CharacterClass.ForceTermination */;
                                }
                                else if (linkBeginChCode === 39 /* CharCode.SingleQuote */ || linkBeginChCode === 34 /* CharCode.DoubleQuote */ || linkBeginChCode === 96 /* CharCode.BackTick */) {
                                    chClass = 0 /* CharacterClass.None */;
                                }
                                else {
                                    chClass = 1 /* CharacterClass.ForceTermination */;
                                }
                                break;
                            case 42 /* CharCode.Asterisk */:
                                // `*` terminates a link if the link began with `*`
                                chClass = (linkBeginChCode === 42 /* CharCode.Asterisk */) ? 1 /* CharacterClass.ForceTermination */ : 0 /* CharacterClass.None */;
                                break;
                            case 124 /* CharCode.Pipe */:
                                // `|` terminates a link if the link began with `|`
                                chClass = (linkBeginChCode === 124 /* CharCode.Pipe */) ? 1 /* CharacterClass.ForceTermination */ : 0 /* CharacterClass.None */;
                                break;
                            case 32 /* CharCode.Space */:
                                // ` ` allow space in between [ and ]
                                chClass = (inSquareBrackets ? 0 /* CharacterClass.None */ : 1 /* CharacterClass.ForceTermination */);
                                break;
                            default:
                                chClass = classifier.get(chCode);
                        }
                        // Check if character terminates link
                        if (chClass === 1 /* CharacterClass.ForceTermination */) {
                            result.push(LinkComputer._createLink(classifier, line, i, linkBeginIndex, j));
                            resetStateMachine = true;
                        }
                    }
                    else if (state === 12 /* State.End */) {
                        let chClass;
                        if (chCode === 91 /* CharCode.OpenSquareBracket */) {
                            // Allow for the authority part to contain ipv6 addresses which contain [ and ]
                            hasOpenSquareBracket = true;
                            chClass = 0 /* CharacterClass.None */;
                        }
                        else {
                            chClass = classifier.get(chCode);
                        }
                        // Check if character terminates link
                        if (chClass === 1 /* CharacterClass.ForceTermination */) {
                            resetStateMachine = true;
                        }
                        else {
                            state = 13 /* State.Accept */;
                        }
                    }
                    else {
                        state = stateMachine.nextState(state, chCode);
                        if (state === 0 /* State.Invalid */) {
                            resetStateMachine = true;
                        }
                    }
                    if (resetStateMachine) {
                        state = 1 /* State.Start */;
                        hasOpenParens = false;
                        hasOpenSquareBracket = false;
                        hasOpenCurlyBracket = false;
                        // Record where the link started
                        linkBeginIndex = j + 1;
                        linkBeginChCode = chCode;
                    }
                    j++;
                }
                if (state === 13 /* State.Accept */) {
                    result.push(LinkComputer._createLink(classifier, line, i, linkBeginIndex, len));
                }
            }
            return result;
        }
    }
    exports.LinkComputer = LinkComputer;
    /**
     * Returns an array of all links contains in the provided
     * document. *Note* that this operation is computational
     * expensive and should not run in the UI thread.
     */
    function computeLinks(model) {
        if (!model || typeof model.getLineCount !== 'function' || typeof model.getLineContent !== 'function') {
            // Unknown caller!
            return [];
        }
        return LinkComputer.computeLinks(model);
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[169/*vs/editor/common/languages/supports*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ScopedLineTokens = void 0;
    exports.createScopedLineTokens = createScopedLineTokens;
    exports.ignoreBracketsInToken = ignoreBracketsInToken;
    function createScopedLineTokens(context, offset) {
        const tokenCount = context.getCount();
        const tokenIndex = context.findTokenIndexAtOffset(offset);
        const desiredLanguageId = context.getLanguageId(tokenIndex);
        let lastTokenIndex = tokenIndex;
        while (lastTokenIndex + 1 < tokenCount && context.getLanguageId(lastTokenIndex + 1) === desiredLanguageId) {
            lastTokenIndex++;
        }
        let firstTokenIndex = tokenIndex;
        while (firstTokenIndex > 0 && context.getLanguageId(firstTokenIndex - 1) === desiredLanguageId) {
            firstTokenIndex--;
        }
        return new ScopedLineTokens(context, desiredLanguageId, firstTokenIndex, lastTokenIndex + 1, context.getStartOffset(firstTokenIndex), context.getEndOffset(lastTokenIndex));
    }
    class ScopedLineTokens {
        constructor(actual, languageId, firstTokenIndex, lastTokenIndex, firstCharOffset, lastCharOffset) {
            this._scopedLineTokensBrand = undefined;
            this._actual = actual;
            this.languageId = languageId;
            this._firstTokenIndex = firstTokenIndex;
            this._lastTokenIndex = lastTokenIndex;
            this.firstCharOffset = firstCharOffset;
            this._lastCharOffset = lastCharOffset;
            this.languageIdCodec = actual.languageIdCodec;
        }
        getLineContent() {
            const actualLineContent = this._actual.getLineContent();
            return actualLineContent.substring(this.firstCharOffset, this._lastCharOffset);
        }
        getLineLength() {
            return this._lastCharOffset - this.firstCharOffset;
        }
        getActualLineContentBefore(offset) {
            const actualLineContent = this._actual.getLineContent();
            return actualLineContent.substring(0, this.firstCharOffset + offset);
        }
        getTokenCount() {
            return this._lastTokenIndex - this._firstTokenIndex;
        }
        findTokenIndexAtOffset(offset) {
            return this._actual.findTokenIndexAtOffset(offset + this.firstCharOffset) - this._firstTokenIndex;
        }
        getStandardTokenType(tokenIndex) {
            return this._actual.getStandardTokenType(tokenIndex + this._firstTokenIndex);
        }
        toIViewLineTokens() {
            return this._actual.sliceAndInflate(this.firstCharOffset, this._lastCharOffset, 0);
        }
    }
    exports.ScopedLineTokens = ScopedLineTokens;
    function ignoreBracketsInToken(standardTokenType) {
        return (standardTokenType & 3 /* IgnoreBracketsInTokens.value */) !== 0;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[76/*vs/editor/common/cursorCommon*/], __M([1/*require*/,0/*exports*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/,23/*vs/editor/common/core/selection*/,169/*vs/editor/common/languages/supports*/,94/*vs/editor/common/core/cursorColumns*/,230/*vs/editor/common/core/indentation*/]), function (require, exports, position_1, range_1, selection_1, supports_1, cursorColumns_1, indentation_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.EditOperationResult = exports.SingleCursorState = exports.PartialViewCursorState = exports.PartialModelCursorState = exports.CursorState = exports.CursorConfiguration = void 0;
    exports.isQuote = isQuote;
    const autoCloseAlways = () => true;
    const autoCloseNever = () => false;
    const autoCloseBeforeWhitespace = (chr) => (chr === ' ' || chr === '\t');
    class CursorConfiguration {
        static shouldRecreate(e) {
            return (e.hasChanged(146 /* EditorOption.layoutInfo */)
                || e.hasChanged(132 /* EditorOption.wordSeparators */)
                || e.hasChanged(37 /* EditorOption.emptySelectionClipboard */)
                || e.hasChanged(77 /* EditorOption.multiCursorMergeOverlapping */)
                || e.hasChanged(79 /* EditorOption.multiCursorPaste */)
                || e.hasChanged(80 /* EditorOption.multiCursorLimit */)
                || e.hasChanged(6 /* EditorOption.autoClosingBrackets */)
                || e.hasChanged(7 /* EditorOption.autoClosingComments */)
                || e.hasChanged(11 /* EditorOption.autoClosingQuotes */)
                || e.hasChanged(9 /* EditorOption.autoClosingDelete */)
                || e.hasChanged(10 /* EditorOption.autoClosingOvertype */)
                || e.hasChanged(14 /* EditorOption.autoSurround */)
                || e.hasChanged(129 /* EditorOption.useTabStops */)
                || e.hasChanged(50 /* EditorOption.fontInfo */)
                || e.hasChanged(92 /* EditorOption.readOnly */)
                || e.hasChanged(131 /* EditorOption.wordSegmenterLocales */));
        }
        constructor(languageId, modelOptions, configuration, languageConfigurationService) {
            this.languageConfigurationService = languageConfigurationService;
            this._cursorMoveConfigurationBrand = undefined;
            this._languageId = languageId;
            const options = configuration.options;
            const layoutInfo = options.get(146 /* EditorOption.layoutInfo */);
            const fontInfo = options.get(50 /* EditorOption.fontInfo */);
            this.readOnly = options.get(92 /* EditorOption.readOnly */);
            this.tabSize = modelOptions.tabSize;
            this.indentSize = modelOptions.indentSize;
            this.insertSpaces = modelOptions.insertSpaces;
            this.stickyTabStops = options.get(117 /* EditorOption.stickyTabStops */);
            this.lineHeight = fontInfo.lineHeight;
            this.typicalHalfwidthCharacterWidth = fontInfo.typicalHalfwidthCharacterWidth;
            this.pageSize = Math.max(1, Math.floor(layoutInfo.height / this.lineHeight) - 2);
            this.useTabStops = options.get(129 /* EditorOption.useTabStops */);
            this.wordSeparators = options.get(132 /* EditorOption.wordSeparators */);
            this.emptySelectionClipboard = options.get(37 /* EditorOption.emptySelectionClipboard */);
            this.copyWithSyntaxHighlighting = options.get(25 /* EditorOption.copyWithSyntaxHighlighting */);
            this.multiCursorMergeOverlapping = options.get(77 /* EditorOption.multiCursorMergeOverlapping */);
            this.multiCursorPaste = options.get(79 /* EditorOption.multiCursorPaste */);
            this.multiCursorLimit = options.get(80 /* EditorOption.multiCursorLimit */);
            this.autoClosingBrackets = options.get(6 /* EditorOption.autoClosingBrackets */);
            this.autoClosingComments = options.get(7 /* EditorOption.autoClosingComments */);
            this.autoClosingQuotes = options.get(11 /* EditorOption.autoClosingQuotes */);
            this.autoClosingDelete = options.get(9 /* EditorOption.autoClosingDelete */);
            this.autoClosingOvertype = options.get(10 /* EditorOption.autoClosingOvertype */);
            this.autoSurround = options.get(14 /* EditorOption.autoSurround */);
            this.autoIndent = options.get(12 /* EditorOption.autoIndent */);
            this.wordSegmenterLocales = options.get(131 /* EditorOption.wordSegmenterLocales */);
            this.surroundingPairs = {};
            this._electricChars = null;
            this.shouldAutoCloseBefore = {
                quote: this._getShouldAutoClose(languageId, this.autoClosingQuotes, true),
                comment: this._getShouldAutoClose(languageId, this.autoClosingComments, false),
                bracket: this._getShouldAutoClose(languageId, this.autoClosingBrackets, false),
            };
            this.autoClosingPairs = this.languageConfigurationService.getLanguageConfiguration(languageId).getAutoClosingPairs();
            const surroundingPairs = this.languageConfigurationService.getLanguageConfiguration(languageId).getSurroundingPairs();
            if (surroundingPairs) {
                for (const pair of surroundingPairs) {
                    this.surroundingPairs[pair.open] = pair.close;
                }
            }
            const commentsConfiguration = this.languageConfigurationService.getLanguageConfiguration(languageId).comments;
            this.blockCommentStartToken = commentsConfiguration?.blockCommentStartToken ?? null;
        }
        get electricChars() {
            if (!this._electricChars) {
                this._electricChars = {};
                const electricChars = this.languageConfigurationService.getLanguageConfiguration(this._languageId).electricCharacter?.getElectricCharacters();
                if (electricChars) {
                    for (const char of electricChars) {
                        this._electricChars[char] = true;
                    }
                }
            }
            return this._electricChars;
        }
        /**
         * Should return opening bracket type to match indentation with
         */
        onElectricCharacter(character, context, column) {
            const scopedLineTokens = (0, supports_1.createScopedLineTokens)(context, column - 1);
            const electricCharacterSupport = this.languageConfigurationService.getLanguageConfiguration(scopedLineTokens.languageId).electricCharacter;
            if (!electricCharacterSupport) {
                return null;
            }
            return electricCharacterSupport.onElectricCharacter(character, scopedLineTokens, column - scopedLineTokens.firstCharOffset);
        }
        normalizeIndentation(str) {
            return (0, indentation_1.normalizeIndentation)(str, this.indentSize, this.insertSpaces);
        }
        _getShouldAutoClose(languageId, autoCloseConfig, forQuotes) {
            switch (autoCloseConfig) {
                case 'beforeWhitespace':
                    return autoCloseBeforeWhitespace;
                case 'languageDefined':
                    return this._getLanguageDefinedShouldAutoClose(languageId, forQuotes);
                case 'always':
                    return autoCloseAlways;
                case 'never':
                    return autoCloseNever;
            }
        }
        _getLanguageDefinedShouldAutoClose(languageId, forQuotes) {
            const autoCloseBeforeSet = this.languageConfigurationService.getLanguageConfiguration(languageId).getAutoCloseBeforeSet(forQuotes);
            return c => autoCloseBeforeSet.indexOf(c) !== -1;
        }
        /**
         * Returns a visible column from a column.
         * @see {@link CursorColumns}
         */
        visibleColumnFromColumn(model, position) {
            return cursorColumns_1.CursorColumns.visibleColumnFromColumn(model.getLineContent(position.lineNumber), position.column, this.tabSize);
        }
        /**
         * Returns a visible column from a column.
         * @see {@link CursorColumns}
         */
        columnFromVisibleColumn(model, lineNumber, visibleColumn) {
            const result = cursorColumns_1.CursorColumns.columnFromVisibleColumn(model.getLineContent(lineNumber), visibleColumn, this.tabSize);
            const minColumn = model.getLineMinColumn(lineNumber);
            if (result < minColumn) {
                return minColumn;
            }
            const maxColumn = model.getLineMaxColumn(lineNumber);
            if (result > maxColumn) {
                return maxColumn;
            }
            return result;
        }
    }
    exports.CursorConfiguration = CursorConfiguration;
    class CursorState {
        static fromModelState(modelState) {
            return new PartialModelCursorState(modelState);
        }
        static fromViewState(viewState) {
            return new PartialViewCursorState(viewState);
        }
        static fromModelSelection(modelSelection) {
            const selection = selection_1.Selection.liftSelection(modelSelection);
            const modelState = new SingleCursorState(range_1.Range.fromPositions(selection.getSelectionStart()), 0 /* SelectionStartKind.Simple */, 0, selection.getPosition(), 0);
            return CursorState.fromModelState(modelState);
        }
        static fromModelSelections(modelSelections) {
            const states = [];
            for (let i = 0, len = modelSelections.length; i < len; i++) {
                states[i] = this.fromModelSelection(modelSelections[i]);
            }
            return states;
        }
        constructor(modelState, viewState) {
            this._cursorStateBrand = undefined;
            this.modelState = modelState;
            this.viewState = viewState;
        }
        equals(other) {
            return (this.viewState.equals(other.viewState) && this.modelState.equals(other.modelState));
        }
    }
    exports.CursorState = CursorState;
    class PartialModelCursorState {
        constructor(modelState) {
            this.modelState = modelState;
            this.viewState = null;
        }
    }
    exports.PartialModelCursorState = PartialModelCursorState;
    class PartialViewCursorState {
        constructor(viewState) {
            this.modelState = null;
            this.viewState = viewState;
        }
    }
    exports.PartialViewCursorState = PartialViewCursorState;
    /**
     * Represents the cursor state on either the model or on the view model.
     */
    class SingleCursorState {
        constructor(selectionStart, selectionStartKind, selectionStartLeftoverVisibleColumns, position, leftoverVisibleColumns) {
            this.selectionStart = selectionStart;
            this.selectionStartKind = selectionStartKind;
            this.selectionStartLeftoverVisibleColumns = selectionStartLeftoverVisibleColumns;
            this.position = position;
            this.leftoverVisibleColumns = leftoverVisibleColumns;
            this._singleCursorStateBrand = undefined;
            this.selection = SingleCursorState._computeSelection(this.selectionStart, this.position);
        }
        equals(other) {
            return (this.selectionStartLeftoverVisibleColumns === other.selectionStartLeftoverVisibleColumns
                && this.leftoverVisibleColumns === other.leftoverVisibleColumns
                && this.selectionStartKind === other.selectionStartKind
                && this.position.equals(other.position)
                && this.selectionStart.equalsRange(other.selectionStart));
        }
        hasSelection() {
            return (!this.selection.isEmpty() || !this.selectionStart.isEmpty());
        }
        move(inSelectionMode, lineNumber, column, leftoverVisibleColumns) {
            if (inSelectionMode) {
                // move just position
                return new SingleCursorState(this.selectionStart, this.selectionStartKind, this.selectionStartLeftoverVisibleColumns, new position_1.Position(lineNumber, column), leftoverVisibleColumns);
            }
            else {
                // move everything
                return new SingleCursorState(new range_1.Range(lineNumber, column, lineNumber, column), 0 /* SelectionStartKind.Simple */, leftoverVisibleColumns, new position_1.Position(lineNumber, column), leftoverVisibleColumns);
            }
        }
        static _computeSelection(selectionStart, position) {
            if (selectionStart.isEmpty() || !position.isBeforeOrEqual(selectionStart.getStartPosition())) {
                return selection_1.Selection.fromPositions(selectionStart.getStartPosition(), position);
            }
            else {
                return selection_1.Selection.fromPositions(selectionStart.getEndPosition(), position);
            }
        }
    }
    exports.SingleCursorState = SingleCursorState;
    class EditOperationResult {
        constructor(type, commands, opts) {
            this._editOperationResultBrand = undefined;
            this.type = type;
            this.commands = commands;
            this.shouldPushStackElementBefore = opts.shouldPushStackElementBefore;
            this.shouldPushStackElementAfter = opts.shouldPushStackElementAfter;
        }
    }
    exports.EditOperationResult = EditOperationResult;
    function isQuote(ch) {
        return (ch === '\'' || ch === '"' || ch === '`');
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[565/*vs/editor/common/cursor/cursorColumnSelection*/], __M([1/*require*/,0/*exports*/,76/*vs/editor/common/cursorCommon*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/]), function (require, exports, cursorCommon_1, position_1, range_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ColumnSelection = void 0;
    class ColumnSelection {
        static columnSelect(config, model, fromLineNumber, fromVisibleColumn, toLineNumber, toVisibleColumn) {
            const lineCount = Math.abs(toLineNumber - fromLineNumber) + 1;
            const reversed = (fromLineNumber > toLineNumber);
            const isRTL = (fromVisibleColumn > toVisibleColumn);
            const isLTR = (fromVisibleColumn < toVisibleColumn);
            const result = [];
            // console.log(`fromVisibleColumn: ${fromVisibleColumn}, toVisibleColumn: ${toVisibleColumn}`);
            for (let i = 0; i < lineCount; i++) {
                const lineNumber = fromLineNumber + (reversed ? -i : i);
                const startColumn = config.columnFromVisibleColumn(model, lineNumber, fromVisibleColumn);
                const endColumn = config.columnFromVisibleColumn(model, lineNumber, toVisibleColumn);
                const visibleStartColumn = config.visibleColumnFromColumn(model, new position_1.Position(lineNumber, startColumn));
                const visibleEndColumn = config.visibleColumnFromColumn(model, new position_1.Position(lineNumber, endColumn));
                // console.log(`lineNumber: ${lineNumber}: visibleStartColumn: ${visibleStartColumn}, visibleEndColumn: ${visibleEndColumn}`);
                if (isLTR) {
                    if (visibleStartColumn > toVisibleColumn) {
                        continue;
                    }
                    if (visibleEndColumn < fromVisibleColumn) {
                        continue;
                    }
                }
                if (isRTL) {
                    if (visibleEndColumn > fromVisibleColumn) {
                        continue;
                    }
                    if (visibleStartColumn < toVisibleColumn) {
                        continue;
                    }
                }
                result.push(new cursorCommon_1.SingleCursorState(new range_1.Range(lineNumber, startColumn, lineNumber, startColumn), 0 /* SelectionStartKind.Simple */, 0, new position_1.Position(lineNumber, endColumn), 0));
            }
            if (result.length === 0) {
                // We are after all the lines, so add cursor at the end of each line
                for (let i = 0; i < lineCount; i++) {
                    const lineNumber = fromLineNumber + (reversed ? -i : i);
                    const maxColumn = model.getLineMaxColumn(lineNumber);
                    result.push(new cursorCommon_1.SingleCursorState(new range_1.Range(lineNumber, maxColumn, lineNumber, maxColumn), 0 /* SelectionStartKind.Simple */, 0, new position_1.Position(lineNumber, maxColumn), 0));
                }
            }
            return {
                viewStates: result,
                reversed: reversed,
                fromLineNumber: fromLineNumber,
                fromVisualColumn: fromVisibleColumn,
                toLineNumber: toLineNumber,
                toVisualColumn: toVisibleColumn
            };
        }
        static columnSelectLeft(config, model, prevColumnSelectData) {
            let toViewVisualColumn = prevColumnSelectData.toViewVisualColumn;
            if (toViewVisualColumn > 0) {
                toViewVisualColumn--;
            }
            return ColumnSelection.columnSelect(config, model, prevColumnSelectData.fromViewLineNumber, prevColumnSelectData.fromViewVisualColumn, prevColumnSelectData.toViewLineNumber, toViewVisualColumn);
        }
        static columnSelectRight(config, model, prevColumnSelectData) {
            let maxVisualViewColumn = 0;
            const minViewLineNumber = Math.min(prevColumnSelectData.fromViewLineNumber, prevColumnSelectData.toViewLineNumber);
            const maxViewLineNumber = Math.max(prevColumnSelectData.fromViewLineNumber, prevColumnSelectData.toViewLineNumber);
            for (let lineNumber = minViewLineNumber; lineNumber <= maxViewLineNumber; lineNumber++) {
                const lineMaxViewColumn = model.getLineMaxColumn(lineNumber);
                const lineMaxVisualViewColumn = config.visibleColumnFromColumn(model, new position_1.Position(lineNumber, lineMaxViewColumn));
                maxVisualViewColumn = Math.max(maxVisualViewColumn, lineMaxVisualViewColumn);
            }
            let toViewVisualColumn = prevColumnSelectData.toViewVisualColumn;
            if (toViewVisualColumn < maxVisualViewColumn) {
                toViewVisualColumn++;
            }
            return this.columnSelect(config, model, prevColumnSelectData.fromViewLineNumber, prevColumnSelectData.fromViewVisualColumn, prevColumnSelectData.toViewLineNumber, toViewVisualColumn);
        }
        static columnSelectUp(config, model, prevColumnSelectData, isPaged) {
            const linesCount = isPaged ? config.pageSize : 1;
            const toViewLineNumber = Math.max(1, prevColumnSelectData.toViewLineNumber - linesCount);
            return this.columnSelect(config, model, prevColumnSelectData.fromViewLineNumber, prevColumnSelectData.fromViewVisualColumn, toViewLineNumber, prevColumnSelectData.toViewVisualColumn);
        }
        static columnSelectDown(config, model, prevColumnSelectData, isPaged) {
            const linesCount = isPaged ? config.pageSize : 1;
            const toViewLineNumber = Math.min(model.getLineCount(), prevColumnSelectData.toViewLineNumber + linesCount);
            return this.columnSelect(config, model, prevColumnSelectData.fromViewLineNumber, prevColumnSelectData.fromViewVisualColumn, toViewLineNumber, prevColumnSelectData.toViewVisualColumn);
        }
    }
    exports.ColumnSelection = ColumnSelection;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[233/*vs/editor/common/cursor/cursorMoveOperations*/], __M([1/*require*/,0/*exports*/,11/*vs/base/common/strings*/,94/*vs/editor/common/core/cursorColumns*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/,313/*vs/editor/common/cursor/cursorAtomicMoveOperations*/,76/*vs/editor/common/cursorCommon*/]), function (require, exports, strings, cursorColumns_1, position_1, range_1, cursorAtomicMoveOperations_1, cursorCommon_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MoveOperations = exports.CursorPosition = void 0;
    class CursorPosition {
        constructor(lineNumber, column, leftoverVisibleColumns) {
            this._cursorPositionBrand = undefined;
            this.lineNumber = lineNumber;
            this.column = column;
            this.leftoverVisibleColumns = leftoverVisibleColumns;
        }
    }
    exports.CursorPosition = CursorPosition;
    class MoveOperations {
        static leftPosition(model, position) {
            if (position.column > model.getLineMinColumn(position.lineNumber)) {
                return position.delta(undefined, -strings.prevCharLength(model.getLineContent(position.lineNumber), position.column - 1));
            }
            else if (position.lineNumber > 1) {
                const newLineNumber = position.lineNumber - 1;
                return new position_1.Position(newLineNumber, model.getLineMaxColumn(newLineNumber));
            }
            else {
                return position;
            }
        }
        static leftPositionAtomicSoftTabs(model, position, tabSize) {
            if (position.column <= model.getLineIndentColumn(position.lineNumber)) {
                const minColumn = model.getLineMinColumn(position.lineNumber);
                const lineContent = model.getLineContent(position.lineNumber);
                const newPosition = cursorAtomicMoveOperations_1.AtomicTabMoveOperations.atomicPosition(lineContent, position.column - 1, tabSize, 0 /* Direction.Left */);
                if (newPosition !== -1 && newPosition + 1 >= minColumn) {
                    return new position_1.Position(position.lineNumber, newPosition + 1);
                }
            }
            return this.leftPosition(model, position);
        }
        static left(config, model, position) {
            const pos = config.stickyTabStops
                ? MoveOperations.leftPositionAtomicSoftTabs(model, position, config.tabSize)
                : MoveOperations.leftPosition(model, position);
            return new CursorPosition(pos.lineNumber, pos.column, 0);
        }
        /**
         * @param noOfColumns Must be either `1`
         * or `Math.round(viewModel.getLineContent(viewLineNumber).length / 2)` (for half lines).
        */
        static moveLeft(config, model, cursor, inSelectionMode, noOfColumns) {
            let lineNumber, column;
            if (cursor.hasSelection() && !inSelectionMode) {
                // If the user has a selection and does not want to extend it,
                // put the cursor at the beginning of the selection.
                lineNumber = cursor.selection.startLineNumber;
                column = cursor.selection.startColumn;
            }
            else {
                // This has no effect if noOfColumns === 1.
                // It is ok to do so in the half-line scenario.
                const pos = cursor.position.delta(undefined, -(noOfColumns - 1));
                // We clip the position before normalization, as normalization is not defined
                // for possibly negative columns.
                const normalizedPos = model.normalizePosition(MoveOperations.clipPositionColumn(pos, model), 0 /* PositionAffinity.Left */);
                const p = MoveOperations.left(config, model, normalizedPos);
                lineNumber = p.lineNumber;
                column = p.column;
            }
            return cursor.move(inSelectionMode, lineNumber, column, 0);
        }
        /**
         * Adjusts the column so that it is within min/max of the line.
        */
        static clipPositionColumn(position, model) {
            return new position_1.Position(position.lineNumber, MoveOperations.clipRange(position.column, model.getLineMinColumn(position.lineNumber), model.getLineMaxColumn(position.lineNumber)));
        }
        static clipRange(value, min, max) {
            if (value < min) {
                return min;
            }
            if (value > max) {
                return max;
            }
            return value;
        }
        static rightPosition(model, lineNumber, column) {
            if (column < model.getLineMaxColumn(lineNumber)) {
                column = column + strings.nextCharLength(model.getLineContent(lineNumber), column - 1);
            }
            else if (lineNumber < model.getLineCount()) {
                lineNumber = lineNumber + 1;
                column = model.getLineMinColumn(lineNumber);
            }
            return new position_1.Position(lineNumber, column);
        }
        static rightPositionAtomicSoftTabs(model, lineNumber, column, tabSize, indentSize) {
            if (column < model.getLineIndentColumn(lineNumber)) {
                const lineContent = model.getLineContent(lineNumber);
                const newPosition = cursorAtomicMoveOperations_1.AtomicTabMoveOperations.atomicPosition(lineContent, column - 1, tabSize, 1 /* Direction.Right */);
                if (newPosition !== -1) {
                    return new position_1.Position(lineNumber, newPosition + 1);
                }
            }
            return this.rightPosition(model, lineNumber, column);
        }
        static right(config, model, position) {
            const pos = config.stickyTabStops
                ? MoveOperations.rightPositionAtomicSoftTabs(model, position.lineNumber, position.column, config.tabSize, config.indentSize)
                : MoveOperations.rightPosition(model, position.lineNumber, position.column);
            return new CursorPosition(pos.lineNumber, pos.column, 0);
        }
        static moveRight(config, model, cursor, inSelectionMode, noOfColumns) {
            let lineNumber, column;
            if (cursor.hasSelection() && !inSelectionMode) {
                // If we are in selection mode, move right without selection cancels selection and puts cursor at the end of the selection
                lineNumber = cursor.selection.endLineNumber;
                column = cursor.selection.endColumn;
            }
            else {
                const pos = cursor.position.delta(undefined, noOfColumns - 1);
                const normalizedPos = model.normalizePosition(MoveOperations.clipPositionColumn(pos, model), 1 /* PositionAffinity.Right */);
                const r = MoveOperations.right(config, model, normalizedPos);
                lineNumber = r.lineNumber;
                column = r.column;
            }
            return cursor.move(inSelectionMode, lineNumber, column, 0);
        }
        static vertical(config, model, lineNumber, column, leftoverVisibleColumns, newLineNumber, allowMoveOnEdgeLine, normalizationAffinity) {
            const currentVisibleColumn = cursorColumns_1.CursorColumns.visibleColumnFromColumn(model.getLineContent(lineNumber), column, config.tabSize) + leftoverVisibleColumns;
            const lineCount = model.getLineCount();
            const wasOnFirstPosition = (lineNumber === 1 && column === 1);
            const wasOnLastPosition = (lineNumber === lineCount && column === model.getLineMaxColumn(lineNumber));
            const wasAtEdgePosition = (newLineNumber < lineNumber ? wasOnFirstPosition : wasOnLastPosition);
            lineNumber = newLineNumber;
            if (lineNumber < 1) {
                lineNumber = 1;
                if (allowMoveOnEdgeLine) {
                    column = model.getLineMinColumn(lineNumber);
                }
                else {
                    column = Math.min(model.getLineMaxColumn(lineNumber), column);
                }
            }
            else if (lineNumber > lineCount) {
                lineNumber = lineCount;
                if (allowMoveOnEdgeLine) {
                    column = model.getLineMaxColumn(lineNumber);
                }
                else {
                    column = Math.min(model.getLineMaxColumn(lineNumber), column);
                }
            }
            else {
                column = config.columnFromVisibleColumn(model, lineNumber, currentVisibleColumn);
            }
            if (wasAtEdgePosition) {
                leftoverVisibleColumns = 0;
            }
            else {
                leftoverVisibleColumns = currentVisibleColumn - cursorColumns_1.CursorColumns.visibleColumnFromColumn(model.getLineContent(lineNumber), column, config.tabSize);
            }
            if (normalizationAffinity !== undefined) {
                const position = new position_1.Position(lineNumber, column);
                const newPosition = model.normalizePosition(position, normalizationAffinity);
                leftoverVisibleColumns = leftoverVisibleColumns + (column - newPosition.column);
                lineNumber = newPosition.lineNumber;
                column = newPosition.column;
            }
            return new CursorPosition(lineNumber, column, leftoverVisibleColumns);
        }
        static down(config, model, lineNumber, column, leftoverVisibleColumns, count, allowMoveOnLastLine) {
            return this.vertical(config, model, lineNumber, column, leftoverVisibleColumns, lineNumber + count, allowMoveOnLastLine, 4 /* PositionAffinity.RightOfInjectedText */);
        }
        static moveDown(config, model, cursor, inSelectionMode, linesCount) {
            let lineNumber, column;
            if (cursor.hasSelection() && !inSelectionMode) {
                // If we are in selection mode, move down acts relative to the end of selection
                lineNumber = cursor.selection.endLineNumber;
                column = cursor.selection.endColumn;
            }
            else {
                lineNumber = cursor.position.lineNumber;
                column = cursor.position.column;
            }
            let i = 0;
            let r;
            do {
                r = MoveOperations.down(config, model, lineNumber + i, column, cursor.leftoverVisibleColumns, linesCount, true);
                const np = model.normalizePosition(new position_1.Position(r.lineNumber, r.column), 2 /* PositionAffinity.None */);
                if (np.lineNumber > lineNumber) {
                    break;
                }
            } while (i++ < 10 && lineNumber + i < model.getLineCount());
            return cursor.move(inSelectionMode, r.lineNumber, r.column, r.leftoverVisibleColumns);
        }
        static translateDown(config, model, cursor) {
            const selection = cursor.selection;
            const selectionStart = MoveOperations.down(config, model, selection.selectionStartLineNumber, selection.selectionStartColumn, cursor.selectionStartLeftoverVisibleColumns, 1, false);
            const position = MoveOperations.down(config, model, selection.positionLineNumber, selection.positionColumn, cursor.leftoverVisibleColumns, 1, false);
            return new cursorCommon_1.SingleCursorState(new range_1.Range(selectionStart.lineNumber, selectionStart.column, selectionStart.lineNumber, selectionStart.column), 0 /* SelectionStartKind.Simple */, selectionStart.leftoverVisibleColumns, new position_1.Position(position.lineNumber, position.column), position.leftoverVisibleColumns);
        }
        static up(config, model, lineNumber, column, leftoverVisibleColumns, count, allowMoveOnFirstLine) {
            return this.vertical(config, model, lineNumber, column, leftoverVisibleColumns, lineNumber - count, allowMoveOnFirstLine, 3 /* PositionAffinity.LeftOfInjectedText */);
        }
        static moveUp(config, model, cursor, inSelectionMode, linesCount) {
            let lineNumber, column;
            if (cursor.hasSelection() && !inSelectionMode) {
                // If we are in selection mode, move up acts relative to the beginning of selection
                lineNumber = cursor.selection.startLineNumber;
                column = cursor.selection.startColumn;
            }
            else {
                lineNumber = cursor.position.lineNumber;
                column = cursor.position.column;
            }
            const r = MoveOperations.up(config, model, lineNumber, column, cursor.leftoverVisibleColumns, linesCount, true);
            return cursor.move(inSelectionMode, r.lineNumber, r.column, r.leftoverVisibleColumns);
        }
        static translateUp(config, model, cursor) {
            const selection = cursor.selection;
            const selectionStart = MoveOperations.up(config, model, selection.selectionStartLineNumber, selection.selectionStartColumn, cursor.selectionStartLeftoverVisibleColumns, 1, false);
            const position = MoveOperations.up(config, model, selection.positionLineNumber, selection.positionColumn, cursor.leftoverVisibleColumns, 1, false);
            return new cursorCommon_1.SingleCursorState(new range_1.Range(selectionStart.lineNumber, selectionStart.column, selectionStart.lineNumber, selectionStart.column), 0 /* SelectionStartKind.Simple */, selectionStart.leftoverVisibleColumns, new position_1.Position(position.lineNumber, position.column), position.leftoverVisibleColumns);
        }
        static _isBlankLine(model, lineNumber) {
            if (model.getLineFirstNonWhitespaceColumn(lineNumber) === 0) {
                // empty or contains only whitespace
                return true;
            }
            return false;
        }
        static moveToPrevBlankLine(config, model, cursor, inSelectionMode) {
            let lineNumber = cursor.position.lineNumber;
            // If our current line is blank, move to the previous non-blank line
            while (lineNumber > 1 && this._isBlankLine(model, lineNumber)) {
                lineNumber--;
            }
            // Find the previous blank line
            while (lineNumber > 1 && !this._isBlankLine(model, lineNumber)) {
                lineNumber--;
            }
            return cursor.move(inSelectionMode, lineNumber, model.getLineMinColumn(lineNumber), 0);
        }
        static moveToNextBlankLine(config, model, cursor, inSelectionMode) {
            const lineCount = model.getLineCount();
            let lineNumber = cursor.position.lineNumber;
            // If our current line is blank, move to the next non-blank line
            while (lineNumber < lineCount && this._isBlankLine(model, lineNumber)) {
                lineNumber++;
            }
            // Find the next blank line
            while (lineNumber < lineCount && !this._isBlankLine(model, lineNumber)) {
                lineNumber++;
            }
            return cursor.move(inSelectionMode, lineNumber, model.getLineMinColumn(lineNumber), 0);
        }
        static moveToBeginningOfLine(config, model, cursor, inSelectionMode) {
            const lineNumber = cursor.position.lineNumber;
            const minColumn = model.getLineMinColumn(lineNumber);
            const firstNonBlankColumn = model.getLineFirstNonWhitespaceColumn(lineNumber) || minColumn;
            let column;
            const relevantColumnNumber = cursor.position.column;
            if (relevantColumnNumber === firstNonBlankColumn) {
                column = minColumn;
            }
            else {
                column = firstNonBlankColumn;
            }
            return cursor.move(inSelectionMode, lineNumber, column, 0);
        }
        static moveToEndOfLine(config, model, cursor, inSelectionMode, sticky) {
            const lineNumber = cursor.position.lineNumber;
            const maxColumn = model.getLineMaxColumn(lineNumber);
            return cursor.move(inSelectionMode, lineNumber, maxColumn, sticky ? 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */ - maxColumn : 0);
        }
        static moveToBeginningOfBuffer(config, model, cursor, inSelectionMode) {
            return cursor.move(inSelectionMode, 1, 1, 0);
        }
        static moveToEndOfBuffer(config, model, cursor, inSelectionMode) {
            const lastLineNumber = model.getLineCount();
            const lastColumn = model.getLineMaxColumn(lastLineNumber);
            return cursor.move(inSelectionMode, lastLineNumber, lastColumn, 0);
        }
    }
    exports.MoveOperations = MoveOperations;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[234/*vs/editor/common/cursor/cursorDeleteOperations*/], __M([1/*require*/,0/*exports*/,11/*vs/base/common/strings*/,146/*vs/editor/common/commands/replaceCommand*/,76/*vs/editor/common/cursorCommon*/,94/*vs/editor/common/core/cursorColumns*/,233/*vs/editor/common/cursor/cursorMoveOperations*/,4/*vs/editor/common/core/range*/,9/*vs/editor/common/core/position*/]), function (require, exports, strings, replaceCommand_1, cursorCommon_1, cursorColumns_1, cursorMoveOperations_1, range_1, position_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DeleteOperations = void 0;
    class DeleteOperations {
        static deleteRight(prevEditOperationType, config, model, selections) {
            const commands = [];
            let shouldPushStackElementBefore = (prevEditOperationType !== 3 /* EditOperationType.DeletingRight */);
            for (let i = 0, len = selections.length; i < len; i++) {
                const selection = selections[i];
                let deleteSelection = selection;
                if (deleteSelection.isEmpty()) {
                    const position = selection.getPosition();
                    const rightOfPosition = cursorMoveOperations_1.MoveOperations.right(config, model, position);
                    deleteSelection = new range_1.Range(rightOfPosition.lineNumber, rightOfPosition.column, position.lineNumber, position.column);
                }
                if (deleteSelection.isEmpty()) {
                    // Probably at end of file => ignore
                    commands[i] = null;
                    continue;
                }
                if (deleteSelection.startLineNumber !== deleteSelection.endLineNumber) {
                    shouldPushStackElementBefore = true;
                }
                commands[i] = new replaceCommand_1.ReplaceCommand(deleteSelection, '');
            }
            return [shouldPushStackElementBefore, commands];
        }
        static isAutoClosingPairDelete(autoClosingDelete, autoClosingBrackets, autoClosingQuotes, autoClosingPairsOpen, model, selections, autoClosedCharacters) {
            if (autoClosingBrackets === 'never' && autoClosingQuotes === 'never') {
                return false;
            }
            if (autoClosingDelete === 'never') {
                return false;
            }
            for (let i = 0, len = selections.length; i < len; i++) {
                const selection = selections[i];
                const position = selection.getPosition();
                if (!selection.isEmpty()) {
                    return false;
                }
                const lineText = model.getLineContent(position.lineNumber);
                if (position.column < 2 || position.column >= lineText.length + 1) {
                    return false;
                }
                const character = lineText.charAt(position.column - 2);
                const autoClosingPairCandidates = autoClosingPairsOpen.get(character);
                if (!autoClosingPairCandidates) {
                    return false;
                }
                if ((0, cursorCommon_1.isQuote)(character)) {
                    if (autoClosingQuotes === 'never') {
                        return false;
                    }
                }
                else {
                    if (autoClosingBrackets === 'never') {
                        return false;
                    }
                }
                const afterCharacter = lineText.charAt(position.column - 1);
                let foundAutoClosingPair = false;
                for (const autoClosingPairCandidate of autoClosingPairCandidates) {
                    if (autoClosingPairCandidate.open === character && autoClosingPairCandidate.close === afterCharacter) {
                        foundAutoClosingPair = true;
                    }
                }
                if (!foundAutoClosingPair) {
                    return false;
                }
                // Must delete the pair only if it was automatically inserted by the editor
                if (autoClosingDelete === 'auto') {
                    let found = false;
                    for (let j = 0, lenJ = autoClosedCharacters.length; j < lenJ; j++) {
                        const autoClosedCharacter = autoClosedCharacters[j];
                        if (position.lineNumber === autoClosedCharacter.startLineNumber && position.column === autoClosedCharacter.startColumn) {
                            found = true;
                            break;
                        }
                    }
                    if (!found) {
                        return false;
                    }
                }
            }
            return true;
        }
        static _runAutoClosingPairDelete(config, model, selections) {
            const commands = [];
            for (let i = 0, len = selections.length; i < len; i++) {
                const position = selections[i].getPosition();
                const deleteSelection = new range_1.Range(position.lineNumber, position.column - 1, position.lineNumber, position.column + 1);
                commands[i] = new replaceCommand_1.ReplaceCommand(deleteSelection, '');
            }
            return [true, commands];
        }
        static deleteLeft(prevEditOperationType, config, model, selections, autoClosedCharacters) {
            if (this.isAutoClosingPairDelete(config.autoClosingDelete, config.autoClosingBrackets, config.autoClosingQuotes, config.autoClosingPairs.autoClosingPairsOpenByEnd, model, selections, autoClosedCharacters)) {
                return this._runAutoClosingPairDelete(config, model, selections);
            }
            const commands = [];
            let shouldPushStackElementBefore = (prevEditOperationType !== 2 /* EditOperationType.DeletingLeft */);
            for (let i = 0, len = selections.length; i < len; i++) {
                const deleteRange = DeleteOperations.getDeleteRange(selections[i], model, config);
                // Ignore empty delete ranges, as they have no effect
                // They happen if the cursor is at the beginning of the file.
                if (deleteRange.isEmpty()) {
                    commands[i] = null;
                    continue;
                }
                if (deleteRange.startLineNumber !== deleteRange.endLineNumber) {
                    shouldPushStackElementBefore = true;
                }
                commands[i] = new replaceCommand_1.ReplaceCommand(deleteRange, '');
            }
            return [shouldPushStackElementBefore, commands];
        }
        static getDeleteRange(selection, model, config) {
            if (!selection.isEmpty()) {
                return selection;
            }
            const position = selection.getPosition();
            // Unintend when using tab stops and cursor is within indentation
            if (config.useTabStops && position.column > 1) {
                const lineContent = model.getLineContent(position.lineNumber);
                const firstNonWhitespaceIndex = strings.firstNonWhitespaceIndex(lineContent);
                const lastIndentationColumn = (firstNonWhitespaceIndex === -1
                    ? /* entire string is whitespace */ lineContent.length + 1
                    : firstNonWhitespaceIndex + 1);
                if (position.column <= lastIndentationColumn) {
                    const fromVisibleColumn = config.visibleColumnFromColumn(model, position);
                    const toVisibleColumn = cursorColumns_1.CursorColumns.prevIndentTabStop(fromVisibleColumn, config.indentSize);
                    const toColumn = config.columnFromVisibleColumn(model, position.lineNumber, toVisibleColumn);
                    return new range_1.Range(position.lineNumber, toColumn, position.lineNumber, position.column);
                }
            }
            return range_1.Range.fromPositions(DeleteOperations.getPositionAfterDeleteLeft(position, model), position);
        }
        static getPositionAfterDeleteLeft(position, model) {
            if (position.column > 1) {
                // Convert 1-based columns to 0-based offsets and back.
                const idx = strings.getLeftDeleteOffset(position.column - 1, model.getLineContent(position.lineNumber));
                return position.with(undefined, idx + 1);
            }
            else if (position.lineNumber > 1) {
                const newLine = position.lineNumber - 1;
                return new position_1.Position(newLine, model.getLineMaxColumn(newLine));
            }
            else {
                return position;
            }
        }
        static cut(config, model, selections) {
            const commands = [];
            let lastCutRange = null;
            selections.sort((a, b) => position_1.Position.compare(a.getStartPosition(), b.getEndPosition()));
            for (let i = 0, len = selections.length; i < len; i++) {
                const selection = selections[i];
                if (selection.isEmpty()) {
                    if (config.emptySelectionClipboard) {
                        // This is a full line cut
                        const position = selection.getPosition();
                        let startLineNumber, startColumn, endLineNumber, endColumn;
                        if (position.lineNumber < model.getLineCount()) {
                            // Cutting a line in the middle of the model
                            startLineNumber = position.lineNumber;
                            startColumn = 1;
                            endLineNumber = position.lineNumber + 1;
                            endColumn = 1;
                        }
                        else if (position.lineNumber > 1 && lastCutRange?.endLineNumber !== position.lineNumber) {
                            // Cutting the last line & there are more than 1 lines in the model & a previous cut operation does not touch the current cut operation
                            startLineNumber = position.lineNumber - 1;
                            startColumn = model.getLineMaxColumn(position.lineNumber - 1);
                            endLineNumber = position.lineNumber;
                            endColumn = model.getLineMaxColumn(position.lineNumber);
                        }
                        else {
                            // Cutting the single line that the model contains
                            startLineNumber = position.lineNumber;
                            startColumn = 1;
                            endLineNumber = position.lineNumber;
                            endColumn = model.getLineMaxColumn(position.lineNumber);
                        }
                        const deleteSelection = new range_1.Range(startLineNumber, startColumn, endLineNumber, endColumn);
                        lastCutRange = deleteSelection;
                        if (!deleteSelection.isEmpty()) {
                            commands[i] = new replaceCommand_1.ReplaceCommand(deleteSelection, '');
                        }
                        else {
                            commands[i] = null;
                        }
                    }
                    else {
                        // Cannot cut empty selection
                        commands[i] = null;
                    }
                }
                else {
                    commands[i] = new replaceCommand_1.ReplaceCommand(selection, '');
                }
            }
            return new cursorCommon_1.EditOperationResult(0 /* EditOperationType.Other */, commands, {
                shouldPushStackElementBefore: true,
                shouldPushStackElementAfter: true
            });
        }
    }
    exports.DeleteOperations = DeleteOperations;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[199/*vs/editor/common/cursor/cursorWordOperations*/], __M([1/*require*/,0/*exports*/,11/*vs/base/common/strings*/,76/*vs/editor/common/cursorCommon*/,234/*vs/editor/common/cursor/cursorDeleteOperations*/,166/*vs/editor/common/core/wordCharacterClassifier*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/]), function (require, exports, strings, cursorCommon_1, cursorDeleteOperations_1, wordCharacterClassifier_1, position_1, range_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.WordPartOperations = exports.WordOperations = void 0;
    class WordOperations {
        static _createWord(lineContent, wordType, nextCharClass, start, end) {
            // console.log('WORD ==> ' + start + ' => ' + end + ':::: <<<' + lineContent.substring(start, end) + '>>>');
            return { start: start, end: end, wordType: wordType, nextCharClass: nextCharClass };
        }
        static _createIntlWord(intlWord, nextCharClass) {
            // console.log('INTL WORD ==> ' + intlWord.index + ' => ' + intlWord.index + intlWord.segment.length + ':::: <<<' + intlWord.segment + '>>>');
            return { start: intlWord.index, end: intlWord.index + intlWord.segment.length, wordType: 1 /* WordType.Regular */, nextCharClass: nextCharClass };
        }
        static _findPreviousWordOnLine(wordSeparators, model, position) {
            const lineContent = model.getLineContent(position.lineNumber);
            return this._doFindPreviousWordOnLine(lineContent, wordSeparators, position);
        }
        static _doFindPreviousWordOnLine(lineContent, wordSeparators, position) {
            let wordType = 0 /* WordType.None */;
            const previousIntlWord = wordSeparators.findPrevIntlWordBeforeOrAtOffset(lineContent, position.column - 2);
            for (let chIndex = position.column - 2; chIndex >= 0; chIndex--) {
                const chCode = lineContent.charCodeAt(chIndex);
                const chClass = wordSeparators.get(chCode);
                if (previousIntlWord && chIndex === previousIntlWord.index) {
                    return this._createIntlWord(previousIntlWord, chClass);
                }
                if (chClass === 0 /* WordCharacterClass.Regular */) {
                    if (wordType === 2 /* WordType.Separator */) {
                        return this._createWord(lineContent, wordType, chClass, chIndex + 1, this._findEndOfWord(lineContent, wordSeparators, wordType, chIndex + 1));
                    }
                    wordType = 1 /* WordType.Regular */;
                }
                else if (chClass === 2 /* WordCharacterClass.WordSeparator */) {
                    if (wordType === 1 /* WordType.Regular */) {
                        return this._createWord(lineContent, wordType, chClass, chIndex + 1, this._findEndOfWord(lineContent, wordSeparators, wordType, chIndex + 1));
                    }
                    wordType = 2 /* WordType.Separator */;
                }
                else if (chClass === 1 /* WordCharacterClass.Whitespace */) {
                    if (wordType !== 0 /* WordType.None */) {
                        return this._createWord(lineContent, wordType, chClass, chIndex + 1, this._findEndOfWord(lineContent, wordSeparators, wordType, chIndex + 1));
                    }
                }
            }
            if (wordType !== 0 /* WordType.None */) {
                return this._createWord(lineContent, wordType, 1 /* WordCharacterClass.Whitespace */, 0, this._findEndOfWord(lineContent, wordSeparators, wordType, 0));
            }
            return null;
        }
        static _findEndOfWord(lineContent, wordSeparators, wordType, startIndex) {
            const nextIntlWord = wordSeparators.findNextIntlWordAtOrAfterOffset(lineContent, startIndex);
            const len = lineContent.length;
            for (let chIndex = startIndex; chIndex < len; chIndex++) {
                const chCode = lineContent.charCodeAt(chIndex);
                const chClass = wordSeparators.get(chCode);
                if (nextIntlWord && chIndex === nextIntlWord.index + nextIntlWord.segment.length) {
                    return chIndex;
                }
                if (chClass === 1 /* WordCharacterClass.Whitespace */) {
                    return chIndex;
                }
                if (wordType === 1 /* WordType.Regular */ && chClass === 2 /* WordCharacterClass.WordSeparator */) {
                    return chIndex;
                }
                if (wordType === 2 /* WordType.Separator */ && chClass === 0 /* WordCharacterClass.Regular */) {
                    return chIndex;
                }
            }
            return len;
        }
        static _findNextWordOnLine(wordSeparators, model, position) {
            const lineContent = model.getLineContent(position.lineNumber);
            return this._doFindNextWordOnLine(lineContent, wordSeparators, position);
        }
        static _doFindNextWordOnLine(lineContent, wordSeparators, position) {
            let wordType = 0 /* WordType.None */;
            const len = lineContent.length;
            const nextIntlWord = wordSeparators.findNextIntlWordAtOrAfterOffset(lineContent, position.column - 1);
            for (let chIndex = position.column - 1; chIndex < len; chIndex++) {
                const chCode = lineContent.charCodeAt(chIndex);
                const chClass = wordSeparators.get(chCode);
                if (nextIntlWord && chIndex === nextIntlWord.index) {
                    return this._createIntlWord(nextIntlWord, chClass);
                }
                if (chClass === 0 /* WordCharacterClass.Regular */) {
                    if (wordType === 2 /* WordType.Separator */) {
                        return this._createWord(lineContent, wordType, chClass, this._findStartOfWord(lineContent, wordSeparators, wordType, chIndex - 1), chIndex);
                    }
                    wordType = 1 /* WordType.Regular */;
                }
                else if (chClass === 2 /* WordCharacterClass.WordSeparator */) {
                    if (wordType === 1 /* WordType.Regular */) {
                        return this._createWord(lineContent, wordType, chClass, this._findStartOfWord(lineContent, wordSeparators, wordType, chIndex - 1), chIndex);
                    }
                    wordType = 2 /* WordType.Separator */;
                }
                else if (chClass === 1 /* WordCharacterClass.Whitespace */) {
                    if (wordType !== 0 /* WordType.None */) {
                        return this._createWord(lineContent, wordType, chClass, this._findStartOfWord(lineContent, wordSeparators, wordType, chIndex - 1), chIndex);
                    }
                }
            }
            if (wordType !== 0 /* WordType.None */) {
                return this._createWord(lineContent, wordType, 1 /* WordCharacterClass.Whitespace */, this._findStartOfWord(lineContent, wordSeparators, wordType, len - 1), len);
            }
            return null;
        }
        static _findStartOfWord(lineContent, wordSeparators, wordType, startIndex) {
            const previousIntlWord = wordSeparators.findPrevIntlWordBeforeOrAtOffset(lineContent, startIndex);
            for (let chIndex = startIndex; chIndex >= 0; chIndex--) {
                const chCode = lineContent.charCodeAt(chIndex);
                const chClass = wordSeparators.get(chCode);
                if (previousIntlWord && chIndex === previousIntlWord.index) {
                    return chIndex;
                }
                if (chClass === 1 /* WordCharacterClass.Whitespace */) {
                    return chIndex + 1;
                }
                if (wordType === 1 /* WordType.Regular */ && chClass === 2 /* WordCharacterClass.WordSeparator */) {
                    return chIndex + 1;
                }
                if (wordType === 2 /* WordType.Separator */ && chClass === 0 /* WordCharacterClass.Regular */) {
                    return chIndex + 1;
                }
            }
            return 0;
        }
        static moveWordLeft(wordSeparators, model, position, wordNavigationType, hasMulticursor) {
            let lineNumber = position.lineNumber;
            let column = position.column;
            if (column === 1) {
                if (lineNumber > 1) {
                    lineNumber = lineNumber - 1;
                    column = model.getLineMaxColumn(lineNumber);
                }
            }
            let prevWordOnLine = WordOperations._findPreviousWordOnLine(wordSeparators, model, new position_1.Position(lineNumber, column));
            if (wordNavigationType === 0 /* WordNavigationType.WordStart */) {
                return new position_1.Position(lineNumber, prevWordOnLine ? prevWordOnLine.start + 1 : 1);
            }
            if (wordNavigationType === 1 /* WordNavigationType.WordStartFast */) {
                if (!hasMulticursor // avoid having multiple cursors stop at different locations when doing word start
                    && prevWordOnLine
                    && prevWordOnLine.wordType === 2 /* WordType.Separator */
                    && prevWordOnLine.end - prevWordOnLine.start === 1
                    && prevWordOnLine.nextCharClass === 0 /* WordCharacterClass.Regular */) {
                    // Skip over a word made up of one single separator and followed by a regular character
                    prevWordOnLine = WordOperations._findPreviousWordOnLine(wordSeparators, model, new position_1.Position(lineNumber, prevWordOnLine.start + 1));
                }
                return new position_1.Position(lineNumber, prevWordOnLine ? prevWordOnLine.start + 1 : 1);
            }
            if (wordNavigationType === 3 /* WordNavigationType.WordAccessibility */) {
                while (prevWordOnLine
                    && prevWordOnLine.wordType === 2 /* WordType.Separator */) {
                    // Skip over words made up of only separators
                    prevWordOnLine = WordOperations._findPreviousWordOnLine(wordSeparators, model, new position_1.Position(lineNumber, prevWordOnLine.start + 1));
                }
                return new position_1.Position(lineNumber, prevWordOnLine ? prevWordOnLine.start + 1 : 1);
            }
            // We are stopping at the ending of words
            if (prevWordOnLine && column <= prevWordOnLine.end + 1) {
                prevWordOnLine = WordOperations._findPreviousWordOnLine(wordSeparators, model, new position_1.Position(lineNumber, prevWordOnLine.start + 1));
            }
            return new position_1.Position(lineNumber, prevWordOnLine ? prevWordOnLine.end + 1 : 1);
        }
        static _moveWordPartLeft(model, position) {
            const lineNumber = position.lineNumber;
            const maxColumn = model.getLineMaxColumn(lineNumber);
            if (position.column === 1) {
                return (lineNumber > 1 ? new position_1.Position(lineNumber - 1, model.getLineMaxColumn(lineNumber - 1)) : position);
            }
            const lineContent = model.getLineContent(lineNumber);
            for (let column = position.column - 1; column > 1; column--) {
                const left = lineContent.charCodeAt(column - 2);
                const right = lineContent.charCodeAt(column - 1);
                if (left === 95 /* CharCode.Underline */ && right !== 95 /* CharCode.Underline */) {
                    // snake_case_variables
                    return new position_1.Position(lineNumber, column);
                }
                if (left === 45 /* CharCode.Dash */ && right !== 45 /* CharCode.Dash */) {
                    // kebab-case-variables
                    return new position_1.Position(lineNumber, column);
                }
                if ((strings.isLowerAsciiLetter(left) || strings.isAsciiDigit(left)) && strings.isUpperAsciiLetter(right)) {
                    // camelCaseVariables
                    return new position_1.Position(lineNumber, column);
                }
                if (strings.isUpperAsciiLetter(left) && strings.isUpperAsciiLetter(right)) {
                    // thisIsACamelCaseWithOneLetterWords
                    if (column + 1 < maxColumn) {
                        const rightRight = lineContent.charCodeAt(column);
                        if (strings.isLowerAsciiLetter(rightRight) || strings.isAsciiDigit(rightRight)) {
                            return new position_1.Position(lineNumber, column);
                        }
                    }
                }
            }
            return new position_1.Position(lineNumber, 1);
        }
        static moveWordRight(wordSeparators, model, position, wordNavigationType) {
            let lineNumber = position.lineNumber;
            let column = position.column;
            let movedDown = false;
            if (column === model.getLineMaxColumn(lineNumber)) {
                if (lineNumber < model.getLineCount()) {
                    movedDown = true;
                    lineNumber = lineNumber + 1;
                    column = 1;
                }
            }
            let nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators, model, new position_1.Position(lineNumber, column));
            if (wordNavigationType === 2 /* WordNavigationType.WordEnd */) {
                if (nextWordOnLine && nextWordOnLine.wordType === 2 /* WordType.Separator */) {
                    if (nextWordOnLine.end - nextWordOnLine.start === 1 && nextWordOnLine.nextCharClass === 0 /* WordCharacterClass.Regular */) {
                        // Skip over a word made up of one single separator and followed by a regular character
                        nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators, model, new position_1.Position(lineNumber, nextWordOnLine.end + 1));
                    }
                }
                if (nextWordOnLine) {
                    column = nextWordOnLine.end + 1;
                }
                else {
                    column = model.getLineMaxColumn(lineNumber);
                }
            }
            else if (wordNavigationType === 3 /* WordNavigationType.WordAccessibility */) {
                if (movedDown) {
                    // If we move to the next line, pretend that the cursor is right before the first character.
                    // This is needed when the first word starts right at the first character - and in order not to miss it,
                    // we need to start before.
                    column = 0;
                }
                while (nextWordOnLine
                    && (nextWordOnLine.wordType === 2 /* WordType.Separator */
                        || nextWordOnLine.start + 1 <= column)) {
                    // Skip over a word made up of one single separator
                    // Also skip over word if it begins before current cursor position to ascertain we're moving forward at least 1 character.
                    nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators, model, new position_1.Position(lineNumber, nextWordOnLine.end + 1));
                }
                if (nextWordOnLine) {
                    column = nextWordOnLine.start + 1;
                }
                else {
                    column = model.getLineMaxColumn(lineNumber);
                }
            }
            else {
                if (nextWordOnLine && !movedDown && column >= nextWordOnLine.start + 1) {
                    nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators, model, new position_1.Position(lineNumber, nextWordOnLine.end + 1));
                }
                if (nextWordOnLine) {
                    column = nextWordOnLine.start + 1;
                }
                else {
                    column = model.getLineMaxColumn(lineNumber);
                }
            }
            return new position_1.Position(lineNumber, column);
        }
        static _moveWordPartRight(model, position) {
            const lineNumber = position.lineNumber;
            const maxColumn = model.getLineMaxColumn(lineNumber);
            if (position.column === maxColumn) {
                return (lineNumber < model.getLineCount() ? new position_1.Position(lineNumber + 1, 1) : position);
            }
            const lineContent = model.getLineContent(lineNumber);
            for (let column = position.column + 1; column < maxColumn; column++) {
                const left = lineContent.charCodeAt(column - 2);
                const right = lineContent.charCodeAt(column - 1);
                if (left !== 95 /* CharCode.Underline */ && right === 95 /* CharCode.Underline */) {
                    // snake_case_variables
                    return new position_1.Position(lineNumber, column);
                }
                if (left !== 45 /* CharCode.Dash */ && right === 45 /* CharCode.Dash */) {
                    // kebab-case-variables
                    return new position_1.Position(lineNumber, column);
                }
                if ((strings.isLowerAsciiLetter(left) || strings.isAsciiDigit(left)) && strings.isUpperAsciiLetter(right)) {
                    // camelCaseVariables
                    return new position_1.Position(lineNumber, column);
                }
                if (strings.isUpperAsciiLetter(left) && strings.isUpperAsciiLetter(right)) {
                    // thisIsACamelCaseWithOneLetterWords
                    if (column + 1 < maxColumn) {
                        const rightRight = lineContent.charCodeAt(column);
                        if (strings.isLowerAsciiLetter(rightRight) || strings.isAsciiDigit(rightRight)) {
                            return new position_1.Position(lineNumber, column);
                        }
                    }
                }
            }
            return new position_1.Position(lineNumber, maxColumn);
        }
        static _deleteWordLeftWhitespace(model, position) {
            const lineContent = model.getLineContent(position.lineNumber);
            const startIndex = position.column - 2;
            const lastNonWhitespace = strings.lastNonWhitespaceIndex(lineContent, startIndex);
            if (lastNonWhitespace + 1 < startIndex) {
                return new range_1.Range(position.lineNumber, lastNonWhitespace + 2, position.lineNumber, position.column);
            }
            return null;
        }
        static deleteWordLeft(ctx, wordNavigationType) {
            const wordSeparators = ctx.wordSeparators;
            const model = ctx.model;
            const selection = ctx.selection;
            const whitespaceHeuristics = ctx.whitespaceHeuristics;
            if (!selection.isEmpty()) {
                return selection;
            }
            if (cursorDeleteOperations_1.DeleteOperations.isAutoClosingPairDelete(ctx.autoClosingDelete, ctx.autoClosingBrackets, ctx.autoClosingQuotes, ctx.autoClosingPairs.autoClosingPairsOpenByEnd, ctx.model, [ctx.selection], ctx.autoClosedCharacters)) {
                const position = ctx.selection.getPosition();
                return new range_1.Range(position.lineNumber, position.column - 1, position.lineNumber, position.column + 1);
            }
            const position = new position_1.Position(selection.positionLineNumber, selection.positionColumn);
            let lineNumber = position.lineNumber;
            let column = position.column;
            if (lineNumber === 1 && column === 1) {
                // Ignore deleting at beginning of file
                return null;
            }
            if (whitespaceHeuristics) {
                const r = this._deleteWordLeftWhitespace(model, position);
                if (r) {
                    return r;
                }
            }
            let prevWordOnLine = WordOperations._findPreviousWordOnLine(wordSeparators, model, position);
            if (wordNavigationType === 0 /* WordNavigationType.WordStart */) {
                if (prevWordOnLine) {
                    column = prevWordOnLine.start + 1;
                }
                else {
                    if (column > 1) {
                        column = 1;
                    }
                    else {
                        lineNumber--;
                        column = model.getLineMaxColumn(lineNumber);
                    }
                }
            }
            else {
                if (prevWordOnLine && column <= prevWordOnLine.end + 1) {
                    prevWordOnLine = WordOperations._findPreviousWordOnLine(wordSeparators, model, new position_1.Position(lineNumber, prevWordOnLine.start + 1));
                }
                if (prevWordOnLine) {
                    column = prevWordOnLine.end + 1;
                }
                else {
                    if (column > 1) {
                        column = 1;
                    }
                    else {
                        lineNumber--;
                        column = model.getLineMaxColumn(lineNumber);
                    }
                }
            }
            return new range_1.Range(lineNumber, column, position.lineNumber, position.column);
        }
        static deleteInsideWord(wordSeparators, model, selection) {
            if (!selection.isEmpty()) {
                return selection;
            }
            const position = new position_1.Position(selection.positionLineNumber, selection.positionColumn);
            const r = this._deleteInsideWordWhitespace(model, position);
            if (r) {
                return r;
            }
            return this._deleteInsideWordDetermineDeleteRange(wordSeparators, model, position);
        }
        static _charAtIsWhitespace(str, index) {
            const charCode = str.charCodeAt(index);
            return (charCode === 32 /* CharCode.Space */ || charCode === 9 /* CharCode.Tab */);
        }
        static _deleteInsideWordWhitespace(model, position) {
            const lineContent = model.getLineContent(position.lineNumber);
            const lineContentLength = lineContent.length;
            if (lineContentLength === 0) {
                // empty line
                return null;
            }
            let leftIndex = Math.max(position.column - 2, 0);
            if (!this._charAtIsWhitespace(lineContent, leftIndex)) {
                // touches a non-whitespace character to the left
                return null;
            }
            let rightIndex = Math.min(position.column - 1, lineContentLength - 1);
            if (!this._charAtIsWhitespace(lineContent, rightIndex)) {
                // touches a non-whitespace character to the right
                return null;
            }
            // walk over whitespace to the left
            while (leftIndex > 0 && this._charAtIsWhitespace(lineContent, leftIndex - 1)) {
                leftIndex--;
            }
            // walk over whitespace to the right
            while (rightIndex + 1 < lineContentLength && this._charAtIsWhitespace(lineContent, rightIndex + 1)) {
                rightIndex++;
            }
            return new range_1.Range(position.lineNumber, leftIndex + 1, position.lineNumber, rightIndex + 2);
        }
        static _deleteInsideWordDetermineDeleteRange(wordSeparators, model, position) {
            const lineContent = model.getLineContent(position.lineNumber);
            const lineLength = lineContent.length;
            if (lineLength === 0) {
                // empty line
                if (position.lineNumber > 1) {
                    return new range_1.Range(position.lineNumber - 1, model.getLineMaxColumn(position.lineNumber - 1), position.lineNumber, 1);
                }
                else {
                    if (position.lineNumber < model.getLineCount()) {
                        return new range_1.Range(position.lineNumber, 1, position.lineNumber + 1, 1);
                    }
                    else {
                        // empty model
                        return new range_1.Range(position.lineNumber, 1, position.lineNumber, 1);
                    }
                }
            }
            const touchesWord = (word) => {
                return (word.start + 1 <= position.column && position.column <= word.end + 1);
            };
            const createRangeWithPosition = (startColumn, endColumn) => {
                startColumn = Math.min(startColumn, position.column);
                endColumn = Math.max(endColumn, position.column);
                return new range_1.Range(position.lineNumber, startColumn, position.lineNumber, endColumn);
            };
            const deleteWordAndAdjacentWhitespace = (word) => {
                let startColumn = word.start + 1;
                let endColumn = word.end + 1;
                let expandedToTheRight = false;
                while (endColumn - 1 < lineLength && this._charAtIsWhitespace(lineContent, endColumn - 1)) {
                    expandedToTheRight = true;
                    endColumn++;
                }
                if (!expandedToTheRight) {
                    while (startColumn > 1 && this._charAtIsWhitespace(lineContent, startColumn - 2)) {
                        startColumn--;
                    }
                }
                return createRangeWithPosition(startColumn, endColumn);
            };
            const prevWordOnLine = WordOperations._findPreviousWordOnLine(wordSeparators, model, position);
            if (prevWordOnLine && touchesWord(prevWordOnLine)) {
                return deleteWordAndAdjacentWhitespace(prevWordOnLine);
            }
            const nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators, model, position);
            if (nextWordOnLine && touchesWord(nextWordOnLine)) {
                return deleteWordAndAdjacentWhitespace(nextWordOnLine);
            }
            if (prevWordOnLine && nextWordOnLine) {
                return createRangeWithPosition(prevWordOnLine.end + 1, nextWordOnLine.start + 1);
            }
            if (prevWordOnLine) {
                return createRangeWithPosition(prevWordOnLine.start + 1, prevWordOnLine.end + 1);
            }
            if (nextWordOnLine) {
                return createRangeWithPosition(nextWordOnLine.start + 1, nextWordOnLine.end + 1);
            }
            return createRangeWithPosition(1, lineLength + 1);
        }
        static _deleteWordPartLeft(model, selection) {
            if (!selection.isEmpty()) {
                return selection;
            }
            const pos = selection.getPosition();
            const toPosition = WordOperations._moveWordPartLeft(model, pos);
            return new range_1.Range(pos.lineNumber, pos.column, toPosition.lineNumber, toPosition.column);
        }
        static _findFirstNonWhitespaceChar(str, startIndex) {
            const len = str.length;
            for (let chIndex = startIndex; chIndex < len; chIndex++) {
                const ch = str.charAt(chIndex);
                if (ch !== ' ' && ch !== '\t') {
                    return chIndex;
                }
            }
            return len;
        }
        static _deleteWordRightWhitespace(model, position) {
            const lineContent = model.getLineContent(position.lineNumber);
            const startIndex = position.column - 1;
            const firstNonWhitespace = this._findFirstNonWhitespaceChar(lineContent, startIndex);
            if (startIndex + 1 < firstNonWhitespace) {
                // bingo
                return new range_1.Range(position.lineNumber, position.column, position.lineNumber, firstNonWhitespace + 1);
            }
            return null;
        }
        static deleteWordRight(ctx, wordNavigationType) {
            const wordSeparators = ctx.wordSeparators;
            const model = ctx.model;
            const selection = ctx.selection;
            const whitespaceHeuristics = ctx.whitespaceHeuristics;
            if (!selection.isEmpty()) {
                return selection;
            }
            const position = new position_1.Position(selection.positionLineNumber, selection.positionColumn);
            let lineNumber = position.lineNumber;
            let column = position.column;
            const lineCount = model.getLineCount();
            const maxColumn = model.getLineMaxColumn(lineNumber);
            if (lineNumber === lineCount && column === maxColumn) {
                // Ignore deleting at end of file
                return null;
            }
            if (whitespaceHeuristics) {
                const r = this._deleteWordRightWhitespace(model, position);
                if (r) {
                    return r;
                }
            }
            let nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators, model, position);
            if (wordNavigationType === 2 /* WordNavigationType.WordEnd */) {
                if (nextWordOnLine) {
                    column = nextWordOnLine.end + 1;
                }
                else {
                    if (column < maxColumn || lineNumber === lineCount) {
                        column = maxColumn;
                    }
                    else {
                        lineNumber++;
                        nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators, model, new position_1.Position(lineNumber, 1));
                        if (nextWordOnLine) {
                            column = nextWordOnLine.start + 1;
                        }
                        else {
                            column = model.getLineMaxColumn(lineNumber);
                        }
                    }
                }
            }
            else {
                if (nextWordOnLine && column >= nextWordOnLine.start + 1) {
                    nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators, model, new position_1.Position(lineNumber, nextWordOnLine.end + 1));
                }
                if (nextWordOnLine) {
                    column = nextWordOnLine.start + 1;
                }
                else {
                    if (column < maxColumn || lineNumber === lineCount) {
                        column = maxColumn;
                    }
                    else {
                        lineNumber++;
                        nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators, model, new position_1.Position(lineNumber, 1));
                        if (nextWordOnLine) {
                            column = nextWordOnLine.start + 1;
                        }
                        else {
                            column = model.getLineMaxColumn(lineNumber);
                        }
                    }
                }
            }
            return new range_1.Range(lineNumber, column, position.lineNumber, position.column);
        }
        static _deleteWordPartRight(model, selection) {
            if (!selection.isEmpty()) {
                return selection;
            }
            const pos = selection.getPosition();
            const toPosition = WordOperations._moveWordPartRight(model, pos);
            return new range_1.Range(pos.lineNumber, pos.column, toPosition.lineNumber, toPosition.column);
        }
        static _createWordAtPosition(model, lineNumber, word) {
            const range = new range_1.Range(lineNumber, word.start + 1, lineNumber, word.end + 1);
            return {
                word: model.getValueInRange(range),
                startColumn: range.startColumn,
                endColumn: range.endColumn
            };
        }
        static getWordAtPosition(model, _wordSeparators, _intlSegmenterLocales, position) {
            const wordSeparators = (0, wordCharacterClassifier_1.getMapForWordSeparators)(_wordSeparators, _intlSegmenterLocales);
            const prevWord = WordOperations._findPreviousWordOnLine(wordSeparators, model, position);
            if (prevWord && prevWord.wordType === 1 /* WordType.Regular */ && prevWord.start <= position.column - 1 && position.column - 1 <= prevWord.end) {
                return WordOperations._createWordAtPosition(model, position.lineNumber, prevWord);
            }
            const nextWord = WordOperations._findNextWordOnLine(wordSeparators, model, position);
            if (nextWord && nextWord.wordType === 1 /* WordType.Regular */ && nextWord.start <= position.column - 1 && position.column - 1 <= nextWord.end) {
                return WordOperations._createWordAtPosition(model, position.lineNumber, nextWord);
            }
            return null;
        }
        static word(config, model, cursor, inSelectionMode, position) {
            const wordSeparators = (0, wordCharacterClassifier_1.getMapForWordSeparators)(config.wordSeparators, config.wordSegmenterLocales);
            const prevWord = WordOperations._findPreviousWordOnLine(wordSeparators, model, position);
            const nextWord = WordOperations._findNextWordOnLine(wordSeparators, model, position);
            if (!inSelectionMode) {
                // Entering word selection for the first time
                let startColumn;
                let endColumn;
                if (prevWord && prevWord.wordType === 1 /* WordType.Regular */ && prevWord.start <= position.column - 1 && position.column - 1 <= prevWord.end) {
                    // isTouchingPrevWord
                    startColumn = prevWord.start + 1;
                    endColumn = prevWord.end + 1;
                }
                else if (nextWord && nextWord.wordType === 1 /* WordType.Regular */ && nextWord.start <= position.column - 1 && position.column - 1 <= nextWord.end) {
                    // isTouchingNextWord
                    startColumn = nextWord.start + 1;
                    endColumn = nextWord.end + 1;
                }
                else {
                    if (prevWord) {
                        startColumn = prevWord.end + 1;
                    }
                    else {
                        startColumn = 1;
                    }
                    if (nextWord) {
                        endColumn = nextWord.start + 1;
                    }
                    else {
                        endColumn = model.getLineMaxColumn(position.lineNumber);
                    }
                }
                return new cursorCommon_1.SingleCursorState(new range_1.Range(position.lineNumber, startColumn, position.lineNumber, endColumn), 1 /* SelectionStartKind.Word */, 0, new position_1.Position(position.lineNumber, endColumn), 0);
            }
            let startColumn;
            let endColumn;
            if (prevWord && prevWord.wordType === 1 /* WordType.Regular */ && prevWord.start < position.column - 1 && position.column - 1 < prevWord.end) {
                // isInsidePrevWord
                startColumn = prevWord.start + 1;
                endColumn = prevWord.end + 1;
            }
            else if (nextWord && nextWord.wordType === 1 /* WordType.Regular */ && nextWord.start < position.column - 1 && position.column - 1 < nextWord.end) {
                // isInsideNextWord
                startColumn = nextWord.start + 1;
                endColumn = nextWord.end + 1;
            }
            else {
                startColumn = position.column;
                endColumn = position.column;
            }
            const lineNumber = position.lineNumber;
            let column;
            if (cursor.selectionStart.containsPosition(position)) {
                column = cursor.selectionStart.endColumn;
            }
            else if (position.isBeforeOrEqual(cursor.selectionStart.getStartPosition())) {
                column = startColumn;
                const possiblePosition = new position_1.Position(lineNumber, column);
                if (cursor.selectionStart.containsPosition(possiblePosition)) {
                    column = cursor.selectionStart.endColumn;
                }
            }
            else {
                column = endColumn;
                const possiblePosition = new position_1.Position(lineNumber, column);
                if (cursor.selectionStart.containsPosition(possiblePosition)) {
                    column = cursor.selectionStart.startColumn;
                }
            }
            return cursor.move(true, lineNumber, column, 0);
        }
    }
    exports.WordOperations = WordOperations;
    class WordPartOperations extends WordOperations {
        static deleteWordPartLeft(ctx) {
            const candidates = enforceDefined([
                WordOperations.deleteWordLeft(ctx, 0 /* WordNavigationType.WordStart */),
                WordOperations.deleteWordLeft(ctx, 2 /* WordNavigationType.WordEnd */),
                WordOperations._deleteWordPartLeft(ctx.model, ctx.selection)
            ]);
            candidates.sort(range_1.Range.compareRangesUsingEnds);
            return candidates[2];
        }
        static deleteWordPartRight(ctx) {
            const candidates = enforceDefined([
                WordOperations.deleteWordRight(ctx, 0 /* WordNavigationType.WordStart */),
                WordOperations.deleteWordRight(ctx, 2 /* WordNavigationType.WordEnd */),
                WordOperations._deleteWordPartRight(ctx.model, ctx.selection)
            ]);
            candidates.sort(range_1.Range.compareRangesUsingStarts);
            return candidates[0];
        }
        static moveWordPartLeft(wordSeparators, model, position, hasMulticursor) {
            const candidates = enforceDefined([
                WordOperations.moveWordLeft(wordSeparators, model, position, 0 /* WordNavigationType.WordStart */, hasMulticursor),
                WordOperations.moveWordLeft(wordSeparators, model, position, 2 /* WordNavigationType.WordEnd */, hasMulticursor),
                WordOperations._moveWordPartLeft(model, position)
            ]);
            candidates.sort(position_1.Position.compare);
            return candidates[2];
        }
        static moveWordPartRight(wordSeparators, model, position) {
            const candidates = enforceDefined([
                WordOperations.moveWordRight(wordSeparators, model, position, 0 /* WordNavigationType.WordStart */),
                WordOperations.moveWordRight(wordSeparators, model, position, 2 /* WordNavigationType.WordEnd */),
                WordOperations._moveWordPartRight(model, position)
            ]);
            candidates.sort(position_1.Position.compare);
            return candidates[0];
        }
    }
    exports.WordPartOperations = WordPartOperations;
    function enforceDefined(arr) {
        return arr.filter(el => Boolean(el));
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[235/*vs/editor/common/cursor/cursorMoveCommands*/], __M([1/*require*/,0/*exports*/,19/*vs/base/common/types*/,76/*vs/editor/common/cursorCommon*/,233/*vs/editor/common/cursor/cursorMoveOperations*/,199/*vs/editor/common/cursor/cursorWordOperations*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/]), function (require, exports, types, cursorCommon_1, cursorMoveOperations_1, cursorWordOperations_1, position_1, range_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CursorMove = exports.CursorMoveCommands = void 0;
    class CursorMoveCommands {
        static addCursorDown(viewModel, cursors, useLogicalLine) {
            const result = [];
            let resultLen = 0;
            for (let i = 0, len = cursors.length; i < len; i++) {
                const cursor = cursors[i];
                result[resultLen++] = new cursorCommon_1.CursorState(cursor.modelState, cursor.viewState);
                if (useLogicalLine) {
                    result[resultLen++] = cursorCommon_1.CursorState.fromModelState(cursorMoveOperations_1.MoveOperations.translateDown(viewModel.cursorConfig, viewModel.model, cursor.modelState));
                }
                else {
                    result[resultLen++] = cursorCommon_1.CursorState.fromViewState(cursorMoveOperations_1.MoveOperations.translateDown(viewModel.cursorConfig, viewModel, cursor.viewState));
                }
            }
            return result;
        }
        static addCursorUp(viewModel, cursors, useLogicalLine) {
            const result = [];
            let resultLen = 0;
            for (let i = 0, len = cursors.length; i < len; i++) {
                const cursor = cursors[i];
                result[resultLen++] = new cursorCommon_1.CursorState(cursor.modelState, cursor.viewState);
                if (useLogicalLine) {
                    result[resultLen++] = cursorCommon_1.CursorState.fromModelState(cursorMoveOperations_1.MoveOperations.translateUp(viewModel.cursorConfig, viewModel.model, cursor.modelState));
                }
                else {
                    result[resultLen++] = cursorCommon_1.CursorState.fromViewState(cursorMoveOperations_1.MoveOperations.translateUp(viewModel.cursorConfig, viewModel, cursor.viewState));
                }
            }
            return result;
        }
        static moveToBeginningOfLine(viewModel, cursors, inSelectionMode) {
            const result = [];
            for (let i = 0, len = cursors.length; i < len; i++) {
                const cursor = cursors[i];
                result[i] = this._moveToLineStart(viewModel, cursor, inSelectionMode);
            }
            return result;
        }
        static _moveToLineStart(viewModel, cursor, inSelectionMode) {
            const currentViewStateColumn = cursor.viewState.position.column;
            const currentModelStateColumn = cursor.modelState.position.column;
            const isFirstLineOfWrappedLine = currentViewStateColumn === currentModelStateColumn;
            const currentViewStatelineNumber = cursor.viewState.position.lineNumber;
            const firstNonBlankColumn = viewModel.getLineFirstNonWhitespaceColumn(currentViewStatelineNumber);
            const isBeginningOfViewLine = currentViewStateColumn === firstNonBlankColumn;
            if (!isFirstLineOfWrappedLine && !isBeginningOfViewLine) {
                return this._moveToLineStartByView(viewModel, cursor, inSelectionMode);
            }
            else {
                return this._moveToLineStartByModel(viewModel, cursor, inSelectionMode);
            }
        }
        static _moveToLineStartByView(viewModel, cursor, inSelectionMode) {
            return cursorCommon_1.CursorState.fromViewState(cursorMoveOperations_1.MoveOperations.moveToBeginningOfLine(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode));
        }
        static _moveToLineStartByModel(viewModel, cursor, inSelectionMode) {
            return cursorCommon_1.CursorState.fromModelState(cursorMoveOperations_1.MoveOperations.moveToBeginningOfLine(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode));
        }
        static moveToEndOfLine(viewModel, cursors, inSelectionMode, sticky) {
            const result = [];
            for (let i = 0, len = cursors.length; i < len; i++) {
                const cursor = cursors[i];
                result[i] = this._moveToLineEnd(viewModel, cursor, inSelectionMode, sticky);
            }
            return result;
        }
        static _moveToLineEnd(viewModel, cursor, inSelectionMode, sticky) {
            const viewStatePosition = cursor.viewState.position;
            const viewModelMaxColumn = viewModel.getLineMaxColumn(viewStatePosition.lineNumber);
            const isEndOfViewLine = viewStatePosition.column === viewModelMaxColumn;
            const modelStatePosition = cursor.modelState.position;
            const modelMaxColumn = viewModel.model.getLineMaxColumn(modelStatePosition.lineNumber);
            const isEndLineOfWrappedLine = viewModelMaxColumn - viewStatePosition.column === modelMaxColumn - modelStatePosition.column;
            if (isEndOfViewLine || isEndLineOfWrappedLine) {
                return this._moveToLineEndByModel(viewModel, cursor, inSelectionMode, sticky);
            }
            else {
                return this._moveToLineEndByView(viewModel, cursor, inSelectionMode, sticky);
            }
        }
        static _moveToLineEndByView(viewModel, cursor, inSelectionMode, sticky) {
            return cursorCommon_1.CursorState.fromViewState(cursorMoveOperations_1.MoveOperations.moveToEndOfLine(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode, sticky));
        }
        static _moveToLineEndByModel(viewModel, cursor, inSelectionMode, sticky) {
            return cursorCommon_1.CursorState.fromModelState(cursorMoveOperations_1.MoveOperations.moveToEndOfLine(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode, sticky));
        }
        static expandLineSelection(viewModel, cursors) {
            const result = [];
            for (let i = 0, len = cursors.length; i < len; i++) {
                const cursor = cursors[i];
                const startLineNumber = cursor.modelState.selection.startLineNumber;
                const lineCount = viewModel.model.getLineCount();
                let endLineNumber = cursor.modelState.selection.endLineNumber;
                let endColumn;
                if (endLineNumber === lineCount) {
                    endColumn = viewModel.model.getLineMaxColumn(lineCount);
                }
                else {
                    endLineNumber++;
                    endColumn = 1;
                }
                result[i] = cursorCommon_1.CursorState.fromModelState(new cursorCommon_1.SingleCursorState(new range_1.Range(startLineNumber, 1, startLineNumber, 1), 0 /* SelectionStartKind.Simple */, 0, new position_1.Position(endLineNumber, endColumn), 0));
            }
            return result;
        }
        static moveToBeginningOfBuffer(viewModel, cursors, inSelectionMode) {
            const result = [];
            for (let i = 0, len = cursors.length; i < len; i++) {
                const cursor = cursors[i];
                result[i] = cursorCommon_1.CursorState.fromModelState(cursorMoveOperations_1.MoveOperations.moveToBeginningOfBuffer(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode));
            }
            return result;
        }
        static moveToEndOfBuffer(viewModel, cursors, inSelectionMode) {
            const result = [];
            for (let i = 0, len = cursors.length; i < len; i++) {
                const cursor = cursors[i];
                result[i] = cursorCommon_1.CursorState.fromModelState(cursorMoveOperations_1.MoveOperations.moveToEndOfBuffer(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode));
            }
            return result;
        }
        static selectAll(viewModel, cursor) {
            const lineCount = viewModel.model.getLineCount();
            const maxColumn = viewModel.model.getLineMaxColumn(lineCount);
            return cursorCommon_1.CursorState.fromModelState(new cursorCommon_1.SingleCursorState(new range_1.Range(1, 1, 1, 1), 0 /* SelectionStartKind.Simple */, 0, new position_1.Position(lineCount, maxColumn), 0));
        }
        static line(viewModel, cursor, inSelectionMode, _position, _viewPosition) {
            const position = viewModel.model.validatePosition(_position);
            const viewPosition = (_viewPosition
                ? viewModel.coordinatesConverter.validateViewPosition(new position_1.Position(_viewPosition.lineNumber, _viewPosition.column), position)
                : viewModel.coordinatesConverter.convertModelPositionToViewPosition(position));
            if (!inSelectionMode) {
                // Entering line selection for the first time
                const lineCount = viewModel.model.getLineCount();
                let selectToLineNumber = position.lineNumber + 1;
                let selectToColumn = 1;
                if (selectToLineNumber > lineCount) {
                    selectToLineNumber = lineCount;
                    selectToColumn = viewModel.model.getLineMaxColumn(selectToLineNumber);
                }
                return cursorCommon_1.CursorState.fromModelState(new cursorCommon_1.SingleCursorState(new range_1.Range(position.lineNumber, 1, selectToLineNumber, selectToColumn), 2 /* SelectionStartKind.Line */, 0, new position_1.Position(selectToLineNumber, selectToColumn), 0));
            }
            // Continuing line selection
            const enteringLineNumber = cursor.modelState.selectionStart.getStartPosition().lineNumber;
            if (position.lineNumber < enteringLineNumber) {
                return cursorCommon_1.CursorState.fromViewState(cursor.viewState.move(true, viewPosition.lineNumber, 1, 0));
            }
            else if (position.lineNumber > enteringLineNumber) {
                const lineCount = viewModel.getLineCount();
                let selectToViewLineNumber = viewPosition.lineNumber + 1;
                let selectToViewColumn = 1;
                if (selectToViewLineNumber > lineCount) {
                    selectToViewLineNumber = lineCount;
                    selectToViewColumn = viewModel.getLineMaxColumn(selectToViewLineNumber);
                }
                return cursorCommon_1.CursorState.fromViewState(cursor.viewState.move(true, selectToViewLineNumber, selectToViewColumn, 0));
            }
            else {
                const endPositionOfSelectionStart = cursor.modelState.selectionStart.getEndPosition();
                return cursorCommon_1.CursorState.fromModelState(cursor.modelState.move(true, endPositionOfSelectionStart.lineNumber, endPositionOfSelectionStart.column, 0));
            }
        }
        static word(viewModel, cursor, inSelectionMode, _position) {
            const position = viewModel.model.validatePosition(_position);
            return cursorCommon_1.CursorState.fromModelState(cursorWordOperations_1.WordOperations.word(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode, position));
        }
        static cancelSelection(viewModel, cursor) {
            if (!cursor.modelState.hasSelection()) {
                return new cursorCommon_1.CursorState(cursor.modelState, cursor.viewState);
            }
            const lineNumber = cursor.viewState.position.lineNumber;
            const column = cursor.viewState.position.column;
            return cursorCommon_1.CursorState.fromViewState(new cursorCommon_1.SingleCursorState(new range_1.Range(lineNumber, column, lineNumber, column), 0 /* SelectionStartKind.Simple */, 0, new position_1.Position(lineNumber, column), 0));
        }
        static moveTo(viewModel, cursor, inSelectionMode, _position, _viewPosition) {
            if (inSelectionMode) {
                if (cursor.modelState.selectionStartKind === 1 /* SelectionStartKind.Word */) {
                    return this.word(viewModel, cursor, inSelectionMode, _position);
                }
                if (cursor.modelState.selectionStartKind === 2 /* SelectionStartKind.Line */) {
                    return this.line(viewModel, cursor, inSelectionMode, _position, _viewPosition);
                }
            }
            const position = viewModel.model.validatePosition(_position);
            const viewPosition = (_viewPosition
                ? viewModel.coordinatesConverter.validateViewPosition(new position_1.Position(_viewPosition.lineNumber, _viewPosition.column), position)
                : viewModel.coordinatesConverter.convertModelPositionToViewPosition(position));
            return cursorCommon_1.CursorState.fromViewState(cursor.viewState.move(inSelectionMode, viewPosition.lineNumber, viewPosition.column, 0));
        }
        static simpleMove(viewModel, cursors, direction, inSelectionMode, value, unit) {
            switch (direction) {
                case 0 /* CursorMove.Direction.Left */: {
                    if (unit === 4 /* CursorMove.Unit.HalfLine */) {
                        // Move left by half the current line length
                        return this._moveHalfLineLeft(viewModel, cursors, inSelectionMode);
                    }
                    else {
                        // Move left by `moveParams.value` columns
                        return this._moveLeft(viewModel, cursors, inSelectionMode, value);
                    }
                }
                case 1 /* CursorMove.Direction.Right */: {
                    if (unit === 4 /* CursorMove.Unit.HalfLine */) {
                        // Move right by half the current line length
                        return this._moveHalfLineRight(viewModel, cursors, inSelectionMode);
                    }
                    else {
                        // Move right by `moveParams.value` columns
                        return this._moveRight(viewModel, cursors, inSelectionMode, value);
                    }
                }
                case 2 /* CursorMove.Direction.Up */: {
                    if (unit === 2 /* CursorMove.Unit.WrappedLine */) {
                        // Move up by view lines
                        return this._moveUpByViewLines(viewModel, cursors, inSelectionMode, value);
                    }
                    else {
                        // Move up by model lines
                        return this._moveUpByModelLines(viewModel, cursors, inSelectionMode, value);
                    }
                }
                case 3 /* CursorMove.Direction.Down */: {
                    if (unit === 2 /* CursorMove.Unit.WrappedLine */) {
                        // Move down by view lines
                        return this._moveDownByViewLines(viewModel, cursors, inSelectionMode, value);
                    }
                    else {
                        // Move down by model lines
                        return this._moveDownByModelLines(viewModel, cursors, inSelectionMode, value);
                    }
                }
                case 4 /* CursorMove.Direction.PrevBlankLine */: {
                    if (unit === 2 /* CursorMove.Unit.WrappedLine */) {
                        return cursors.map(cursor => cursorCommon_1.CursorState.fromViewState(cursorMoveOperations_1.MoveOperations.moveToPrevBlankLine(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode)));
                    }
                    else {
                        return cursors.map(cursor => cursorCommon_1.CursorState.fromModelState(cursorMoveOperations_1.MoveOperations.moveToPrevBlankLine(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode)));
                    }
                }
                case 5 /* CursorMove.Direction.NextBlankLine */: {
                    if (unit === 2 /* CursorMove.Unit.WrappedLine */) {
                        return cursors.map(cursor => cursorCommon_1.CursorState.fromViewState(cursorMoveOperations_1.MoveOperations.moveToNextBlankLine(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode)));
                    }
                    else {
                        return cursors.map(cursor => cursorCommon_1.CursorState.fromModelState(cursorMoveOperations_1.MoveOperations.moveToNextBlankLine(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode)));
                    }
                }
                case 6 /* CursorMove.Direction.WrappedLineStart */: {
                    // Move to the beginning of the current view line
                    return this._moveToViewMinColumn(viewModel, cursors, inSelectionMode);
                }
                case 7 /* CursorMove.Direction.WrappedLineFirstNonWhitespaceCharacter */: {
                    // Move to the first non-whitespace column of the current view line
                    return this._moveToViewFirstNonWhitespaceColumn(viewModel, cursors, inSelectionMode);
                }
                case 8 /* CursorMove.Direction.WrappedLineColumnCenter */: {
                    // Move to the "center" of the current view line
                    return this._moveToViewCenterColumn(viewModel, cursors, inSelectionMode);
                }
                case 9 /* CursorMove.Direction.WrappedLineEnd */: {
                    // Move to the end of the current view line
                    return this._moveToViewMaxColumn(viewModel, cursors, inSelectionMode);
                }
                case 10 /* CursorMove.Direction.WrappedLineLastNonWhitespaceCharacter */: {
                    // Move to the last non-whitespace column of the current view line
                    return this._moveToViewLastNonWhitespaceColumn(viewModel, cursors, inSelectionMode);
                }
                default:
                    return null;
            }
        }
        static viewportMove(viewModel, cursors, direction, inSelectionMode, value) {
            const visibleViewRange = viewModel.getCompletelyVisibleViewRange();
            const visibleModelRange = viewModel.coordinatesConverter.convertViewRangeToModelRange(visibleViewRange);
            switch (direction) {
                case 11 /* CursorMove.Direction.ViewPortTop */: {
                    // Move to the nth line start in the viewport (from the top)
                    const modelLineNumber = this._firstLineNumberInRange(viewModel.model, visibleModelRange, value);
                    const modelColumn = viewModel.model.getLineFirstNonWhitespaceColumn(modelLineNumber);
                    return [this._moveToModelPosition(viewModel, cursors[0], inSelectionMode, modelLineNumber, modelColumn)];
                }
                case 13 /* CursorMove.Direction.ViewPortBottom */: {
                    // Move to the nth line start in the viewport (from the bottom)
                    const modelLineNumber = this._lastLineNumberInRange(viewModel.model, visibleModelRange, value);
                    const modelColumn = viewModel.model.getLineFirstNonWhitespaceColumn(modelLineNumber);
                    return [this._moveToModelPosition(viewModel, cursors[0], inSelectionMode, modelLineNumber, modelColumn)];
                }
                case 12 /* CursorMove.Direction.ViewPortCenter */: {
                    // Move to the line start in the viewport center
                    const modelLineNumber = Math.round((visibleModelRange.startLineNumber + visibleModelRange.endLineNumber) / 2);
                    const modelColumn = viewModel.model.getLineFirstNonWhitespaceColumn(modelLineNumber);
                    return [this._moveToModelPosition(viewModel, cursors[0], inSelectionMode, modelLineNumber, modelColumn)];
                }
                case 14 /* CursorMove.Direction.ViewPortIfOutside */: {
                    // Move to a position inside the viewport
                    const result = [];
                    for (let i = 0, len = cursors.length; i < len; i++) {
                        const cursor = cursors[i];
                        result[i] = this.findPositionInViewportIfOutside(viewModel, cursor, visibleViewRange, inSelectionMode);
                    }
                    return result;
                }
                default:
                    return null;
            }
        }
        static findPositionInViewportIfOutside(viewModel, cursor, visibleViewRange, inSelectionMode) {
            const viewLineNumber = cursor.viewState.position.lineNumber;
            if (visibleViewRange.startLineNumber <= viewLineNumber && viewLineNumber <= visibleViewRange.endLineNumber - 1) {
                // Nothing to do, cursor is in viewport
                return new cursorCommon_1.CursorState(cursor.modelState, cursor.viewState);
            }
            else {
                let newViewLineNumber;
                if (viewLineNumber > visibleViewRange.endLineNumber - 1) {
                    newViewLineNumber = visibleViewRange.endLineNumber - 1;
                }
                else if (viewLineNumber < visibleViewRange.startLineNumber) {
                    newViewLineNumber = visibleViewRange.startLineNumber;
                }
                else {
                    newViewLineNumber = viewLineNumber;
                }
                const position = cursorMoveOperations_1.MoveOperations.vertical(viewModel.cursorConfig, viewModel, viewLineNumber, cursor.viewState.position.column, cursor.viewState.leftoverVisibleColumns, newViewLineNumber, false);
                return cursorCommon_1.CursorState.fromViewState(cursor.viewState.move(inSelectionMode, position.lineNumber, position.column, position.leftoverVisibleColumns));
            }
        }
        /**
         * Find the nth line start included in the range (from the start).
         */
        static _firstLineNumberInRange(model, range, count) {
            let startLineNumber = range.startLineNumber;
            if (range.startColumn !== model.getLineMinColumn(startLineNumber)) {
                // Move on to the second line if the first line start is not included in the range
                startLineNumber++;
            }
            return Math.min(range.endLineNumber, startLineNumber + count - 1);
        }
        /**
         * Find the nth line start included in the range (from the end).
         */
        static _lastLineNumberInRange(model, range, count) {
            let startLineNumber = range.startLineNumber;
            if (range.startColumn !== model.getLineMinColumn(startLineNumber)) {
                // Move on to the second line if the first line start is not included in the range
                startLineNumber++;
            }
            return Math.max(startLineNumber, range.endLineNumber - count + 1);
        }
        static _moveLeft(viewModel, cursors, inSelectionMode, noOfColumns) {
            return cursors.map(cursor => cursorCommon_1.CursorState.fromViewState(cursorMoveOperations_1.MoveOperations.moveLeft(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode, noOfColumns)));
        }
        static _moveHalfLineLeft(viewModel, cursors, inSelectionMode) {
            const result = [];
            for (let i = 0, len = cursors.length; i < len; i++) {
                const cursor = cursors[i];
                const viewLineNumber = cursor.viewState.position.lineNumber;
                const halfLine = Math.round(viewModel.getLineLength(viewLineNumber) / 2);
                result[i] = cursorCommon_1.CursorState.fromViewState(cursorMoveOperations_1.MoveOperations.moveLeft(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode, halfLine));
            }
            return result;
        }
        static _moveRight(viewModel, cursors, inSelectionMode, noOfColumns) {
            return cursors.map(cursor => cursorCommon_1.CursorState.fromViewState(cursorMoveOperations_1.MoveOperations.moveRight(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode, noOfColumns)));
        }
        static _moveHalfLineRight(viewModel, cursors, inSelectionMode) {
            const result = [];
            for (let i = 0, len = cursors.length; i < len; i++) {
                const cursor = cursors[i];
                const viewLineNumber = cursor.viewState.position.lineNumber;
                const halfLine = Math.round(viewModel.getLineLength(viewLineNumber) / 2);
                result[i] = cursorCommon_1.CursorState.fromViewState(cursorMoveOperations_1.MoveOperations.moveRight(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode, halfLine));
            }
            return result;
        }
        static _moveDownByViewLines(viewModel, cursors, inSelectionMode, linesCount) {
            const result = [];
            for (let i = 0, len = cursors.length; i < len; i++) {
                const cursor = cursors[i];
                result[i] = cursorCommon_1.CursorState.fromViewState(cursorMoveOperations_1.MoveOperations.moveDown(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode, linesCount));
            }
            return result;
        }
        static _moveDownByModelLines(viewModel, cursors, inSelectionMode, linesCount) {
            const result = [];
            for (let i = 0, len = cursors.length; i < len; i++) {
                const cursor = cursors[i];
                result[i] = cursorCommon_1.CursorState.fromModelState(cursorMoveOperations_1.MoveOperations.moveDown(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode, linesCount));
            }
            return result;
        }
        static _moveUpByViewLines(viewModel, cursors, inSelectionMode, linesCount) {
            const result = [];
            for (let i = 0, len = cursors.length; i < len; i++) {
                const cursor = cursors[i];
                result[i] = cursorCommon_1.CursorState.fromViewState(cursorMoveOperations_1.MoveOperations.moveUp(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode, linesCount));
            }
            return result;
        }
        static _moveUpByModelLines(viewModel, cursors, inSelectionMode, linesCount) {
            const result = [];
            for (let i = 0, len = cursors.length; i < len; i++) {
                const cursor = cursors[i];
                result[i] = cursorCommon_1.CursorState.fromModelState(cursorMoveOperations_1.MoveOperations.moveUp(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode, linesCount));
            }
            return result;
        }
        static _moveToViewPosition(viewModel, cursor, inSelectionMode, toViewLineNumber, toViewColumn) {
            return cursorCommon_1.CursorState.fromViewState(cursor.viewState.move(inSelectionMode, toViewLineNumber, toViewColumn, 0));
        }
        static _moveToModelPosition(viewModel, cursor, inSelectionMode, toModelLineNumber, toModelColumn) {
            return cursorCommon_1.CursorState.fromModelState(cursor.modelState.move(inSelectionMode, toModelLineNumber, toModelColumn, 0));
        }
        static _moveToViewMinColumn(viewModel, cursors, inSelectionMode) {
            const result = [];
            for (let i = 0, len = cursors.length; i < len; i++) {
                const cursor = cursors[i];
                const viewLineNumber = cursor.viewState.position.lineNumber;
                const viewColumn = viewModel.getLineMinColumn(viewLineNumber);
                result[i] = this._moveToViewPosition(viewModel, cursor, inSelectionMode, viewLineNumber, viewColumn);
            }
            return result;
        }
        static _moveToViewFirstNonWhitespaceColumn(viewModel, cursors, inSelectionMode) {
            const result = [];
            for (let i = 0, len = cursors.length; i < len; i++) {
                const cursor = cursors[i];
                const viewLineNumber = cursor.viewState.position.lineNumber;
                const viewColumn = viewModel.getLineFirstNonWhitespaceColumn(viewLineNumber);
                result[i] = this._moveToViewPosition(viewModel, cursor, inSelectionMode, viewLineNumber, viewColumn);
            }
            return result;
        }
        static _moveToViewCenterColumn(viewModel, cursors, inSelectionMode) {
            const result = [];
            for (let i = 0, len = cursors.length; i < len; i++) {
                const cursor = cursors[i];
                const viewLineNumber = cursor.viewState.position.lineNumber;
                const viewColumn = Math.round((viewModel.getLineMaxColumn(viewLineNumber) + viewModel.getLineMinColumn(viewLineNumber)) / 2);
                result[i] = this._moveToViewPosition(viewModel, cursor, inSelectionMode, viewLineNumber, viewColumn);
            }
            return result;
        }
        static _moveToViewMaxColumn(viewModel, cursors, inSelectionMode) {
            const result = [];
            for (let i = 0, len = cursors.length; i < len; i++) {
                const cursor = cursors[i];
                const viewLineNumber = cursor.viewState.position.lineNumber;
                const viewColumn = viewModel.getLineMaxColumn(viewLineNumber);
                result[i] = this._moveToViewPosition(viewModel, cursor, inSelectionMode, viewLineNumber, viewColumn);
            }
            return result;
        }
        static _moveToViewLastNonWhitespaceColumn(viewModel, cursors, inSelectionMode) {
            const result = [];
            for (let i = 0, len = cursors.length; i < len; i++) {
                const cursor = cursors[i];
                const viewLineNumber = cursor.viewState.position.lineNumber;
                const viewColumn = viewModel.getLineLastNonWhitespaceColumn(viewLineNumber);
                result[i] = this._moveToViewPosition(viewModel, cursor, inSelectionMode, viewLineNumber, viewColumn);
            }
            return result;
        }
    }
    exports.CursorMoveCommands = CursorMoveCommands;
    var CursorMove;
    (function (CursorMove) {
        const isCursorMoveArgs = function (arg) {
            if (!types.isObject(arg)) {
                return false;
            }
            const cursorMoveArg = arg;
            if (!types.isString(cursorMoveArg.to)) {
                return false;
            }
            if (!types.isUndefined(cursorMoveArg.select) && !types.isBoolean(cursorMoveArg.select)) {
                return false;
            }
            if (!types.isUndefined(cursorMoveArg.by) && !types.isString(cursorMoveArg.by)) {
                return false;
            }
            if (!types.isUndefined(cursorMoveArg.value) && !types.isNumber(cursorMoveArg.value)) {
                return false;
            }
            return true;
        };
        CursorMove.metadata = {
            description: 'Move cursor to a logical position in the view',
            args: [
                {
                    name: 'Cursor move argument object',
                    description: `Property-value pairs that can be passed through this argument:
					* 'to': A mandatory logical position value providing where to move the cursor.
						\`\`\`
						'left', 'right', 'up', 'down', 'prevBlankLine', 'nextBlankLine',
						'wrappedLineStart', 'wrappedLineEnd', 'wrappedLineColumnCenter'
						'wrappedLineFirstNonWhitespaceCharacter', 'wrappedLineLastNonWhitespaceCharacter'
						'viewPortTop', 'viewPortCenter', 'viewPortBottom', 'viewPortIfOutside'
						\`\`\`
					* 'by': Unit to move. Default is computed based on 'to' value.
						\`\`\`
						'line', 'wrappedLine', 'character', 'halfLine'
						\`\`\`
					* 'value': Number of units to move. Default is '1'.
					* 'select': If 'true' makes the selection. Default is 'false'.
				`,
                    constraint: isCursorMoveArgs,
                    schema: {
                        'type': 'object',
                        'required': ['to'],
                        'properties': {
                            'to': {
                                'type': 'string',
                                'enum': ['left', 'right', 'up', 'down', 'prevBlankLine', 'nextBlankLine', 'wrappedLineStart', 'wrappedLineEnd', 'wrappedLineColumnCenter', 'wrappedLineFirstNonWhitespaceCharacter', 'wrappedLineLastNonWhitespaceCharacter', 'viewPortTop', 'viewPortCenter', 'viewPortBottom', 'viewPortIfOutside']
                            },
                            'by': {
                                'type': 'string',
                                'enum': ['line', 'wrappedLine', 'character', 'halfLine']
                            },
                            'value': {
                                'type': 'number',
                                'default': 1
                            },
                            'select': {
                                'type': 'boolean',
                                'default': false
                            }
                        }
                    }
                }
            ]
        };
        /**
         * Positions in the view for cursor move command.
         */
        CursorMove.RawDirection = {
            Left: 'left',
            Right: 'right',
            Up: 'up',
            Down: 'down',
            PrevBlankLine: 'prevBlankLine',
            NextBlankLine: 'nextBlankLine',
            WrappedLineStart: 'wrappedLineStart',
            WrappedLineFirstNonWhitespaceCharacter: 'wrappedLineFirstNonWhitespaceCharacter',
            WrappedLineColumnCenter: 'wrappedLineColumnCenter',
            WrappedLineEnd: 'wrappedLineEnd',
            WrappedLineLastNonWhitespaceCharacter: 'wrappedLineLastNonWhitespaceCharacter',
            ViewPortTop: 'viewPortTop',
            ViewPortCenter: 'viewPortCenter',
            ViewPortBottom: 'viewPortBottom',
            ViewPortIfOutside: 'viewPortIfOutside'
        };
        /**
         * Units for Cursor move 'by' argument
         */
        CursorMove.RawUnit = {
            Line: 'line',
            WrappedLine: 'wrappedLine',
            Character: 'character',
            HalfLine: 'halfLine'
        };
        function parse(args) {
            if (!args.to) {
                // illegal arguments
                return null;
            }
            let direction;
            switch (args.to) {
                case CursorMove.RawDirection.Left:
                    direction = 0 /* Direction.Left */;
                    break;
                case CursorMove.RawDirection.Right:
                    direction = 1 /* Direction.Right */;
                    break;
                case CursorMove.RawDirection.Up:
                    direction = 2 /* Direction.Up */;
                    break;
                case CursorMove.RawDirection.Down:
                    direction = 3 /* Direction.Down */;
                    break;
                case CursorMove.RawDirection.PrevBlankLine:
                    direction = 4 /* Direction.PrevBlankLine */;
                    break;
                case CursorMove.RawDirection.NextBlankLine:
                    direction = 5 /* Direction.NextBlankLine */;
                    break;
                case CursorMove.RawDirection.WrappedLineStart:
                    direction = 6 /* Direction.WrappedLineStart */;
                    break;
                case CursorMove.RawDirection.WrappedLineFirstNonWhitespaceCharacter:
                    direction = 7 /* Direction.WrappedLineFirstNonWhitespaceCharacter */;
                    break;
                case CursorMove.RawDirection.WrappedLineColumnCenter:
                    direction = 8 /* Direction.WrappedLineColumnCenter */;
                    break;
                case CursorMove.RawDirection.WrappedLineEnd:
                    direction = 9 /* Direction.WrappedLineEnd */;
                    break;
                case CursorMove.RawDirection.WrappedLineLastNonWhitespaceCharacter:
                    direction = 10 /* Direction.WrappedLineLastNonWhitespaceCharacter */;
                    break;
                case CursorMove.RawDirection.ViewPortTop:
                    direction = 11 /* Direction.ViewPortTop */;
                    break;
                case CursorMove.RawDirection.ViewPortBottom:
                    direction = 13 /* Direction.ViewPortBottom */;
                    break;
                case CursorMove.RawDirection.ViewPortCenter:
                    direction = 12 /* Direction.ViewPortCenter */;
                    break;
                case CursorMove.RawDirection.ViewPortIfOutside:
                    direction = 14 /* Direction.ViewPortIfOutside */;
                    break;
                default:
                    // illegal arguments
                    return null;
            }
            let unit = 0 /* Unit.None */;
            switch (args.by) {
                case CursorMove.RawUnit.Line:
                    unit = 1 /* Unit.Line */;
                    break;
                case CursorMove.RawUnit.WrappedLine:
                    unit = 2 /* Unit.WrappedLine */;
                    break;
                case CursorMove.RawUnit.Character:
                    unit = 3 /* Unit.Character */;
                    break;
                case CursorMove.RawUnit.HalfLine:
                    unit = 4 /* Unit.HalfLine */;
                    break;
            }
            return {
                direction: direction,
                unit: unit,
                select: (!!args.select),
                value: (args.value || 1)
            };
        }
        CursorMove.parse = parse;
    })(CursorMove || (exports.CursorMove = CursorMove = {}));
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[566/*vs/editor/common/cursor/oneCursor*/], __M([1/*require*/,0/*exports*/,76/*vs/editor/common/cursorCommon*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/,23/*vs/editor/common/core/selection*/]), function (require, exports, cursorCommon_1, position_1, range_1, selection_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Cursor = void 0;
    /**
     * Represents a single cursor.
    */
    class Cursor {
        constructor(context) {
            this._selTrackedRange = null;
            this._trackSelection = true;
            this._setState(context, new cursorCommon_1.SingleCursorState(new range_1.Range(1, 1, 1, 1), 0 /* SelectionStartKind.Simple */, 0, new position_1.Position(1, 1), 0), new cursorCommon_1.SingleCursorState(new range_1.Range(1, 1, 1, 1), 0 /* SelectionStartKind.Simple */, 0, new position_1.Position(1, 1), 0));
        }
        dispose(context) {
            this._removeTrackedRange(context);
        }
        startTrackingSelection(context) {
            this._trackSelection = true;
            this._updateTrackedRange(context);
        }
        stopTrackingSelection(context) {
            this._trackSelection = false;
            this._removeTrackedRange(context);
        }
        _updateTrackedRange(context) {
            if (!this._trackSelection) {
                // don't track the selection
                return;
            }
            this._selTrackedRange = context.model._setTrackedRange(this._selTrackedRange, this.modelState.selection, 0 /* TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges */);
        }
        _removeTrackedRange(context) {
            this._selTrackedRange = context.model._setTrackedRange(this._selTrackedRange, null, 0 /* TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges */);
        }
        asCursorState() {
            return new cursorCommon_1.CursorState(this.modelState, this.viewState);
        }
        readSelectionFromMarkers(context) {
            const range = context.model._getTrackedRange(this._selTrackedRange);
            if (this.modelState.selection.isEmpty() && !range.isEmpty()) {
                // Avoid selecting text when recovering from markers
                return selection_1.Selection.fromRange(range.collapseToEnd(), this.modelState.selection.getDirection());
            }
            return selection_1.Selection.fromRange(range, this.modelState.selection.getDirection());
        }
        ensureValidState(context) {
            this._setState(context, this.modelState, this.viewState);
        }
        setState(context, modelState, viewState) {
            this._setState(context, modelState, viewState);
        }
        static _validatePositionWithCache(viewModel, position, cacheInput, cacheOutput) {
            if (position.equals(cacheInput)) {
                return cacheOutput;
            }
            return viewModel.normalizePosition(position, 2 /* PositionAffinity.None */);
        }
        static _validateViewState(viewModel, viewState) {
            const position = viewState.position;
            const sStartPosition = viewState.selectionStart.getStartPosition();
            const sEndPosition = viewState.selectionStart.getEndPosition();
            const validPosition = viewModel.normalizePosition(position, 2 /* PositionAffinity.None */);
            const validSStartPosition = this._validatePositionWithCache(viewModel, sStartPosition, position, validPosition);
            const validSEndPosition = this._validatePositionWithCache(viewModel, sEndPosition, sStartPosition, validSStartPosition);
            if (position.equals(validPosition) && sStartPosition.equals(validSStartPosition) && sEndPosition.equals(validSEndPosition)) {
                // fast path: the state is valid
                return viewState;
            }
            return new cursorCommon_1.SingleCursorState(range_1.Range.fromPositions(validSStartPosition, validSEndPosition), viewState.selectionStartKind, viewState.selectionStartLeftoverVisibleColumns + sStartPosition.column - validSStartPosition.column, validPosition, viewState.leftoverVisibleColumns + position.column - validPosition.column);
        }
        _setState(context, modelState, viewState) {
            if (viewState) {
                viewState = Cursor._validateViewState(context.viewModel, viewState);
            }
            if (!modelState) {
                if (!viewState) {
                    return;
                }
                // We only have the view state => compute the model state
                const selectionStart = context.model.validateRange(context.coordinatesConverter.convertViewRangeToModelRange(viewState.selectionStart));
                const position = context.model.validatePosition(context.coordinatesConverter.convertViewPositionToModelPosition(viewState.position));
                modelState = new cursorCommon_1.SingleCursorState(selectionStart, viewState.selectionStartKind, viewState.selectionStartLeftoverVisibleColumns, position, viewState.leftoverVisibleColumns);
            }
            else {
                // Validate new model state
                const selectionStart = context.model.validateRange(modelState.selectionStart);
                const selectionStartLeftoverVisibleColumns = modelState.selectionStart.equalsRange(selectionStart) ? modelState.selectionStartLeftoverVisibleColumns : 0;
                const position = context.model.validatePosition(modelState.position);
                const leftoverVisibleColumns = modelState.position.equals(position) ? modelState.leftoverVisibleColumns : 0;
                modelState = new cursorCommon_1.SingleCursorState(selectionStart, modelState.selectionStartKind, selectionStartLeftoverVisibleColumns, position, leftoverVisibleColumns);
            }
            if (!viewState) {
                // We only have the model state => compute the view state
                const viewSelectionStart1 = context.coordinatesConverter.convertModelPositionToViewPosition(new position_1.Position(modelState.selectionStart.startLineNumber, modelState.selectionStart.startColumn));
                const viewSelectionStart2 = context.coordinatesConverter.convertModelPositionToViewPosition(new position_1.Position(modelState.selectionStart.endLineNumber, modelState.selectionStart.endColumn));
                const viewSelectionStart = new range_1.Range(viewSelectionStart1.lineNumber, viewSelectionStart1.column, viewSelectionStart2.lineNumber, viewSelectionStart2.column);
                const viewPosition = context.coordinatesConverter.convertModelPositionToViewPosition(modelState.position);
                viewState = new cursorCommon_1.SingleCursorState(viewSelectionStart, modelState.selectionStartKind, modelState.selectionStartLeftoverVisibleColumns, viewPosition, modelState.leftoverVisibleColumns);
            }
            else {
                // Validate new view state
                const viewSelectionStart = context.coordinatesConverter.validateViewRange(viewState.selectionStart, modelState.selectionStart);
                const viewPosition = context.coordinatesConverter.validateViewPosition(viewState.position, modelState.position);
                viewState = new cursorCommon_1.SingleCursorState(viewSelectionStart, modelState.selectionStartKind, modelState.selectionStartLeftoverVisibleColumns, viewPosition, modelState.leftoverVisibleColumns);
            }
            this.modelState = modelState;
            this.viewState = viewState;
            this._updateTrackedRange(context);
        }
    }
    exports.Cursor = Cursor;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[567/*vs/editor/common/cursor/cursorCollection*/], __M([1/*require*/,0/*exports*/,13/*vs/base/common/arrays*/,67/*vs/base/common/arraysFind*/,76/*vs/editor/common/cursorCommon*/,566/*vs/editor/common/cursor/oneCursor*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/,23/*vs/editor/common/core/selection*/]), function (require, exports, arrays_1, arraysFind_1, cursorCommon_1, oneCursor_1, position_1, range_1, selection_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CursorCollection = void 0;
    class CursorCollection {
        constructor(context) {
            this.context = context;
            this.cursors = [new oneCursor_1.Cursor(context)];
            this.lastAddedCursorIndex = 0;
        }
        dispose() {
            for (const cursor of this.cursors) {
                cursor.dispose(this.context);
            }
        }
        startTrackingSelections() {
            for (const cursor of this.cursors) {
                cursor.startTrackingSelection(this.context);
            }
        }
        stopTrackingSelections() {
            for (const cursor of this.cursors) {
                cursor.stopTrackingSelection(this.context);
            }
        }
        updateContext(context) {
            this.context = context;
        }
        ensureValidState() {
            for (const cursor of this.cursors) {
                cursor.ensureValidState(this.context);
            }
        }
        readSelectionFromMarkers() {
            return this.cursors.map(c => c.readSelectionFromMarkers(this.context));
        }
        getAll() {
            return this.cursors.map(c => c.asCursorState());
        }
        getViewPositions() {
            return this.cursors.map(c => c.viewState.position);
        }
        getTopMostViewPosition() {
            return (0, arraysFind_1.findFirstMin)(this.cursors, (0, arrays_1.compareBy)(c => c.viewState.position, position_1.Position.compare)).viewState.position;
        }
        getBottomMostViewPosition() {
            return (0, arraysFind_1.findLastMax)(this.cursors, (0, arrays_1.compareBy)(c => c.viewState.position, position_1.Position.compare)).viewState.position;
        }
        getSelections() {
            return this.cursors.map(c => c.modelState.selection);
        }
        getViewSelections() {
            return this.cursors.map(c => c.viewState.selection);
        }
        setSelections(selections) {
            this.setStates(cursorCommon_1.CursorState.fromModelSelections(selections));
        }
        getPrimaryCursor() {
            return this.cursors[0].asCursorState();
        }
        setStates(states) {
            if (states === null) {
                return;
            }
            this.cursors[0].setState(this.context, states[0].modelState, states[0].viewState);
            this._setSecondaryStates(states.slice(1));
        }
        /**
         * Creates or disposes secondary cursors as necessary to match the number of `secondarySelections`.
         */
        _setSecondaryStates(secondaryStates) {
            const secondaryCursorsLength = this.cursors.length - 1;
            const secondaryStatesLength = secondaryStates.length;
            if (secondaryCursorsLength < secondaryStatesLength) {
                const createCnt = secondaryStatesLength - secondaryCursorsLength;
                for (let i = 0; i < createCnt; i++) {
                    this._addSecondaryCursor();
                }
            }
            else if (secondaryCursorsLength > secondaryStatesLength) {
                const removeCnt = secondaryCursorsLength - secondaryStatesLength;
                for (let i = 0; i < removeCnt; i++) {
                    this._removeSecondaryCursor(this.cursors.length - 2);
                }
            }
            for (let i = 0; i < secondaryStatesLength; i++) {
                this.cursors[i + 1].setState(this.context, secondaryStates[i].modelState, secondaryStates[i].viewState);
            }
        }
        killSecondaryCursors() {
            this._setSecondaryStates([]);
        }
        _addSecondaryCursor() {
            this.cursors.push(new oneCursor_1.Cursor(this.context));
            this.lastAddedCursorIndex = this.cursors.length - 1;
        }
        getLastAddedCursorIndex() {
            if (this.cursors.length === 1 || this.lastAddedCursorIndex === 0) {
                return 0;
            }
            return this.lastAddedCursorIndex;
        }
        _removeSecondaryCursor(removeIndex) {
            if (this.lastAddedCursorIndex >= removeIndex + 1) {
                this.lastAddedCursorIndex--;
            }
            this.cursors[removeIndex + 1].dispose(this.context);
            this.cursors.splice(removeIndex + 1, 1);
        }
        normalize() {
            if (this.cursors.length === 1) {
                return;
            }
            const cursors = this.cursors.slice(0);
            const sortedCursors = [];
            for (let i = 0, len = cursors.length; i < len; i++) {
                sortedCursors.push({
                    index: i,
                    selection: cursors[i].modelState.selection,
                });
            }
            sortedCursors.sort((0, arrays_1.compareBy)(s => s.selection, range_1.Range.compareRangesUsingStarts));
            for (let sortedCursorIndex = 0; sortedCursorIndex < sortedCursors.length - 1; sortedCursorIndex++) {
                const current = sortedCursors[sortedCursorIndex];
                const next = sortedCursors[sortedCursorIndex + 1];
                const currentSelection = current.selection;
                const nextSelection = next.selection;
                if (!this.context.cursorConfig.multiCursorMergeOverlapping) {
                    continue;
                }
                let shouldMergeCursors;
                if (nextSelection.isEmpty() || currentSelection.isEmpty()) {
                    // Merge touching cursors if one of them is collapsed
                    shouldMergeCursors = nextSelection.getStartPosition().isBeforeOrEqual(currentSelection.getEndPosition());
                }
                else {
                    // Merge only overlapping cursors (i.e. allow touching ranges)
                    shouldMergeCursors = nextSelection.getStartPosition().isBefore(currentSelection.getEndPosition());
                }
                if (shouldMergeCursors) {
                    const winnerSortedCursorIndex = current.index < next.index ? sortedCursorIndex : sortedCursorIndex + 1;
                    const looserSortedCursorIndex = current.index < next.index ? sortedCursorIndex + 1 : sortedCursorIndex;
                    const looserIndex = sortedCursors[looserSortedCursorIndex].index;
                    const winnerIndex = sortedCursors[winnerSortedCursorIndex].index;
                    const looserSelection = sortedCursors[looserSortedCursorIndex].selection;
                    const winnerSelection = sortedCursors[winnerSortedCursorIndex].selection;
                    if (!looserSelection.equalsSelection(winnerSelection)) {
                        const resultingRange = looserSelection.plusRange(winnerSelection);
                        const looserSelectionIsLTR = (looserSelection.selectionStartLineNumber === looserSelection.startLineNumber && looserSelection.selectionStartColumn === looserSelection.startColumn);
                        const winnerSelectionIsLTR = (winnerSelection.selectionStartLineNumber === winnerSelection.startLineNumber && winnerSelection.selectionStartColumn === winnerSelection.startColumn);
                        // Give more importance to the last added cursor (think Ctrl-dragging + hitting another cursor)
                        let resultingSelectionIsLTR;
                        if (looserIndex === this.lastAddedCursorIndex) {
                            resultingSelectionIsLTR = looserSelectionIsLTR;
                            this.lastAddedCursorIndex = winnerIndex;
                        }
                        else {
                            // Winner takes it all
                            resultingSelectionIsLTR = winnerSelectionIsLTR;
                        }
                        let resultingSelection;
                        if (resultingSelectionIsLTR) {
                            resultingSelection = new selection_1.Selection(resultingRange.startLineNumber, resultingRange.startColumn, resultingRange.endLineNumber, resultingRange.endColumn);
                        }
                        else {
                            resultingSelection = new selection_1.Selection(resultingRange.endLineNumber, resultingRange.endColumn, resultingRange.startLineNumber, resultingRange.startColumn);
                        }
                        sortedCursors[winnerSortedCursorIndex].selection = resultingSelection;
                        const resultingState = cursorCommon_1.CursorState.fromModelSelection(resultingSelection);
                        cursors[winnerIndex].setState(this.context, resultingState.modelState, resultingState.viewState);
                    }
                    for (const sortedCursor of sortedCursors) {
                        if (sortedCursor.index > looserIndex) {
                            sortedCursor.index--;
                        }
                    }
                    cursors.splice(looserIndex, 1);
                    sortedCursors.splice(looserSortedCursorIndex, 1);
                    this._removeSecondaryCursor(looserIndex - 1);
                    sortedCursorIndex--;
                }
            }
        }
    }
    exports.CursorCollection = CursorCollection;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[568/*vs/editor/common/languages/supports/characterPair*/], __M([1/*require*/,0/*exports*/,131/*vs/editor/common/languages/languageConfiguration*/]), function (require, exports, languageConfiguration_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CharacterPairSupport = void 0;
    class CharacterPairSupport {
        static { this.DEFAULT_AUTOCLOSE_BEFORE_LANGUAGE_DEFINED_QUOTES = ';:.,=}])> \n\t'; }
        static { this.DEFAULT_AUTOCLOSE_BEFORE_LANGUAGE_DEFINED_BRACKETS = '\'"`;:.,=}])> \n\t'; }
        constructor(config) {
            if (config.autoClosingPairs) {
                this._autoClosingPairs = config.autoClosingPairs.map(el => new languageConfiguration_1.StandardAutoClosingPairConditional(el));
            }
            else if (config.brackets) {
                this._autoClosingPairs = config.brackets.map(b => new languageConfiguration_1.StandardAutoClosingPairConditional({ open: b[0], close: b[1] }));
            }
            else {
                this._autoClosingPairs = [];
            }
            if (config.__electricCharacterSupport && config.__electricCharacterSupport.docComment) {
                const docComment = config.__electricCharacterSupport.docComment;
                // IDocComment is legacy, only partially supported
                this._autoClosingPairs.push(new languageConfiguration_1.StandardAutoClosingPairConditional({ open: docComment.open, close: docComment.close || '' }));
            }
            this._autoCloseBeforeForQuotes = typeof config.autoCloseBefore === 'string' ? config.autoCloseBefore : CharacterPairSupport.DEFAULT_AUTOCLOSE_BEFORE_LANGUAGE_DEFINED_QUOTES;
            this._autoCloseBeforeForBrackets = typeof config.autoCloseBefore === 'string' ? config.autoCloseBefore : CharacterPairSupport.DEFAULT_AUTOCLOSE_BEFORE_LANGUAGE_DEFINED_BRACKETS;
            this._surroundingPairs = config.surroundingPairs || this._autoClosingPairs;
        }
        getAutoClosingPairs() {
            return this._autoClosingPairs;
        }
        getAutoCloseBeforeSet(forQuotes) {
            return (forQuotes ? this._autoCloseBeforeForQuotes : this._autoCloseBeforeForBrackets);
        }
        getSurroundingPairs() {
            return this._surroundingPairs;
        }
    }
    exports.CharacterPairSupport = CharacterPairSupport;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[569/*vs/editor/common/languages/supports/indentRules*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.IndentRulesSupport = void 0;
    function resetGlobalRegex(reg) {
        if (reg.global) {
            reg.lastIndex = 0;
        }
        return true;
    }
    class IndentRulesSupport {
        constructor(indentationRules) {
            this._indentationRules = indentationRules;
        }
        shouldIncrease(text) {
            if (this._indentationRules) {
                if (this._indentationRules.increaseIndentPattern && resetGlobalRegex(this._indentationRules.increaseIndentPattern) && this._indentationRules.increaseIndentPattern.test(text)) {
                    return true;
                }
                // if (this._indentationRules.indentNextLinePattern && this._indentationRules.indentNextLinePattern.test(text)) {
                // 	return true;
                // }
            }
            return false;
        }
        shouldDecrease(text) {
            if (this._indentationRules && this._indentationRules.decreaseIndentPattern && resetGlobalRegex(this._indentationRules.decreaseIndentPattern) && this._indentationRules.decreaseIndentPattern.test(text)) {
                return true;
            }
            return false;
        }
        shouldIndentNextLine(text) {
            if (this._indentationRules && this._indentationRules.indentNextLinePattern && resetGlobalRegex(this._indentationRules.indentNextLinePattern) && this._indentationRules.indentNextLinePattern.test(text)) {
                return true;
            }
            return false;
        }
        shouldIgnore(text) {
            // the text matches `unIndentedLinePattern`
            if (this._indentationRules && this._indentationRules.unIndentedLinePattern && resetGlobalRegex(this._indentationRules.unIndentedLinePattern) && this._indentationRules.unIndentedLinePattern.test(text)) {
                return true;
            }
            return false;
        }
        getIndentMetadata(text) {
            let ret = 0;
            if (this.shouldIncrease(text)) {
                ret += 1 /* IndentConsts.INCREASE_MASK */;
            }
            if (this.shouldDecrease(text)) {
                ret += 2 /* IndentConsts.DECREASE_MASK */;
            }
            if (this.shouldIndentNextLine(text)) {
                ret += 4 /* IndentConsts.INDENT_NEXTLINE_MASK */;
            }
            if (this.shouldIgnore(text)) {
                ret += 8 /* IndentConsts.UNINDENT_MASK */;
            }
            return ret;
        }
    }
    exports.IndentRulesSupport = IndentRulesSupport;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[570/*vs/editor/common/languages/supports/inplaceReplaceSupport*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.BasicInplaceReplace = void 0;
    class BasicInplaceReplace {
        constructor() {
            this._defaultValueSet = [
                ['true', 'false'],
                ['True', 'False'],
                ['Private', 'Public', 'Friend', 'ReadOnly', 'Partial', 'Protected', 'WriteOnly'],
                ['public', 'protected', 'private'],
            ];
        }
        static { this.INSTANCE = new BasicInplaceReplace(); }
        navigateValueSet(range1, text1, range2, text2, up) {
            if (range1 && text1) {
                const result = this.doNavigateValueSet(text1, up);
                if (result) {
                    return {
                        range: range1,
                        value: result
                    };
                }
            }
            if (range2 && text2) {
                const result = this.doNavigateValueSet(text2, up);
                if (result) {
                    return {
                        range: range2,
                        value: result
                    };
                }
            }
            return null;
        }
        doNavigateValueSet(text, up) {
            const numberResult = this.numberReplace(text, up);
            if (numberResult !== null) {
                return numberResult;
            }
            return this.textReplace(text, up);
        }
        numberReplace(value, up) {
            const precision = Math.pow(10, value.length - (value.lastIndexOf('.') + 1));
            let n1 = Number(value);
            const n2 = parseFloat(value);
            if (!isNaN(n1) && !isNaN(n2) && n1 === n2) {
                if (n1 === 0 && !up) {
                    return null; // don't do negative
                    //			} else if(n1 === 9 && up) {
                    //				return null; // don't insert 10 into a number
                }
                else {
                    n1 = Math.floor(n1 * precision);
                    n1 += up ? precision : -precision;
                    return String(n1 / precision);
                }
            }
            return null;
        }
        textReplace(value, up) {
            return this.valueSetsReplace(this._defaultValueSet, value, up);
        }
        valueSetsReplace(valueSets, value, up) {
            let result = null;
            for (let i = 0, len = valueSets.length; result === null && i < len; i++) {
                result = this.valueSetReplace(valueSets[i], value, up);
            }
            return result;
        }
        valueSetReplace(valueSet, value, up) {
            let idx = valueSet.indexOf(value);
            if (idx >= 0) {
                idx += up ? +1 : -1;
                if (idx < 0) {
                    idx = valueSet.length - 1;
                }
                else {
                    idx %= valueSet.length;
                }
                return valueSet[idx];
            }
            return null;
        }
    }
    exports.BasicInplaceReplace = BasicInplaceReplace;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[571/*vs/editor/common/languages/supports/onEnter*/], __M([1/*require*/,0/*exports*/,8/*vs/base/common/errors*/,11/*vs/base/common/strings*/,131/*vs/editor/common/languages/languageConfiguration*/]), function (require, exports, errors_1, strings, languageConfiguration_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.OnEnterSupport = void 0;
    class OnEnterSupport {
        constructor(opts) {
            opts = opts || {};
            opts.brackets = opts.brackets || [
                ['(', ')'],
                ['{', '}'],
                ['[', ']']
            ];
            this._brackets = [];
            opts.brackets.forEach((bracket) => {
                const openRegExp = OnEnterSupport._createOpenBracketRegExp(bracket[0]);
                const closeRegExp = OnEnterSupport._createCloseBracketRegExp(bracket[1]);
                if (openRegExp && closeRegExp) {
                    this._brackets.push({
                        open: bracket[0],
                        openRegExp: openRegExp,
                        close: bracket[1],
                        closeRegExp: closeRegExp,
                    });
                }
            });
            this._regExpRules = opts.onEnterRules || [];
        }
        onEnter(autoIndent, previousLineText, beforeEnterText, afterEnterText) {
            // (1): `regExpRules`
            if (autoIndent >= 3 /* EditorAutoIndentStrategy.Advanced */) {
                for (let i = 0, len = this._regExpRules.length; i < len; i++) {
                    const rule = this._regExpRules[i];
                    const regResult = [{
                            reg: rule.beforeText,
                            text: beforeEnterText
                        }, {
                            reg: rule.afterText,
                            text: afterEnterText
                        }, {
                            reg: rule.previousLineText,
                            text: previousLineText
                        }].every((obj) => {
                        if (!obj.reg) {
                            return true;
                        }
                        obj.reg.lastIndex = 0; // To disable the effect of the "g" flag.
                        return obj.reg.test(obj.text);
                    });
                    if (regResult) {
                        return rule.action;
                    }
                }
            }
            // (2): Special indent-outdent
            if (autoIndent >= 2 /* EditorAutoIndentStrategy.Brackets */) {
                if (beforeEnterText.length > 0 && afterEnterText.length > 0) {
                    for (let i = 0, len = this._brackets.length; i < len; i++) {
                        const bracket = this._brackets[i];
                        if (bracket.openRegExp.test(beforeEnterText) && bracket.closeRegExp.test(afterEnterText)) {
                            return { indentAction: languageConfiguration_1.IndentAction.IndentOutdent };
                        }
                    }
                }
            }
            // (4): Open bracket based logic
            if (autoIndent >= 2 /* EditorAutoIndentStrategy.Brackets */) {
                if (beforeEnterText.length > 0) {
                    for (let i = 0, len = this._brackets.length; i < len; i++) {
                        const bracket = this._brackets[i];
                        if (bracket.openRegExp.test(beforeEnterText)) {
                            return { indentAction: languageConfiguration_1.IndentAction.Indent };
                        }
                    }
                }
            }
            return null;
        }
        static _createOpenBracketRegExp(bracket) {
            let str = strings.escapeRegExpCharacters(bracket);
            if (!/\B/.test(str.charAt(0))) {
                str = '\\b' + str;
            }
            str += '\\s*$';
            return OnEnterSupport._safeRegExp(str);
        }
        static _createCloseBracketRegExp(bracket) {
            let str = strings.escapeRegExpCharacters(bracket);
            if (!/\B/.test(str.charAt(str.length - 1))) {
                str = str + '\\b';
            }
            str = '^\\s*' + str;
            return OnEnterSupport._safeRegExp(str);
        }
        static _safeRegExp(def) {
            try {
                return new RegExp(def);
            }
            catch (err) {
                (0, errors_1.onUnexpectedError)(err);
                return null;
            }
        }
    }
    exports.OnEnterSupport = OnEnterSupport;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[572/*vs/editor/common/languages/supports/tokenization*/], __M([1/*require*/,0/*exports*/,33/*vs/base/common/color*/]), function (require, exports, color_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ThemeTrieElement = exports.ThemeTrieElementRule = exports.TokenTheme = exports.ColorMap = exports.ParsedTokenThemeRule = void 0;
    exports.parseTokenTheme = parseTokenTheme;
    exports.toStandardTokenType = toStandardTokenType;
    exports.strcmp = strcmp;
    exports.generateTokensCSSForColorMap = generateTokensCSSForColorMap;
    class ParsedTokenThemeRule {
        constructor(token, index, fontStyle, foreground, background) {
            this._parsedThemeRuleBrand = undefined;
            this.token = token;
            this.index = index;
            this.fontStyle = fontStyle;
            this.foreground = foreground;
            this.background = background;
        }
    }
    exports.ParsedTokenThemeRule = ParsedTokenThemeRule;
    /**
     * Parse a raw theme into rules.
     */
    function parseTokenTheme(source) {
        if (!source || !Array.isArray(source)) {
            return [];
        }
        const result = [];
        let resultLen = 0;
        for (let i = 0, len = source.length; i < len; i++) {
            const entry = source[i];
            let fontStyle = -1 /* FontStyle.NotSet */;
            if (typeof entry.fontStyle === 'string') {
                fontStyle = 0 /* FontStyle.None */;
                const segments = entry.fontStyle.split(' ');
                for (let j = 0, lenJ = segments.length; j < lenJ; j++) {
                    const segment = segments[j];
                    switch (segment) {
                        case 'italic':
                            fontStyle = fontStyle | 1 /* FontStyle.Italic */;
                            break;
                        case 'bold':
                            fontStyle = fontStyle | 2 /* FontStyle.Bold */;
                            break;
                        case 'underline':
                            fontStyle = fontStyle | 4 /* FontStyle.Underline */;
                            break;
                        case 'strikethrough':
                            fontStyle = fontStyle | 8 /* FontStyle.Strikethrough */;
                            break;
                    }
                }
            }
            let foreground = null;
            if (typeof entry.foreground === 'string') {
                foreground = entry.foreground;
            }
            let background = null;
            if (typeof entry.background === 'string') {
                background = entry.background;
            }
            result[resultLen++] = new ParsedTokenThemeRule(entry.token || '', i, fontStyle, foreground, background);
        }
        return result;
    }
    /**
     * Resolve rules (i.e. inheritance).
     */
    function resolveParsedTokenThemeRules(parsedThemeRules, customTokenColors) {
        // Sort rules lexicographically, and then by index if necessary
        parsedThemeRules.sort((a, b) => {
            const r = strcmp(a.token, b.token);
            if (r !== 0) {
                return r;
            }
            return a.index - b.index;
        });
        // Determine defaults
        let defaultFontStyle = 0 /* FontStyle.None */;
        let defaultForeground = '000000';
        let defaultBackground = 'ffffff';
        while (parsedThemeRules.length >= 1 && parsedThemeRules[0].token === '') {
            const incomingDefaults = parsedThemeRules.shift();
            if (incomingDefaults.fontStyle !== -1 /* FontStyle.NotSet */) {
                defaultFontStyle = incomingDefaults.fontStyle;
            }
            if (incomingDefaults.foreground !== null) {
                defaultForeground = incomingDefaults.foreground;
            }
            if (incomingDefaults.background !== null) {
                defaultBackground = incomingDefaults.background;
            }
        }
        const colorMap = new ColorMap();
        // start with token colors from custom token themes
        for (const color of customTokenColors) {
            colorMap.getId(color);
        }
        const foregroundColorId = colorMap.getId(defaultForeground);
        const backgroundColorId = colorMap.getId(defaultBackground);
        const defaults = new ThemeTrieElementRule(defaultFontStyle, foregroundColorId, backgroundColorId);
        const root = new ThemeTrieElement(defaults);
        for (let i = 0, len = parsedThemeRules.length; i < len; i++) {
            const rule = parsedThemeRules[i];
            root.insert(rule.token, rule.fontStyle, colorMap.getId(rule.foreground), colorMap.getId(rule.background));
        }
        return new TokenTheme(colorMap, root);
    }
    const colorRegExp = /^#?([0-9A-Fa-f]{6})([0-9A-Fa-f]{2})?$/;
    class ColorMap {
        constructor() {
            this._lastColorId = 0;
            this._id2color = [];
            this._color2id = new Map();
        }
        getId(color) {
            if (color === null) {
                return 0;
            }
            const match = color.match(colorRegExp);
            if (!match) {
                throw new Error('Illegal value for token color: ' + color);
            }
            color = match[1].toUpperCase();
            let value = this._color2id.get(color);
            if (value) {
                return value;
            }
            value = ++this._lastColorId;
            this._color2id.set(color, value);
            this._id2color[value] = color_1.Color.fromHex('#' + color);
            return value;
        }
        getColorMap() {
            return this._id2color.slice(0);
        }
    }
    exports.ColorMap = ColorMap;
    class TokenTheme {
        static createFromRawTokenTheme(source, customTokenColors) {
            return this.createFromParsedTokenTheme(parseTokenTheme(source), customTokenColors);
        }
        static createFromParsedTokenTheme(source, customTokenColors) {
            return resolveParsedTokenThemeRules(source, customTokenColors);
        }
        constructor(colorMap, root) {
            this._colorMap = colorMap;
            this._root = root;
            this._cache = new Map();
        }
        getColorMap() {
            return this._colorMap.getColorMap();
        }
        _match(token) {
            return this._root.match(token);
        }
        match(languageId, token) {
            // The cache contains the metadata without the language bits set.
            let result = this._cache.get(token);
            if (typeof result === 'undefined') {
                const rule = this._match(token);
                const standardToken = toStandardTokenType(token);
                result = (rule.metadata
                    | (standardToken << 8 /* MetadataConsts.TOKEN_TYPE_OFFSET */)) >>> 0;
                this._cache.set(token, result);
            }
            return (result
                | (languageId << 0 /* MetadataConsts.LANGUAGEID_OFFSET */)) >>> 0;
        }
    }
    exports.TokenTheme = TokenTheme;
    const STANDARD_TOKEN_TYPE_REGEXP = /\b(comment|string|regex|regexp)\b/;
    function toStandardTokenType(tokenType) {
        const m = tokenType.match(STANDARD_TOKEN_TYPE_REGEXP);
        if (!m) {
            return 0 /* StandardTokenType.Other */;
        }
        switch (m[1]) {
            case 'comment':
                return 1 /* StandardTokenType.Comment */;
            case 'string':
                return 2 /* StandardTokenType.String */;
            case 'regex':
                return 3 /* StandardTokenType.RegEx */;
            case 'regexp':
                return 3 /* StandardTokenType.RegEx */;
        }
        throw new Error('Unexpected match for standard token type!');
    }
    function strcmp(a, b) {
        if (a < b) {
            return -1;
        }
        if (a > b) {
            return 1;
        }
        return 0;
    }
    class ThemeTrieElementRule {
        constructor(fontStyle, foreground, background) {
            this._themeTrieElementRuleBrand = undefined;
            this._fontStyle = fontStyle;
            this._foreground = foreground;
            this._background = background;
            this.metadata = ((this._fontStyle << 11 /* MetadataConsts.FONT_STYLE_OFFSET */)
                | (this._foreground << 15 /* MetadataConsts.FOREGROUND_OFFSET */)
                | (this._background << 24 /* MetadataConsts.BACKGROUND_OFFSET */)) >>> 0;
        }
        clone() {
            return new ThemeTrieElementRule(this._fontStyle, this._foreground, this._background);
        }
        acceptOverwrite(fontStyle, foreground, background) {
            if (fontStyle !== -1 /* FontStyle.NotSet */) {
                this._fontStyle = fontStyle;
            }
            if (foreground !== 0 /* ColorId.None */) {
                this._foreground = foreground;
            }
            if (background !== 0 /* ColorId.None */) {
                this._background = background;
            }
            this.metadata = ((this._fontStyle << 11 /* MetadataConsts.FONT_STYLE_OFFSET */)
                | (this._foreground << 15 /* MetadataConsts.FOREGROUND_OFFSET */)
                | (this._background << 24 /* MetadataConsts.BACKGROUND_OFFSET */)) >>> 0;
        }
    }
    exports.ThemeTrieElementRule = ThemeTrieElementRule;
    class ThemeTrieElement {
        constructor(mainRule) {
            this._themeTrieElementBrand = undefined;
            this._mainRule = mainRule;
            this._children = new Map();
        }
        match(token) {
            if (token === '') {
                return this._mainRule;
            }
            const dotIndex = token.indexOf('.');
            let head;
            let tail;
            if (dotIndex === -1) {
                head = token;
                tail = '';
            }
            else {
                head = token.substring(0, dotIndex);
                tail = token.substring(dotIndex + 1);
            }
            const child = this._children.get(head);
            if (typeof child !== 'undefined') {
                return child.match(tail);
            }
            return this._mainRule;
        }
        insert(token, fontStyle, foreground, background) {
            if (token === '') {
                // Merge into the main rule
                this._mainRule.acceptOverwrite(fontStyle, foreground, background);
                return;
            }
            const dotIndex = token.indexOf('.');
            let head;
            let tail;
            if (dotIndex === -1) {
                head = token;
                tail = '';
            }
            else {
                head = token.substring(0, dotIndex);
                tail = token.substring(dotIndex + 1);
            }
            let child = this._children.get(head);
            if (typeof child === 'undefined') {
                child = new ThemeTrieElement(this._mainRule.clone());
                this._children.set(head, child);
            }
            child.insert(tail, fontStyle, foreground, background);
        }
    }
    exports.ThemeTrieElement = ThemeTrieElement;
    function generateTokensCSSForColorMap(colorMap) {
        const rules = [];
        for (let i = 1, len = colorMap.length; i < len; i++) {
            const color = colorMap[i];
            rules[i] = `.mtk${i} { color: ${color}; }`;
        }
        rules.push('.mtki { font-style: italic; }');
        rules.push('.mtkb { font-weight: bold; }');
        rules.push('.mtku { text-decoration: underline; text-underline-position: under; }');
        rules.push('.mtks { text-decoration: line-through; }');
        rules.push('.mtks.mtku { text-decoration: underline line-through; text-underline-position: under; }');
        return rules.join('\n');
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[40/*vs/editor/common/model*/], __M([1/*require*/,0/*exports*/,60/*vs/base/common/objects*/]), function (require, exports, objects_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ApplyEditsResult = exports.SearchData = exports.ValidAnnotatedEditOperation = exports.FindMatch = exports.TextModelResolvedOptions = exports.InjectedTextCursorStops = exports.GlyphMarginLane = exports.OverviewRulerLane = void 0;
    exports.isITextSnapshot = isITextSnapshot;
    exports.shouldSynchronizeModel = shouldSynchronizeModel;
    /**
     * Vertical Lane in the overview ruler of the editor.
     */
    var OverviewRulerLane;
    (function (OverviewRulerLane) {
        OverviewRulerLane[OverviewRulerLane["Left"] = 1] = "Left";
        OverviewRulerLane[OverviewRulerLane["Center"] = 2] = "Center";
        OverviewRulerLane[OverviewRulerLane["Right"] = 4] = "Right";
        OverviewRulerLane[OverviewRulerLane["Full"] = 7] = "Full";
    })(OverviewRulerLane || (exports.OverviewRulerLane = OverviewRulerLane = {}));
    /**
     * Vertical Lane in the glyph margin of the editor.
     */
    var GlyphMarginLane;
    (function (GlyphMarginLane) {
        GlyphMarginLane[GlyphMarginLane["Left"] = 1] = "Left";
        GlyphMarginLane[GlyphMarginLane["Center"] = 2] = "Center";
        GlyphMarginLane[GlyphMarginLane["Right"] = 3] = "Right";
    })(GlyphMarginLane || (exports.GlyphMarginLane = GlyphMarginLane = {}));
    var InjectedTextCursorStops;
    (function (InjectedTextCursorStops) {
        InjectedTextCursorStops[InjectedTextCursorStops["Both"] = 0] = "Both";
        InjectedTextCursorStops[InjectedTextCursorStops["Right"] = 1] = "Right";
        InjectedTextCursorStops[InjectedTextCursorStops["Left"] = 2] = "Left";
        InjectedTextCursorStops[InjectedTextCursorStops["None"] = 3] = "None";
    })(InjectedTextCursorStops || (exports.InjectedTextCursorStops = InjectedTextCursorStops = {}));
    class TextModelResolvedOptions {
        get originalIndentSize() {
            return this._indentSizeIsTabSize ? 'tabSize' : this.indentSize;
        }
        /**
         * @internal
         */
        constructor(src) {
            this._textModelResolvedOptionsBrand = undefined;
            this.tabSize = Math.max(1, src.tabSize | 0);
            if (src.indentSize === 'tabSize') {
                this.indentSize = this.tabSize;
                this._indentSizeIsTabSize = true;
            }
            else {
                this.indentSize = Math.max(1, src.indentSize | 0);
                this._indentSizeIsTabSize = false;
            }
            this.insertSpaces = Boolean(src.insertSpaces);
            this.defaultEOL = src.defaultEOL | 0;
            this.trimAutoWhitespace = Boolean(src.trimAutoWhitespace);
            this.bracketPairColorizationOptions = src.bracketPairColorizationOptions;
        }
        /**
         * @internal
         */
        equals(other) {
            return (this.tabSize === other.tabSize
                && this._indentSizeIsTabSize === other._indentSizeIsTabSize
                && this.indentSize === other.indentSize
                && this.insertSpaces === other.insertSpaces
                && this.defaultEOL === other.defaultEOL
                && this.trimAutoWhitespace === other.trimAutoWhitespace
                && (0, objects_1.equals)(this.bracketPairColorizationOptions, other.bracketPairColorizationOptions));
        }
        /**
         * @internal
         */
        createChangeEvent(newOpts) {
            return {
                tabSize: this.tabSize !== newOpts.tabSize,
                indentSize: this.indentSize !== newOpts.indentSize,
                insertSpaces: this.insertSpaces !== newOpts.insertSpaces,
                trimAutoWhitespace: this.trimAutoWhitespace !== newOpts.trimAutoWhitespace,
            };
        }
    }
    exports.TextModelResolvedOptions = TextModelResolvedOptions;
    class FindMatch {
        /**
         * @internal
         */
        constructor(range, matches) {
            this._findMatchBrand = undefined;
            this.range = range;
            this.matches = matches;
        }
    }
    exports.FindMatch = FindMatch;
    /**
     * @internal
     */
    function isITextSnapshot(obj) {
        return (obj && typeof obj.read === 'function');
    }
    /**
     * @internal
     */
    class ValidAnnotatedEditOperation {
        constructor(identifier, range, text, forceMoveMarkers, isAutoWhitespaceEdit, _isTracked) {
            this.identifier = identifier;
            this.range = range;
            this.text = text;
            this.forceMoveMarkers = forceMoveMarkers;
            this.isAutoWhitespaceEdit = isAutoWhitespaceEdit;
            this._isTracked = _isTracked;
        }
    }
    exports.ValidAnnotatedEditOperation = ValidAnnotatedEditOperation;
    /**
     * @internal
     */
    class SearchData {
        constructor(regex, wordSeparators, simpleSearch) {
            this.regex = regex;
            this.wordSeparators = wordSeparators;
            this.simpleSearch = simpleSearch;
        }
    }
    exports.SearchData = SearchData;
    /**
     * @internal
     */
    class ApplyEditsResult {
        constructor(reverseEdits, changes, trimAutoWhitespaceLineNumbers) {
            this.reverseEdits = reverseEdits;
            this.changes = changes;
            this.trimAutoWhitespaceLineNumbers = trimAutoWhitespaceLineNumbers;
        }
    }
    exports.ApplyEditsResult = ApplyEditsResult;
    /**
     * @internal
     */
    function shouldSynchronizeModel(model) {
        return (!model.isTooLargeForSyncing() && !model.isForSimpleWidget);
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[106/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/length*/], __M([1/*require*/,0/*exports*/,11/*vs/base/common/strings*/,4/*vs/editor/common/core/range*/,113/*vs/editor/common/core/textLength*/]), function (require, exports, strings_1, range_1, textLength_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.lengthZero = void 0;
    exports.lengthDiff = lengthDiff;
    exports.lengthIsZero = lengthIsZero;
    exports.toLength = toLength;
    exports.lengthToObj = lengthToObj;
    exports.lengthGetLineCount = lengthGetLineCount;
    exports.lengthGetColumnCountIfZeroLineCount = lengthGetColumnCountIfZeroLineCount;
    exports.lengthAdd = lengthAdd;
    exports.sumLengths = sumLengths;
    exports.lengthEquals = lengthEquals;
    exports.lengthDiffNonNegative = lengthDiffNonNegative;
    exports.lengthLessThan = lengthLessThan;
    exports.lengthLessThanEqual = lengthLessThanEqual;
    exports.lengthGreaterThanEqual = lengthGreaterThanEqual;
    exports.positionToLength = positionToLength;
    exports.lengthsToRange = lengthsToRange;
    exports.lengthOfString = lengthOfString;
    /**
     * The end must be greater than or equal to the start.
    */
    function lengthDiff(startLineCount, startColumnCount, endLineCount, endColumnCount) {
        return (startLineCount !== endLineCount)
            ? toLength(endLineCount - startLineCount, endColumnCount)
            : toLength(0, endColumnCount - startColumnCount);
    }
    exports.lengthZero = 0;
    function lengthIsZero(length) {
        return length === 0;
    }
    /*
     * We have 52 bits available in a JS number.
     * We use the upper 26 bits to store the line and the lower 26 bits to store the column.
     */
    ///*
    const factor = 2 ** 26;
    /*/
    const factor = 1000000;
    // */
    function toLength(lineCount, columnCount) {
        // llllllllllllllllllllllllllcccccccccccccccccccccccccc (52 bits)
        //       line count (26 bits)    column count (26 bits)
        // If there is no overflow (all values/sums below 2^26 = 67108864),
        // we have `toLength(lns1, cols1) + toLength(lns2, cols2) = toLength(lns1 + lns2, cols1 + cols2)`.
        return (lineCount * factor + columnCount);
    }
    function lengthToObj(length) {
        const l = length;
        const lineCount = Math.floor(l / factor);
        const columnCount = l - lineCount * factor;
        return new textLength_1.TextLength(lineCount, columnCount);
    }
    function lengthGetLineCount(length) {
        return Math.floor(length / factor);
    }
    /**
     * Returns the amount of columns of the given length, assuming that it does not span any line.
    */
    function lengthGetColumnCountIfZeroLineCount(length) {
        return length;
    }
    function lengthAdd(l1, l2) {
        let r = l1 + l2;
        if (l2 >= factor) {
            r = r - (l1 % factor);
        }
        return r;
    }
    function sumLengths(items, lengthFn) {
        return items.reduce((a, b) => lengthAdd(a, lengthFn(b)), exports.lengthZero);
    }
    function lengthEquals(length1, length2) {
        return length1 === length2;
    }
    /**
     * Returns a non negative length `result` such that `lengthAdd(length1, result) = length2`, or zero if such length does not exist.
     */
    function lengthDiffNonNegative(length1, length2) {
        const l1 = length1;
        const l2 = length2;
        const diff = l2 - l1;
        if (diff <= 0) {
            // line-count of length1 is higher than line-count of length2
            // or they are equal and column-count of length1 is higher than column-count of length2
            return exports.lengthZero;
        }
        const lineCount1 = Math.floor(l1 / factor);
        const lineCount2 = Math.floor(l2 / factor);
        const colCount2 = l2 - lineCount2 * factor;
        if (lineCount1 === lineCount2) {
            const colCount1 = l1 - lineCount1 * factor;
            return toLength(0, colCount2 - colCount1);
        }
        else {
            return toLength(lineCount2 - lineCount1, colCount2);
        }
    }
    function lengthLessThan(length1, length2) {
        // First, compare line counts, then column counts.
        return length1 < length2;
    }
    function lengthLessThanEqual(length1, length2) {
        return length1 <= length2;
    }
    function lengthGreaterThanEqual(length1, length2) {
        return length1 >= length2;
    }
    function positionToLength(position) {
        return toLength(position.lineNumber - 1, position.column - 1);
    }
    function lengthsToRange(lengthStart, lengthEnd) {
        const l = lengthStart;
        const lineCount = Math.floor(l / factor);
        const colCount = l - lineCount * factor;
        const l2 = lengthEnd;
        const lineCount2 = Math.floor(l2 / factor);
        const colCount2 = l2 - lineCount2 * factor;
        return new range_1.Range(lineCount + 1, colCount + 1, lineCount2 + 1, colCount2 + 1);
    }
    function lengthOfString(str) {
        const lines = (0, strings_1.splitLines)(str);
        return toLength(lines.length - 1, lines[lines.length - 1].length);
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[200/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/beforeEditPositionMapper*/], __M([1/*require*/,0/*exports*/,4/*vs/editor/common/core/range*/,106/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/length*/]), function (require, exports, range_1, length_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.BeforeEditPositionMapper = exports.TextEditInfo = void 0;
    class TextEditInfo {
        static fromModelContentChanges(changes) {
            // Must be sorted in ascending order
            const edits = changes.map(c => {
                const range = range_1.Range.lift(c.range);
                return new TextEditInfo((0, length_1.positionToLength)(range.getStartPosition()), (0, length_1.positionToLength)(range.getEndPosition()), (0, length_1.lengthOfString)(c.text));
            }).reverse();
            return edits;
        }
        constructor(startOffset, endOffset, newLength) {
            this.startOffset = startOffset;
            this.endOffset = endOffset;
            this.newLength = newLength;
        }
        toString() {
            return `[${(0, length_1.lengthToObj)(this.startOffset)}...${(0, length_1.lengthToObj)(this.endOffset)}) -> ${(0, length_1.lengthToObj)(this.newLength)}`;
        }
    }
    exports.TextEditInfo = TextEditInfo;
    class BeforeEditPositionMapper {
        /**
         * @param edits Must be sorted by offset in ascending order.
        */
        constructor(edits) {
            this.nextEditIdx = 0;
            this.deltaOldToNewLineCount = 0;
            this.deltaOldToNewColumnCount = 0;
            this.deltaLineIdxInOld = -1;
            this.edits = edits.map(edit => TextEditInfoCache.from(edit));
        }
        /**
         * @param offset Must be equal to or greater than the last offset this method has been called with.
        */
        getOffsetBeforeChange(offset) {
            this.adjustNextEdit(offset);
            return this.translateCurToOld(offset);
        }
        /**
         * @param offset Must be equal to or greater than the last offset this method has been called with.
         * Returns null if there is no edit anymore.
        */
        getDistanceToNextChange(offset) {
            this.adjustNextEdit(offset);
            const nextEdit = this.edits[this.nextEditIdx];
            const nextChangeOffset = nextEdit ? this.translateOldToCur(nextEdit.offsetObj) : null;
            if (nextChangeOffset === null) {
                return null;
            }
            return (0, length_1.lengthDiffNonNegative)(offset, nextChangeOffset);
        }
        translateOldToCur(oldOffsetObj) {
            if (oldOffsetObj.lineCount === this.deltaLineIdxInOld) {
                return (0, length_1.toLength)(oldOffsetObj.lineCount + this.deltaOldToNewLineCount, oldOffsetObj.columnCount + this.deltaOldToNewColumnCount);
            }
            else {
                return (0, length_1.toLength)(oldOffsetObj.lineCount + this.deltaOldToNewLineCount, oldOffsetObj.columnCount);
            }
        }
        translateCurToOld(newOffset) {
            const offsetObj = (0, length_1.lengthToObj)(newOffset);
            if (offsetObj.lineCount - this.deltaOldToNewLineCount === this.deltaLineIdxInOld) {
                return (0, length_1.toLength)(offsetObj.lineCount - this.deltaOldToNewLineCount, offsetObj.columnCount - this.deltaOldToNewColumnCount);
            }
            else {
                return (0, length_1.toLength)(offsetObj.lineCount - this.deltaOldToNewLineCount, offsetObj.columnCount);
            }
        }
        adjustNextEdit(offset) {
            while (this.nextEditIdx < this.edits.length) {
                const nextEdit = this.edits[this.nextEditIdx];
                // After applying the edit, what is its end offset (considering all previous edits)?
                const nextEditEndOffsetInCur = this.translateOldToCur(nextEdit.endOffsetAfterObj);
                if ((0, length_1.lengthLessThanEqual)(nextEditEndOffsetInCur, offset)) {
                    // We are after the edit, skip it
                    this.nextEditIdx++;
                    const nextEditEndOffsetInCurObj = (0, length_1.lengthToObj)(nextEditEndOffsetInCur);
                    // Before applying the edit, what is its end offset (considering all previous edits)?
                    const nextEditEndOffsetBeforeInCurObj = (0, length_1.lengthToObj)(this.translateOldToCur(nextEdit.endOffsetBeforeObj));
                    const lineDelta = nextEditEndOffsetInCurObj.lineCount - nextEditEndOffsetBeforeInCurObj.lineCount;
                    this.deltaOldToNewLineCount += lineDelta;
                    const previousColumnDelta = this.deltaLineIdxInOld === nextEdit.endOffsetBeforeObj.lineCount ? this.deltaOldToNewColumnCount : 0;
                    const columnDelta = nextEditEndOffsetInCurObj.columnCount - nextEditEndOffsetBeforeInCurObj.columnCount;
                    this.deltaOldToNewColumnCount = previousColumnDelta + columnDelta;
                    this.deltaLineIdxInOld = nextEdit.endOffsetBeforeObj.lineCount;
                }
                else {
                    // We are in or before the edit.
                    break;
                }
            }
        }
    }
    exports.BeforeEditPositionMapper = BeforeEditPositionMapper;
    class TextEditInfoCache {
        static from(edit) {
            return new TextEditInfoCache(edit.startOffset, edit.endOffset, edit.newLength);
        }
        constructor(startOffset, endOffset, textLength) {
            this.endOffsetBeforeObj = (0, length_1.lengthToObj)(endOffset);
            this.endOffsetAfterObj = (0, length_1.lengthToObj)((0, length_1.lengthAdd)(startOffset, textLength));
            this.offsetObj = (0, length_1.lengthToObj)(startOffset);
        }
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[319/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/combineTextEditInfos*/], __M([1/*require*/,0/*exports*/,13/*vs/base/common/arrays*/,200/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/beforeEditPositionMapper*/,106/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/length*/]), function (require, exports, arrays_1, beforeEditPositionMapper_1, length_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.combineTextEditInfos = combineTextEditInfos;
    function combineTextEditInfos(textEditInfoFirst, textEditInfoSecond) {
        if (textEditInfoFirst.length === 0) {
            return textEditInfoSecond;
        }
        if (textEditInfoSecond.length === 0) {
            return textEditInfoFirst;
        }
        // s0: State before any edits
        const s0ToS1Map = new arrays_1.ArrayQueue(toLengthMapping(textEditInfoFirst));
        // s1: State after first edit, but before second edit
        const s1ToS2Map = toLengthMapping(textEditInfoSecond);
        s1ToS2Map.push({ modified: false, lengthBefore: undefined, lengthAfter: undefined }); // Copy everything from old to new
        // s2: State after both edits
        let curItem = s0ToS1Map.dequeue();
        /**
         * @param s1Length Use undefined for length "infinity"
         */
        function nextS0ToS1MapWithS1LengthOf(s1Length) {
            if (s1Length === undefined) {
                const arr = s0ToS1Map.takeWhile(v => true) || [];
                if (curItem) {
                    arr.unshift(curItem);
                }
                return arr;
            }
            const result = [];
            while (curItem && !(0, length_1.lengthIsZero)(s1Length)) {
                const [item, remainingItem] = curItem.splitAt(s1Length);
                result.push(item);
                s1Length = (0, length_1.lengthDiffNonNegative)(item.lengthAfter, s1Length);
                curItem = remainingItem ?? s0ToS1Map.dequeue();
            }
            if (!(0, length_1.lengthIsZero)(s1Length)) {
                result.push(new LengthMapping(false, s1Length, s1Length));
            }
            return result;
        }
        const result = [];
        function pushEdit(startOffset, endOffset, newLength) {
            if (result.length > 0 && (0, length_1.lengthEquals)(result[result.length - 1].endOffset, startOffset)) {
                const lastResult = result[result.length - 1];
                result[result.length - 1] = new beforeEditPositionMapper_1.TextEditInfo(lastResult.startOffset, endOffset, (0, length_1.lengthAdd)(lastResult.newLength, newLength));
            }
            else {
                result.push({ startOffset, endOffset, newLength });
            }
        }
        let s0offset = length_1.lengthZero;
        for (const s1ToS2 of s1ToS2Map) {
            const s0ToS1Map = nextS0ToS1MapWithS1LengthOf(s1ToS2.lengthBefore);
            if (s1ToS2.modified) {
                const s0Length = (0, length_1.sumLengths)(s0ToS1Map, s => s.lengthBefore);
                const s0EndOffset = (0, length_1.lengthAdd)(s0offset, s0Length);
                pushEdit(s0offset, s0EndOffset, s1ToS2.lengthAfter);
                s0offset = s0EndOffset;
            }
            else {
                for (const s1 of s0ToS1Map) {
                    const s0startOffset = s0offset;
                    s0offset = (0, length_1.lengthAdd)(s0offset, s1.lengthBefore);
                    if (s1.modified) {
                        pushEdit(s0startOffset, s0offset, s1.lengthAfter);
                    }
                }
            }
        }
        return result;
    }
    class LengthMapping {
        constructor(
        /**
         * If false, length before and length after equal.
         */
        modified, lengthBefore, lengthAfter) {
            this.modified = modified;
            this.lengthBefore = lengthBefore;
            this.lengthAfter = lengthAfter;
        }
        splitAt(lengthAfter) {
            const remainingLengthAfter = (0, length_1.lengthDiffNonNegative)(lengthAfter, this.lengthAfter);
            if ((0, length_1.lengthEquals)(remainingLengthAfter, length_1.lengthZero)) {
                return [this, undefined];
            }
            else if (this.modified) {
                return [
                    new LengthMapping(this.modified, this.lengthBefore, lengthAfter),
                    new LengthMapping(this.modified, length_1.lengthZero, remainingLengthAfter)
                ];
            }
            else {
                return [
                    new LengthMapping(this.modified, lengthAfter, lengthAfter),
                    new LengthMapping(this.modified, remainingLengthAfter, remainingLengthAfter)
                ];
            }
        }
        toString() {
            return `${this.modified ? 'M' : 'U'}:${(0, length_1.lengthToObj)(this.lengthBefore)} -> ${(0, length_1.lengthToObj)(this.lengthAfter)}`;
        }
    }
    function toLengthMapping(textEditInfos) {
        const result = [];
        let lastOffset = length_1.lengthZero;
        for (const textEditInfo of textEditInfos) {
            const spaceLength = (0, length_1.lengthDiffNonNegative)(lastOffset, textEditInfo.startOffset);
            if (!(0, length_1.lengthIsZero)(spaceLength)) {
                result.push(new LengthMapping(false, spaceLength, spaceLength));
            }
            const lengthBefore = (0, length_1.lengthDiffNonNegative)(textEditInfo.startOffset, textEditInfo.endOffset);
            result.push(new LengthMapping(true, lengthBefore, textEditInfo.newLength));
            lastOffset = textEditInfo.endOffset;
        }
        return result;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[573/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/nodeReader*/], __M([1/*require*/,0/*exports*/,106/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/length*/]), function (require, exports, length_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.NodeReader = void 0;
    /**
     * Allows to efficiently find a longest child at a given offset in a fixed node.
     * The requested offsets must increase monotonously.
    */
    class NodeReader {
        constructor(node) {
            this.lastOffset = length_1.lengthZero;
            this.nextNodes = [node];
            this.offsets = [length_1.lengthZero];
            this.idxs = [];
        }
        /**
         * Returns the longest node at `offset` that satisfies the predicate.
         * @param offset must be greater than or equal to the last offset this method has been called with!
        */
        readLongestNodeAt(offset, predicate) {
            if ((0, length_1.lengthLessThan)(offset, this.lastOffset)) {
                throw new Error('Invalid offset');
            }
            this.lastOffset = offset;
            // Find the longest node of all those that are closest to the current offset.
            while (true) {
                const curNode = lastOrUndefined(this.nextNodes);
                if (!curNode) {
                    return undefined;
                }
                const curNodeOffset = lastOrUndefined(this.offsets);
                if ((0, length_1.lengthLessThan)(offset, curNodeOffset)) {
                    // The next best node is not here yet.
                    // The reader must advance before a cached node is hit.
                    return undefined;
                }
                if ((0, length_1.lengthLessThan)(curNodeOffset, offset)) {
                    // The reader is ahead of the current node.
                    if ((0, length_1.lengthAdd)(curNodeOffset, curNode.length) <= offset) {
                        // The reader is after the end of the current node.
                        this.nextNodeAfterCurrent();
                    }
                    else {
                        // The reader is somewhere in the current node.
                        const nextChildIdx = getNextChildIdx(curNode);
                        if (nextChildIdx !== -1) {
                            // Go to the first child and repeat.
                            this.nextNodes.push(curNode.getChild(nextChildIdx));
                            this.offsets.push(curNodeOffset);
                            this.idxs.push(nextChildIdx);
                        }
                        else {
                            // We don't have children
                            this.nextNodeAfterCurrent();
                        }
                    }
                }
                else {
                    // readerOffsetBeforeChange === curNodeOffset
                    if (predicate(curNode)) {
                        this.nextNodeAfterCurrent();
                        return curNode;
                    }
                    else {
                        const nextChildIdx = getNextChildIdx(curNode);
                        // look for shorter node
                        if (nextChildIdx === -1) {
                            // There is no shorter node.
                            this.nextNodeAfterCurrent();
                            return undefined;
                        }
                        else {
                            // Descend into first child & repeat.
                            this.nextNodes.push(curNode.getChild(nextChildIdx));
                            this.offsets.push(curNodeOffset);
                            this.idxs.push(nextChildIdx);
                        }
                    }
                }
            }
        }
        // Navigates to the longest node that continues after the current node.
        nextNodeAfterCurrent() {
            while (true) {
                const currentOffset = lastOrUndefined(this.offsets);
                const currentNode = lastOrUndefined(this.nextNodes);
                this.nextNodes.pop();
                this.offsets.pop();
                if (this.idxs.length === 0) {
                    // We just popped the root node, there is no next node.
                    break;
                }
                // Parent is not undefined, because idxs is not empty
                const parent = lastOrUndefined(this.nextNodes);
                const nextChildIdx = getNextChildIdx(parent, this.idxs[this.idxs.length - 1]);
                if (nextChildIdx !== -1) {
                    this.nextNodes.push(parent.getChild(nextChildIdx));
                    this.offsets.push((0, length_1.lengthAdd)(currentOffset, currentNode.length));
                    this.idxs[this.idxs.length - 1] = nextChildIdx;
                    break;
                }
                else {
                    this.idxs.pop();
                }
                // We fully consumed the parent.
                // Current node is now parent, so call nextNodeAfterCurrent again
            }
        }
    }
    exports.NodeReader = NodeReader;
    function getNextChildIdx(node, curIdx = -1) {
        while (true) {
            curIdx++;
            if (curIdx >= node.childrenLength) {
                return -1;
            }
            if (node.getChild(curIdx)) {
                return curIdx;
            }
        }
    }
    function lastOrUndefined(arr) {
        return arr.length > 0 ? arr[arr.length - 1] : undefined;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[149/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/smallImmutableSet*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DenseKeyProvider = exports.identityKeyProvider = exports.SmallImmutableSet = void 0;
    const emptyArr = [];
    /**
     * Represents an immutable set that works best for a small number of elements (less than 32).
     * It uses bits to encode element membership efficiently.
    */
    class SmallImmutableSet {
        static { this.cache = new Array(129); }
        static create(items, additionalItems) {
            if (items <= 128 && additionalItems.length === 0) {
                // We create a cache of 128=2^7 elements to cover all sets with up to 7 (dense) elements.
                let cached = SmallImmutableSet.cache[items];
                if (!cached) {
                    cached = new SmallImmutableSet(items, additionalItems);
                    SmallImmutableSet.cache[items] = cached;
                }
                return cached;
            }
            return new SmallImmutableSet(items, additionalItems);
        }
        static { this.empty = SmallImmutableSet.create(0, emptyArr); }
        static getEmpty() {
            return this.empty;
        }
        constructor(items, additionalItems) {
            this.items = items;
            this.additionalItems = additionalItems;
        }
        add(value, keyProvider) {
            const key = keyProvider.getKey(value);
            let idx = key >> 5; // divided by 32
            if (idx === 0) {
                // fast path
                const newItem = (1 << key) | this.items;
                if (newItem === this.items) {
                    return this;
                }
                return SmallImmutableSet.create(newItem, this.additionalItems);
            }
            idx--;
            const newItems = this.additionalItems.slice(0);
            while (newItems.length < idx) {
                newItems.push(0);
            }
            newItems[idx] |= 1 << (key & 31);
            return SmallImmutableSet.create(this.items, newItems);
        }
        merge(other) {
            const merged = this.items | other.items;
            if (this.additionalItems === emptyArr && other.additionalItems === emptyArr) {
                // fast path
                if (merged === this.items) {
                    return this;
                }
                if (merged === other.items) {
                    return other;
                }
                return SmallImmutableSet.create(merged, emptyArr);
            }
            // This can be optimized, but it's not a common case
            const newItems = [];
            for (let i = 0; i < Math.max(this.additionalItems.length, other.additionalItems.length); i++) {
                const item1 = this.additionalItems[i] || 0;
                const item2 = other.additionalItems[i] || 0;
                newItems.push(item1 | item2);
            }
            return SmallImmutableSet.create(merged, newItems);
        }
        intersects(other) {
            if ((this.items & other.items) !== 0) {
                return true;
            }
            for (let i = 0; i < Math.min(this.additionalItems.length, other.additionalItems.length); i++) {
                if ((this.additionalItems[i] & other.additionalItems[i]) !== 0) {
                    return true;
                }
            }
            return false;
        }
    }
    exports.SmallImmutableSet = SmallImmutableSet;
    exports.identityKeyProvider = {
        getKey(value) {
            return value;
        }
    };
    /**
     * Assigns values a unique incrementing key.
    */
    class DenseKeyProvider {
        constructor() {
            this.items = new Map();
        }
        getKey(value) {
            let existing = this.items.get(value);
            if (existing === undefined) {
                existing = this.items.size;
                this.items.set(value, existing);
            }
            return existing;
        }
    }
    exports.DenseKeyProvider = DenseKeyProvider;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[201/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/ast*/], __M([1/*require*/,0/*exports*/,8/*vs/base/common/errors*/,94/*vs/editor/common/core/cursorColumns*/,106/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/length*/,149/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/smallImmutableSet*/]), function (require, exports, errors_1, cursorColumns_1, length_1, smallImmutableSet_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.InvalidBracketAstNode = exports.BracketAstNode = exports.TextAstNode = exports.ListAstNode = exports.PairAstNode = void 0;
    /**
     * The base implementation for all AST nodes.
    */
    class BaseAstNode {
        /**
         * The length of the entire node, which should equal the sum of lengths of all children.
        */
        get length() {
            return this._length;
        }
        constructor(length) {
            this._length = length;
        }
    }
    /**
     * Represents a bracket pair including its child (e.g. `{ ... }`).
     * Might be unclosed.
     * Immutable, if all children are immutable.
    */
    class PairAstNode extends BaseAstNode {
        static create(openingBracket, child, closingBracket) {
            let length = openingBracket.length;
            if (child) {
                length = (0, length_1.lengthAdd)(length, child.length);
            }
            if (closingBracket) {
                length = (0, length_1.lengthAdd)(length, closingBracket.length);
            }
            return new PairAstNode(length, openingBracket, child, closingBracket, child ? child.missingOpeningBracketIds : smallImmutableSet_1.SmallImmutableSet.getEmpty());
        }
        get kind() {
            return 2 /* AstNodeKind.Pair */;
        }
        get listHeight() {
            return 0;
        }
        get childrenLength() {
            return 3;
        }
        getChild(idx) {
            switch (idx) {
                case 0: return this.openingBracket;
                case 1: return this.child;
                case 2: return this.closingBracket;
            }
            throw new Error('Invalid child index');
        }
        /**
         * Avoid using this property, it allocates an array!
        */
        get children() {
            const result = [];
            result.push(this.openingBracket);
            if (this.child) {
                result.push(this.child);
            }
            if (this.closingBracket) {
                result.push(this.closingBracket);
            }
            return result;
        }
        constructor(length, openingBracket, child, closingBracket, missingOpeningBracketIds) {
            super(length);
            this.openingBracket = openingBracket;
            this.child = child;
            this.closingBracket = closingBracket;
            this.missingOpeningBracketIds = missingOpeningBracketIds;
        }
        canBeReused(openBracketIds) {
            if (this.closingBracket === null) {
                // Unclosed pair ast nodes only
                // end at the end of the document
                // or when a parent node is closed.
                // This could be improved:
                // Only return false if some next token is neither "undefined" nor a bracket that closes a parent.
                return false;
            }
            if (openBracketIds.intersects(this.missingOpeningBracketIds)) {
                return false;
            }
            return true;
        }
        deepClone() {
            return new PairAstNode(this.length, this.openingBracket.deepClone(), this.child && this.child.deepClone(), this.closingBracket && this.closingBracket.deepClone(), this.missingOpeningBracketIds);
        }
        computeMinIndentation(offset, textModel) {
            return this.child ? this.child.computeMinIndentation((0, length_1.lengthAdd)(offset, this.openingBracket.length), textModel) : Number.MAX_SAFE_INTEGER;
        }
    }
    exports.PairAstNode = PairAstNode;
    class ListAstNode extends BaseAstNode {
        /**
         * This method uses more memory-efficient list nodes that can only store 2 or 3 children.
        */
        static create23(item1, item2, item3, immutable = false) {
            let length = item1.length;
            let missingBracketIds = item1.missingOpeningBracketIds;
            if (item1.listHeight !== item2.listHeight) {
                throw new Error('Invalid list heights');
            }
            length = (0, length_1.lengthAdd)(length, item2.length);
            missingBracketIds = missingBracketIds.merge(item2.missingOpeningBracketIds);
            if (item3) {
                if (item1.listHeight !== item3.listHeight) {
                    throw new Error('Invalid list heights');
                }
                length = (0, length_1.lengthAdd)(length, item3.length);
                missingBracketIds = missingBracketIds.merge(item3.missingOpeningBracketIds);
            }
            return immutable
                ? new Immutable23ListAstNode(length, item1.listHeight + 1, item1, item2, item3, missingBracketIds)
                : new TwoThreeListAstNode(length, item1.listHeight + 1, item1, item2, item3, missingBracketIds);
        }
        static getEmpty() {
            return new ImmutableArrayListAstNode(length_1.lengthZero, 0, [], smallImmutableSet_1.SmallImmutableSet.getEmpty());
        }
        get kind() {
            return 4 /* AstNodeKind.List */;
        }
        get missingOpeningBracketIds() {
            return this._missingOpeningBracketIds;
        }
        /**
         * Use ListAstNode.create.
        */
        constructor(length, listHeight, _missingOpeningBracketIds) {
            super(length);
            this.listHeight = listHeight;
            this._missingOpeningBracketIds = _missingOpeningBracketIds;
            this.cachedMinIndentation = -1;
        }
        throwIfImmutable() {
            // NOOP
        }
        makeLastElementMutable() {
            this.throwIfImmutable();
            const childCount = this.childrenLength;
            if (childCount === 0) {
                return undefined;
            }
            const lastChild = this.getChild(childCount - 1);
            const mutable = lastChild.kind === 4 /* AstNodeKind.List */ ? lastChild.toMutable() : lastChild;
            if (lastChild !== mutable) {
                this.setChild(childCount - 1, mutable);
            }
            return mutable;
        }
        makeFirstElementMutable() {
            this.throwIfImmutable();
            const childCount = this.childrenLength;
            if (childCount === 0) {
                return undefined;
            }
            const firstChild = this.getChild(0);
            const mutable = firstChild.kind === 4 /* AstNodeKind.List */ ? firstChild.toMutable() : firstChild;
            if (firstChild !== mutable) {
                this.setChild(0, mutable);
            }
            return mutable;
        }
        canBeReused(openBracketIds) {
            if (openBracketIds.intersects(this.missingOpeningBracketIds)) {
                return false;
            }
            if (this.childrenLength === 0) {
                // Don't reuse empty lists.
                return false;
            }
            let lastChild = this;
            while (lastChild.kind === 4 /* AstNodeKind.List */) {
                const lastLength = lastChild.childrenLength;
                if (lastLength === 0) {
                    // Empty lists should never be contained in other lists.
                    throw new errors_1.BugIndicatingError();
                }
                lastChild = lastChild.getChild(lastLength - 1);
            }
            return lastChild.canBeReused(openBracketIds);
        }
        handleChildrenChanged() {
            this.throwIfImmutable();
            const count = this.childrenLength;
            let length = this.getChild(0).length;
            let unopenedBrackets = this.getChild(0).missingOpeningBracketIds;
            for (let i = 1; i < count; i++) {
                const child = this.getChild(i);
                length = (0, length_1.lengthAdd)(length, child.length);
                unopenedBrackets = unopenedBrackets.merge(child.missingOpeningBracketIds);
            }
            this._length = length;
            this._missingOpeningBracketIds = unopenedBrackets;
            this.cachedMinIndentation = -1;
        }
        computeMinIndentation(offset, textModel) {
            if (this.cachedMinIndentation !== -1) {
                return this.cachedMinIndentation;
            }
            let minIndentation = Number.MAX_SAFE_INTEGER;
            let childOffset = offset;
            for (let i = 0; i < this.childrenLength; i++) {
                const child = this.getChild(i);
                if (child) {
                    minIndentation = Math.min(minIndentation, child.computeMinIndentation(childOffset, textModel));
                    childOffset = (0, length_1.lengthAdd)(childOffset, child.length);
                }
            }
            this.cachedMinIndentation = minIndentation;
            return minIndentation;
        }
    }
    exports.ListAstNode = ListAstNode;
    class TwoThreeListAstNode extends ListAstNode {
        get childrenLength() {
            return this._item3 !== null ? 3 : 2;
        }
        getChild(idx) {
            switch (idx) {
                case 0: return this._item1;
                case 1: return this._item2;
                case 2: return this._item3;
            }
            throw new Error('Invalid child index');
        }
        setChild(idx, node) {
            switch (idx) {
                case 0:
                    this._item1 = node;
                    return;
                case 1:
                    this._item2 = node;
                    return;
                case 2:
                    this._item3 = node;
                    return;
            }
            throw new Error('Invalid child index');
        }
        get children() {
            return this._item3 ? [this._item1, this._item2, this._item3] : [this._item1, this._item2];
        }
        get item1() {
            return this._item1;
        }
        get item2() {
            return this._item2;
        }
        get item3() {
            return this._item3;
        }
        constructor(length, listHeight, _item1, _item2, _item3, missingOpeningBracketIds) {
            super(length, listHeight, missingOpeningBracketIds);
            this._item1 = _item1;
            this._item2 = _item2;
            this._item3 = _item3;
        }
        deepClone() {
            return new TwoThreeListAstNode(this.length, this.listHeight, this._item1.deepClone(), this._item2.deepClone(), this._item3 ? this._item3.deepClone() : null, this.missingOpeningBracketIds);
        }
        appendChildOfSameHeight(node) {
            if (this._item3) {
                throw new Error('Cannot append to a full (2,3) tree node');
            }
            this.throwIfImmutable();
            this._item3 = node;
            this.handleChildrenChanged();
        }
        unappendChild() {
            if (!this._item3) {
                throw new Error('Cannot remove from a non-full (2,3) tree node');
            }
            this.throwIfImmutable();
            const result = this._item3;
            this._item3 = null;
            this.handleChildrenChanged();
            return result;
        }
        prependChildOfSameHeight(node) {
            if (this._item3) {
                throw new Error('Cannot prepend to a full (2,3) tree node');
            }
            this.throwIfImmutable();
            this._item3 = this._item2;
            this._item2 = this._item1;
            this._item1 = node;
            this.handleChildrenChanged();
        }
        unprependChild() {
            if (!this._item3) {
                throw new Error('Cannot remove from a non-full (2,3) tree node');
            }
            this.throwIfImmutable();
            const result = this._item1;
            this._item1 = this._item2;
            this._item2 = this._item3;
            this._item3 = null;
            this.handleChildrenChanged();
            return result;
        }
        toMutable() {
            return this;
        }
    }
    /**
     * Immutable, if all children are immutable.
    */
    class Immutable23ListAstNode extends TwoThreeListAstNode {
        toMutable() {
            return new TwoThreeListAstNode(this.length, this.listHeight, this.item1, this.item2, this.item3, this.missingOpeningBracketIds);
        }
        throwIfImmutable() {
            throw new Error('this instance is immutable');
        }
    }
    /**
     * For debugging.
    */
    class ArrayListAstNode extends ListAstNode {
        get childrenLength() {
            return this._children.length;
        }
        getChild(idx) {
            return this._children[idx];
        }
        setChild(idx, child) {
            this._children[idx] = child;
        }
        get children() {
            return this._children;
        }
        constructor(length, listHeight, _children, missingOpeningBracketIds) {
            super(length, listHeight, missingOpeningBracketIds);
            this._children = _children;
        }
        deepClone() {
            const children = new Array(this._children.length);
            for (let i = 0; i < this._children.length; i++) {
                children[i] = this._children[i].deepClone();
            }
            return new ArrayListAstNode(this.length, this.listHeight, children, this.missingOpeningBracketIds);
        }
        appendChildOfSameHeight(node) {
            this.throwIfImmutable();
            this._children.push(node);
            this.handleChildrenChanged();
        }
        unappendChild() {
            this.throwIfImmutable();
            const item = this._children.pop();
            this.handleChildrenChanged();
            return item;
        }
        prependChildOfSameHeight(node) {
            this.throwIfImmutable();
            this._children.unshift(node);
            this.handleChildrenChanged();
        }
        unprependChild() {
            this.throwIfImmutable();
            const item = this._children.shift();
            this.handleChildrenChanged();
            return item;
        }
        toMutable() {
            return this;
        }
    }
    /**
     * Immutable, if all children are immutable.
    */
    class ImmutableArrayListAstNode extends ArrayListAstNode {
        toMutable() {
            return new ArrayListAstNode(this.length, this.listHeight, [...this.children], this.missingOpeningBracketIds);
        }
        throwIfImmutable() {
            throw new Error('this instance is immutable');
        }
    }
    const emptyArray = [];
    class ImmutableLeafAstNode extends BaseAstNode {
        get listHeight() {
            return 0;
        }
        get childrenLength() {
            return 0;
        }
        getChild(idx) {
            return null;
        }
        get children() {
            return emptyArray;
        }
        deepClone() {
            return this;
        }
    }
    class TextAstNode extends ImmutableLeafAstNode {
        get kind() {
            return 0 /* AstNodeKind.Text */;
        }
        get missingOpeningBracketIds() {
            return smallImmutableSet_1.SmallImmutableSet.getEmpty();
        }
        canBeReused(_openedBracketIds) {
            return true;
        }
        computeMinIndentation(offset, textModel) {
            const start = (0, length_1.lengthToObj)(offset);
            // Text ast nodes don't have partial indentation (ensured by the tokenizer).
            // Thus, if this text node does not start at column 0, the first line cannot have any indentation at all.
            const startLineNumber = (start.columnCount === 0 ? start.lineCount : start.lineCount + 1) + 1;
            const endLineNumber = (0, length_1.lengthGetLineCount)((0, length_1.lengthAdd)(offset, this.length)) + 1;
            let result = Number.MAX_SAFE_INTEGER;
            for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
                const firstNonWsColumn = textModel.getLineFirstNonWhitespaceColumn(lineNumber);
                const lineContent = textModel.getLineContent(lineNumber);
                if (firstNonWsColumn === 0) {
                    continue;
                }
                const visibleColumn = cursorColumns_1.CursorColumns.visibleColumnFromColumn(lineContent, firstNonWsColumn, textModel.getOptions().tabSize);
                result = Math.min(result, visibleColumn);
            }
            return result;
        }
    }
    exports.TextAstNode = TextAstNode;
    class BracketAstNode extends ImmutableLeafAstNode {
        static create(length, bracketInfo, bracketIds) {
            const node = new BracketAstNode(length, bracketInfo, bracketIds);
            return node;
        }
        get kind() {
            return 1 /* AstNodeKind.Bracket */;
        }
        get missingOpeningBracketIds() {
            return smallImmutableSet_1.SmallImmutableSet.getEmpty();
        }
        constructor(length, bracketInfo, 
        /**
         * In case of a opening bracket, this is the id of the opening bracket.
         * In case of a closing bracket, this contains the ids of all opening brackets it can close.
        */
        bracketIds) {
            super(length);
            this.bracketInfo = bracketInfo;
            this.bracketIds = bracketIds;
        }
        get text() {
            return this.bracketInfo.bracketText;
        }
        get languageId() {
            return this.bracketInfo.languageId;
        }
        canBeReused(_openedBracketIds) {
            // These nodes could be reused,
            // but not in a general way.
            // Their parent may be reused.
            return false;
        }
        computeMinIndentation(offset, textModel) {
            return Number.MAX_SAFE_INTEGER;
        }
    }
    exports.BracketAstNode = BracketAstNode;
    class InvalidBracketAstNode extends ImmutableLeafAstNode {
        get kind() {
            return 3 /* AstNodeKind.UnexpectedClosingBracket */;
        }
        constructor(closingBrackets, length) {
            super(length);
            this.missingOpeningBracketIds = closingBrackets;
        }
        canBeReused(openedBracketIds) {
            return !openedBracketIds.intersects(this.missingOpeningBracketIds);
        }
        computeMinIndentation(offset, textModel) {
            return Number.MAX_SAFE_INTEGER;
        }
    }
    exports.InvalidBracketAstNode = InvalidBracketAstNode;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[574/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/concat23Trees*/], __M([1/*require*/,0/*exports*/,201/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/ast*/]), function (require, exports, ast_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.concat23Trees = concat23Trees;
    exports.concat23TreesOfSameHeight = concat23TreesOfSameHeight;
    /**
     * Concatenates a list of (2,3) AstNode's into a single (2,3) AstNode.
     * This mutates the items of the input array!
     * If all items have the same height, this method has runtime O(items.length).
     * Otherwise, it has runtime O(items.length * max(log(items.length), items.max(i => i.height))).
    */
    function concat23Trees(items) {
        if (items.length === 0) {
            return null;
        }
        if (items.length === 1) {
            return items[0];
        }
        let i = 0;
        /**
         * Reads nodes of same height and concatenates them to a single node.
        */
        function readNode() {
            if (i >= items.length) {
                return null;
            }
            const start = i;
            const height = items[start].listHeight;
            i++;
            while (i < items.length && items[i].listHeight === height) {
                i++;
            }
            if (i - start >= 2) {
                return concat23TreesOfSameHeight(start === 0 && i === items.length ? items : items.slice(start, i), false);
            }
            else {
                return items[start];
            }
        }
        // The items might not have the same height.
        // We merge all items by using a binary concat operator.
        let first = readNode(); // There must be a first item
        let second = readNode();
        if (!second) {
            return first;
        }
        for (let item = readNode(); item; item = readNode()) {
            // Prefer concatenating smaller trees, as the runtime of concat depends on the tree height.
            if (heightDiff(first, second) <= heightDiff(second, item)) {
                first = concat(first, second);
                second = item;
            }
            else {
                second = concat(second, item);
            }
        }
        const result = concat(first, second);
        return result;
    }
    function concat23TreesOfSameHeight(items, createImmutableLists = false) {
        if (items.length === 0) {
            return null;
        }
        if (items.length === 1) {
            return items[0];
        }
        let length = items.length;
        // All trees have same height, just create parent nodes.
        while (length > 3) {
            const newLength = length >> 1;
            for (let i = 0; i < newLength; i++) {
                const j = i << 1;
                items[i] = ast_1.ListAstNode.create23(items[j], items[j + 1], j + 3 === length ? items[j + 2] : null, createImmutableLists);
            }
            length = newLength;
        }
        return ast_1.ListAstNode.create23(items[0], items[1], length >= 3 ? items[2] : null, createImmutableLists);
    }
    function heightDiff(node1, node2) {
        return Math.abs(node1.listHeight - node2.listHeight);
    }
    function concat(node1, node2) {
        if (node1.listHeight === node2.listHeight) {
            return ast_1.ListAstNode.create23(node1, node2, null, false);
        }
        else if (node1.listHeight > node2.listHeight) {
            // node1 is the tree we want to insert into
            return append(node1, node2);
        }
        else {
            return prepend(node2, node1);
        }
    }
    /**
     * Appends the given node to the end of this (2,3) tree.
     * Returns the new root.
    */
    function append(list, nodeToAppend) {
        list = list.toMutable();
        let curNode = list;
        const parents = [];
        let nodeToAppendOfCorrectHeight;
        while (true) {
            // assert nodeToInsert.listHeight <= curNode.listHeight
            if (nodeToAppend.listHeight === curNode.listHeight) {
                nodeToAppendOfCorrectHeight = nodeToAppend;
                break;
            }
            // assert 0 <= nodeToInsert.listHeight < curNode.listHeight
            if (curNode.kind !== 4 /* AstNodeKind.List */) {
                throw new Error('unexpected');
            }
            parents.push(curNode);
            // assert 2 <= curNode.childrenLength <= 3
            curNode = curNode.makeLastElementMutable();
        }
        // assert nodeToAppendOfCorrectHeight!.listHeight === curNode.listHeight
        for (let i = parents.length - 1; i >= 0; i--) {
            const parent = parents[i];
            if (nodeToAppendOfCorrectHeight) {
                // Can we take the element?
                if (parent.childrenLength >= 3) {
                    // assert parent.childrenLength === 3 && parent.listHeight === nodeToAppendOfCorrectHeight.listHeight + 1
                    // we need to split to maintain (2,3)-tree property.
                    // Send the third element + the new element to the parent.
                    nodeToAppendOfCorrectHeight = ast_1.ListAstNode.create23(parent.unappendChild(), nodeToAppendOfCorrectHeight, null, false);
                }
                else {
                    parent.appendChildOfSameHeight(nodeToAppendOfCorrectHeight);
                    nodeToAppendOfCorrectHeight = undefined;
                }
            }
            else {
                parent.handleChildrenChanged();
            }
        }
        if (nodeToAppendOfCorrectHeight) {
            return ast_1.ListAstNode.create23(list, nodeToAppendOfCorrectHeight, null, false);
        }
        else {
            return list;
        }
    }
    /**
     * Prepends the given node to the end of this (2,3) tree.
     * Returns the new root.
    */
    function prepend(list, nodeToAppend) {
        list = list.toMutable();
        let curNode = list;
        const parents = [];
        // assert nodeToInsert.listHeight <= curNode.listHeight
        while (nodeToAppend.listHeight !== curNode.listHeight) {
            // assert 0 <= nodeToInsert.listHeight < curNode.listHeight
            if (curNode.kind !== 4 /* AstNodeKind.List */) {
                throw new Error('unexpected');
            }
            parents.push(curNode);
            // assert 2 <= curNode.childrenFast.length <= 3
            curNode = curNode.makeFirstElementMutable();
        }
        let nodeToPrependOfCorrectHeight = nodeToAppend;
        // assert nodeToAppendOfCorrectHeight!.listHeight === curNode.listHeight
        for (let i = parents.length - 1; i >= 0; i--) {
            const parent = parents[i];
            if (nodeToPrependOfCorrectHeight) {
                // Can we take the element?
                if (parent.childrenLength >= 3) {
                    // assert parent.childrenLength === 3 && parent.listHeight === nodeToAppendOfCorrectHeight.listHeight + 1
                    // we need to split to maintain (2,3)-tree property.
                    // Send the third element + the new element to the parent.
                    nodeToPrependOfCorrectHeight = ast_1.ListAstNode.create23(nodeToPrependOfCorrectHeight, parent.unprependChild(), null, false);
                }
                else {
                    parent.prependChildOfSameHeight(nodeToPrependOfCorrectHeight);
                    nodeToPrependOfCorrectHeight = undefined;
                }
            }
            else {
                parent.handleChildrenChanged();
            }
        }
        if (nodeToPrependOfCorrectHeight) {
            return ast_1.ListAstNode.create23(nodeToPrependOfCorrectHeight, list, null, false);
        }
        else {
            return list;
        }
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[320/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/parser*/], __M([1/*require*/,0/*exports*/,201/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/ast*/,200/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/beforeEditPositionMapper*/,149/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/smallImmutableSet*/,106/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/length*/,574/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/concat23Trees*/,573/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/nodeReader*/]), function (require, exports, ast_1, beforeEditPositionMapper_1, smallImmutableSet_1, length_1, concat23Trees_1, nodeReader_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.parseDocument = parseDocument;
    /**
     * Non incrementally built ASTs are immutable.
    */
    function parseDocument(tokenizer, edits, oldNode, createImmutableLists) {
        const parser = new Parser(tokenizer, edits, oldNode, createImmutableLists);
        return parser.parseDocument();
    }
    /**
     * Non incrementally built ASTs are immutable.
    */
    class Parser {
        constructor(tokenizer, edits, oldNode, createImmutableLists) {
            this.tokenizer = tokenizer;
            this.createImmutableLists = createImmutableLists;
            this._itemsConstructed = 0;
            this._itemsFromCache = 0;
            if (oldNode && createImmutableLists) {
                throw new Error('Not supported');
            }
            this.oldNodeReader = oldNode ? new nodeReader_1.NodeReader(oldNode) : undefined;
            this.positionMapper = new beforeEditPositionMapper_1.BeforeEditPositionMapper(edits);
        }
        parseDocument() {
            this._itemsConstructed = 0;
            this._itemsFromCache = 0;
            let result = this.parseList(smallImmutableSet_1.SmallImmutableSet.getEmpty(), 0);
            if (!result) {
                result = ast_1.ListAstNode.getEmpty();
            }
            return result;
        }
        parseList(openedBracketIds, level) {
            const items = [];
            while (true) {
                let child = this.tryReadChildFromCache(openedBracketIds);
                if (!child) {
                    const token = this.tokenizer.peek();
                    if (!token ||
                        (token.kind === 2 /* TokenKind.ClosingBracket */ &&
                            token.bracketIds.intersects(openedBracketIds))) {
                        break;
                    }
                    child = this.parseChild(openedBracketIds, level + 1);
                }
                if (child.kind === 4 /* AstNodeKind.List */ && child.childrenLength === 0) {
                    continue;
                }
                items.push(child);
            }
            // When there is no oldNodeReader, all items are created from scratch and must have the same height.
            const result = this.oldNodeReader ? (0, concat23Trees_1.concat23Trees)(items) : (0, concat23Trees_1.concat23TreesOfSameHeight)(items, this.createImmutableLists);
            return result;
        }
        tryReadChildFromCache(openedBracketIds) {
            if (this.oldNodeReader) {
                const maxCacheableLength = this.positionMapper.getDistanceToNextChange(this.tokenizer.offset);
                if (maxCacheableLength === null || !(0, length_1.lengthIsZero)(maxCacheableLength)) {
                    const cachedNode = this.oldNodeReader.readLongestNodeAt(this.positionMapper.getOffsetBeforeChange(this.tokenizer.offset), curNode => {
                        // The edit could extend the ending token, thus we cannot re-use nodes that touch the edit.
                        // If there is no edit anymore, we can re-use the node in any case.
                        if (maxCacheableLength !== null && !(0, length_1.lengthLessThan)(curNode.length, maxCacheableLength)) {
                            // Either the node contains edited text or touches edited text.
                            // In the latter case, brackets might have been extended (`end` -> `ending`), so even touching nodes cannot be reused.
                            return false;
                        }
                        const canBeReused = curNode.canBeReused(openedBracketIds);
                        return canBeReused;
                    });
                    if (cachedNode) {
                        this._itemsFromCache++;
                        this.tokenizer.skip(cachedNode.length);
                        return cachedNode;
                    }
                }
            }
            return undefined;
        }
        parseChild(openedBracketIds, level) {
            this._itemsConstructed++;
            const token = this.tokenizer.read();
            switch (token.kind) {
                case 2 /* TokenKind.ClosingBracket */:
                    return new ast_1.InvalidBracketAstNode(token.bracketIds, token.length);
                case 0 /* TokenKind.Text */:
                    return token.astNode;
                case 1 /* TokenKind.OpeningBracket */: {
                    if (level > 300) {
                        // To prevent stack overflows
                        return new ast_1.TextAstNode(token.length);
                    }
                    const set = openedBracketIds.merge(token.bracketIds);
                    const child = this.parseList(set, level + 1);
                    const nextToken = this.tokenizer.peek();
                    if (nextToken &&
                        nextToken.kind === 2 /* TokenKind.ClosingBracket */ &&
                        (nextToken.bracketId === token.bracketId || nextToken.bracketIds.intersects(token.bracketIds))) {
                        this.tokenizer.read();
                        return ast_1.PairAstNode.create(token.astNode, child, nextToken.astNode);
                    }
                    else {
                        return ast_1.PairAstNode.create(token.astNode, child, null);
                    }
                }
                default:
                    throw new Error('unexpected');
            }
        }
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[236/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/tokenizer*/], __M([1/*require*/,0/*exports*/,8/*vs/base/common/errors*/,148/*vs/editor/common/encodedTokenAttributes*/,201/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/ast*/,106/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/length*/,149/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/smallImmutableSet*/]), function (require, exports, errors_1, encodedTokenAttributes_1, ast_1, length_1, smallImmutableSet_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.FastTokenizer = exports.TextBufferTokenizer = exports.Token = void 0;
    class Token {
        constructor(length, kind, 
        /**
         * If this token is an opening bracket, this is the id of the opening bracket.
         * If this token is a closing bracket, this is the id of the first opening bracket that is closed by this bracket.
         * Otherwise, it is -1.
         */
        bracketId, 
        /**
         * If this token is an opening bracket, this just contains `bracketId`.
         * If this token is a closing bracket, this lists all opening bracket ids, that it closes.
         * Otherwise, it is empty.
         */
        bracketIds, astNode) {
            this.length = length;
            this.kind = kind;
            this.bracketId = bracketId;
            this.bracketIds = bracketIds;
            this.astNode = astNode;
        }
    }
    exports.Token = Token;
    class TextBufferTokenizer {
        constructor(textModel, bracketTokens) {
            this.textModel = textModel;
            this.bracketTokens = bracketTokens;
            this.reader = new NonPeekableTextBufferTokenizer(this.textModel, this.bracketTokens);
            this._offset = length_1.lengthZero;
            this.didPeek = false;
            this.peeked = null;
            this.textBufferLineCount = textModel.getLineCount();
            this.textBufferLastLineLength = textModel.getLineLength(this.textBufferLineCount);
        }
        get offset() {
            return this._offset;
        }
        get length() {
            return (0, length_1.toLength)(this.textBufferLineCount - 1, this.textBufferLastLineLength);
        }
        skip(length) {
            this.didPeek = false;
            this._offset = (0, length_1.lengthAdd)(this._offset, length);
            const obj = (0, length_1.lengthToObj)(this._offset);
            this.reader.setPosition(obj.lineCount, obj.columnCount);
        }
        read() {
            let token;
            if (this.peeked) {
                this.didPeek = false;
                token = this.peeked;
            }
            else {
                token = this.reader.read();
            }
            if (token) {
                this._offset = (0, length_1.lengthAdd)(this._offset, token.length);
            }
            return token;
        }
        peek() {
            if (!this.didPeek) {
                this.peeked = this.reader.read();
                this.didPeek = true;
            }
            return this.peeked;
        }
    }
    exports.TextBufferTokenizer = TextBufferTokenizer;
    /**
     * Does not support peek.
    */
    class NonPeekableTextBufferTokenizer {
        constructor(textModel, bracketTokens) {
            this.textModel = textModel;
            this.bracketTokens = bracketTokens;
            this.lineIdx = 0;
            this.line = null;
            this.lineCharOffset = 0;
            this.lineTokens = null;
            this.lineTokenOffset = 0;
            /** Must be a zero line token. The end of the document cannot be peeked. */
            this.peekedToken = null;
            this.textBufferLineCount = textModel.getLineCount();
            this.textBufferLastLineLength = textModel.getLineLength(this.textBufferLineCount);
        }
        setPosition(lineIdx, column) {
            // We must not jump into a token!
            if (lineIdx === this.lineIdx) {
                this.lineCharOffset = column;
                if (this.line !== null) {
                    this.lineTokenOffset = this.lineCharOffset === 0 ? 0 : this.lineTokens.findTokenIndexAtOffset(this.lineCharOffset);
                }
            }
            else {
                this.lineIdx = lineIdx;
                this.lineCharOffset = column;
                this.line = null;
            }
            this.peekedToken = null;
        }
        read() {
            if (this.peekedToken) {
                const token = this.peekedToken;
                this.peekedToken = null;
                this.lineCharOffset += (0, length_1.lengthGetColumnCountIfZeroLineCount)(token.length);
                return token;
            }
            if (this.lineIdx > this.textBufferLineCount - 1 || (this.lineIdx === this.textBufferLineCount - 1 && this.lineCharOffset >= this.textBufferLastLineLength)) {
                // We are after the end
                return null;
            }
            if (this.line === null) {
                this.lineTokens = this.textModel.tokenization.getLineTokens(this.lineIdx + 1);
                this.line = this.lineTokens.getLineContent();
                this.lineTokenOffset = this.lineCharOffset === 0 ? 0 : this.lineTokens.findTokenIndexAtOffset(this.lineCharOffset);
            }
            const startLineIdx = this.lineIdx;
            const startLineCharOffset = this.lineCharOffset;
            // limits the length of text tokens.
            // If text tokens get too long, incremental updates will be slow
            let lengthHeuristic = 0;
            while (true) {
                const lineTokens = this.lineTokens;
                const tokenCount = lineTokens.getCount();
                let peekedBracketToken = null;
                if (this.lineTokenOffset < tokenCount) {
                    const tokenMetadata = lineTokens.getMetadata(this.lineTokenOffset);
                    while (this.lineTokenOffset + 1 < tokenCount && tokenMetadata === lineTokens.getMetadata(this.lineTokenOffset + 1)) {
                        // Skip tokens that are identical.
                        // Sometimes, (bracket) identifiers are split up into multiple tokens.
                        this.lineTokenOffset++;
                    }
                    const isOther = encodedTokenAttributes_1.TokenMetadata.getTokenType(tokenMetadata) === 0 /* StandardTokenType.Other */;
                    const containsBracketType = encodedTokenAttributes_1.TokenMetadata.containsBalancedBrackets(tokenMetadata);
                    const endOffset = lineTokens.getEndOffset(this.lineTokenOffset);
                    // Is there a bracket token next? Only consume text.
                    if (containsBracketType && isOther && this.lineCharOffset < endOffset) {
                        const languageId = lineTokens.getLanguageId(this.lineTokenOffset);
                        const text = this.line.substring(this.lineCharOffset, endOffset);
                        const brackets = this.bracketTokens.getSingleLanguageBracketTokens(languageId);
                        const regexp = brackets.regExpGlobal;
                        if (regexp) {
                            regexp.lastIndex = 0;
                            const match = regexp.exec(text);
                            if (match) {
                                peekedBracketToken = brackets.getToken(match[0]);
                                if (peekedBracketToken) {
                                    // Consume leading text of the token
                                    this.lineCharOffset += match.index;
                                }
                            }
                        }
                    }
                    lengthHeuristic += endOffset - this.lineCharOffset;
                    if (peekedBracketToken) {
                        // Don't skip the entire token, as a single token could contain multiple brackets.
                        if (startLineIdx !== this.lineIdx || startLineCharOffset !== this.lineCharOffset) {
                            // There is text before the bracket
                            this.peekedToken = peekedBracketToken;
                            break;
                        }
                        else {
                            // Consume the peeked token
                            this.lineCharOffset += (0, length_1.lengthGetColumnCountIfZeroLineCount)(peekedBracketToken.length);
                            return peekedBracketToken;
                        }
                    }
                    else {
                        // Skip the entire token, as the token contains no brackets at all.
                        this.lineTokenOffset++;
                        this.lineCharOffset = endOffset;
                    }
                }
                else {
                    if (this.lineIdx === this.textBufferLineCount - 1) {
                        break;
                    }
                    this.lineIdx++;
                    this.lineTokens = this.textModel.tokenization.getLineTokens(this.lineIdx + 1);
                    this.lineTokenOffset = 0;
                    this.line = this.lineTokens.getLineContent();
                    this.lineCharOffset = 0;
                    lengthHeuristic += 33; // max 1000/33 = 30 lines
                    // This limits the amount of work to recompute min-indentation
                    if (lengthHeuristic > 1000) {
                        // only break (automatically) at the end of line.
                        break;
                    }
                }
                if (lengthHeuristic > 1500) {
                    // Eventually break regardless of the line length so that
                    // very long lines do not cause bad performance.
                    // This effective limits max indentation to 500, as
                    // indentation is not computed across multiple text nodes.
                    break;
                }
            }
            // If a token contains some proper indentation, it also contains \n{INDENTATION+}(?!{INDENTATION}),
            // unless the line is too long.
            // Thus, the min indentation of the document is the minimum min indentation of every text node.
            const length = (0, length_1.lengthDiff)(startLineIdx, startLineCharOffset, this.lineIdx, this.lineCharOffset);
            return new Token(length, 0 /* TokenKind.Text */, -1, smallImmutableSet_1.SmallImmutableSet.getEmpty(), new ast_1.TextAstNode(length));
        }
    }
    class FastTokenizer {
        constructor(text, brackets) {
            this.text = text;
            this._offset = length_1.lengthZero;
            this.idx = 0;
            const regExpStr = brackets.getRegExpStr();
            const regexp = regExpStr ? new RegExp(regExpStr + '|\n', 'gi') : null;
            const tokens = [];
            let match;
            let curLineCount = 0;
            let lastLineBreakOffset = 0;
            let lastTokenEndOffset = 0;
            let lastTokenEndLine = 0;
            const smallTextTokens0Line = [];
            for (let i = 0; i < 60; i++) {
                smallTextTokens0Line.push(new Token((0, length_1.toLength)(0, i), 0 /* TokenKind.Text */, -1, smallImmutableSet_1.SmallImmutableSet.getEmpty(), new ast_1.TextAstNode((0, length_1.toLength)(0, i))));
            }
            const smallTextTokens1Line = [];
            for (let i = 0; i < 60; i++) {
                smallTextTokens1Line.push(new Token((0, length_1.toLength)(1, i), 0 /* TokenKind.Text */, -1, smallImmutableSet_1.SmallImmutableSet.getEmpty(), new ast_1.TextAstNode((0, length_1.toLength)(1, i))));
            }
            if (regexp) {
                regexp.lastIndex = 0;
                // If a token contains indentation, it also contains \n{INDENTATION+}(?!{INDENTATION})
                while ((match = regexp.exec(text)) !== null) {
                    const curOffset = match.index;
                    const value = match[0];
                    if (value === '\n') {
                        curLineCount++;
                        lastLineBreakOffset = curOffset + 1;
                    }
                    else {
                        if (lastTokenEndOffset !== curOffset) {
                            let token;
                            if (lastTokenEndLine === curLineCount) {
                                const colCount = curOffset - lastTokenEndOffset;
                                if (colCount < smallTextTokens0Line.length) {
                                    token = smallTextTokens0Line[colCount];
                                }
                                else {
                                    const length = (0, length_1.toLength)(0, colCount);
                                    token = new Token(length, 0 /* TokenKind.Text */, -1, smallImmutableSet_1.SmallImmutableSet.getEmpty(), new ast_1.TextAstNode(length));
                                }
                            }
                            else {
                                const lineCount = curLineCount - lastTokenEndLine;
                                const colCount = curOffset - lastLineBreakOffset;
                                if (lineCount === 1 && colCount < smallTextTokens1Line.length) {
                                    token = smallTextTokens1Line[colCount];
                                }
                                else {
                                    const length = (0, length_1.toLength)(lineCount, colCount);
                                    token = new Token(length, 0 /* TokenKind.Text */, -1, smallImmutableSet_1.SmallImmutableSet.getEmpty(), new ast_1.TextAstNode(length));
                                }
                            }
                            tokens.push(token);
                        }
                        // value is matched by regexp, so the token must exist
                        tokens.push(brackets.getToken(value));
                        lastTokenEndOffset = curOffset + value.length;
                        lastTokenEndLine = curLineCount;
                    }
                }
            }
            const offset = text.length;
            if (lastTokenEndOffset !== offset) {
                const length = (lastTokenEndLine === curLineCount)
                    ? (0, length_1.toLength)(0, offset - lastTokenEndOffset)
                    : (0, length_1.toLength)(curLineCount - lastTokenEndLine, offset - lastLineBreakOffset);
                tokens.push(new Token(length, 0 /* TokenKind.Text */, -1, smallImmutableSet_1.SmallImmutableSet.getEmpty(), new ast_1.TextAstNode(length)));
            }
            this.length = (0, length_1.toLength)(curLineCount, offset - lastLineBreakOffset);
            this.tokens = tokens;
        }
        get offset() {
            return this._offset;
        }
        read() {
            return this.tokens[this.idx++] || null;
        }
        peek() {
            return this.tokens[this.idx] || null;
        }
        skip(length) {
            throw new errors_1.NotSupportedError();
        }
    }
    exports.FastTokenizer = FastTokenizer;
});

define(__m[321/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/brackets*/], __M([1/*require*/,0/*exports*/,11/*vs/base/common/strings*/,201/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/ast*/,106/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/length*/,149/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/smallImmutableSet*/,236/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/tokenizer*/]), function (require, exports, strings_1, ast_1, length_1, smallImmutableSet_1, tokenizer_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.LanguageAgnosticBracketTokens = exports.BracketTokens = void 0;
    class BracketTokens {
        static createFromLanguage(configuration, denseKeyProvider) {
            function getId(bracketInfo) {
                return denseKeyProvider.getKey(`${bracketInfo.languageId}:::${bracketInfo.bracketText}`);
            }
            const map = new Map();
            for (const openingBracket of configuration.bracketsNew.openingBrackets) {
                const length = (0, length_1.toLength)(0, openingBracket.bracketText.length);
                const openingTextId = getId(openingBracket);
                const bracketIds = smallImmutableSet_1.SmallImmutableSet.getEmpty().add(openingTextId, smallImmutableSet_1.identityKeyProvider);
                map.set(openingBracket.bracketText, new tokenizer_1.Token(length, 1 /* TokenKind.OpeningBracket */, openingTextId, bracketIds, ast_1.BracketAstNode.create(length, openingBracket, bracketIds)));
            }
            for (const closingBracket of configuration.bracketsNew.closingBrackets) {
                const length = (0, length_1.toLength)(0, closingBracket.bracketText.length);
                let bracketIds = smallImmutableSet_1.SmallImmutableSet.getEmpty();
                const closingBrackets = closingBracket.getOpeningBrackets();
                for (const bracket of closingBrackets) {
                    bracketIds = bracketIds.add(getId(bracket), smallImmutableSet_1.identityKeyProvider);
                }
                map.set(closingBracket.bracketText, new tokenizer_1.Token(length, 2 /* TokenKind.ClosingBracket */, getId(closingBrackets[0]), bracketIds, ast_1.BracketAstNode.create(length, closingBracket, bracketIds)));
            }
            return new BracketTokens(map);
        }
        constructor(map) {
            this.map = map;
            this.hasRegExp = false;
            this._regExpGlobal = null;
        }
        getRegExpStr() {
            if (this.isEmpty) {
                return null;
            }
            else {
                const keys = [...this.map.keys()];
                keys.sort();
                keys.reverse();
                return keys.map(k => prepareBracketForRegExp(k)).join('|');
            }
        }
        /**
         * Returns null if there is no such regexp (because there are no brackets).
        */
        get regExpGlobal() {
            if (!this.hasRegExp) {
                const regExpStr = this.getRegExpStr();
                this._regExpGlobal = regExpStr ? new RegExp(regExpStr, 'gi') : null;
                this.hasRegExp = true;
            }
            return this._regExpGlobal;
        }
        getToken(value) {
            return this.map.get(value.toLowerCase());
        }
        findClosingTokenText(openingBracketIds) {
            for (const [closingText, info] of this.map) {
                if (info.kind === 2 /* TokenKind.ClosingBracket */ && info.bracketIds.intersects(openingBracketIds)) {
                    return closingText;
                }
            }
            return undefined;
        }
        get isEmpty() {
            return this.map.size === 0;
        }
    }
    exports.BracketTokens = BracketTokens;
    function prepareBracketForRegExp(str) {
        let escaped = (0, strings_1.escapeRegExpCharacters)(str);
        // These bracket pair delimiters start or end with letters
        // see https://github.com/microsoft/vscode/issues/132162 https://github.com/microsoft/vscode/issues/150440
        if (/^[\w ]+/.test(str)) {
            escaped = `\\b${escaped}`;
        }
        if (/[\w ]+$/.test(str)) {
            escaped = `${escaped}\\b`;
        }
        return escaped;
    }
    class LanguageAgnosticBracketTokens {
        constructor(denseKeyProvider, getLanguageConfiguration) {
            this.denseKeyProvider = denseKeyProvider;
            this.getLanguageConfiguration = getLanguageConfiguration;
            this.languageIdToBracketTokens = new Map();
        }
        didLanguageChange(languageId) {
            // Report a change whenever the language configuration updates.
            return this.languageIdToBracketTokens.has(languageId);
        }
        getSingleLanguageBracketTokens(languageId) {
            let singleLanguageBracketTokens = this.languageIdToBracketTokens.get(languageId);
            if (!singleLanguageBracketTokens) {
                singleLanguageBracketTokens = BracketTokens.createFromLanguage(this.getLanguageConfiguration(languageId), this.denseKeyProvider);
                this.languageIdToBracketTokens.set(languageId, singleLanguageBracketTokens);
            }
            return singleLanguageBracketTokens;
        }
    }
    exports.LanguageAgnosticBracketTokens = LanguageAgnosticBracketTokens;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[575/*vs/editor/common/model/bracketPairsTextModelPart/fixBrackets*/], __M([1/*require*/,0/*exports*/,321/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/brackets*/,106/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/length*/,320/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/parser*/,149/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/smallImmutableSet*/,236/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/tokenizer*/]), function (require, exports, brackets_1, length_1, parser_1, smallImmutableSet_1, tokenizer_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.fixBracketsInLine = fixBracketsInLine;
    function fixBracketsInLine(tokens, languageConfigurationService) {
        const denseKeyProvider = new smallImmutableSet_1.DenseKeyProvider();
        const bracketTokens = new brackets_1.LanguageAgnosticBracketTokens(denseKeyProvider, (languageId) => languageConfigurationService.getLanguageConfiguration(languageId));
        const tokenizer = new tokenizer_1.TextBufferTokenizer(new StaticTokenizerSource([tokens]), bracketTokens);
        const node = (0, parser_1.parseDocument)(tokenizer, [], undefined, true);
        let str = '';
        const line = tokens.getLineContent();
        function processNode(node, offset) {
            if (node.kind === 2 /* AstNodeKind.Pair */) {
                processNode(node.openingBracket, offset);
                offset = (0, length_1.lengthAdd)(offset, node.openingBracket.length);
                if (node.child) {
                    processNode(node.child, offset);
                    offset = (0, length_1.lengthAdd)(offset, node.child.length);
                }
                if (node.closingBracket) {
                    processNode(node.closingBracket, offset);
                    offset = (0, length_1.lengthAdd)(offset, node.closingBracket.length);
                }
                else {
                    const singleLangBracketTokens = bracketTokens.getSingleLanguageBracketTokens(node.openingBracket.languageId);
                    const closingTokenText = singleLangBracketTokens.findClosingTokenText(node.openingBracket.bracketIds);
                    str += closingTokenText;
                }
            }
            else if (node.kind === 3 /* AstNodeKind.UnexpectedClosingBracket */) {
                // remove the bracket
            }
            else if (node.kind === 0 /* AstNodeKind.Text */ || node.kind === 1 /* AstNodeKind.Bracket */) {
                str += line.substring((0, length_1.lengthGetColumnCountIfZeroLineCount)(offset), (0, length_1.lengthGetColumnCountIfZeroLineCount)((0, length_1.lengthAdd)(offset, node.length)));
            }
            else if (node.kind === 4 /* AstNodeKind.List */) {
                for (const child of node.children) {
                    processNode(child, offset);
                    offset = (0, length_1.lengthAdd)(offset, child.length);
                }
            }
        }
        processNode(node, length_1.lengthZero);
        return str;
    }
    class StaticTokenizerSource {
        constructor(lines) {
            this.lines = lines;
            this.tokenization = {
                getLineTokens: (lineNumber) => {
                    return this.lines[lineNumber - 1];
                }
            };
        }
        getLineCount() {
            return this.lines.length;
        }
        getLineLength(lineNumber) {
            return this.lines[lineNumber - 1].getLineContent().length;
        }
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[576/*vs/editor/common/model/fixedArray*/], __M([1/*require*/,0/*exports*/,13/*vs/base/common/arrays*/]), function (require, exports, arrays_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.FixedArray = void 0;
    /**
     * An array that avoids being sparse by always
     * filling up unused indices with a default value.
     */
    class FixedArray {
        constructor(_default) {
            this._default = _default;
            this._store = [];
        }
        get(index) {
            if (index < this._store.length) {
                return this._store[index];
            }
            return this._default;
        }
        set(index, value) {
            while (index >= this._store.length) {
                this._store[this._store.length] = this._default;
            }
            this._store[index] = value;
        }
        replace(index, oldLength, newLength) {
            if (index >= this._store.length) {
                return;
            }
            if (oldLength === 0) {
                this.insert(index, newLength);
                return;
            }
            else if (newLength === 0) {
                this.delete(index, oldLength);
                return;
            }
            const before = this._store.slice(0, index);
            const after = this._store.slice(index + oldLength);
            const insertArr = arrayFill(newLength, this._default);
            this._store = before.concat(insertArr, after);
        }
        delete(deleteIndex, deleteCount) {
            if (deleteCount === 0 || deleteIndex >= this._store.length) {
                return;
            }
            this._store.splice(deleteIndex, deleteCount);
        }
        insert(insertIndex, insertCount) {
            if (insertCount === 0 || insertIndex >= this._store.length) {
                return;
            }
            const arr = [];
            for (let i = 0; i < insertCount; i++) {
                arr[i] = this._default;
            }
            this._store = (0, arrays_1.arrayInsert)(this._store, insertIndex, arr);
        }
    }
    exports.FixedArray = FixedArray;
    function arrayFill(length, value) {
        const arr = [];
        for (let i = 0; i < length; i++) {
            arr[i] = value;
        }
        return arr;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[577/*vs/editor/common/model/indentationGuesser*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.guessIndentation = guessIndentation;
    class SpacesDiffResult {
        constructor() {
            this.spacesDiff = 0;
            this.looksLikeAlignment = false;
        }
    }
    /**
     * Compute the diff in spaces between two line's indentation.
     */
    function spacesDiff(a, aLength, b, bLength, result) {
        result.spacesDiff = 0;
        result.looksLikeAlignment = false;
        // This can go both ways (e.g.):
        //  - a: "\t"
        //  - b: "\t    "
        //  => This should count 1 tab and 4 spaces
        let i;
        for (i = 0; i < aLength && i < bLength; i++) {
            const aCharCode = a.charCodeAt(i);
            const bCharCode = b.charCodeAt(i);
            if (aCharCode !== bCharCode) {
                break;
            }
        }
        let aSpacesCnt = 0, aTabsCount = 0;
        for (let j = i; j < aLength; j++) {
            const aCharCode = a.charCodeAt(j);
            if (aCharCode === 32 /* CharCode.Space */) {
                aSpacesCnt++;
            }
            else {
                aTabsCount++;
            }
        }
        let bSpacesCnt = 0, bTabsCount = 0;
        for (let j = i; j < bLength; j++) {
            const bCharCode = b.charCodeAt(j);
            if (bCharCode === 32 /* CharCode.Space */) {
                bSpacesCnt++;
            }
            else {
                bTabsCount++;
            }
        }
        if (aSpacesCnt > 0 && aTabsCount > 0) {
            return;
        }
        if (bSpacesCnt > 0 && bTabsCount > 0) {
            return;
        }
        const tabsDiff = Math.abs(aTabsCount - bTabsCount);
        const spacesDiff = Math.abs(aSpacesCnt - bSpacesCnt);
        if (tabsDiff === 0) {
            // check if the indentation difference might be caused by alignment reasons
            // sometime folks like to align their code, but this should not be used as a hint
            result.spacesDiff = spacesDiff;
            if (spacesDiff > 0 && 0 <= bSpacesCnt - 1 && bSpacesCnt - 1 < a.length && bSpacesCnt < b.length) {
                if (b.charCodeAt(bSpacesCnt) !== 32 /* CharCode.Space */ && a.charCodeAt(bSpacesCnt - 1) === 32 /* CharCode.Space */) {
                    if (a.charCodeAt(a.length - 1) === 44 /* CharCode.Comma */) {
                        // This looks like an alignment desire: e.g.
                        // const a = b + c,
                        //       d = b - c;
                        result.looksLikeAlignment = true;
                    }
                }
            }
            return;
        }
        if (spacesDiff % tabsDiff === 0) {
            result.spacesDiff = spacesDiff / tabsDiff;
            return;
        }
    }
    function guessIndentation(source, defaultTabSize, defaultInsertSpaces) {
        // Look at most at the first 10k lines
        const linesCount = Math.min(source.getLineCount(), 10000);
        let linesIndentedWithTabsCount = 0; // number of lines that contain at least one tab in indentation
        let linesIndentedWithSpacesCount = 0; // number of lines that contain only spaces in indentation
        let previousLineText = ''; // content of latest line that contained non-whitespace chars
        let previousLineIndentation = 0; // index at which latest line contained the first non-whitespace char
        const ALLOWED_TAB_SIZE_GUESSES = [2, 4, 6, 8, 3, 5, 7]; // prefer even guesses for `tabSize`, limit to [2, 8].
        const MAX_ALLOWED_TAB_SIZE_GUESS = 8; // max(ALLOWED_TAB_SIZE_GUESSES) = 8
        const spacesDiffCount = [0, 0, 0, 0, 0, 0, 0, 0, 0]; // `tabSize` scores
        const tmp = new SpacesDiffResult();
        for (let lineNumber = 1; lineNumber <= linesCount; lineNumber++) {
            const currentLineLength = source.getLineLength(lineNumber);
            const currentLineText = source.getLineContent(lineNumber);
            // if the text buffer is chunk based, so long lines are cons-string, v8 will flattern the string when we check charCode.
            // checking charCode on chunks directly is cheaper.
            const useCurrentLineText = (currentLineLength <= 65536);
            let currentLineHasContent = false; // does `currentLineText` contain non-whitespace chars
            let currentLineIndentation = 0; // index at which `currentLineText` contains the first non-whitespace char
            let currentLineSpacesCount = 0; // count of spaces found in `currentLineText` indentation
            let currentLineTabsCount = 0; // count of tabs found in `currentLineText` indentation
            for (let j = 0, lenJ = currentLineLength; j < lenJ; j++) {
                const charCode = (useCurrentLineText ? currentLineText.charCodeAt(j) : source.getLineCharCode(lineNumber, j));
                if (charCode === 9 /* CharCode.Tab */) {
                    currentLineTabsCount++;
                }
                else if (charCode === 32 /* CharCode.Space */) {
                    currentLineSpacesCount++;
                }
                else {
                    // Hit non whitespace character on this line
                    currentLineHasContent = true;
                    currentLineIndentation = j;
                    break;
                }
            }
            // Ignore empty or only whitespace lines
            if (!currentLineHasContent) {
                continue;
            }
            if (currentLineTabsCount > 0) {
                linesIndentedWithTabsCount++;
            }
            else if (currentLineSpacesCount > 1) {
                linesIndentedWithSpacesCount++;
            }
            spacesDiff(previousLineText, previousLineIndentation, currentLineText, currentLineIndentation, tmp);
            if (tmp.looksLikeAlignment) {
                // if defaultInsertSpaces === true && the spaces count == tabSize, we may want to count it as valid indentation
                //
                // - item1
                //   - item2
                //
                // otherwise skip this line entirely
                //
                // const a = 1,
                //       b = 2;
                if (!(defaultInsertSpaces && defaultTabSize === tmp.spacesDiff)) {
                    continue;
                }
            }
            const currentSpacesDiff = tmp.spacesDiff;
            if (currentSpacesDiff <= MAX_ALLOWED_TAB_SIZE_GUESS) {
                spacesDiffCount[currentSpacesDiff]++;
            }
            previousLineText = currentLineText;
            previousLineIndentation = currentLineIndentation;
        }
        let insertSpaces = defaultInsertSpaces;
        if (linesIndentedWithTabsCount !== linesIndentedWithSpacesCount) {
            insertSpaces = (linesIndentedWithTabsCount < linesIndentedWithSpacesCount);
        }
        let tabSize = defaultTabSize;
        // Guess tabSize only if inserting spaces...
        if (insertSpaces) {
            let tabSizeScore = (insertSpaces ? 0 : 0.1 * linesCount);
            // console.log("score threshold: " + tabSizeScore);
            ALLOWED_TAB_SIZE_GUESSES.forEach((possibleTabSize) => {
                const possibleTabSizeScore = spacesDiffCount[possibleTabSize];
                if (possibleTabSizeScore > tabSizeScore) {
                    tabSizeScore = possibleTabSizeScore;
                    tabSize = possibleTabSize;
                }
            });
            // Let a tabSize of 2 win even if it is not the maximum
            // (only in case 4 was guessed)
            if (tabSize === 4 && spacesDiffCount[4] > 0 && spacesDiffCount[2] > 0 && spacesDiffCount[2] >= spacesDiffCount[4] / 2) {
                tabSize = 2;
            }
        }
        // console.log('--------------------------');
        // console.log('linesIndentedWithTabsCount: ' + linesIndentedWithTabsCount + ', linesIndentedWithSpacesCount: ' + linesIndentedWithSpacesCount);
        // console.log('spacesDiffCount: ' + spacesDiffCount);
        // console.log('tabSize: ' + tabSize + ', tabSizeScore: ' + tabSizeScore);
        return {
            insertSpaces: insertSpaces,
            tabSize: tabSize
        };
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[578/*vs/editor/common/model/intervalTree*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.IntervalTree = exports.SENTINEL = exports.IntervalNode = void 0;
    exports.getNodeColor = getNodeColor;
    exports.nodeAcceptEdit = nodeAcceptEdit;
    exports.recomputeMaxEnd = recomputeMaxEnd;
    exports.intervalCompare = intervalCompare;
    function getNodeColor(node) {
        return ((node.metadata & 1 /* Constants.ColorMask */) >>> 0 /* Constants.ColorOffset */);
    }
    function setNodeColor(node, color) {
        node.metadata = ((node.metadata & 254 /* Constants.ColorMaskInverse */) | (color << 0 /* Constants.ColorOffset */));
    }
    function getNodeIsVisited(node) {
        return ((node.metadata & 2 /* Constants.IsVisitedMask */) >>> 1 /* Constants.IsVisitedOffset */) === 1;
    }
    function setNodeIsVisited(node, value) {
        node.metadata = ((node.metadata & 253 /* Constants.IsVisitedMaskInverse */) | ((value ? 1 : 0) << 1 /* Constants.IsVisitedOffset */));
    }
    function getNodeIsForValidation(node) {
        return ((node.metadata & 4 /* Constants.IsForValidationMask */) >>> 2 /* Constants.IsForValidationOffset */) === 1;
    }
    function setNodeIsForValidation(node, value) {
        node.metadata = ((node.metadata & 251 /* Constants.IsForValidationMaskInverse */) | ((value ? 1 : 0) << 2 /* Constants.IsForValidationOffset */));
    }
    function getNodeIsInGlyphMargin(node) {
        return ((node.metadata & 64 /* Constants.IsMarginMask */) >>> 6 /* Constants.IsMarginOffset */) === 1;
    }
    function setNodeIsInGlyphMargin(node, value) {
        node.metadata = ((node.metadata & 191 /* Constants.IsMarginMaskInverse */) | ((value ? 1 : 0) << 6 /* Constants.IsMarginOffset */));
    }
    function getNodeStickiness(node) {
        return ((node.metadata & 24 /* Constants.StickinessMask */) >>> 3 /* Constants.StickinessOffset */);
    }
    function _setNodeStickiness(node, stickiness) {
        node.metadata = ((node.metadata & 231 /* Constants.StickinessMaskInverse */) | (stickiness << 3 /* Constants.StickinessOffset */));
    }
    function getCollapseOnReplaceEdit(node) {
        return ((node.metadata & 32 /* Constants.CollapseOnReplaceEditMask */) >>> 5 /* Constants.CollapseOnReplaceEditOffset */) === 1;
    }
    function setCollapseOnReplaceEdit(node, value) {
        node.metadata = ((node.metadata & 223 /* Constants.CollapseOnReplaceEditMaskInverse */) | ((value ? 1 : 0) << 5 /* Constants.CollapseOnReplaceEditOffset */));
    }
    class IntervalNode {
        constructor(id, start, end) {
            this.metadata = 0;
            this.parent = this;
            this.left = this;
            this.right = this;
            setNodeColor(this, 1 /* NodeColor.Red */);
            this.start = start;
            this.end = end;
            // FORCE_OVERFLOWING_TEST: this.delta = start;
            this.delta = 0;
            this.maxEnd = end;
            this.id = id;
            this.ownerId = 0;
            this.options = null;
            setNodeIsForValidation(this, false);
            setNodeIsInGlyphMargin(this, false);
            _setNodeStickiness(this, 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */);
            setCollapseOnReplaceEdit(this, false);
            this.cachedVersionId = 0;
            this.cachedAbsoluteStart = start;
            this.cachedAbsoluteEnd = end;
            this.range = null;
            setNodeIsVisited(this, false);
        }
        reset(versionId, start, end, range) {
            this.start = start;
            this.end = end;
            this.maxEnd = end;
            this.cachedVersionId = versionId;
            this.cachedAbsoluteStart = start;
            this.cachedAbsoluteEnd = end;
            this.range = range;
        }
        setOptions(options) {
            this.options = options;
            const className = this.options.className;
            setNodeIsForValidation(this, (className === "squiggly-error" /* ClassName.EditorErrorDecoration */
                || className === "squiggly-warning" /* ClassName.EditorWarningDecoration */
                || className === "squiggly-info" /* ClassName.EditorInfoDecoration */));
            setNodeIsInGlyphMargin(this, this.options.glyphMarginClassName !== null);
            _setNodeStickiness(this, this.options.stickiness);
            setCollapseOnReplaceEdit(this, this.options.collapseOnReplaceEdit);
        }
        setCachedOffsets(absoluteStart, absoluteEnd, cachedVersionId) {
            if (this.cachedVersionId !== cachedVersionId) {
                this.range = null;
            }
            this.cachedVersionId = cachedVersionId;
            this.cachedAbsoluteStart = absoluteStart;
            this.cachedAbsoluteEnd = absoluteEnd;
        }
        detach() {
            this.parent = null;
            this.left = null;
            this.right = null;
        }
    }
    exports.IntervalNode = IntervalNode;
    exports.SENTINEL = new IntervalNode(null, 0, 0);
    exports.SENTINEL.parent = exports.SENTINEL;
    exports.SENTINEL.left = exports.SENTINEL;
    exports.SENTINEL.right = exports.SENTINEL;
    setNodeColor(exports.SENTINEL, 0 /* NodeColor.Black */);
    class IntervalTree {
        constructor() {
            this.root = exports.SENTINEL;
            this.requestNormalizeDelta = false;
        }
        intervalSearch(start, end, filterOwnerId, filterOutValidation, cachedVersionId, onlyMarginDecorations) {
            if (this.root === exports.SENTINEL) {
                return [];
            }
            return intervalSearch(this, start, end, filterOwnerId, filterOutValidation, cachedVersionId, onlyMarginDecorations);
        }
        search(filterOwnerId, filterOutValidation, cachedVersionId, onlyMarginDecorations) {
            if (this.root === exports.SENTINEL) {
                return [];
            }
            return search(this, filterOwnerId, filterOutValidation, cachedVersionId, onlyMarginDecorations);
        }
        /**
         * Will not set `cachedAbsoluteStart` nor `cachedAbsoluteEnd` on the returned nodes!
         */
        collectNodesFromOwner(ownerId) {
            return collectNodesFromOwner(this, ownerId);
        }
        /**
         * Will not set `cachedAbsoluteStart` nor `cachedAbsoluteEnd` on the returned nodes!
         */
        collectNodesPostOrder() {
            return collectNodesPostOrder(this);
        }
        insert(node) {
            rbTreeInsert(this, node);
            this._normalizeDeltaIfNecessary();
        }
        delete(node) {
            rbTreeDelete(this, node);
            this._normalizeDeltaIfNecessary();
        }
        resolveNode(node, cachedVersionId) {
            const initialNode = node;
            let delta = 0;
            while (node !== this.root) {
                if (node === node.parent.right) {
                    delta += node.parent.delta;
                }
                node = node.parent;
            }
            const nodeStart = initialNode.start + delta;
            const nodeEnd = initialNode.end + delta;
            initialNode.setCachedOffsets(nodeStart, nodeEnd, cachedVersionId);
        }
        acceptReplace(offset, length, textLength, forceMoveMarkers) {
            // Our strategy is to remove all directly impacted nodes, and then add them back to the tree.
            // (1) collect all nodes that are intersecting this edit as nodes of interest
            const nodesOfInterest = searchForEditing(this, offset, offset + length);
            // (2) remove all nodes that are intersecting this edit
            for (let i = 0, len = nodesOfInterest.length; i < len; i++) {
                const node = nodesOfInterest[i];
                rbTreeDelete(this, node);
            }
            this._normalizeDeltaIfNecessary();
            // (3) edit all tree nodes except the nodes of interest
            noOverlapReplace(this, offset, offset + length, textLength);
            this._normalizeDeltaIfNecessary();
            // (4) edit the nodes of interest and insert them back in the tree
            for (let i = 0, len = nodesOfInterest.length; i < len; i++) {
                const node = nodesOfInterest[i];
                node.start = node.cachedAbsoluteStart;
                node.end = node.cachedAbsoluteEnd;
                nodeAcceptEdit(node, offset, (offset + length), textLength, forceMoveMarkers);
                node.maxEnd = node.end;
                rbTreeInsert(this, node);
            }
            this._normalizeDeltaIfNecessary();
        }
        _normalizeDeltaIfNecessary() {
            if (!this.requestNormalizeDelta) {
                return;
            }
            this.requestNormalizeDelta = false;
            normalizeDelta(this);
        }
    }
    exports.IntervalTree = IntervalTree;
    //#region Delta Normalization
    function normalizeDelta(T) {
        let node = T.root;
        let delta = 0;
        while (node !== exports.SENTINEL) {
            if (node.left !== exports.SENTINEL && !getNodeIsVisited(node.left)) {
                // go left
                node = node.left;
                continue;
            }
            if (node.right !== exports.SENTINEL && !getNodeIsVisited(node.right)) {
                // go right
                delta += node.delta;
                node = node.right;
                continue;
            }
            // handle current node
            node.start = delta + node.start;
            node.end = delta + node.end;
            node.delta = 0;
            recomputeMaxEnd(node);
            setNodeIsVisited(node, true);
            // going up from this node
            setNodeIsVisited(node.left, false);
            setNodeIsVisited(node.right, false);
            if (node === node.parent.right) {
                delta -= node.parent.delta;
            }
            node = node.parent;
        }
        setNodeIsVisited(T.root, false);
    }
    function adjustMarkerBeforeColumn(markerOffset, markerStickToPreviousCharacter, checkOffset, moveSemantics) {
        if (markerOffset < checkOffset) {
            return true;
        }
        if (markerOffset > checkOffset) {
            return false;
        }
        if (moveSemantics === 1 /* MarkerMoveSemantics.ForceMove */) {
            return false;
        }
        if (moveSemantics === 2 /* MarkerMoveSemantics.ForceStay */) {
            return true;
        }
        return markerStickToPreviousCharacter;
    }
    /**
     * This is a lot more complicated than strictly necessary to maintain the same behaviour
     * as when decorations were implemented using two markers.
     */
    function nodeAcceptEdit(node, start, end, textLength, forceMoveMarkers) {
        const nodeStickiness = getNodeStickiness(node);
        const startStickToPreviousCharacter = (nodeStickiness === 0 /* TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges */
            || nodeStickiness === 2 /* TrackedRangeStickiness.GrowsOnlyWhenTypingBefore */);
        const endStickToPreviousCharacter = (nodeStickiness === 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */
            || nodeStickiness === 2 /* TrackedRangeStickiness.GrowsOnlyWhenTypingBefore */);
        const deletingCnt = (end - start);
        const insertingCnt = textLength;
        const commonLength = Math.min(deletingCnt, insertingCnt);
        const nodeStart = node.start;
        let startDone = false;
        const nodeEnd = node.end;
        let endDone = false;
        if (start <= nodeStart && nodeEnd <= end && getCollapseOnReplaceEdit(node)) {
            // This edit encompasses the entire decoration range
            // and the decoration has asked to become collapsed
            node.start = start;
            startDone = true;
            node.end = start;
            endDone = true;
        }
        {
            const moveSemantics = forceMoveMarkers ? 1 /* MarkerMoveSemantics.ForceMove */ : (deletingCnt > 0 ? 2 /* MarkerMoveSemantics.ForceStay */ : 0 /* MarkerMoveSemantics.MarkerDefined */);
            if (!startDone && adjustMarkerBeforeColumn(nodeStart, startStickToPreviousCharacter, start, moveSemantics)) {
                startDone = true;
            }
            if (!endDone && adjustMarkerBeforeColumn(nodeEnd, endStickToPreviousCharacter, start, moveSemantics)) {
                endDone = true;
            }
        }
        if (commonLength > 0 && !forceMoveMarkers) {
            const moveSemantics = (deletingCnt > insertingCnt ? 2 /* MarkerMoveSemantics.ForceStay */ : 0 /* MarkerMoveSemantics.MarkerDefined */);
            if (!startDone && adjustMarkerBeforeColumn(nodeStart, startStickToPreviousCharacter, start + commonLength, moveSemantics)) {
                startDone = true;
            }
            if (!endDone && adjustMarkerBeforeColumn(nodeEnd, endStickToPreviousCharacter, start + commonLength, moveSemantics)) {
                endDone = true;
            }
        }
        {
            const moveSemantics = forceMoveMarkers ? 1 /* MarkerMoveSemantics.ForceMove */ : 0 /* MarkerMoveSemantics.MarkerDefined */;
            if (!startDone && adjustMarkerBeforeColumn(nodeStart, startStickToPreviousCharacter, end, moveSemantics)) {
                node.start = start + insertingCnt;
                startDone = true;
            }
            if (!endDone && adjustMarkerBeforeColumn(nodeEnd, endStickToPreviousCharacter, end, moveSemantics)) {
                node.end = start + insertingCnt;
                endDone = true;
            }
        }
        // Finish
        const deltaColumn = (insertingCnt - deletingCnt);
        if (!startDone) {
            node.start = Math.max(0, nodeStart + deltaColumn);
        }
        if (!endDone) {
            node.end = Math.max(0, nodeEnd + deltaColumn);
        }
        if (node.start > node.end) {
            node.end = node.start;
        }
    }
    function searchForEditing(T, start, end) {
        // https://en.wikipedia.org/wiki/Interval_tree#Augmented_tree
        // Now, it is known that two intervals A and B overlap only when both
        // A.low <= B.high and A.high >= B.low. When searching the trees for
        // nodes overlapping with a given interval, you can immediately skip:
        //  a) all nodes to the right of nodes whose low value is past the end of the given interval.
        //  b) all nodes that have their maximum 'high' value below the start of the given interval.
        let node = T.root;
        let delta = 0;
        let nodeMaxEnd = 0;
        let nodeStart = 0;
        let nodeEnd = 0;
        const result = [];
        let resultLen = 0;
        while (node !== exports.SENTINEL) {
            if (getNodeIsVisited(node)) {
                // going up from this node
                setNodeIsVisited(node.left, false);
                setNodeIsVisited(node.right, false);
                if (node === node.parent.right) {
                    delta -= node.parent.delta;
                }
                node = node.parent;
                continue;
            }
            if (!getNodeIsVisited(node.left)) {
                // first time seeing this node
                nodeMaxEnd = delta + node.maxEnd;
                if (nodeMaxEnd < start) {
                    // cover case b) from above
                    // there is no need to search this node or its children
                    setNodeIsVisited(node, true);
                    continue;
                }
                if (node.left !== exports.SENTINEL) {
                    // go left
                    node = node.left;
                    continue;
                }
            }
            // handle current node
            nodeStart = delta + node.start;
            if (nodeStart > end) {
                // cover case a) from above
                // there is no need to search this node or its right subtree
                setNodeIsVisited(node, true);
                continue;
            }
            nodeEnd = delta + node.end;
            if (nodeEnd >= start) {
                node.setCachedOffsets(nodeStart, nodeEnd, 0);
                result[resultLen++] = node;
            }
            setNodeIsVisited(node, true);
            if (node.right !== exports.SENTINEL && !getNodeIsVisited(node.right)) {
                // go right
                delta += node.delta;
                node = node.right;
                continue;
            }
        }
        setNodeIsVisited(T.root, false);
        return result;
    }
    function noOverlapReplace(T, start, end, textLength) {
        // https://en.wikipedia.org/wiki/Interval_tree#Augmented_tree
        // Now, it is known that two intervals A and B overlap only when both
        // A.low <= B.high and A.high >= B.low. When searching the trees for
        // nodes overlapping with a given interval, you can immediately skip:
        //  a) all nodes to the right of nodes whose low value is past the end of the given interval.
        //  b) all nodes that have their maximum 'high' value below the start of the given interval.
        let node = T.root;
        let delta = 0;
        let nodeMaxEnd = 0;
        let nodeStart = 0;
        const editDelta = (textLength - (end - start));
        while (node !== exports.SENTINEL) {
            if (getNodeIsVisited(node)) {
                // going up from this node
                setNodeIsVisited(node.left, false);
                setNodeIsVisited(node.right, false);
                if (node === node.parent.right) {
                    delta -= node.parent.delta;
                }
                recomputeMaxEnd(node);
                node = node.parent;
                continue;
            }
            if (!getNodeIsVisited(node.left)) {
                // first time seeing this node
                nodeMaxEnd = delta + node.maxEnd;
                if (nodeMaxEnd < start) {
                    // cover case b) from above
                    // there is no need to search this node or its children
                    setNodeIsVisited(node, true);
                    continue;
                }
                if (node.left !== exports.SENTINEL) {
                    // go left
                    node = node.left;
                    continue;
                }
            }
            // handle current node
            nodeStart = delta + node.start;
            if (nodeStart > end) {
                node.start += editDelta;
                node.end += editDelta;
                node.delta += editDelta;
                if (node.delta < -1073741824 /* Constants.MIN_SAFE_DELTA */ || node.delta > 1073741824 /* Constants.MAX_SAFE_DELTA */) {
                    T.requestNormalizeDelta = true;
                }
                // cover case a) from above
                // there is no need to search this node or its right subtree
                setNodeIsVisited(node, true);
                continue;
            }
            setNodeIsVisited(node, true);
            if (node.right !== exports.SENTINEL && !getNodeIsVisited(node.right)) {
                // go right
                delta += node.delta;
                node = node.right;
                continue;
            }
        }
        setNodeIsVisited(T.root, false);
    }
    //#endregion
    //#region Searching
    function collectNodesFromOwner(T, ownerId) {
        let node = T.root;
        const result = [];
        let resultLen = 0;
        while (node !== exports.SENTINEL) {
            if (getNodeIsVisited(node)) {
                // going up from this node
                setNodeIsVisited(node.left, false);
                setNodeIsVisited(node.right, false);
                node = node.parent;
                continue;
            }
            if (node.left !== exports.SENTINEL && !getNodeIsVisited(node.left)) {
                // go left
                node = node.left;
                continue;
            }
            // handle current node
            if (node.ownerId === ownerId) {
                result[resultLen++] = node;
            }
            setNodeIsVisited(node, true);
            if (node.right !== exports.SENTINEL && !getNodeIsVisited(node.right)) {
                // go right
                node = node.right;
                continue;
            }
        }
        setNodeIsVisited(T.root, false);
        return result;
    }
    function collectNodesPostOrder(T) {
        let node = T.root;
        const result = [];
        let resultLen = 0;
        while (node !== exports.SENTINEL) {
            if (getNodeIsVisited(node)) {
                // going up from this node
                setNodeIsVisited(node.left, false);
                setNodeIsVisited(node.right, false);
                node = node.parent;
                continue;
            }
            if (node.left !== exports.SENTINEL && !getNodeIsVisited(node.left)) {
                // go left
                node = node.left;
                continue;
            }
            if (node.right !== exports.SENTINEL && !getNodeIsVisited(node.right)) {
                // go right
                node = node.right;
                continue;
            }
            // handle current node
            result[resultLen++] = node;
            setNodeIsVisited(node, true);
        }
        setNodeIsVisited(T.root, false);
        return result;
    }
    function search(T, filterOwnerId, filterOutValidation, cachedVersionId, onlyMarginDecorations) {
        let node = T.root;
        let delta = 0;
        let nodeStart = 0;
        let nodeEnd = 0;
        const result = [];
        let resultLen = 0;
        while (node !== exports.SENTINEL) {
            if (getNodeIsVisited(node)) {
                // going up from this node
                setNodeIsVisited(node.left, false);
                setNodeIsVisited(node.right, false);
                if (node === node.parent.right) {
                    delta -= node.parent.delta;
                }
                node = node.parent;
                continue;
            }
            if (node.left !== exports.SENTINEL && !getNodeIsVisited(node.left)) {
                // go left
                node = node.left;
                continue;
            }
            // handle current node
            nodeStart = delta + node.start;
            nodeEnd = delta + node.end;
            node.setCachedOffsets(nodeStart, nodeEnd, cachedVersionId);
            let include = true;
            if (filterOwnerId && node.ownerId && node.ownerId !== filterOwnerId) {
                include = false;
            }
            if (filterOutValidation && getNodeIsForValidation(node)) {
                include = false;
            }
            if (onlyMarginDecorations && !getNodeIsInGlyphMargin(node)) {
                include = false;
            }
            if (include) {
                result[resultLen++] = node;
            }
            setNodeIsVisited(node, true);
            if (node.right !== exports.SENTINEL && !getNodeIsVisited(node.right)) {
                // go right
                delta += node.delta;
                node = node.right;
                continue;
            }
        }
        setNodeIsVisited(T.root, false);
        return result;
    }
    function intervalSearch(T, intervalStart, intervalEnd, filterOwnerId, filterOutValidation, cachedVersionId, onlyMarginDecorations) {
        // https://en.wikipedia.org/wiki/Interval_tree#Augmented_tree
        // Now, it is known that two intervals A and B overlap only when both
        // A.low <= B.high and A.high >= B.low. When searching the trees for
        // nodes overlapping with a given interval, you can immediately skip:
        //  a) all nodes to the right of nodes whose low value is past the end of the given interval.
        //  b) all nodes that have their maximum 'high' value below the start of the given interval.
        let node = T.root;
        let delta = 0;
        let nodeMaxEnd = 0;
        let nodeStart = 0;
        let nodeEnd = 0;
        const result = [];
        let resultLen = 0;
        while (node !== exports.SENTINEL) {
            if (getNodeIsVisited(node)) {
                // going up from this node
                setNodeIsVisited(node.left, false);
                setNodeIsVisited(node.right, false);
                if (node === node.parent.right) {
                    delta -= node.parent.delta;
                }
                node = node.parent;
                continue;
            }
            if (!getNodeIsVisited(node.left)) {
                // first time seeing this node
                nodeMaxEnd = delta + node.maxEnd;
                if (nodeMaxEnd < intervalStart) {
                    // cover case b) from above
                    // there is no need to search this node or its children
                    setNodeIsVisited(node, true);
                    continue;
                }
                if (node.left !== exports.SENTINEL) {
                    // go left
                    node = node.left;
                    continue;
                }
            }
            // handle current node
            nodeStart = delta + node.start;
            if (nodeStart > intervalEnd) {
                // cover case a) from above
                // there is no need to search this node or its right subtree
                setNodeIsVisited(node, true);
                continue;
            }
            nodeEnd = delta + node.end;
            if (nodeEnd >= intervalStart) {
                // There is overlap
                node.setCachedOffsets(nodeStart, nodeEnd, cachedVersionId);
                let include = true;
                if (filterOwnerId && node.ownerId && node.ownerId !== filterOwnerId) {
                    include = false;
                }
                if (filterOutValidation && getNodeIsForValidation(node)) {
                    include = false;
                }
                if (onlyMarginDecorations && !getNodeIsInGlyphMargin(node)) {
                    include = false;
                }
                if (include) {
                    result[resultLen++] = node;
                }
            }
            setNodeIsVisited(node, true);
            if (node.right !== exports.SENTINEL && !getNodeIsVisited(node.right)) {
                // go right
                delta += node.delta;
                node = node.right;
                continue;
            }
        }
        setNodeIsVisited(T.root, false);
        return result;
    }
    //#endregion
    //#region Insertion
    function rbTreeInsert(T, newNode) {
        if (T.root === exports.SENTINEL) {
            newNode.parent = exports.SENTINEL;
            newNode.left = exports.SENTINEL;
            newNode.right = exports.SENTINEL;
            setNodeColor(newNode, 0 /* NodeColor.Black */);
            T.root = newNode;
            return T.root;
        }
        treeInsert(T, newNode);
        recomputeMaxEndWalkToRoot(newNode.parent);
        // repair tree
        let x = newNode;
        while (x !== T.root && getNodeColor(x.parent) === 1 /* NodeColor.Red */) {
            if (x.parent === x.parent.parent.left) {
                const y = x.parent.parent.right;
                if (getNodeColor(y) === 1 /* NodeColor.Red */) {
                    setNodeColor(x.parent, 0 /* NodeColor.Black */);
                    setNodeColor(y, 0 /* NodeColor.Black */);
                    setNodeColor(x.parent.parent, 1 /* NodeColor.Red */);
                    x = x.parent.parent;
                }
                else {
                    if (x === x.parent.right) {
                        x = x.parent;
                        leftRotate(T, x);
                    }
                    setNodeColor(x.parent, 0 /* NodeColor.Black */);
                    setNodeColor(x.parent.parent, 1 /* NodeColor.Red */);
                    rightRotate(T, x.parent.parent);
                }
            }
            else {
                const y = x.parent.parent.left;
                if (getNodeColor(y) === 1 /* NodeColor.Red */) {
                    setNodeColor(x.parent, 0 /* NodeColor.Black */);
                    setNodeColor(y, 0 /* NodeColor.Black */);
                    setNodeColor(x.parent.parent, 1 /* NodeColor.Red */);
                    x = x.parent.parent;
                }
                else {
                    if (x === x.parent.left) {
                        x = x.parent;
                        rightRotate(T, x);
                    }
                    setNodeColor(x.parent, 0 /* NodeColor.Black */);
                    setNodeColor(x.parent.parent, 1 /* NodeColor.Red */);
                    leftRotate(T, x.parent.parent);
                }
            }
        }
        setNodeColor(T.root, 0 /* NodeColor.Black */);
        return newNode;
    }
    function treeInsert(T, z) {
        let delta = 0;
        let x = T.root;
        const zAbsoluteStart = z.start;
        const zAbsoluteEnd = z.end;
        while (true) {
            const cmp = intervalCompare(zAbsoluteStart, zAbsoluteEnd, x.start + delta, x.end + delta);
            if (cmp < 0) {
                // this node should be inserted to the left
                // => it is not affected by the node's delta
                if (x.left === exports.SENTINEL) {
                    z.start -= delta;
                    z.end -= delta;
                    z.maxEnd -= delta;
                    x.left = z;
                    break;
                }
                else {
                    x = x.left;
                }
            }
            else {
                // this node should be inserted to the right
                // => it is not affected by the node's delta
                if (x.right === exports.SENTINEL) {
                    z.start -= (delta + x.delta);
                    z.end -= (delta + x.delta);
                    z.maxEnd -= (delta + x.delta);
                    x.right = z;
                    break;
                }
                else {
                    delta += x.delta;
                    x = x.right;
                }
            }
        }
        z.parent = x;
        z.left = exports.SENTINEL;
        z.right = exports.SENTINEL;
        setNodeColor(z, 1 /* NodeColor.Red */);
    }
    //#endregion
    //#region Deletion
    function rbTreeDelete(T, z) {
        let x;
        let y;
        // RB-DELETE except we don't swap z and y in case c)
        // i.e. we always delete what's pointed at by z.
        if (z.left === exports.SENTINEL) {
            x = z.right;
            y = z;
            // x's delta is no longer influenced by z's delta
            x.delta += z.delta;
            if (x.delta < -1073741824 /* Constants.MIN_SAFE_DELTA */ || x.delta > 1073741824 /* Constants.MAX_SAFE_DELTA */) {
                T.requestNormalizeDelta = true;
            }
            x.start += z.delta;
            x.end += z.delta;
        }
        else if (z.right === exports.SENTINEL) {
            x = z.left;
            y = z;
        }
        else {
            y = leftest(z.right);
            x = y.right;
            // y's delta is no longer influenced by z's delta,
            // but we don't want to walk the entire right-hand-side subtree of x.
            // we therefore maintain z's delta in y, and adjust only x
            x.start += y.delta;
            x.end += y.delta;
            x.delta += y.delta;
            if (x.delta < -1073741824 /* Constants.MIN_SAFE_DELTA */ || x.delta > 1073741824 /* Constants.MAX_SAFE_DELTA */) {
                T.requestNormalizeDelta = true;
            }
            y.start += z.delta;
            y.end += z.delta;
            y.delta = z.delta;
            if (y.delta < -1073741824 /* Constants.MIN_SAFE_DELTA */ || y.delta > 1073741824 /* Constants.MAX_SAFE_DELTA */) {
                T.requestNormalizeDelta = true;
            }
        }
        if (y === T.root) {
            T.root = x;
            setNodeColor(x, 0 /* NodeColor.Black */);
            z.detach();
            resetSentinel();
            recomputeMaxEnd(x);
            T.root.parent = exports.SENTINEL;
            return;
        }
        const yWasRed = (getNodeColor(y) === 1 /* NodeColor.Red */);
        if (y === y.parent.left) {
            y.parent.left = x;
        }
        else {
            y.parent.right = x;
        }
        if (y === z) {
            x.parent = y.parent;
        }
        else {
            if (y.parent === z) {
                x.parent = y;
            }
            else {
                x.parent = y.parent;
            }
            y.left = z.left;
            y.right = z.right;
            y.parent = z.parent;
            setNodeColor(y, getNodeColor(z));
            if (z === T.root) {
                T.root = y;
            }
            else {
                if (z === z.parent.left) {
                    z.parent.left = y;
                }
                else {
                    z.parent.right = y;
                }
            }
            if (y.left !== exports.SENTINEL) {
                y.left.parent = y;
            }
            if (y.right !== exports.SENTINEL) {
                y.right.parent = y;
            }
        }
        z.detach();
        if (yWasRed) {
            recomputeMaxEndWalkToRoot(x.parent);
            if (y !== z) {
                recomputeMaxEndWalkToRoot(y);
                recomputeMaxEndWalkToRoot(y.parent);
            }
            resetSentinel();
            return;
        }
        recomputeMaxEndWalkToRoot(x);
        recomputeMaxEndWalkToRoot(x.parent);
        if (y !== z) {
            recomputeMaxEndWalkToRoot(y);
            recomputeMaxEndWalkToRoot(y.parent);
        }
        // RB-DELETE-FIXUP
        let w;
        while (x !== T.root && getNodeColor(x) === 0 /* NodeColor.Black */) {
            if (x === x.parent.left) {
                w = x.parent.right;
                if (getNodeColor(w) === 1 /* NodeColor.Red */) {
                    setNodeColor(w, 0 /* NodeColor.Black */);
                    setNodeColor(x.parent, 1 /* NodeColor.Red */);
                    leftRotate(T, x.parent);
                    w = x.parent.right;
                }
                if (getNodeColor(w.left) === 0 /* NodeColor.Black */ && getNodeColor(w.right) === 0 /* NodeColor.Black */) {
                    setNodeColor(w, 1 /* NodeColor.Red */);
                    x = x.parent;
                }
                else {
                    if (getNodeColor(w.right) === 0 /* NodeColor.Black */) {
                        setNodeColor(w.left, 0 /* NodeColor.Black */);
                        setNodeColor(w, 1 /* NodeColor.Red */);
                        rightRotate(T, w);
                        w = x.parent.right;
                    }
                    setNodeColor(w, getNodeColor(x.parent));
                    setNodeColor(x.parent, 0 /* NodeColor.Black */);
                    setNodeColor(w.right, 0 /* NodeColor.Black */);
                    leftRotate(T, x.parent);
                    x = T.root;
                }
            }
            else {
                w = x.parent.left;
                if (getNodeColor(w) === 1 /* NodeColor.Red */) {
                    setNodeColor(w, 0 /* NodeColor.Black */);
                    setNodeColor(x.parent, 1 /* NodeColor.Red */);
                    rightRotate(T, x.parent);
                    w = x.parent.left;
                }
                if (getNodeColor(w.left) === 0 /* NodeColor.Black */ && getNodeColor(w.right) === 0 /* NodeColor.Black */) {
                    setNodeColor(w, 1 /* NodeColor.Red */);
                    x = x.parent;
                }
                else {
                    if (getNodeColor(w.left) === 0 /* NodeColor.Black */) {
                        setNodeColor(w.right, 0 /* NodeColor.Black */);
                        setNodeColor(w, 1 /* NodeColor.Red */);
                        leftRotate(T, w);
                        w = x.parent.left;
                    }
                    setNodeColor(w, getNodeColor(x.parent));
                    setNodeColor(x.parent, 0 /* NodeColor.Black */);
                    setNodeColor(w.left, 0 /* NodeColor.Black */);
                    rightRotate(T, x.parent);
                    x = T.root;
                }
            }
        }
        setNodeColor(x, 0 /* NodeColor.Black */);
        resetSentinel();
    }
    function leftest(node) {
        while (node.left !== exports.SENTINEL) {
            node = node.left;
        }
        return node;
    }
    function resetSentinel() {
        exports.SENTINEL.parent = exports.SENTINEL;
        exports.SENTINEL.delta = 0; // optional
        exports.SENTINEL.start = 0; // optional
        exports.SENTINEL.end = 0; // optional
    }
    //#endregion
    //#region Rotations
    function leftRotate(T, x) {
        const y = x.right; // set y.
        y.delta += x.delta; // y's delta is no longer influenced by x's delta
        if (y.delta < -1073741824 /* Constants.MIN_SAFE_DELTA */ || y.delta > 1073741824 /* Constants.MAX_SAFE_DELTA */) {
            T.requestNormalizeDelta = true;
        }
        y.start += x.delta;
        y.end += x.delta;
        x.right = y.left; // turn y's left subtree into x's right subtree.
        if (y.left !== exports.SENTINEL) {
            y.left.parent = x;
        }
        y.parent = x.parent; // link x's parent to y.
        if (x.parent === exports.SENTINEL) {
            T.root = y;
        }
        else if (x === x.parent.left) {
            x.parent.left = y;
        }
        else {
            x.parent.right = y;
        }
        y.left = x; // put x on y's left.
        x.parent = y;
        recomputeMaxEnd(x);
        recomputeMaxEnd(y);
    }
    function rightRotate(T, y) {
        const x = y.left;
        y.delta -= x.delta;
        if (y.delta < -1073741824 /* Constants.MIN_SAFE_DELTA */ || y.delta > 1073741824 /* Constants.MAX_SAFE_DELTA */) {
            T.requestNormalizeDelta = true;
        }
        y.start -= x.delta;
        y.end -= x.delta;
        y.left = x.right;
        if (x.right !== exports.SENTINEL) {
            x.right.parent = y;
        }
        x.parent = y.parent;
        if (y.parent === exports.SENTINEL) {
            T.root = x;
        }
        else if (y === y.parent.right) {
            y.parent.right = x;
        }
        else {
            y.parent.left = x;
        }
        x.right = y;
        y.parent = x;
        recomputeMaxEnd(y);
        recomputeMaxEnd(x);
    }
    //#endregion
    //#region max end computation
    function computeMaxEnd(node) {
        let maxEnd = node.end;
        if (node.left !== exports.SENTINEL) {
            const leftMaxEnd = node.left.maxEnd;
            if (leftMaxEnd > maxEnd) {
                maxEnd = leftMaxEnd;
            }
        }
        if (node.right !== exports.SENTINEL) {
            const rightMaxEnd = node.right.maxEnd + node.delta;
            if (rightMaxEnd > maxEnd) {
                maxEnd = rightMaxEnd;
            }
        }
        return maxEnd;
    }
    function recomputeMaxEnd(node) {
        node.maxEnd = computeMaxEnd(node);
    }
    function recomputeMaxEndWalkToRoot(node) {
        while (node !== exports.SENTINEL) {
            const maxEnd = computeMaxEnd(node);
            if (node.maxEnd === maxEnd) {
                // no need to go further
                return;
            }
            node.maxEnd = maxEnd;
            node = node.parent;
        }
    }
    //#endregion
    //#region utils
    function intervalCompare(aStart, aEnd, bStart, bEnd) {
        if (aStart === bStart) {
            return aEnd - bEnd;
        }
        return aStart - bStart;
    }
});
//#endregion

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[579/*vs/editor/common/model/pieceTreeTextBuffer/rbTreeBase*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SENTINEL = exports.TreeNode = void 0;
    exports.leftest = leftest;
    exports.righttest = righttest;
    exports.leftRotate = leftRotate;
    exports.rightRotate = rightRotate;
    exports.rbDelete = rbDelete;
    exports.fixInsert = fixInsert;
    exports.updateTreeMetadata = updateTreeMetadata;
    exports.recomputeTreeMetadata = recomputeTreeMetadata;
    class TreeNode {
        constructor(piece, color) {
            this.piece = piece;
            this.color = color;
            this.size_left = 0;
            this.lf_left = 0;
            this.parent = this;
            this.left = this;
            this.right = this;
        }
        next() {
            if (this.right !== exports.SENTINEL) {
                return leftest(this.right);
            }
            let node = this;
            while (node.parent !== exports.SENTINEL) {
                if (node.parent.left === node) {
                    break;
                }
                node = node.parent;
            }
            if (node.parent === exports.SENTINEL) {
                return exports.SENTINEL;
            }
            else {
                return node.parent;
            }
        }
        prev() {
            if (this.left !== exports.SENTINEL) {
                return righttest(this.left);
            }
            let node = this;
            while (node.parent !== exports.SENTINEL) {
                if (node.parent.right === node) {
                    break;
                }
                node = node.parent;
            }
            if (node.parent === exports.SENTINEL) {
                return exports.SENTINEL;
            }
            else {
                return node.parent;
            }
        }
        detach() {
            this.parent = null;
            this.left = null;
            this.right = null;
        }
    }
    exports.TreeNode = TreeNode;
    exports.SENTINEL = new TreeNode(null, 0 /* NodeColor.Black */);
    exports.SENTINEL.parent = exports.SENTINEL;
    exports.SENTINEL.left = exports.SENTINEL;
    exports.SENTINEL.right = exports.SENTINEL;
    exports.SENTINEL.color = 0 /* NodeColor.Black */;
    function leftest(node) {
        while (node.left !== exports.SENTINEL) {
            node = node.left;
        }
        return node;
    }
    function righttest(node) {
        while (node.right !== exports.SENTINEL) {
            node = node.right;
        }
        return node;
    }
    function calculateSize(node) {
        if (node === exports.SENTINEL) {
            return 0;
        }
        return node.size_left + node.piece.length + calculateSize(node.right);
    }
    function calculateLF(node) {
        if (node === exports.SENTINEL) {
            return 0;
        }
        return node.lf_left + node.piece.lineFeedCnt + calculateLF(node.right);
    }
    function resetSentinel() {
        exports.SENTINEL.parent = exports.SENTINEL;
    }
    function leftRotate(tree, x) {
        const y = x.right;
        // fix size_left
        y.size_left += x.size_left + (x.piece ? x.piece.length : 0);
        y.lf_left += x.lf_left + (x.piece ? x.piece.lineFeedCnt : 0);
        x.right = y.left;
        if (y.left !== exports.SENTINEL) {
            y.left.parent = x;
        }
        y.parent = x.parent;
        if (x.parent === exports.SENTINEL) {
            tree.root = y;
        }
        else if (x.parent.left === x) {
            x.parent.left = y;
        }
        else {
            x.parent.right = y;
        }
        y.left = x;
        x.parent = y;
    }
    function rightRotate(tree, y) {
        const x = y.left;
        y.left = x.right;
        if (x.right !== exports.SENTINEL) {
            x.right.parent = y;
        }
        x.parent = y.parent;
        // fix size_left
        y.size_left -= x.size_left + (x.piece ? x.piece.length : 0);
        y.lf_left -= x.lf_left + (x.piece ? x.piece.lineFeedCnt : 0);
        if (y.parent === exports.SENTINEL) {
            tree.root = x;
        }
        else if (y === y.parent.right) {
            y.parent.right = x;
        }
        else {
            y.parent.left = x;
        }
        x.right = y;
        y.parent = x;
    }
    function rbDelete(tree, z) {
        let x;
        let y;
        if (z.left === exports.SENTINEL) {
            y = z;
            x = y.right;
        }
        else if (z.right === exports.SENTINEL) {
            y = z;
            x = y.left;
        }
        else {
            y = leftest(z.right);
            x = y.right;
        }
        if (y === tree.root) {
            tree.root = x;
            // if x is null, we are removing the only node
            x.color = 0 /* NodeColor.Black */;
            z.detach();
            resetSentinel();
            tree.root.parent = exports.SENTINEL;
            return;
        }
        const yWasRed = (y.color === 1 /* NodeColor.Red */);
        if (y === y.parent.left) {
            y.parent.left = x;
        }
        else {
            y.parent.right = x;
        }
        if (y === z) {
            x.parent = y.parent;
            recomputeTreeMetadata(tree, x);
        }
        else {
            if (y.parent === z) {
                x.parent = y;
            }
            else {
                x.parent = y.parent;
            }
            // as we make changes to x's hierarchy, update size_left of subtree first
            recomputeTreeMetadata(tree, x);
            y.left = z.left;
            y.right = z.right;
            y.parent = z.parent;
            y.color = z.color;
            if (z === tree.root) {
                tree.root = y;
            }
            else {
                if (z === z.parent.left) {
                    z.parent.left = y;
                }
                else {
                    z.parent.right = y;
                }
            }
            if (y.left !== exports.SENTINEL) {
                y.left.parent = y;
            }
            if (y.right !== exports.SENTINEL) {
                y.right.parent = y;
            }
            // update metadata
            // we replace z with y, so in this sub tree, the length change is z.item.length
            y.size_left = z.size_left;
            y.lf_left = z.lf_left;
            recomputeTreeMetadata(tree, y);
        }
        z.detach();
        if (x.parent.left === x) {
            const newSizeLeft = calculateSize(x);
            const newLFLeft = calculateLF(x);
            if (newSizeLeft !== x.parent.size_left || newLFLeft !== x.parent.lf_left) {
                const delta = newSizeLeft - x.parent.size_left;
                const lf_delta = newLFLeft - x.parent.lf_left;
                x.parent.size_left = newSizeLeft;
                x.parent.lf_left = newLFLeft;
                updateTreeMetadata(tree, x.parent, delta, lf_delta);
            }
        }
        recomputeTreeMetadata(tree, x.parent);
        if (yWasRed) {
            resetSentinel();
            return;
        }
        // RB-DELETE-FIXUP
        let w;
        while (x !== tree.root && x.color === 0 /* NodeColor.Black */) {
            if (x === x.parent.left) {
                w = x.parent.right;
                if (w.color === 1 /* NodeColor.Red */) {
                    w.color = 0 /* NodeColor.Black */;
                    x.parent.color = 1 /* NodeColor.Red */;
                    leftRotate(tree, x.parent);
                    w = x.parent.right;
                }
                if (w.left.color === 0 /* NodeColor.Black */ && w.right.color === 0 /* NodeColor.Black */) {
                    w.color = 1 /* NodeColor.Red */;
                    x = x.parent;
                }
                else {
                    if (w.right.color === 0 /* NodeColor.Black */) {
                        w.left.color = 0 /* NodeColor.Black */;
                        w.color = 1 /* NodeColor.Red */;
                        rightRotate(tree, w);
                        w = x.parent.right;
                    }
                    w.color = x.parent.color;
                    x.parent.color = 0 /* NodeColor.Black */;
                    w.right.color = 0 /* NodeColor.Black */;
                    leftRotate(tree, x.parent);
                    x = tree.root;
                }
            }
            else {
                w = x.parent.left;
                if (w.color === 1 /* NodeColor.Red */) {
                    w.color = 0 /* NodeColor.Black */;
                    x.parent.color = 1 /* NodeColor.Red */;
                    rightRotate(tree, x.parent);
                    w = x.parent.left;
                }
                if (w.left.color === 0 /* NodeColor.Black */ && w.right.color === 0 /* NodeColor.Black */) {
                    w.color = 1 /* NodeColor.Red */;
                    x = x.parent;
                }
                else {
                    if (w.left.color === 0 /* NodeColor.Black */) {
                        w.right.color = 0 /* NodeColor.Black */;
                        w.color = 1 /* NodeColor.Red */;
                        leftRotate(tree, w);
                        w = x.parent.left;
                    }
                    w.color = x.parent.color;
                    x.parent.color = 0 /* NodeColor.Black */;
                    w.left.color = 0 /* NodeColor.Black */;
                    rightRotate(tree, x.parent);
                    x = tree.root;
                }
            }
        }
        x.color = 0 /* NodeColor.Black */;
        resetSentinel();
    }
    function fixInsert(tree, x) {
        recomputeTreeMetadata(tree, x);
        while (x !== tree.root && x.parent.color === 1 /* NodeColor.Red */) {
            if (x.parent === x.parent.parent.left) {
                const y = x.parent.parent.right;
                if (y.color === 1 /* NodeColor.Red */) {
                    x.parent.color = 0 /* NodeColor.Black */;
                    y.color = 0 /* NodeColor.Black */;
                    x.parent.parent.color = 1 /* NodeColor.Red */;
                    x = x.parent.parent;
                }
                else {
                    if (x === x.parent.right) {
                        x = x.parent;
                        leftRotate(tree, x);
                    }
                    x.parent.color = 0 /* NodeColor.Black */;
                    x.parent.parent.color = 1 /* NodeColor.Red */;
                    rightRotate(tree, x.parent.parent);
                }
            }
            else {
                const y = x.parent.parent.left;
                if (y.color === 1 /* NodeColor.Red */) {
                    x.parent.color = 0 /* NodeColor.Black */;
                    y.color = 0 /* NodeColor.Black */;
                    x.parent.parent.color = 1 /* NodeColor.Red */;
                    x = x.parent.parent;
                }
                else {
                    if (x === x.parent.left) {
                        x = x.parent;
                        rightRotate(tree, x);
                    }
                    x.parent.color = 0 /* NodeColor.Black */;
                    x.parent.parent.color = 1 /* NodeColor.Red */;
                    leftRotate(tree, x.parent.parent);
                }
            }
        }
        tree.root.color = 0 /* NodeColor.Black */;
    }
    function updateTreeMetadata(tree, x, delta, lineFeedCntDelta) {
        // node length change or line feed count change
        while (x !== tree.root && x !== exports.SENTINEL) {
            if (x.parent.left === x) {
                x.parent.size_left += delta;
                x.parent.lf_left += lineFeedCntDelta;
            }
            x = x.parent;
        }
    }
    function recomputeTreeMetadata(tree, x) {
        let delta = 0;
        let lf_delta = 0;
        if (x === tree.root) {
            return;
        }
        // go upwards till the node whose left subtree is changed.
        while (x !== tree.root && x === x.parent.right) {
            x = x.parent;
        }
        if (x === tree.root) {
            // well, it means we add a node to the end (inorder)
            return;
        }
        // x is the node whose right subtree is changed.
        x = x.parent;
        delta = calculateSize(x.left) - x.size_left;
        lf_delta = calculateLF(x.left) - x.lf_left;
        x.size_left += delta;
        x.lf_left += lf_delta;
        // go upwards till root. O(logN)
        while (x !== tree.root && (delta !== 0 || lf_delta !== 0)) {
            if (x.parent.left === x) {
                x.parent.size_left += delta;
                x.parent.lf_left += lf_delta;
            }
            x = x.parent;
        }
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[322/*vs/editor/common/model/prefixSumComputer*/], __M([1/*require*/,0/*exports*/,13/*vs/base/common/arrays*/,192/*vs/base/common/uint*/]), function (require, exports, arrays_1, uint_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.PrefixSumIndexOfResult = exports.ConstantTimePrefixSumComputer = exports.PrefixSumComputer = void 0;
    class PrefixSumComputer {
        constructor(values) {
            this.values = values;
            this.prefixSum = new Uint32Array(values.length);
            this.prefixSumValidIndex = new Int32Array(1);
            this.prefixSumValidIndex[0] = -1;
        }
        insertValues(insertIndex, insertValues) {
            insertIndex = (0, uint_1.toUint32)(insertIndex);
            const oldValues = this.values;
            const oldPrefixSum = this.prefixSum;
            const insertValuesLen = insertValues.length;
            if (insertValuesLen === 0) {
                return false;
            }
            this.values = new Uint32Array(oldValues.length + insertValuesLen);
            this.values.set(oldValues.subarray(0, insertIndex), 0);
            this.values.set(oldValues.subarray(insertIndex), insertIndex + insertValuesLen);
            this.values.set(insertValues, insertIndex);
            if (insertIndex - 1 < this.prefixSumValidIndex[0]) {
                this.prefixSumValidIndex[0] = insertIndex - 1;
            }
            this.prefixSum = new Uint32Array(this.values.length);
            if (this.prefixSumValidIndex[0] >= 0) {
                this.prefixSum.set(oldPrefixSum.subarray(0, this.prefixSumValidIndex[0] + 1));
            }
            return true;
        }
        setValue(index, value) {
            index = (0, uint_1.toUint32)(index);
            value = (0, uint_1.toUint32)(value);
            if (this.values[index] === value) {
                return false;
            }
            this.values[index] = value;
            if (index - 1 < this.prefixSumValidIndex[0]) {
                this.prefixSumValidIndex[0] = index - 1;
            }
            return true;
        }
        removeValues(startIndex, count) {
            startIndex = (0, uint_1.toUint32)(startIndex);
            count = (0, uint_1.toUint32)(count);
            const oldValues = this.values;
            const oldPrefixSum = this.prefixSum;
            if (startIndex >= oldValues.length) {
                return false;
            }
            const maxCount = oldValues.length - startIndex;
            if (count >= maxCount) {
                count = maxCount;
            }
            if (count === 0) {
                return false;
            }
            this.values = new Uint32Array(oldValues.length - count);
            this.values.set(oldValues.subarray(0, startIndex), 0);
            this.values.set(oldValues.subarray(startIndex + count), startIndex);
            this.prefixSum = new Uint32Array(this.values.length);
            if (startIndex - 1 < this.prefixSumValidIndex[0]) {
                this.prefixSumValidIndex[0] = startIndex - 1;
            }
            if (this.prefixSumValidIndex[0] >= 0) {
                this.prefixSum.set(oldPrefixSum.subarray(0, this.prefixSumValidIndex[0] + 1));
            }
            return true;
        }
        getTotalSum() {
            if (this.values.length === 0) {
                return 0;
            }
            return this._getPrefixSum(this.values.length - 1);
        }
        /**
         * Returns the sum of the first `index + 1` many items.
         * @returns `SUM(0 <= j <= index, values[j])`.
         */
        getPrefixSum(index) {
            if (index < 0) {
                return 0;
            }
            index = (0, uint_1.toUint32)(index);
            return this._getPrefixSum(index);
        }
        _getPrefixSum(index) {
            if (index <= this.prefixSumValidIndex[0]) {
                return this.prefixSum[index];
            }
            let startIndex = this.prefixSumValidIndex[0] + 1;
            if (startIndex === 0) {
                this.prefixSum[0] = this.values[0];
                startIndex++;
            }
            if (index >= this.values.length) {
                index = this.values.length - 1;
            }
            for (let i = startIndex; i <= index; i++) {
                this.prefixSum[i] = this.prefixSum[i - 1] + this.values[i];
            }
            this.prefixSumValidIndex[0] = Math.max(this.prefixSumValidIndex[0], index);
            return this.prefixSum[index];
        }
        getIndexOf(sum) {
            sum = Math.floor(sum);
            // Compute all sums (to get a fully valid prefixSum)
            this.getTotalSum();
            let low = 0;
            let high = this.values.length - 1;
            let mid = 0;
            let midStop = 0;
            let midStart = 0;
            while (low <= high) {
                mid = low + ((high - low) / 2) | 0;
                midStop = this.prefixSum[mid];
                midStart = midStop - this.values[mid];
                if (sum < midStart) {
                    high = mid - 1;
                }
                else if (sum >= midStop) {
                    low = mid + 1;
                }
                else {
                    break;
                }
            }
            return new PrefixSumIndexOfResult(mid, sum - midStart);
        }
    }
    exports.PrefixSumComputer = PrefixSumComputer;
    /**
     * {@link getIndexOf} has an amortized runtime complexity of O(1).
     *
     * ({@link PrefixSumComputer.getIndexOf} is just  O(log n))
    */
    class ConstantTimePrefixSumComputer {
        constructor(values) {
            this._values = values;
            this._isValid = false;
            this._validEndIndex = -1;
            this._prefixSum = [];
            this._indexBySum = [];
        }
        /**
         * @returns SUM(0 <= j < values.length, values[j])
         */
        getTotalSum() {
            this._ensureValid();
            return this._indexBySum.length;
        }
        /**
         * Returns the sum of the first `count` many items.
         * @returns `SUM(0 <= j < count, values[j])`.
         */
        getPrefixSum(count) {
            this._ensureValid();
            if (count === 0) {
                return 0;
            }
            return this._prefixSum[count - 1];
        }
        /**
         * @returns `result`, such that `getPrefixSum(result.index) + result.remainder = sum`
         */
        getIndexOf(sum) {
            this._ensureValid();
            const idx = this._indexBySum[sum];
            const viewLinesAbove = idx > 0 ? this._prefixSum[idx - 1] : 0;
            return new PrefixSumIndexOfResult(idx, sum - viewLinesAbove);
        }
        removeValues(start, deleteCount) {
            this._values.splice(start, deleteCount);
            this._invalidate(start);
        }
        insertValues(insertIndex, insertArr) {
            this._values = (0, arrays_1.arrayInsert)(this._values, insertIndex, insertArr);
            this._invalidate(insertIndex);
        }
        _invalidate(index) {
            this._isValid = false;
            this._validEndIndex = Math.min(this._validEndIndex, index - 1);
        }
        _ensureValid() {
            if (this._isValid) {
                return;
            }
            for (let i = this._validEndIndex + 1, len = this._values.length; i < len; i++) {
                const value = this._values[i];
                const sumAbove = i > 0 ? this._prefixSum[i - 1] : 0;
                this._prefixSum[i] = sumAbove + value;
                for (let j = 0; j < value; j++) {
                    this._indexBySum[sumAbove + j] = i;
                }
            }
            // trim things
            this._prefixSum.length = this._values.length;
            this._indexBySum.length = this._prefixSum[this._prefixSum.length - 1];
            // mark as valid
            this._isValid = true;
            this._validEndIndex = this._values.length - 1;
        }
        setValue(index, value) {
            if (this._values[index] === value) {
                // no change
                return;
            }
            this._values[index] = value;
            this._invalidate(index);
        }
    }
    exports.ConstantTimePrefixSumComputer = ConstantTimePrefixSumComputer;
    class PrefixSumIndexOfResult {
        constructor(index, remainder) {
            this.index = index;
            this.remainder = remainder;
            this._prefixSumIndexOfResultBrand = undefined;
            this.index = index;
            this.remainder = remainder;
        }
    }
    exports.PrefixSumIndexOfResult = PrefixSumIndexOfResult;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[580/*vs/editor/common/model/mirrorTextModel*/], __M([1/*require*/,0/*exports*/,11/*vs/base/common/strings*/,9/*vs/editor/common/core/position*/,322/*vs/editor/common/model/prefixSumComputer*/]), function (require, exports, strings_1, position_1, prefixSumComputer_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MirrorTextModel = void 0;
    class MirrorTextModel {
        constructor(uri, lines, eol, versionId) {
            this._uri = uri;
            this._lines = lines;
            this._eol = eol;
            this._versionId = versionId;
            this._lineStarts = null;
            this._cachedTextValue = null;
        }
        dispose() {
            this._lines.length = 0;
        }
        get version() {
            return this._versionId;
        }
        getText() {
            if (this._cachedTextValue === null) {
                this._cachedTextValue = this._lines.join(this._eol);
            }
            return this._cachedTextValue;
        }
        onEvents(e) {
            if (e.eol && e.eol !== this._eol) {
                this._eol = e.eol;
                this._lineStarts = null;
            }
            // Update my lines
            const changes = e.changes;
            for (const change of changes) {
                this._acceptDeleteRange(change.range);
                this._acceptInsertText(new position_1.Position(change.range.startLineNumber, change.range.startColumn), change.text);
            }
            this._versionId = e.versionId;
            this._cachedTextValue = null;
        }
        _ensureLineStarts() {
            if (!this._lineStarts) {
                const eolLength = this._eol.length;
                const linesLength = this._lines.length;
                const lineStartValues = new Uint32Array(linesLength);
                for (let i = 0; i < linesLength; i++) {
                    lineStartValues[i] = this._lines[i].length + eolLength;
                }
                this._lineStarts = new prefixSumComputer_1.PrefixSumComputer(lineStartValues);
            }
        }
        /**
         * All changes to a line's text go through this method
         */
        _setLineText(lineIndex, newValue) {
            this._lines[lineIndex] = newValue;
            if (this._lineStarts) {
                // update prefix sum
                this._lineStarts.setValue(lineIndex, this._lines[lineIndex].length + this._eol.length);
            }
        }
        _acceptDeleteRange(range) {
            if (range.startLineNumber === range.endLineNumber) {
                if (range.startColumn === range.endColumn) {
                    // Nothing to delete
                    return;
                }
                // Delete text on the affected line
                this._setLineText(range.startLineNumber - 1, this._lines[range.startLineNumber - 1].substring(0, range.startColumn - 1)
                    + this._lines[range.startLineNumber - 1].substring(range.endColumn - 1));
                return;
            }
            // Take remaining text on last line and append it to remaining text on first line
            this._setLineText(range.startLineNumber - 1, this._lines[range.startLineNumber - 1].substring(0, range.startColumn - 1)
                + this._lines[range.endLineNumber - 1].substring(range.endColumn - 1));
            // Delete middle lines
            this._lines.splice(range.startLineNumber, range.endLineNumber - range.startLineNumber);
            if (this._lineStarts) {
                // update prefix sum
                this._lineStarts.removeValues(range.startLineNumber, range.endLineNumber - range.startLineNumber);
            }
        }
        _acceptInsertText(position, insertText) {
            if (insertText.length === 0) {
                // Nothing to insert
                return;
            }
            const insertLines = (0, strings_1.splitLines)(insertText);
            if (insertLines.length === 1) {
                // Inserting text on one line
                this._setLineText(position.lineNumber - 1, this._lines[position.lineNumber - 1].substring(0, position.column - 1)
                    + insertLines[0]
                    + this._lines[position.lineNumber - 1].substring(position.column - 1));
                return;
            }
            // Append overflowing text from first line to the end of text to insert
            insertLines[insertLines.length - 1] += this._lines[position.lineNumber - 1].substring(position.column - 1);
            // Delete overflowing text from first line and insert text on first line
            this._setLineText(position.lineNumber - 1, this._lines[position.lineNumber - 1].substring(0, position.column - 1)
                + insertLines[0]);
            // Insert new lines & store lengths
            const newLengths = new Uint32Array(insertLines.length - 1);
            for (let i = 1; i < insertLines.length; i++) {
                this._lines.splice(position.lineNumber + i - 1, 0, insertLines[i]);
                newLengths[i - 1] = insertLines[i].length + this._eol.length;
            }
            if (this._lineStarts) {
                // update prefix sum
                this._lineStarts.insertValues(position.lineNumber, newLengths);
            }
        }
    }
    exports.MirrorTextModel = MirrorTextModel;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[323/*vs/editor/common/model/textModelPart*/], __M([1/*require*/,0/*exports*/,2/*vs/base/common/lifecycle*/]), function (require, exports, lifecycle_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.TextModelPart = void 0;
    class TextModelPart extends lifecycle_1.Disposable {
        constructor() {
            super(...arguments);
            this._isDisposed = false;
        }
        dispose() {
            super.dispose();
            this._isDisposed = true;
        }
        assertNotDisposed() {
            if (this._isDisposed) {
                throw new Error('TextModelPart is disposed!');
            }
        }
    }
    exports.TextModelPart = TextModelPart;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[202/*vs/editor/common/model/textModelSearch*/], __M([1/*require*/,0/*exports*/,11/*vs/base/common/strings*/,166/*vs/editor/common/core/wordCharacterClassifier*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/,40/*vs/editor/common/model*/]), function (require, exports, strings, wordCharacterClassifier_1, position_1, range_1, model_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Searcher = exports.TextModelSearch = exports.SearchParams = void 0;
    exports.isMultilineRegexSource = isMultilineRegexSource;
    exports.createFindMatch = createFindMatch;
    exports.isValidMatch = isValidMatch;
    const LIMIT_FIND_COUNT = 999;
    class SearchParams {
        constructor(searchString, isRegex, matchCase, wordSeparators) {
            this.searchString = searchString;
            this.isRegex = isRegex;
            this.matchCase = matchCase;
            this.wordSeparators = wordSeparators;
        }
        parseSearchRequest() {
            if (this.searchString === '') {
                return null;
            }
            // Try to create a RegExp out of the params
            let multiline;
            if (this.isRegex) {
                multiline = isMultilineRegexSource(this.searchString);
            }
            else {
                multiline = (this.searchString.indexOf('\n') >= 0);
            }
            let regex = null;
            try {
                regex = strings.createRegExp(this.searchString, this.isRegex, {
                    matchCase: this.matchCase,
                    wholeWord: false,
                    multiline: multiline,
                    global: true,
                    unicode: true
                });
            }
            catch (err) {
                return null;
            }
            if (!regex) {
                return null;
            }
            let canUseSimpleSearch = (!this.isRegex && !multiline);
            if (canUseSimpleSearch && this.searchString.toLowerCase() !== this.searchString.toUpperCase()) {
                // casing might make a difference
                canUseSimpleSearch = this.matchCase;
            }
            return new model_1.SearchData(regex, this.wordSeparators ? (0, wordCharacterClassifier_1.getMapForWordSeparators)(this.wordSeparators, []) : null, canUseSimpleSearch ? this.searchString : null);
        }
    }
    exports.SearchParams = SearchParams;
    function isMultilineRegexSource(searchString) {
        if (!searchString || searchString.length === 0) {
            return false;
        }
        for (let i = 0, len = searchString.length; i < len; i++) {
            const chCode = searchString.charCodeAt(i);
            if (chCode === 10 /* CharCode.LineFeed */) {
                return true;
            }
            if (chCode === 92 /* CharCode.Backslash */) {
                // move to next char
                i++;
                if (i >= len) {
                    // string ends with a \
                    break;
                }
                const nextChCode = searchString.charCodeAt(i);
                if (nextChCode === 110 /* CharCode.n */ || nextChCode === 114 /* CharCode.r */ || nextChCode === 87 /* CharCode.W */) {
                    return true;
                }
            }
        }
        return false;
    }
    function createFindMatch(range, rawMatches, captureMatches) {
        if (!captureMatches) {
            return new model_1.FindMatch(range, null);
        }
        const matches = [];
        for (let i = 0, len = rawMatches.length; i < len; i++) {
            matches[i] = rawMatches[i];
        }
        return new model_1.FindMatch(range, matches);
    }
    class LineFeedCounter {
        constructor(text) {
            const lineFeedsOffsets = [];
            let lineFeedsOffsetsLen = 0;
            for (let i = 0, textLen = text.length; i < textLen; i++) {
                if (text.charCodeAt(i) === 10 /* CharCode.LineFeed */) {
                    lineFeedsOffsets[lineFeedsOffsetsLen++] = i;
                }
            }
            this._lineFeedsOffsets = lineFeedsOffsets;
        }
        findLineFeedCountBeforeOffset(offset) {
            const lineFeedsOffsets = this._lineFeedsOffsets;
            let min = 0;
            let max = lineFeedsOffsets.length - 1;
            if (max === -1) {
                // no line feeds
                return 0;
            }
            if (offset <= lineFeedsOffsets[0]) {
                // before first line feed
                return 0;
            }
            while (min < max) {
                const mid = min + ((max - min) / 2 >> 0);
                if (lineFeedsOffsets[mid] >= offset) {
                    max = mid - 1;
                }
                else {
                    if (lineFeedsOffsets[mid + 1] >= offset) {
                        // bingo!
                        min = mid;
                        max = mid;
                    }
                    else {
                        min = mid + 1;
                    }
                }
            }
            return min + 1;
        }
    }
    class TextModelSearch {
        static findMatches(model, searchParams, searchRange, captureMatches, limitResultCount) {
            const searchData = searchParams.parseSearchRequest();
            if (!searchData) {
                return [];
            }
            if (searchData.regex.multiline) {
                return this._doFindMatchesMultiline(model, searchRange, new Searcher(searchData.wordSeparators, searchData.regex), captureMatches, limitResultCount);
            }
            return this._doFindMatchesLineByLine(model, searchRange, searchData, captureMatches, limitResultCount);
        }
        /**
         * Multiline search always executes on the lines concatenated with \n.
         * We must therefore compensate for the count of \n in case the model is CRLF
         */
        static _getMultilineMatchRange(model, deltaOffset, text, lfCounter, matchIndex, match0) {
            let startOffset;
            let lineFeedCountBeforeMatch = 0;
            if (lfCounter) {
                lineFeedCountBeforeMatch = lfCounter.findLineFeedCountBeforeOffset(matchIndex);
                startOffset = deltaOffset + matchIndex + lineFeedCountBeforeMatch /* add as many \r as there were \n */;
            }
            else {
                startOffset = deltaOffset + matchIndex;
            }
            let endOffset;
            if (lfCounter) {
                const lineFeedCountBeforeEndOfMatch = lfCounter.findLineFeedCountBeforeOffset(matchIndex + match0.length);
                const lineFeedCountInMatch = lineFeedCountBeforeEndOfMatch - lineFeedCountBeforeMatch;
                endOffset = startOffset + match0.length + lineFeedCountInMatch /* add as many \r as there were \n */;
            }
            else {
                endOffset = startOffset + match0.length;
            }
            const startPosition = model.getPositionAt(startOffset);
            const endPosition = model.getPositionAt(endOffset);
            return new range_1.Range(startPosition.lineNumber, startPosition.column, endPosition.lineNumber, endPosition.column);
        }
        static _doFindMatchesMultiline(model, searchRange, searcher, captureMatches, limitResultCount) {
            const deltaOffset = model.getOffsetAt(searchRange.getStartPosition());
            // We always execute multiline search over the lines joined with \n
            // This makes it that \n will match the EOL for both CRLF and LF models
            // We compensate for offset errors in `_getMultilineMatchRange`
            const text = model.getValueInRange(searchRange, 1 /* EndOfLinePreference.LF */);
            const lfCounter = (model.getEOL() === '\r\n' ? new LineFeedCounter(text) : null);
            const result = [];
            let counter = 0;
            let m;
            searcher.reset(0);
            while ((m = searcher.next(text))) {
                result[counter++] = createFindMatch(this._getMultilineMatchRange(model, deltaOffset, text, lfCounter, m.index, m[0]), m, captureMatches);
                if (counter >= limitResultCount) {
                    return result;
                }
            }
            return result;
        }
        static _doFindMatchesLineByLine(model, searchRange, searchData, captureMatches, limitResultCount) {
            const result = [];
            let resultLen = 0;
            // Early case for a search range that starts & stops on the same line number
            if (searchRange.startLineNumber === searchRange.endLineNumber) {
                const text = model.getLineContent(searchRange.startLineNumber).substring(searchRange.startColumn - 1, searchRange.endColumn - 1);
                resultLen = this._findMatchesInLine(searchData, text, searchRange.startLineNumber, searchRange.startColumn - 1, resultLen, result, captureMatches, limitResultCount);
                return result;
            }
            // Collect results from first line
            const text = model.getLineContent(searchRange.startLineNumber).substring(searchRange.startColumn - 1);
            resultLen = this._findMatchesInLine(searchData, text, searchRange.startLineNumber, searchRange.startColumn - 1, resultLen, result, captureMatches, limitResultCount);
            // Collect results from middle lines
            for (let lineNumber = searchRange.startLineNumber + 1; lineNumber < searchRange.endLineNumber && resultLen < limitResultCount; lineNumber++) {
                resultLen = this._findMatchesInLine(searchData, model.getLineContent(lineNumber), lineNumber, 0, resultLen, result, captureMatches, limitResultCount);
            }
            // Collect results from last line
            if (resultLen < limitResultCount) {
                const text = model.getLineContent(searchRange.endLineNumber).substring(0, searchRange.endColumn - 1);
                resultLen = this._findMatchesInLine(searchData, text, searchRange.endLineNumber, 0, resultLen, result, captureMatches, limitResultCount);
            }
            return result;
        }
        static _findMatchesInLine(searchData, text, lineNumber, deltaOffset, resultLen, result, captureMatches, limitResultCount) {
            const wordSeparators = searchData.wordSeparators;
            if (!captureMatches && searchData.simpleSearch) {
                const searchString = searchData.simpleSearch;
                const searchStringLen = searchString.length;
                const textLength = text.length;
                let lastMatchIndex = -searchStringLen;
                while ((lastMatchIndex = text.indexOf(searchString, lastMatchIndex + searchStringLen)) !== -1) {
                    if (!wordSeparators || isValidMatch(wordSeparators, text, textLength, lastMatchIndex, searchStringLen)) {
                        result[resultLen++] = new model_1.FindMatch(new range_1.Range(lineNumber, lastMatchIndex + 1 + deltaOffset, lineNumber, lastMatchIndex + 1 + searchStringLen + deltaOffset), null);
                        if (resultLen >= limitResultCount) {
                            return resultLen;
                        }
                    }
                }
                return resultLen;
            }
            const searcher = new Searcher(searchData.wordSeparators, searchData.regex);
            let m;
            // Reset regex to search from the beginning
            searcher.reset(0);
            do {
                m = searcher.next(text);
                if (m) {
                    result[resultLen++] = createFindMatch(new range_1.Range(lineNumber, m.index + 1 + deltaOffset, lineNumber, m.index + 1 + m[0].length + deltaOffset), m, captureMatches);
                    if (resultLen >= limitResultCount) {
                        return resultLen;
                    }
                }
            } while (m);
            return resultLen;
        }
        static findNextMatch(model, searchParams, searchStart, captureMatches) {
            const searchData = searchParams.parseSearchRequest();
            if (!searchData) {
                return null;
            }
            const searcher = new Searcher(searchData.wordSeparators, searchData.regex);
            if (searchData.regex.multiline) {
                return this._doFindNextMatchMultiline(model, searchStart, searcher, captureMatches);
            }
            return this._doFindNextMatchLineByLine(model, searchStart, searcher, captureMatches);
        }
        static _doFindNextMatchMultiline(model, searchStart, searcher, captureMatches) {
            const searchTextStart = new position_1.Position(searchStart.lineNumber, 1);
            const deltaOffset = model.getOffsetAt(searchTextStart);
            const lineCount = model.getLineCount();
            // We always execute multiline search over the lines joined with \n
            // This makes it that \n will match the EOL for both CRLF and LF models
            // We compensate for offset errors in `_getMultilineMatchRange`
            const text = model.getValueInRange(new range_1.Range(searchTextStart.lineNumber, searchTextStart.column, lineCount, model.getLineMaxColumn(lineCount)), 1 /* EndOfLinePreference.LF */);
            const lfCounter = (model.getEOL() === '\r\n' ? new LineFeedCounter(text) : null);
            searcher.reset(searchStart.column - 1);
            const m = searcher.next(text);
            if (m) {
                return createFindMatch(this._getMultilineMatchRange(model, deltaOffset, text, lfCounter, m.index, m[0]), m, captureMatches);
            }
            if (searchStart.lineNumber !== 1 || searchStart.column !== 1) {
                // Try again from the top
                return this._doFindNextMatchMultiline(model, new position_1.Position(1, 1), searcher, captureMatches);
            }
            return null;
        }
        static _doFindNextMatchLineByLine(model, searchStart, searcher, captureMatches) {
            const lineCount = model.getLineCount();
            const startLineNumber = searchStart.lineNumber;
            // Look in first line
            const text = model.getLineContent(startLineNumber);
            const r = this._findFirstMatchInLine(searcher, text, startLineNumber, searchStart.column, captureMatches);
            if (r) {
                return r;
            }
            for (let i = 1; i <= lineCount; i++) {
                const lineIndex = (startLineNumber + i - 1) % lineCount;
                const text = model.getLineContent(lineIndex + 1);
                const r = this._findFirstMatchInLine(searcher, text, lineIndex + 1, 1, captureMatches);
                if (r) {
                    return r;
                }
            }
            return null;
        }
        static _findFirstMatchInLine(searcher, text, lineNumber, fromColumn, captureMatches) {
            // Set regex to search from column
            searcher.reset(fromColumn - 1);
            const m = searcher.next(text);
            if (m) {
                return createFindMatch(new range_1.Range(lineNumber, m.index + 1, lineNumber, m.index + 1 + m[0].length), m, captureMatches);
            }
            return null;
        }
        static findPreviousMatch(model, searchParams, searchStart, captureMatches) {
            const searchData = searchParams.parseSearchRequest();
            if (!searchData) {
                return null;
            }
            const searcher = new Searcher(searchData.wordSeparators, searchData.regex);
            if (searchData.regex.multiline) {
                return this._doFindPreviousMatchMultiline(model, searchStart, searcher, captureMatches);
            }
            return this._doFindPreviousMatchLineByLine(model, searchStart, searcher, captureMatches);
        }
        static _doFindPreviousMatchMultiline(model, searchStart, searcher, captureMatches) {
            const matches = this._doFindMatchesMultiline(model, new range_1.Range(1, 1, searchStart.lineNumber, searchStart.column), searcher, captureMatches, 10 * LIMIT_FIND_COUNT);
            if (matches.length > 0) {
                return matches[matches.length - 1];
            }
            const lineCount = model.getLineCount();
            if (searchStart.lineNumber !== lineCount || searchStart.column !== model.getLineMaxColumn(lineCount)) {
                // Try again with all content
                return this._doFindPreviousMatchMultiline(model, new position_1.Position(lineCount, model.getLineMaxColumn(lineCount)), searcher, captureMatches);
            }
            return null;
        }
        static _doFindPreviousMatchLineByLine(model, searchStart, searcher, captureMatches) {
            const lineCount = model.getLineCount();
            const startLineNumber = searchStart.lineNumber;
            // Look in first line
            const text = model.getLineContent(startLineNumber).substring(0, searchStart.column - 1);
            const r = this._findLastMatchInLine(searcher, text, startLineNumber, captureMatches);
            if (r) {
                return r;
            }
            for (let i = 1; i <= lineCount; i++) {
                const lineIndex = (lineCount + startLineNumber - i - 1) % lineCount;
                const text = model.getLineContent(lineIndex + 1);
                const r = this._findLastMatchInLine(searcher, text, lineIndex + 1, captureMatches);
                if (r) {
                    return r;
                }
            }
            return null;
        }
        static _findLastMatchInLine(searcher, text, lineNumber, captureMatches) {
            let bestResult = null;
            let m;
            searcher.reset(0);
            while ((m = searcher.next(text))) {
                bestResult = createFindMatch(new range_1.Range(lineNumber, m.index + 1, lineNumber, m.index + 1 + m[0].length), m, captureMatches);
            }
            return bestResult;
        }
    }
    exports.TextModelSearch = TextModelSearch;
    function leftIsWordBounday(wordSeparators, text, textLength, matchStartIndex, matchLength) {
        if (matchStartIndex === 0) {
            // Match starts at start of string
            return true;
        }
        const charBefore = text.charCodeAt(matchStartIndex - 1);
        if (wordSeparators.get(charBefore) !== 0 /* WordCharacterClass.Regular */) {
            // The character before the match is a word separator
            return true;
        }
        if (charBefore === 13 /* CharCode.CarriageReturn */ || charBefore === 10 /* CharCode.LineFeed */) {
            // The character before the match is line break or carriage return.
            return true;
        }
        if (matchLength > 0) {
            const firstCharInMatch = text.charCodeAt(matchStartIndex);
            if (wordSeparators.get(firstCharInMatch) !== 0 /* WordCharacterClass.Regular */) {
                // The first character inside the match is a word separator
                return true;
            }
        }
        return false;
    }
    function rightIsWordBounday(wordSeparators, text, textLength, matchStartIndex, matchLength) {
        if (matchStartIndex + matchLength === textLength) {
            // Match ends at end of string
            return true;
        }
        const charAfter = text.charCodeAt(matchStartIndex + matchLength);
        if (wordSeparators.get(charAfter) !== 0 /* WordCharacterClass.Regular */) {
            // The character after the match is a word separator
            return true;
        }
        if (charAfter === 13 /* CharCode.CarriageReturn */ || charAfter === 10 /* CharCode.LineFeed */) {
            // The character after the match is line break or carriage return.
            return true;
        }
        if (matchLength > 0) {
            const lastCharInMatch = text.charCodeAt(matchStartIndex + matchLength - 1);
            if (wordSeparators.get(lastCharInMatch) !== 0 /* WordCharacterClass.Regular */) {
                // The last character in the match is a word separator
                return true;
            }
        }
        return false;
    }
    function isValidMatch(wordSeparators, text, textLength, matchStartIndex, matchLength) {
        return (leftIsWordBounday(wordSeparators, text, textLength, matchStartIndex, matchLength)
            && rightIsWordBounday(wordSeparators, text, textLength, matchStartIndex, matchLength));
    }
    class Searcher {
        constructor(wordSeparators, searchRegex) {
            this._wordSeparators = wordSeparators;
            this._searchRegex = searchRegex;
            this._prevMatchStartIndex = -1;
            this._prevMatchLength = 0;
        }
        reset(lastIndex) {
            this._searchRegex.lastIndex = lastIndex;
            this._prevMatchStartIndex = -1;
            this._prevMatchLength = 0;
        }
        next(text) {
            const textLength = text.length;
            let m;
            do {
                if (this._prevMatchStartIndex + this._prevMatchLength === textLength) {
                    // Reached the end of the line
                    return null;
                }
                m = this._searchRegex.exec(text);
                if (!m) {
                    return null;
                }
                const matchStartIndex = m.index;
                const matchLength = m[0].length;
                if (matchStartIndex === this._prevMatchStartIndex && matchLength === this._prevMatchLength) {
                    if (matchLength === 0) {
                        // the search result is an empty string and won't advance `regex.lastIndex`, so `regex.exec` will stuck here
                        // we attempt to recover from that by advancing by two if surrogate pair found and by one otherwise
                        if (strings.getNextCodePoint(text, textLength, this._searchRegex.lastIndex) > 0xFFFF) {
                            this._searchRegex.lastIndex += 2;
                        }
                        else {
                            this._searchRegex.lastIndex += 1;
                        }
                        continue;
                    }
                    // Exit early if the regex matches the same range twice
                    return null;
                }
                this._prevMatchStartIndex = matchStartIndex;
                this._prevMatchLength = matchLength;
                if (!this._wordSeparators || isValidMatch(this._wordSeparators, text, textLength, matchStartIndex, matchLength)) {
                    return m;
                }
            } while (m);
            return null;
        }
    }
    exports.Searcher = Searcher;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[324/*vs/editor/common/model/pieceTreeTextBuffer/pieceTreeBase*/], __M([1/*require*/,0/*exports*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/,40/*vs/editor/common/model*/,579/*vs/editor/common/model/pieceTreeTextBuffer/rbTreeBase*/,202/*vs/editor/common/model/textModelSearch*/]), function (require, exports, position_1, range_1, model_1, rbTreeBase_1, textModelSearch_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.PieceTreeBase = exports.StringBuffer = exports.Piece = void 0;
    exports.createLineStartsFast = createLineStartsFast;
    exports.createLineStarts = createLineStarts;
    // const lfRegex = new RegExp(/\r\n|\r|\n/g);
    const AverageBufferSize = 65535;
    function createUintArray(arr) {
        let r;
        if (arr[arr.length - 1] < 65536) {
            r = new Uint16Array(arr.length);
        }
        else {
            r = new Uint32Array(arr.length);
        }
        r.set(arr, 0);
        return r;
    }
    class LineStarts {
        constructor(lineStarts, cr, lf, crlf, isBasicASCII) {
            this.lineStarts = lineStarts;
            this.cr = cr;
            this.lf = lf;
            this.crlf = crlf;
            this.isBasicASCII = isBasicASCII;
        }
    }
    function createLineStartsFast(str, readonly = true) {
        const r = [0];
        let rLength = 1;
        for (let i = 0, len = str.length; i < len; i++) {
            const chr = str.charCodeAt(i);
            if (chr === 13 /* CharCode.CarriageReturn */) {
                if (i + 1 < len && str.charCodeAt(i + 1) === 10 /* CharCode.LineFeed */) {
                    // \r\n... case
                    r[rLength++] = i + 2;
                    i++; // skip \n
                }
                else {
                    // \r... case
                    r[rLength++] = i + 1;
                }
            }
            else if (chr === 10 /* CharCode.LineFeed */) {
                r[rLength++] = i + 1;
            }
        }
        if (readonly) {
            return createUintArray(r);
        }
        else {
            return r;
        }
    }
    function createLineStarts(r, str) {
        r.length = 0;
        r[0] = 0;
        let rLength = 1;
        let cr = 0, lf = 0, crlf = 0;
        let isBasicASCII = true;
        for (let i = 0, len = str.length; i < len; i++) {
            const chr = str.charCodeAt(i);
            if (chr === 13 /* CharCode.CarriageReturn */) {
                if (i + 1 < len && str.charCodeAt(i + 1) === 10 /* CharCode.LineFeed */) {
                    // \r\n... case
                    crlf++;
                    r[rLength++] = i + 2;
                    i++; // skip \n
                }
                else {
                    cr++;
                    // \r... case
                    r[rLength++] = i + 1;
                }
            }
            else if (chr === 10 /* CharCode.LineFeed */) {
                lf++;
                r[rLength++] = i + 1;
            }
            else {
                if (isBasicASCII) {
                    if (chr !== 9 /* CharCode.Tab */ && (chr < 32 || chr > 126)) {
                        isBasicASCII = false;
                    }
                }
            }
        }
        const result = new LineStarts(createUintArray(r), cr, lf, crlf, isBasicASCII);
        r.length = 0;
        return result;
    }
    class Piece {
        constructor(bufferIndex, start, end, lineFeedCnt, length) {
            this.bufferIndex = bufferIndex;
            this.start = start;
            this.end = end;
            this.lineFeedCnt = lineFeedCnt;
            this.length = length;
        }
    }
    exports.Piece = Piece;
    class StringBuffer {
        constructor(buffer, lineStarts) {
            this.buffer = buffer;
            this.lineStarts = lineStarts;
        }
    }
    exports.StringBuffer = StringBuffer;
    /**
     * Readonly snapshot for piece tree.
     * In a real multiple thread environment, to make snapshot reading always work correctly, we need to
     * 1. Make TreeNode.piece immutable, then reading and writing can run in parallel.
     * 2. TreeNode/Buffers normalization should not happen during snapshot reading.
     */
    class PieceTreeSnapshot {
        constructor(tree, BOM) {
            this._pieces = [];
            this._tree = tree;
            this._BOM = BOM;
            this._index = 0;
            if (tree.root !== rbTreeBase_1.SENTINEL) {
                tree.iterate(tree.root, node => {
                    if (node !== rbTreeBase_1.SENTINEL) {
                        this._pieces.push(node.piece);
                    }
                    return true;
                });
            }
        }
        read() {
            if (this._pieces.length === 0) {
                if (this._index === 0) {
                    this._index++;
                    return this._BOM;
                }
                else {
                    return null;
                }
            }
            if (this._index > this._pieces.length - 1) {
                return null;
            }
            if (this._index === 0) {
                return this._BOM + this._tree.getPieceContent(this._pieces[this._index++]);
            }
            return this._tree.getPieceContent(this._pieces[this._index++]);
        }
    }
    class PieceTreeSearchCache {
        constructor(limit) {
            this._limit = limit;
            this._cache = [];
        }
        get(offset) {
            for (let i = this._cache.length - 1; i >= 0; i--) {
                const nodePos = this._cache[i];
                if (nodePos.nodeStartOffset <= offset && nodePos.nodeStartOffset + nodePos.node.piece.length >= offset) {
                    return nodePos;
                }
            }
            return null;
        }
        get2(lineNumber) {
            for (let i = this._cache.length - 1; i >= 0; i--) {
                const nodePos = this._cache[i];
                if (nodePos.nodeStartLineNumber && nodePos.nodeStartLineNumber < lineNumber && nodePos.nodeStartLineNumber + nodePos.node.piece.lineFeedCnt >= lineNumber) {
                    return nodePos;
                }
            }
            return null;
        }
        set(nodePosition) {
            if (this._cache.length >= this._limit) {
                this._cache.shift();
            }
            this._cache.push(nodePosition);
        }
        validate(offset) {
            let hasInvalidVal = false;
            const tmp = this._cache;
            for (let i = 0; i < tmp.length; i++) {
                const nodePos = tmp[i];
                if (nodePos.node.parent === null || nodePos.nodeStartOffset >= offset) {
                    tmp[i] = null;
                    hasInvalidVal = true;
                    continue;
                }
            }
            if (hasInvalidVal) {
                const newArr = [];
                for (const entry of tmp) {
                    if (entry !== null) {
                        newArr.push(entry);
                    }
                }
                this._cache = newArr;
            }
        }
    }
    class PieceTreeBase {
        constructor(chunks, eol, eolNormalized) {
            this.create(chunks, eol, eolNormalized);
        }
        create(chunks, eol, eolNormalized) {
            this._buffers = [
                new StringBuffer('', [0])
            ];
            this._lastChangeBufferPos = { line: 0, column: 0 };
            this.root = rbTreeBase_1.SENTINEL;
            this._lineCnt = 1;
            this._length = 0;
            this._EOL = eol;
            this._EOLLength = eol.length;
            this._EOLNormalized = eolNormalized;
            let lastNode = null;
            for (let i = 0, len = chunks.length; i < len; i++) {
                if (chunks[i].buffer.length > 0) {
                    if (!chunks[i].lineStarts) {
                        chunks[i].lineStarts = createLineStartsFast(chunks[i].buffer);
                    }
                    const 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);
                    this._buffers.push(chunks[i]);
                    lastNode = this.rbInsertRight(lastNode, piece);
                }
            }
            this._searchCache = new PieceTreeSearchCache(1);
            this._lastVisitedLine = { lineNumber: 0, value: '' };
            this.computeBufferMetadata();
        }
        normalizeEOL(eol) {
            const averageBufferSize = AverageBufferSize;
            const min = averageBufferSize - Math.floor(averageBufferSize / 3);
            const max = min * 2;
            let tempChunk = '';
            let tempChunkLen = 0;
            const chunks = [];
            this.iterate(this.root, node => {
                const str = this.getNodeContent(node);
                const len = str.length;
                if (tempChunkLen <= min || tempChunkLen + len < max) {
                    tempChunk += str;
                    tempChunkLen += len;
                    return true;
                }
                // flush anyways
                const text = tempChunk.replace(/\r\n|\r|\n/g, eol);
                chunks.push(new StringBuffer(text, createLineStartsFast(text)));
                tempChunk = str;
                tempChunkLen = len;
                return true;
            });
            if (tempChunkLen > 0) {
                const text = tempChunk.replace(/\r\n|\r|\n/g, eol);
                chunks.push(new StringBuffer(text, createLineStartsFast(text)));
            }
            this.create(chunks, eol, true);
        }
        // #region Buffer API
        getEOL() {
            return this._EOL;
        }
        setEOL(newEOL) {
            this._EOL = newEOL;
            this._EOLLength = this._EOL.length;
            this.normalizeEOL(newEOL);
        }
        createSnapshot(BOM) {
            return new PieceTreeSnapshot(this, BOM);
        }
        getOffsetAt(lineNumber, column) {
            let leftLen = 0; // inorder
            let x = this.root;
            while (x !== rbTreeBase_1.SENTINEL) {
                if (x.left !== rbTreeBase_1.SENTINEL && x.lf_left + 1 >= lineNumber) {
                    x = x.left;
                }
                else if (x.lf_left + x.piece.lineFeedCnt + 1 >= lineNumber) {
                    leftLen += x.size_left;
                    // lineNumber >= 2
                    const accumualtedValInCurrentIndex = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2);
                    return leftLen += accumualtedValInCurrentIndex + column - 1;
                }
                else {
                    lineNumber -= x.lf_left + x.piece.lineFeedCnt;
                    leftLen += x.size_left + x.piece.length;
                    x = x.right;
                }
            }
            return leftLen;
        }
        getPositionAt(offset) {
            offset = Math.floor(offset);
            offset = Math.max(0, offset);
            let x = this.root;
            let lfCnt = 0;
            const originalOffset = offset;
            while (x !== rbTreeBase_1.SENTINEL) {
                if (x.size_left !== 0 && x.size_left >= offset) {
                    x = x.left;
                }
                else if (x.size_left + x.piece.length >= offset) {
                    const out = this.getIndexOf(x, offset - x.size_left);
                    lfCnt += x.lf_left + out.index;
                    if (out.index === 0) {
                        const lineStartOffset = this.getOffsetAt(lfCnt + 1, 1);
                        const column = originalOffset - lineStartOffset;
                        return new position_1.Position(lfCnt + 1, column + 1);
                    }
                    return new position_1.Position(lfCnt + 1, out.remainder + 1);
                }
                else {
                    offset -= x.size_left + x.piece.length;
                    lfCnt += x.lf_left + x.piece.lineFeedCnt;
                    if (x.right === rbTreeBase_1.SENTINEL) {
                        // last node
                        const lineStartOffset = this.getOffsetAt(lfCnt + 1, 1);
                        const column = originalOffset - offset - lineStartOffset;
                        return new position_1.Position(lfCnt + 1, column + 1);
                    }
                    else {
                        x = x.right;
                    }
                }
            }
            return new position_1.Position(1, 1);
        }
        getValueInRange(range, eol) {
            if (range.startLineNumber === range.endLineNumber && range.startColumn === range.endColumn) {
                return '';
            }
            const startPosition = this.nodeAt2(range.startLineNumber, range.startColumn);
            const endPosition = this.nodeAt2(range.endLineNumber, range.endColumn);
            const value = this.getValueInRange2(startPosition, endPosition);
            if (eol) {
                if (eol !== this._EOL || !this._EOLNormalized) {
                    return value.replace(/\r\n|\r|\n/g, eol);
                }
                if (eol === this.getEOL() && this._EOLNormalized) {
                    if (eol === '\r\n') {
                    }
                    return value;
                }
                return value.replace(/\r\n|\r|\n/g, eol);
            }
            return value;
        }
        getValueInRange2(startPosition, endPosition) {
            if (startPosition.node === endPosition.node) {
                const node = startPosition.node;
                const buffer = this._buffers[node.piece.bufferIndex].buffer;
                const startOffset = this.offsetInBuffer(node.piece.bufferIndex, node.piece.start);
                return buffer.substring(startOffset + startPosition.remainder, startOffset + endPosition.remainder);
            }
            let x = startPosition.node;
            const buffer = this._buffers[x.piece.bufferIndex].buffer;
            const startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);
            let ret = buffer.substring(startOffset + startPosition.remainder, startOffset + x.piece.length);
            x = x.next();
            while (x !== rbTreeBase_1.SENTINEL) {
                const buffer = this._buffers[x.piece.bufferIndex].buffer;
                const startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);
                if (x === endPosition.node) {
                    ret += buffer.substring(startOffset, startOffset + endPosition.remainder);
                    break;
                }
                else {
                    ret += buffer.substr(startOffset, x.piece.length);
                }
                x = x.next();
            }
            return ret;
        }
        getLinesContent() {
            const lines = [];
            let linesLength = 0;
            let currentLine = '';
            let danglingCR = false;
            this.iterate(this.root, node => {
                if (node === rbTreeBase_1.SENTINEL) {
                    return true;
                }
                const piece = node.piece;
                let pieceLength = piece.length;
                if (pieceLength === 0) {
                    return true;
                }
                const buffer = this._buffers[piece.bufferIndex].buffer;
                const lineStarts = this._buffers[piece.bufferIndex].lineStarts;
                const pieceStartLine = piece.start.line;
                const pieceEndLine = piece.end.line;
                let pieceStartOffset = lineStarts[pieceStartLine] + piece.start.column;
                if (danglingCR) {
                    if (buffer.charCodeAt(pieceStartOffset) === 10 /* CharCode.LineFeed */) {
                        // pretend the \n was in the previous piece..
                        pieceStartOffset++;
                        pieceLength--;
                    }
                    lines[linesLength++] = currentLine;
                    currentLine = '';
                    danglingCR = false;
                    if (pieceLength === 0) {
                        return true;
                    }
                }
                if (pieceStartLine === pieceEndLine) {
                    // this piece has no new lines
                    if (!this._EOLNormalized && buffer.charCodeAt(pieceStartOffset + pieceLength - 1) === 13 /* CharCode.CarriageReturn */) {
                        danglingCR = true;
                        currentLine += buffer.substr(pieceStartOffset, pieceLength - 1);
                    }
                    else {
                        currentLine += buffer.substr(pieceStartOffset, pieceLength);
                    }
                    return true;
                }
                // add the text before the first line start in this piece
                currentLine += (this._EOLNormalized
                    ? buffer.substring(pieceStartOffset, Math.max(pieceStartOffset, lineStarts[pieceStartLine + 1] - this._EOLLength))
                    : buffer.substring(pieceStartOffset, lineStarts[pieceStartLine + 1]).replace(/(\r\n|\r|\n)$/, ''));
                lines[linesLength++] = currentLine;
                for (let line = pieceStartLine + 1; line < pieceEndLine; line++) {
                    currentLine = (this._EOLNormalized
                        ? buffer.substring(lineStarts[line], lineStarts[line + 1] - this._EOLLength)
                        : buffer.substring(lineStarts[line], lineStarts[line + 1]).replace(/(\r\n|\r|\n)$/, ''));
                    lines[linesLength++] = currentLine;
                }
                if (!this._EOLNormalized && buffer.charCodeAt(lineStarts[pieceEndLine] + piece.end.column - 1) === 13 /* CharCode.CarriageReturn */) {
                    danglingCR = true;
                    if (piece.end.column === 0) {
                        // The last line ended with a \r, let's undo the push, it will be pushed by next iteration
                        linesLength--;
                    }
                    else {
                        currentLine = buffer.substr(lineStarts[pieceEndLine], piece.end.column - 1);
                    }
                }
                else {
                    currentLine = buffer.substr(lineStarts[pieceEndLine], piece.end.column);
                }
                return true;
            });
            if (danglingCR) {
                lines[linesLength++] = currentLine;
                currentLine = '';
            }
            lines[linesLength++] = currentLine;
            return lines;
        }
        getLength() {
            return this._length;
        }
        getLineCount() {
            return this._lineCnt;
        }
        getLineContent(lineNumber) {
            if (this._lastVisitedLine.lineNumber === lineNumber) {
                return this._lastVisitedLine.value;
            }
            this._lastVisitedLine.lineNumber = lineNumber;
            if (lineNumber === this._lineCnt) {
                this._lastVisitedLine.value = this.getLineRawContent(lineNumber);
            }
            else if (this._EOLNormalized) {
                this._lastVisitedLine.value = this.getLineRawContent(lineNumber, this._EOLLength);
            }
            else {
                this._lastVisitedLine.value = this.getLineRawContent(lineNumber).replace(/(\r\n|\r|\n)$/, '');
            }
            return this._lastVisitedLine.value;
        }
        _getCharCode(nodePos) {
            if (nodePos.remainder === nodePos.node.piece.length) {
                // the char we want to fetch is at the head of next node.
                const matchingNode = nodePos.node.next();
                if (!matchingNode) {
                    return 0;
                }
                const buffer = this._buffers[matchingNode.piece.bufferIndex];
                const startOffset = this.offsetInBuffer(matchingNode.piece.bufferIndex, matchingNode.piece.start);
                return buffer.buffer.charCodeAt(startOffset);
            }
            else {
                const buffer = this._buffers[nodePos.node.piece.bufferIndex];
                const startOffset = this.offsetInBuffer(nodePos.node.piece.bufferIndex, nodePos.node.piece.start);
                const targetOffset = startOffset + nodePos.remainder;
                return buffer.buffer.charCodeAt(targetOffset);
            }
        }
        getLineCharCode(lineNumber, index) {
            const nodePos = this.nodeAt2(lineNumber, index + 1);
            return this._getCharCode(nodePos);
        }
        getLineLength(lineNumber) {
            if (lineNumber === this.getLineCount()) {
                const startOffset = this.getOffsetAt(lineNumber, 1);
                return this.getLength() - startOffset;
            }
            return this.getOffsetAt(lineNumber + 1, 1) - this.getOffsetAt(lineNumber, 1) - this._EOLLength;
        }
        findMatchesInNode(node, searcher, startLineNumber, startColumn, startCursor, endCursor, searchData, captureMatches, limitResultCount, resultLen, result) {
            const buffer = this._buffers[node.piece.bufferIndex];
            const startOffsetInBuffer = this.offsetInBuffer(node.piece.bufferIndex, node.piece.start);
            const start = this.offsetInBuffer(node.piece.bufferIndex, startCursor);
            const end = this.offsetInBuffer(node.piece.bufferIndex, endCursor);
            let m;
            // Reset regex to search from the beginning
            const ret = { line: 0, column: 0 };
            let searchText;
            let offsetInBuffer;
            if (searcher._wordSeparators) {
                searchText = buffer.buffer.substring(start, end);
                offsetInBuffer = (offset) => offset + start;
                searcher.reset(0);
            }
            else {
                searchText = buffer.buffer;
                offsetInBuffer = (offset) => offset;
                searcher.reset(start);
            }
            do {
                m = searcher.next(searchText);
                if (m) {
                    if (offsetInBuffer(m.index) >= end) {
                        return resultLen;
                    }
                    this.positionInBuffer(node, offsetInBuffer(m.index) - startOffsetInBuffer, ret);
                    const lineFeedCnt = this.getLineFeedCnt(node.piece.bufferIndex, startCursor, ret);
                    const retStartColumn = ret.line === startCursor.line ? ret.column - startCursor.column + startColumn : ret.column + 1;
                    const retEndColumn = retStartColumn + m[0].length;
                    result[resultLen++] = (0, textModelSearch_1.createFindMatch)(new range_1.Range(startLineNumber + lineFeedCnt, retStartColumn, startLineNumber + lineFeedCnt, retEndColumn), m, captureMatches);
                    if (offsetInBuffer(m.index) + m[0].length >= end) {
                        return resultLen;
                    }
                    if (resultLen >= limitResultCount) {
                        return resultLen;
                    }
                }
            } while (m);
            return resultLen;
        }
        findMatchesLineByLine(searchRange, searchData, captureMatches, limitResultCount) {
            const result = [];
            let resultLen = 0;
            const searcher = new textModelSearch_1.Searcher(searchData.wordSeparators, searchData.regex);
            let startPosition = this.nodeAt2(searchRange.startLineNumber, searchRange.startColumn);
            if (startPosition === null) {
                return [];
            }
            const endPosition = this.nodeAt2(searchRange.endLineNumber, searchRange.endColumn);
            if (endPosition === null) {
                return [];
            }
            let start = this.positionInBuffer(startPosition.node, startPosition.remainder);
            const end = this.positionInBuffer(endPosition.node, endPosition.remainder);
            if (startPosition.node === endPosition.node) {
                this.findMatchesInNode(startPosition.node, searcher, searchRange.startLineNumber, searchRange.startColumn, start, end, searchData, captureMatches, limitResultCount, resultLen, result);
                return result;
            }
            let startLineNumber = searchRange.startLineNumber;
            let currentNode = startPosition.node;
            while (currentNode !== endPosition.node) {
                const lineBreakCnt = this.getLineFeedCnt(currentNode.piece.bufferIndex, start, currentNode.piece.end);
                if (lineBreakCnt >= 1) {
                    // last line break position
                    const lineStarts = this._buffers[currentNode.piece.bufferIndex].lineStarts;
                    const startOffsetInBuffer = this.offsetInBuffer(currentNode.piece.bufferIndex, currentNode.piece.start);
                    const nextLineStartOffset = lineStarts[start.line + lineBreakCnt];
                    const startColumn = startLineNumber === searchRange.startLineNumber ? searchRange.startColumn : 1;
                    resultLen = this.findMatchesInNode(currentNode, searcher, startLineNumber, startColumn, start, this.positionInBuffer(currentNode, nextLineStartOffset - startOffsetInBuffer), searchData, captureMatches, limitResultCount, resultLen, result);
                    if (resultLen >= limitResultCount) {
                        return result;
                    }
                    startLineNumber += lineBreakCnt;
                }
                const startColumn = startLineNumber === searchRange.startLineNumber ? searchRange.startColumn - 1 : 0;
                // search for the remaining content
                if (startLineNumber === searchRange.endLineNumber) {
                    const text = this.getLineContent(startLineNumber).substring(startColumn, searchRange.endColumn - 1);
                    resultLen = this._findMatchesInLine(searchData, searcher, text, searchRange.endLineNumber, startColumn, resultLen, result, captureMatches, limitResultCount);
                    return result;
                }
                resultLen = this._findMatchesInLine(searchData, searcher, this.getLineContent(startLineNumber).substr(startColumn), startLineNumber, startColumn, resultLen, result, captureMatches, limitResultCount);
                if (resultLen >= limitResultCount) {
                    return result;
                }
                startLineNumber++;
                startPosition = this.nodeAt2(startLineNumber, 1);
                currentNode = startPosition.node;
                start = this.positionInBuffer(startPosition.node, startPosition.remainder);
            }
            if (startLineNumber === searchRange.endLineNumber) {
                const startColumn = startLineNumber === searchRange.startLineNumber ? searchRange.startColumn - 1 : 0;
                const text = this.getLineContent(startLineNumber).substring(startColumn, searchRange.endColumn - 1);
                resultLen = this._findMatchesInLine(searchData, searcher, text, searchRange.endLineNumber, startColumn, resultLen, result, captureMatches, limitResultCount);
                return result;
            }
            const startColumn = startLineNumber === searchRange.startLineNumber ? searchRange.startColumn : 1;
            resultLen = this.findMatchesInNode(endPosition.node, searcher, startLineNumber, startColumn, start, end, searchData, captureMatches, limitResultCount, resultLen, result);
            return result;
        }
        _findMatchesInLine(searchData, searcher, text, lineNumber, deltaOffset, resultLen, result, captureMatches, limitResultCount) {
            const wordSeparators = searchData.wordSeparators;
            if (!captureMatches && searchData.simpleSearch) {
                const searchString = searchData.simpleSearch;
                const searchStringLen = searchString.length;
                const textLength = text.length;
                let lastMatchIndex = -searchStringLen;
                while ((lastMatchIndex = text.indexOf(searchString, lastMatchIndex + searchStringLen)) !== -1) {
                    if (!wordSeparators || (0, textModelSearch_1.isValidMatch)(wordSeparators, text, textLength, lastMatchIndex, searchStringLen)) {
                        result[resultLen++] = new model_1.FindMatch(new range_1.Range(lineNumber, lastMatchIndex + 1 + deltaOffset, lineNumber, lastMatchIndex + 1 + searchStringLen + deltaOffset), null);
                        if (resultLen >= limitResultCount) {
                            return resultLen;
                        }
                    }
                }
                return resultLen;
            }
            let m;
            // Reset regex to search from the beginning
            searcher.reset(0);
            do {
                m = searcher.next(text);
                if (m) {
                    result[resultLen++] = (0, textModelSearch_1.createFindMatch)(new range_1.Range(lineNumber, m.index + 1 + deltaOffset, lineNumber, m.index + 1 + m[0].length + deltaOffset), m, captureMatches);
                    if (resultLen >= limitResultCount) {
                        return resultLen;
                    }
                }
            } while (m);
            return resultLen;
        }
        // #endregion
        // #region Piece Table
        insert(offset, value, eolNormalized = false) {
            this._EOLNormalized = this._EOLNormalized && eolNormalized;
            this._lastVisitedLine.lineNumber = 0;
            this._lastVisitedLine.value = '';
            if (this.root !== rbTreeBase_1.SENTINEL) {
                const { node, remainder, nodeStartOffset } = this.nodeAt(offset);
                const piece = node.piece;
                const bufferIndex = piece.bufferIndex;
                const insertPosInBuffer = this.positionInBuffer(node, remainder);
                if (node.piece.bufferIndex === 0 &&
                    piece.end.line === this._lastChangeBufferPos.line &&
                    piece.end.column === this._lastChangeBufferPos.column &&
                    (nodeStartOffset + piece.length === offset) &&
                    value.length < AverageBufferSize) {
                    // changed buffer
                    this.appendToNode(node, value);
                    this.computeBufferMetadata();
                    return;
                }
                if (nodeStartOffset === offset) {
                    this.insertContentToNodeLeft(value, node);
                    this._searchCache.validate(offset);
                }
                else if (nodeStartOffset + node.piece.length > offset) {
                    // we are inserting into the middle of a node.
                    const nodesToDel = [];
                    let newRightPiece = new Piece(piece.bufferIndex, insertPosInBuffer, piece.end, this.getLineFeedCnt(piece.bufferIndex, insertPosInBuffer, piece.end), this.offsetInBuffer(bufferIndex, piece.end) - this.offsetInBuffer(bufferIndex, insertPosInBuffer));
                    if (this.shouldCheckCRLF() && this.endWithCR(value)) {
                        const headOfRight = this.nodeCharCodeAt(node, remainder);
                        if (headOfRight === 10 /** \n */) {
                            const newStart = { line: newRightPiece.start.line + 1, column: 0 };
                            newRightPiece = new Piece(newRightPiece.bufferIndex, newStart, newRightPiece.end, this.getLineFeedCnt(newRightPiece.bufferIndex, newStart, newRightPiece.end), newRightPiece.length - 1);
                            value += '\n';
                        }
                    }
                    // reuse node for content before insertion point.
                    if (this.shouldCheckCRLF() && this.startWithLF(value)) {
                        const tailOfLeft = this.nodeCharCodeAt(node, remainder - 1);
                        if (tailOfLeft === 13 /** \r */) {
                            const previousPos = this.positionInBuffer(node, remainder - 1);
                            this.deleteNodeTail(node, previousPos);
                            value = '\r' + value;
                            if (node.piece.length === 0) {
                                nodesToDel.push(node);
                            }
                        }
                        else {
                            this.deleteNodeTail(node, insertPosInBuffer);
                        }
                    }
                    else {
                        this.deleteNodeTail(node, insertPosInBuffer);
                    }
                    const newPieces = this.createNewPieces(value);
                    if (newRightPiece.length > 0) {
                        this.rbInsertRight(node, newRightPiece);
                    }
                    let tmpNode = node;
                    for (let k = 0; k < newPieces.length; k++) {
                        tmpNode = this.rbInsertRight(tmpNode, newPieces[k]);
                    }
                    this.deleteNodes(nodesToDel);
                }
                else {
                    this.insertContentToNodeRight(value, node);
                }
            }
            else {
                // insert new node
                const pieces = this.createNewPieces(value);
                let node = this.rbInsertLeft(null, pieces[0]);
                for (let k = 1; k < pieces.length; k++) {
                    node = this.rbInsertRight(node, pieces[k]);
                }
            }
            // todo, this is too brutal. Total line feed count should be updated the same way as lf_left.
            this.computeBufferMetadata();
        }
        delete(offset, cnt) {
            this._lastVisitedLine.lineNumber = 0;
            this._lastVisitedLine.value = '';
            if (cnt <= 0 || this.root === rbTreeBase_1.SENTINEL) {
                return;
            }
            const startPosition = this.nodeAt(offset);
            const endPosition = this.nodeAt(offset + cnt);
            const startNode = startPosition.node;
            const endNode = endPosition.node;
            if (startNode === endNode) {
                const startSplitPosInBuffer = this.positionInBuffer(startNode, startPosition.remainder);
                const endSplitPosInBuffer = this.positionInBuffer(startNode, endPosition.remainder);
                if (startPosition.nodeStartOffset === offset) {
                    if (cnt === startNode.piece.length) { // delete node
                        const next = startNode.next();
                        (0, rbTreeBase_1.rbDelete)(this, startNode);
                        this.validateCRLFWithPrevNode(next);
                        this.computeBufferMetadata();
                        return;
                    }
                    this.deleteNodeHead(startNode, endSplitPosInBuffer);
                    this._searchCache.validate(offset);
                    this.validateCRLFWithPrevNode(startNode);
                    this.computeBufferMetadata();
                    return;
                }
                if (startPosition.nodeStartOffset + startNode.piece.length === offset + cnt) {
                    this.deleteNodeTail(startNode, startSplitPosInBuffer);
                    this.validateCRLFWithNextNode(startNode);
                    this.computeBufferMetadata();
                    return;
                }
                // delete content in the middle, this node will be splitted to nodes
                this.shrinkNode(startNode, startSplitPosInBuffer, endSplitPosInBuffer);
                this.computeBufferMetadata();
                return;
            }
            const nodesToDel = [];
            const startSplitPosInBuffer = this.positionInBuffer(startNode, startPosition.remainder);
            this.deleteNodeTail(startNode, startSplitPosInBuffer);
            this._searchCache.validate(offset);
            if (startNode.piece.length === 0) {
                nodesToDel.push(startNode);
            }
            // update last touched node
            const endSplitPosInBuffer = this.positionInBuffer(endNode, endPosition.remainder);
            this.deleteNodeHead(endNode, endSplitPosInBuffer);
            if (endNode.piece.length === 0) {
                nodesToDel.push(endNode);
            }
            // delete nodes in between
            const secondNode = startNode.next();
            for (let node = secondNode; node !== rbTreeBase_1.SENTINEL && node !== endNode; node = node.next()) {
                nodesToDel.push(node);
            }
            const prev = startNode.piece.length === 0 ? startNode.prev() : startNode;
            this.deleteNodes(nodesToDel);
            this.validateCRLFWithNextNode(prev);
            this.computeBufferMetadata();
        }
        insertContentToNodeLeft(value, node) {
            // we are inserting content to the beginning of node
            const nodesToDel = [];
            if (this.shouldCheckCRLF() && this.endWithCR(value) && this.startWithLF(node)) {
                // move `\n` to new node.
                const piece = node.piece;
                const newStart = { line: piece.start.line + 1, column: 0 };
                const nPiece = new Piece(piece.bufferIndex, newStart, piece.end, this.getLineFeedCnt(piece.bufferIndex, newStart, piece.end), piece.length - 1);
                node.piece = nPiece;
                value += '\n';
                (0, rbTreeBase_1.updateTreeMetadata)(this, node, -1, -1);
                if (node.piece.length === 0) {
                    nodesToDel.push(node);
                }
            }
            const newPieces = this.createNewPieces(value);
            let newNode = this.rbInsertLeft(node, newPieces[newPieces.length - 1]);
            for (let k = newPieces.length - 2; k >= 0; k--) {
                newNode = this.rbInsertLeft(newNode, newPieces[k]);
            }
            this.validateCRLFWithPrevNode(newNode);
            this.deleteNodes(nodesToDel);
        }
        insertContentToNodeRight(value, node) {
            // we are inserting to the right of this node.
            if (this.adjustCarriageReturnFromNext(value, node)) {
                // move \n to the new node.
                value += '\n';
            }
            const newPieces = this.createNewPieces(value);
            const newNode = this.rbInsertRight(node, newPieces[0]);
            let tmpNode = newNode;
            for (let k = 1; k < newPieces.length; k++) {
                tmpNode = this.rbInsertRight(tmpNode, newPieces[k]);
            }
            this.validateCRLFWithPrevNode(newNode);
        }
        positionInBuffer(node, remainder, ret) {
            const piece = node.piece;
            const bufferIndex = node.piece.bufferIndex;
            const lineStarts = this._buffers[bufferIndex].lineStarts;
            const startOffset = lineStarts[piece.start.line] + piece.start.column;
            const offset = startOffset + remainder;
            // binary search offset between startOffset and endOffset
            let low = piece.start.line;
            let high = piece.end.line;
            let mid = 0;
            let midStop = 0;
            let midStart = 0;
            while (low <= high) {
                mid = low + ((high - low) / 2) | 0;
                midStart = lineStarts[mid];
                if (mid === high) {
                    break;
                }
                midStop = lineStarts[mid + 1];
                if (offset < midStart) {
                    high = mid - 1;
                }
                else if (offset >= midStop) {
                    low = mid + 1;
                }
                else {
                    break;
                }
            }
            if (ret) {
                ret.line = mid;
                ret.column = offset - midStart;
                return null;
            }
            return {
                line: mid,
                column: offset - midStart
            };
        }
        getLineFeedCnt(bufferIndex, start, end) {
            // 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.
            // 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
            if (end.column === 0) {
                return end.line - start.line;
            }
            const lineStarts = this._buffers[bufferIndex].lineStarts;
            if (end.line === lineStarts.length - 1) { // it means, there is no \n after end, otherwise, there will be one more lineStart.
                return end.line - start.line;
            }
            const nextLineStartOffset = lineStarts[end.line + 1];
            const endOffset = lineStarts[end.line] + end.column;
            if (nextLineStartOffset > endOffset + 1) { // there are more than 1 character after end, which means it can't be \n
                return end.line - start.line;
            }
            // endOffset + 1 === nextLineStartOffset
            // character at endOffset is \n, so we check the character before first
            // if character at endOffset is \r, end.column is 0 and we can't get here.
            const previousCharOffset = endOffset - 1; // end.column > 0 so it's okay.
            const buffer = this._buffers[bufferIndex].buffer;
            if (buffer.charCodeAt(previousCharOffset) === 13) {
                return end.line - start.line + 1;
            }
            else {
                return end.line - start.line;
            }
        }
        offsetInBuffer(bufferIndex, cursor) {
            const lineStarts = this._buffers[bufferIndex].lineStarts;
            return lineStarts[cursor.line] + cursor.column;
        }
        deleteNodes(nodes) {
            for (let i = 0; i < nodes.length; i++) {
                (0, rbTreeBase_1.rbDelete)(this, nodes[i]);
            }
        }
        createNewPieces(text) {
            if (text.length > AverageBufferSize) {
                // the content is large, operations like substring, charCode becomes slow
                // so here we split it into smaller chunks, just like what we did for CR/LF normalization
                const newPieces = [];
                while (text.length > AverageBufferSize) {
                    const lastChar = text.charCodeAt(AverageBufferSize - 1);
                    let splitText;
                    if (lastChar === 13 /* CharCode.CarriageReturn */ || (lastChar >= 0xD800 && lastChar <= 0xDBFF)) {
                        // last character is \r or a high surrogate => keep it back
                        splitText = text.substring(0, AverageBufferSize - 1);
                        text = text.substring(AverageBufferSize - 1);
                    }
                    else {
                        splitText = text.substring(0, AverageBufferSize);
                        text = text.substring(AverageBufferSize);
                    }
                    const lineStarts = createLineStartsFast(splitText);
                    newPieces.push(new Piece(this._buffers.length, /* buffer index */ { line: 0, column: 0 }, { line: lineStarts.length - 1, column: splitText.length - lineStarts[lineStarts.length - 1] }, lineStarts.length - 1, splitText.length));
                    this._buffers.push(new StringBuffer(splitText, lineStarts));
                }
                const lineStarts = createLineStartsFast(text);
                newPieces.push(new Piece(this._buffers.length, /* buffer index */ { line: 0, column: 0 }, { line: lineStarts.length - 1, column: text.length - lineStarts[lineStarts.length - 1] }, lineStarts.length - 1, text.length));
                this._buffers.push(new StringBuffer(text, lineStarts));
                return newPieces;
            }
            let startOffset = this._buffers[0].buffer.length;
            const lineStarts = createLineStartsFast(text, false);
            let start = this._lastChangeBufferPos;
            if (this._buffers[0].lineStarts[this._buffers[0].lineStarts.length - 1] === startOffset
                && startOffset !== 0
                && this.startWithLF(text)
                && this.endWithCR(this._buffers[0].buffer) // todo, we can check this._lastChangeBufferPos's column as it's the last one
            ) {
                this._lastChangeBufferPos = { line: this._lastChangeBufferPos.line, column: this._lastChangeBufferPos.column + 1 };
                start = this._lastChangeBufferPos;
                for (let i = 0; i < lineStarts.length; i++) {
                    lineStarts[i] += startOffset + 1;
                }
                this._buffers[0].lineStarts = this._buffers[0].lineStarts.concat(lineStarts.slice(1));
                this._buffers[0].buffer += '_' + text;
                startOffset += 1;
            }
            else {
                if (startOffset !== 0) {
                    for (let i = 0; i < lineStarts.length; i++) {
                        lineStarts[i] += startOffset;
                    }
                }
                this._buffers[0].lineStarts = this._buffers[0].lineStarts.concat(lineStarts.slice(1));
                this._buffers[0].buffer += text;
            }
            const endOffset = this._buffers[0].buffer.length;
            const endIndex = this._buffers[0].lineStarts.length - 1;
            const endColumn = endOffset - this._buffers[0].lineStarts[endIndex];
            const endPos = { line: endIndex, column: endColumn };
            const newPiece = new Piece(0, /** todo@peng */ start, endPos, this.getLineFeedCnt(0, start, endPos), endOffset - startOffset);
            this._lastChangeBufferPos = endPos;
            return [newPiece];
        }
        getLineRawContent(lineNumber, endOffset = 0) {
            let x = this.root;
            let ret = '';
            const cache = this._searchCache.get2(lineNumber);
            if (cache) {
                x = cache.node;
                const prevAccumulatedValue = this.getAccumulatedValue(x, lineNumber - cache.nodeStartLineNumber - 1);
                const buffer = this._buffers[x.piece.bufferIndex].buffer;
                const startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);
                if (cache.nodeStartLineNumber + x.piece.lineFeedCnt === lineNumber) {
                    ret = buffer.substring(startOffset + prevAccumulatedValue, startOffset + x.piece.length);
                }
                else {
                    const accumulatedValue = this.getAccumulatedValue(x, lineNumber - cache.nodeStartLineNumber);
                    return buffer.substring(startOffset + prevAccumulatedValue, startOffset + accumulatedValue - endOffset);
                }
            }
            else {
                let nodeStartOffset = 0;
                const originalLineNumber = lineNumber;
                while (x !== rbTreeBase_1.SENTINEL) {
                    if (x.left !== rbTreeBase_1.SENTINEL && x.lf_left >= lineNumber - 1) {
                        x = x.left;
                    }
                    else if (x.lf_left + x.piece.lineFeedCnt > lineNumber - 1) {
                        const prevAccumulatedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2);
                        const accumulatedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 1);
                        const buffer = this._buffers[x.piece.bufferIndex].buffer;
                        const startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);
                        nodeStartOffset += x.size_left;
                        this._searchCache.set({
                            node: x,
                            nodeStartOffset,
                            nodeStartLineNumber: originalLineNumber - (lineNumber - 1 - x.lf_left)
                        });
                        return buffer.substring(startOffset + prevAccumulatedValue, startOffset + accumulatedValue - endOffset);
                    }
                    else if (x.lf_left + x.piece.lineFeedCnt === lineNumber - 1) {
                        const prevAccumulatedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2);
                        const buffer = this._buffers[x.piece.bufferIndex].buffer;
                        const startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);
                        ret = buffer.substring(startOffset + prevAccumulatedValue, startOffset + x.piece.length);
                        break;
                    }
                    else {
                        lineNumber -= x.lf_left + x.piece.lineFeedCnt;
                        nodeStartOffset += x.size_left + x.piece.length;
                        x = x.right;
                    }
                }
            }
            // search in order, to find the node contains end column
            x = x.next();
            while (x !== rbTreeBase_1.SENTINEL) {
                const buffer = this._buffers[x.piece.bufferIndex].buffer;
                if (x.piece.lineFeedCnt > 0) {
                    const accumulatedValue = this.getAccumulatedValue(x, 0);
                    const startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);
                    ret += buffer.substring(startOffset, startOffset + accumulatedValue - endOffset);
                    return ret;
                }
                else {
                    const startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);
                    ret += buffer.substr(startOffset, x.piece.length);
                }
                x = x.next();
            }
            return ret;
        }
        computeBufferMetadata() {
            let x = this.root;
            let lfCnt = 1;
            let len = 0;
            while (x !== rbTreeBase_1.SENTINEL) {
                lfCnt += x.lf_left + x.piece.lineFeedCnt;
                len += x.size_left + x.piece.length;
                x = x.right;
            }
            this._lineCnt = lfCnt;
            this._length = len;
            this._searchCache.validate(this._length);
        }
        // #region node operations
        getIndexOf(node, accumulatedValue) {
            const piece = node.piece;
            const pos = this.positionInBuffer(node, accumulatedValue);
            const lineCnt = pos.line - piece.start.line;
            if (this.offsetInBuffer(piece.bufferIndex, piece.end) - this.offsetInBuffer(piece.bufferIndex, piece.start) === accumulatedValue) {
                // we are checking the end of this node, so a CRLF check is necessary.
                const realLineCnt = this.getLineFeedCnt(node.piece.bufferIndex, piece.start, pos);
                if (realLineCnt !== lineCnt) {
                    // aha yes, CRLF
                    return { index: realLineCnt, remainder: 0 };
                }
            }
            return { index: lineCnt, remainder: pos.column };
        }
        getAccumulatedValue(node, index) {
            if (index < 0) {
                return 0;
            }
            const piece = node.piece;
            const lineStarts = this._buffers[piece.bufferIndex].lineStarts;
            const expectedLineStartIndex = piece.start.line + index + 1;
            if (expectedLineStartIndex > piece.end.line) {
                return lineStarts[piece.end.line] + piece.end.column - lineStarts[piece.start.line] - piece.start.column;
            }
            else {
                return lineStarts[expectedLineStartIndex] - lineStarts[piece.start.line] - piece.start.column;
            }
        }
        deleteNodeTail(node, pos) {
            const piece = node.piece;
            const originalLFCnt = piece.lineFeedCnt;
            const originalEndOffset = this.offsetInBuffer(piece.bufferIndex, piece.end);
            const newEnd = pos;
            const newEndOffset = this.offsetInBuffer(piece.bufferIndex, newEnd);
            const newLineFeedCnt = this.getLineFeedCnt(piece.bufferIndex, piece.start, newEnd);
            const lf_delta = newLineFeedCnt - originalLFCnt;
            const size_delta = newEndOffset - originalEndOffset;
            const newLength = piece.length + size_delta;
            node.piece = new Piece(piece.bufferIndex, piece.start, newEnd, newLineFeedCnt, newLength);
            (0, rbTreeBase_1.updateTreeMetadata)(this, node, size_delta, lf_delta);
        }
        deleteNodeHead(node, pos) {
            const piece = node.piece;
            const originalLFCnt = piece.lineFeedCnt;
            const originalStartOffset = this.offsetInBuffer(piece.bufferIndex, piece.start);
            const newStart = pos;
            const newLineFeedCnt = this.getLineFeedCnt(piece.bufferIndex, newStart, piece.end);
            const newStartOffset = this.offsetInBuffer(piece.bufferIndex, newStart);
            const lf_delta = newLineFeedCnt - originalLFCnt;
            const size_delta = originalStartOffset - newStartOffset;
            const newLength = piece.length + size_delta;
            node.piece = new Piece(piece.bufferIndex, newStart, piece.end, newLineFeedCnt, newLength);
            (0, rbTreeBase_1.updateTreeMetadata)(this, node, size_delta, lf_delta);
        }
        shrinkNode(node, start, end) {
            const piece = node.piece;
            const originalStartPos = piece.start;
            const originalEndPos = piece.end;
            // old piece, originalStartPos, start
            const oldLength = piece.length;
            const oldLFCnt = piece.lineFeedCnt;
            const newEnd = start;
            const newLineFeedCnt = this.getLineFeedCnt(piece.bufferIndex, piece.start, newEnd);
            const newLength = this.offsetInBuffer(piece.bufferIndex, start) - this.offsetInBuffer(piece.bufferIndex, originalStartPos);
            node.piece = new Piece(piece.bufferIndex, piece.start, newEnd, newLineFeedCnt, newLength);
            (0, rbTreeBase_1.updateTreeMetadata)(this, node, newLength - oldLength, newLineFeedCnt - oldLFCnt);
            // new right piece, end, originalEndPos
            const newPiece = new Piece(piece.bufferIndex, end, originalEndPos, this.getLineFeedCnt(piece.bufferIndex, end, originalEndPos), this.offsetInBuffer(piece.bufferIndex, originalEndPos) - this.offsetInBuffer(piece.bufferIndex, end));
            const newNode = this.rbInsertRight(node, newPiece);
            this.validateCRLFWithPrevNode(newNode);
        }
        appendToNode(node, value) {
            if (this.adjustCarriageReturnFromNext(value, node)) {
                value += '\n';
            }
            const hitCRLF = this.shouldCheckCRLF() && this.startWithLF(value) && this.endWithCR(node);
            const startOffset = this._buffers[0].buffer.length;
            this._buffers[0].buffer += value;
            const lineStarts = createLineStartsFast(value, false);
            for (let i = 0; i < lineStarts.length; i++) {
                lineStarts[i] += startOffset;
            }
            if (hitCRLF) {
                const prevStartOffset = this._buffers[0].lineStarts[this._buffers[0].lineStarts.length - 2];
                this._buffers[0].lineStarts.pop();
                // _lastChangeBufferPos is already wrong
                this._lastChangeBufferPos = { line: this._lastChangeBufferPos.line - 1, column: startOffset - prevStartOffset };
            }
            this._buffers[0].lineStarts = this._buffers[0].lineStarts.concat(lineStarts.slice(1));
            const endIndex = this._buffers[0].lineStarts.length - 1;
            const endColumn = this._buffers[0].buffer.length - this._buffers[0].lineStarts[endIndex];
            const newEnd = { line: endIndex, column: endColumn };
            const newLength = node.piece.length + value.length;
            const oldLineFeedCnt = node.piece.lineFeedCnt;
            const newLineFeedCnt = this.getLineFeedCnt(0, node.piece.start, newEnd);
            const lf_delta = newLineFeedCnt - oldLineFeedCnt;
            node.piece = new Piece(node.piece.bufferIndex, node.piece.start, newEnd, newLineFeedCnt, newLength);
            this._lastChangeBufferPos = newEnd;
            (0, rbTreeBase_1.updateTreeMetadata)(this, node, value.length, lf_delta);
        }
        nodeAt(offset) {
            let x = this.root;
            const cache = this._searchCache.get(offset);
            if (cache) {
                return {
                    node: cache.node,
                    nodeStartOffset: cache.nodeStartOffset,
                    remainder: offset - cache.nodeStartOffset
                };
            }
            let nodeStartOffset = 0;
            while (x !== rbTreeBase_1.SENTINEL) {
                if (x.size_left > offset) {
                    x = x.left;
                }
                else if (x.size_left + x.piece.length >= offset) {
                    nodeStartOffset += x.size_left;
                    const ret = {
                        node: x,
                        remainder: offset - x.size_left,
                        nodeStartOffset
                    };
                    this._searchCache.set(ret);
                    return ret;
                }
                else {
                    offset -= x.size_left + x.piece.length;
                    nodeStartOffset += x.size_left + x.piece.length;
                    x = x.right;
                }
            }
            return null;
        }
        nodeAt2(lineNumber, column) {
            let x = this.root;
            let nodeStartOffset = 0;
            while (x !== rbTreeBase_1.SENTINEL) {
                if (x.left !== rbTreeBase_1.SENTINEL && x.lf_left >= lineNumber - 1) {
                    x = x.left;
                }
                else if (x.lf_left + x.piece.lineFeedCnt > lineNumber - 1) {
                    const prevAccumualtedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2);
                    const accumulatedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 1);
                    nodeStartOffset += x.size_left;
                    return {
                        node: x,
                        remainder: Math.min(prevAccumualtedValue + column - 1, accumulatedValue),
                        nodeStartOffset
                    };
                }
                else if (x.lf_left + x.piece.lineFeedCnt === lineNumber - 1) {
                    const prevAccumualtedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2);
                    if (prevAccumualtedValue + column - 1 <= x.piece.length) {
                        return {
                            node: x,
                            remainder: prevAccumualtedValue + column - 1,
                            nodeStartOffset
                        };
                    }
                    else {
                        column -= x.piece.length - prevAccumualtedValue;
                        break;
                    }
                }
                else {
                    lineNumber -= x.lf_left + x.piece.lineFeedCnt;
                    nodeStartOffset += x.size_left + x.piece.length;
                    x = x.right;
                }
            }
            // search in order, to find the node contains position.column
            x = x.next();
            while (x !== rbTreeBase_1.SENTINEL) {
                if (x.piece.lineFeedCnt > 0) {
                    const accumulatedValue = this.getAccumulatedValue(x, 0);
                    const nodeStartOffset = this.offsetOfNode(x);
                    return {
                        node: x,
                        remainder: Math.min(column - 1, accumulatedValue),
                        nodeStartOffset
                    };
                }
                else {
                    if (x.piece.length >= column - 1) {
                        const nodeStartOffset = this.offsetOfNode(x);
                        return {
                            node: x,
                            remainder: column - 1,
                            nodeStartOffset
                        };
                    }
                    else {
                        column -= x.piece.length;
                    }
                }
                x = x.next();
            }
            return null;
        }
        nodeCharCodeAt(node, offset) {
            if (node.piece.lineFeedCnt < 1) {
                return -1;
            }
            const buffer = this._buffers[node.piece.bufferIndex];
            const newOffset = this.offsetInBuffer(node.piece.bufferIndex, node.piece.start) + offset;
            return buffer.buffer.charCodeAt(newOffset);
        }
        offsetOfNode(node) {
            if (!node) {
                return 0;
            }
            let pos = node.size_left;
            while (node !== this.root) {
                if (node.parent.right === node) {
                    pos += node.parent.size_left + node.parent.piece.length;
                }
                node = node.parent;
            }
            return pos;
        }
        // #endregion
        // #region CRLF
        shouldCheckCRLF() {
            return !(this._EOLNormalized && this._EOL === '\n');
        }
        startWithLF(val) {
            if (typeof val === 'string') {
                return val.charCodeAt(0) === 10;
            }
            if (val === rbTreeBase_1.SENTINEL || val.piece.lineFeedCnt === 0) {
                return false;
            }
            const piece = val.piece;
            const lineStarts = this._buffers[piece.bufferIndex].lineStarts;
            const line = piece.start.line;
            const startOffset = lineStarts[line] + piece.start.column;
            if (line === lineStarts.length - 1) {
                // last line, so there is no line feed at the end of this line
                return false;
            }
            const nextLineOffset = lineStarts[line + 1];
            if (nextLineOffset > startOffset + 1) {
                return false;
            }
            return this._buffers[piece.bufferIndex].buffer.charCodeAt(startOffset) === 10;
        }
        endWithCR(val) {
            if (typeof val === 'string') {
                return val.charCodeAt(val.length - 1) === 13;
            }
            if (val === rbTreeBase_1.SENTINEL || val.piece.lineFeedCnt === 0) {
                return false;
            }
            return this.nodeCharCodeAt(val, val.piece.length - 1) === 13;
        }
        validateCRLFWithPrevNode(nextNode) {
            if (this.shouldCheckCRLF() && this.startWithLF(nextNode)) {
                const node = nextNode.prev();
                if (this.endWithCR(node)) {
                    this.fixCRLF(node, nextNode);
                }
            }
        }
        validateCRLFWithNextNode(node) {
            if (this.shouldCheckCRLF() && this.endWithCR(node)) {
                const nextNode = node.next();
                if (this.startWithLF(nextNode)) {
                    this.fixCRLF(node, nextNode);
                }
            }
        }
        fixCRLF(prev, next) {
            const nodesToDel = [];
            // update node
            const lineStarts = this._buffers[prev.piece.bufferIndex].lineStarts;
            let newEnd;
            if (prev.piece.end.column === 0) {
                // it means, last line ends with \r, not \r\n
                newEnd = { line: prev.piece.end.line - 1, column: lineStarts[prev.piece.end.line] - lineStarts[prev.piece.end.line - 1] - 1 };
            }
            else {
                // \r\n
                newEnd = { line: prev.piece.end.line, column: prev.piece.end.column - 1 };
            }
            const prevNewLength = prev.piece.length - 1;
            const prevNewLFCnt = prev.piece.lineFeedCnt - 1;
            prev.piece = new Piece(prev.piece.bufferIndex, prev.piece.start, newEnd, prevNewLFCnt, prevNewLength);
            (0, rbTreeBase_1.updateTreeMetadata)(this, prev, -1, -1);
            if (prev.piece.length === 0) {
                nodesToDel.push(prev);
            }
            // update nextNode
            const newStart = { line: next.piece.start.line + 1, column: 0 };
            const newLength = next.piece.length - 1;
            const newLineFeedCnt = this.getLineFeedCnt(next.piece.bufferIndex, newStart, next.piece.end);
            next.piece = new Piece(next.piece.bufferIndex, newStart, next.piece.end, newLineFeedCnt, newLength);
            (0, rbTreeBase_1.updateTreeMetadata)(this, next, -1, -1);
            if (next.piece.length === 0) {
                nodesToDel.push(next);
            }
            // create new piece which contains \r\n
            const pieces = this.createNewPieces('\r\n');
            this.rbInsertRight(prev, pieces[0]);
            // delete empty nodes
            for (let i = 0; i < nodesToDel.length; i++) {
                (0, rbTreeBase_1.rbDelete)(this, nodesToDel[i]);
            }
        }
        adjustCarriageReturnFromNext(value, node) {
            if (this.shouldCheckCRLF() && this.endWithCR(value)) {
                const nextNode = node.next();
                if (this.startWithLF(nextNode)) {
                    // move `\n` forward
                    value += '\n';
                    if (nextNode.piece.length === 1) {
                        (0, rbTreeBase_1.rbDelete)(this, nextNode);
                    }
                    else {
                        const piece = nextNode.piece;
                        const newStart = { line: piece.start.line + 1, column: 0 };
                        const newLength = piece.length - 1;
                        const newLineFeedCnt = this.getLineFeedCnt(piece.bufferIndex, newStart, piece.end);
                        nextNode.piece = new Piece(piece.bufferIndex, newStart, piece.end, newLineFeedCnt, newLength);
                        (0, rbTreeBase_1.updateTreeMetadata)(this, nextNode, -1, -1);
                    }
                    return true;
                }
            }
            return false;
        }
        // #endregion
        // #endregion
        // #region Tree operations
        iterate(node, callback) {
            if (node === rbTreeBase_1.SENTINEL) {
                return callback(rbTreeBase_1.SENTINEL);
            }
            const leftRet = this.iterate(node.left, callback);
            if (!leftRet) {
                return leftRet;
            }
            return callback(node) && this.iterate(node.right, callback);
        }
        getNodeContent(node) {
            if (node === rbTreeBase_1.SENTINEL) {
                return '';
            }
            const buffer = this._buffers[node.piece.bufferIndex];
            const piece = node.piece;
            const startOffset = this.offsetInBuffer(piece.bufferIndex, piece.start);
            const endOffset = this.offsetInBuffer(piece.bufferIndex, piece.end);
            const currentContent = buffer.buffer.substring(startOffset, endOffset);
            return currentContent;
        }
        getPieceContent(piece) {
            const buffer = this._buffers[piece.bufferIndex];
            const startOffset = this.offsetInBuffer(piece.bufferIndex, piece.start);
            const endOffset = this.offsetInBuffer(piece.bufferIndex, piece.end);
            const currentContent = buffer.buffer.substring(startOffset, endOffset);
            return currentContent;
        }
        /**
         *      node              node
         *     /  \              /  \
         *    a   b    <----   a    b
         *                         /
         *                        z
         */
        rbInsertRight(node, p) {
            const z = new rbTreeBase_1.TreeNode(p, 1 /* NodeColor.Red */);
            z.left = rbTreeBase_1.SENTINEL;
            z.right = rbTreeBase_1.SENTINEL;
            z.parent = rbTreeBase_1.SENTINEL;
            z.size_left = 0;
            z.lf_left = 0;
            const x = this.root;
            if (x === rbTreeBase_1.SENTINEL) {
                this.root = z;
                z.color = 0 /* NodeColor.Black */;
            }
            else if (node.right === rbTreeBase_1.SENTINEL) {
                node.right = z;
                z.parent = node;
            }
            else {
                const nextNode = (0, rbTreeBase_1.leftest)(node.right);
                nextNode.left = z;
                z.parent = nextNode;
            }
            (0, rbTreeBase_1.fixInsert)(this, z);
            return z;
        }
        /**
         *      node              node
         *     /  \              /  \
         *    a   b     ---->   a    b
         *                       \
         *                        z
         */
        rbInsertLeft(node, p) {
            const z = new rbTreeBase_1.TreeNode(p, 1 /* NodeColor.Red */);
            z.left = rbTreeBase_1.SENTINEL;
            z.right = rbTreeBase_1.SENTINEL;
            z.parent = rbTreeBase_1.SENTINEL;
            z.size_left = 0;
            z.lf_left = 0;
            if (this.root === rbTreeBase_1.SENTINEL) {
                this.root = z;
                z.color = 0 /* NodeColor.Black */;
            }
            else if (node.left === rbTreeBase_1.SENTINEL) {
                node.left = z;
                z.parent = node;
            }
            else {
                const prevNode = (0, rbTreeBase_1.righttest)(node.left); // a
                prevNode.right = z;
                z.parent = prevNode;
            }
            (0, rbTreeBase_1.fixInsert)(this, z);
            return z;
        }
    }
    exports.PieceTreeBase = PieceTreeBase;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[581/*vs/editor/common/model/textModelText*/], __M([1/*require*/,0/*exports*/,104/*vs/editor/common/core/textEdit*/,113/*vs/editor/common/core/textLength*/]), function (require, exports, textEdit_1, textLength_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.TextModelText = void 0;
    class TextModelText extends textEdit_1.AbstractText {
        constructor(_textModel) {
            super();
            this._textModel = _textModel;
        }
        getValueOfRange(range) {
            return this._textModel.getValueInRange(range);
        }
        get length() {
            const lastLineNumber = this._textModel.getLineCount();
            const lastLineLen = this._textModel.getLineLength(lastLineNumber);
            return new textLength_1.TextLength(lastLineNumber - 1, lastLineLen);
        }
    }
    exports.TextModelText = TextModelText;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[237/*vs/editor/common/model/utils*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.computeIndentLevel = computeIndentLevel;
    /**
     * Returns:
     *  - -1 => the line consists of whitespace
     *  - otherwise => the indent level is returned value
     */
    function computeIndentLevel(line, tabSize) {
        let indent = 0;
        let i = 0;
        const len = line.length;
        while (i < len) {
            const chCode = line.charCodeAt(i);
            if (chCode === 32 /* CharCode.Space */) {
                indent++;
            }
            else if (chCode === 9 /* CharCode.Tab */) {
                indent = indent - indent % tabSize + tabSize;
            }
            else {
                break;
            }
            i++;
        }
        if (i === len) {
            return -1; // line only consists of whitespace
        }
        return indent;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[325/*vs/editor/common/modelLineProjectionData*/], __M([1/*require*/,0/*exports*/,90/*vs/base/common/assert*/,9/*vs/editor/common/core/position*/,40/*vs/editor/common/model*/]), function (require, exports, assert_1, position_1, model_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.OutputPosition = exports.InjectedText = exports.ModelLineProjectionData = void 0;
    /**
     * *input*:
     * ```
     * xxxxxxxxxxxxxxxxxxxxxxxxxxx
     * ```
     *
     * -> Applying injections `[i...i]`, *inputWithInjections*:
     * ```
     * xxxxxx[iiiiiiiiii]xxxxxxxxxxxxxxxxx[ii]xxxx
     * ```
     *
     * -> breaking at offsets `|` in `xxxxxx[iiiiiii|iii]xxxxxxxxxxx|xxxxxx[ii]xxxx|`:
     * ```
     * xxxxxx[iiiiiii
     * iii]xxxxxxxxxxx
     * xxxxxx[ii]xxxx
     * ```
     *
     * -> applying wrappedTextIndentLength, *output*:
     * ```
     * xxxxxx[iiiiiii
     *    iii]xxxxxxxxxxx
     *    xxxxxx[ii]xxxx
     * ```
     */
    class ModelLineProjectionData {
        constructor(injectionOffsets, 
        /**
         * `injectionOptions.length` must equal `injectionOffsets.length`
         */
        injectionOptions, 
        /**
         * Refers to offsets after applying injections to the source.
         * The last break offset indicates the length of the source after applying injections.
         */
        breakOffsets, 
        /**
         * Refers to offsets after applying injections
         */
        breakOffsetsVisibleColumn, wrappedTextIndentLength) {
            this.injectionOffsets = injectionOffsets;
            this.injectionOptions = injectionOptions;
            this.breakOffsets = breakOffsets;
            this.breakOffsetsVisibleColumn = breakOffsetsVisibleColumn;
            this.wrappedTextIndentLength = wrappedTextIndentLength;
        }
        getOutputLineCount() {
            return this.breakOffsets.length;
        }
        getMinOutputOffset(outputLineIndex) {
            if (outputLineIndex > 0) {
                return this.wrappedTextIndentLength;
            }
            return 0;
        }
        getLineLength(outputLineIndex) {
            // These offsets refer to model text with injected text.
            const startOffset = outputLineIndex > 0 ? this.breakOffsets[outputLineIndex - 1] : 0;
            const endOffset = this.breakOffsets[outputLineIndex];
            let lineLength = endOffset - startOffset;
            if (outputLineIndex > 0) {
                lineLength += this.wrappedTextIndentLength;
            }
            return lineLength;
        }
        getMaxOutputOffset(outputLineIndex) {
            return this.getLineLength(outputLineIndex);
        }
        translateToInputOffset(outputLineIndex, outputOffset) {
            if (outputLineIndex > 0) {
                outputOffset = Math.max(0, outputOffset - this.wrappedTextIndentLength);
            }
            const offsetInInputWithInjection = outputLineIndex === 0 ? outputOffset : this.breakOffsets[outputLineIndex - 1] + outputOffset;
            let offsetInInput = offsetInInputWithInjection;
            if (this.injectionOffsets !== null) {
                for (let i = 0; i < this.injectionOffsets.length; i++) {
                    if (offsetInInput > this.injectionOffsets[i]) {
                        if (offsetInInput < this.injectionOffsets[i] + this.injectionOptions[i].content.length) {
                            // `inputOffset` is within injected text
                            offsetInInput = this.injectionOffsets[i];
                        }
                        else {
                            offsetInInput -= this.injectionOptions[i].content.length;
                        }
                    }
                    else {
                        break;
                    }
                }
            }
            return offsetInInput;
        }
        translateToOutputPosition(inputOffset, affinity = 2 /* PositionAffinity.None */) {
            let inputOffsetInInputWithInjection = inputOffset;
            if (this.injectionOffsets !== null) {
                for (let i = 0; i < this.injectionOffsets.length; i++) {
                    if (inputOffset < this.injectionOffsets[i]) {
                        break;
                    }
                    if (affinity !== 1 /* PositionAffinity.Right */ && inputOffset === this.injectionOffsets[i]) {
                        break;
                    }
                    inputOffsetInInputWithInjection += this.injectionOptions[i].content.length;
                }
            }
            return this.offsetInInputWithInjectionsToOutputPosition(inputOffsetInInputWithInjection, affinity);
        }
        offsetInInputWithInjectionsToOutputPosition(offsetInInputWithInjections, affinity = 2 /* PositionAffinity.None */) {
            let low = 0;
            let high = this.breakOffsets.length - 1;
            let mid = 0;
            let midStart = 0;
            while (low <= high) {
                mid = low + ((high - low) / 2) | 0;
                const midStop = this.breakOffsets[mid];
                midStart = mid > 0 ? this.breakOffsets[mid - 1] : 0;
                if (affinity === 0 /* PositionAffinity.Left */) {
                    if (offsetInInputWithInjections <= midStart) {
                        high = mid - 1;
                    }
                    else if (offsetInInputWithInjections > midStop) {
                        low = mid + 1;
                    }
                    else {
                        break;
                    }
                }
                else {
                    if (offsetInInputWithInjections < midStart) {
                        high = mid - 1;
                    }
                    else if (offsetInInputWithInjections >= midStop) {
                        low = mid + 1;
                    }
                    else {
                        break;
                    }
                }
            }
            let outputOffset = offsetInInputWithInjections - midStart;
            if (mid > 0) {
                outputOffset += this.wrappedTextIndentLength;
            }
            return new OutputPosition(mid, outputOffset);
        }
        normalizeOutputPosition(outputLineIndex, outputOffset, affinity) {
            if (this.injectionOffsets !== null) {
                const offsetInInputWithInjections = this.outputPositionToOffsetInInputWithInjections(outputLineIndex, outputOffset);
                const normalizedOffsetInUnwrappedLine = this.normalizeOffsetInInputWithInjectionsAroundInjections(offsetInInputWithInjections, affinity);
                if (normalizedOffsetInUnwrappedLine !== offsetInInputWithInjections) {
                    // injected text caused a change
                    return this.offsetInInputWithInjectionsToOutputPosition(normalizedOffsetInUnwrappedLine, affinity);
                }
            }
            if (affinity === 0 /* PositionAffinity.Left */) {
                if (outputLineIndex > 0 && outputOffset === this.getMinOutputOffset(outputLineIndex)) {
                    return new OutputPosition(outputLineIndex - 1, this.getMaxOutputOffset(outputLineIndex - 1));
                }
            }
            else if (affinity === 1 /* PositionAffinity.Right */) {
                const maxOutputLineIndex = this.getOutputLineCount() - 1;
                if (outputLineIndex < maxOutputLineIndex && outputOffset === this.getMaxOutputOffset(outputLineIndex)) {
                    return new OutputPosition(outputLineIndex + 1, this.getMinOutputOffset(outputLineIndex + 1));
                }
            }
            return new OutputPosition(outputLineIndex, outputOffset);
        }
        outputPositionToOffsetInInputWithInjections(outputLineIndex, outputOffset) {
            if (outputLineIndex > 0) {
                outputOffset = Math.max(0, outputOffset - this.wrappedTextIndentLength);
            }
            const result = (outputLineIndex > 0 ? this.breakOffsets[outputLineIndex - 1] : 0) + outputOffset;
            return result;
        }
        normalizeOffsetInInputWithInjectionsAroundInjections(offsetInInputWithInjections, affinity) {
            const injectedText = this.getInjectedTextAtOffset(offsetInInputWithInjections);
            if (!injectedText) {
                return offsetInInputWithInjections;
            }
            if (affinity === 2 /* PositionAffinity.None */) {
                if (offsetInInputWithInjections === injectedText.offsetInInputWithInjections + injectedText.length
                    && hasRightCursorStop(this.injectionOptions[injectedText.injectedTextIndex].cursorStops)) {
                    return injectedText.offsetInInputWithInjections + injectedText.length;
                }
                else {
                    let result = injectedText.offsetInInputWithInjections;
                    if (hasLeftCursorStop(this.injectionOptions[injectedText.injectedTextIndex].cursorStops)) {
                        return result;
                    }
                    let index = injectedText.injectedTextIndex - 1;
                    while (index >= 0 && this.injectionOffsets[index] === this.injectionOffsets[injectedText.injectedTextIndex]) {
                        if (hasRightCursorStop(this.injectionOptions[index].cursorStops)) {
                            break;
                        }
                        result -= this.injectionOptions[index].content.length;
                        if (hasLeftCursorStop(this.injectionOptions[index].cursorStops)) {
                            break;
                        }
                        index--;
                    }
                    return result;
                }
            }
            else if (affinity === 1 /* PositionAffinity.Right */ || affinity === 4 /* PositionAffinity.RightOfInjectedText */) {
                let result = injectedText.offsetInInputWithInjections + injectedText.length;
                let index = injectedText.injectedTextIndex;
                // traverse all injected text that touch each other
                while (index + 1 < this.injectionOffsets.length && this.injectionOffsets[index + 1] === this.injectionOffsets[index]) {
                    result += this.injectionOptions[index + 1].content.length;
                    index++;
                }
                return result;
            }
            else if (affinity === 0 /* PositionAffinity.Left */ || affinity === 3 /* PositionAffinity.LeftOfInjectedText */) {
                // affinity is left
                let result = injectedText.offsetInInputWithInjections;
                let index = injectedText.injectedTextIndex;
                // traverse all injected text that touch each other
                while (index - 1 >= 0 && this.injectionOffsets[index - 1] === this.injectionOffsets[index]) {
                    result -= this.injectionOptions[index - 1].content.length;
                    index--;
                }
                return result;
            }
            (0, assert_1.assertNever)(affinity);
        }
        getInjectedText(outputLineIndex, outputOffset) {
            const offset = this.outputPositionToOffsetInInputWithInjections(outputLineIndex, outputOffset);
            const injectedText = this.getInjectedTextAtOffset(offset);
            if (!injectedText) {
                return null;
            }
            return {
                options: this.injectionOptions[injectedText.injectedTextIndex]
            };
        }
        getInjectedTextAtOffset(offsetInInputWithInjections) {
            const injectionOffsets = this.injectionOffsets;
            const injectionOptions = this.injectionOptions;
            if (injectionOffsets !== null) {
                let totalInjectedTextLengthBefore = 0;
                for (let i = 0; i < injectionOffsets.length; i++) {
                    const length = injectionOptions[i].content.length;
                    const injectedTextStartOffsetInInputWithInjections = injectionOffsets[i] + totalInjectedTextLengthBefore;
                    const injectedTextEndOffsetInInputWithInjections = injectionOffsets[i] + totalInjectedTextLengthBefore + length;
                    if (injectedTextStartOffsetInInputWithInjections > offsetInInputWithInjections) {
                        // Injected text starts later.
                        break; // All later injected texts have an even larger offset.
                    }
                    if (offsetInInputWithInjections <= injectedTextEndOffsetInInputWithInjections) {
                        // Injected text ends after or with the given position (but also starts with or before it).
                        return {
                            injectedTextIndex: i,
                            offsetInInputWithInjections: injectedTextStartOffsetInInputWithInjections,
                            length
                        };
                    }
                    totalInjectedTextLengthBefore += length;
                }
            }
            return undefined;
        }
    }
    exports.ModelLineProjectionData = ModelLineProjectionData;
    function hasRightCursorStop(cursorStop) {
        if (cursorStop === null || cursorStop === undefined) {
            return true;
        }
        return cursorStop === model_1.InjectedTextCursorStops.Right || cursorStop === model_1.InjectedTextCursorStops.Both;
    }
    function hasLeftCursorStop(cursorStop) {
        if (cursorStop === null || cursorStop === undefined) {
            return true;
        }
        return cursorStop === model_1.InjectedTextCursorStops.Left || cursorStop === model_1.InjectedTextCursorStops.Both;
    }
    class InjectedText {
        constructor(options) {
            this.options = options;
        }
    }
    exports.InjectedText = InjectedText;
    class OutputPosition {
        constructor(outputLineIndex, outputOffset) {
            this.outputLineIndex = outputLineIndex;
            this.outputOffset = outputOffset;
        }
        toString() {
            return `${this.outputLineIndex}:${this.outputOffset}`;
        }
        toPosition(baseLineNumber) {
            return new position_1.Position(baseLineNumber + this.outputLineIndex, this.outputOffset + 1);
        }
    }
    exports.OutputPosition = OutputPosition;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[326/*vs/editor/common/services/editorWorkerHost*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.EditorWorkerHost = void 0;
    class EditorWorkerHost {
        static { this.CHANNEL_NAME = 'editorWorkerHost'; }
        static getChannel(workerServer) {
            return workerServer.getChannel(EditorWorkerHost.CHANNEL_NAME);
        }
        static setChannel(workerClient, obj) {
            workerClient.setChannel(EditorWorkerHost.CHANNEL_NAME, obj);
        }
    }
    exports.EditorWorkerHost = EditorWorkerHost;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[582/*vs/editor/common/services/findSectionHeaders*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.findSectionHeaders = findSectionHeaders;
    const markRegex = new RegExp('\\bMARK:\\s*(.*)$', 'd');
    const trimDashesRegex = /^-+|-+$/g;
    /**
     * Find section headers in the model.
     *
     * @param model the text model to search in
     * @param options options to search with
     * @returns an array of section headers
     */
    function findSectionHeaders(model, options) {
        let headers = [];
        if (options.findRegionSectionHeaders && options.foldingRules?.markers) {
            const regionHeaders = collectRegionHeaders(model, options);
            headers = headers.concat(regionHeaders);
        }
        if (options.findMarkSectionHeaders) {
            const markHeaders = collectMarkHeaders(model);
            headers = headers.concat(markHeaders);
        }
        return headers;
    }
    function collectRegionHeaders(model, options) {
        const regionHeaders = [];
        const endLineNumber = model.getLineCount();
        for (let lineNumber = 1; lineNumber <= endLineNumber; lineNumber++) {
            const lineContent = model.getLineContent(lineNumber);
            const match = lineContent.match(options.foldingRules.markers.start);
            if (match) {
                const range = { startLineNumber: lineNumber, startColumn: match[0].length + 1, endLineNumber: lineNumber, endColumn: lineContent.length + 1 };
                if (range.endColumn > range.startColumn) {
                    const sectionHeader = {
                        range,
                        ...getHeaderText(lineContent.substring(match[0].length)),
                        shouldBeInComments: false
                    };
                    if (sectionHeader.text || sectionHeader.hasSeparatorLine) {
                        regionHeaders.push(sectionHeader);
                    }
                }
            }
        }
        return regionHeaders;
    }
    function collectMarkHeaders(model) {
        const markHeaders = [];
        const endLineNumber = model.getLineCount();
        for (let lineNumber = 1; lineNumber <= endLineNumber; lineNumber++) {
            const lineContent = model.getLineContent(lineNumber);
            addMarkHeaderIfFound(lineContent, lineNumber, markHeaders);
        }
        return markHeaders;
    }
    function addMarkHeaderIfFound(lineContent, lineNumber, sectionHeaders) {
        markRegex.lastIndex = 0;
        const match = markRegex.exec(lineContent);
        if (match) {
            const column = match.indices[1][0] + 1;
            const endColumn = match.indices[1][1] + 1;
            const range = { startLineNumber: lineNumber, startColumn: column, endLineNumber: lineNumber, endColumn: endColumn };
            if (range.endColumn > range.startColumn) {
                const sectionHeader = {
                    range,
                    ...getHeaderText(match[1]),
                    shouldBeInComments: true
                };
                if (sectionHeader.text || sectionHeader.hasSeparatorLine) {
                    sectionHeaders.push(sectionHeader);
                }
            }
        }
    }
    function getHeaderText(text) {
        text = text.trim();
        const hasSeparatorLine = text.startsWith('-');
        text = text.replace(trimDashesRegex, '');
        return { text, hasSeparatorLine };
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[327/*vs/editor/common/services/treeViewsDnd*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DraggedTreeItemsIdentifier = exports.TreeViewsDnDService = void 0;
    class TreeViewsDnDService {
        constructor() {
            this._dragOperations = new Map();
        }
        removeDragOperationTransfer(uuid) {
            if ((uuid && this._dragOperations.has(uuid))) {
                const operation = this._dragOperations.get(uuid);
                this._dragOperations.delete(uuid);
                return operation;
            }
            return undefined;
        }
    }
    exports.TreeViewsDnDService = TreeViewsDnDService;
    class DraggedTreeItemsIdentifier {
        constructor(identifier) {
            this.identifier = identifier;
        }
    }
    exports.DraggedTreeItemsIdentifier = DraggedTreeItemsIdentifier;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[328/*vs/editor/common/services/unicodeTextModelHighlighter*/], __M([1/*require*/,0/*exports*/,4/*vs/editor/common/core/range*/,202/*vs/editor/common/model/textModelSearch*/,11/*vs/base/common/strings*/,90/*vs/base/common/assert*/,147/*vs/editor/common/core/wordHelper*/]), function (require, exports, range_1, textModelSearch_1, strings, assert_1, wordHelper_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.UnicodeTextModelHighlighter = void 0;
    class UnicodeTextModelHighlighter {
        static computeUnicodeHighlights(model, options, range) {
            const startLine = range ? range.startLineNumber : 1;
            const endLine = range ? range.endLineNumber : model.getLineCount();
            const codePointHighlighter = new CodePointHighlighter(options);
            const candidates = codePointHighlighter.getCandidateCodePoints();
            let regex;
            if (candidates === 'allNonBasicAscii') {
                regex = new RegExp('[^\\t\\n\\r\\x20-\\x7E]', 'g');
            }
            else {
                regex = new RegExp(`${buildRegExpCharClassExpr(Array.from(candidates))}`, 'g');
            }
            const searcher = new textModelSearch_1.Searcher(null, regex);
            const ranges = [];
            let hasMore = false;
            let m;
            let ambiguousCharacterCount = 0;
            let invisibleCharacterCount = 0;
            let nonBasicAsciiCharacterCount = 0;
            forLoop: for (let lineNumber = startLine, lineCount = endLine; lineNumber <= lineCount; lineNumber++) {
                const lineContent = model.getLineContent(lineNumber);
                const lineLength = lineContent.length;
                // Reset regex to search from the beginning
                searcher.reset(0);
                do {
                    m = searcher.next(lineContent);
                    if (m) {
                        let startIndex = m.index;
                        let endIndex = m.index + m[0].length;
                        // Extend range to entire code point
                        if (startIndex > 0) {
                            const charCodeBefore = lineContent.charCodeAt(startIndex - 1);
                            if (strings.isHighSurrogate(charCodeBefore)) {
                                startIndex--;
                            }
                        }
                        if (endIndex + 1 < lineLength) {
                            const charCodeBefore = lineContent.charCodeAt(endIndex - 1);
                            if (strings.isHighSurrogate(charCodeBefore)) {
                                endIndex++;
                            }
                        }
                        const str = lineContent.substring(startIndex, endIndex);
                        let word = (0, wordHelper_1.getWordAtText)(startIndex + 1, wordHelper_1.DEFAULT_WORD_REGEXP, lineContent, 0);
                        if (word && word.endColumn <= startIndex + 1) {
                            // The word does not include the problematic character, ignore the word
                            word = null;
                        }
                        const highlightReason = codePointHighlighter.shouldHighlightNonBasicASCII(str, word ? word.word : null);
                        if (highlightReason !== 0 /* SimpleHighlightReason.None */) {
                            if (highlightReason === 3 /* SimpleHighlightReason.Ambiguous */) {
                                ambiguousCharacterCount++;
                            }
                            else if (highlightReason === 2 /* SimpleHighlightReason.Invisible */) {
                                invisibleCharacterCount++;
                            }
                            else if (highlightReason === 1 /* SimpleHighlightReason.NonBasicASCII */) {
                                nonBasicAsciiCharacterCount++;
                            }
                            else {
                                (0, assert_1.assertNever)(highlightReason);
                            }
                            const MAX_RESULT_LENGTH = 1000;
                            if (ranges.length >= MAX_RESULT_LENGTH) {
                                hasMore = true;
                                break forLoop;
                            }
                            ranges.push(new range_1.Range(lineNumber, startIndex + 1, lineNumber, endIndex + 1));
                        }
                    }
                } while (m);
            }
            return {
                ranges,
                hasMore,
                ambiguousCharacterCount,
                invisibleCharacterCount,
                nonBasicAsciiCharacterCount
            };
        }
        static computeUnicodeHighlightReason(char, options) {
            const codePointHighlighter = new CodePointHighlighter(options);
            const reason = codePointHighlighter.shouldHighlightNonBasicASCII(char, null);
            switch (reason) {
                case 0 /* SimpleHighlightReason.None */:
                    return null;
                case 2 /* SimpleHighlightReason.Invisible */:
                    return { kind: 1 /* UnicodeHighlighterReasonKind.Invisible */ };
                case 3 /* SimpleHighlightReason.Ambiguous */: {
                    const codePoint = char.codePointAt(0);
                    const primaryConfusable = codePointHighlighter.ambiguousCharacters.getPrimaryConfusable(codePoint);
                    const notAmbiguousInLocales = strings.AmbiguousCharacters.getLocales().filter((l) => !strings.AmbiguousCharacters.getInstance(new Set([...options.allowedLocales, l])).isAmbiguous(codePoint));
                    return { kind: 0 /* UnicodeHighlighterReasonKind.Ambiguous */, confusableWith: String.fromCodePoint(primaryConfusable), notAmbiguousInLocales };
                }
                case 1 /* SimpleHighlightReason.NonBasicASCII */:
                    return { kind: 2 /* UnicodeHighlighterReasonKind.NonBasicAscii */ };
            }
        }
    }
    exports.UnicodeTextModelHighlighter = UnicodeTextModelHighlighter;
    function buildRegExpCharClassExpr(codePoints, flags) {
        const src = `[${strings.escapeRegExpCharacters(codePoints.map((i) => String.fromCodePoint(i)).join(''))}]`;
        return src;
    }
    class CodePointHighlighter {
        constructor(options) {
            this.options = options;
            this.allowedCodePoints = new Set(options.allowedCodePoints);
            this.ambiguousCharacters = strings.AmbiguousCharacters.getInstance(new Set(options.allowedLocales));
        }
        getCandidateCodePoints() {
            if (this.options.nonBasicASCII) {
                return 'allNonBasicAscii';
            }
            const set = new Set();
            if (this.options.invisibleCharacters) {
                for (const cp of strings.InvisibleCharacters.codePoints) {
                    if (!isAllowedInvisibleCharacter(String.fromCodePoint(cp))) {
                        set.add(cp);
                    }
                }
            }
            if (this.options.ambiguousCharacters) {
                for (const cp of this.ambiguousCharacters.getConfusableCodePoints()) {
                    set.add(cp);
                }
            }
            for (const cp of this.allowedCodePoints) {
                set.delete(cp);
            }
            return set;
        }
        shouldHighlightNonBasicASCII(character, wordContext) {
            const codePoint = character.codePointAt(0);
            if (this.allowedCodePoints.has(codePoint)) {
                return 0 /* SimpleHighlightReason.None */;
            }
            if (this.options.nonBasicASCII) {
                return 1 /* SimpleHighlightReason.NonBasicASCII */;
            }
            let hasBasicASCIICharacters = false;
            let hasNonConfusableNonBasicAsciiCharacter = false;
            if (wordContext) {
                for (const char of wordContext) {
                    const codePoint = char.codePointAt(0);
                    const isBasicASCII = strings.isBasicASCII(char);
                    hasBasicASCIICharacters = hasBasicASCIICharacters || isBasicASCII;
                    if (!isBasicASCII &&
                        !this.ambiguousCharacters.isAmbiguous(codePoint) &&
                        !strings.InvisibleCharacters.isInvisibleCharacter(codePoint)) {
                        hasNonConfusableNonBasicAsciiCharacter = true;
                    }
                }
            }
            if (
            /* Don't allow mixing weird looking characters with ASCII */ !hasBasicASCIICharacters &&
                /* Is there an obviously weird looking character? */ hasNonConfusableNonBasicAsciiCharacter) {
                return 0 /* SimpleHighlightReason.None */;
            }
            if (this.options.invisibleCharacters) {
                // TODO check for emojis
                if (!isAllowedInvisibleCharacter(character) && strings.InvisibleCharacters.isInvisibleCharacter(codePoint)) {
                    return 2 /* SimpleHighlightReason.Invisible */;
                }
            }
            if (this.options.ambiguousCharacters) {
                if (this.ambiguousCharacters.isAmbiguous(codePoint)) {
                    return 3 /* SimpleHighlightReason.Ambiguous */;
                }
            }
            return 0 /* SimpleHighlightReason.None */;
        }
    }
    function isAllowedInvisibleCharacter(character) {
        return character === ' ' || character === '\n' || character === '\t';
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[238/*vs/editor/common/standalone/standaloneEnums*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.WrappingIndent = exports.TrackedRangeStickiness = exports.TextEditorCursorStyle = exports.TextEditorCursorBlinkingStyle = exports.SymbolTag = exports.SymbolKind = exports.SignatureHelpTriggerKind = exports.ShowLightbulbIconMode = exports.SelectionDirection = exports.ScrollbarVisibility = exports.ScrollType = exports.RenderMinimap = exports.RenderLineNumbersType = exports.PositionAffinity = exports.PartialAcceptTriggerKind = exports.OverviewRulerLane = exports.OverlayWidgetPositionPreference = exports.NewSymbolNameTriggerKind = exports.NewSymbolNameTag = exports.MouseTargetType = exports.MinimapSectionHeaderStyle = exports.MinimapPosition = exports.MarkerTag = exports.MarkerSeverity = exports.KeyCode = exports.InlineEditTriggerKind = exports.InlineCompletionTriggerKind = exports.InlayHintKind = exports.InjectedTextCursorStops = exports.IndentAction = exports.HoverVerbosityAction = exports.GlyphMarginLane = exports.EndOfLineSequence = exports.EndOfLinePreference = exports.EditorOption = exports.EditorAutoIndentStrategy = exports.DocumentHighlightKind = exports.DefaultEndOfLine = exports.CursorChangeReason = exports.ContentWidgetPositionPreference = exports.CompletionTriggerKind = exports.CompletionItemTag = exports.CompletionItemKind = exports.CompletionItemInsertTextRule = exports.CodeActionTriggerType = exports.AccessibilitySupport = void 0;
    // THIS IS A GENERATED FILE. DO NOT EDIT DIRECTLY.
    var AccessibilitySupport;
    (function (AccessibilitySupport) {
        /**
         * This should be the browser case where it is not known if a screen reader is attached or no.
         */
        AccessibilitySupport[AccessibilitySupport["Unknown"] = 0] = "Unknown";
        AccessibilitySupport[AccessibilitySupport["Disabled"] = 1] = "Disabled";
        AccessibilitySupport[AccessibilitySupport["Enabled"] = 2] = "Enabled";
    })(AccessibilitySupport || (exports.AccessibilitySupport = AccessibilitySupport = {}));
    var CodeActionTriggerType;
    (function (CodeActionTriggerType) {
        CodeActionTriggerType[CodeActionTriggerType["Invoke"] = 1] = "Invoke";
        CodeActionTriggerType[CodeActionTriggerType["Auto"] = 2] = "Auto";
    })(CodeActionTriggerType || (exports.CodeActionTriggerType = CodeActionTriggerType = {}));
    var CompletionItemInsertTextRule;
    (function (CompletionItemInsertTextRule) {
        CompletionItemInsertTextRule[CompletionItemInsertTextRule["None"] = 0] = "None";
        /**
         * Adjust whitespace/indentation of multiline insert texts to
         * match the current line indentation.
         */
        CompletionItemInsertTextRule[CompletionItemInsertTextRule["KeepWhitespace"] = 1] = "KeepWhitespace";
        /**
         * `insertText` is a snippet.
         */
        CompletionItemInsertTextRule[CompletionItemInsertTextRule["InsertAsSnippet"] = 4] = "InsertAsSnippet";
    })(CompletionItemInsertTextRule || (exports.CompletionItemInsertTextRule = CompletionItemInsertTextRule = {}));
    var CompletionItemKind;
    (function (CompletionItemKind) {
        CompletionItemKind[CompletionItemKind["Method"] = 0] = "Method";
        CompletionItemKind[CompletionItemKind["Function"] = 1] = "Function";
        CompletionItemKind[CompletionItemKind["Constructor"] = 2] = "Constructor";
        CompletionItemKind[CompletionItemKind["Field"] = 3] = "Field";
        CompletionItemKind[CompletionItemKind["Variable"] = 4] = "Variable";
        CompletionItemKind[CompletionItemKind["Class"] = 5] = "Class";
        CompletionItemKind[CompletionItemKind["Struct"] = 6] = "Struct";
        CompletionItemKind[CompletionItemKind["Interface"] = 7] = "Interface";
        CompletionItemKind[CompletionItemKind["Module"] = 8] = "Module";
        CompletionItemKind[CompletionItemKind["Property"] = 9] = "Property";
        CompletionItemKind[CompletionItemKind["Event"] = 10] = "Event";
        CompletionItemKind[CompletionItemKind["Operator"] = 11] = "Operator";
        CompletionItemKind[CompletionItemKind["Unit"] = 12] = "Unit";
        CompletionItemKind[CompletionItemKind["Value"] = 13] = "Value";
        CompletionItemKind[CompletionItemKind["Constant"] = 14] = "Constant";
        CompletionItemKind[CompletionItemKind["Enum"] = 15] = "Enum";
        CompletionItemKind[CompletionItemKind["EnumMember"] = 16] = "EnumMember";
        CompletionItemKind[CompletionItemKind["Keyword"] = 17] = "Keyword";
        CompletionItemKind[CompletionItemKind["Text"] = 18] = "Text";
        CompletionItemKind[CompletionItemKind["Color"] = 19] = "Color";
        CompletionItemKind[CompletionItemKind["File"] = 20] = "File";
        CompletionItemKind[CompletionItemKind["Reference"] = 21] = "Reference";
        CompletionItemKind[CompletionItemKind["Customcolor"] = 22] = "Customcolor";
        CompletionItemKind[CompletionItemKind["Folder"] = 23] = "Folder";
        CompletionItemKind[CompletionItemKind["TypeParameter"] = 24] = "TypeParameter";
        CompletionItemKind[CompletionItemKind["User"] = 25] = "User";
        CompletionItemKind[CompletionItemKind["Issue"] = 26] = "Issue";
        CompletionItemKind[CompletionItemKind["Snippet"] = 27] = "Snippet";
    })(CompletionItemKind || (exports.CompletionItemKind = CompletionItemKind = {}));
    var CompletionItemTag;
    (function (CompletionItemTag) {
        CompletionItemTag[CompletionItemTag["Deprecated"] = 1] = "Deprecated";
    })(CompletionItemTag || (exports.CompletionItemTag = CompletionItemTag = {}));
    /**
     * How a suggest provider was triggered.
     */
    var CompletionTriggerKind;
    (function (CompletionTriggerKind) {
        CompletionTriggerKind[CompletionTriggerKind["Invoke"] = 0] = "Invoke";
        CompletionTriggerKind[CompletionTriggerKind["TriggerCharacter"] = 1] = "TriggerCharacter";
        CompletionTriggerKind[CompletionTriggerKind["TriggerForIncompleteCompletions"] = 2] = "TriggerForIncompleteCompletions";
    })(CompletionTriggerKind || (exports.CompletionTriggerKind = CompletionTriggerKind = {}));
    /**
     * A positioning preference for rendering content widgets.
     */
    var ContentWidgetPositionPreference;
    (function (ContentWidgetPositionPreference) {
        /**
         * Place the content widget exactly at a position
         */
        ContentWidgetPositionPreference[ContentWidgetPositionPreference["EXACT"] = 0] = "EXACT";
        /**
         * Place the content widget above a position
         */
        ContentWidgetPositionPreference[ContentWidgetPositionPreference["ABOVE"] = 1] = "ABOVE";
        /**
         * Place the content widget below a position
         */
        ContentWidgetPositionPreference[ContentWidgetPositionPreference["BELOW"] = 2] = "BELOW";
    })(ContentWidgetPositionPreference || (exports.ContentWidgetPositionPreference = ContentWidgetPositionPreference = {}));
    /**
     * Describes the reason the cursor has changed its position.
     */
    var CursorChangeReason;
    (function (CursorChangeReason) {
        /**
         * Unknown or not set.
         */
        CursorChangeReason[CursorChangeReason["NotSet"] = 0] = "NotSet";
        /**
         * A `model.setValue()` was called.
         */
        CursorChangeReason[CursorChangeReason["ContentFlush"] = 1] = "ContentFlush";
        /**
         * The `model` has been changed outside of this cursor and the cursor recovers its position from associated markers.
         */
        CursorChangeReason[CursorChangeReason["RecoverFromMarkers"] = 2] = "RecoverFromMarkers";
        /**
         * There was an explicit user gesture.
         */
        CursorChangeReason[CursorChangeReason["Explicit"] = 3] = "Explicit";
        /**
         * There was a Paste.
         */
        CursorChangeReason[CursorChangeReason["Paste"] = 4] = "Paste";
        /**
         * There was an Undo.
         */
        CursorChangeReason[CursorChangeReason["Undo"] = 5] = "Undo";
        /**
         * There was a Redo.
         */
        CursorChangeReason[CursorChangeReason["Redo"] = 6] = "Redo";
    })(CursorChangeReason || (exports.CursorChangeReason = CursorChangeReason = {}));
    /**
     * The default end of line to use when instantiating models.
     */
    var DefaultEndOfLine;
    (function (DefaultEndOfLine) {
        /**
         * Use line feed (\n) as the end of line character.
         */
        DefaultEndOfLine[DefaultEndOfLine["LF"] = 1] = "LF";
        /**
         * Use carriage return and line feed (\r\n) as the end of line character.
         */
        DefaultEndOfLine[DefaultEndOfLine["CRLF"] = 2] = "CRLF";
    })(DefaultEndOfLine || (exports.DefaultEndOfLine = DefaultEndOfLine = {}));
    /**
     * A document highlight kind.
     */
    var DocumentHighlightKind;
    (function (DocumentHighlightKind) {
        /**
         * A textual occurrence.
         */
        DocumentHighlightKind[DocumentHighlightKind["Text"] = 0] = "Text";
        /**
         * Read-access of a symbol, like reading a variable.
         */
        DocumentHighlightKind[DocumentHighlightKind["Read"] = 1] = "Read";
        /**
         * Write-access of a symbol, like writing to a variable.
         */
        DocumentHighlightKind[DocumentHighlightKind["Write"] = 2] = "Write";
    })(DocumentHighlightKind || (exports.DocumentHighlightKind = DocumentHighlightKind = {}));
    /**
     * Configuration options for auto indentation in the editor
     */
    var EditorAutoIndentStrategy;
    (function (EditorAutoIndentStrategy) {
        EditorAutoIndentStrategy[EditorAutoIndentStrategy["None"] = 0] = "None";
        EditorAutoIndentStrategy[EditorAutoIndentStrategy["Keep"] = 1] = "Keep";
        EditorAutoIndentStrategy[EditorAutoIndentStrategy["Brackets"] = 2] = "Brackets";
        EditorAutoIndentStrategy[EditorAutoIndentStrategy["Advanced"] = 3] = "Advanced";
        EditorAutoIndentStrategy[EditorAutoIndentStrategy["Full"] = 4] = "Full";
    })(EditorAutoIndentStrategy || (exports.EditorAutoIndentStrategy = EditorAutoIndentStrategy = {}));
    var EditorOption;
    (function (EditorOption) {
        EditorOption[EditorOption["acceptSuggestionOnCommitCharacter"] = 0] = "acceptSuggestionOnCommitCharacter";
        EditorOption[EditorOption["acceptSuggestionOnEnter"] = 1] = "acceptSuggestionOnEnter";
        EditorOption[EditorOption["accessibilitySupport"] = 2] = "accessibilitySupport";
        EditorOption[EditorOption["accessibilityPageSize"] = 3] = "accessibilityPageSize";
        EditorOption[EditorOption["ariaLabel"] = 4] = "ariaLabel";
        EditorOption[EditorOption["ariaRequired"] = 5] = "ariaRequired";
        EditorOption[EditorOption["autoClosingBrackets"] = 6] = "autoClosingBrackets";
        EditorOption[EditorOption["autoClosingComments"] = 7] = "autoClosingComments";
        EditorOption[EditorOption["screenReaderAnnounceInlineSuggestion"] = 8] = "screenReaderAnnounceInlineSuggestion";
        EditorOption[EditorOption["autoClosingDelete"] = 9] = "autoClosingDelete";
        EditorOption[EditorOption["autoClosingOvertype"] = 10] = "autoClosingOvertype";
        EditorOption[EditorOption["autoClosingQuotes"] = 11] = "autoClosingQuotes";
        EditorOption[EditorOption["autoIndent"] = 12] = "autoIndent";
        EditorOption[EditorOption["automaticLayout"] = 13] = "automaticLayout";
        EditorOption[EditorOption["autoSurround"] = 14] = "autoSurround";
        EditorOption[EditorOption["bracketPairColorization"] = 15] = "bracketPairColorization";
        EditorOption[EditorOption["guides"] = 16] = "guides";
        EditorOption[EditorOption["codeLens"] = 17] = "codeLens";
        EditorOption[EditorOption["codeLensFontFamily"] = 18] = "codeLensFontFamily";
        EditorOption[EditorOption["codeLensFontSize"] = 19] = "codeLensFontSize";
        EditorOption[EditorOption["colorDecorators"] = 20] = "colorDecorators";
        EditorOption[EditorOption["colorDecoratorsLimit"] = 21] = "colorDecoratorsLimit";
        EditorOption[EditorOption["columnSelection"] = 22] = "columnSelection";
        EditorOption[EditorOption["comments"] = 23] = "comments";
        EditorOption[EditorOption["contextmenu"] = 24] = "contextmenu";
        EditorOption[EditorOption["copyWithSyntaxHighlighting"] = 25] = "copyWithSyntaxHighlighting";
        EditorOption[EditorOption["cursorBlinking"] = 26] = "cursorBlinking";
        EditorOption[EditorOption["cursorSmoothCaretAnimation"] = 27] = "cursorSmoothCaretAnimation";
        EditorOption[EditorOption["cursorStyle"] = 28] = "cursorStyle";
        EditorOption[EditorOption["cursorSurroundingLines"] = 29] = "cursorSurroundingLines";
        EditorOption[EditorOption["cursorSurroundingLinesStyle"] = 30] = "cursorSurroundingLinesStyle";
        EditorOption[EditorOption["cursorWidth"] = 31] = "cursorWidth";
        EditorOption[EditorOption["disableLayerHinting"] = 32] = "disableLayerHinting";
        EditorOption[EditorOption["disableMonospaceOptimizations"] = 33] = "disableMonospaceOptimizations";
        EditorOption[EditorOption["domReadOnly"] = 34] = "domReadOnly";
        EditorOption[EditorOption["dragAndDrop"] = 35] = "dragAndDrop";
        EditorOption[EditorOption["dropIntoEditor"] = 36] = "dropIntoEditor";
        EditorOption[EditorOption["emptySelectionClipboard"] = 37] = "emptySelectionClipboard";
        EditorOption[EditorOption["experimentalWhitespaceRendering"] = 38] = "experimentalWhitespaceRendering";
        EditorOption[EditorOption["extraEditorClassName"] = 39] = "extraEditorClassName";
        EditorOption[EditorOption["fastScrollSensitivity"] = 40] = "fastScrollSensitivity";
        EditorOption[EditorOption["find"] = 41] = "find";
        EditorOption[EditorOption["fixedOverflowWidgets"] = 42] = "fixedOverflowWidgets";
        EditorOption[EditorOption["folding"] = 43] = "folding";
        EditorOption[EditorOption["foldingStrategy"] = 44] = "foldingStrategy";
        EditorOption[EditorOption["foldingHighlight"] = 45] = "foldingHighlight";
        EditorOption[EditorOption["foldingImportsByDefault"] = 46] = "foldingImportsByDefault";
        EditorOption[EditorOption["foldingMaximumRegions"] = 47] = "foldingMaximumRegions";
        EditorOption[EditorOption["unfoldOnClickAfterEndOfLine"] = 48] = "unfoldOnClickAfterEndOfLine";
        EditorOption[EditorOption["fontFamily"] = 49] = "fontFamily";
        EditorOption[EditorOption["fontInfo"] = 50] = "fontInfo";
        EditorOption[EditorOption["fontLigatures"] = 51] = "fontLigatures";
        EditorOption[EditorOption["fontSize"] = 52] = "fontSize";
        EditorOption[EditorOption["fontWeight"] = 53] = "fontWeight";
        EditorOption[EditorOption["fontVariations"] = 54] = "fontVariations";
        EditorOption[EditorOption["formatOnPaste"] = 55] = "formatOnPaste";
        EditorOption[EditorOption["formatOnType"] = 56] = "formatOnType";
        EditorOption[EditorOption["glyphMargin"] = 57] = "glyphMargin";
        EditorOption[EditorOption["gotoLocation"] = 58] = "gotoLocation";
        EditorOption[EditorOption["hideCursorInOverviewRuler"] = 59] = "hideCursorInOverviewRuler";
        EditorOption[EditorOption["hover"] = 60] = "hover";
        EditorOption[EditorOption["inDiffEditor"] = 61] = "inDiffEditor";
        EditorOption[EditorOption["inlineSuggest"] = 62] = "inlineSuggest";
        EditorOption[EditorOption["inlineEdit"] = 63] = "inlineEdit";
        EditorOption[EditorOption["letterSpacing"] = 64] = "letterSpacing";
        EditorOption[EditorOption["lightbulb"] = 65] = "lightbulb";
        EditorOption[EditorOption["lineDecorationsWidth"] = 66] = "lineDecorationsWidth";
        EditorOption[EditorOption["lineHeight"] = 67] = "lineHeight";
        EditorOption[EditorOption["lineNumbers"] = 68] = "lineNumbers";
        EditorOption[EditorOption["lineNumbersMinChars"] = 69] = "lineNumbersMinChars";
        EditorOption[EditorOption["linkedEditing"] = 70] = "linkedEditing";
        EditorOption[EditorOption["links"] = 71] = "links";
        EditorOption[EditorOption["matchBrackets"] = 72] = "matchBrackets";
        EditorOption[EditorOption["minimap"] = 73] = "minimap";
        EditorOption[EditorOption["mouseStyle"] = 74] = "mouseStyle";
        EditorOption[EditorOption["mouseWheelScrollSensitivity"] = 75] = "mouseWheelScrollSensitivity";
        EditorOption[EditorOption["mouseWheelZoom"] = 76] = "mouseWheelZoom";
        EditorOption[EditorOption["multiCursorMergeOverlapping"] = 77] = "multiCursorMergeOverlapping";
        EditorOption[EditorOption["multiCursorModifier"] = 78] = "multiCursorModifier";
        EditorOption[EditorOption["multiCursorPaste"] = 79] = "multiCursorPaste";
        EditorOption[EditorOption["multiCursorLimit"] = 80] = "multiCursorLimit";
        EditorOption[EditorOption["occurrencesHighlight"] = 81] = "occurrencesHighlight";
        EditorOption[EditorOption["overviewRulerBorder"] = 82] = "overviewRulerBorder";
        EditorOption[EditorOption["overviewRulerLanes"] = 83] = "overviewRulerLanes";
        EditorOption[EditorOption["padding"] = 84] = "padding";
        EditorOption[EditorOption["pasteAs"] = 85] = "pasteAs";
        EditorOption[EditorOption["parameterHints"] = 86] = "parameterHints";
        EditorOption[EditorOption["peekWidgetDefaultFocus"] = 87] = "peekWidgetDefaultFocus";
        EditorOption[EditorOption["placeholder"] = 88] = "placeholder";
        EditorOption[EditorOption["definitionLinkOpensInPeek"] = 89] = "definitionLinkOpensInPeek";
        EditorOption[EditorOption["quickSuggestions"] = 90] = "quickSuggestions";
        EditorOption[EditorOption["quickSuggestionsDelay"] = 91] = "quickSuggestionsDelay";
        EditorOption[EditorOption["readOnly"] = 92] = "readOnly";
        EditorOption[EditorOption["readOnlyMessage"] = 93] = "readOnlyMessage";
        EditorOption[EditorOption["renameOnType"] = 94] = "renameOnType";
        EditorOption[EditorOption["renderControlCharacters"] = 95] = "renderControlCharacters";
        EditorOption[EditorOption["renderFinalNewline"] = 96] = "renderFinalNewline";
        EditorOption[EditorOption["renderLineHighlight"] = 97] = "renderLineHighlight";
        EditorOption[EditorOption["renderLineHighlightOnlyWhenFocus"] = 98] = "renderLineHighlightOnlyWhenFocus";
        EditorOption[EditorOption["renderValidationDecorations"] = 99] = "renderValidationDecorations";
        EditorOption[EditorOption["renderWhitespace"] = 100] = "renderWhitespace";
        EditorOption[EditorOption["revealHorizontalRightPadding"] = 101] = "revealHorizontalRightPadding";
        EditorOption[EditorOption["roundedSelection"] = 102] = "roundedSelection";
        EditorOption[EditorOption["rulers"] = 103] = "rulers";
        EditorOption[EditorOption["scrollbar"] = 104] = "scrollbar";
        EditorOption[EditorOption["scrollBeyondLastColumn"] = 105] = "scrollBeyondLastColumn";
        EditorOption[EditorOption["scrollBeyondLastLine"] = 106] = "scrollBeyondLastLine";
        EditorOption[EditorOption["scrollPredominantAxis"] = 107] = "scrollPredominantAxis";
        EditorOption[EditorOption["selectionClipboard"] = 108] = "selectionClipboard";
        EditorOption[EditorOption["selectionHighlight"] = 109] = "selectionHighlight";
        EditorOption[EditorOption["selectOnLineNumbers"] = 110] = "selectOnLineNumbers";
        EditorOption[EditorOption["showFoldingControls"] = 111] = "showFoldingControls";
        EditorOption[EditorOption["showUnused"] = 112] = "showUnused";
        EditorOption[EditorOption["snippetSuggestions"] = 113] = "snippetSuggestions";
        EditorOption[EditorOption["smartSelect"] = 114] = "smartSelect";
        EditorOption[EditorOption["smoothScrolling"] = 115] = "smoothScrolling";
        EditorOption[EditorOption["stickyScroll"] = 116] = "stickyScroll";
        EditorOption[EditorOption["stickyTabStops"] = 117] = "stickyTabStops";
        EditorOption[EditorOption["stopRenderingLineAfter"] = 118] = "stopRenderingLineAfter";
        EditorOption[EditorOption["suggest"] = 119] = "suggest";
        EditorOption[EditorOption["suggestFontSize"] = 120] = "suggestFontSize";
        EditorOption[EditorOption["suggestLineHeight"] = 121] = "suggestLineHeight";
        EditorOption[EditorOption["suggestOnTriggerCharacters"] = 122] = "suggestOnTriggerCharacters";
        EditorOption[EditorOption["suggestSelection"] = 123] = "suggestSelection";
        EditorOption[EditorOption["tabCompletion"] = 124] = "tabCompletion";
        EditorOption[EditorOption["tabIndex"] = 125] = "tabIndex";
        EditorOption[EditorOption["unicodeHighlighting"] = 126] = "unicodeHighlighting";
        EditorOption[EditorOption["unusualLineTerminators"] = 127] = "unusualLineTerminators";
        EditorOption[EditorOption["useShadowDOM"] = 128] = "useShadowDOM";
        EditorOption[EditorOption["useTabStops"] = 129] = "useTabStops";
        EditorOption[EditorOption["wordBreak"] = 130] = "wordBreak";
        EditorOption[EditorOption["wordSegmenterLocales"] = 131] = "wordSegmenterLocales";
        EditorOption[EditorOption["wordSeparators"] = 132] = "wordSeparators";
        EditorOption[EditorOption["wordWrap"] = 133] = "wordWrap";
        EditorOption[EditorOption["wordWrapBreakAfterCharacters"] = 134] = "wordWrapBreakAfterCharacters";
        EditorOption[EditorOption["wordWrapBreakBeforeCharacters"] = 135] = "wordWrapBreakBeforeCharacters";
        EditorOption[EditorOption["wordWrapColumn"] = 136] = "wordWrapColumn";
        EditorOption[EditorOption["wordWrapOverride1"] = 137] = "wordWrapOverride1";
        EditorOption[EditorOption["wordWrapOverride2"] = 138] = "wordWrapOverride2";
        EditorOption[EditorOption["wrappingIndent"] = 139] = "wrappingIndent";
        EditorOption[EditorOption["wrappingStrategy"] = 140] = "wrappingStrategy";
        EditorOption[EditorOption["showDeprecated"] = 141] = "showDeprecated";
        EditorOption[EditorOption["inlayHints"] = 142] = "inlayHints";
        EditorOption[EditorOption["editorClassName"] = 143] = "editorClassName";
        EditorOption[EditorOption["pixelRatio"] = 144] = "pixelRatio";
        EditorOption[EditorOption["tabFocusMode"] = 145] = "tabFocusMode";
        EditorOption[EditorOption["layoutInfo"] = 146] = "layoutInfo";
        EditorOption[EditorOption["wrappingInfo"] = 147] = "wrappingInfo";
        EditorOption[EditorOption["defaultColorDecorators"] = 148] = "defaultColorDecorators";
        EditorOption[EditorOption["colorDecoratorsActivatedOn"] = 149] = "colorDecoratorsActivatedOn";
        EditorOption[EditorOption["inlineCompletionsAccessibilityVerbose"] = 150] = "inlineCompletionsAccessibilityVerbose";
    })(EditorOption || (exports.EditorOption = EditorOption = {}));
    /**
     * End of line character preference.
     */
    var EndOfLinePreference;
    (function (EndOfLinePreference) {
        /**
         * Use the end of line character identified in the text buffer.
         */
        EndOfLinePreference[EndOfLinePreference["TextDefined"] = 0] = "TextDefined";
        /**
         * Use line feed (\n) as the end of line character.
         */
        EndOfLinePreference[EndOfLinePreference["LF"] = 1] = "LF";
        /**
         * Use carriage return and line feed (\r\n) as the end of line character.
         */
        EndOfLinePreference[EndOfLinePreference["CRLF"] = 2] = "CRLF";
    })(EndOfLinePreference || (exports.EndOfLinePreference = EndOfLinePreference = {}));
    /**
     * End of line character preference.
     */
    var EndOfLineSequence;
    (function (EndOfLineSequence) {
        /**
         * Use line feed (\n) as the end of line character.
         */
        EndOfLineSequence[EndOfLineSequence["LF"] = 0] = "LF";
        /**
         * Use carriage return and line feed (\r\n) as the end of line character.
         */
        EndOfLineSequence[EndOfLineSequence["CRLF"] = 1] = "CRLF";
    })(EndOfLineSequence || (exports.EndOfLineSequence = EndOfLineSequence = {}));
    /**
     * Vertical Lane in the glyph margin of the editor.
     */
    var GlyphMarginLane;
    (function (GlyphMarginLane) {
        GlyphMarginLane[GlyphMarginLane["Left"] = 1] = "Left";
        GlyphMarginLane[GlyphMarginLane["Center"] = 2] = "Center";
        GlyphMarginLane[GlyphMarginLane["Right"] = 3] = "Right";
    })(GlyphMarginLane || (exports.GlyphMarginLane = GlyphMarginLane = {}));
    var HoverVerbosityAction;
    (function (HoverVerbosityAction) {
        /**
         * Increase the verbosity of the hover
         */
        HoverVerbosityAction[HoverVerbosityAction["Increase"] = 0] = "Increase";
        /**
         * Decrease the verbosity of the hover
         */
        HoverVerbosityAction[HoverVerbosityAction["Decrease"] = 1] = "Decrease";
    })(HoverVerbosityAction || (exports.HoverVerbosityAction = HoverVerbosityAction = {}));
    /**
     * Describes what to do with the indentation when pressing Enter.
     */
    var IndentAction;
    (function (IndentAction) {
        /**
         * Insert new line and copy the previous line's indentation.
         */
        IndentAction[IndentAction["None"] = 0] = "None";
        /**
         * Insert new line and indent once (relative to the previous line's indentation).
         */
        IndentAction[IndentAction["Indent"] = 1] = "Indent";
        /**
         * Insert two new lines:
         *  - the first one indented which will hold the cursor
         *  - the second one at the same indentation level
         */
        IndentAction[IndentAction["IndentOutdent"] = 2] = "IndentOutdent";
        /**
         * Insert new line and outdent once (relative to the previous line's indentation).
         */
        IndentAction[IndentAction["Outdent"] = 3] = "Outdent";
    })(IndentAction || (exports.IndentAction = IndentAction = {}));
    var InjectedTextCursorStops;
    (function (InjectedTextCursorStops) {
        InjectedTextCursorStops[InjectedTextCursorStops["Both"] = 0] = "Both";
        InjectedTextCursorStops[InjectedTextCursorStops["Right"] = 1] = "Right";
        InjectedTextCursorStops[InjectedTextCursorStops["Left"] = 2] = "Left";
        InjectedTextCursorStops[InjectedTextCursorStops["None"] = 3] = "None";
    })(InjectedTextCursorStops || (exports.InjectedTextCursorStops = InjectedTextCursorStops = {}));
    var InlayHintKind;
    (function (InlayHintKind) {
        InlayHintKind[InlayHintKind["Type"] = 1] = "Type";
        InlayHintKind[InlayHintKind["Parameter"] = 2] = "Parameter";
    })(InlayHintKind || (exports.InlayHintKind = InlayHintKind = {}));
    /**
     * How an {@link InlineCompletionsProvider inline completion provider} was triggered.
     */
    var InlineCompletionTriggerKind;
    (function (InlineCompletionTriggerKind) {
        /**
         * Completion was triggered automatically while editing.
         * It is sufficient to return a single completion item in this case.
         */
        InlineCompletionTriggerKind[InlineCompletionTriggerKind["Automatic"] = 0] = "Automatic";
        /**
         * Completion was triggered explicitly by a user gesture.
         * Return multiple completion items to enable cycling through them.
         */
        InlineCompletionTriggerKind[InlineCompletionTriggerKind["Explicit"] = 1] = "Explicit";
    })(InlineCompletionTriggerKind || (exports.InlineCompletionTriggerKind = InlineCompletionTriggerKind = {}));
    var InlineEditTriggerKind;
    (function (InlineEditTriggerKind) {
        InlineEditTriggerKind[InlineEditTriggerKind["Invoke"] = 0] = "Invoke";
        InlineEditTriggerKind[InlineEditTriggerKind["Automatic"] = 1] = "Automatic";
    })(InlineEditTriggerKind || (exports.InlineEditTriggerKind = InlineEditTriggerKind = {}));
    /**
     * Virtual Key Codes, the value does not hold any inherent meaning.
     * Inspired somewhat from https://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx
     * But these are "more general", as they should work across browsers & OS`s.
     */
    var KeyCode;
    (function (KeyCode) {
        KeyCode[KeyCode["DependsOnKbLayout"] = -1] = "DependsOnKbLayout";
        /**
         * Placed first to cover the 0 value of the enum.
         */
        KeyCode[KeyCode["Unknown"] = 0] = "Unknown";
        KeyCode[KeyCode["Backspace"] = 1] = "Backspace";
        KeyCode[KeyCode["Tab"] = 2] = "Tab";
        KeyCode[KeyCode["Enter"] = 3] = "Enter";
        KeyCode[KeyCode["Shift"] = 4] = "Shift";
        KeyCode[KeyCode["Ctrl"] = 5] = "Ctrl";
        KeyCode[KeyCode["Alt"] = 6] = "Alt";
        KeyCode[KeyCode["PauseBreak"] = 7] = "PauseBreak";
        KeyCode[KeyCode["CapsLock"] = 8] = "CapsLock";
        KeyCode[KeyCode["Escape"] = 9] = "Escape";
        KeyCode[KeyCode["Space"] = 10] = "Space";
        KeyCode[KeyCode["PageUp"] = 11] = "PageUp";
        KeyCode[KeyCode["PageDown"] = 12] = "PageDown";
        KeyCode[KeyCode["End"] = 13] = "End";
        KeyCode[KeyCode["Home"] = 14] = "Home";
        KeyCode[KeyCode["LeftArrow"] = 15] = "LeftArrow";
        KeyCode[KeyCode["UpArrow"] = 16] = "UpArrow";
        KeyCode[KeyCode["RightArrow"] = 17] = "RightArrow";
        KeyCode[KeyCode["DownArrow"] = 18] = "DownArrow";
        KeyCode[KeyCode["Insert"] = 19] = "Insert";
        KeyCode[KeyCode["Delete"] = 20] = "Delete";
        KeyCode[KeyCode["Digit0"] = 21] = "Digit0";
        KeyCode[KeyCode["Digit1"] = 22] = "Digit1";
        KeyCode[KeyCode["Digit2"] = 23] = "Digit2";
        KeyCode[KeyCode["Digit3"] = 24] = "Digit3";
        KeyCode[KeyCode["Digit4"] = 25] = "Digit4";
        KeyCode[KeyCode["Digit5"] = 26] = "Digit5";
        KeyCode[KeyCode["Digit6"] = 27] = "Digit6";
        KeyCode[KeyCode["Digit7"] = 28] = "Digit7";
        KeyCode[KeyCode["Digit8"] = 29] = "Digit8";
        KeyCode[KeyCode["Digit9"] = 30] = "Digit9";
        KeyCode[KeyCode["KeyA"] = 31] = "KeyA";
        KeyCode[KeyCode["KeyB"] = 32] = "KeyB";
        KeyCode[KeyCode["KeyC"] = 33] = "KeyC";
        KeyCode[KeyCode["KeyD"] = 34] = "KeyD";
        KeyCode[KeyCode["KeyE"] = 35] = "KeyE";
        KeyCode[KeyCode["KeyF"] = 36] = "KeyF";
        KeyCode[KeyCode["KeyG"] = 37] = "KeyG";
        KeyCode[KeyCode["KeyH"] = 38] = "KeyH";
        KeyCode[KeyCode["KeyI"] = 39] = "KeyI";
        KeyCode[KeyCode["KeyJ"] = 40] = "KeyJ";
        KeyCode[KeyCode["KeyK"] = 41] = "KeyK";
        KeyCode[KeyCode["KeyL"] = 42] = "KeyL";
        KeyCode[KeyCode["KeyM"] = 43] = "KeyM";
        KeyCode[KeyCode["KeyN"] = 44] = "KeyN";
        KeyCode[KeyCode["KeyO"] = 45] = "KeyO";
        KeyCode[KeyCode["KeyP"] = 46] = "KeyP";
        KeyCode[KeyCode["KeyQ"] = 47] = "KeyQ";
        KeyCode[KeyCode["KeyR"] = 48] = "KeyR";
        KeyCode[KeyCode["KeyS"] = 49] = "KeyS";
        KeyCode[KeyCode["KeyT"] = 50] = "KeyT";
        KeyCode[KeyCode["KeyU"] = 51] = "KeyU";
        KeyCode[KeyCode["KeyV"] = 52] = "KeyV";
        KeyCode[KeyCode["KeyW"] = 53] = "KeyW";
        KeyCode[KeyCode["KeyX"] = 54] = "KeyX";
        KeyCode[KeyCode["KeyY"] = 55] = "KeyY";
        KeyCode[KeyCode["KeyZ"] = 56] = "KeyZ";
        KeyCode[KeyCode["Meta"] = 57] = "Meta";
        KeyCode[KeyCode["ContextMenu"] = 58] = "ContextMenu";
        KeyCode[KeyCode["F1"] = 59] = "F1";
        KeyCode[KeyCode["F2"] = 60] = "F2";
        KeyCode[KeyCode["F3"] = 61] = "F3";
        KeyCode[KeyCode["F4"] = 62] = "F4";
        KeyCode[KeyCode["F5"] = 63] = "F5";
        KeyCode[KeyCode["F6"] = 64] = "F6";
        KeyCode[KeyCode["F7"] = 65] = "F7";
        KeyCode[KeyCode["F8"] = 66] = "F8";
        KeyCode[KeyCode["F9"] = 67] = "F9";
        KeyCode[KeyCode["F10"] = 68] = "F10";
        KeyCode[KeyCode["F11"] = 69] = "F11";
        KeyCode[KeyCode["F12"] = 70] = "F12";
        KeyCode[KeyCode["F13"] = 71] = "F13";
        KeyCode[KeyCode["F14"] = 72] = "F14";
        KeyCode[KeyCode["F15"] = 73] = "F15";
        KeyCode[KeyCode["F16"] = 74] = "F16";
        KeyCode[KeyCode["F17"] = 75] = "F17";
        KeyCode[KeyCode["F18"] = 76] = "F18";
        KeyCode[KeyCode["F19"] = 77] = "F19";
        KeyCode[KeyCode["F20"] = 78] = "F20";
        KeyCode[KeyCode["F21"] = 79] = "F21";
        KeyCode[KeyCode["F22"] = 80] = "F22";
        KeyCode[KeyCode["F23"] = 81] = "F23";
        KeyCode[KeyCode["F24"] = 82] = "F24";
        KeyCode[KeyCode["NumLock"] = 83] = "NumLock";
        KeyCode[KeyCode["ScrollLock"] = 84] = "ScrollLock";
        /**
         * Used for miscellaneous characters; it can vary by keyboard.
         * For the US standard keyboard, the ';:' key
         */
        KeyCode[KeyCode["Semicolon"] = 85] = "Semicolon";
        /**
         * For any country/region, the '+' key
         * For the US standard keyboard, the '=+' key
         */
        KeyCode[KeyCode["Equal"] = 86] = "Equal";
        /**
         * For any country/region, the ',' key
         * For the US standard keyboard, the ',<' key
         */
        KeyCode[KeyCode["Comma"] = 87] = "Comma";
        /**
         * For any country/region, the '-' key
         * For the US standard keyboard, the '-_' key
         */
        KeyCode[KeyCode["Minus"] = 88] = "Minus";
        /**
         * For any country/region, the '.' key
         * For the US standard keyboard, the '.>' key
         */
        KeyCode[KeyCode["Period"] = 89] = "Period";
        /**
         * Used for miscellaneous characters; it can vary by keyboard.
         * For the US standard keyboard, the '/?' key
         */
        KeyCode[KeyCode["Slash"] = 90] = "Slash";
        /**
         * Used for miscellaneous characters; it can vary by keyboard.
         * For the US standard keyboard, the '`~' key
         */
        KeyCode[KeyCode["Backquote"] = 91] = "Backquote";
        /**
         * Used for miscellaneous characters; it can vary by keyboard.
         * For the US standard keyboard, the '[{' key
         */
        KeyCode[KeyCode["BracketLeft"] = 92] = "BracketLeft";
        /**
         * Used for miscellaneous characters; it can vary by keyboard.
         * For the US standard keyboard, the '\|' key
         */
        KeyCode[KeyCode["Backslash"] = 93] = "Backslash";
        /**
         * Used for miscellaneous characters; it can vary by keyboard.
         * For the US standard keyboard, the ']}' key
         */
        KeyCode[KeyCode["BracketRight"] = 94] = "BracketRight";
        /**
         * Used for miscellaneous characters; it can vary by keyboard.
         * For the US standard keyboard, the ''"' key
         */
        KeyCode[KeyCode["Quote"] = 95] = "Quote";
        /**
         * Used for miscellaneous characters; it can vary by keyboard.
         */
        KeyCode[KeyCode["OEM_8"] = 96] = "OEM_8";
        /**
         * Either the angle bracket key or the backslash key on the RT 102-key keyboard.
         */
        KeyCode[KeyCode["IntlBackslash"] = 97] = "IntlBackslash";
        KeyCode[KeyCode["Numpad0"] = 98] = "Numpad0";
        KeyCode[KeyCode["Numpad1"] = 99] = "Numpad1";
        KeyCode[KeyCode["Numpad2"] = 100] = "Numpad2";
        KeyCode[KeyCode["Numpad3"] = 101] = "Numpad3";
        KeyCode[KeyCode["Numpad4"] = 102] = "Numpad4";
        KeyCode[KeyCode["Numpad5"] = 103] = "Numpad5";
        KeyCode[KeyCode["Numpad6"] = 104] = "Numpad6";
        KeyCode[KeyCode["Numpad7"] = 105] = "Numpad7";
        KeyCode[KeyCode["Numpad8"] = 106] = "Numpad8";
        KeyCode[KeyCode["Numpad9"] = 107] = "Numpad9";
        KeyCode[KeyCode["NumpadMultiply"] = 108] = "NumpadMultiply";
        KeyCode[KeyCode["NumpadAdd"] = 109] = "NumpadAdd";
        KeyCode[KeyCode["NUMPAD_SEPARATOR"] = 110] = "NUMPAD_SEPARATOR";
        KeyCode[KeyCode["NumpadSubtract"] = 111] = "NumpadSubtract";
        KeyCode[KeyCode["NumpadDecimal"] = 112] = "NumpadDecimal";
        KeyCode[KeyCode["NumpadDivide"] = 113] = "NumpadDivide";
        /**
         * Cover all key codes when IME is processing input.
         */
        KeyCode[KeyCode["KEY_IN_COMPOSITION"] = 114] = "KEY_IN_COMPOSITION";
        KeyCode[KeyCode["ABNT_C1"] = 115] = "ABNT_C1";
        KeyCode[KeyCode["ABNT_C2"] = 116] = "ABNT_C2";
        KeyCode[KeyCode["AudioVolumeMute"] = 117] = "AudioVolumeMute";
        KeyCode[KeyCode["AudioVolumeUp"] = 118] = "AudioVolumeUp";
        KeyCode[KeyCode["AudioVolumeDown"] = 119] = "AudioVolumeDown";
        KeyCode[KeyCode["BrowserSearch"] = 120] = "BrowserSearch";
        KeyCode[KeyCode["BrowserHome"] = 121] = "BrowserHome";
        KeyCode[KeyCode["BrowserBack"] = 122] = "BrowserBack";
        KeyCode[KeyCode["BrowserForward"] = 123] = "BrowserForward";
        KeyCode[KeyCode["MediaTrackNext"] = 124] = "MediaTrackNext";
        KeyCode[KeyCode["MediaTrackPrevious"] = 125] = "MediaTrackPrevious";
        KeyCode[KeyCode["MediaStop"] = 126] = "MediaStop";
        KeyCode[KeyCode["MediaPlayPause"] = 127] = "MediaPlayPause";
        KeyCode[KeyCode["LaunchMediaPlayer"] = 128] = "LaunchMediaPlayer";
        KeyCode[KeyCode["LaunchMail"] = 129] = "LaunchMail";
        KeyCode[KeyCode["LaunchApp2"] = 130] = "LaunchApp2";
        /**
         * VK_CLEAR, 0x0C, CLEAR key
         */
        KeyCode[KeyCode["Clear"] = 131] = "Clear";
        /**
         * Placed last to cover the length of the enum.
         * Please do not depend on this value!
         */
        KeyCode[KeyCode["MAX_VALUE"] = 132] = "MAX_VALUE";
    })(KeyCode || (exports.KeyCode = KeyCode = {}));
    var MarkerSeverity;
    (function (MarkerSeverity) {
        MarkerSeverity[MarkerSeverity["Hint"] = 1] = "Hint";
        MarkerSeverity[MarkerSeverity["Info"] = 2] = "Info";
        MarkerSeverity[MarkerSeverity["Warning"] = 4] = "Warning";
        MarkerSeverity[MarkerSeverity["Error"] = 8] = "Error";
    })(MarkerSeverity || (exports.MarkerSeverity = MarkerSeverity = {}));
    var MarkerTag;
    (function (MarkerTag) {
        MarkerTag[MarkerTag["Unnecessary"] = 1] = "Unnecessary";
        MarkerTag[MarkerTag["Deprecated"] = 2] = "Deprecated";
    })(MarkerTag || (exports.MarkerTag = MarkerTag = {}));
    /**
     * Position in the minimap to render the decoration.
     */
    var MinimapPosition;
    (function (MinimapPosition) {
        MinimapPosition[MinimapPosition["Inline"] = 1] = "Inline";
        MinimapPosition[MinimapPosition["Gutter"] = 2] = "Gutter";
    })(MinimapPosition || (exports.MinimapPosition = MinimapPosition = {}));
    /**
     * Section header style.
     */
    var MinimapSectionHeaderStyle;
    (function (MinimapSectionHeaderStyle) {
        MinimapSectionHeaderStyle[MinimapSectionHeaderStyle["Normal"] = 1] = "Normal";
        MinimapSectionHeaderStyle[MinimapSectionHeaderStyle["Underlined"] = 2] = "Underlined";
    })(MinimapSectionHeaderStyle || (exports.MinimapSectionHeaderStyle = MinimapSectionHeaderStyle = {}));
    /**
     * Type of hit element with the mouse in the editor.
     */
    var MouseTargetType;
    (function (MouseTargetType) {
        /**
         * Mouse is on top of an unknown element.
         */
        MouseTargetType[MouseTargetType["UNKNOWN"] = 0] = "UNKNOWN";
        /**
         * Mouse is on top of the textarea used for input.
         */
        MouseTargetType[MouseTargetType["TEXTAREA"] = 1] = "TEXTAREA";
        /**
         * Mouse is on top of the glyph margin
         */
        MouseTargetType[MouseTargetType["GUTTER_GLYPH_MARGIN"] = 2] = "GUTTER_GLYPH_MARGIN";
        /**
         * Mouse is on top of the line numbers
         */
        MouseTargetType[MouseTargetType["GUTTER_LINE_NUMBERS"] = 3] = "GUTTER_LINE_NUMBERS";
        /**
         * Mouse is on top of the line decorations
         */
        MouseTargetType[MouseTargetType["GUTTER_LINE_DECORATIONS"] = 4] = "GUTTER_LINE_DECORATIONS";
        /**
         * Mouse is on top of the whitespace left in the gutter by a view zone.
         */
        MouseTargetType[MouseTargetType["GUTTER_VIEW_ZONE"] = 5] = "GUTTER_VIEW_ZONE";
        /**
         * Mouse is on top of text in the content.
         */
        MouseTargetType[MouseTargetType["CONTENT_TEXT"] = 6] = "CONTENT_TEXT";
        /**
         * Mouse is on top of empty space in the content (e.g. after line text or below last line)
         */
        MouseTargetType[MouseTargetType["CONTENT_EMPTY"] = 7] = "CONTENT_EMPTY";
        /**
         * Mouse is on top of a view zone in the content.
         */
        MouseTargetType[MouseTargetType["CONTENT_VIEW_ZONE"] = 8] = "CONTENT_VIEW_ZONE";
        /**
         * Mouse is on top of a content widget.
         */
        MouseTargetType[MouseTargetType["CONTENT_WIDGET"] = 9] = "CONTENT_WIDGET";
        /**
         * Mouse is on top of the decorations overview ruler.
         */
        MouseTargetType[MouseTargetType["OVERVIEW_RULER"] = 10] = "OVERVIEW_RULER";
        /**
         * Mouse is on top of a scrollbar.
         */
        MouseTargetType[MouseTargetType["SCROLLBAR"] = 11] = "SCROLLBAR";
        /**
         * Mouse is on top of an overlay widget.
         */
        MouseTargetType[MouseTargetType["OVERLAY_WIDGET"] = 12] = "OVERLAY_WIDGET";
        /**
         * Mouse is outside of the editor.
         */
        MouseTargetType[MouseTargetType["OUTSIDE_EDITOR"] = 13] = "OUTSIDE_EDITOR";
    })(MouseTargetType || (exports.MouseTargetType = MouseTargetType = {}));
    var NewSymbolNameTag;
    (function (NewSymbolNameTag) {
        NewSymbolNameTag[NewSymbolNameTag["AIGenerated"] = 1] = "AIGenerated";
    })(NewSymbolNameTag || (exports.NewSymbolNameTag = NewSymbolNameTag = {}));
    var NewSymbolNameTriggerKind;
    (function (NewSymbolNameTriggerKind) {
        NewSymbolNameTriggerKind[NewSymbolNameTriggerKind["Invoke"] = 0] = "Invoke";
        NewSymbolNameTriggerKind[NewSymbolNameTriggerKind["Automatic"] = 1] = "Automatic";
    })(NewSymbolNameTriggerKind || (exports.NewSymbolNameTriggerKind = NewSymbolNameTriggerKind = {}));
    /**
     * A positioning preference for rendering overlay widgets.
     */
    var OverlayWidgetPositionPreference;
    (function (OverlayWidgetPositionPreference) {
        /**
         * Position the overlay widget in the top right corner
         */
        OverlayWidgetPositionPreference[OverlayWidgetPositionPreference["TOP_RIGHT_CORNER"] = 0] = "TOP_RIGHT_CORNER";
        /**
         * Position the overlay widget in the bottom right corner
         */
        OverlayWidgetPositionPreference[OverlayWidgetPositionPreference["BOTTOM_RIGHT_CORNER"] = 1] = "BOTTOM_RIGHT_CORNER";
        /**
         * Position the overlay widget in the top center
         */
        OverlayWidgetPositionPreference[OverlayWidgetPositionPreference["TOP_CENTER"] = 2] = "TOP_CENTER";
    })(OverlayWidgetPositionPreference || (exports.OverlayWidgetPositionPreference = OverlayWidgetPositionPreference = {}));
    /**
     * Vertical Lane in the overview ruler of the editor.
     */
    var OverviewRulerLane;
    (function (OverviewRulerLane) {
        OverviewRulerLane[OverviewRulerLane["Left"] = 1] = "Left";
        OverviewRulerLane[OverviewRulerLane["Center"] = 2] = "Center";
        OverviewRulerLane[OverviewRulerLane["Right"] = 4] = "Right";
        OverviewRulerLane[OverviewRulerLane["Full"] = 7] = "Full";
    })(OverviewRulerLane || (exports.OverviewRulerLane = OverviewRulerLane = {}));
    /**
     * How a partial acceptance was triggered.
     */
    var PartialAcceptTriggerKind;
    (function (PartialAcceptTriggerKind) {
        PartialAcceptTriggerKind[PartialAcceptTriggerKind["Word"] = 0] = "Word";
        PartialAcceptTriggerKind[PartialAcceptTriggerKind["Line"] = 1] = "Line";
        PartialAcceptTriggerKind[PartialAcceptTriggerKind["Suggest"] = 2] = "Suggest";
    })(PartialAcceptTriggerKind || (exports.PartialAcceptTriggerKind = PartialAcceptTriggerKind = {}));
    var PositionAffinity;
    (function (PositionAffinity) {
        /**
         * Prefers the left most position.
        */
        PositionAffinity[PositionAffinity["Left"] = 0] = "Left";
        /**
         * Prefers the right most position.
        */
        PositionAffinity[PositionAffinity["Right"] = 1] = "Right";
        /**
         * No preference.
        */
        PositionAffinity[PositionAffinity["None"] = 2] = "None";
        /**
         * If the given position is on injected text, prefers the position left of it.
        */
        PositionAffinity[PositionAffinity["LeftOfInjectedText"] = 3] = "LeftOfInjectedText";
        /**
         * If the given position is on injected text, prefers the position right of it.
        */
        PositionAffinity[PositionAffinity["RightOfInjectedText"] = 4] = "RightOfInjectedText";
    })(PositionAffinity || (exports.PositionAffinity = PositionAffinity = {}));
    var RenderLineNumbersType;
    (function (RenderLineNumbersType) {
        RenderLineNumbersType[RenderLineNumbersType["Off"] = 0] = "Off";
        RenderLineNumbersType[RenderLineNumbersType["On"] = 1] = "On";
        RenderLineNumbersType[RenderLineNumbersType["Relative"] = 2] = "Relative";
        RenderLineNumbersType[RenderLineNumbersType["Interval"] = 3] = "Interval";
        RenderLineNumbersType[RenderLineNumbersType["Custom"] = 4] = "Custom";
    })(RenderLineNumbersType || (exports.RenderLineNumbersType = RenderLineNumbersType = {}));
    var RenderMinimap;
    (function (RenderMinimap) {
        RenderMinimap[RenderMinimap["None"] = 0] = "None";
        RenderMinimap[RenderMinimap["Text"] = 1] = "Text";
        RenderMinimap[RenderMinimap["Blocks"] = 2] = "Blocks";
    })(RenderMinimap || (exports.RenderMinimap = RenderMinimap = {}));
    var ScrollType;
    (function (ScrollType) {
        ScrollType[ScrollType["Smooth"] = 0] = "Smooth";
        ScrollType[ScrollType["Immediate"] = 1] = "Immediate";
    })(ScrollType || (exports.ScrollType = ScrollType = {}));
    var ScrollbarVisibility;
    (function (ScrollbarVisibility) {
        ScrollbarVisibility[ScrollbarVisibility["Auto"] = 1] = "Auto";
        ScrollbarVisibility[ScrollbarVisibility["Hidden"] = 2] = "Hidden";
        ScrollbarVisibility[ScrollbarVisibility["Visible"] = 3] = "Visible";
    })(ScrollbarVisibility || (exports.ScrollbarVisibility = ScrollbarVisibility = {}));
    /**
     * The direction of a selection.
     */
    var SelectionDirection;
    (function (SelectionDirection) {
        /**
         * The selection starts above where it ends.
         */
        SelectionDirection[SelectionDirection["LTR"] = 0] = "LTR";
        /**
         * The selection starts below where it ends.
         */
        SelectionDirection[SelectionDirection["RTL"] = 1] = "RTL";
    })(SelectionDirection || (exports.SelectionDirection = SelectionDirection = {}));
    var ShowLightbulbIconMode;
    (function (ShowLightbulbIconMode) {
        ShowLightbulbIconMode["Off"] = "off";
        ShowLightbulbIconMode["OnCode"] = "onCode";
        ShowLightbulbIconMode["On"] = "on";
    })(ShowLightbulbIconMode || (exports.ShowLightbulbIconMode = ShowLightbulbIconMode = {}));
    var SignatureHelpTriggerKind;
    (function (SignatureHelpTriggerKind) {
        SignatureHelpTriggerKind[SignatureHelpTriggerKind["Invoke"] = 1] = "Invoke";
        SignatureHelpTriggerKind[SignatureHelpTriggerKind["TriggerCharacter"] = 2] = "TriggerCharacter";
        SignatureHelpTriggerKind[SignatureHelpTriggerKind["ContentChange"] = 3] = "ContentChange";
    })(SignatureHelpTriggerKind || (exports.SignatureHelpTriggerKind = SignatureHelpTriggerKind = {}));
    /**
     * A symbol kind.
     */
    var SymbolKind;
    (function (SymbolKind) {
        SymbolKind[SymbolKind["File"] = 0] = "File";
        SymbolKind[SymbolKind["Module"] = 1] = "Module";
        SymbolKind[SymbolKind["Namespace"] = 2] = "Namespace";
        SymbolKind[SymbolKind["Package"] = 3] = "Package";
        SymbolKind[SymbolKind["Class"] = 4] = "Class";
        SymbolKind[SymbolKind["Method"] = 5] = "Method";
        SymbolKind[SymbolKind["Property"] = 6] = "Property";
        SymbolKind[SymbolKind["Field"] = 7] = "Field";
        SymbolKind[SymbolKind["Constructor"] = 8] = "Constructor";
        SymbolKind[SymbolKind["Enum"] = 9] = "Enum";
        SymbolKind[SymbolKind["Interface"] = 10] = "Interface";
        SymbolKind[SymbolKind["Function"] = 11] = "Function";
        SymbolKind[SymbolKind["Variable"] = 12] = "Variable";
        SymbolKind[SymbolKind["Constant"] = 13] = "Constant";
        SymbolKind[SymbolKind["String"] = 14] = "String";
        SymbolKind[SymbolKind["Number"] = 15] = "Number";
        SymbolKind[SymbolKind["Boolean"] = 16] = "Boolean";
        SymbolKind[SymbolKind["Array"] = 17] = "Array";
        SymbolKind[SymbolKind["Object"] = 18] = "Object";
        SymbolKind[SymbolKind["Key"] = 19] = "Key";
        SymbolKind[SymbolKind["Null"] = 20] = "Null";
        SymbolKind[SymbolKind["EnumMember"] = 21] = "EnumMember";
        SymbolKind[SymbolKind["Struct"] = 22] = "Struct";
        SymbolKind[SymbolKind["Event"] = 23] = "Event";
        SymbolKind[SymbolKind["Operator"] = 24] = "Operator";
        SymbolKind[SymbolKind["TypeParameter"] = 25] = "TypeParameter";
    })(SymbolKind || (exports.SymbolKind = SymbolKind = {}));
    var SymbolTag;
    (function (SymbolTag) {
        SymbolTag[SymbolTag["Deprecated"] = 1] = "Deprecated";
    })(SymbolTag || (exports.SymbolTag = SymbolTag = {}));
    /**
     * The kind of animation in which the editor's cursor should be rendered.
     */
    var TextEditorCursorBlinkingStyle;
    (function (TextEditorCursorBlinkingStyle) {
        /**
         * Hidden
         */
        TextEditorCursorBlinkingStyle[TextEditorCursorBlinkingStyle["Hidden"] = 0] = "Hidden";
        /**
         * Blinking
         */
        TextEditorCursorBlinkingStyle[TextEditorCursorBlinkingStyle["Blink"] = 1] = "Blink";
        /**
         * Blinking with smooth fading
         */
        TextEditorCursorBlinkingStyle[TextEditorCursorBlinkingStyle["Smooth"] = 2] = "Smooth";
        /**
         * Blinking with prolonged filled state and smooth fading
         */
        TextEditorCursorBlinkingStyle[TextEditorCursorBlinkingStyle["Phase"] = 3] = "Phase";
        /**
         * Expand collapse animation on the y axis
         */
        TextEditorCursorBlinkingStyle[TextEditorCursorBlinkingStyle["Expand"] = 4] = "Expand";
        /**
         * No-Blinking
         */
        TextEditorCursorBlinkingStyle[TextEditorCursorBlinkingStyle["Solid"] = 5] = "Solid";
    })(TextEditorCursorBlinkingStyle || (exports.TextEditorCursorBlinkingStyle = TextEditorCursorBlinkingStyle = {}));
    /**
     * The style in which the editor's cursor should be rendered.
     */
    var TextEditorCursorStyle;
    (function (TextEditorCursorStyle) {
        /**
         * As a vertical line (sitting between two characters).
         */
        TextEditorCursorStyle[TextEditorCursorStyle["Line"] = 1] = "Line";
        /**
         * As a block (sitting on top of a character).
         */
        TextEditorCursorStyle[TextEditorCursorStyle["Block"] = 2] = "Block";
        /**
         * As a horizontal line (sitting under a character).
         */
        TextEditorCursorStyle[TextEditorCursorStyle["Underline"] = 3] = "Underline";
        /**
         * As a thin vertical line (sitting between two characters).
         */
        TextEditorCursorStyle[TextEditorCursorStyle["LineThin"] = 4] = "LineThin";
        /**
         * As an outlined block (sitting on top of a character).
         */
        TextEditorCursorStyle[TextEditorCursorStyle["BlockOutline"] = 5] = "BlockOutline";
        /**
         * As a thin horizontal line (sitting under a character).
         */
        TextEditorCursorStyle[TextEditorCursorStyle["UnderlineThin"] = 6] = "UnderlineThin";
    })(TextEditorCursorStyle || (exports.TextEditorCursorStyle = TextEditorCursorStyle = {}));
    /**
     * Describes the behavior of decorations when typing/editing near their edges.
     * Note: Please do not edit the values, as they very carefully match `DecorationRangeBehavior`
     */
    var TrackedRangeStickiness;
    (function (TrackedRangeStickiness) {
        TrackedRangeStickiness[TrackedRangeStickiness["AlwaysGrowsWhenTypingAtEdges"] = 0] = "AlwaysGrowsWhenTypingAtEdges";
        TrackedRangeStickiness[TrackedRangeStickiness["NeverGrowsWhenTypingAtEdges"] = 1] = "NeverGrowsWhenTypingAtEdges";
        TrackedRangeStickiness[TrackedRangeStickiness["GrowsOnlyWhenTypingBefore"] = 2] = "GrowsOnlyWhenTypingBefore";
        TrackedRangeStickiness[TrackedRangeStickiness["GrowsOnlyWhenTypingAfter"] = 3] = "GrowsOnlyWhenTypingAfter";
    })(TrackedRangeStickiness || (exports.TrackedRangeStickiness = TrackedRangeStickiness = {}));
    /**
     * Describes how to indent wrapped lines.
     */
    var WrappingIndent;
    (function (WrappingIndent) {
        /**
         * No indentation => wrapped lines begin at column 1.
         */
        WrappingIndent[WrappingIndent["None"] = 0] = "None";
        /**
         * Same => wrapped lines get the same indentation as the parent.
         */
        WrappingIndent[WrappingIndent["Same"] = 1] = "Same";
        /**
         * Indent => wrapped lines get +1 indentation toward the parent.
         */
        WrappingIndent[WrappingIndent["Indent"] = 2] = "Indent";
        /**
         * DeepIndent => wrapped lines get +2 indentation toward the parent.
         */
        WrappingIndent[WrappingIndent["DeepIndent"] = 3] = "DeepIndent";
    })(WrappingIndent || (exports.WrappingIndent = WrappingIndent = {}));
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[583/*vs/editor/common/textModelBracketPairs*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.BracketPairWithMinIndentationInfo = exports.BracketPairInfo = exports.BracketInfo = void 0;
    class BracketInfo {
        constructor(range, 
        /** 0-based level */
        nestingLevel, nestingLevelOfEqualBracketType, isInvalid) {
            this.range = range;
            this.nestingLevel = nestingLevel;
            this.nestingLevelOfEqualBracketType = nestingLevelOfEqualBracketType;
            this.isInvalid = isInvalid;
        }
    }
    exports.BracketInfo = BracketInfo;
    class BracketPairInfo {
        constructor(range, openingBracketRange, closingBracketRange, 
        /** 0-based */
        nestingLevel, nestingLevelOfEqualBracketType, bracketPairNode) {
            this.range = range;
            this.openingBracketRange = openingBracketRange;
            this.closingBracketRange = closingBracketRange;
            this.nestingLevel = nestingLevel;
            this.nestingLevelOfEqualBracketType = nestingLevelOfEqualBracketType;
            this.bracketPairNode = bracketPairNode;
        }
        get openingBracketInfo() {
            return this.bracketPairNode.openingBracket.bracketInfo;
        }
    }
    exports.BracketPairInfo = BracketPairInfo;
    class BracketPairWithMinIndentationInfo extends BracketPairInfo {
        constructor(range, openingBracketRange, closingBracketRange, 
        /**
         * 0-based
        */
        nestingLevel, nestingLevelOfEqualBracketType, bracketPairNode, 
        /**
         * -1 if not requested, otherwise the size of the minimum indentation in the bracket pair in terms of visible columns.
        */
        minVisibleColumnIndentation) {
            super(range, openingBracketRange, closingBracketRange, nestingLevel, nestingLevelOfEqualBracketType, bracketPairNode);
            this.minVisibleColumnIndentation = minVisibleColumnIndentation;
        }
    }
    exports.BracketPairWithMinIndentationInfo = BracketPairWithMinIndentationInfo;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[584/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/bracketPairsTree*/], __M([1/*require*/,0/*exports*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,583/*vs/editor/common/textModelBracketPairs*/,200/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/beforeEditPositionMapper*/,321/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/brackets*/,106/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/length*/,320/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/parser*/,149/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/smallImmutableSet*/,236/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/tokenizer*/,13/*vs/base/common/arrays*/,319/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/combineTextEditInfos*/]), function (require, exports, event_1, lifecycle_1, textModelBracketPairs_1, beforeEditPositionMapper_1, brackets_1, length_1, parser_1, smallImmutableSet_1, tokenizer_1, arrays_1, combineTextEditInfos_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.BracketPairsTree = void 0;
    class BracketPairsTree extends lifecycle_1.Disposable {
        didLanguageChange(languageId) {
            return this.brackets.didLanguageChange(languageId);
        }
        constructor(textModel, getLanguageConfiguration) {
            super();
            this.textModel = textModel;
            this.getLanguageConfiguration = getLanguageConfiguration;
            this.didChangeEmitter = new event_1.Emitter();
            this.denseKeyProvider = new smallImmutableSet_1.DenseKeyProvider();
            this.brackets = new brackets_1.LanguageAgnosticBracketTokens(this.denseKeyProvider, this.getLanguageConfiguration);
            this.onDidChange = this.didChangeEmitter.event;
            this.queuedTextEditsForInitialAstWithoutTokens = [];
            this.queuedTextEdits = [];
            if (!textModel.tokenization.hasTokens) {
                const brackets = this.brackets.getSingleLanguageBracketTokens(this.textModel.getLanguageId());
                const tokenizer = new tokenizer_1.FastTokenizer(this.textModel.getValue(), brackets);
                this.initialAstWithoutTokens = (0, parser_1.parseDocument)(tokenizer, [], undefined, true);
                this.astWithTokens = this.initialAstWithoutTokens;
            }
            else if (textModel.tokenization.backgroundTokenizationState === 2 /* BackgroundTokenizationState.Completed */) {
                // Skip the initial ast, as there is no flickering.
                // Directly create the tree with token information.
                this.initialAstWithoutTokens = undefined;
                this.astWithTokens = this.parseDocumentFromTextBuffer([], undefined, false);
            }
            else {
                // We missed some token changes already, so we cannot use the fast tokenizer + delta increments
                this.initialAstWithoutTokens = this.parseDocumentFromTextBuffer([], undefined, true);
                this.astWithTokens = this.initialAstWithoutTokens;
            }
        }
        //#region TextModel events
        handleDidChangeBackgroundTokenizationState() {
            if (this.textModel.tokenization.backgroundTokenizationState === 2 /* BackgroundTokenizationState.Completed */) {
                const wasUndefined = this.initialAstWithoutTokens === undefined;
                // Clear the initial tree as we can use the tree with token information now.
                this.initialAstWithoutTokens = undefined;
                if (!wasUndefined) {
                    this.didChangeEmitter.fire();
                }
            }
        }
        handleDidChangeTokens({ ranges }) {
            const edits = ranges.map(r => new beforeEditPositionMapper_1.TextEditInfo((0, length_1.toLength)(r.fromLineNumber - 1, 0), (0, length_1.toLength)(r.toLineNumber, 0), (0, length_1.toLength)(r.toLineNumber - r.fromLineNumber + 1, 0)));
            this.handleEdits(edits, true);
            if (!this.initialAstWithoutTokens) {
                this.didChangeEmitter.fire();
            }
        }
        handleContentChanged(change) {
            const edits = beforeEditPositionMapper_1.TextEditInfo.fromModelContentChanges(change.changes);
            this.handleEdits(edits, false);
        }
        handleEdits(edits, tokenChange) {
            // Lazily queue the edits and only apply them when the tree is accessed.
            const result = (0, combineTextEditInfos_1.combineTextEditInfos)(this.queuedTextEdits, edits);
            this.queuedTextEdits = result;
            if (this.initialAstWithoutTokens && !tokenChange) {
                this.queuedTextEditsForInitialAstWithoutTokens = (0, combineTextEditInfos_1.combineTextEditInfos)(this.queuedTextEditsForInitialAstWithoutTokens, edits);
            }
        }
        //#endregion
        flushQueue() {
            if (this.queuedTextEdits.length > 0) {
                this.astWithTokens = this.parseDocumentFromTextBuffer(this.queuedTextEdits, this.astWithTokens, false);
                this.queuedTextEdits = [];
            }
            if (this.queuedTextEditsForInitialAstWithoutTokens.length > 0) {
                if (this.initialAstWithoutTokens) {
                    this.initialAstWithoutTokens = this.parseDocumentFromTextBuffer(this.queuedTextEditsForInitialAstWithoutTokens, this.initialAstWithoutTokens, false);
                }
                this.queuedTextEditsForInitialAstWithoutTokens = [];
            }
        }
        /**
         * @pure (only if isPure = true)
        */
        parseDocumentFromTextBuffer(edits, previousAst, immutable) {
            // Is much faster if `isPure = false`.
            const isPure = false;
            const previousAstClone = isPure ? previousAst?.deepClone() : previousAst;
            const tokenizer = new tokenizer_1.TextBufferTokenizer(this.textModel, this.brackets);
            const result = (0, parser_1.parseDocument)(tokenizer, edits, previousAstClone, immutable);
            return result;
        }
        getBracketsInRange(range, onlyColorizedBrackets) {
            this.flushQueue();
            const startOffset = (0, length_1.toLength)(range.startLineNumber - 1, range.startColumn - 1);
            const endOffset = (0, length_1.toLength)(range.endLineNumber - 1, range.endColumn - 1);
            return new arrays_1.CallbackIterable(cb => {
                const node = this.initialAstWithoutTokens || this.astWithTokens;
                collectBrackets(node, length_1.lengthZero, node.length, startOffset, endOffset, cb, 0, 0, new Map(), onlyColorizedBrackets);
            });
        }
        getBracketPairsInRange(range, includeMinIndentation) {
            this.flushQueue();
            const startLength = (0, length_1.positionToLength)(range.getStartPosition());
            const endLength = (0, length_1.positionToLength)(range.getEndPosition());
            return new arrays_1.CallbackIterable(cb => {
                const node = this.initialAstWithoutTokens || this.astWithTokens;
                const context = new CollectBracketPairsContext(cb, includeMinIndentation, this.textModel);
                collectBracketPairs(node, length_1.lengthZero, node.length, startLength, endLength, context, 0, new Map());
            });
        }
        getFirstBracketAfter(position) {
            this.flushQueue();
            const node = this.initialAstWithoutTokens || this.astWithTokens;
            return getFirstBracketAfter(node, length_1.lengthZero, node.length, (0, length_1.positionToLength)(position));
        }
        getFirstBracketBefore(position) {
            this.flushQueue();
            const node = this.initialAstWithoutTokens || this.astWithTokens;
            return getFirstBracketBefore(node, length_1.lengthZero, node.length, (0, length_1.positionToLength)(position));
        }
    }
    exports.BracketPairsTree = BracketPairsTree;
    function getFirstBracketBefore(node, nodeOffsetStart, nodeOffsetEnd, position) {
        if (node.kind === 4 /* AstNodeKind.List */ || node.kind === 2 /* AstNodeKind.Pair */) {
            const lengths = [];
            for (const child of node.children) {
                nodeOffsetEnd = (0, length_1.lengthAdd)(nodeOffsetStart, child.length);
                lengths.push({ nodeOffsetStart, nodeOffsetEnd });
                nodeOffsetStart = nodeOffsetEnd;
            }
            for (let i = lengths.length - 1; i >= 0; i--) {
                const { nodeOffsetStart, nodeOffsetEnd } = lengths[i];
                if ((0, length_1.lengthLessThan)(nodeOffsetStart, position)) {
                    const result = getFirstBracketBefore(node.children[i], nodeOffsetStart, nodeOffsetEnd, position);
                    if (result) {
                        return result;
                    }
                }
            }
            return null;
        }
        else if (node.kind === 3 /* AstNodeKind.UnexpectedClosingBracket */) {
            return null;
        }
        else if (node.kind === 1 /* AstNodeKind.Bracket */) {
            const range = (0, length_1.lengthsToRange)(nodeOffsetStart, nodeOffsetEnd);
            return {
                bracketInfo: node.bracketInfo,
                range
            };
        }
        return null;
    }
    function getFirstBracketAfter(node, nodeOffsetStart, nodeOffsetEnd, position) {
        if (node.kind === 4 /* AstNodeKind.List */ || node.kind === 2 /* AstNodeKind.Pair */) {
            for (const child of node.children) {
                nodeOffsetEnd = (0, length_1.lengthAdd)(nodeOffsetStart, child.length);
                if ((0, length_1.lengthLessThan)(position, nodeOffsetEnd)) {
                    const result = getFirstBracketAfter(child, nodeOffsetStart, nodeOffsetEnd, position);
                    if (result) {
                        return result;
                    }
                }
                nodeOffsetStart = nodeOffsetEnd;
            }
            return null;
        }
        else if (node.kind === 3 /* AstNodeKind.UnexpectedClosingBracket */) {
            return null;
        }
        else if (node.kind === 1 /* AstNodeKind.Bracket */) {
            const range = (0, length_1.lengthsToRange)(nodeOffsetStart, nodeOffsetEnd);
            return {
                bracketInfo: node.bracketInfo,
                range
            };
        }
        return null;
    }
    function collectBrackets(node, nodeOffsetStart, nodeOffsetEnd, startOffset, endOffset, push, level, nestingLevelOfEqualBracketType, levelPerBracketType, onlyColorizedBrackets, parentPairIsIncomplete = false) {
        if (level > 200) {
            return true;
        }
        whileLoop: while (true) {
            switch (node.kind) {
                case 4 /* AstNodeKind.List */: {
                    const childCount = node.childrenLength;
                    for (let i = 0; i < childCount; i++) {
                        const child = node.getChild(i);
                        if (!child) {
                            continue;
                        }
                        nodeOffsetEnd = (0, length_1.lengthAdd)(nodeOffsetStart, child.length);
                        if ((0, length_1.lengthLessThanEqual)(nodeOffsetStart, endOffset) &&
                            (0, length_1.lengthGreaterThanEqual)(nodeOffsetEnd, startOffset)) {
                            const childEndsAfterEnd = (0, length_1.lengthGreaterThanEqual)(nodeOffsetEnd, endOffset);
                            if (childEndsAfterEnd) {
                                // No child after this child in the requested window, don't recurse
                                node = child;
                                continue whileLoop;
                            }
                            const shouldContinue = collectBrackets(child, nodeOffsetStart, nodeOffsetEnd, startOffset, endOffset, push, level, 0, levelPerBracketType, onlyColorizedBrackets);
                            if (!shouldContinue) {
                                return false;
                            }
                        }
                        nodeOffsetStart = nodeOffsetEnd;
                    }
                    return true;
                }
                case 2 /* AstNodeKind.Pair */: {
                    const colorize = !onlyColorizedBrackets || !node.closingBracket || node.closingBracket.bracketInfo.closesColorized(node.openingBracket.bracketInfo);
                    let levelPerBracket = 0;
                    if (levelPerBracketType) {
                        let existing = levelPerBracketType.get(node.openingBracket.text);
                        if (existing === undefined) {
                            existing = 0;
                        }
                        levelPerBracket = existing;
                        if (colorize) {
                            existing++;
                            levelPerBracketType.set(node.openingBracket.text, existing);
                        }
                    }
                    const childCount = node.childrenLength;
                    for (let i = 0; i < childCount; i++) {
                        const child = node.getChild(i);
                        if (!child) {
                            continue;
                        }
                        nodeOffsetEnd = (0, length_1.lengthAdd)(nodeOffsetStart, child.length);
                        if ((0, length_1.lengthLessThanEqual)(nodeOffsetStart, endOffset) &&
                            (0, length_1.lengthGreaterThanEqual)(nodeOffsetEnd, startOffset)) {
                            const childEndsAfterEnd = (0, length_1.lengthGreaterThanEqual)(nodeOffsetEnd, endOffset);
                            if (childEndsAfterEnd && child.kind !== 1 /* AstNodeKind.Bracket */) {
                                // No child after this child in the requested window, don't recurse
                                // Don't do this for brackets because of unclosed/unopened brackets
                                node = child;
                                if (colorize) {
                                    level++;
                                    nestingLevelOfEqualBracketType = levelPerBracket + 1;
                                }
                                else {
                                    nestingLevelOfEqualBracketType = levelPerBracket;
                                }
                                continue whileLoop;
                            }
                            if (colorize || child.kind !== 1 /* AstNodeKind.Bracket */ || !node.closingBracket) {
                                const shouldContinue = collectBrackets(child, nodeOffsetStart, nodeOffsetEnd, startOffset, endOffset, push, colorize ? level + 1 : level, colorize ? levelPerBracket + 1 : levelPerBracket, levelPerBracketType, onlyColorizedBrackets, !node.closingBracket);
                                if (!shouldContinue) {
                                    return false;
                                }
                            }
                        }
                        nodeOffsetStart = nodeOffsetEnd;
                    }
                    levelPerBracketType?.set(node.openingBracket.text, levelPerBracket);
                    return true;
                }
                case 3 /* AstNodeKind.UnexpectedClosingBracket */: {
                    const range = (0, length_1.lengthsToRange)(nodeOffsetStart, nodeOffsetEnd);
                    return push(new textModelBracketPairs_1.BracketInfo(range, level - 1, 0, true));
                }
                case 1 /* AstNodeKind.Bracket */: {
                    const range = (0, length_1.lengthsToRange)(nodeOffsetStart, nodeOffsetEnd);
                    return push(new textModelBracketPairs_1.BracketInfo(range, level - 1, nestingLevelOfEqualBracketType - 1, parentPairIsIncomplete));
                }
                case 0 /* AstNodeKind.Text */:
                    return true;
            }
        }
    }
    class CollectBracketPairsContext {
        constructor(push, includeMinIndentation, textModel) {
            this.push = push;
            this.includeMinIndentation = includeMinIndentation;
            this.textModel = textModel;
        }
    }
    function collectBracketPairs(node, nodeOffsetStart, nodeOffsetEnd, startOffset, endOffset, context, level, levelPerBracketType) {
        if (level > 200) {
            return true;
        }
        let shouldContinue = true;
        if (node.kind === 2 /* AstNodeKind.Pair */) {
            let levelPerBracket = 0;
            if (levelPerBracketType) {
                let existing = levelPerBracketType.get(node.openingBracket.text);
                if (existing === undefined) {
                    existing = 0;
                }
                levelPerBracket = existing;
                existing++;
                levelPerBracketType.set(node.openingBracket.text, existing);
            }
            const openingBracketEnd = (0, length_1.lengthAdd)(nodeOffsetStart, node.openingBracket.length);
            let minIndentation = -1;
            if (context.includeMinIndentation) {
                minIndentation = node.computeMinIndentation(nodeOffsetStart, context.textModel);
            }
            shouldContinue = context.push(new textModelBracketPairs_1.BracketPairWithMinIndentationInfo((0, length_1.lengthsToRange)(nodeOffsetStart, nodeOffsetEnd), (0, length_1.lengthsToRange)(nodeOffsetStart, openingBracketEnd), node.closingBracket
                ? (0, length_1.lengthsToRange)((0, length_1.lengthAdd)(openingBracketEnd, node.child?.length || length_1.lengthZero), nodeOffsetEnd)
                : undefined, level, levelPerBracket, node, minIndentation));
            nodeOffsetStart = openingBracketEnd;
            if (shouldContinue && node.child) {
                const child = node.child;
                nodeOffsetEnd = (0, length_1.lengthAdd)(nodeOffsetStart, child.length);
                if ((0, length_1.lengthLessThanEqual)(nodeOffsetStart, endOffset) &&
                    (0, length_1.lengthGreaterThanEqual)(nodeOffsetEnd, startOffset)) {
                    shouldContinue = collectBracketPairs(child, nodeOffsetStart, nodeOffsetEnd, startOffset, endOffset, context, level + 1, levelPerBracketType);
                    if (!shouldContinue) {
                        return false;
                    }
                }
            }
            levelPerBracketType?.set(node.openingBracket.text, levelPerBracket);
        }
        else {
            let curOffset = nodeOffsetStart;
            for (const child of node.children) {
                const childOffset = curOffset;
                curOffset = (0, length_1.lengthAdd)(curOffset, child.length);
                if ((0, length_1.lengthLessThanEqual)(childOffset, endOffset) &&
                    (0, length_1.lengthLessThanEqual)(startOffset, curOffset)) {
                    shouldContinue = collectBracketPairs(child, childOffset, curOffset, startOffset, endOffset, context, level, levelPerBracketType);
                    if (!shouldContinue) {
                        return false;
                    }
                }
            }
        }
        return shouldContinue;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[132/*vs/editor/common/textModelEvents*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.InternalModelContentChangeEvent = exports.ModelInjectedTextChangedEvent = exports.ModelRawContentChangedEvent = exports.ModelRawEOLChanged = exports.ModelRawLinesInserted = exports.ModelRawLinesDeleted = exports.ModelRawLineChanged = exports.LineInjectedText = exports.ModelRawFlush = void 0;
    /**
     * An event describing that a model has been reset to a new value.
     * @internal
     */
    class ModelRawFlush {
        constructor() {
            this.changeType = 1 /* RawContentChangedType.Flush */;
        }
    }
    exports.ModelRawFlush = ModelRawFlush;
    /**
     * Represents text injected on a line
     * @internal
     */
    class LineInjectedText {
        static applyInjectedText(lineText, injectedTexts) {
            if (!injectedTexts || injectedTexts.length === 0) {
                return lineText;
            }
            let result = '';
            let lastOriginalOffset = 0;
            for (const injectedText of injectedTexts) {
                result += lineText.substring(lastOriginalOffset, injectedText.column - 1);
                lastOriginalOffset = injectedText.column - 1;
                result += injectedText.options.content;
            }
            result += lineText.substring(lastOriginalOffset);
            return result;
        }
        static fromDecorations(decorations) {
            const result = [];
            for (const decoration of decorations) {
                if (decoration.options.before && decoration.options.before.content.length > 0) {
                    result.push(new LineInjectedText(decoration.ownerId, decoration.range.startLineNumber, decoration.range.startColumn, decoration.options.before, 0));
                }
                if (decoration.options.after && decoration.options.after.content.length > 0) {
                    result.push(new LineInjectedText(decoration.ownerId, decoration.range.endLineNumber, decoration.range.endColumn, decoration.options.after, 1));
                }
            }
            result.sort((a, b) => {
                if (a.lineNumber === b.lineNumber) {
                    if (a.column === b.column) {
                        return a.order - b.order;
                    }
                    return a.column - b.column;
                }
                return a.lineNumber - b.lineNumber;
            });
            return result;
        }
        constructor(ownerId, lineNumber, column, options, order) {
            this.ownerId = ownerId;
            this.lineNumber = lineNumber;
            this.column = column;
            this.options = options;
            this.order = order;
        }
    }
    exports.LineInjectedText = LineInjectedText;
    /**
     * An event describing that a line has changed in a model.
     * @internal
     */
    class ModelRawLineChanged {
        constructor(lineNumber, detail, injectedText) {
            this.changeType = 2 /* RawContentChangedType.LineChanged */;
            this.lineNumber = lineNumber;
            this.detail = detail;
            this.injectedText = injectedText;
        }
    }
    exports.ModelRawLineChanged = ModelRawLineChanged;
    /**
     * An event describing that line(s) have been deleted in a model.
     * @internal
     */
    class ModelRawLinesDeleted {
        constructor(fromLineNumber, toLineNumber) {
            this.changeType = 3 /* RawContentChangedType.LinesDeleted */;
            this.fromLineNumber = fromLineNumber;
            this.toLineNumber = toLineNumber;
        }
    }
    exports.ModelRawLinesDeleted = ModelRawLinesDeleted;
    /**
     * An event describing that line(s) have been inserted in a model.
     * @internal
     */
    class ModelRawLinesInserted {
        constructor(fromLineNumber, toLineNumber, detail, injectedTexts) {
            this.changeType = 4 /* RawContentChangedType.LinesInserted */;
            this.injectedTexts = injectedTexts;
            this.fromLineNumber = fromLineNumber;
            this.toLineNumber = toLineNumber;
            this.detail = detail;
        }
    }
    exports.ModelRawLinesInserted = ModelRawLinesInserted;
    /**
     * An event describing that a model has had its EOL changed.
     * @internal
     */
    class ModelRawEOLChanged {
        constructor() {
            this.changeType = 5 /* RawContentChangedType.EOLChanged */;
        }
    }
    exports.ModelRawEOLChanged = ModelRawEOLChanged;
    /**
     * An event describing a change in the text of a model.
     * @internal
     */
    class ModelRawContentChangedEvent {
        constructor(changes, versionId, isUndoing, isRedoing) {
            this.changes = changes;
            this.versionId = versionId;
            this.isUndoing = isUndoing;
            this.isRedoing = isRedoing;
            this.resultingSelection = null;
        }
        containsEvent(type) {
            for (let i = 0, len = this.changes.length; i < len; i++) {
                const change = this.changes[i];
                if (change.changeType === type) {
                    return true;
                }
            }
            return false;
        }
        static merge(a, b) {
            const changes = [].concat(a.changes).concat(b.changes);
            const versionId = b.versionId;
            const isUndoing = (a.isUndoing || b.isUndoing);
            const isRedoing = (a.isRedoing || b.isRedoing);
            return new ModelRawContentChangedEvent(changes, versionId, isUndoing, isRedoing);
        }
    }
    exports.ModelRawContentChangedEvent = ModelRawContentChangedEvent;
    /**
     * An event describing a change in injected text.
     * @internal
     */
    class ModelInjectedTextChangedEvent {
        constructor(changes) {
            this.changes = changes;
        }
    }
    exports.ModelInjectedTextChangedEvent = ModelInjectedTextChangedEvent;
    /**
     * @internal
     */
    class InternalModelContentChangeEvent {
        constructor(rawContentChangedEvent, contentChangedEvent) {
            this.rawContentChangedEvent = rawContentChangedEvent;
            this.contentChangedEvent = contentChangedEvent;
        }
        merge(other) {
            const rawContentChangedEvent = ModelRawContentChangedEvent.merge(this.rawContentChangedEvent, other.rawContentChangedEvent);
            const contentChangedEvent = InternalModelContentChangeEvent._mergeChangeEvents(this.contentChangedEvent, other.contentChangedEvent);
            return new InternalModelContentChangeEvent(rawContentChangedEvent, contentChangedEvent);
        }
        static _mergeChangeEvents(a, b) {
            const changes = [].concat(a.changes).concat(b.changes);
            const eol = b.eol;
            const versionId = b.versionId;
            const isUndoing = (a.isUndoing || b.isUndoing);
            const isRedoing = (a.isRedoing || b.isRedoing);
            const isFlush = (a.isFlush || b.isFlush);
            const isEolChange = a.isEolChange && b.isEolChange; // both must be true to not confuse listeners who skip such edits
            return {
                changes: changes,
                eol: eol,
                isEolChange: isEolChange,
                versionId: versionId,
                isUndoing: isUndoing,
                isRedoing: isRedoing,
                isFlush: isFlush,
            };
        }
    }
    exports.InternalModelContentChangeEvent = InternalModelContentChangeEvent;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[239/*vs/editor/common/textModelGuides*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.IndentGuideHorizontalLine = exports.IndentGuide = exports.HorizontalGuidesState = void 0;
    var HorizontalGuidesState;
    (function (HorizontalGuidesState) {
        HorizontalGuidesState[HorizontalGuidesState["Disabled"] = 0] = "Disabled";
        HorizontalGuidesState[HorizontalGuidesState["EnabledForActive"] = 1] = "EnabledForActive";
        HorizontalGuidesState[HorizontalGuidesState["Enabled"] = 2] = "Enabled";
    })(HorizontalGuidesState || (exports.HorizontalGuidesState = HorizontalGuidesState = {}));
    class IndentGuide {
        constructor(visibleColumn, column, className, 
        /**
         * If set, this indent guide is a horizontal guide (no vertical part).
         * It starts at visibleColumn and continues until endColumn.
        */
        horizontalLine, 
        /**
         * If set (!= -1), only show this guide for wrapped lines that don't contain this model column, but are after it.
        */
        forWrappedLinesAfterColumn, forWrappedLinesBeforeOrAtColumn) {
            this.visibleColumn = visibleColumn;
            this.column = column;
            this.className = className;
            this.horizontalLine = horizontalLine;
            this.forWrappedLinesAfterColumn = forWrappedLinesAfterColumn;
            this.forWrappedLinesBeforeOrAtColumn = forWrappedLinesBeforeOrAtColumn;
            if ((visibleColumn !== -1) === (column !== -1)) {
                throw new Error();
            }
        }
    }
    exports.IndentGuide = IndentGuide;
    class IndentGuideHorizontalLine {
        constructor(top, endColumn) {
            this.top = top;
            this.endColumn = endColumn;
        }
    }
    exports.IndentGuideHorizontalLine = IndentGuideHorizontalLine;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[329/*vs/editor/common/model/guidesTextModelPart*/], __M([1/*require*/,0/*exports*/,67/*vs/base/common/arraysFind*/,11/*vs/base/common/strings*/,94/*vs/editor/common/core/cursorColumns*/,4/*vs/editor/common/core/range*/,323/*vs/editor/common/model/textModelPart*/,237/*vs/editor/common/model/utils*/,239/*vs/editor/common/textModelGuides*/,8/*vs/base/common/errors*/]), function (require, exports, arraysFind_1, strings, cursorColumns_1, range_1, textModelPart_1, utils_1, textModelGuides_1, errors_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.BracketPairGuidesClassNames = exports.GuidesTextModelPart = void 0;
    class GuidesTextModelPart extends textModelPart_1.TextModelPart {
        constructor(textModel, languageConfigurationService) {
            super();
            this.textModel = textModel;
            this.languageConfigurationService = languageConfigurationService;
        }
        getLanguageConfiguration(languageId) {
            return this.languageConfigurationService.getLanguageConfiguration(languageId);
        }
        _computeIndentLevel(lineIndex) {
            return (0, utils_1.computeIndentLevel)(this.textModel.getLineContent(lineIndex + 1), this.textModel.getOptions().tabSize);
        }
        getActiveIndentGuide(lineNumber, minLineNumber, maxLineNumber) {
            this.assertNotDisposed();
            const lineCount = this.textModel.getLineCount();
            if (lineNumber < 1 || lineNumber > lineCount) {
                throw new errors_1.BugIndicatingError('Illegal value for lineNumber');
            }
            const foldingRules = this.getLanguageConfiguration(this.textModel.getLanguageId()).foldingRules;
            const offSide = Boolean(foldingRules && foldingRules.offSide);
            let up_aboveContentLineIndex = -2; /* -2 is a marker for not having computed it */
            let up_aboveContentLineIndent = -1;
            let up_belowContentLineIndex = -2; /* -2 is a marker for not having computed it */
            let up_belowContentLineIndent = -1;
            const up_resolveIndents = (lineNumber) => {
                if (up_aboveContentLineIndex !== -1 &&
                    (up_aboveContentLineIndex === -2 ||
                        up_aboveContentLineIndex > lineNumber - 1)) {
                    up_aboveContentLineIndex = -1;
                    up_aboveContentLineIndent = -1;
                    // must find previous line with content
                    for (let lineIndex = lineNumber - 2; lineIndex >= 0; lineIndex--) {
                        const indent = this._computeIndentLevel(lineIndex);
                        if (indent >= 0) {
                            up_aboveContentLineIndex = lineIndex;
                            up_aboveContentLineIndent = indent;
                            break;
                        }
                    }
                }
                if (up_belowContentLineIndex === -2) {
                    up_belowContentLineIndex = -1;
                    up_belowContentLineIndent = -1;
                    // must find next line with content
                    for (let lineIndex = lineNumber; lineIndex < lineCount; lineIndex++) {
                        const indent = this._computeIndentLevel(lineIndex);
                        if (indent >= 0) {
                            up_belowContentLineIndex = lineIndex;
                            up_belowContentLineIndent = indent;
                            break;
                        }
                    }
                }
            };
            let down_aboveContentLineIndex = -2; /* -2 is a marker for not having computed it */
            let down_aboveContentLineIndent = -1;
            let down_belowContentLineIndex = -2; /* -2 is a marker for not having computed it */
            let down_belowContentLineIndent = -1;
            const down_resolveIndents = (lineNumber) => {
                if (down_aboveContentLineIndex === -2) {
                    down_aboveContentLineIndex = -1;
                    down_aboveContentLineIndent = -1;
                    // must find previous line with content
                    for (let lineIndex = lineNumber - 2; lineIndex >= 0; lineIndex--) {
                        const indent = this._computeIndentLevel(lineIndex);
                        if (indent >= 0) {
                            down_aboveContentLineIndex = lineIndex;
                            down_aboveContentLineIndent = indent;
                            break;
                        }
                    }
                }
                if (down_belowContentLineIndex !== -1 &&
                    (down_belowContentLineIndex === -2 ||
                        down_belowContentLineIndex < lineNumber - 1)) {
                    down_belowContentLineIndex = -1;
                    down_belowContentLineIndent = -1;
                    // must find next line with content
                    for (let lineIndex = lineNumber; lineIndex < lineCount; lineIndex++) {
                        const indent = this._computeIndentLevel(lineIndex);
                        if (indent >= 0) {
                            down_belowContentLineIndex = lineIndex;
                            down_belowContentLineIndent = indent;
                            break;
                        }
                    }
                }
            };
            let startLineNumber = 0;
            let goUp = true;
            let endLineNumber = 0;
            let goDown = true;
            let indent = 0;
            let initialIndent = 0;
            for (let distance = 0; goUp || goDown; distance++) {
                const upLineNumber = lineNumber - distance;
                const downLineNumber = lineNumber + distance;
                if (distance > 1 && (upLineNumber < 1 || upLineNumber < minLineNumber)) {
                    goUp = false;
                }
                if (distance > 1 &&
                    (downLineNumber > lineCount || downLineNumber > maxLineNumber)) {
                    goDown = false;
                }
                if (distance > 50000) {
                    // stop processing
                    goUp = false;
                    goDown = false;
                }
                let upLineIndentLevel = -1;
                if (goUp && upLineNumber >= 1) {
                    // compute indent level going up
                    const currentIndent = this._computeIndentLevel(upLineNumber - 1);
                    if (currentIndent >= 0) {
                        // This line has content (besides whitespace)
                        // Use the line's indent
                        up_belowContentLineIndex = upLineNumber - 1;
                        up_belowContentLineIndent = currentIndent;
                        upLineIndentLevel = Math.ceil(currentIndent / this.textModel.getOptions().indentSize);
                    }
                    else {
                        up_resolveIndents(upLineNumber);
                        upLineIndentLevel = this._getIndentLevelForWhitespaceLine(offSide, up_aboveContentLineIndent, up_belowContentLineIndent);
                    }
                }
                let downLineIndentLevel = -1;
                if (goDown && downLineNumber <= lineCount) {
                    // compute indent level going down
                    const currentIndent = this._computeIndentLevel(downLineNumber - 1);
                    if (currentIndent >= 0) {
                        // This line has content (besides whitespace)
                        // Use the line's indent
                        down_aboveContentLineIndex = downLineNumber - 1;
                        down_aboveContentLineIndent = currentIndent;
                        downLineIndentLevel = Math.ceil(currentIndent / this.textModel.getOptions().indentSize);
                    }
                    else {
                        down_resolveIndents(downLineNumber);
                        downLineIndentLevel = this._getIndentLevelForWhitespaceLine(offSide, down_aboveContentLineIndent, down_belowContentLineIndent);
                    }
                }
                if (distance === 0) {
                    initialIndent = upLineIndentLevel;
                    continue;
                }
                if (distance === 1) {
                    if (downLineNumber <= lineCount &&
                        downLineIndentLevel >= 0 &&
                        initialIndent + 1 === downLineIndentLevel) {
                        // This is the beginning of a scope, we have special handling here, since we want the
                        // child scope indent to be active, not the parent scope
                        goUp = false;
                        startLineNumber = downLineNumber;
                        endLineNumber = downLineNumber;
                        indent = downLineIndentLevel;
                        continue;
                    }
                    if (upLineNumber >= 1 &&
                        upLineIndentLevel >= 0 &&
                        upLineIndentLevel - 1 === initialIndent) {
                        // This is the end of a scope, just like above
                        goDown = false;
                        startLineNumber = upLineNumber;
                        endLineNumber = upLineNumber;
                        indent = upLineIndentLevel;
                        continue;
                    }
                    startLineNumber = lineNumber;
                    endLineNumber = lineNumber;
                    indent = initialIndent;
                    if (indent === 0) {
                        // No need to continue
                        return { startLineNumber, endLineNumber, indent };
                    }
                }
                if (goUp) {
                    if (upLineIndentLevel >= indent) {
                        startLineNumber = upLineNumber;
                    }
                    else {
                        goUp = false;
                    }
                }
                if (goDown) {
                    if (downLineIndentLevel >= indent) {
                        endLineNumber = downLineNumber;
                    }
                    else {
                        goDown = false;
                    }
                }
            }
            return { startLineNumber, endLineNumber, indent };
        }
        getLinesBracketGuides(startLineNumber, endLineNumber, activePosition, options) {
            const result = [];
            for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
                result.push([]);
            }
            // If requested, this could be made configurable.
            const includeSingleLinePairs = true;
            const bracketPairs = this.textModel.bracketPairs.getBracketPairsInRangeWithMinIndentation(new range_1.Range(startLineNumber, 1, endLineNumber, this.textModel.getLineMaxColumn(endLineNumber))).toArray();
            let activeBracketPairRange = undefined;
            if (activePosition && bracketPairs.length > 0) {
                const bracketsContainingActivePosition = (startLineNumber <= activePosition.lineNumber &&
                    activePosition.lineNumber <= endLineNumber
                    // We don't need to query the brackets again if the cursor is in the viewport
                    ? bracketPairs
                    : this.textModel.bracketPairs.getBracketPairsInRange(range_1.Range.fromPositions(activePosition)).toArray()).filter((bp) => range_1.Range.strictContainsPosition(bp.range, activePosition));
                activeBracketPairRange = (0, arraysFind_1.findLast)(bracketsContainingActivePosition, (i) => includeSingleLinePairs || i.range.startLineNumber !== i.range.endLineNumber)?.range;
            }
            const independentColorPoolPerBracketType = this.textModel.getOptions().bracketPairColorizationOptions.independentColorPoolPerBracketType;
            const colorProvider = new BracketPairGuidesClassNames();
            for (const pair of bracketPairs) {
                /*
    
    
                        {
                        |
                        }
    
                        {
                        |
                        ----}
    
                    ____{
                    |test
                    ----}
    
                    renderHorizontalEndLineAtTheBottom:
                        {
                        |
                        |x}
                        --
                    renderHorizontalEndLineAtTheBottom:
                    ____{
                    |test
                    | x }
                    ----
                */
                if (!pair.closingBracketRange) {
                    continue;
                }
                const isActive = activeBracketPairRange && pair.range.equalsRange(activeBracketPairRange);
                if (!isActive && !options.includeInactive) {
                    continue;
                }
                const className = colorProvider.getInlineClassName(pair.nestingLevel, pair.nestingLevelOfEqualBracketType, independentColorPoolPerBracketType) +
                    (options.highlightActive && isActive
                        ? ' ' + colorProvider.activeClassName
                        : '');
                const start = pair.openingBracketRange.getStartPosition();
                const end = pair.closingBracketRange.getStartPosition();
                const horizontalGuides = options.horizontalGuides === textModelGuides_1.HorizontalGuidesState.Enabled || (options.horizontalGuides === textModelGuides_1.HorizontalGuidesState.EnabledForActive && isActive);
                if (pair.range.startLineNumber === pair.range.endLineNumber) {
                    if (includeSingleLinePairs && horizontalGuides) {
                        result[pair.range.startLineNumber - startLineNumber].push(new textModelGuides_1.IndentGuide(-1, pair.openingBracketRange.getEndPosition().column, className, new textModelGuides_1.IndentGuideHorizontalLine(false, end.column), -1, -1));
                    }
                    continue;
                }
                const endVisibleColumn = this.getVisibleColumnFromPosition(end);
                const startVisibleColumn = this.getVisibleColumnFromPosition(pair.openingBracketRange.getStartPosition());
                const guideVisibleColumn = Math.min(startVisibleColumn, endVisibleColumn, pair.minVisibleColumnIndentation + 1);
                let renderHorizontalEndLineAtTheBottom = false;
                const firstNonWsIndex = strings.firstNonWhitespaceIndex(this.textModel.getLineContent(pair.closingBracketRange.startLineNumber));
                const hasTextBeforeClosingBracket = firstNonWsIndex < pair.closingBracketRange.startColumn - 1;
                if (hasTextBeforeClosingBracket) {
                    renderHorizontalEndLineAtTheBottom = true;
                }
                const visibleGuideStartLineNumber = Math.max(start.lineNumber, startLineNumber);
                const visibleGuideEndLineNumber = Math.min(end.lineNumber, endLineNumber);
                const offset = renderHorizontalEndLineAtTheBottom ? 1 : 0;
                for (let l = visibleGuideStartLineNumber; l < visibleGuideEndLineNumber + offset; l++) {
                    result[l - startLineNumber].push(new textModelGuides_1.IndentGuide(guideVisibleColumn, -1, className, null, l === start.lineNumber ? start.column : -1, l === end.lineNumber ? end.column : -1));
                }
                if (horizontalGuides) {
                    if (start.lineNumber >= startLineNumber && startVisibleColumn > guideVisibleColumn) {
                        result[start.lineNumber - startLineNumber].push(new textModelGuides_1.IndentGuide(guideVisibleColumn, -1, className, new textModelGuides_1.IndentGuideHorizontalLine(false, start.column), -1, -1));
                    }
                    if (end.lineNumber <= endLineNumber && endVisibleColumn > guideVisibleColumn) {
                        result[end.lineNumber - startLineNumber].push(new textModelGuides_1.IndentGuide(guideVisibleColumn, -1, className, new textModelGuides_1.IndentGuideHorizontalLine(!renderHorizontalEndLineAtTheBottom, end.column), -1, -1));
                    }
                }
            }
            for (const guides of result) {
                guides.sort((a, b) => a.visibleColumn - b.visibleColumn);
            }
            return result;
        }
        getVisibleColumnFromPosition(position) {
            return (cursorColumns_1.CursorColumns.visibleColumnFromColumn(this.textModel.getLineContent(position.lineNumber), position.column, this.textModel.getOptions().tabSize) + 1);
        }
        getLinesIndentGuides(startLineNumber, endLineNumber) {
            this.assertNotDisposed();
            const lineCount = this.textModel.getLineCount();
            if (startLineNumber < 1 || startLineNumber > lineCount) {
                throw new Error('Illegal value for startLineNumber');
            }
            if (endLineNumber < 1 || endLineNumber > lineCount) {
                throw new Error('Illegal value for endLineNumber');
            }
            const options = this.textModel.getOptions();
            const foldingRules = this.getLanguageConfiguration(this.textModel.getLanguageId()).foldingRules;
            const offSide = Boolean(foldingRules && foldingRules.offSide);
            const result = new Array(endLineNumber - startLineNumber + 1);
            let aboveContentLineIndex = -2; /* -2 is a marker for not having computed it */
            let aboveContentLineIndent = -1;
            let belowContentLineIndex = -2; /* -2 is a marker for not having computed it */
            let belowContentLineIndent = -1;
            for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
                const resultIndex = lineNumber - startLineNumber;
                const currentIndent = this._computeIndentLevel(lineNumber - 1);
                if (currentIndent >= 0) {
                    // This line has content (besides whitespace)
                    // Use the line's indent
                    aboveContentLineIndex = lineNumber - 1;
                    aboveContentLineIndent = currentIndent;
                    result[resultIndex] = Math.ceil(currentIndent / options.indentSize);
                    continue;
                }
                if (aboveContentLineIndex === -2) {
                    aboveContentLineIndex = -1;
                    aboveContentLineIndent = -1;
                    // must find previous line with content
                    for (let lineIndex = lineNumber - 2; lineIndex >= 0; lineIndex--) {
                        const indent = this._computeIndentLevel(lineIndex);
                        if (indent >= 0) {
                            aboveContentLineIndex = lineIndex;
                            aboveContentLineIndent = indent;
                            break;
                        }
                    }
                }
                if (belowContentLineIndex !== -1 &&
                    (belowContentLineIndex === -2 || belowContentLineIndex < lineNumber - 1)) {
                    belowContentLineIndex = -1;
                    belowContentLineIndent = -1;
                    // must find next line with content
                    for (let lineIndex = lineNumber; lineIndex < lineCount; lineIndex++) {
                        const indent = this._computeIndentLevel(lineIndex);
                        if (indent >= 0) {
                            belowContentLineIndex = lineIndex;
                            belowContentLineIndent = indent;
                            break;
                        }
                    }
                }
                result[resultIndex] = this._getIndentLevelForWhitespaceLine(offSide, aboveContentLineIndent, belowContentLineIndent);
            }
            return result;
        }
        _getIndentLevelForWhitespaceLine(offSide, aboveContentLineIndent, belowContentLineIndent) {
            const options = this.textModel.getOptions();
            if (aboveContentLineIndent === -1 || belowContentLineIndent === -1) {
                // At the top or bottom of the file
                return 0;
            }
            else if (aboveContentLineIndent < belowContentLineIndent) {
                // we are inside the region above
                return 1 + Math.floor(aboveContentLineIndent / options.indentSize);
            }
            else if (aboveContentLineIndent === belowContentLineIndent) {
                // we are in between two regions
                return Math.ceil(belowContentLineIndent / options.indentSize);
            }
            else {
                if (offSide) {
                    // same level as region below
                    return Math.ceil(belowContentLineIndent / options.indentSize);
                }
                else {
                    // we are inside the region that ends below
                    return 1 + Math.floor(belowContentLineIndent / options.indentSize);
                }
            }
        }
    }
    exports.GuidesTextModelPart = GuidesTextModelPart;
    class BracketPairGuidesClassNames {
        constructor() {
            this.activeClassName = 'indent-active';
        }
        getInlineClassName(nestingLevel, nestingLevelOfEqualBracketType, independentColorPoolPerBracketType) {
            return this.getInlineClassNameOfLevel(independentColorPoolPerBracketType ? nestingLevelOfEqualBracketType : nestingLevel);
        }
        getInlineClassNameOfLevel(level) {
            // To support a dynamic amount of colors up to 6 colors,
            // we use a number that is a lcm of all numbers from 1 to 6.
            return `bracket-indent-guide lvl-${level % 30}`;
        }
    }
    exports.BracketPairGuidesClassNames = BracketPairGuidesClassNames;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[585/*vs/editor/common/tokenizationRegistry*/], __M([1/*require*/,0/*exports*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/]), function (require, exports, event_1, lifecycle_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.TokenizationRegistry = void 0;
    class TokenizationRegistry {
        constructor() {
            this._tokenizationSupports = new Map();
            this._factories = new Map();
            this._onDidChange = new event_1.Emitter();
            this.onDidChange = this._onDidChange.event;
            this._colorMap = null;
        }
        handleChange(languageIds) {
            this._onDidChange.fire({
                changedLanguages: languageIds,
                changedColorMap: false
            });
        }
        register(languageId, support) {
            this._tokenizationSupports.set(languageId, support);
            this.handleChange([languageId]);
            return (0, lifecycle_1.toDisposable)(() => {
                if (this._tokenizationSupports.get(languageId) !== support) {
                    return;
                }
                this._tokenizationSupports.delete(languageId);
                this.handleChange([languageId]);
            });
        }
        get(languageId) {
            return this._tokenizationSupports.get(languageId) || null;
        }
        registerFactory(languageId, factory) {
            this._factories.get(languageId)?.dispose();
            const myData = new TokenizationSupportFactoryData(this, languageId, factory);
            this._factories.set(languageId, myData);
            return (0, lifecycle_1.toDisposable)(() => {
                const v = this._factories.get(languageId);
                if (!v || v !== myData) {
                    return;
                }
                this._factories.delete(languageId);
                v.dispose();
            });
        }
        async getOrCreate(languageId) {
            // check first if the support is already set
            const tokenizationSupport = this.get(languageId);
            if (tokenizationSupport) {
                return tokenizationSupport;
            }
            const factory = this._factories.get(languageId);
            if (!factory || factory.isResolved) {
                // no factory or factory.resolve already finished
                return null;
            }
            await factory.resolve();
            return this.get(languageId);
        }
        isResolved(languageId) {
            const tokenizationSupport = this.get(languageId);
            if (tokenizationSupport) {
                return true;
            }
            const factory = this._factories.get(languageId);
            if (!factory || factory.isResolved) {
                return true;
            }
            return false;
        }
        setColorMap(colorMap) {
            this._colorMap = colorMap;
            this._onDidChange.fire({
                changedLanguages: Array.from(this._tokenizationSupports.keys()),
                changedColorMap: true
            });
        }
        getColorMap() {
            return this._colorMap;
        }
        getDefaultBackground() {
            if (this._colorMap && this._colorMap.length > 2 /* ColorId.DefaultBackground */) {
                return this._colorMap[2 /* ColorId.DefaultBackground */];
            }
            return null;
        }
    }
    exports.TokenizationRegistry = TokenizationRegistry;
    class TokenizationSupportFactoryData extends lifecycle_1.Disposable {
        get isResolved() {
            return this._isResolved;
        }
        constructor(_registry, _languageId, _factory) {
            super();
            this._registry = _registry;
            this._languageId = _languageId;
            this._factory = _factory;
            this._isDisposed = false;
            this._resolvePromise = null;
            this._isResolved = false;
        }
        dispose() {
            this._isDisposed = true;
            super.dispose();
        }
        async resolve() {
            if (!this._resolvePromise) {
                this._resolvePromise = this._create();
            }
            return this._resolvePromise;
        }
        async _create() {
            const value = await this._factory.tokenizationSupport;
            this._isResolved = true;
            if (value && !this._isDisposed) {
                this._register(this._registry.register(this._languageId, value));
            }
        }
    }
});

define(__m[586/*vs/editor/common/tokens/contiguousMultilineTokens*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ContiguousMultilineTokens = void 0;
    /**
     * Represents contiguous tokens over a contiguous range of lines.
     */
    class ContiguousMultilineTokens {
        /**
         * (Inclusive) start line number for these tokens.
         */
        get startLineNumber() {
            return this._startLineNumber;
        }
        /**
         * (Inclusive) end line number for these tokens.
         */
        get endLineNumber() {
            return this._startLineNumber + this._tokens.length - 1;
        }
        constructor(startLineNumber, tokens) {
            this._startLineNumber = startLineNumber;
            this._tokens = tokens;
        }
        /**
         * @see {@link _tokens}
         */
        getLineTokens(lineNumber) {
            return this._tokens[lineNumber - this._startLineNumber];
        }
        appendLineTokens(lineTokens) {
            this._tokens.push(lineTokens);
        }
    }
    exports.ContiguousMultilineTokens = ContiguousMultilineTokens;
});

define(__m[330/*vs/editor/common/tokens/contiguousMultilineTokensBuilder*/], __M([1/*require*/,0/*exports*/,586/*vs/editor/common/tokens/contiguousMultilineTokens*/]), function (require, exports, contiguousMultilineTokens_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ContiguousMultilineTokensBuilder = void 0;
    class ContiguousMultilineTokensBuilder {
        constructor() {
            this._tokens = [];
        }
        add(lineNumber, lineTokens) {
            if (this._tokens.length > 0) {
                const last = this._tokens[this._tokens.length - 1];
                if (last.endLineNumber + 1 === lineNumber) {
                    // append
                    last.appendLineTokens(lineTokens);
                    return;
                }
            }
            this._tokens.push(new contiguousMultilineTokens_1.ContiguousMultilineTokens(lineNumber, [lineTokens]));
        }
        finalize() {
            return this._tokens;
        }
    }
    exports.ContiguousMultilineTokensBuilder = ContiguousMultilineTokensBuilder;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[83/*vs/editor/common/tokens/lineTokens*/], __M([1/*require*/,0/*exports*/,148/*vs/editor/common/encodedTokenAttributes*/]), function (require, exports, encodedTokenAttributes_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.LineTokens = void 0;
    exports.getStandardTokenTypeAtPosition = getStandardTokenTypeAtPosition;
    class LineTokens {
        static { this.defaultTokenMetadata = ((0 /* FontStyle.None */ << 11 /* MetadataConsts.FONT_STYLE_OFFSET */)
            | (1 /* ColorId.DefaultForeground */ << 15 /* MetadataConsts.FOREGROUND_OFFSET */)
            | (2 /* ColorId.DefaultBackground */ << 24 /* MetadataConsts.BACKGROUND_OFFSET */)) >>> 0; }
        static createEmpty(lineContent, decoder) {
            const defaultMetadata = LineTokens.defaultTokenMetadata;
            const tokens = new Uint32Array(2);
            tokens[0] = lineContent.length;
            tokens[1] = defaultMetadata;
            return new LineTokens(tokens, lineContent, decoder);
        }
        static createFromTextAndMetadata(data, decoder) {
            let offset = 0;
            let fullText = '';
            const tokens = new Array();
            for (const { text, metadata } of data) {
                tokens.push(offset + text.length, metadata);
                offset += text.length;
                fullText += text;
            }
            return new LineTokens(new Uint32Array(tokens), fullText, decoder);
        }
        constructor(tokens, text, decoder) {
            this._lineTokensBrand = undefined;
            this._tokens = tokens;
            this._tokensCount = (this._tokens.length >>> 1);
            this._text = text;
            this.languageIdCodec = decoder;
        }
        equals(other) {
            if (other instanceof LineTokens) {
                return this.slicedEquals(other, 0, this._tokensCount);
            }
            return false;
        }
        slicedEquals(other, sliceFromTokenIndex, sliceTokenCount) {
            if (this._text !== other._text) {
                return false;
            }
            if (this._tokensCount !== other._tokensCount) {
                return false;
            }
            const from = (sliceFromTokenIndex << 1);
            const to = from + (sliceTokenCount << 1);
            for (let i = from; i < to; i++) {
                if (this._tokens[i] !== other._tokens[i]) {
                    return false;
                }
            }
            return true;
        }
        getLineContent() {
            return this._text;
        }
        getCount() {
            return this._tokensCount;
        }
        getStartOffset(tokenIndex) {
            if (tokenIndex > 0) {
                return this._tokens[(tokenIndex - 1) << 1];
            }
            return 0;
        }
        getMetadata(tokenIndex) {
            const metadata = this._tokens[(tokenIndex << 1) + 1];
            return metadata;
        }
        getLanguageId(tokenIndex) {
            const metadata = this._tokens[(tokenIndex << 1) + 1];
            const languageId = encodedTokenAttributes_1.TokenMetadata.getLanguageId(metadata);
            return this.languageIdCodec.decodeLanguageId(languageId);
        }
        getStandardTokenType(tokenIndex) {
            const metadata = this._tokens[(tokenIndex << 1) + 1];
            return encodedTokenAttributes_1.TokenMetadata.getTokenType(metadata);
        }
        getForeground(tokenIndex) {
            const metadata = this._tokens[(tokenIndex << 1) + 1];
            return encodedTokenAttributes_1.TokenMetadata.getForeground(metadata);
        }
        getClassName(tokenIndex) {
            const metadata = this._tokens[(tokenIndex << 1) + 1];
            return encodedTokenAttributes_1.TokenMetadata.getClassNameFromMetadata(metadata);
        }
        getInlineStyle(tokenIndex, colorMap) {
            const metadata = this._tokens[(tokenIndex << 1) + 1];
            return encodedTokenAttributes_1.TokenMetadata.getInlineStyleFromMetadata(metadata, colorMap);
        }
        getPresentation(tokenIndex) {
            const metadata = this._tokens[(tokenIndex << 1) + 1];
            return encodedTokenAttributes_1.TokenMetadata.getPresentationFromMetadata(metadata);
        }
        getEndOffset(tokenIndex) {
            return this._tokens[tokenIndex << 1];
        }
        /**
         * Find the token containing offset `offset`.
         * @param offset The search offset
         * @return The index of the token containing the offset.
         */
        findTokenIndexAtOffset(offset) {
            return LineTokens.findIndexInTokensArray(this._tokens, offset);
        }
        inflate() {
            return this;
        }
        sliceAndInflate(startOffset, endOffset, deltaOffset) {
            return new SliceLineTokens(this, startOffset, endOffset, deltaOffset);
        }
        static convertToEndOffset(tokens, lineTextLength) {
            const tokenCount = (tokens.length >>> 1);
            const lastTokenIndex = tokenCount - 1;
            for (let tokenIndex = 0; tokenIndex < lastTokenIndex; tokenIndex++) {
                tokens[tokenIndex << 1] = tokens[(tokenIndex + 1) << 1];
            }
            tokens[lastTokenIndex << 1] = lineTextLength;
        }
        static findIndexInTokensArray(tokens, desiredIndex) {
            if (tokens.length <= 2) {
                return 0;
            }
            let low = 0;
            let high = (tokens.length >>> 1) - 1;
            while (low < high) {
                const mid = low + Math.floor((high - low) / 2);
                const endOffset = tokens[(mid << 1)];
                if (endOffset === desiredIndex) {
                    return mid + 1;
                }
                else if (endOffset < desiredIndex) {
                    low = mid + 1;
                }
                else if (endOffset > desiredIndex) {
                    high = mid;
                }
            }
            return low;
        }
        /**
         * @pure
         * @param insertTokens Must be sorted by offset.
        */
        withInserted(insertTokens) {
            if (insertTokens.length === 0) {
                return this;
            }
            let nextOriginalTokenIdx = 0;
            let nextInsertTokenIdx = 0;
            let text = '';
            const newTokens = new Array();
            let originalEndOffset = 0;
            while (true) {
                const nextOriginalTokenEndOffset = nextOriginalTokenIdx < this._tokensCount ? this._tokens[nextOriginalTokenIdx << 1] : -1;
                const nextInsertToken = nextInsertTokenIdx < insertTokens.length ? insertTokens[nextInsertTokenIdx] : null;
                if (nextOriginalTokenEndOffset !== -1 && (nextInsertToken === null || nextOriginalTokenEndOffset <= nextInsertToken.offset)) {
                    // original token ends before next insert token
                    text += this._text.substring(originalEndOffset, nextOriginalTokenEndOffset);
                    const metadata = this._tokens[(nextOriginalTokenIdx << 1) + 1];
                    newTokens.push(text.length, metadata);
                    nextOriginalTokenIdx++;
                    originalEndOffset = nextOriginalTokenEndOffset;
                }
                else if (nextInsertToken) {
                    if (nextInsertToken.offset > originalEndOffset) {
                        // insert token is in the middle of the next token.
                        text += this._text.substring(originalEndOffset, nextInsertToken.offset);
                        const metadata = this._tokens[(nextOriginalTokenIdx << 1) + 1];
                        newTokens.push(text.length, metadata);
                        originalEndOffset = nextInsertToken.offset;
                    }
                    text += nextInsertToken.text;
                    newTokens.push(text.length, nextInsertToken.tokenMetadata);
                    nextInsertTokenIdx++;
                }
                else {
                    break;
                }
            }
            return new LineTokens(new Uint32Array(newTokens), text, this.languageIdCodec);
        }
        getTokenText(tokenIndex) {
            const startOffset = this.getStartOffset(tokenIndex);
            const endOffset = this.getEndOffset(tokenIndex);
            const text = this._text.substring(startOffset, endOffset);
            return text;
        }
        forEach(callback) {
            const tokenCount = this.getCount();
            for (let tokenIndex = 0; tokenIndex < tokenCount; tokenIndex++) {
                callback(tokenIndex);
            }
        }
    }
    exports.LineTokens = LineTokens;
    class SliceLineTokens {
        constructor(source, startOffset, endOffset, deltaOffset) {
            this._source = source;
            this._startOffset = startOffset;
            this._endOffset = endOffset;
            this._deltaOffset = deltaOffset;
            this._firstTokenIndex = source.findTokenIndexAtOffset(startOffset);
            this.languageIdCodec = source.languageIdCodec;
            this._tokensCount = 0;
            for (let i = this._firstTokenIndex, len = source.getCount(); i < len; i++) {
                const tokenStartOffset = source.getStartOffset(i);
                if (tokenStartOffset >= endOffset) {
                    break;
                }
                this._tokensCount++;
            }
        }
        getMetadata(tokenIndex) {
            return this._source.getMetadata(this._firstTokenIndex + tokenIndex);
        }
        getLanguageId(tokenIndex) {
            return this._source.getLanguageId(this._firstTokenIndex + tokenIndex);
        }
        getLineContent() {
            return this._source.getLineContent().substring(this._startOffset, this._endOffset);
        }
        equals(other) {
            if (other instanceof SliceLineTokens) {
                return (this._startOffset === other._startOffset
                    && this._endOffset === other._endOffset
                    && this._deltaOffset === other._deltaOffset
                    && this._source.slicedEquals(other._source, this._firstTokenIndex, this._tokensCount));
            }
            return false;
        }
        getCount() {
            return this._tokensCount;
        }
        getStandardTokenType(tokenIndex) {
            return this._source.getStandardTokenType(this._firstTokenIndex + tokenIndex);
        }
        getForeground(tokenIndex) {
            return this._source.getForeground(this._firstTokenIndex + tokenIndex);
        }
        getEndOffset(tokenIndex) {
            const tokenEndOffset = this._source.getEndOffset(this._firstTokenIndex + tokenIndex);
            return Math.min(this._endOffset, tokenEndOffset) - this._startOffset + this._deltaOffset;
        }
        getClassName(tokenIndex) {
            return this._source.getClassName(this._firstTokenIndex + tokenIndex);
        }
        getInlineStyle(tokenIndex, colorMap) {
            return this._source.getInlineStyle(this._firstTokenIndex + tokenIndex, colorMap);
        }
        getPresentation(tokenIndex) {
            return this._source.getPresentation(this._firstTokenIndex + tokenIndex);
        }
        findTokenIndexAtOffset(offset) {
            return this._source.findTokenIndexAtOffset(offset + this._startOffset - this._deltaOffset) - this._firstTokenIndex;
        }
        getTokenText(tokenIndex) {
            const adjustedTokenIndex = this._firstTokenIndex + tokenIndex;
            const tokenStartOffset = this._source.getStartOffset(adjustedTokenIndex);
            const tokenEndOffset = this._source.getEndOffset(adjustedTokenIndex);
            let text = this._source.getTokenText(adjustedTokenIndex);
            if (tokenStartOffset < this._startOffset) {
                text = text.substring(this._startOffset - tokenStartOffset);
            }
            if (tokenEndOffset > this._endOffset) {
                text = text.substring(0, text.length - (tokenEndOffset - this._endOffset));
            }
            return text;
        }
        forEach(callback) {
            for (let tokenIndex = 0; tokenIndex < this.getCount(); tokenIndex++) {
                callback(tokenIndex);
            }
        }
    }
    function getStandardTokenTypeAtPosition(model, position) {
        const lineNumber = position.lineNumber;
        if (!model.tokenization.isCheapToTokenize(lineNumber)) {
            return undefined;
        }
        model.tokenization.forceTokenization(lineNumber);
        const lineTokens = model.tokenization.getLineTokens(lineNumber);
        const tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
        const tokenType = lineTokens.getStandardTokenType(tokenIndex);
        return tokenType;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[240/*vs/editor/common/languages/supports/indentationLineProcessor*/], __M([1/*require*/,0/*exports*/,11/*vs/base/common/strings*/,169/*vs/editor/common/languages/supports*/,83/*vs/editor/common/tokens/lineTokens*/]), function (require, exports, strings, supports_1, lineTokens_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.IndentationContextProcessor = exports.ProcessedIndentRulesSupport = void 0;
    exports.isLanguageDifferentFromLineStart = isLanguageDifferentFromLineStart;
    /**
     * This class is a wrapper class around {@link IndentRulesSupport}.
     * It processes the lines by removing the language configuration brackets from the regex, string and comment tokens.
     * It then calls into the {@link IndentRulesSupport} to validate the indentation conditions.
     */
    class ProcessedIndentRulesSupport {
        constructor(model, indentRulesSupport, languageConfigurationService) {
            this._indentRulesSupport = indentRulesSupport;
            this._indentationLineProcessor = new IndentationLineProcessor(model, languageConfigurationService);
        }
        /**
         * Apply the new indentation and return whether the indentation level should be increased after the given line number
         */
        shouldIncrease(lineNumber, newIndentation) {
            const processedLine = this._indentationLineProcessor.getProcessedLine(lineNumber, newIndentation);
            return this._indentRulesSupport.shouldIncrease(processedLine);
        }
        /**
         * Apply the new indentation and return whether the indentation level should be decreased after the given line number
         */
        shouldDecrease(lineNumber, newIndentation) {
            const processedLine = this._indentationLineProcessor.getProcessedLine(lineNumber, newIndentation);
            return this._indentRulesSupport.shouldDecrease(processedLine);
        }
        /**
         * Apply the new indentation and return whether the indentation level should remain unchanged at the given line number
         */
        shouldIgnore(lineNumber, newIndentation) {
            const processedLine = this._indentationLineProcessor.getProcessedLine(lineNumber, newIndentation);
            return this._indentRulesSupport.shouldIgnore(processedLine);
        }
        /**
         * Apply the new indentation and return whether the indentation level should increase on the line after the given line number
         */
        shouldIndentNextLine(lineNumber, newIndentation) {
            const processedLine = this._indentationLineProcessor.getProcessedLine(lineNumber, newIndentation);
            return this._indentRulesSupport.shouldIndentNextLine(processedLine);
        }
    }
    exports.ProcessedIndentRulesSupport = ProcessedIndentRulesSupport;
    /**
     * This class fetches the processed text around a range which can be used for indentation evaluation.
     * It returns:
     * - The processed text before the given range and on the same start line
     * - The processed text after the given range and on the same end line
     * - The processed text on the previous line
     */
    class IndentationContextProcessor {
        constructor(model, languageConfigurationService) {
            this.model = model;
            this.indentationLineProcessor = new IndentationLineProcessor(model, languageConfigurationService);
        }
        /**
         * Returns the processed text, stripped from the language configuration brackets within the string, comment and regex tokens, around the given range
         */
        getProcessedTokenContextAroundRange(range) {
            const beforeRangeProcessedTokens = this._getProcessedTokensBeforeRange(range);
            const afterRangeProcessedTokens = this._getProcessedTokensAfterRange(range);
            const previousLineProcessedTokens = this._getProcessedPreviousLineTokens(range);
            return { beforeRangeProcessedTokens, afterRangeProcessedTokens, previousLineProcessedTokens };
        }
        _getProcessedTokensBeforeRange(range) {
            this.model.tokenization.forceTokenization(range.startLineNumber);
            const lineTokens = this.model.tokenization.getLineTokens(range.startLineNumber);
            const scopedLineTokens = (0, supports_1.createScopedLineTokens)(lineTokens, range.startColumn - 1);
            let slicedTokens;
            if (isLanguageDifferentFromLineStart(this.model, range.getStartPosition())) {
                const columnIndexWithinScope = (range.startColumn - 1) - scopedLineTokens.firstCharOffset;
                const firstCharacterOffset = scopedLineTokens.firstCharOffset;
                const lastCharacterOffset = firstCharacterOffset + columnIndexWithinScope;
                slicedTokens = lineTokens.sliceAndInflate(firstCharacterOffset, lastCharacterOffset, 0);
            }
            else {
                const columnWithinLine = range.startColumn - 1;
                slicedTokens = lineTokens.sliceAndInflate(0, columnWithinLine, 0);
            }
            const processedTokens = this.indentationLineProcessor.getProcessedTokens(slicedTokens);
            return processedTokens;
        }
        _getProcessedTokensAfterRange(range) {
            const position = range.isEmpty() ? range.getStartPosition() : range.getEndPosition();
            this.model.tokenization.forceTokenization(position.lineNumber);
            const lineTokens = this.model.tokenization.getLineTokens(position.lineNumber);
            const scopedLineTokens = (0, supports_1.createScopedLineTokens)(lineTokens, position.column - 1);
            const columnIndexWithinScope = position.column - 1 - scopedLineTokens.firstCharOffset;
            const firstCharacterOffset = scopedLineTokens.firstCharOffset + columnIndexWithinScope;
            const lastCharacterOffset = scopedLineTokens.firstCharOffset + scopedLineTokens.getLineLength();
            const slicedTokens = lineTokens.sliceAndInflate(firstCharacterOffset, lastCharacterOffset, 0);
            const processedTokens = this.indentationLineProcessor.getProcessedTokens(slicedTokens);
            return processedTokens;
        }
        _getProcessedPreviousLineTokens(range) {
            const getScopedLineTokensAtEndColumnOfLine = (lineNumber) => {
                this.model.tokenization.forceTokenization(lineNumber);
                const lineTokens = this.model.tokenization.getLineTokens(lineNumber);
                const endColumnOfLine = this.model.getLineMaxColumn(lineNumber) - 1;
                const scopedLineTokensAtEndColumn = (0, supports_1.createScopedLineTokens)(lineTokens, endColumnOfLine);
                return scopedLineTokensAtEndColumn;
            };
            this.model.tokenization.forceTokenization(range.startLineNumber);
            const lineTokens = this.model.tokenization.getLineTokens(range.startLineNumber);
            const scopedLineTokens = (0, supports_1.createScopedLineTokens)(lineTokens, range.startColumn - 1);
            const emptyTokens = lineTokens_1.LineTokens.createEmpty('', scopedLineTokens.languageIdCodec);
            const previousLineNumber = range.startLineNumber - 1;
            const isFirstLine = previousLineNumber === 0;
            if (isFirstLine) {
                return emptyTokens;
            }
            const canScopeExtendOnPreviousLine = scopedLineTokens.firstCharOffset === 0;
            if (!canScopeExtendOnPreviousLine) {
                return emptyTokens;
            }
            const scopedLineTokensAtEndColumnOfPreviousLine = getScopedLineTokensAtEndColumnOfLine(previousLineNumber);
            const doesLanguageContinueOnPreviousLine = scopedLineTokens.languageId === scopedLineTokensAtEndColumnOfPreviousLine.languageId;
            if (!doesLanguageContinueOnPreviousLine) {
                return emptyTokens;
            }
            const previousSlicedLineTokens = scopedLineTokensAtEndColumnOfPreviousLine.toIViewLineTokens();
            const processedTokens = this.indentationLineProcessor.getProcessedTokens(previousSlicedLineTokens);
            return processedTokens;
        }
    }
    exports.IndentationContextProcessor = IndentationContextProcessor;
    /**
     * This class performs the actual processing of the indentation lines.
     * The brackets of the language configuration are removed from the regex, string and comment tokens.
     */
    class IndentationLineProcessor {
        constructor(model, languageConfigurationService) {
            this.model = model;
            this.languageConfigurationService = languageConfigurationService;
        }
        /**
         * Get the processed line for the given line number and potentially adjust the indentation level.
         * Remove the language configuration brackets from the regex, string and comment tokens.
         */
        getProcessedLine(lineNumber, newIndentation) {
            const replaceIndentation = (line, newIndentation) => {
                const currentIndentation = strings.getLeadingWhitespace(line);
                const adjustedLine = newIndentation + line.substring(currentIndentation.length);
                return adjustedLine;
            };
            this.model.tokenization.forceTokenization?.(lineNumber);
            const tokens = this.model.tokenization.getLineTokens(lineNumber);
            let processedLine = this.getProcessedTokens(tokens).getLineContent();
            if (newIndentation !== undefined) {
                processedLine = replaceIndentation(processedLine, newIndentation);
            }
            return processedLine;
        }
        /**
         * Process the line with the given tokens, remove the language configuration brackets from the regex, string and comment tokens.
         */
        getProcessedTokens(tokens) {
            const shouldRemoveBracketsFromTokenType = (tokenType) => {
                return tokenType === 2 /* StandardTokenType.String */
                    || tokenType === 3 /* StandardTokenType.RegEx */
                    || tokenType === 1 /* StandardTokenType.Comment */;
            };
            const languageId = tokens.getLanguageId(0);
            const bracketsConfiguration = this.languageConfigurationService.getLanguageConfiguration(languageId).bracketsNew;
            const bracketsRegExp = bracketsConfiguration.getBracketRegExp({ global: true });
            const textAndMetadata = [];
            tokens.forEach((tokenIndex) => {
                const tokenType = tokens.getStandardTokenType(tokenIndex);
                let text = tokens.getTokenText(tokenIndex);
                if (shouldRemoveBracketsFromTokenType(tokenType)) {
                    text = text.replace(bracketsRegExp, '');
                }
                const metadata = tokens.getMetadata(tokenIndex);
                textAndMetadata.push({ text, metadata });
            });
            const processedLineTokens = lineTokens_1.LineTokens.createFromTextAndMetadata(textAndMetadata, tokens.languageIdCodec);
            return processedLineTokens;
        }
    }
    function isLanguageDifferentFromLineStart(model, position) {
        model.tokenization.forceTokenization(position.lineNumber);
        const lineTokens = model.tokenization.getLineTokens(position.lineNumber);
        const scopedLineTokens = (0, supports_1.createScopedLineTokens)(lineTokens, position.column - 1);
        const doesScopeStartAtOffsetZero = scopedLineTokens.firstCharOffset === 0;
        const isScopedLanguageEqualToFirstLanguageOnLine = lineTokens.getLanguageId(0) === scopedLineTokens.languageId;
        const languageIsDifferentFromLineStart = !doesScopeStartAtOffsetZero && !isScopedLanguageEqualToFirstLanguageOnLine;
        return languageIsDifferentFromLineStart;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[241/*vs/editor/common/languages/autoIndent*/], __M([1/*require*/,0/*exports*/,11/*vs/base/common/strings*/,131/*vs/editor/common/languages/languageConfiguration*/,240/*vs/editor/common/languages/supports/indentationLineProcessor*/]), function (require, exports, strings, languageConfiguration_1, indentationLineProcessor_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.getInheritIndentForLine = getInheritIndentForLine;
    exports.getGoodIndentForLine = getGoodIndentForLine;
    exports.getIndentForEnter = getIndentForEnter;
    exports.getIndentActionForType = getIndentActionForType;
    exports.getIndentMetadata = getIndentMetadata;
    /**
     * Get nearest preceding line which doesn't match unIndentPattern or contains all whitespace.
     * Result:
     * -1: run into the boundary of embedded languages
     * 0: every line above are invalid
     * else: nearest preceding line of the same language
     */
    function getPrecedingValidLine(model, lineNumber, processedIndentRulesSupport) {
        const languageId = model.tokenization.getLanguageIdAtPosition(lineNumber, 0);
        if (lineNumber > 1) {
            let lastLineNumber;
            let resultLineNumber = -1;
            for (lastLineNumber = lineNumber - 1; lastLineNumber >= 1; lastLineNumber--) {
                if (model.tokenization.getLanguageIdAtPosition(lastLineNumber, 0) !== languageId) {
                    return resultLineNumber;
                }
                const text = model.getLineContent(lastLineNumber);
                if (processedIndentRulesSupport.shouldIgnore(lastLineNumber) || /^\s+$/.test(text) || text === '') {
                    resultLineNumber = lastLineNumber;
                    continue;
                }
                return lastLineNumber;
            }
        }
        return -1;
    }
    /**
     * Get inherited indentation from above lines.
     * 1. Find the nearest preceding line which doesn't match unIndentedLinePattern.
     * 2. If this line matches indentNextLinePattern or increaseIndentPattern, it means that the indent level of `lineNumber` should be 1 greater than this line.
     * 3. If this line doesn't match any indent rules
     *   a. check whether the line above it matches indentNextLinePattern
     *   b. If not, the indent level of this line is the result
     *   c. If so, it means the indent of this line is *temporary*, go upward utill we find a line whose indent is not temporary (the same workflow a -> b -> c).
     * 4. Otherwise, we fail to get an inherited indent from aboves. Return null and we should not touch the indent of `lineNumber`
     *
     * This function only return the inherited indent based on above lines, it doesn't check whether current line should decrease or not.
     */
    function getInheritIndentForLine(autoIndent, model, lineNumber, honorIntentialIndent = true, languageConfigurationService) {
        if (autoIndent < 4 /* EditorAutoIndentStrategy.Full */) {
            return null;
        }
        const indentRulesSupport = languageConfigurationService.getLanguageConfiguration(model.tokenization.getLanguageId()).indentRulesSupport;
        if (!indentRulesSupport) {
            return null;
        }
        const processedIndentRulesSupport = new indentationLineProcessor_1.ProcessedIndentRulesSupport(model, indentRulesSupport, languageConfigurationService);
        if (lineNumber <= 1) {
            return {
                indentation: '',
                action: null
            };
        }
        // Use no indent if this is the first non-blank line
        for (let priorLineNumber = lineNumber - 1; priorLineNumber > 0; priorLineNumber--) {
            if (model.getLineContent(priorLineNumber) !== '') {
                break;
            }
            if (priorLineNumber === 1) {
                return {
                    indentation: '',
                    action: null
                };
            }
        }
        const precedingUnIgnoredLine = getPrecedingValidLine(model, lineNumber, processedIndentRulesSupport);
        if (precedingUnIgnoredLine < 0) {
            return null;
        }
        else if (precedingUnIgnoredLine < 1) {
            return {
                indentation: '',
                action: null
            };
        }
        if (processedIndentRulesSupport.shouldIncrease(precedingUnIgnoredLine) || processedIndentRulesSupport.shouldIndentNextLine(precedingUnIgnoredLine)) {
            const precedingUnIgnoredLineContent = model.getLineContent(precedingUnIgnoredLine);
            return {
                indentation: strings.getLeadingWhitespace(precedingUnIgnoredLineContent),
                action: languageConfiguration_1.IndentAction.Indent,
                line: precedingUnIgnoredLine
            };
        }
        else if (processedIndentRulesSupport.shouldDecrease(precedingUnIgnoredLine)) {
            const precedingUnIgnoredLineContent = model.getLineContent(precedingUnIgnoredLine);
            return {
                indentation: strings.getLeadingWhitespace(precedingUnIgnoredLineContent),
                action: null,
                line: precedingUnIgnoredLine
            };
        }
        else {
            // precedingUnIgnoredLine can not be ignored.
            // it doesn't increase indent of following lines
            // it doesn't increase just next line
            // so current line is not affect by precedingUnIgnoredLine
            // and then we should get a correct inheritted indentation from above lines
            if (precedingUnIgnoredLine === 1) {
                return {
                    indentation: strings.getLeadingWhitespace(model.getLineContent(precedingUnIgnoredLine)),
                    action: null,
                    line: precedingUnIgnoredLine
                };
            }
            const previousLine = precedingUnIgnoredLine - 1;
            const previousLineIndentMetadata = indentRulesSupport.getIndentMetadata(model.getLineContent(previousLine));
            if (!(previousLineIndentMetadata & (1 /* IndentConsts.INCREASE_MASK */ | 2 /* IndentConsts.DECREASE_MASK */)) &&
                (previousLineIndentMetadata & 4 /* IndentConsts.INDENT_NEXTLINE_MASK */)) {
                let stopLine = 0;
                for (let i = previousLine - 1; i > 0; i--) {
                    if (processedIndentRulesSupport.shouldIndentNextLine(i)) {
                        continue;
                    }
                    stopLine = i;
                    break;
                }
                return {
                    indentation: strings.getLeadingWhitespace(model.getLineContent(stopLine + 1)),
                    action: null,
                    line: stopLine + 1
                };
            }
            if (honorIntentialIndent) {
                return {
                    indentation: strings.getLeadingWhitespace(model.getLineContent(precedingUnIgnoredLine)),
                    action: null,
                    line: precedingUnIgnoredLine
                };
            }
            else {
                // search from precedingUnIgnoredLine until we find one whose indent is not temporary
                for (let i = precedingUnIgnoredLine; i > 0; i--) {
                    if (processedIndentRulesSupport.shouldIncrease(i)) {
                        return {
                            indentation: strings.getLeadingWhitespace(model.getLineContent(i)),
                            action: languageConfiguration_1.IndentAction.Indent,
                            line: i
                        };
                    }
                    else if (processedIndentRulesSupport.shouldIndentNextLine(i)) {
                        let stopLine = 0;
                        for (let j = i - 1; j > 0; j--) {
                            if (processedIndentRulesSupport.shouldIndentNextLine(i)) {
                                continue;
                            }
                            stopLine = j;
                            break;
                        }
                        return {
                            indentation: strings.getLeadingWhitespace(model.getLineContent(stopLine + 1)),
                            action: null,
                            line: stopLine + 1
                        };
                    }
                    else if (processedIndentRulesSupport.shouldDecrease(i)) {
                        return {
                            indentation: strings.getLeadingWhitespace(model.getLineContent(i)),
                            action: null,
                            line: i
                        };
                    }
                }
                return {
                    indentation: strings.getLeadingWhitespace(model.getLineContent(1)),
                    action: null,
                    line: 1
                };
            }
        }
    }
    function getGoodIndentForLine(autoIndent, virtualModel, languageId, lineNumber, indentConverter, languageConfigurationService) {
        if (autoIndent < 4 /* EditorAutoIndentStrategy.Full */) {
            return null;
        }
        const richEditSupport = languageConfigurationService.getLanguageConfiguration(languageId);
        if (!richEditSupport) {
            return null;
        }
        const indentRulesSupport = languageConfigurationService.getLanguageConfiguration(languageId).indentRulesSupport;
        if (!indentRulesSupport) {
            return null;
        }
        const processedIndentRulesSupport = new indentationLineProcessor_1.ProcessedIndentRulesSupport(virtualModel, indentRulesSupport, languageConfigurationService);
        const indent = getInheritIndentForLine(autoIndent, virtualModel, lineNumber, undefined, languageConfigurationService);
        if (indent) {
            const inheritLine = indent.line;
            if (inheritLine !== undefined) {
                // Apply enter action as long as there are only whitespace lines between inherited line and this line.
                let shouldApplyEnterRules = true;
                for (let inBetweenLine = inheritLine; inBetweenLine < lineNumber - 1; inBetweenLine++) {
                    if (!/^\s*$/.test(virtualModel.getLineContent(inBetweenLine))) {
                        shouldApplyEnterRules = false;
                        break;
                    }
                }
                if (shouldApplyEnterRules) {
                    const enterResult = richEditSupport.onEnter(autoIndent, '', virtualModel.getLineContent(inheritLine), '');
                    if (enterResult) {
                        let indentation = strings.getLeadingWhitespace(virtualModel.getLineContent(inheritLine));
                        if (enterResult.removeText) {
                            indentation = indentation.substring(0, indentation.length - enterResult.removeText);
                        }
                        if ((enterResult.indentAction === languageConfiguration_1.IndentAction.Indent) ||
                            (enterResult.indentAction === languageConfiguration_1.IndentAction.IndentOutdent)) {
                            indentation = indentConverter.shiftIndent(indentation);
                        }
                        else if (enterResult.indentAction === languageConfiguration_1.IndentAction.Outdent) {
                            indentation = indentConverter.unshiftIndent(indentation);
                        }
                        if (processedIndentRulesSupport.shouldDecrease(lineNumber)) {
                            indentation = indentConverter.unshiftIndent(indentation);
                        }
                        if (enterResult.appendText) {
                            indentation += enterResult.appendText;
                        }
                        return strings.getLeadingWhitespace(indentation);
                    }
                }
            }
            if (processedIndentRulesSupport.shouldDecrease(lineNumber)) {
                if (indent.action === languageConfiguration_1.IndentAction.Indent) {
                    return indent.indentation;
                }
                else {
                    return indentConverter.unshiftIndent(indent.indentation);
                }
            }
            else {
                if (indent.action === languageConfiguration_1.IndentAction.Indent) {
                    return indentConverter.shiftIndent(indent.indentation);
                }
                else {
                    return indent.indentation;
                }
            }
        }
        return null;
    }
    function getIndentForEnter(autoIndent, model, range, indentConverter, languageConfigurationService) {
        if (autoIndent < 4 /* EditorAutoIndentStrategy.Full */) {
            return null;
        }
        const languageId = model.getLanguageIdAtPosition(range.startLineNumber, range.startColumn);
        const indentRulesSupport = languageConfigurationService.getLanguageConfiguration(languageId).indentRulesSupport;
        if (!indentRulesSupport) {
            return null;
        }
        model.tokenization.forceTokenization(range.startLineNumber);
        const indentationContextProcessor = new indentationLineProcessor_1.IndentationContextProcessor(model, languageConfigurationService);
        const processedContextTokens = indentationContextProcessor.getProcessedTokenContextAroundRange(range);
        const afterEnterProcessedTokens = processedContextTokens.afterRangeProcessedTokens;
        const beforeEnterProcessedTokens = processedContextTokens.beforeRangeProcessedTokens;
        const beforeEnterIndent = strings.getLeadingWhitespace(beforeEnterProcessedTokens.getLineContent());
        const virtualModel = createVirtualModelWithModifiedTokensAtLine(model, range.startLineNumber, beforeEnterProcessedTokens);
        const languageIsDifferentFromLineStart = (0, indentationLineProcessor_1.isLanguageDifferentFromLineStart)(model, range.getStartPosition());
        const currentLine = model.getLineContent(range.startLineNumber);
        const currentLineIndent = strings.getLeadingWhitespace(currentLine);
        const afterEnterAction = getInheritIndentForLine(autoIndent, virtualModel, range.startLineNumber + 1, undefined, languageConfigurationService);
        if (!afterEnterAction) {
            const beforeEnter = languageIsDifferentFromLineStart ? currentLineIndent : beforeEnterIndent;
            return {
                beforeEnter: beforeEnter,
                afterEnter: beforeEnter
            };
        }
        let afterEnterIndent = languageIsDifferentFromLineStart ? currentLineIndent : afterEnterAction.indentation;
        if (afterEnterAction.action === languageConfiguration_1.IndentAction.Indent) {
            afterEnterIndent = indentConverter.shiftIndent(afterEnterIndent);
        }
        if (indentRulesSupport.shouldDecrease(afterEnterProcessedTokens.getLineContent())) {
            afterEnterIndent = indentConverter.unshiftIndent(afterEnterIndent);
        }
        return {
            beforeEnter: languageIsDifferentFromLineStart ? currentLineIndent : beforeEnterIndent,
            afterEnter: afterEnterIndent
        };
    }
    /**
     * We should always allow intentional indentation. It means, if users change the indentation of `lineNumber` and the content of
     * this line doesn't match decreaseIndentPattern, we should not adjust the indentation.
     */
    function getIndentActionForType(cursorConfig, model, range, ch, indentConverter, languageConfigurationService) {
        const autoIndent = cursorConfig.autoIndent;
        if (autoIndent < 4 /* EditorAutoIndentStrategy.Full */) {
            return null;
        }
        const languageIsDifferentFromLineStart = (0, indentationLineProcessor_1.isLanguageDifferentFromLineStart)(model, range.getStartPosition());
        if (languageIsDifferentFromLineStart) {
            // this line has mixed languages and indentation rules will not work
            return null;
        }
        const languageId = model.getLanguageIdAtPosition(range.startLineNumber, range.startColumn);
        const indentRulesSupport = languageConfigurationService.getLanguageConfiguration(languageId).indentRulesSupport;
        if (!indentRulesSupport) {
            return null;
        }
        const indentationContextProcessor = new indentationLineProcessor_1.IndentationContextProcessor(model, languageConfigurationService);
        const processedContextTokens = indentationContextProcessor.getProcessedTokenContextAroundRange(range);
        const beforeRangeText = processedContextTokens.beforeRangeProcessedTokens.getLineContent();
        const afterRangeText = processedContextTokens.afterRangeProcessedTokens.getLineContent();
        const textAroundRange = beforeRangeText + afterRangeText;
        const textAroundRangeWithCharacter = beforeRangeText + ch + afterRangeText;
        // If previous content already matches decreaseIndentPattern, it means indentation of this line should already be adjusted
        // Users might change the indentation by purpose and we should honor that instead of readjusting.
        if (!indentRulesSupport.shouldDecrease(textAroundRange) && indentRulesSupport.shouldDecrease(textAroundRangeWithCharacter)) {
            // after typing `ch`, the content matches decreaseIndentPattern, we should adjust the indent to a good manner.
            // 1. Get inherited indent action
            const r = getInheritIndentForLine(autoIndent, model, range.startLineNumber, false, languageConfigurationService);
            if (!r) {
                return null;
            }
            let indentation = r.indentation;
            if (r.action !== languageConfiguration_1.IndentAction.Indent) {
                indentation = indentConverter.unshiftIndent(indentation);
            }
            return indentation;
        }
        const previousLineNumber = range.startLineNumber - 1;
        if (previousLineNumber > 0) {
            const previousLine = model.getLineContent(previousLineNumber);
            if (indentRulesSupport.shouldIndentNextLine(previousLine) && indentRulesSupport.shouldIncrease(textAroundRangeWithCharacter)) {
                const inheritedIndentationData = getInheritIndentForLine(autoIndent, model, range.startLineNumber, false, languageConfigurationService);
                const inheritedIndentation = inheritedIndentationData?.indentation;
                if (inheritedIndentation !== undefined) {
                    const currentLine = model.getLineContent(range.startLineNumber);
                    const actualCurrentIndentation = strings.getLeadingWhitespace(currentLine);
                    const inferredCurrentIndentation = indentConverter.shiftIndent(inheritedIndentation);
                    // If the inferred current indentation is not equal to the actual current indentation, then the indentation has been intentionally changed, in that case keep it
                    const inferredIndentationEqualsActual = inferredCurrentIndentation === actualCurrentIndentation;
                    const textAroundRangeContainsOnlyWhitespace = /^\s*$/.test(textAroundRange);
                    const autoClosingPairs = cursorConfig.autoClosingPairs.autoClosingPairsOpenByEnd.get(ch);
                    const autoClosingPairExists = autoClosingPairs && autoClosingPairs.length > 0;
                    const isChFirstNonWhitespaceCharacterAndInAutoClosingPair = autoClosingPairExists && textAroundRangeContainsOnlyWhitespace;
                    if (inferredIndentationEqualsActual && isChFirstNonWhitespaceCharacterAndInAutoClosingPair) {
                        return inheritedIndentation;
                    }
                }
            }
        }
        return null;
    }
    function getIndentMetadata(model, lineNumber, languageConfigurationService) {
        const indentRulesSupport = languageConfigurationService.getLanguageConfiguration(model.getLanguageId()).indentRulesSupport;
        if (!indentRulesSupport) {
            return null;
        }
        if (lineNumber < 1 || lineNumber > model.getLineCount()) {
            return null;
        }
        return indentRulesSupport.getIndentMetadata(model.getLineContent(lineNumber));
    }
    function createVirtualModelWithModifiedTokensAtLine(model, modifiedLineNumber, modifiedTokens) {
        const virtualModel = {
            tokenization: {
                getLineTokens: (lineNumber) => {
                    if (lineNumber === modifiedLineNumber) {
                        return modifiedTokens;
                    }
                    else {
                        return model.tokenization.getLineTokens(lineNumber);
                    }
                },
                getLanguageId: () => {
                    return model.getLanguageId();
                },
                getLanguageIdAtPosition: (lineNumber, column) => {
                    return model.getLanguageIdAtPosition(lineNumber, column);
                },
            },
            getLineContent: (lineNumber) => {
                if (lineNumber === modifiedLineNumber) {
                    return modifiedTokens.getLineContent();
                }
                else {
                    return model.getLineContent(lineNumber);
                }
            }
        };
        return virtualModel;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[587/*vs/editor/common/tokens/contiguousTokensEditing*/], __M([1/*require*/,0/*exports*/,83/*vs/editor/common/tokens/lineTokens*/]), function (require, exports, lineTokens_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ContiguousTokensEditing = exports.EMPTY_LINE_TOKENS = void 0;
    exports.toUint32Array = toUint32Array;
    exports.EMPTY_LINE_TOKENS = (new Uint32Array(0)).buffer;
    class ContiguousTokensEditing {
        static deleteBeginning(lineTokens, toChIndex) {
            if (lineTokens === null || lineTokens === exports.EMPTY_LINE_TOKENS) {
                return lineTokens;
            }
            return ContiguousTokensEditing.delete(lineTokens, 0, toChIndex);
        }
        static deleteEnding(lineTokens, fromChIndex) {
            if (lineTokens === null || lineTokens === exports.EMPTY_LINE_TOKENS) {
                return lineTokens;
            }
            const tokens = toUint32Array(lineTokens);
            const lineTextLength = tokens[tokens.length - 2];
            return ContiguousTokensEditing.delete(lineTokens, fromChIndex, lineTextLength);
        }
        static delete(lineTokens, fromChIndex, toChIndex) {
            if (lineTokens === null || lineTokens === exports.EMPTY_LINE_TOKENS || fromChIndex === toChIndex) {
                return lineTokens;
            }
            const tokens = toUint32Array(lineTokens);
            const tokensCount = (tokens.length >>> 1);
            // special case: deleting everything
            if (fromChIndex === 0 && tokens[tokens.length - 2] === toChIndex) {
                return exports.EMPTY_LINE_TOKENS;
            }
            const fromTokenIndex = lineTokens_1.LineTokens.findIndexInTokensArray(tokens, fromChIndex);
            const fromTokenStartOffset = (fromTokenIndex > 0 ? tokens[(fromTokenIndex - 1) << 1] : 0);
            const fromTokenEndOffset = tokens[fromTokenIndex << 1];
            if (toChIndex < fromTokenEndOffset) {
                // the delete range is inside a single token
                const delta = (toChIndex - fromChIndex);
                for (let i = fromTokenIndex; i < tokensCount; i++) {
                    tokens[i << 1] -= delta;
                }
                return lineTokens;
            }
            let dest;
            let lastEnd;
            if (fromTokenStartOffset !== fromChIndex) {
                tokens[fromTokenIndex << 1] = fromChIndex;
                dest = ((fromTokenIndex + 1) << 1);
                lastEnd = fromChIndex;
            }
            else {
                dest = (fromTokenIndex << 1);
                lastEnd = fromTokenStartOffset;
            }
            const delta = (toChIndex - fromChIndex);
            for (let tokenIndex = fromTokenIndex + 1; tokenIndex < tokensCount; tokenIndex++) {
                const tokenEndOffset = tokens[tokenIndex << 1] - delta;
                if (tokenEndOffset > lastEnd) {
                    tokens[dest++] = tokenEndOffset;
                    tokens[dest++] = tokens[(tokenIndex << 1) + 1];
                    lastEnd = tokenEndOffset;
                }
            }
            if (dest === tokens.length) {
                // nothing to trim
                return lineTokens;
            }
            const tmp = new Uint32Array(dest);
            tmp.set(tokens.subarray(0, dest), 0);
            return tmp.buffer;
        }
        static append(lineTokens, _otherTokens) {
            if (_otherTokens === exports.EMPTY_LINE_TOKENS) {
                return lineTokens;
            }
            if (lineTokens === exports.EMPTY_LINE_TOKENS) {
                return _otherTokens;
            }
            if (lineTokens === null) {
                return lineTokens;
            }
            if (_otherTokens === null) {
                // cannot determine combined line length...
                return null;
            }
            const myTokens = toUint32Array(lineTokens);
            const otherTokens = toUint32Array(_otherTokens);
            const otherTokensCount = (otherTokens.length >>> 1);
            const result = new Uint32Array(myTokens.length + otherTokens.length);
            result.set(myTokens, 0);
            let dest = myTokens.length;
            const delta = myTokens[myTokens.length - 2];
            for (let i = 0; i < otherTokensCount; i++) {
                result[dest++] = otherTokens[(i << 1)] + delta;
                result[dest++] = otherTokens[(i << 1) + 1];
            }
            return result.buffer;
        }
        static insert(lineTokens, chIndex, textLength) {
            if (lineTokens === null || lineTokens === exports.EMPTY_LINE_TOKENS) {
                // nothing to do
                return lineTokens;
            }
            const tokens = toUint32Array(lineTokens);
            const tokensCount = (tokens.length >>> 1);
            let fromTokenIndex = lineTokens_1.LineTokens.findIndexInTokensArray(tokens, chIndex);
            if (fromTokenIndex > 0) {
                const fromTokenStartOffset = tokens[(fromTokenIndex - 1) << 1];
                if (fromTokenStartOffset === chIndex) {
                    fromTokenIndex--;
                }
            }
            for (let tokenIndex = fromTokenIndex; tokenIndex < tokensCount; tokenIndex++) {
                tokens[tokenIndex << 1] += textLength;
            }
            return lineTokens;
        }
    }
    exports.ContiguousTokensEditing = ContiguousTokensEditing;
    function toUint32Array(arr) {
        if (arr instanceof Uint32Array) {
            return arr;
        }
        else {
            return new Uint32Array(arr);
        }
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[588/*vs/editor/common/tokens/contiguousTokensStore*/], __M([1/*require*/,0/*exports*/,13/*vs/base/common/arrays*/,9/*vs/editor/common/core/position*/,587/*vs/editor/common/tokens/contiguousTokensEditing*/,83/*vs/editor/common/tokens/lineTokens*/,148/*vs/editor/common/encodedTokenAttributes*/]), function (require, exports, arrays, position_1, contiguousTokensEditing_1, lineTokens_1, encodedTokenAttributes_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ContiguousTokensStore = void 0;
    /**
     * Represents contiguous tokens in a text model.
     */
    class ContiguousTokensStore {
        constructor(languageIdCodec) {
            this._lineTokens = [];
            this._len = 0;
            this._languageIdCodec = languageIdCodec;
        }
        flush() {
            this._lineTokens = [];
            this._len = 0;
        }
        get hasTokens() {
            return this._lineTokens.length > 0;
        }
        getTokens(topLevelLanguageId, lineIndex, lineText) {
            let rawLineTokens = null;
            if (lineIndex < this._len) {
                rawLineTokens = this._lineTokens[lineIndex];
            }
            if (rawLineTokens !== null && rawLineTokens !== contiguousTokensEditing_1.EMPTY_LINE_TOKENS) {
                return new lineTokens_1.LineTokens((0, contiguousTokensEditing_1.toUint32Array)(rawLineTokens), lineText, this._languageIdCodec);
            }
            const lineTokens = new Uint32Array(2);
            lineTokens[0] = lineText.length;
            lineTokens[1] = getDefaultMetadata(this._languageIdCodec.encodeLanguageId(topLevelLanguageId));
            return new lineTokens_1.LineTokens(lineTokens, lineText, this._languageIdCodec);
        }
        static _massageTokens(topLevelLanguageId, lineTextLength, _tokens) {
            const tokens = _tokens ? (0, contiguousTokensEditing_1.toUint32Array)(_tokens) : null;
            if (lineTextLength === 0) {
                let hasDifferentLanguageId = false;
                if (tokens && tokens.length > 1) {
                    hasDifferentLanguageId = (encodedTokenAttributes_1.TokenMetadata.getLanguageId(tokens[1]) !== topLevelLanguageId);
                }
                if (!hasDifferentLanguageId) {
                    return contiguousTokensEditing_1.EMPTY_LINE_TOKENS;
                }
            }
            if (!tokens || tokens.length === 0) {
                const tokens = new Uint32Array(2);
                tokens[0] = lineTextLength;
                tokens[1] = getDefaultMetadata(topLevelLanguageId);
                return tokens.buffer;
            }
            // Ensure the last token covers the end of the text
            tokens[tokens.length - 2] = lineTextLength;
            if (tokens.byteOffset === 0 && tokens.byteLength === tokens.buffer.byteLength) {
                // Store directly the ArrayBuffer pointer to save an object
                return tokens.buffer;
            }
            return tokens;
        }
        _ensureLine(lineIndex) {
            while (lineIndex >= this._len) {
                this._lineTokens[this._len] = null;
                this._len++;
            }
        }
        _deleteLines(start, deleteCount) {
            if (deleteCount === 0) {
                return;
            }
            if (start + deleteCount > this._len) {
                deleteCount = this._len - start;
            }
            this._lineTokens.splice(start, deleteCount);
            this._len -= deleteCount;
        }
        _insertLines(insertIndex, insertCount) {
            if (insertCount === 0) {
                return;
            }
            const lineTokens = [];
            for (let i = 0; i < insertCount; i++) {
                lineTokens[i] = null;
            }
            this._lineTokens = arrays.arrayInsert(this._lineTokens, insertIndex, lineTokens);
            this._len += insertCount;
        }
        setTokens(topLevelLanguageId, lineIndex, lineTextLength, _tokens, checkEquality) {
            const tokens = ContiguousTokensStore._massageTokens(this._languageIdCodec.encodeLanguageId(topLevelLanguageId), lineTextLength, _tokens);
            this._ensureLine(lineIndex);
            const oldTokens = this._lineTokens[lineIndex];
            this._lineTokens[lineIndex] = tokens;
            if (checkEquality) {
                return !ContiguousTokensStore._equals(oldTokens, tokens);
            }
            return false;
        }
        static _equals(_a, _b) {
            if (!_a || !_b) {
                return !_a && !_b;
            }
            const a = (0, contiguousTokensEditing_1.toUint32Array)(_a);
            const b = (0, contiguousTokensEditing_1.toUint32Array)(_b);
            if (a.length !== b.length) {
                return false;
            }
            for (let i = 0, len = a.length; i < len; i++) {
                if (a[i] !== b[i]) {
                    return false;
                }
            }
            return true;
        }
        //#region Editing
        acceptEdit(range, eolCount, firstLineLength) {
            this._acceptDeleteRange(range);
            this._acceptInsertText(new position_1.Position(range.startLineNumber, range.startColumn), eolCount, firstLineLength);
        }
        _acceptDeleteRange(range) {
            const firstLineIndex = range.startLineNumber - 1;
            if (firstLineIndex >= this._len) {
                return;
            }
            if (range.startLineNumber === range.endLineNumber) {
                if (range.startColumn === range.endColumn) {
                    // Nothing to delete
                    return;
                }
                this._lineTokens[firstLineIndex] = contiguousTokensEditing_1.ContiguousTokensEditing.delete(this._lineTokens[firstLineIndex], range.startColumn - 1, range.endColumn - 1);
                return;
            }
            this._lineTokens[firstLineIndex] = contiguousTokensEditing_1.ContiguousTokensEditing.deleteEnding(this._lineTokens[firstLineIndex], range.startColumn - 1);
            const lastLineIndex = range.endLineNumber - 1;
            let lastLineTokens = null;
            if (lastLineIndex < this._len) {
                lastLineTokens = contiguousTokensEditing_1.ContiguousTokensEditing.deleteBeginning(this._lineTokens[lastLineIndex], range.endColumn - 1);
            }
            // Take remaining text on last line and append it to remaining text on first line
            this._lineTokens[firstLineIndex] = contiguousTokensEditing_1.ContiguousTokensEditing.append(this._lineTokens[firstLineIndex], lastLineTokens);
            // Delete middle lines
            this._deleteLines(range.startLineNumber, range.endLineNumber - range.startLineNumber);
        }
        _acceptInsertText(position, eolCount, firstLineLength) {
            if (eolCount === 0 && firstLineLength === 0) {
                // Nothing to insert
                return;
            }
            const lineIndex = position.lineNumber - 1;
            if (lineIndex >= this._len) {
                return;
            }
            if (eolCount === 0) {
                // Inserting text on one line
                this._lineTokens[lineIndex] = contiguousTokensEditing_1.ContiguousTokensEditing.insert(this._lineTokens[lineIndex], position.column - 1, firstLineLength);
                return;
            }
            this._lineTokens[lineIndex] = contiguousTokensEditing_1.ContiguousTokensEditing.deleteEnding(this._lineTokens[lineIndex], position.column - 1);
            this._lineTokens[lineIndex] = contiguousTokensEditing_1.ContiguousTokensEditing.insert(this._lineTokens[lineIndex], position.column - 1, firstLineLength);
            this._insertLines(position.lineNumber, eolCount);
        }
        //#endregion
        setMultilineTokens(tokens, textModel) {
            if (tokens.length === 0) {
                return { changes: [] };
            }
            const ranges = [];
            for (let i = 0, len = tokens.length; i < len; i++) {
                const element = tokens[i];
                let minChangedLineNumber = 0;
                let maxChangedLineNumber = 0;
                let hasChange = false;
                for (let lineNumber = element.startLineNumber; lineNumber <= element.endLineNumber; lineNumber++) {
                    if (hasChange) {
                        this.setTokens(textModel.getLanguageId(), lineNumber - 1, textModel.getLineLength(lineNumber), element.getLineTokens(lineNumber), false);
                        maxChangedLineNumber = lineNumber;
                    }
                    else {
                        const lineHasChange = this.setTokens(textModel.getLanguageId(), lineNumber - 1, textModel.getLineLength(lineNumber), element.getLineTokens(lineNumber), true);
                        if (lineHasChange) {
                            hasChange = true;
                            minChangedLineNumber = lineNumber;
                            maxChangedLineNumber = lineNumber;
                        }
                    }
                }
                if (hasChange) {
                    ranges.push({ fromLineNumber: minChangedLineNumber, toLineNumber: maxChangedLineNumber, });
                }
            }
            return { changes: ranges };
        }
    }
    exports.ContiguousTokensStore = ContiguousTokensStore;
    function getDefaultMetadata(topLevelLanguageId) {
        return ((topLevelLanguageId << 0 /* MetadataConsts.LANGUAGEID_OFFSET */)
            | (0 /* StandardTokenType.Other */ << 8 /* MetadataConsts.TOKEN_TYPE_OFFSET */)
            | (0 /* FontStyle.None */ << 11 /* MetadataConsts.FONT_STYLE_OFFSET */)
            | (1 /* ColorId.DefaultForeground */ << 15 /* MetadataConsts.FOREGROUND_OFFSET */)
            | (2 /* ColorId.DefaultBackground */ << 24 /* MetadataConsts.BACKGROUND_OFFSET */)
            // If there is no grammar, we just take a guess and try to match brackets.
            | (1024 /* MetadataConsts.BALANCED_BRACKETS_MASK */)) >>> 0;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[589/*vs/editor/common/tokens/sparseMultilineTokens*/], __M([1/*require*/,0/*exports*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/,145/*vs/editor/common/core/eolCounter*/]), function (require, exports, position_1, range_1, eolCounter_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SparseLineTokens = exports.SparseMultilineTokens = void 0;
    /**
     * Represents sparse tokens over a contiguous range of lines.
     */
    class SparseMultilineTokens {
        static create(startLineNumber, tokens) {
            return new SparseMultilineTokens(startLineNumber, new SparseMultilineTokensStorage(tokens));
        }
        /**
         * (Inclusive) start line number for these tokens.
         */
        get startLineNumber() {
            return this._startLineNumber;
        }
        /**
         * (Inclusive) end line number for these tokens.
         */
        get endLineNumber() {
            return this._endLineNumber;
        }
        constructor(startLineNumber, tokens) {
            this._startLineNumber = startLineNumber;
            this._tokens = tokens;
            this._endLineNumber = this._startLineNumber + this._tokens.getMaxDeltaLine();
        }
        toString() {
            return this._tokens.toString(this._startLineNumber);
        }
        _updateEndLineNumber() {
            this._endLineNumber = this._startLineNumber + this._tokens.getMaxDeltaLine();
        }
        isEmpty() {
            return this._tokens.isEmpty();
        }
        getLineTokens(lineNumber) {
            if (this._startLineNumber <= lineNumber && lineNumber <= this._endLineNumber) {
                return this._tokens.getLineTokens(lineNumber - this._startLineNumber);
            }
            return null;
        }
        getRange() {
            const deltaRange = this._tokens.getRange();
            if (!deltaRange) {
                return deltaRange;
            }
            return new range_1.Range(this._startLineNumber + deltaRange.startLineNumber, deltaRange.startColumn, this._startLineNumber + deltaRange.endLineNumber, deltaRange.endColumn);
        }
        removeTokens(range) {
            const startLineIndex = range.startLineNumber - this._startLineNumber;
            const endLineIndex = range.endLineNumber - this._startLineNumber;
            this._startLineNumber += this._tokens.removeTokens(startLineIndex, range.startColumn - 1, endLineIndex, range.endColumn - 1);
            this._updateEndLineNumber();
        }
        split(range) {
            // split tokens to two:
            // a) all the tokens before `range`
            // b) all the tokens after `range`
            const startLineIndex = range.startLineNumber - this._startLineNumber;
            const endLineIndex = range.endLineNumber - this._startLineNumber;
            const [a, b, bDeltaLine] = this._tokens.split(startLineIndex, range.startColumn - 1, endLineIndex, range.endColumn - 1);
            return [new SparseMultilineTokens(this._startLineNumber, a), new SparseMultilineTokens(this._startLineNumber + bDeltaLine, b)];
        }
        applyEdit(range, text) {
            const [eolCount, firstLineLength, lastLineLength] = (0, eolCounter_1.countEOL)(text);
            this.acceptEdit(range, eolCount, firstLineLength, lastLineLength, text.length > 0 ? text.charCodeAt(0) : 0 /* CharCode.Null */);
        }
        acceptEdit(range, eolCount, firstLineLength, lastLineLength, firstCharCode) {
            this._acceptDeleteRange(range);
            this._acceptInsertText(new position_1.Position(range.startLineNumber, range.startColumn), eolCount, firstLineLength, lastLineLength, firstCharCode);
            this._updateEndLineNumber();
        }
        _acceptDeleteRange(range) {
            if (range.startLineNumber === range.endLineNumber && range.startColumn === range.endColumn) {
                // Nothing to delete
                return;
            }
            const firstLineIndex = range.startLineNumber - this._startLineNumber;
            const lastLineIndex = range.endLineNumber - this._startLineNumber;
            if (lastLineIndex < 0) {
                // this deletion occurs entirely before this block, so we only need to adjust line numbers
                const deletedLinesCount = lastLineIndex - firstLineIndex;
                this._startLineNumber -= deletedLinesCount;
                return;
            }
            const tokenMaxDeltaLine = this._tokens.getMaxDeltaLine();
            if (firstLineIndex >= tokenMaxDeltaLine + 1) {
                // this deletion occurs entirely after this block, so there is nothing to do
                return;
            }
            if (firstLineIndex < 0 && lastLineIndex >= tokenMaxDeltaLine + 1) {
                // this deletion completely encompasses this block
                this._startLineNumber = 0;
                this._tokens.clear();
                return;
            }
            if (firstLineIndex < 0) {
                const deletedBefore = -firstLineIndex;
                this._startLineNumber -= deletedBefore;
                this._tokens.acceptDeleteRange(range.startColumn - 1, 0, 0, lastLineIndex, range.endColumn - 1);
            }
            else {
                this._tokens.acceptDeleteRange(0, firstLineIndex, range.startColumn - 1, lastLineIndex, range.endColumn - 1);
            }
        }
        _acceptInsertText(position, eolCount, firstLineLength, lastLineLength, firstCharCode) {
            if (eolCount === 0 && firstLineLength === 0) {
                // Nothing to insert
                return;
            }
            const lineIndex = position.lineNumber - this._startLineNumber;
            if (lineIndex < 0) {
                // this insertion occurs before this block, so we only need to adjust line numbers
                this._startLineNumber += eolCount;
                return;
            }
            const tokenMaxDeltaLine = this._tokens.getMaxDeltaLine();
            if (lineIndex >= tokenMaxDeltaLine + 1) {
                // this insertion occurs after this block, so there is nothing to do
                return;
            }
            this._tokens.acceptInsertText(lineIndex, position.column - 1, eolCount, firstLineLength, lastLineLength, firstCharCode);
        }
    }
    exports.SparseMultilineTokens = SparseMultilineTokens;
    class SparseMultilineTokensStorage {
        constructor(tokens) {
            this._tokens = tokens;
            this._tokenCount = tokens.length / 4;
        }
        toString(startLineNumber) {
            const pieces = [];
            for (let i = 0; i < this._tokenCount; i++) {
                pieces.push(`(${this._getDeltaLine(i) + startLineNumber},${this._getStartCharacter(i)}-${this._getEndCharacter(i)})`);
            }
            return `[${pieces.join(',')}]`;
        }
        getMaxDeltaLine() {
            const tokenCount = this._getTokenCount();
            if (tokenCount === 0) {
                return -1;
            }
            return this._getDeltaLine(tokenCount - 1);
        }
        getRange() {
            const tokenCount = this._getTokenCount();
            if (tokenCount === 0) {
                return null;
            }
            const startChar = this._getStartCharacter(0);
            const maxDeltaLine = this._getDeltaLine(tokenCount - 1);
            const endChar = this._getEndCharacter(tokenCount - 1);
            return new range_1.Range(0, startChar + 1, maxDeltaLine, endChar + 1);
        }
        _getTokenCount() {
            return this._tokenCount;
        }
        _getDeltaLine(tokenIndex) {
            return this._tokens[4 * tokenIndex];
        }
        _getStartCharacter(tokenIndex) {
            return this._tokens[4 * tokenIndex + 1];
        }
        _getEndCharacter(tokenIndex) {
            return this._tokens[4 * tokenIndex + 2];
        }
        isEmpty() {
            return (this._getTokenCount() === 0);
        }
        getLineTokens(deltaLine) {
            let low = 0;
            let high = this._getTokenCount() - 1;
            while (low < high) {
                const mid = low + Math.floor((high - low) / 2);
                const midDeltaLine = this._getDeltaLine(mid);
                if (midDeltaLine < deltaLine) {
                    low = mid + 1;
                }
                else if (midDeltaLine > deltaLine) {
                    high = mid - 1;
                }
                else {
                    let min = mid;
                    while (min > low && this._getDeltaLine(min - 1) === deltaLine) {
                        min--;
                    }
                    let max = mid;
                    while (max < high && this._getDeltaLine(max + 1) === deltaLine) {
                        max++;
                    }
                    return new SparseLineTokens(this._tokens.subarray(4 * min, 4 * max + 4));
                }
            }
            if (this._getDeltaLine(low) === deltaLine) {
                return new SparseLineTokens(this._tokens.subarray(4 * low, 4 * low + 4));
            }
            return null;
        }
        clear() {
            this._tokenCount = 0;
        }
        removeTokens(startDeltaLine, startChar, endDeltaLine, endChar) {
            const tokens = this._tokens;
            const tokenCount = this._tokenCount;
            let newTokenCount = 0;
            let hasDeletedTokens = false;
            let firstDeltaLine = 0;
            for (let i = 0; i < tokenCount; i++) {
                const srcOffset = 4 * i;
                const tokenDeltaLine = tokens[srcOffset];
                const tokenStartCharacter = tokens[srcOffset + 1];
                const tokenEndCharacter = tokens[srcOffset + 2];
                const tokenMetadata = tokens[srcOffset + 3];
                if ((tokenDeltaLine > startDeltaLine || (tokenDeltaLine === startDeltaLine && tokenEndCharacter >= startChar))
                    && (tokenDeltaLine < endDeltaLine || (tokenDeltaLine === endDeltaLine && tokenStartCharacter <= endChar))) {
                    hasDeletedTokens = true;
                }
                else {
                    if (newTokenCount === 0) {
                        firstDeltaLine = tokenDeltaLine;
                    }
                    if (hasDeletedTokens) {
                        // must move the token to the left
                        const destOffset = 4 * newTokenCount;
                        tokens[destOffset] = tokenDeltaLine - firstDeltaLine;
                        tokens[destOffset + 1] = tokenStartCharacter;
                        tokens[destOffset + 2] = tokenEndCharacter;
                        tokens[destOffset + 3] = tokenMetadata;
                    }
                    newTokenCount++;
                }
            }
            this._tokenCount = newTokenCount;
            return firstDeltaLine;
        }
        split(startDeltaLine, startChar, endDeltaLine, endChar) {
            const tokens = this._tokens;
            const tokenCount = this._tokenCount;
            const aTokens = [];
            const bTokens = [];
            let destTokens = aTokens;
            let destOffset = 0;
            let destFirstDeltaLine = 0;
            for (let i = 0; i < tokenCount; i++) {
                const srcOffset = 4 * i;
                const tokenDeltaLine = tokens[srcOffset];
                const tokenStartCharacter = tokens[srcOffset + 1];
                const tokenEndCharacter = tokens[srcOffset + 2];
                const tokenMetadata = tokens[srcOffset + 3];
                if ((tokenDeltaLine > startDeltaLine || (tokenDeltaLine === startDeltaLine && tokenEndCharacter >= startChar))) {
                    if ((tokenDeltaLine < endDeltaLine || (tokenDeltaLine === endDeltaLine && tokenStartCharacter <= endChar))) {
                        // this token is touching the range
                        continue;
                    }
                    else {
                        // this token is after the range
                        if (destTokens !== bTokens) {
                            // this token is the first token after the range
                            destTokens = bTokens;
                            destOffset = 0;
                            destFirstDeltaLine = tokenDeltaLine;
                        }
                    }
                }
                destTokens[destOffset++] = tokenDeltaLine - destFirstDeltaLine;
                destTokens[destOffset++] = tokenStartCharacter;
                destTokens[destOffset++] = tokenEndCharacter;
                destTokens[destOffset++] = tokenMetadata;
            }
            return [new SparseMultilineTokensStorage(new Uint32Array(aTokens)), new SparseMultilineTokensStorage(new Uint32Array(bTokens)), destFirstDeltaLine];
        }
        acceptDeleteRange(horizontalShiftForFirstLineTokens, startDeltaLine, startCharacter, endDeltaLine, endCharacter) {
            // This is a bit complex, here are the cases I used to think about this:
            //
            // 1. The token starts before the deletion range
            // 1a. The token is completely before the deletion range
            //               -----------
            //                          xxxxxxxxxxx
            // 1b. The token starts before, the deletion range ends after the token
            //               -----------
            //                      xxxxxxxxxxx
            // 1c. The token starts before, the deletion range ends precisely with the token
            //               ---------------
            //                      xxxxxxxx
            // 1d. The token starts before, the deletion range is inside the token
            //               ---------------
            //                    xxxxx
            //
            // 2. The token starts at the same position with the deletion range
            // 2a. The token starts at the same position, and ends inside the deletion range
            //               -------
            //               xxxxxxxxxxx
            // 2b. The token starts at the same position, and ends at the same position as the deletion range
            //               ----------
            //               xxxxxxxxxx
            // 2c. The token starts at the same position, and ends after the deletion range
            //               -------------
            //               xxxxxxx
            //
            // 3. The token starts inside the deletion range
            // 3a. The token is inside the deletion range
            //                -------
            //             xxxxxxxxxxxxx
            // 3b. The token starts inside the deletion range, and ends at the same position as the deletion range
            //                ----------
            //             xxxxxxxxxxxxx
            // 3c. The token starts inside the deletion range, and ends after the deletion range
            //                ------------
            //             xxxxxxxxxxx
            //
            // 4. The token starts after the deletion range
            //                  -----------
            //          xxxxxxxx
            //
            const tokens = this._tokens;
            const tokenCount = this._tokenCount;
            const deletedLineCount = (endDeltaLine - startDeltaLine);
            let newTokenCount = 0;
            let hasDeletedTokens = false;
            for (let i = 0; i < tokenCount; i++) {
                const srcOffset = 4 * i;
                let tokenDeltaLine = tokens[srcOffset];
                let tokenStartCharacter = tokens[srcOffset + 1];
                let tokenEndCharacter = tokens[srcOffset + 2];
                const tokenMetadata = tokens[srcOffset + 3];
                if (tokenDeltaLine < startDeltaLine || (tokenDeltaLine === startDeltaLine && tokenEndCharacter <= startCharacter)) {
                    // 1a. The token is completely before the deletion range
                    // => nothing to do
                    newTokenCount++;
                    continue;
                }
                else if (tokenDeltaLine === startDeltaLine && tokenStartCharacter < startCharacter) {
                    // 1b, 1c, 1d
                    // => the token survives, but it needs to shrink
                    if (tokenDeltaLine === endDeltaLine && tokenEndCharacter > endCharacter) {
                        // 1d. The token starts before, the deletion range is inside the token
                        // => the token shrinks by the deletion character count
                        tokenEndCharacter -= (endCharacter - startCharacter);
                    }
                    else {
                        // 1b. The token starts before, the deletion range ends after the token
                        // 1c. The token starts before, the deletion range ends precisely with the token
                        // => the token shrinks its ending to the deletion start
                        tokenEndCharacter = startCharacter;
                    }
                }
                else if (tokenDeltaLine === startDeltaLine && tokenStartCharacter === startCharacter) {
                    // 2a, 2b, 2c
                    if (tokenDeltaLine === endDeltaLine && tokenEndCharacter > endCharacter) {
                        // 2c. The token starts at the same position, and ends after the deletion range
                        // => the token shrinks by the deletion character count
                        tokenEndCharacter -= (endCharacter - startCharacter);
                    }
                    else {
                        // 2a. The token starts at the same position, and ends inside the deletion range
                        // 2b. The token starts at the same position, and ends at the same position as the deletion range
                        // => the token is deleted
                        hasDeletedTokens = true;
                        continue;
                    }
                }
                else if (tokenDeltaLine < endDeltaLine || (tokenDeltaLine === endDeltaLine && tokenStartCharacter < endCharacter)) {
                    // 3a, 3b, 3c
                    if (tokenDeltaLine === endDeltaLine && tokenEndCharacter > endCharacter) {
                        // 3c. The token starts inside the deletion range, and ends after the deletion range
                        // => the token moves to continue right after the deletion
                        tokenDeltaLine = startDeltaLine;
                        tokenStartCharacter = startCharacter;
                        tokenEndCharacter = tokenStartCharacter + (tokenEndCharacter - endCharacter);
                    }
                    else {
                        // 3a. The token is inside the deletion range
                        // 3b. The token starts inside the deletion range, and ends at the same position as the deletion range
                        // => the token is deleted
                        hasDeletedTokens = true;
                        continue;
                    }
                }
                else if (tokenDeltaLine > endDeltaLine) {
                    // 4. (partial) The token starts after the deletion range, on a line below...
                    if (deletedLineCount === 0 && !hasDeletedTokens) {
                        // early stop, there is no need to walk all the tokens and do nothing...
                        newTokenCount = tokenCount;
                        break;
                    }
                    tokenDeltaLine -= deletedLineCount;
                }
                else if (tokenDeltaLine === endDeltaLine && tokenStartCharacter >= endCharacter) {
                    // 4. (continued) The token starts after the deletion range, on the last line where a deletion occurs
                    if (horizontalShiftForFirstLineTokens && tokenDeltaLine === 0) {
                        tokenStartCharacter += horizontalShiftForFirstLineTokens;
                        tokenEndCharacter += horizontalShiftForFirstLineTokens;
                    }
                    tokenDeltaLine -= deletedLineCount;
                    tokenStartCharacter -= (endCharacter - startCharacter);
                    tokenEndCharacter -= (endCharacter - startCharacter);
                }
                else {
                    throw new Error(`Not possible!`);
                }
                const destOffset = 4 * newTokenCount;
                tokens[destOffset] = tokenDeltaLine;
                tokens[destOffset + 1] = tokenStartCharacter;
                tokens[destOffset + 2] = tokenEndCharacter;
                tokens[destOffset + 3] = tokenMetadata;
                newTokenCount++;
            }
            this._tokenCount = newTokenCount;
        }
        acceptInsertText(deltaLine, character, eolCount, firstLineLength, lastLineLength, firstCharCode) {
            // Here are the cases I used to think about this:
            //
            // 1. The token is completely before the insertion point
            //            -----------   |
            // 2. The token ends precisely at the insertion point
            //            -----------|
            // 3. The token contains the insertion point
            //            -----|------
            // 4. The token starts precisely at the insertion point
            //            |-----------
            // 5. The token is completely after the insertion point
            //            |   -----------
            //
            const isInsertingPreciselyOneWordCharacter = (eolCount === 0
                && firstLineLength === 1
                && ((firstCharCode >= 48 /* CharCode.Digit0 */ && firstCharCode <= 57 /* CharCode.Digit9 */)
                    || (firstCharCode >= 65 /* CharCode.A */ && firstCharCode <= 90 /* CharCode.Z */)
                    || (firstCharCode >= 97 /* CharCode.a */ && firstCharCode <= 122 /* CharCode.z */)));
            const tokens = this._tokens;
            const tokenCount = this._tokenCount;
            for (let i = 0; i < tokenCount; i++) {
                const offset = 4 * i;
                let tokenDeltaLine = tokens[offset];
                let tokenStartCharacter = tokens[offset + 1];
                let tokenEndCharacter = tokens[offset + 2];
                if (tokenDeltaLine < deltaLine || (tokenDeltaLine === deltaLine && tokenEndCharacter < character)) {
                    // 1. The token is completely before the insertion point
                    // => nothing to do
                    continue;
                }
                else if (tokenDeltaLine === deltaLine && tokenEndCharacter === character) {
                    // 2. The token ends precisely at the insertion point
                    // => expand the end character only if inserting precisely one character that is a word character
                    if (isInsertingPreciselyOneWordCharacter) {
                        tokenEndCharacter += 1;
                    }
                    else {
                        continue;
                    }
                }
                else if (tokenDeltaLine === deltaLine && tokenStartCharacter < character && character < tokenEndCharacter) {
                    // 3. The token contains the insertion point
                    if (eolCount === 0) {
                        // => just expand the end character
                        tokenEndCharacter += firstLineLength;
                    }
                    else {
                        // => cut off the token
                        tokenEndCharacter = character;
                    }
                }
                else {
                    // 4. or 5.
                    if (tokenDeltaLine === deltaLine && tokenStartCharacter === character) {
                        // 4. The token starts precisely at the insertion point
                        // => grow the token (by keeping its start constant) only if inserting precisely one character that is a word character
                        // => otherwise behave as in case 5.
                        if (isInsertingPreciselyOneWordCharacter) {
                            continue;
                        }
                    }
                    // => the token must move and keep its size constant
                    if (tokenDeltaLine === deltaLine) {
                        tokenDeltaLine += eolCount;
                        // this token is on the line where the insertion is taking place
                        if (eolCount === 0) {
                            tokenStartCharacter += firstLineLength;
                            tokenEndCharacter += firstLineLength;
                        }
                        else {
                            const tokenLength = tokenEndCharacter - tokenStartCharacter;
                            tokenStartCharacter = lastLineLength + (tokenStartCharacter - character);
                            tokenEndCharacter = tokenStartCharacter + tokenLength;
                        }
                    }
                    else {
                        tokenDeltaLine += eolCount;
                    }
                }
                tokens[offset] = tokenDeltaLine;
                tokens[offset + 1] = tokenStartCharacter;
                tokens[offset + 2] = tokenEndCharacter;
            }
        }
    }
    class SparseLineTokens {
        constructor(tokens) {
            this._tokens = tokens;
        }
        getCount() {
            return this._tokens.length / 4;
        }
        getStartCharacter(tokenIndex) {
            return this._tokens[4 * tokenIndex + 1];
        }
        getEndCharacter(tokenIndex) {
            return this._tokens[4 * tokenIndex + 2];
        }
        getMetadata(tokenIndex) {
            return this._tokens[4 * tokenIndex + 3];
        }
    }
    exports.SparseLineTokens = SparseLineTokens;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[590/*vs/editor/common/tokens/sparseTokensStore*/], __M([1/*require*/,0/*exports*/,13/*vs/base/common/arrays*/,83/*vs/editor/common/tokens/lineTokens*/]), function (require, exports, arrays, lineTokens_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SparseTokensStore = void 0;
    /**
     * Represents sparse tokens in a text model.
     */
    class SparseTokensStore {
        constructor(languageIdCodec) {
            this._pieces = [];
            this._isComplete = false;
            this._languageIdCodec = languageIdCodec;
        }
        flush() {
            this._pieces = [];
            this._isComplete = false;
        }
        isEmpty() {
            return (this._pieces.length === 0);
        }
        set(pieces, isComplete) {
            this._pieces = pieces || [];
            this._isComplete = isComplete;
        }
        setPartial(_range, pieces) {
            // console.log(`setPartial ${_range} ${pieces.map(p => p.toString()).join(', ')}`);
            let range = _range;
            if (pieces.length > 0) {
                const _firstRange = pieces[0].getRange();
                const _lastRange = pieces[pieces.length - 1].getRange();
                if (!_firstRange || !_lastRange) {
                    return _range;
                }
                range = _range.plusRange(_firstRange).plusRange(_lastRange);
            }
            let insertPosition = null;
            for (let i = 0, len = this._pieces.length; i < len; i++) {
                const piece = this._pieces[i];
                if (piece.endLineNumber < range.startLineNumber) {
                    // this piece is before the range
                    continue;
                }
                if (piece.startLineNumber > range.endLineNumber) {
                    // this piece is after the range, so mark the spot before this piece
                    // as a good insertion position and stop looping
                    insertPosition = insertPosition || { index: i };
                    break;
                }
                // this piece might intersect with the range
                piece.removeTokens(range);
                if (piece.isEmpty()) {
                    // remove the piece if it became empty
                    this._pieces.splice(i, 1);
                    i--;
                    len--;
                    continue;
                }
                if (piece.endLineNumber < range.startLineNumber) {
                    // after removal, this piece is before the range
                    continue;
                }
                if (piece.startLineNumber > range.endLineNumber) {
                    // after removal, this piece is after the range
                    insertPosition = insertPosition || { index: i };
                    continue;
                }
                // after removal, this piece contains the range
                const [a, b] = piece.split(range);
                if (a.isEmpty()) {
                    // this piece is actually after the range
                    insertPosition = insertPosition || { index: i };
                    continue;
                }
                if (b.isEmpty()) {
                    // this piece is actually before the range
                    continue;
                }
                this._pieces.splice(i, 1, a, b);
                i++;
                len++;
                insertPosition = insertPosition || { index: i };
            }
            insertPosition = insertPosition || { index: this._pieces.length };
            if (pieces.length > 0) {
                this._pieces = arrays.arrayInsert(this._pieces, insertPosition.index, pieces);
            }
            // console.log(`I HAVE ${this._pieces.length} pieces`);
            // console.log(`${this._pieces.map(p => p.toString()).join('\n')}`);
            return range;
        }
        isComplete() {
            return this._isComplete;
        }
        addSparseTokens(lineNumber, aTokens) {
            if (aTokens.getLineContent().length === 0) {
                // Don't do anything for empty lines
                return aTokens;
            }
            const pieces = this._pieces;
            if (pieces.length === 0) {
                return aTokens;
            }
            const pieceIndex = SparseTokensStore._findFirstPieceWithLine(pieces, lineNumber);
            const bTokens = pieces[pieceIndex].getLineTokens(lineNumber);
            if (!bTokens) {
                return aTokens;
            }
            const aLen = aTokens.getCount();
            const bLen = bTokens.getCount();
            let aIndex = 0;
            const result = [];
            let resultLen = 0;
            let lastEndOffset = 0;
            const emitToken = (endOffset, metadata) => {
                if (endOffset === lastEndOffset) {
                    return;
                }
                lastEndOffset = endOffset;
                result[resultLen++] = endOffset;
                result[resultLen++] = metadata;
            };
            for (let bIndex = 0; bIndex < bLen; bIndex++) {
                const bStartCharacter = bTokens.getStartCharacter(bIndex);
                const bEndCharacter = bTokens.getEndCharacter(bIndex);
                const bMetadata = bTokens.getMetadata(bIndex);
                const bMask = (((bMetadata & 1 /* MetadataConsts.SEMANTIC_USE_ITALIC */) ? 2048 /* MetadataConsts.ITALIC_MASK */ : 0)
                    | ((bMetadata & 2 /* MetadataConsts.SEMANTIC_USE_BOLD */) ? 4096 /* MetadataConsts.BOLD_MASK */ : 0)
                    | ((bMetadata & 4 /* MetadataConsts.SEMANTIC_USE_UNDERLINE */) ? 8192 /* MetadataConsts.UNDERLINE_MASK */ : 0)
                    | ((bMetadata & 8 /* MetadataConsts.SEMANTIC_USE_STRIKETHROUGH */) ? 16384 /* MetadataConsts.STRIKETHROUGH_MASK */ : 0)
                    | ((bMetadata & 16 /* MetadataConsts.SEMANTIC_USE_FOREGROUND */) ? 16744448 /* MetadataConsts.FOREGROUND_MASK */ : 0)
                    | ((bMetadata & 32 /* MetadataConsts.SEMANTIC_USE_BACKGROUND */) ? 4278190080 /* MetadataConsts.BACKGROUND_MASK */ : 0)) >>> 0;
                const aMask = (~bMask) >>> 0;
                // push any token from `a` that is before `b`
                while (aIndex < aLen && aTokens.getEndOffset(aIndex) <= bStartCharacter) {
                    emitToken(aTokens.getEndOffset(aIndex), aTokens.getMetadata(aIndex));
                    aIndex++;
                }
                // push the token from `a` if it intersects the token from `b`
                if (aIndex < aLen && aTokens.getStartOffset(aIndex) < bStartCharacter) {
                    emitToken(bStartCharacter, aTokens.getMetadata(aIndex));
                }
                // skip any tokens from `a` that are contained inside `b`
                while (aIndex < aLen && aTokens.getEndOffset(aIndex) < bEndCharacter) {
                    emitToken(aTokens.getEndOffset(aIndex), (aTokens.getMetadata(aIndex) & aMask) | (bMetadata & bMask));
                    aIndex++;
                }
                if (aIndex < aLen) {
                    emitToken(bEndCharacter, (aTokens.getMetadata(aIndex) & aMask) | (bMetadata & bMask));
                    if (aTokens.getEndOffset(aIndex) === bEndCharacter) {
                        // `a` ends exactly at the same spot as `b`!
                        aIndex++;
                    }
                }
                else {
                    const aMergeIndex = Math.min(Math.max(0, aIndex - 1), aLen - 1);
                    // push the token from `b`
                    emitToken(bEndCharacter, (aTokens.getMetadata(aMergeIndex) & aMask) | (bMetadata & bMask));
                }
            }
            // push the remaining tokens from `a`
            while (aIndex < aLen) {
                emitToken(aTokens.getEndOffset(aIndex), aTokens.getMetadata(aIndex));
                aIndex++;
            }
            return new lineTokens_1.LineTokens(new Uint32Array(result), aTokens.getLineContent(), this._languageIdCodec);
        }
        static _findFirstPieceWithLine(pieces, lineNumber) {
            let low = 0;
            let high = pieces.length - 1;
            while (low < high) {
                let mid = low + Math.floor((high - low) / 2);
                if (pieces[mid].endLineNumber < lineNumber) {
                    low = mid + 1;
                }
                else if (pieces[mid].startLineNumber > lineNumber) {
                    high = mid - 1;
                }
                else {
                    while (mid > low && pieces[mid - 1].startLineNumber <= lineNumber && lineNumber <= pieces[mid - 1].endLineNumber) {
                        mid--;
                    }
                    return mid;
                }
            }
            return low;
        }
        acceptEdit(range, eolCount, firstLineLength, lastLineLength, firstCharCode) {
            for (const piece of this._pieces) {
                piece.acceptEdit(range, eolCount, firstLineLength, lastLineLength, firstCharCode);
            }
        }
    }
    exports.SparseTokensStore = SparseTokensStore;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[170/*vs/editor/common/viewEventHandler*/], __M([1/*require*/,0/*exports*/,2/*vs/base/common/lifecycle*/]), function (require, exports, lifecycle_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ViewEventHandler = void 0;
    class ViewEventHandler extends lifecycle_1.Disposable {
        constructor() {
            super();
            this._shouldRender = true;
        }
        shouldRender() {
            return this._shouldRender;
        }
        forceShouldRender() {
            this._shouldRender = true;
        }
        setShouldRender() {
            this._shouldRender = true;
        }
        onDidRender() {
            this._shouldRender = false;
        }
        // --- begin event handlers
        onCompositionStart(e) {
            return false;
        }
        onCompositionEnd(e) {
            return false;
        }
        onConfigurationChanged(e) {
            return false;
        }
        onCursorStateChanged(e) {
            return false;
        }
        onDecorationsChanged(e) {
            return false;
        }
        onFlushed(e) {
            return false;
        }
        onFocusChanged(e) {
            return false;
        }
        onLanguageConfigurationChanged(e) {
            return false;
        }
        onLineMappingChanged(e) {
            return false;
        }
        onLinesChanged(e) {
            return false;
        }
        onLinesDeleted(e) {
            return false;
        }
        onLinesInserted(e) {
            return false;
        }
        onRevealRangeRequest(e) {
            return false;
        }
        onScrollChanged(e) {
            return false;
        }
        onThemeChanged(e) {
            return false;
        }
        onTokensChanged(e) {
            return false;
        }
        onTokensColorsChanged(e) {
            return false;
        }
        onZonesChanged(e) {
            return false;
        }
        // --- end event handlers
        handleEvents(events) {
            let shouldRender = false;
            for (let i = 0, len = events.length; i < len; i++) {
                const e = events[i];
                switch (e.type) {
                    case 0 /* viewEvents.ViewEventType.ViewCompositionStart */:
                        if (this.onCompositionStart(e)) {
                            shouldRender = true;
                        }
                        break;
                    case 1 /* viewEvents.ViewEventType.ViewCompositionEnd */:
                        if (this.onCompositionEnd(e)) {
                            shouldRender = true;
                        }
                        break;
                    case 2 /* viewEvents.ViewEventType.ViewConfigurationChanged */:
                        if (this.onConfigurationChanged(e)) {
                            shouldRender = true;
                        }
                        break;
                    case 3 /* viewEvents.ViewEventType.ViewCursorStateChanged */:
                        if (this.onCursorStateChanged(e)) {
                            shouldRender = true;
                        }
                        break;
                    case 4 /* viewEvents.ViewEventType.ViewDecorationsChanged */:
                        if (this.onDecorationsChanged(e)) {
                            shouldRender = true;
                        }
                        break;
                    case 5 /* viewEvents.ViewEventType.ViewFlushed */:
                        if (this.onFlushed(e)) {
                            shouldRender = true;
                        }
                        break;
                    case 6 /* viewEvents.ViewEventType.ViewFocusChanged */:
                        if (this.onFocusChanged(e)) {
                            shouldRender = true;
                        }
                        break;
                    case 7 /* viewEvents.ViewEventType.ViewLanguageConfigurationChanged */:
                        if (this.onLanguageConfigurationChanged(e)) {
                            shouldRender = true;
                        }
                        break;
                    case 8 /* viewEvents.ViewEventType.ViewLineMappingChanged */:
                        if (this.onLineMappingChanged(e)) {
                            shouldRender = true;
                        }
                        break;
                    case 9 /* viewEvents.ViewEventType.ViewLinesChanged */:
                        if (this.onLinesChanged(e)) {
                            shouldRender = true;
                        }
                        break;
                    case 10 /* viewEvents.ViewEventType.ViewLinesDeleted */:
                        if (this.onLinesDeleted(e)) {
                            shouldRender = true;
                        }
                        break;
                    case 11 /* viewEvents.ViewEventType.ViewLinesInserted */:
                        if (this.onLinesInserted(e)) {
                            shouldRender = true;
                        }
                        break;
                    case 12 /* viewEvents.ViewEventType.ViewRevealRangeRequest */:
                        if (this.onRevealRangeRequest(e)) {
                            shouldRender = true;
                        }
                        break;
                    case 13 /* viewEvents.ViewEventType.ViewScrollChanged */:
                        if (this.onScrollChanged(e)) {
                            shouldRender = true;
                        }
                        break;
                    case 15 /* viewEvents.ViewEventType.ViewTokensChanged */:
                        if (this.onTokensChanged(e)) {
                            shouldRender = true;
                        }
                        break;
                    case 14 /* viewEvents.ViewEventType.ViewThemeChanged */:
                        if (this.onThemeChanged(e)) {
                            shouldRender = true;
                        }
                        break;
                    case 16 /* viewEvents.ViewEventType.ViewTokensColorsChanged */:
                        if (this.onTokensColorsChanged(e)) {
                            shouldRender = true;
                        }
                        break;
                    case 17 /* viewEvents.ViewEventType.ViewZonesChanged */:
                        if (this.onZonesChanged(e)) {
                            shouldRender = true;
                        }
                        break;
                    default:
                        console.info('View received unknown event: ');
                        console.info(e);
                }
            }
            if (shouldRender) {
                this._shouldRender = true;
            }
        }
    }
    exports.ViewEventHandler = ViewEventHandler;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[133/*vs/editor/browser/view/dynamicViewOverlay*/], __M([1/*require*/,0/*exports*/,170/*vs/editor/common/viewEventHandler*/]), function (require, exports, viewEventHandler_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DynamicViewOverlay = void 0;
    class DynamicViewOverlay extends viewEventHandler_1.ViewEventHandler {
    }
    exports.DynamicViewOverlay = DynamicViewOverlay;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[56/*vs/editor/browser/view/viewPart*/], __M([1/*require*/,0/*exports*/,170/*vs/editor/common/viewEventHandler*/]), function (require, exports, viewEventHandler_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.PartFingerprints = exports.ViewPart = void 0;
    class ViewPart extends viewEventHandler_1.ViewEventHandler {
        constructor(context) {
            super();
            this._context = context;
            this._context.addEventHandler(this);
        }
        dispose() {
            this._context.removeEventHandler(this);
            super.dispose();
        }
    }
    exports.ViewPart = ViewPart;
    class PartFingerprints {
        static write(target, partId) {
            target.setAttribute('data-mprt', String(partId));
        }
        static read(target) {
            const r = target.getAttribute('data-mprt');
            if (r === null) {
                return 0 /* PartFingerprint.None */;
            }
            return parseInt(r, 10);
        }
        static collect(child, stopAt) {
            const result = [];
            let resultLen = 0;
            while (child && child !== child.ownerDocument.body) {
                if (child === stopAt) {
                    break;
                }
                if (child.nodeType === child.ELEMENT_NODE) {
                    result[resultLen++] = this.read(child);
                }
                child = child.parentElement;
            }
            const r = new Uint8Array(resultLen);
            for (let i = 0; i < resultLen; i++) {
                r[i] = result[resultLen - i - 1];
            }
            return r;
        }
    }
    exports.PartFingerprints = PartFingerprints;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[591/*vs/editor/browser/viewParts/blockDecorations/blockDecorations*/], __M([1/*require*/,0/*exports*/,39/*vs/base/browser/fastDomNode*/,56/*vs/editor/browser/view/viewPart*/,481/*vs/css!vs/editor/browser/viewParts/blockDecorations/blockDecorations*/]), function (require, exports, fastDomNode_1, viewPart_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.BlockDecorations = void 0;
    class BlockDecorations extends viewPart_1.ViewPart {
        constructor(context) {
            super(context);
            this.blocks = [];
            this.contentWidth = -1;
            this.contentLeft = 0;
            this.domNode = (0, fastDomNode_1.createFastDomNode)(document.createElement('div'));
            this.domNode.setAttribute('role', 'presentation');
            this.domNode.setAttribute('aria-hidden', 'true');
            this.domNode.setClassName('blockDecorations-container');
            this.update();
        }
        update() {
            let didChange = false;
            const options = this._context.configuration.options;
            const layoutInfo = options.get(146 /* EditorOption.layoutInfo */);
            const newContentWidth = layoutInfo.contentWidth - layoutInfo.verticalScrollbarWidth;
            if (this.contentWidth !== newContentWidth) {
                this.contentWidth = newContentWidth;
                didChange = true;
            }
            const newContentLeft = layoutInfo.contentLeft;
            if (this.contentLeft !== newContentLeft) {
                this.contentLeft = newContentLeft;
                didChange = true;
            }
            return didChange;
        }
        dispose() {
            super.dispose();
        }
        // --- begin event handlers
        onConfigurationChanged(e) {
            return this.update();
        }
        onScrollChanged(e) {
            return e.scrollTopChanged || e.scrollLeftChanged;
        }
        onDecorationsChanged(e) {
            return true;
        }
        onZonesChanged(e) {
            return true;
        }
        // --- end event handlers
        prepareRender(ctx) {
            // Nothing to read
        }
        render(ctx) {
            let count = 0;
            const decorations = ctx.getDecorationsInViewport();
            for (const decoration of decorations) {
                if (!decoration.options.blockClassName) {
                    continue;
                }
                let block = this.blocks[count];
                if (!block) {
                    block = this.blocks[count] = (0, fastDomNode_1.createFastDomNode)(document.createElement('div'));
                    this.domNode.appendChild(block);
                }
                let top;
                let bottom;
                if (decoration.options.blockIsAfterEnd) {
                    // range must be empty
                    top = ctx.getVerticalOffsetAfterLineNumber(decoration.range.endLineNumber, false);
                    bottom = ctx.getVerticalOffsetAfterLineNumber(decoration.range.endLineNumber, true);
                }
                else {
                    top = ctx.getVerticalOffsetForLineNumber(decoration.range.startLineNumber, true);
                    bottom = decoration.range.isEmpty() && !decoration.options.blockDoesNotCollapse
                        ? ctx.getVerticalOffsetForLineNumber(decoration.range.startLineNumber, false)
                        : ctx.getVerticalOffsetAfterLineNumber(decoration.range.endLineNumber, true);
                }
                const [paddingTop, paddingRight, paddingBottom, paddingLeft] = decoration.options.blockPadding ?? [0, 0, 0, 0];
                block.setClassName('blockDecorations-block ' + decoration.options.blockClassName);
                block.setLeft(this.contentLeft - paddingLeft);
                block.setWidth(this.contentWidth + paddingLeft + paddingRight);
                block.setTop(top - ctx.scrollTop - paddingTop);
                block.setHeight(bottom - top + paddingTop + paddingBottom);
                count++;
            }
            for (let i = count; i < this.blocks.length; i++) {
                this.blocks[i].domNode.remove();
            }
            this.blocks.length = count;
        }
    }
    exports.BlockDecorations = BlockDecorations;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[592/*vs/editor/browser/viewParts/decorations/decorations*/], __M([1/*require*/,0/*exports*/,133/*vs/editor/browser/view/dynamicViewOverlay*/,164/*vs/editor/browser/view/renderingContext*/,4/*vs/editor/common/core/range*/,483/*vs/css!vs/editor/browser/viewParts/decorations/decorations*/]), function (require, exports, dynamicViewOverlay_1, renderingContext_1, range_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DecorationsOverlay = void 0;
    class DecorationsOverlay extends dynamicViewOverlay_1.DynamicViewOverlay {
        constructor(context) {
            super();
            this._context = context;
            const options = this._context.configuration.options;
            this._typicalHalfwidthCharacterWidth = options.get(50 /* EditorOption.fontInfo */).typicalHalfwidthCharacterWidth;
            this._renderResult = null;
            this._context.addEventHandler(this);
        }
        dispose() {
            this._context.removeEventHandler(this);
            this._renderResult = null;
            super.dispose();
        }
        // --- begin event handlers
        onConfigurationChanged(e) {
            const options = this._context.configuration.options;
            this._typicalHalfwidthCharacterWidth = options.get(50 /* EditorOption.fontInfo */).typicalHalfwidthCharacterWidth;
            return true;
        }
        onDecorationsChanged(e) {
            return true;
        }
        onFlushed(e) {
            return true;
        }
        onLinesChanged(e) {
            return true;
        }
        onLinesDeleted(e) {
            return true;
        }
        onLinesInserted(e) {
            return true;
        }
        onScrollChanged(e) {
            return e.scrollTopChanged || e.scrollWidthChanged;
        }
        onZonesChanged(e) {
            return true;
        }
        // --- end event handlers
        prepareRender(ctx) {
            const _decorations = ctx.getDecorationsInViewport();
            // Keep only decorations with `className`
            let decorations = [];
            let decorationsLen = 0;
            for (let i = 0, len = _decorations.length; i < len; i++) {
                const d = _decorations[i];
                if (d.options.className) {
                    decorations[decorationsLen++] = d;
                }
            }
            // Sort decorations for consistent render output
            decorations = decorations.sort((a, b) => {
                if (a.options.zIndex < b.options.zIndex) {
                    return -1;
                }
                if (a.options.zIndex > b.options.zIndex) {
                    return 1;
                }
                const aClassName = a.options.className;
                const bClassName = b.options.className;
                if (aClassName < bClassName) {
                    return -1;
                }
                if (aClassName > bClassName) {
                    return 1;
                }
                return range_1.Range.compareRangesUsingStarts(a.range, b.range);
            });
            const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
            const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
            const output = [];
            for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
                const lineIndex = lineNumber - visibleStartLineNumber;
                output[lineIndex] = '';
            }
            // Render first whole line decorations and then regular decorations
            this._renderWholeLineDecorations(ctx, decorations, output);
            this._renderNormalDecorations(ctx, decorations, output);
            this._renderResult = output;
        }
        _renderWholeLineDecorations(ctx, decorations, output) {
            const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
            const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
            for (let i = 0, lenI = decorations.length; i < lenI; i++) {
                const d = decorations[i];
                if (!d.options.isWholeLine) {
                    continue;
                }
                const decorationOutput = ('<div class="cdr '
                    + d.options.className
                    + '" style="left:0;width:100%;"></div>');
                const startLineNumber = Math.max(d.range.startLineNumber, visibleStartLineNumber);
                const endLineNumber = Math.min(d.range.endLineNumber, visibleEndLineNumber);
                for (let j = startLineNumber; j <= endLineNumber; j++) {
                    const lineIndex = j - visibleStartLineNumber;
                    output[lineIndex] += decorationOutput;
                }
            }
        }
        _renderNormalDecorations(ctx, decorations, output) {
            const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
            let prevClassName = null;
            let prevShowIfCollapsed = false;
            let prevRange = null;
            let prevShouldFillLineOnLineBreak = false;
            for (let i = 0, lenI = decorations.length; i < lenI; i++) {
                const d = decorations[i];
                if (d.options.isWholeLine) {
                    continue;
                }
                const className = d.options.className;
                const showIfCollapsed = Boolean(d.options.showIfCollapsed);
                let range = d.range;
                if (showIfCollapsed && range.endColumn === 1 && range.endLineNumber !== range.startLineNumber) {
                    range = new range_1.Range(range.startLineNumber, range.startColumn, range.endLineNumber - 1, this._context.viewModel.getLineMaxColumn(range.endLineNumber - 1));
                }
                if (prevClassName === className && prevShowIfCollapsed === showIfCollapsed && range_1.Range.areIntersectingOrTouching(prevRange, range)) {
                    // merge into previous decoration
                    prevRange = range_1.Range.plusRange(prevRange, range);
                    continue;
                }
                // flush previous decoration
                if (prevClassName !== null) {
                    this._renderNormalDecoration(ctx, prevRange, prevClassName, prevShouldFillLineOnLineBreak, prevShowIfCollapsed, visibleStartLineNumber, output);
                }
                prevClassName = className;
                prevShowIfCollapsed = showIfCollapsed;
                prevRange = range;
                prevShouldFillLineOnLineBreak = d.options.shouldFillLineOnLineBreak ?? false;
            }
            if (prevClassName !== null) {
                this._renderNormalDecoration(ctx, prevRange, prevClassName, prevShouldFillLineOnLineBreak, prevShowIfCollapsed, visibleStartLineNumber, output);
            }
        }
        _renderNormalDecoration(ctx, range, className, shouldFillLineOnLineBreak, showIfCollapsed, visibleStartLineNumber, output) {
            const linesVisibleRanges = ctx.linesVisibleRangesForRange(range, /*TODO@Alex*/ className === 'findMatch');
            if (!linesVisibleRanges) {
                return;
            }
            for (let j = 0, lenJ = linesVisibleRanges.length; j < lenJ; j++) {
                const lineVisibleRanges = linesVisibleRanges[j];
                if (lineVisibleRanges.outsideRenderedLine) {
                    continue;
                }
                const lineIndex = lineVisibleRanges.lineNumber - visibleStartLineNumber;
                if (showIfCollapsed && lineVisibleRanges.ranges.length === 1) {
                    const singleVisibleRange = lineVisibleRanges.ranges[0];
                    if (singleVisibleRange.width < this._typicalHalfwidthCharacterWidth) {
                        // collapsed/very small range case => make the decoration visible by expanding its width
                        // expand its size on both sides (both to the left and to the right, keeping it centered)
                        const center = Math.round(singleVisibleRange.left + singleVisibleRange.width / 2);
                        const left = Math.max(0, Math.round(center - this._typicalHalfwidthCharacterWidth / 2));
                        lineVisibleRanges.ranges[0] = new renderingContext_1.HorizontalRange(left, this._typicalHalfwidthCharacterWidth);
                    }
                }
                for (let k = 0, lenK = lineVisibleRanges.ranges.length; k < lenK; k++) {
                    const expandToLeft = shouldFillLineOnLineBreak && lineVisibleRanges.continuesOnNextLine && lenK === 1;
                    const visibleRange = lineVisibleRanges.ranges[k];
                    const decorationOutput = ('<div class="cdr '
                        + className
                        + '" style="left:'
                        + String(visibleRange.left)
                        + 'px;width:'
                        + (expandToLeft ?
                            '100%;' :
                            (String(visibleRange.width) + 'px;'))
                        + '"></div>');
                    output[lineIndex] += decorationOutput;
                }
            }
        }
        render(startLineNumber, lineNumber) {
            if (!this._renderResult) {
                return '';
            }
            const lineIndex = lineNumber - startLineNumber;
            if (lineIndex < 0 || lineIndex >= this._renderResult.length) {
                return '';
            }
            return this._renderResult[lineIndex];
        }
    }
    exports.DecorationsOverlay = DecorationsOverlay;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[242/*vs/editor/browser/viewParts/glyphMargin/glyphMargin*/], __M([1/*require*/,0/*exports*/,39/*vs/base/browser/fastDomNode*/,13/*vs/base/common/arrays*/,133/*vs/editor/browser/view/dynamicViewOverlay*/,56/*vs/editor/browser/view/viewPart*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/,40/*vs/editor/common/model*/,484/*vs/css!vs/editor/browser/viewParts/glyphMargin/glyphMargin*/]), function (require, exports, fastDomNode_1, arrays_1, dynamicViewOverlay_1, viewPart_1, position_1, range_1, model_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.GlyphMarginWidgets = exports.DedupOverlay = exports.VisibleLineDecorationsToRender = exports.LineDecorationToRender = exports.DecorationToRender = void 0;
    /**
     * Represents a decoration that should be shown along the lines from `startLineNumber` to `endLineNumber`.
     * This can end up producing multiple `LineDecorationToRender`.
     */
    class DecorationToRender {
        constructor(startLineNumber, endLineNumber, className, tooltip, zIndex) {
            this.startLineNumber = startLineNumber;
            this.endLineNumber = endLineNumber;
            this.className = className;
            this.tooltip = tooltip;
            this._decorationToRenderBrand = undefined;
            this.zIndex = zIndex ?? 0;
        }
    }
    exports.DecorationToRender = DecorationToRender;
    /**
     * A decoration that should be shown along a line.
     */
    class LineDecorationToRender {
        constructor(className, zIndex, tooltip) {
            this.className = className;
            this.zIndex = zIndex;
            this.tooltip = tooltip;
        }
    }
    exports.LineDecorationToRender = LineDecorationToRender;
    /**
     * Decorations to render on a visible line.
     */
    class VisibleLineDecorationsToRender {
        constructor() {
            this.decorations = [];
        }
        add(decoration) {
            this.decorations.push(decoration);
        }
        getDecorations() {
            return this.decorations;
        }
    }
    exports.VisibleLineDecorationsToRender = VisibleLineDecorationsToRender;
    class DedupOverlay extends dynamicViewOverlay_1.DynamicViewOverlay {
        /**
         * Returns an array with an element for each visible line number.
         */
        _render(visibleStartLineNumber, visibleEndLineNumber, decorations) {
            const output = [];
            for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
                const lineIndex = lineNumber - visibleStartLineNumber;
                output[lineIndex] = new VisibleLineDecorationsToRender();
            }
            if (decorations.length === 0) {
                return output;
            }
            // Sort decorations by className, then by startLineNumber and then by endLineNumber
            decorations.sort((a, b) => {
                if (a.className === b.className) {
                    if (a.startLineNumber === b.startLineNumber) {
                        return a.endLineNumber - b.endLineNumber;
                    }
                    return a.startLineNumber - b.startLineNumber;
                }
                return (a.className < b.className ? -1 : 1);
            });
            let prevClassName = null;
            let prevEndLineIndex = 0;
            for (let i = 0, len = decorations.length; i < len; i++) {
                const d = decorations[i];
                const className = d.className;
                const zIndex = d.zIndex;
                let startLineIndex = Math.max(d.startLineNumber, visibleStartLineNumber) - visibleStartLineNumber;
                const endLineIndex = Math.min(d.endLineNumber, visibleEndLineNumber) - visibleStartLineNumber;
                if (prevClassName === className) {
                    // Here we avoid rendering the same className multiple times on the same line
                    startLineIndex = Math.max(prevEndLineIndex + 1, startLineIndex);
                    prevEndLineIndex = Math.max(prevEndLineIndex, endLineIndex);
                }
                else {
                    prevClassName = className;
                    prevEndLineIndex = endLineIndex;
                }
                for (let i = startLineIndex; i <= prevEndLineIndex; i++) {
                    output[i].add(new LineDecorationToRender(className, zIndex, d.tooltip));
                }
            }
            return output;
        }
    }
    exports.DedupOverlay = DedupOverlay;
    class GlyphMarginWidgets extends viewPart_1.ViewPart {
        constructor(context) {
            super(context);
            this._widgets = {};
            this._context = context;
            const options = this._context.configuration.options;
            const layoutInfo = options.get(146 /* EditorOption.layoutInfo */);
            this.domNode = (0, fastDomNode_1.createFastDomNode)(document.createElement('div'));
            this.domNode.setClassName('glyph-margin-widgets');
            this.domNode.setPosition('absolute');
            this.domNode.setTop(0);
            this._lineHeight = options.get(67 /* EditorOption.lineHeight */);
            this._glyphMargin = options.get(57 /* EditorOption.glyphMargin */);
            this._glyphMarginLeft = layoutInfo.glyphMarginLeft;
            this._glyphMarginWidth = layoutInfo.glyphMarginWidth;
            this._glyphMarginDecorationLaneCount = layoutInfo.glyphMarginDecorationLaneCount;
            this._managedDomNodes = [];
            this._decorationGlyphsToRender = [];
        }
        dispose() {
            this._managedDomNodes = [];
            this._decorationGlyphsToRender = [];
            this._widgets = {};
            super.dispose();
        }
        getWidgets() {
            return Object.values(this._widgets);
        }
        // --- begin event handlers
        onConfigurationChanged(e) {
            const options = this._context.configuration.options;
            const layoutInfo = options.get(146 /* EditorOption.layoutInfo */);
            this._lineHeight = options.get(67 /* EditorOption.lineHeight */);
            this._glyphMargin = options.get(57 /* EditorOption.glyphMargin */);
            this._glyphMarginLeft = layoutInfo.glyphMarginLeft;
            this._glyphMarginWidth = layoutInfo.glyphMarginWidth;
            this._glyphMarginDecorationLaneCount = layoutInfo.glyphMarginDecorationLaneCount;
            return true;
        }
        onDecorationsChanged(e) {
            return true;
        }
        onFlushed(e) {
            return true;
        }
        onLinesChanged(e) {
            return true;
        }
        onLinesDeleted(e) {
            return true;
        }
        onLinesInserted(e) {
            return true;
        }
        onScrollChanged(e) {
            return e.scrollTopChanged;
        }
        onZonesChanged(e) {
            return true;
        }
        // --- end event handlers
        // --- begin widget management
        addWidget(widget) {
            const domNode = (0, fastDomNode_1.createFastDomNode)(widget.getDomNode());
            this._widgets[widget.getId()] = {
                widget: widget,
                preference: widget.getPosition(),
                domNode: domNode,
                renderInfo: null
            };
            domNode.setPosition('absolute');
            domNode.setDisplay('none');
            domNode.setAttribute('widgetId', widget.getId());
            this.domNode.appendChild(domNode);
            this.setShouldRender();
        }
        setWidgetPosition(widget, preference) {
            const myWidget = this._widgets[widget.getId()];
            if (myWidget.preference.lane === preference.lane
                && myWidget.preference.zIndex === preference.zIndex
                && range_1.Range.equalsRange(myWidget.preference.range, preference.range)) {
                return false;
            }
            myWidget.preference = preference;
            this.setShouldRender();
            return true;
        }
        removeWidget(widget) {
            const widgetId = widget.getId();
            if (this._widgets[widgetId]) {
                const widgetData = this._widgets[widgetId];
                const domNode = widgetData.domNode.domNode;
                delete this._widgets[widgetId];
                domNode.remove();
                this.setShouldRender();
            }
        }
        // --- end widget management
        _collectDecorationBasedGlyphRenderRequest(ctx, requests) {
            const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
            const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
            const decorations = ctx.getDecorationsInViewport();
            for (const d of decorations) {
                const glyphMarginClassName = d.options.glyphMarginClassName;
                if (!glyphMarginClassName) {
                    continue;
                }
                const startLineNumber = Math.max(d.range.startLineNumber, visibleStartLineNumber);
                const endLineNumber = Math.min(d.range.endLineNumber, visibleEndLineNumber);
                const lane = d.options.glyphMargin?.position ?? model_1.GlyphMarginLane.Center;
                const zIndex = d.options.zIndex ?? 0;
                for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
                    const modelPosition = this._context.viewModel.coordinatesConverter.convertViewPositionToModelPosition(new position_1.Position(lineNumber, 0));
                    const laneIndex = this._context.viewModel.glyphLanes.getLanesAtLine(modelPosition.lineNumber).indexOf(lane);
                    requests.push(new DecorationBasedGlyphRenderRequest(lineNumber, laneIndex, zIndex, glyphMarginClassName));
                }
            }
        }
        _collectWidgetBasedGlyphRenderRequest(ctx, requests) {
            const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
            const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
            for (const widget of Object.values(this._widgets)) {
                const range = widget.preference.range;
                const { startLineNumber, endLineNumber } = this._context.viewModel.coordinatesConverter.convertModelRangeToViewRange(range_1.Range.lift(range));
                if (!startLineNumber || !endLineNumber || endLineNumber < visibleStartLineNumber || startLineNumber > visibleEndLineNumber) {
                    // The widget is not in the viewport
                    continue;
                }
                // The widget is in the viewport, find a good line for it
                const widgetLineNumber = Math.max(startLineNumber, visibleStartLineNumber);
                const modelPosition = this._context.viewModel.coordinatesConverter.convertViewPositionToModelPosition(new position_1.Position(widgetLineNumber, 0));
                const laneIndex = this._context.viewModel.glyphLanes.getLanesAtLine(modelPosition.lineNumber).indexOf(widget.preference.lane);
                requests.push(new WidgetBasedGlyphRenderRequest(widgetLineNumber, laneIndex, widget.preference.zIndex, widget));
            }
        }
        _collectSortedGlyphRenderRequests(ctx) {
            const requests = [];
            this._collectDecorationBasedGlyphRenderRequest(ctx, requests);
            this._collectWidgetBasedGlyphRenderRequest(ctx, requests);
            // sort requests by lineNumber ASC, lane  ASC, zIndex DESC, type DESC (widgets first), className ASC
            // don't change this sort unless you understand `prepareRender` below.
            requests.sort((a, b) => {
                if (a.lineNumber === b.lineNumber) {
                    if (a.laneIndex === b.laneIndex) {
                        if (a.zIndex === b.zIndex) {
                            if (b.type === a.type) {
                                if (a.type === 0 /* GlyphRenderRequestType.Decoration */ && b.type === 0 /* GlyphRenderRequestType.Decoration */) {
                                    return (a.className < b.className ? -1 : 1);
                                }
                                return 0;
                            }
                            return b.type - a.type;
                        }
                        return b.zIndex - a.zIndex;
                    }
                    return a.laneIndex - b.laneIndex;
                }
                return a.lineNumber - b.lineNumber;
            });
            return requests;
        }
        /**
         * Will store render information in each widget's renderInfo and in `_decorationGlyphsToRender`.
         */
        prepareRender(ctx) {
            if (!this._glyphMargin) {
                this._decorationGlyphsToRender = [];
                return;
            }
            for (const widget of Object.values(this._widgets)) {
                widget.renderInfo = null;
            }
            const requests = new arrays_1.ArrayQueue(this._collectSortedGlyphRenderRequests(ctx));
            const decorationGlyphsToRender = [];
            while (requests.length > 0) {
                const first = requests.peek();
                if (!first) {
                    // not possible
                    break;
                }
                // Requests are sorted by lineNumber and lane, so we read all requests for this particular location
                const requestsAtLocation = requests.takeWhile((el) => el.lineNumber === first.lineNumber && el.laneIndex === first.laneIndex);
                if (!requestsAtLocation || requestsAtLocation.length === 0) {
                    // not possible
                    break;
                }
                const winner = requestsAtLocation[0];
                if (winner.type === 0 /* GlyphRenderRequestType.Decoration */) {
                    // combine all decorations with the same z-index
                    const classNames = [];
                    // requests are sorted by zIndex, type, and className so we can dedup className by looking at the previous one
                    for (const request of requestsAtLocation) {
                        if (request.zIndex !== winner.zIndex || request.type !== winner.type) {
                            break;
                        }
                        if (classNames.length === 0 || classNames[classNames.length - 1] !== request.className) {
                            classNames.push(request.className);
                        }
                    }
                    decorationGlyphsToRender.push(winner.accept(classNames.join(' '))); // TODO@joyceerhl Implement overflow for remaining decorations
                }
                else {
                    // widgets cannot be combined
                    winner.widget.renderInfo = {
                        lineNumber: winner.lineNumber,
                        laneIndex: winner.laneIndex,
                    };
                }
            }
            this._decorationGlyphsToRender = decorationGlyphsToRender;
        }
        render(ctx) {
            if (!this._glyphMargin) {
                for (const widget of Object.values(this._widgets)) {
                    widget.domNode.setDisplay('none');
                }
                while (this._managedDomNodes.length > 0) {
                    const domNode = this._managedDomNodes.pop();
                    domNode?.domNode.remove();
                }
                return;
            }
            const width = (Math.round(this._glyphMarginWidth / this._glyphMarginDecorationLaneCount));
            // Render widgets
            for (const widget of Object.values(this._widgets)) {
                if (!widget.renderInfo) {
                    // this widget is not visible
                    widget.domNode.setDisplay('none');
                }
                else {
                    const top = ctx.viewportData.relativeVerticalOffset[widget.renderInfo.lineNumber - ctx.viewportData.startLineNumber];
                    const left = this._glyphMarginLeft + widget.renderInfo.laneIndex * this._lineHeight;
                    widget.domNode.setDisplay('block');
                    widget.domNode.setTop(top);
                    widget.domNode.setLeft(left);
                    widget.domNode.setWidth(width);
                    widget.domNode.setHeight(this._lineHeight);
                }
            }
            // Render decorations, reusing previous dom nodes as possible
            for (let i = 0; i < this._decorationGlyphsToRender.length; i++) {
                const dec = this._decorationGlyphsToRender[i];
                const top = ctx.viewportData.relativeVerticalOffset[dec.lineNumber - ctx.viewportData.startLineNumber];
                const left = this._glyphMarginLeft + dec.laneIndex * this._lineHeight;
                let domNode;
                if (i < this._managedDomNodes.length) {
                    domNode = this._managedDomNodes[i];
                }
                else {
                    domNode = (0, fastDomNode_1.createFastDomNode)(document.createElement('div'));
                    this._managedDomNodes.push(domNode);
                    this.domNode.appendChild(domNode);
                }
                domNode.setClassName(`cgmr codicon ` + dec.combinedClassName);
                domNode.setPosition(`absolute`);
                domNode.setTop(top);
                domNode.setLeft(left);
                domNode.setWidth(width);
                domNode.setHeight(this._lineHeight);
            }
            // remove extra dom nodes
            while (this._managedDomNodes.length > this._decorationGlyphsToRender.length) {
                const domNode = this._managedDomNodes.pop();
                domNode?.domNode.remove();
            }
        }
    }
    exports.GlyphMarginWidgets = GlyphMarginWidgets;
    /**
     * A request to render a decoration in the glyph margin at a certain location.
     */
    class DecorationBasedGlyphRenderRequest {
        constructor(lineNumber, laneIndex, zIndex, className) {
            this.lineNumber = lineNumber;
            this.laneIndex = laneIndex;
            this.zIndex = zIndex;
            this.className = className;
            this.type = 0 /* GlyphRenderRequestType.Decoration */;
        }
        accept(combinedClassName) {
            return new DecorationBasedGlyph(this.lineNumber, this.laneIndex, combinedClassName);
        }
    }
    /**
     * A request to render a widget in the glyph margin at a certain location.
     */
    class WidgetBasedGlyphRenderRequest {
        constructor(lineNumber, laneIndex, zIndex, widget) {
            this.lineNumber = lineNumber;
            this.laneIndex = laneIndex;
            this.zIndex = zIndex;
            this.widget = widget;
            this.type = 1 /* GlyphRenderRequestType.Widget */;
        }
    }
    class DecorationBasedGlyph {
        constructor(lineNumber, laneIndex, combinedClassName) {
            this.lineNumber = lineNumber;
            this.laneIndex = laneIndex;
            this.combinedClassName = combinedClassName;
        }
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[593/*vs/editor/browser/viewParts/linesDecorations/linesDecorations*/], __M([1/*require*/,0/*exports*/,242/*vs/editor/browser/viewParts/glyphMargin/glyphMargin*/,488/*vs/css!vs/editor/browser/viewParts/linesDecorations/linesDecorations*/]), function (require, exports, glyphMargin_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.LinesDecorationsOverlay = void 0;
    class LinesDecorationsOverlay extends glyphMargin_1.DedupOverlay {
        constructor(context) {
            super();
            this._context = context;
            const options = this._context.configuration.options;
            const layoutInfo = options.get(146 /* EditorOption.layoutInfo */);
            this._decorationsLeft = layoutInfo.decorationsLeft;
            this._decorationsWidth = layoutInfo.decorationsWidth;
            this._renderResult = null;
            this._context.addEventHandler(this);
        }
        dispose() {
            this._context.removeEventHandler(this);
            this._renderResult = null;
            super.dispose();
        }
        // --- begin event handlers
        onConfigurationChanged(e) {
            const options = this._context.configuration.options;
            const layoutInfo = options.get(146 /* EditorOption.layoutInfo */);
            this._decorationsLeft = layoutInfo.decorationsLeft;
            this._decorationsWidth = layoutInfo.decorationsWidth;
            return true;
        }
        onDecorationsChanged(e) {
            return true;
        }
        onFlushed(e) {
            return true;
        }
        onLinesChanged(e) {
            return true;
        }
        onLinesDeleted(e) {
            return true;
        }
        onLinesInserted(e) {
            return true;
        }
        onScrollChanged(e) {
            return e.scrollTopChanged;
        }
        onZonesChanged(e) {
            return true;
        }
        // --- end event handlers
        _getDecorations(ctx) {
            const decorations = ctx.getDecorationsInViewport();
            const r = [];
            let rLen = 0;
            for (let i = 0, len = decorations.length; i < len; i++) {
                const d = decorations[i];
                const linesDecorationsClassName = d.options.linesDecorationsClassName;
                const zIndex = d.options.zIndex;
                if (linesDecorationsClassName) {
                    r[rLen++] = new glyphMargin_1.DecorationToRender(d.range.startLineNumber, d.range.endLineNumber, linesDecorationsClassName, d.options.linesDecorationsTooltip ?? null, zIndex);
                }
                const firstLineDecorationClassName = d.options.firstLineDecorationClassName;
                if (firstLineDecorationClassName) {
                    r[rLen++] = new glyphMargin_1.DecorationToRender(d.range.startLineNumber, d.range.startLineNumber, firstLineDecorationClassName, d.options.linesDecorationsTooltip ?? null, zIndex);
                }
            }
            return r;
        }
        prepareRender(ctx) {
            const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
            const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
            const toRender = this._render(visibleStartLineNumber, visibleEndLineNumber, this._getDecorations(ctx));
            const left = this._decorationsLeft.toString();
            const width = this._decorationsWidth.toString();
            const common = '" style="left:' + left + 'px;width:' + width + 'px;"></div>';
            const output = [];
            for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
                const lineIndex = lineNumber - visibleStartLineNumber;
                const decorations = toRender[lineIndex].getDecorations();
                let lineOutput = '';
                for (const decoration of decorations) {
                    let addition = '<div class="cldr ' + decoration.className;
                    if (decoration.tooltip !== null) {
                        addition += '" title="' + decoration.tooltip; // The tooltip is already escaped.
                    }
                    addition += common;
                    lineOutput += addition;
                }
                output[lineIndex] = lineOutput;
            }
            this._renderResult = output;
        }
        render(startLineNumber, lineNumber) {
            if (!this._renderResult) {
                return '';
            }
            return this._renderResult[lineNumber - startLineNumber];
        }
    }
    exports.LinesDecorationsOverlay = LinesDecorationsOverlay;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[331/*vs/editor/browser/viewParts/margin/margin*/], __M([1/*require*/,0/*exports*/,39/*vs/base/browser/fastDomNode*/,56/*vs/editor/browser/view/viewPart*/,489/*vs/css!vs/editor/browser/viewParts/margin/margin*/]), function (require, exports, fastDomNode_1, viewPart_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Margin = void 0;
    class Margin extends viewPart_1.ViewPart {
        static { this.CLASS_NAME = 'glyph-margin'; }
        static { this.OUTER_CLASS_NAME = 'margin'; }
        constructor(context) {
            super(context);
            const options = this._context.configuration.options;
            const layoutInfo = options.get(146 /* EditorOption.layoutInfo */);
            this._canUseLayerHinting = !options.get(32 /* EditorOption.disableLayerHinting */);
            this._contentLeft = layoutInfo.contentLeft;
            this._glyphMarginLeft = layoutInfo.glyphMarginLeft;
            this._glyphMarginWidth = layoutInfo.glyphMarginWidth;
            this._domNode = (0, fastDomNode_1.createFastDomNode)(document.createElement('div'));
            this._domNode.setClassName(Margin.OUTER_CLASS_NAME);
            this._domNode.setPosition('absolute');
            this._domNode.setAttribute('role', 'presentation');
            this._domNode.setAttribute('aria-hidden', 'true');
            this._glyphMarginBackgroundDomNode = (0, fastDomNode_1.createFastDomNode)(document.createElement('div'));
            this._glyphMarginBackgroundDomNode.setClassName(Margin.CLASS_NAME);
            this._domNode.appendChild(this._glyphMarginBackgroundDomNode);
        }
        dispose() {
            super.dispose();
        }
        getDomNode() {
            return this._domNode;
        }
        // --- begin event handlers
        onConfigurationChanged(e) {
            const options = this._context.configuration.options;
            const layoutInfo = options.get(146 /* EditorOption.layoutInfo */);
            this._canUseLayerHinting = !options.get(32 /* EditorOption.disableLayerHinting */);
            this._contentLeft = layoutInfo.contentLeft;
            this._glyphMarginLeft = layoutInfo.glyphMarginLeft;
            this._glyphMarginWidth = layoutInfo.glyphMarginWidth;
            return true;
        }
        onScrollChanged(e) {
            return super.onScrollChanged(e) || e.scrollTopChanged;
        }
        // --- end event handlers
        prepareRender(ctx) {
            // Nothing to read
        }
        render(ctx) {
            this._domNode.setLayerHinting(this._canUseLayerHinting);
            this._domNode.setContain('strict');
            const adjustedScrollTop = ctx.scrollTop - ctx.bigNumbersDelta;
            this._domNode.setTop(-adjustedScrollTop);
            const height = Math.min(ctx.scrollHeight, 1000000);
            this._domNode.setHeight(height);
            this._domNode.setWidth(this._contentLeft);
            this._glyphMarginBackgroundDomNode.setLeft(this._glyphMarginLeft);
            this._glyphMarginBackgroundDomNode.setWidth(this._glyphMarginWidth);
            this._glyphMarginBackgroundDomNode.setHeight(height);
        }
    }
    exports.Margin = Margin;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[594/*vs/editor/browser/viewParts/marginDecorations/marginDecorations*/], __M([1/*require*/,0/*exports*/,242/*vs/editor/browser/viewParts/glyphMargin/glyphMargin*/,490/*vs/css!vs/editor/browser/viewParts/marginDecorations/marginDecorations*/]), function (require, exports, glyphMargin_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MarginViewLineDecorationsOverlay = void 0;
    class MarginViewLineDecorationsOverlay extends glyphMargin_1.DedupOverlay {
        constructor(context) {
            super();
            this._context = context;
            this._renderResult = null;
            this._context.addEventHandler(this);
        }
        dispose() {
            this._context.removeEventHandler(this);
            this._renderResult = null;
            super.dispose();
        }
        // --- begin event handlers
        onConfigurationChanged(e) {
            return true;
        }
        onDecorationsChanged(e) {
            return true;
        }
        onFlushed(e) {
            return true;
        }
        onLinesChanged(e) {
            return true;
        }
        onLinesDeleted(e) {
            return true;
        }
        onLinesInserted(e) {
            return true;
        }
        onScrollChanged(e) {
            return e.scrollTopChanged;
        }
        onZonesChanged(e) {
            return true;
        }
        // --- end event handlers
        _getDecorations(ctx) {
            const decorations = ctx.getDecorationsInViewport();
            const r = [];
            let rLen = 0;
            for (let i = 0, len = decorations.length; i < len; i++) {
                const d = decorations[i];
                const marginClassName = d.options.marginClassName;
                const zIndex = d.options.zIndex;
                if (marginClassName) {
                    r[rLen++] = new glyphMargin_1.DecorationToRender(d.range.startLineNumber, d.range.endLineNumber, marginClassName, null, zIndex);
                }
            }
            return r;
        }
        prepareRender(ctx) {
            const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
            const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
            const toRender = this._render(visibleStartLineNumber, visibleEndLineNumber, this._getDecorations(ctx));
            const output = [];
            for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
                const lineIndex = lineNumber - visibleStartLineNumber;
                const decorations = toRender[lineIndex].getDecorations();
                let lineOutput = '';
                for (const decoration of decorations) {
                    lineOutput += '<div class="cmdr ' + decoration.className + '" style=""></div>';
                }
                output[lineIndex] = lineOutput;
            }
            this._renderResult = output;
        }
        render(startLineNumber, lineNumber) {
            if (!this._renderResult) {
                return '';
            }
            return this._renderResult[lineNumber - startLineNumber];
        }
    }
    exports.MarginViewLineDecorationsOverlay = MarginViewLineDecorationsOverlay;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[595/*vs/editor/browser/viewParts/rulers/rulers*/], __M([1/*require*/,0/*exports*/,39/*vs/base/browser/fastDomNode*/,56/*vs/editor/browser/view/viewPart*/,493/*vs/css!vs/editor/browser/viewParts/rulers/rulers*/]), function (require, exports, fastDomNode_1, viewPart_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Rulers = void 0;
    class Rulers extends viewPart_1.ViewPart {
        constructor(context) {
            super(context);
            this.domNode = (0, fastDomNode_1.createFastDomNode)(document.createElement('div'));
            this.domNode.setAttribute('role', 'presentation');
            this.domNode.setAttribute('aria-hidden', 'true');
            this.domNode.setClassName('view-rulers');
            this._renderedRulers = [];
            const options = this._context.configuration.options;
            this._rulers = options.get(103 /* EditorOption.rulers */);
            this._typicalHalfwidthCharacterWidth = options.get(50 /* EditorOption.fontInfo */).typicalHalfwidthCharacterWidth;
        }
        dispose() {
            super.dispose();
        }
        // --- begin event handlers
        onConfigurationChanged(e) {
            const options = this._context.configuration.options;
            this._rulers = options.get(103 /* EditorOption.rulers */);
            this._typicalHalfwidthCharacterWidth = options.get(50 /* EditorOption.fontInfo */).typicalHalfwidthCharacterWidth;
            return true;
        }
        onScrollChanged(e) {
            return e.scrollHeightChanged;
        }
        // --- end event handlers
        prepareRender(ctx) {
            // Nothing to read
        }
        _ensureRulersCount() {
            const currentCount = this._renderedRulers.length;
            const desiredCount = this._rulers.length;
            if (currentCount === desiredCount) {
                // Nothing to do
                return;
            }
            if (currentCount < desiredCount) {
                const { tabSize } = this._context.viewModel.model.getOptions();
                const rulerWidth = tabSize;
                let addCount = desiredCount - currentCount;
                while (addCount > 0) {
                    const node = (0, fastDomNode_1.createFastDomNode)(document.createElement('div'));
                    node.setClassName('view-ruler');
                    node.setWidth(rulerWidth);
                    this.domNode.appendChild(node);
                    this._renderedRulers.push(node);
                    addCount--;
                }
                return;
            }
            let removeCount = currentCount - desiredCount;
            while (removeCount > 0) {
                const node = this._renderedRulers.pop();
                this.domNode.removeChild(node);
                removeCount--;
            }
        }
        render(ctx) {
            this._ensureRulersCount();
            for (let i = 0, len = this._rulers.length; i < len; i++) {
                const node = this._renderedRulers[i];
                const ruler = this._rulers[i];
                node.setBoxShadow(ruler.color ? `1px 0 0 0 ${ruler.color} inset` : ``);
                node.setHeight(Math.min(ctx.scrollHeight, 1000000));
                node.setLeft(ruler.column * this._typicalHalfwidthCharacterWidth);
            }
        }
    }
    exports.Rulers = Rulers;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[596/*vs/editor/browser/viewParts/scrollDecoration/scrollDecoration*/], __M([1/*require*/,0/*exports*/,39/*vs/base/browser/fastDomNode*/,56/*vs/editor/browser/view/viewPart*/,494/*vs/css!vs/editor/browser/viewParts/scrollDecoration/scrollDecoration*/]), function (require, exports, fastDomNode_1, viewPart_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ScrollDecorationViewPart = void 0;
    class ScrollDecorationViewPart extends viewPart_1.ViewPart {
        constructor(context) {
            super(context);
            this._scrollTop = 0;
            this._width = 0;
            this._updateWidth();
            this._shouldShow = false;
            const options = this._context.configuration.options;
            const scrollbar = options.get(104 /* EditorOption.scrollbar */);
            this._useShadows = scrollbar.useShadows;
            this._domNode = (0, fastDomNode_1.createFastDomNode)(document.createElement('div'));
            this._domNode.setAttribute('role', 'presentation');
            this._domNode.setAttribute('aria-hidden', 'true');
        }
        dispose() {
            super.dispose();
        }
        _updateShouldShow() {
            const newShouldShow = (this._useShadows && this._scrollTop > 0);
            if (this._shouldShow !== newShouldShow) {
                this._shouldShow = newShouldShow;
                return true;
            }
            return false;
        }
        getDomNode() {
            return this._domNode;
        }
        _updateWidth() {
            const options = this._context.configuration.options;
            const layoutInfo = options.get(146 /* EditorOption.layoutInfo */);
            if (layoutInfo.minimap.renderMinimap === 0 || (layoutInfo.minimap.minimapWidth > 0 && layoutInfo.minimap.minimapLeft === 0)) {
                this._width = layoutInfo.width;
            }
            else {
                this._width = layoutInfo.width - layoutInfo.verticalScrollbarWidth;
            }
        }
        // --- begin event handlers
        onConfigurationChanged(e) {
            const options = this._context.configuration.options;
            const scrollbar = options.get(104 /* EditorOption.scrollbar */);
            this._useShadows = scrollbar.useShadows;
            this._updateWidth();
            this._updateShouldShow();
            return true;
        }
        onScrollChanged(e) {
            this._scrollTop = e.scrollTop;
            return this._updateShouldShow();
        }
        // --- end event handlers
        prepareRender(ctx) {
            // Nothing to read
        }
        render(ctx) {
            this._domNode.setWidth(this._width);
            this._domNode.setClassName(this._shouldShow ? 'scroll-decoration' : '');
        }
    }
    exports.ScrollDecorationViewPart = ScrollDecorationViewPart;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[597/*vs/editor/browser/viewParts/viewZones/viewZones*/], __M([1/*require*/,0/*exports*/,39/*vs/base/browser/fastDomNode*/,8/*vs/base/common/errors*/,56/*vs/editor/browser/view/viewPart*/,9/*vs/editor/common/core/position*/]), function (require, exports, fastDomNode_1, errors_1, viewPart_1, position_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ViewZones = void 0;
    const invalidFunc = () => { throw new Error(`Invalid change accessor`); };
    class ViewZones extends viewPart_1.ViewPart {
        constructor(context) {
            super(context);
            const options = this._context.configuration.options;
            const layoutInfo = options.get(146 /* EditorOption.layoutInfo */);
            this._lineHeight = options.get(67 /* EditorOption.lineHeight */);
            this._contentWidth = layoutInfo.contentWidth;
            this._contentLeft = layoutInfo.contentLeft;
            this.domNode = (0, fastDomNode_1.createFastDomNode)(document.createElement('div'));
            this.domNode.setClassName('view-zones');
            this.domNode.setPosition('absolute');
            this.domNode.setAttribute('role', 'presentation');
            this.domNode.setAttribute('aria-hidden', 'true');
            this.marginDomNode = (0, fastDomNode_1.createFastDomNode)(document.createElement('div'));
            this.marginDomNode.setClassName('margin-view-zones');
            this.marginDomNode.setPosition('absolute');
            this.marginDomNode.setAttribute('role', 'presentation');
            this.marginDomNode.setAttribute('aria-hidden', 'true');
            this._zones = {};
        }
        dispose() {
            super.dispose();
            this._zones = {};
        }
        // ---- begin view event handlers
        _recomputeWhitespacesProps() {
            const whitespaces = this._context.viewLayout.getWhitespaces();
            const oldWhitespaces = new Map();
            for (const whitespace of whitespaces) {
                oldWhitespaces.set(whitespace.id, whitespace);
            }
            let hadAChange = false;
            this._context.viewModel.changeWhitespace((whitespaceAccessor) => {
                const keys = Object.keys(this._zones);
                for (let i = 0, len = keys.length; i < len; i++) {
                    const id = keys[i];
                    const zone = this._zones[id];
                    const props = this._computeWhitespaceProps(zone.delegate);
                    zone.isInHiddenArea = props.isInHiddenArea;
                    const oldWhitespace = oldWhitespaces.get(id);
                    if (oldWhitespace && (oldWhitespace.afterLineNumber !== props.afterViewLineNumber || oldWhitespace.height !== props.heightInPx)) {
                        whitespaceAccessor.changeOneWhitespace(id, props.afterViewLineNumber, props.heightInPx);
                        this._safeCallOnComputedHeight(zone.delegate, props.heightInPx);
                        hadAChange = true;
                    }
                }
            });
            return hadAChange;
        }
        onConfigurationChanged(e) {
            const options = this._context.configuration.options;
            const layoutInfo = options.get(146 /* EditorOption.layoutInfo */);
            this._lineHeight = options.get(67 /* EditorOption.lineHeight */);
            this._contentWidth = layoutInfo.contentWidth;
            this._contentLeft = layoutInfo.contentLeft;
            if (e.hasChanged(67 /* EditorOption.lineHeight */)) {
                this._recomputeWhitespacesProps();
            }
            return true;
        }
        onLineMappingChanged(e) {
            return this._recomputeWhitespacesProps();
        }
        onLinesDeleted(e) {
            return true;
        }
        onScrollChanged(e) {
            return e.scrollTopChanged || e.scrollWidthChanged;
        }
        onZonesChanged(e) {
            return true;
        }
        onLinesInserted(e) {
            return true;
        }
        // ---- end view event handlers
        _getZoneOrdinal(zone) {
            return zone.ordinal ?? zone.afterColumn ?? 10000;
        }
        _computeWhitespaceProps(zone) {
            if (zone.afterLineNumber === 0) {
                return {
                    isInHiddenArea: false,
                    afterViewLineNumber: 0,
                    heightInPx: this._heightInPixels(zone),
                    minWidthInPx: this._minWidthInPixels(zone)
                };
            }
            let zoneAfterModelPosition;
            if (typeof zone.afterColumn !== 'undefined') {
                zoneAfterModelPosition = this._context.viewModel.model.validatePosition({
                    lineNumber: zone.afterLineNumber,
                    column: zone.afterColumn
                });
            }
            else {
                const validAfterLineNumber = this._context.viewModel.model.validatePosition({
                    lineNumber: zone.afterLineNumber,
                    column: 1
                }).lineNumber;
                zoneAfterModelPosition = new position_1.Position(validAfterLineNumber, this._context.viewModel.model.getLineMaxColumn(validAfterLineNumber));
            }
            let zoneBeforeModelPosition;
            if (zoneAfterModelPosition.column === this._context.viewModel.model.getLineMaxColumn(zoneAfterModelPosition.lineNumber)) {
                zoneBeforeModelPosition = this._context.viewModel.model.validatePosition({
                    lineNumber: zoneAfterModelPosition.lineNumber + 1,
                    column: 1
                });
            }
            else {
                zoneBeforeModelPosition = this._context.viewModel.model.validatePosition({
                    lineNumber: zoneAfterModelPosition.lineNumber,
                    column: zoneAfterModelPosition.column + 1
                });
            }
            const viewPosition = this._context.viewModel.coordinatesConverter.convertModelPositionToViewPosition(zoneAfterModelPosition, zone.afterColumnAffinity, true);
            const isVisible = zone.showInHiddenAreas || this._context.viewModel.coordinatesConverter.modelPositionIsVisible(zoneBeforeModelPosition);
            return {
                isInHiddenArea: !isVisible,
                afterViewLineNumber: viewPosition.lineNumber,
                heightInPx: (isVisible ? this._heightInPixels(zone) : 0),
                minWidthInPx: this._minWidthInPixels(zone)
            };
        }
        changeViewZones(callback) {
            let zonesHaveChanged = false;
            this._context.viewModel.changeWhitespace((whitespaceAccessor) => {
                const changeAccessor = {
                    addZone: (zone) => {
                        zonesHaveChanged = true;
                        return this._addZone(whitespaceAccessor, zone);
                    },
                    removeZone: (id) => {
                        if (!id) {
                            return;
                        }
                        zonesHaveChanged = this._removeZone(whitespaceAccessor, id) || zonesHaveChanged;
                    },
                    layoutZone: (id) => {
                        if (!id) {
                            return;
                        }
                        zonesHaveChanged = this._layoutZone(whitespaceAccessor, id) || zonesHaveChanged;
                    }
                };
                safeInvoke1Arg(callback, changeAccessor);
                // Invalidate changeAccessor
                changeAccessor.addZone = invalidFunc;
                changeAccessor.removeZone = invalidFunc;
                changeAccessor.layoutZone = invalidFunc;
            });
            return zonesHaveChanged;
        }
        _addZone(whitespaceAccessor, zone) {
            const props = this._computeWhitespaceProps(zone);
            const whitespaceId = whitespaceAccessor.insertWhitespace(props.afterViewLineNumber, this._getZoneOrdinal(zone), props.heightInPx, props.minWidthInPx);
            const myZone = {
                whitespaceId: whitespaceId,
                delegate: zone,
                isInHiddenArea: props.isInHiddenArea,
                isVisible: false,
                domNode: (0, fastDomNode_1.createFastDomNode)(zone.domNode),
                marginDomNode: zone.marginDomNode ? (0, fastDomNode_1.createFastDomNode)(zone.marginDomNode) : null
            };
            this._safeCallOnComputedHeight(myZone.delegate, props.heightInPx);
            myZone.domNode.setPosition('absolute');
            myZone.domNode.domNode.style.width = '100%';
            myZone.domNode.setDisplay('none');
            myZone.domNode.setAttribute('monaco-view-zone', myZone.whitespaceId);
            this.domNode.appendChild(myZone.domNode);
            if (myZone.marginDomNode) {
                myZone.marginDomNode.setPosition('absolute');
                myZone.marginDomNode.domNode.style.width = '100%';
                myZone.marginDomNode.setDisplay('none');
                myZone.marginDomNode.setAttribute('monaco-view-zone', myZone.whitespaceId);
                this.marginDomNode.appendChild(myZone.marginDomNode);
            }
            this._zones[myZone.whitespaceId] = myZone;
            this.setShouldRender();
            return myZone.whitespaceId;
        }
        _removeZone(whitespaceAccessor, id) {
            if (this._zones.hasOwnProperty(id)) {
                const zone = this._zones[id];
                delete this._zones[id];
                whitespaceAccessor.removeWhitespace(zone.whitespaceId);
                zone.domNode.removeAttribute('monaco-visible-view-zone');
                zone.domNode.removeAttribute('monaco-view-zone');
                zone.domNode.domNode.remove();
                if (zone.marginDomNode) {
                    zone.marginDomNode.removeAttribute('monaco-visible-view-zone');
                    zone.marginDomNode.removeAttribute('monaco-view-zone');
                    zone.marginDomNode.domNode.remove();
                }
                this.setShouldRender();
                return true;
            }
            return false;
        }
        _layoutZone(whitespaceAccessor, id) {
            if (this._zones.hasOwnProperty(id)) {
                const zone = this._zones[id];
                const props = this._computeWhitespaceProps(zone.delegate);
                zone.isInHiddenArea = props.isInHiddenArea;
                // const newOrdinal = this._getZoneOrdinal(zone.delegate);
                whitespaceAccessor.changeOneWhitespace(zone.whitespaceId, props.afterViewLineNumber, props.heightInPx);
                // TODO@Alex: change `newOrdinal` too
                this._safeCallOnComputedHeight(zone.delegate, props.heightInPx);
                this.setShouldRender();
                return true;
            }
            return false;
        }
        shouldSuppressMouseDownOnViewZone(id) {
            if (this._zones.hasOwnProperty(id)) {
                const zone = this._zones[id];
                return Boolean(zone.delegate.suppressMouseDown);
            }
            return false;
        }
        _heightInPixels(zone) {
            if (typeof zone.heightInPx === 'number') {
                return zone.heightInPx;
            }
            if (typeof zone.heightInLines === 'number') {
                return this._lineHeight * zone.heightInLines;
            }
            return this._lineHeight;
        }
        _minWidthInPixels(zone) {
            if (typeof zone.minWidthInPx === 'number') {
                return zone.minWidthInPx;
            }
            return 0;
        }
        _safeCallOnComputedHeight(zone, height) {
            if (typeof zone.onComputedHeight === 'function') {
                try {
                    zone.onComputedHeight(height);
                }
                catch (e) {
                    (0, errors_1.onUnexpectedError)(e);
                }
            }
        }
        _safeCallOnDomNodeTop(zone, top) {
            if (typeof zone.onDomNodeTop === 'function') {
                try {
                    zone.onDomNodeTop(top);
                }
                catch (e) {
                    (0, errors_1.onUnexpectedError)(e);
                }
            }
        }
        prepareRender(ctx) {
            // Nothing to read
        }
        render(ctx) {
            const visibleWhitespaces = ctx.viewportData.whitespaceViewportData;
            const visibleZones = {};
            let hasVisibleZone = false;
            for (const visibleWhitespace of visibleWhitespaces) {
                if (this._zones[visibleWhitespace.id].isInHiddenArea) {
                    continue;
                }
                visibleZones[visibleWhitespace.id] = visibleWhitespace;
                hasVisibleZone = true;
            }
            const keys = Object.keys(this._zones);
            for (let i = 0, len = keys.length; i < len; i++) {
                const id = keys[i];
                const zone = this._zones[id];
                let newTop = 0;
                let newHeight = 0;
                let newDisplay = 'none';
                if (visibleZones.hasOwnProperty(id)) {
                    newTop = visibleZones[id].verticalOffset - ctx.bigNumbersDelta;
                    newHeight = visibleZones[id].height;
                    newDisplay = 'block';
                    // zone is visible
                    if (!zone.isVisible) {
                        zone.domNode.setAttribute('monaco-visible-view-zone', 'true');
                        zone.isVisible = true;
                    }
                    this._safeCallOnDomNodeTop(zone.delegate, ctx.getScrolledTopFromAbsoluteTop(visibleZones[id].verticalOffset));
                }
                else {
                    if (zone.isVisible) {
                        zone.domNode.removeAttribute('monaco-visible-view-zone');
                        zone.isVisible = false;
                    }
                    this._safeCallOnDomNodeTop(zone.delegate, ctx.getScrolledTopFromAbsoluteTop(-1000000));
                }
                zone.domNode.setTop(newTop);
                zone.domNode.setHeight(newHeight);
                zone.domNode.setDisplay(newDisplay);
                if (zone.marginDomNode) {
                    zone.marginDomNode.setTop(newTop);
                    zone.marginDomNode.setHeight(newHeight);
                    zone.marginDomNode.setDisplay(newDisplay);
                }
            }
            if (hasVisibleZone) {
                this.domNode.setWidth(Math.max(ctx.scrollWidth, this._contentWidth));
                this.marginDomNode.setWidth(this._contentLeft);
            }
        }
    }
    exports.ViewZones = ViewZones;
    function safeInvoke1Arg(func, arg1) {
        try {
            return func(arg1);
        }
        catch (e) {
            (0, errors_1.onUnexpectedError)(e);
        }
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[243/*vs/editor/common/viewEvents*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ViewZonesChangedEvent = exports.ViewTokensColorsChangedEvent = exports.ViewTokensChangedEvent = exports.ViewThemeChangedEvent = exports.ViewScrollChangedEvent = exports.ViewRevealRangeRequestEvent = exports.ViewLinesInsertedEvent = exports.ViewLinesDeletedEvent = exports.ViewLinesChangedEvent = exports.ViewLineMappingChangedEvent = exports.ViewLanguageConfigurationEvent = exports.ViewFocusChangedEvent = exports.ViewFlushedEvent = exports.ViewDecorationsChangedEvent = exports.ViewCursorStateChangedEvent = exports.ViewConfigurationChangedEvent = exports.ViewCompositionEndEvent = exports.ViewCompositionStartEvent = void 0;
    class ViewCompositionStartEvent {
        constructor() {
            this.type = 0 /* ViewEventType.ViewCompositionStart */;
        }
    }
    exports.ViewCompositionStartEvent = ViewCompositionStartEvent;
    class ViewCompositionEndEvent {
        constructor() {
            this.type = 1 /* ViewEventType.ViewCompositionEnd */;
        }
    }
    exports.ViewCompositionEndEvent = ViewCompositionEndEvent;
    class ViewConfigurationChangedEvent {
        constructor(source) {
            this.type = 2 /* ViewEventType.ViewConfigurationChanged */;
            this._source = source;
        }
        hasChanged(id) {
            return this._source.hasChanged(id);
        }
    }
    exports.ViewConfigurationChangedEvent = ViewConfigurationChangedEvent;
    class ViewCursorStateChangedEvent {
        constructor(selections, modelSelections, reason) {
            this.selections = selections;
            this.modelSelections = modelSelections;
            this.reason = reason;
            this.type = 3 /* ViewEventType.ViewCursorStateChanged */;
        }
    }
    exports.ViewCursorStateChangedEvent = ViewCursorStateChangedEvent;
    class ViewDecorationsChangedEvent {
        constructor(source) {
            this.type = 4 /* ViewEventType.ViewDecorationsChanged */;
            if (source) {
                this.affectsMinimap = source.affectsMinimap;
                this.affectsOverviewRuler = source.affectsOverviewRuler;
                this.affectsGlyphMargin = source.affectsGlyphMargin;
                this.affectsLineNumber = source.affectsLineNumber;
            }
            else {
                this.affectsMinimap = true;
                this.affectsOverviewRuler = true;
                this.affectsGlyphMargin = true;
                this.affectsLineNumber = true;
            }
        }
    }
    exports.ViewDecorationsChangedEvent = ViewDecorationsChangedEvent;
    class ViewFlushedEvent {
        constructor() {
            this.type = 5 /* ViewEventType.ViewFlushed */;
            // Nothing to do
        }
    }
    exports.ViewFlushedEvent = ViewFlushedEvent;
    class ViewFocusChangedEvent {
        constructor(isFocused) {
            this.type = 6 /* ViewEventType.ViewFocusChanged */;
            this.isFocused = isFocused;
        }
    }
    exports.ViewFocusChangedEvent = ViewFocusChangedEvent;
    class ViewLanguageConfigurationEvent {
        constructor() {
            this.type = 7 /* ViewEventType.ViewLanguageConfigurationChanged */;
        }
    }
    exports.ViewLanguageConfigurationEvent = ViewLanguageConfigurationEvent;
    class ViewLineMappingChangedEvent {
        constructor() {
            this.type = 8 /* ViewEventType.ViewLineMappingChanged */;
            // Nothing to do
        }
    }
    exports.ViewLineMappingChangedEvent = ViewLineMappingChangedEvent;
    class ViewLinesChangedEvent {
        constructor(
        /**
         * The first line that has changed.
         */
        fromLineNumber, 
        /**
         * The number of lines that have changed.
         */
        count) {
            this.fromLineNumber = fromLineNumber;
            this.count = count;
            this.type = 9 /* ViewEventType.ViewLinesChanged */;
        }
    }
    exports.ViewLinesChangedEvent = ViewLinesChangedEvent;
    class ViewLinesDeletedEvent {
        constructor(fromLineNumber, toLineNumber) {
            this.type = 10 /* ViewEventType.ViewLinesDeleted */;
            this.fromLineNumber = fromLineNumber;
            this.toLineNumber = toLineNumber;
        }
    }
    exports.ViewLinesDeletedEvent = ViewLinesDeletedEvent;
    class ViewLinesInsertedEvent {
        constructor(fromLineNumber, toLineNumber) {
            this.type = 11 /* ViewEventType.ViewLinesInserted */;
            this.fromLineNumber = fromLineNumber;
            this.toLineNumber = toLineNumber;
        }
    }
    exports.ViewLinesInsertedEvent = ViewLinesInsertedEvent;
    class ViewRevealRangeRequestEvent {
        constructor(
        /**
         * Source of the call that caused the event.
         */
        source, 
        /**
         * Reduce the revealing to a minimum (e.g. avoid scrolling if the bounding box is visible and near the viewport edge).
         */
        minimalReveal, 
        /**
         * Range to be reavealed.
         */
        range, 
        /**
         * Selections to be revealed.
         */
        selections, 
        /**
         * The vertical reveal strategy.
         */
        verticalType, 
        /**
         * If true: there should be a horizontal & vertical revealing.
         * If false: there should be just a vertical revealing.
         */
        revealHorizontal, 
        /**
         * The scroll type.
         */
        scrollType) {
            this.source = source;
            this.minimalReveal = minimalReveal;
            this.range = range;
            this.selections = selections;
            this.verticalType = verticalType;
            this.revealHorizontal = revealHorizontal;
            this.scrollType = scrollType;
            this.type = 12 /* ViewEventType.ViewRevealRangeRequest */;
        }
    }
    exports.ViewRevealRangeRequestEvent = ViewRevealRangeRequestEvent;
    class ViewScrollChangedEvent {
        constructor(source) {
            this.type = 13 /* ViewEventType.ViewScrollChanged */;
            this.scrollWidth = source.scrollWidth;
            this.scrollLeft = source.scrollLeft;
            this.scrollHeight = source.scrollHeight;
            this.scrollTop = source.scrollTop;
            this.scrollWidthChanged = source.scrollWidthChanged;
            this.scrollLeftChanged = source.scrollLeftChanged;
            this.scrollHeightChanged = source.scrollHeightChanged;
            this.scrollTopChanged = source.scrollTopChanged;
        }
    }
    exports.ViewScrollChangedEvent = ViewScrollChangedEvent;
    class ViewThemeChangedEvent {
        constructor(theme) {
            this.theme = theme;
            this.type = 14 /* ViewEventType.ViewThemeChanged */;
        }
    }
    exports.ViewThemeChangedEvent = ViewThemeChangedEvent;
    class ViewTokensChangedEvent {
        constructor(ranges) {
            this.type = 15 /* ViewEventType.ViewTokensChanged */;
            this.ranges = ranges;
        }
    }
    exports.ViewTokensChangedEvent = ViewTokensChangedEvent;
    class ViewTokensColorsChangedEvent {
        constructor() {
            this.type = 16 /* ViewEventType.ViewTokensColorsChanged */;
            // Nothing to do
        }
    }
    exports.ViewTokensColorsChangedEvent = ViewTokensColorsChangedEvent;
    class ViewZonesChangedEvent {
        constructor() {
            this.type = 17 /* ViewEventType.ViewZonesChanged */;
            // Nothing to do
        }
    }
    exports.ViewZonesChangedEvent = ViewZonesChangedEvent;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[150/*vs/editor/common/viewLayout/lineDecorations*/], __M([1/*require*/,0/*exports*/,11/*vs/base/common/strings*/]), function (require, exports, strings) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.LineDecorationsNormalizer = exports.DecorationSegment = exports.LineDecoration = void 0;
    class LineDecoration {
        constructor(startColumn, endColumn, className, type) {
            this.startColumn = startColumn;
            this.endColumn = endColumn;
            this.className = className;
            this.type = type;
            this._lineDecorationBrand = undefined;
        }
        static _equals(a, b) {
            return (a.startColumn === b.startColumn
                && a.endColumn === b.endColumn
                && a.className === b.className
                && a.type === b.type);
        }
        static equalsArr(a, b) {
            const aLen = a.length;
            const bLen = b.length;
            if (aLen !== bLen) {
                return false;
            }
            for (let i = 0; i < aLen; i++) {
                if (!LineDecoration._equals(a[i], b[i])) {
                    return false;
                }
            }
            return true;
        }
        static extractWrapped(arr, startOffset, endOffset) {
            if (arr.length === 0) {
                return arr;
            }
            const startColumn = startOffset + 1;
            const endColumn = endOffset + 1;
            const lineLength = endOffset - startOffset;
            const r = [];
            let rLength = 0;
            for (const dec of arr) {
                if (dec.endColumn <= startColumn || dec.startColumn >= endColumn) {
                    continue;
                }
                r[rLength++] = new LineDecoration(Math.max(1, dec.startColumn - startColumn + 1), Math.min(lineLength + 1, dec.endColumn - startColumn + 1), dec.className, dec.type);
            }
            return r;
        }
        static filter(lineDecorations, lineNumber, minLineColumn, maxLineColumn) {
            if (lineDecorations.length === 0) {
                return [];
            }
            const result = [];
            let resultLen = 0;
            for (let i = 0, len = lineDecorations.length; i < len; i++) {
                const d = lineDecorations[i];
                const range = d.range;
                if (range.endLineNumber < lineNumber || range.startLineNumber > lineNumber) {
                    // Ignore decorations that sit outside this line
                    continue;
                }
                if (range.isEmpty() && (d.type === 0 /* InlineDecorationType.Regular */ || d.type === 3 /* InlineDecorationType.RegularAffectingLetterSpacing */)) {
                    // Ignore empty range decorations
                    continue;
                }
                const startColumn = (range.startLineNumber === lineNumber ? range.startColumn : minLineColumn);
                const endColumn = (range.endLineNumber === lineNumber ? range.endColumn : maxLineColumn);
                result[resultLen++] = new LineDecoration(startColumn, endColumn, d.inlineClassName, d.type);
            }
            return result;
        }
        static _typeCompare(a, b) {
            const ORDER = [2, 0, 1, 3];
            return ORDER[a] - ORDER[b];
        }
        static compare(a, b) {
            if (a.startColumn !== b.startColumn) {
                return a.startColumn - b.startColumn;
            }
            if (a.endColumn !== b.endColumn) {
                return a.endColumn - b.endColumn;
            }
            const typeCmp = LineDecoration._typeCompare(a.type, b.type);
            if (typeCmp !== 0) {
                return typeCmp;
            }
            if (a.className !== b.className) {
                return a.className < b.className ? -1 : 1;
            }
            return 0;
        }
    }
    exports.LineDecoration = LineDecoration;
    class DecorationSegment {
        constructor(startOffset, endOffset, className, metadata) {
            this.startOffset = startOffset;
            this.endOffset = endOffset;
            this.className = className;
            this.metadata = metadata;
        }
    }
    exports.DecorationSegment = DecorationSegment;
    class Stack {
        constructor() {
            this.stopOffsets = [];
            this.classNames = [];
            this.metadata = [];
            this.count = 0;
        }
        static _metadata(metadata) {
            let result = 0;
            for (let i = 0, len = metadata.length; i < len; i++) {
                result |= metadata[i];
            }
            return result;
        }
        consumeLowerThan(maxStopOffset, nextStartOffset, result) {
            while (this.count > 0 && this.stopOffsets[0] < maxStopOffset) {
                let i = 0;
                // Take all equal stopping offsets
                while (i + 1 < this.count && this.stopOffsets[i] === this.stopOffsets[i + 1]) {
                    i++;
                }
                // Basically we are consuming the first i + 1 elements of the stack
                result.push(new DecorationSegment(nextStartOffset, this.stopOffsets[i], this.classNames.join(' '), Stack._metadata(this.metadata)));
                nextStartOffset = this.stopOffsets[i] + 1;
                // Consume them
                this.stopOffsets.splice(0, i + 1);
                this.classNames.splice(0, i + 1);
                this.metadata.splice(0, i + 1);
                this.count -= (i + 1);
            }
            if (this.count > 0 && nextStartOffset < maxStopOffset) {
                result.push(new DecorationSegment(nextStartOffset, maxStopOffset - 1, this.classNames.join(' '), Stack._metadata(this.metadata)));
                nextStartOffset = maxStopOffset;
            }
            return nextStartOffset;
        }
        insert(stopOffset, className, metadata) {
            if (this.count === 0 || this.stopOffsets[this.count - 1] <= stopOffset) {
                // Insert at the end
                this.stopOffsets.push(stopOffset);
                this.classNames.push(className);
                this.metadata.push(metadata);
            }
            else {
                // Find the insertion position for `stopOffset`
                for (let i = 0; i < this.count; i++) {
                    if (this.stopOffsets[i] >= stopOffset) {
                        this.stopOffsets.splice(i, 0, stopOffset);
                        this.classNames.splice(i, 0, className);
                        this.metadata.splice(i, 0, metadata);
                        break;
                    }
                }
            }
            this.count++;
            return;
        }
    }
    class LineDecorationsNormalizer {
        /**
         * Normalize line decorations. Overlapping decorations will generate multiple segments
         */
        static normalize(lineContent, lineDecorations) {
            if (lineDecorations.length === 0) {
                return [];
            }
            const result = [];
            const stack = new Stack();
            let nextStartOffset = 0;
            for (let i = 0, len = lineDecorations.length; i < len; i++) {
                const d = lineDecorations[i];
                let startColumn = d.startColumn;
                let endColumn = d.endColumn;
                const className = d.className;
                const metadata = (d.type === 1 /* InlineDecorationType.Before */
                    ? 2 /* LinePartMetadata.PSEUDO_BEFORE */
                    : d.type === 2 /* InlineDecorationType.After */
                        ? 4 /* LinePartMetadata.PSEUDO_AFTER */
                        : 0);
                // If the position would end up in the middle of a high-low surrogate pair, we move it to before the pair
                if (startColumn > 1) {
                    const charCodeBefore = lineContent.charCodeAt(startColumn - 2);
                    if (strings.isHighSurrogate(charCodeBefore)) {
                        startColumn--;
                    }
                }
                if (endColumn > 1) {
                    const charCodeBefore = lineContent.charCodeAt(endColumn - 2);
                    if (strings.isHighSurrogate(charCodeBefore)) {
                        endColumn--;
                    }
                }
                const currentStartOffset = startColumn - 1;
                const currentEndOffset = endColumn - 2;
                nextStartOffset = stack.consumeLowerThan(currentStartOffset, nextStartOffset, result);
                if (stack.count === 0) {
                    nextStartOffset = currentStartOffset;
                }
                stack.insert(currentEndOffset, className, metadata);
            }
            stack.consumeLowerThan(1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */, nextStartOffset, result);
            return result;
        }
    }
    exports.LineDecorationsNormalizer = LineDecorationsNormalizer;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[598/*vs/editor/common/viewLayout/linePart*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.LinePart = void 0;
    class LinePart {
        constructor(
        /**
         * last char index of this token (not inclusive).
         */
        endIndex, type, metadata, containsRTL) {
            this.endIndex = endIndex;
            this.type = type;
            this.metadata = metadata;
            this.containsRTL = containsRTL;
            this._linePartBrand = undefined;
        }
        isWhitespace() {
            return (this.metadata & 1 /* LinePartMetadata.IS_WHITESPACE_MASK */ ? true : false);
        }
        isPseudoAfter() {
            return (this.metadata & 4 /* LinePartMetadata.PSEUDO_AFTER_MASK */ ? true : false);
        }
    }
    exports.LinePart = LinePart;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[599/*vs/editor/common/viewLayout/linesLayout*/], __M([1/*require*/,0/*exports*/,11/*vs/base/common/strings*/]), function (require, exports, strings) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.LinesLayout = exports.EditorWhitespace = void 0;
    class PendingChanges {
        constructor() {
            this._hasPending = false;
            this._inserts = [];
            this._changes = [];
            this._removes = [];
        }
        insert(x) {
            this._hasPending = true;
            this._inserts.push(x);
        }
        change(x) {
            this._hasPending = true;
            this._changes.push(x);
        }
        remove(x) {
            this._hasPending = true;
            this._removes.push(x);
        }
        mustCommit() {
            return this._hasPending;
        }
        commit(linesLayout) {
            if (!this._hasPending) {
                return;
            }
            const inserts = this._inserts;
            const changes = this._changes;
            const removes = this._removes;
            this._hasPending = false;
            this._inserts = [];
            this._changes = [];
            this._removes = [];
            linesLayout._commitPendingChanges(inserts, changes, removes);
        }
    }
    class EditorWhitespace {
        constructor(id, afterLineNumber, ordinal, height, minWidth) {
            this.id = id;
            this.afterLineNumber = afterLineNumber;
            this.ordinal = ordinal;
            this.height = height;
            this.minWidth = minWidth;
            this.prefixSum = 0;
        }
    }
    exports.EditorWhitespace = EditorWhitespace;
    /**
     * Layouting of objects that take vertical space (by having a height) and push down other objects.
     *
     * These objects are basically either text (lines) or spaces between those lines (whitespaces).
     * This provides commodity operations for working with lines that contain whitespace that pushes lines lower (vertically).
     */
    class LinesLayout {
        static { this.INSTANCE_COUNT = 0; }
        constructor(lineCount, lineHeight, paddingTop, paddingBottom) {
            this._instanceId = strings.singleLetterHash(++LinesLayout.INSTANCE_COUNT);
            this._pendingChanges = new PendingChanges();
            this._lastWhitespaceId = 0;
            this._arr = [];
            this._prefixSumValidIndex = -1;
            this._minWidth = -1; /* marker for not being computed */
            this._lineCount = lineCount;
            this._lineHeight = lineHeight;
            this._paddingTop = paddingTop;
            this._paddingBottom = paddingBottom;
        }
        /**
         * Find the insertion index for a new value inside a sorted array of values.
         * If the value is already present in the sorted array, the insertion index will be after the already existing value.
         */
        static findInsertionIndex(arr, afterLineNumber, ordinal) {
            let low = 0;
            let high = arr.length;
            while (low < high) {
                const mid = ((low + high) >>> 1);
                if (afterLineNumber === arr[mid].afterLineNumber) {
                    if (ordinal < arr[mid].ordinal) {
                        high = mid;
                    }
                    else {
                        low = mid + 1;
                    }
                }
                else if (afterLineNumber < arr[mid].afterLineNumber) {
                    high = mid;
                }
                else {
                    low = mid + 1;
                }
            }
            return low;
        }
        /**
         * Change the height of a line in pixels.
         */
        setLineHeight(lineHeight) {
            this._checkPendingChanges();
            this._lineHeight = lineHeight;
        }
        /**
         * Changes the padding used to calculate vertical offsets.
         */
        setPadding(paddingTop, paddingBottom) {
            this._paddingTop = paddingTop;
            this._paddingBottom = paddingBottom;
        }
        /**
         * Set the number of lines.
         *
         * @param lineCount New number of lines.
         */
        onFlushed(lineCount) {
            this._checkPendingChanges();
            this._lineCount = lineCount;
        }
        changeWhitespace(callback) {
            let hadAChange = false;
            try {
                const accessor = {
                    insertWhitespace: (afterLineNumber, ordinal, heightInPx, minWidth) => {
                        hadAChange = true;
                        afterLineNumber = afterLineNumber | 0;
                        ordinal = ordinal | 0;
                        heightInPx = heightInPx | 0;
                        minWidth = minWidth | 0;
                        const id = this._instanceId + (++this._lastWhitespaceId);
                        this._pendingChanges.insert(new EditorWhitespace(id, afterLineNumber, ordinal, heightInPx, minWidth));
                        return id;
                    },
                    changeOneWhitespace: (id, newAfterLineNumber, newHeight) => {
                        hadAChange = true;
                        newAfterLineNumber = newAfterLineNumber | 0;
                        newHeight = newHeight | 0;
                        this._pendingChanges.change({ id, newAfterLineNumber, newHeight });
                    },
                    removeWhitespace: (id) => {
                        hadAChange = true;
                        this._pendingChanges.remove({ id });
                    }
                };
                callback(accessor);
            }
            finally {
                this._pendingChanges.commit(this);
            }
            return hadAChange;
        }
        _commitPendingChanges(inserts, changes, removes) {
            if (inserts.length > 0 || removes.length > 0) {
                this._minWidth = -1; /* marker for not being computed */
            }
            if (inserts.length + changes.length + removes.length <= 1) {
                // when only one thing happened, handle it "delicately"
                for (const insert of inserts) {
                    this._insertWhitespace(insert);
                }
                for (const change of changes) {
                    this._changeOneWhitespace(change.id, change.newAfterLineNumber, change.newHeight);
                }
                for (const remove of removes) {
                    const index = this._findWhitespaceIndex(remove.id);
                    if (index === -1) {
                        continue;
                    }
                    this._removeWhitespace(index);
                }
                return;
            }
            // simply rebuild the entire datastructure
            const toRemove = new Set();
            for (const remove of removes) {
                toRemove.add(remove.id);
            }
            const toChange = new Map();
            for (const change of changes) {
                toChange.set(change.id, change);
            }
            const applyRemoveAndChange = (whitespaces) => {
                const result = [];
                for (const whitespace of whitespaces) {
                    if (toRemove.has(whitespace.id)) {
                        continue;
                    }
                    if (toChange.has(whitespace.id)) {
                        const change = toChange.get(whitespace.id);
                        whitespace.afterLineNumber = change.newAfterLineNumber;
                        whitespace.height = change.newHeight;
                    }
                    result.push(whitespace);
                }
                return result;
            };
            const result = applyRemoveAndChange(this._arr).concat(applyRemoveAndChange(inserts));
            result.sort((a, b) => {
                if (a.afterLineNumber === b.afterLineNumber) {
                    return a.ordinal - b.ordinal;
                }
                return a.afterLineNumber - b.afterLineNumber;
            });
            this._arr = result;
            this._prefixSumValidIndex = -1;
        }
        _checkPendingChanges() {
            if (this._pendingChanges.mustCommit()) {
                this._pendingChanges.commit(this);
            }
        }
        _insertWhitespace(whitespace) {
            const insertIndex = LinesLayout.findInsertionIndex(this._arr, whitespace.afterLineNumber, whitespace.ordinal);
            this._arr.splice(insertIndex, 0, whitespace);
            this._prefixSumValidIndex = Math.min(this._prefixSumValidIndex, insertIndex - 1);
        }
        _findWhitespaceIndex(id) {
            const arr = this._arr;
            for (let i = 0, len = arr.length; i < len; i++) {
                if (arr[i].id === id) {
                    return i;
                }
            }
            return -1;
        }
        _changeOneWhitespace(id, newAfterLineNumber, newHeight) {
            const index = this._findWhitespaceIndex(id);
            if (index === -1) {
                return;
            }
            if (this._arr[index].height !== newHeight) {
                this._arr[index].height = newHeight;
                this._prefixSumValidIndex = Math.min(this._prefixSumValidIndex, index - 1);
            }
            if (this._arr[index].afterLineNumber !== newAfterLineNumber) {
                // `afterLineNumber` changed for this whitespace
                // Record old whitespace
                const whitespace = this._arr[index];
                // Since changing `afterLineNumber` can trigger a reordering, we're gonna remove this whitespace
                this._removeWhitespace(index);
                whitespace.afterLineNumber = newAfterLineNumber;
                // And add it again
                this._insertWhitespace(whitespace);
            }
        }
        _removeWhitespace(removeIndex) {
            this._arr.splice(removeIndex, 1);
            this._prefixSumValidIndex = Math.min(this._prefixSumValidIndex, removeIndex - 1);
        }
        /**
         * Notify the layouter that lines have been deleted (a continuous zone of lines).
         *
         * @param fromLineNumber The line number at which the deletion started, inclusive
         * @param toLineNumber The line number at which the deletion ended, inclusive
         */
        onLinesDeleted(fromLineNumber, toLineNumber) {
            this._checkPendingChanges();
            fromLineNumber = fromLineNumber | 0;
            toLineNumber = toLineNumber | 0;
            this._lineCount -= (toLineNumber - fromLineNumber + 1);
            for (let i = 0, len = this._arr.length; i < len; i++) {
                const afterLineNumber = this._arr[i].afterLineNumber;
                if (fromLineNumber <= afterLineNumber && afterLineNumber <= toLineNumber) {
                    // The line this whitespace was after has been deleted
                    //  => move whitespace to before first deleted line
                    this._arr[i].afterLineNumber = fromLineNumber - 1;
                }
                else if (afterLineNumber > toLineNumber) {
                    // The line this whitespace was after has been moved up
                    //  => move whitespace up
                    this._arr[i].afterLineNumber -= (toLineNumber - fromLineNumber + 1);
                }
            }
        }
        /**
         * Notify the layouter that lines have been inserted (a continuous zone of lines).
         *
         * @param fromLineNumber The line number at which the insertion started, inclusive
         * @param toLineNumber The line number at which the insertion ended, inclusive.
         */
        onLinesInserted(fromLineNumber, toLineNumber) {
            this._checkPendingChanges();
            fromLineNumber = fromLineNumber | 0;
            toLineNumber = toLineNumber | 0;
            this._lineCount += (toLineNumber - fromLineNumber + 1);
            for (let i = 0, len = this._arr.length; i < len; i++) {
                const afterLineNumber = this._arr[i].afterLineNumber;
                if (fromLineNumber <= afterLineNumber) {
                    this._arr[i].afterLineNumber += (toLineNumber - fromLineNumber + 1);
                }
            }
        }
        /**
         * Get the sum of all the whitespaces.
         */
        getWhitespacesTotalHeight() {
            this._checkPendingChanges();
            if (this._arr.length === 0) {
                return 0;
            }
            return this.getWhitespacesAccumulatedHeight(this._arr.length - 1);
        }
        /**
         * Return the sum of the heights of the whitespaces at [0..index].
         * This includes the whitespace at `index`.
         *
         * @param index The index of the whitespace.
         * @return The sum of the heights of all whitespaces before the one at `index`, including the one at `index`.
         */
        getWhitespacesAccumulatedHeight(index) {
            this._checkPendingChanges();
            index = index | 0;
            let startIndex = Math.max(0, this._prefixSumValidIndex + 1);
            if (startIndex === 0) {
                this._arr[0].prefixSum = this._arr[0].height;
                startIndex++;
            }
            for (let i = startIndex; i <= index; i++) {
                this._arr[i].prefixSum = this._arr[i - 1].prefixSum + this._arr[i].height;
            }
            this._prefixSumValidIndex = Math.max(this._prefixSumValidIndex, index);
            return this._arr[index].prefixSum;
        }
        /**
         * Get the sum of heights for all objects.
         *
         * @return The sum of heights for all objects.
         */
        getLinesTotalHeight() {
            this._checkPendingChanges();
            const linesHeight = this._lineHeight * this._lineCount;
            const whitespacesHeight = this.getWhitespacesTotalHeight();
            return linesHeight + whitespacesHeight + this._paddingTop + this._paddingBottom;
        }
        /**
         * Returns the accumulated height of whitespaces before the given line number.
         *
         * @param lineNumber The line number
         */
        getWhitespaceAccumulatedHeightBeforeLineNumber(lineNumber) {
            this._checkPendingChanges();
            lineNumber = lineNumber | 0;
            const lastWhitespaceBeforeLineNumber = this._findLastWhitespaceBeforeLineNumber(lineNumber);
            if (lastWhitespaceBeforeLineNumber === -1) {
                return 0;
            }
            return this.getWhitespacesAccumulatedHeight(lastWhitespaceBeforeLineNumber);
        }
        _findLastWhitespaceBeforeLineNumber(lineNumber) {
            lineNumber = lineNumber | 0;
            // Find the whitespace before line number
            const arr = this._arr;
            let low = 0;
            let high = arr.length - 1;
            while (low <= high) {
                const delta = (high - low) | 0;
                const halfDelta = (delta / 2) | 0;
                const mid = (low + halfDelta) | 0;
                if (arr[mid].afterLineNumber < lineNumber) {
                    if (mid + 1 >= arr.length || arr[mid + 1].afterLineNumber >= lineNumber) {
                        return mid;
                    }
                    else {
                        low = (mid + 1) | 0;
                    }
                }
                else {
                    high = (mid - 1) | 0;
                }
            }
            return -1;
        }
        _findFirstWhitespaceAfterLineNumber(lineNumber) {
            lineNumber = lineNumber | 0;
            const lastWhitespaceBeforeLineNumber = this._findLastWhitespaceBeforeLineNumber(lineNumber);
            const firstWhitespaceAfterLineNumber = lastWhitespaceBeforeLineNumber + 1;
            if (firstWhitespaceAfterLineNumber < this._arr.length) {
                return firstWhitespaceAfterLineNumber;
            }
            return -1;
        }
        /**
         * Find the index of the first whitespace which has `afterLineNumber` >= `lineNumber`.
         * @return The index of the first whitespace with `afterLineNumber` >= `lineNumber` or -1 if no whitespace is found.
         */
        getFirstWhitespaceIndexAfterLineNumber(lineNumber) {
            this._checkPendingChanges();
            lineNumber = lineNumber | 0;
            return this._findFirstWhitespaceAfterLineNumber(lineNumber);
        }
        /**
         * Get the vertical offset (the sum of heights for all objects above) a certain line number.
         *
         * @param lineNumber The line number
         * @return The sum of heights for all objects above `lineNumber`.
         */
        getVerticalOffsetForLineNumber(lineNumber, includeViewZones = false) {
            this._checkPendingChanges();
            lineNumber = lineNumber | 0;
            let previousLinesHeight;
            if (lineNumber > 1) {
                previousLinesHeight = this._lineHeight * (lineNumber - 1);
            }
            else {
                previousLinesHeight = 0;
            }
            const previousWhitespacesHeight = this.getWhitespaceAccumulatedHeightBeforeLineNumber(lineNumber - (includeViewZones ? 1 : 0));
            return previousLinesHeight + previousWhitespacesHeight + this._paddingTop;
        }
        /**
         * Get the vertical offset (the sum of heights for all objects above) a certain line number.
         *
         * @param lineNumber The line number
         * @return The sum of heights for all objects above `lineNumber`.
         */
        getVerticalOffsetAfterLineNumber(lineNumber, includeViewZones = false) {
            this._checkPendingChanges();
            lineNumber = lineNumber | 0;
            const previousLinesHeight = this._lineHeight * lineNumber;
            const previousWhitespacesHeight = this.getWhitespaceAccumulatedHeightBeforeLineNumber(lineNumber + (includeViewZones ? 1 : 0));
            return previousLinesHeight + previousWhitespacesHeight + this._paddingTop;
        }
        /**
         * The maximum min width for all whitespaces.
         */
        getWhitespaceMinWidth() {
            this._checkPendingChanges();
            if (this._minWidth === -1) {
                let minWidth = 0;
                for (let i = 0, len = this._arr.length; i < len; i++) {
                    minWidth = Math.max(minWidth, this._arr[i].minWidth);
                }
                this._minWidth = minWidth;
            }
            return this._minWidth;
        }
        /**
         * Check if `verticalOffset` is below all lines.
         */
        isAfterLines(verticalOffset) {
            this._checkPendingChanges();
            const totalHeight = this.getLinesTotalHeight();
            return verticalOffset > totalHeight;
        }
        isInTopPadding(verticalOffset) {
            if (this._paddingTop === 0) {
                return false;
            }
            this._checkPendingChanges();
            return (verticalOffset < this._paddingTop);
        }
        isInBottomPadding(verticalOffset) {
            if (this._paddingBottom === 0) {
                return false;
            }
            this._checkPendingChanges();
            const totalHeight = this.getLinesTotalHeight();
            return (verticalOffset >= totalHeight - this._paddingBottom);
        }
        /**
         * Find the first line number that is at or after vertical offset `verticalOffset`.
         * i.e. if getVerticalOffsetForLine(line) is x and getVerticalOffsetForLine(line + 1) is y, then
         * getLineNumberAtOrAfterVerticalOffset(i) = line, x <= i < y.
         *
         * @param verticalOffset The vertical offset to search at.
         * @return The line number at or after vertical offset `verticalOffset`.
         */
        getLineNumberAtOrAfterVerticalOffset(verticalOffset) {
            this._checkPendingChanges();
            verticalOffset = verticalOffset | 0;
            if (verticalOffset < 0) {
                return 1;
            }
            const linesCount = this._lineCount | 0;
            const lineHeight = this._lineHeight;
            let minLineNumber = 1;
            let maxLineNumber = linesCount;
            while (minLineNumber < maxLineNumber) {
                const midLineNumber = ((minLineNumber + maxLineNumber) / 2) | 0;
                const midLineNumberVerticalOffset = this.getVerticalOffsetForLineNumber(midLineNumber) | 0;
                if (verticalOffset >= midLineNumberVerticalOffset + lineHeight) {
                    // vertical offset is after mid line number
                    minLineNumber = midLineNumber + 1;
                }
                else if (verticalOffset >= midLineNumberVerticalOffset) {
                    // Hit
                    return midLineNumber;
                }
                else {
                    // vertical offset is before mid line number, but mid line number could still be what we're searching for
                    maxLineNumber = midLineNumber;
                }
            }
            if (minLineNumber > linesCount) {
                return linesCount;
            }
            return minLineNumber;
        }
        /**
         * Get all the lines and their relative vertical offsets that are positioned between `verticalOffset1` and `verticalOffset2`.
         *
         * @param verticalOffset1 The beginning of the viewport.
         * @param verticalOffset2 The end of the viewport.
         * @return A structure describing the lines positioned between `verticalOffset1` and `verticalOffset2`.
         */
        getLinesViewportData(verticalOffset1, verticalOffset2) {
            this._checkPendingChanges();
            verticalOffset1 = verticalOffset1 | 0;
            verticalOffset2 = verticalOffset2 | 0;
            const lineHeight = this._lineHeight;
            // Find first line number
            // We don't live in a perfect world, so the line number might start before or after verticalOffset1
            const startLineNumber = this.getLineNumberAtOrAfterVerticalOffset(verticalOffset1) | 0;
            const startLineNumberVerticalOffset = this.getVerticalOffsetForLineNumber(startLineNumber) | 0;
            let endLineNumber = this._lineCount | 0;
            // Also keep track of what whitespace we've got
            let whitespaceIndex = this.getFirstWhitespaceIndexAfterLineNumber(startLineNumber) | 0;
            const whitespaceCount = this.getWhitespacesCount() | 0;
            let currentWhitespaceHeight;
            let currentWhitespaceAfterLineNumber;
            if (whitespaceIndex === -1) {
                whitespaceIndex = whitespaceCount;
                currentWhitespaceAfterLineNumber = endLineNumber + 1;
                currentWhitespaceHeight = 0;
            }
            else {
                currentWhitespaceAfterLineNumber = this.getAfterLineNumberForWhitespaceIndex(whitespaceIndex) | 0;
                currentWhitespaceHeight = this.getHeightForWhitespaceIndex(whitespaceIndex) | 0;
            }
            let currentVerticalOffset = startLineNumberVerticalOffset;
            let currentLineRelativeOffset = currentVerticalOffset;
            // IE (all versions) cannot handle units above about 1,533,908 px, so every 500k pixels bring numbers down
            const STEP_SIZE = 500000;
            let bigNumbersDelta = 0;
            if (startLineNumberVerticalOffset >= STEP_SIZE) {
                // Compute a delta that guarantees that lines are positioned at `lineHeight` increments
                bigNumbersDelta = Math.floor(startLineNumberVerticalOffset / STEP_SIZE) * STEP_SIZE;
                bigNumbersDelta = Math.floor(bigNumbersDelta / lineHeight) * lineHeight;
                currentLineRelativeOffset -= bigNumbersDelta;
            }
            const linesOffsets = [];
            const verticalCenter = verticalOffset1 + (verticalOffset2 - verticalOffset1) / 2;
            let centeredLineNumber = -1;
            // Figure out how far the lines go
            for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
                if (centeredLineNumber === -1) {
                    const currentLineTop = currentVerticalOffset;
                    const currentLineBottom = currentVerticalOffset + lineHeight;
                    if ((currentLineTop <= verticalCenter && verticalCenter < currentLineBottom) || currentLineTop > verticalCenter) {
                        centeredLineNumber = lineNumber;
                    }
                }
                // Count current line height in the vertical offsets
                currentVerticalOffset += lineHeight;
                linesOffsets[lineNumber - startLineNumber] = currentLineRelativeOffset;
                // Next line starts immediately after this one
                currentLineRelativeOffset += lineHeight;
                while (currentWhitespaceAfterLineNumber === lineNumber) {
                    // Push down next line with the height of the current whitespace
                    currentLineRelativeOffset += currentWhitespaceHeight;
                    // Count current whitespace in the vertical offsets
                    currentVerticalOffset += currentWhitespaceHeight;
                    whitespaceIndex++;
                    if (whitespaceIndex >= whitespaceCount) {
                        currentWhitespaceAfterLineNumber = endLineNumber + 1;
                    }
                    else {
                        currentWhitespaceAfterLineNumber = this.getAfterLineNumberForWhitespaceIndex(whitespaceIndex) | 0;
                        currentWhitespaceHeight = this.getHeightForWhitespaceIndex(whitespaceIndex) | 0;
                    }
                }
                if (currentVerticalOffset >= verticalOffset2) {
                    // We have covered the entire viewport area, time to stop
                    endLineNumber = lineNumber;
                    break;
                }
            }
            if (centeredLineNumber === -1) {
                centeredLineNumber = endLineNumber;
            }
            const endLineNumberVerticalOffset = this.getVerticalOffsetForLineNumber(endLineNumber) | 0;
            let completelyVisibleStartLineNumber = startLineNumber;
            let completelyVisibleEndLineNumber = endLineNumber;
            if (completelyVisibleStartLineNumber < completelyVisibleEndLineNumber) {
                if (startLineNumberVerticalOffset < verticalOffset1) {
                    completelyVisibleStartLineNumber++;
                }
            }
            if (completelyVisibleStartLineNumber < completelyVisibleEndLineNumber) {
                if (endLineNumberVerticalOffset + lineHeight > verticalOffset2) {
                    completelyVisibleEndLineNumber--;
                }
            }
            return {
                bigNumbersDelta: bigNumbersDelta,
                startLineNumber: startLineNumber,
                endLineNumber: endLineNumber,
                relativeVerticalOffset: linesOffsets,
                centeredLineNumber: centeredLineNumber,
                completelyVisibleStartLineNumber: completelyVisibleStartLineNumber,
                completelyVisibleEndLineNumber: completelyVisibleEndLineNumber,
                lineHeight: this._lineHeight,
            };
        }
        getVerticalOffsetForWhitespaceIndex(whitespaceIndex) {
            this._checkPendingChanges();
            whitespaceIndex = whitespaceIndex | 0;
            const afterLineNumber = this.getAfterLineNumberForWhitespaceIndex(whitespaceIndex);
            let previousLinesHeight;
            if (afterLineNumber >= 1) {
                previousLinesHeight = this._lineHeight * afterLineNumber;
            }
            else {
                previousLinesHeight = 0;
            }
            let previousWhitespacesHeight;
            if (whitespaceIndex > 0) {
                previousWhitespacesHeight = this.getWhitespacesAccumulatedHeight(whitespaceIndex - 1);
            }
            else {
                previousWhitespacesHeight = 0;
            }
            return previousLinesHeight + previousWhitespacesHeight + this._paddingTop;
        }
        getWhitespaceIndexAtOrAfterVerticallOffset(verticalOffset) {
            this._checkPendingChanges();
            verticalOffset = verticalOffset | 0;
            let minWhitespaceIndex = 0;
            let maxWhitespaceIndex = this.getWhitespacesCount() - 1;
            if (maxWhitespaceIndex < 0) {
                return -1;
            }
            // Special case: nothing to be found
            const maxWhitespaceVerticalOffset = this.getVerticalOffsetForWhitespaceIndex(maxWhitespaceIndex);
            const maxWhitespaceHeight = this.getHeightForWhitespaceIndex(maxWhitespaceIndex);
            if (verticalOffset >= maxWhitespaceVerticalOffset + maxWhitespaceHeight) {
                return -1;
            }
            while (minWhitespaceIndex < maxWhitespaceIndex) {
                const midWhitespaceIndex = Math.floor((minWhitespaceIndex + maxWhitespaceIndex) / 2);
                const midWhitespaceVerticalOffset = this.getVerticalOffsetForWhitespaceIndex(midWhitespaceIndex);
                const midWhitespaceHeight = this.getHeightForWhitespaceIndex(midWhitespaceIndex);
                if (verticalOffset >= midWhitespaceVerticalOffset + midWhitespaceHeight) {
                    // vertical offset is after whitespace
                    minWhitespaceIndex = midWhitespaceIndex + 1;
                }
                else if (verticalOffset >= midWhitespaceVerticalOffset) {
                    // Hit
                    return midWhitespaceIndex;
                }
                else {
                    // vertical offset is before whitespace, but midWhitespaceIndex might still be what we're searching for
                    maxWhitespaceIndex = midWhitespaceIndex;
                }
            }
            return minWhitespaceIndex;
        }
        /**
         * Get exactly the whitespace that is layouted at `verticalOffset`.
         *
         * @param verticalOffset The vertical offset.
         * @return Precisely the whitespace that is layouted at `verticaloffset` or null.
         */
        getWhitespaceAtVerticalOffset(verticalOffset) {
            this._checkPendingChanges();
            verticalOffset = verticalOffset | 0;
            const candidateIndex = this.getWhitespaceIndexAtOrAfterVerticallOffset(verticalOffset);
            if (candidateIndex < 0) {
                return null;
            }
            if (candidateIndex >= this.getWhitespacesCount()) {
                return null;
            }
            const candidateTop = this.getVerticalOffsetForWhitespaceIndex(candidateIndex);
            if (candidateTop > verticalOffset) {
                return null;
            }
            const candidateHeight = this.getHeightForWhitespaceIndex(candidateIndex);
            const candidateId = this.getIdForWhitespaceIndex(candidateIndex);
            const candidateAfterLineNumber = this.getAfterLineNumberForWhitespaceIndex(candidateIndex);
            return {
                id: candidateId,
                afterLineNumber: candidateAfterLineNumber,
                verticalOffset: candidateTop,
                height: candidateHeight
            };
        }
        /**
         * Get a list of whitespaces that are positioned between `verticalOffset1` and `verticalOffset2`.
         *
         * @param verticalOffset1 The beginning of the viewport.
         * @param verticalOffset2 The end of the viewport.
         * @return An array with all the whitespaces in the viewport. If no whitespace is in viewport, the array is empty.
         */
        getWhitespaceViewportData(verticalOffset1, verticalOffset2) {
            this._checkPendingChanges();
            verticalOffset1 = verticalOffset1 | 0;
            verticalOffset2 = verticalOffset2 | 0;
            const startIndex = this.getWhitespaceIndexAtOrAfterVerticallOffset(verticalOffset1);
            const endIndex = this.getWhitespacesCount() - 1;
            if (startIndex < 0) {
                return [];
            }
            const result = [];
            for (let i = startIndex; i <= endIndex; i++) {
                const top = this.getVerticalOffsetForWhitespaceIndex(i);
                const height = this.getHeightForWhitespaceIndex(i);
                if (top >= verticalOffset2) {
                    break;
                }
                result.push({
                    id: this.getIdForWhitespaceIndex(i),
                    afterLineNumber: this.getAfterLineNumberForWhitespaceIndex(i),
                    verticalOffset: top,
                    height: height
                });
            }
            return result;
        }
        /**
         * Get all whitespaces.
         */
        getWhitespaces() {
            this._checkPendingChanges();
            return this._arr.slice(0);
        }
        /**
         * The number of whitespaces.
         */
        getWhitespacesCount() {
            this._checkPendingChanges();
            return this._arr.length;
        }
        /**
         * Get the `id` for whitespace at index `index`.
         *
         * @param index The index of the whitespace.
         * @return `id` of whitespace at `index`.
         */
        getIdForWhitespaceIndex(index) {
            this._checkPendingChanges();
            index = index | 0;
            return this._arr[index].id;
        }
        /**
         * Get the `afterLineNumber` for whitespace at index `index`.
         *
         * @param index The index of the whitespace.
         * @return `afterLineNumber` of whitespace at `index`.
         */
        getAfterLineNumberForWhitespaceIndex(index) {
            this._checkPendingChanges();
            index = index | 0;
            return this._arr[index].afterLineNumber;
        }
        /**
         * Get the `height` for whitespace at index `index`.
         *
         * @param index The index of the whitespace.
         * @return `height` of whitespace at `index`.
         */
        getHeightForWhitespaceIndex(index) {
            this._checkPendingChanges();
            index = index | 0;
            return this._arr[index].height;
        }
    }
    exports.LinesLayout = LinesLayout;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[600/*vs/editor/common/viewLayout/viewLinesViewportData*/], __M([1/*require*/,0/*exports*/,4/*vs/editor/common/core/range*/]), function (require, exports, range_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ViewportData = void 0;
    /**
     * Contains all data needed to render at a specific viewport.
     */
    class ViewportData {
        constructor(selections, partialData, whitespaceViewportData, model) {
            this.selections = selections;
            this.startLineNumber = partialData.startLineNumber | 0;
            this.endLineNumber = partialData.endLineNumber | 0;
            this.relativeVerticalOffset = partialData.relativeVerticalOffset;
            this.bigNumbersDelta = partialData.bigNumbersDelta | 0;
            this.lineHeight = partialData.lineHeight | 0;
            this.whitespaceViewportData = whitespaceViewportData;
            this._model = model;
            this.visibleRange = new range_1.Range(partialData.startLineNumber, this._model.getLineMinColumn(partialData.startLineNumber), partialData.endLineNumber, this._model.getLineMaxColumn(partialData.endLineNumber));
        }
        getViewLineRenderingData(lineNumber) {
            return this._model.getViewportViewLineRenderingData(this.visibleRange, lineNumber);
        }
        getDecorationsInViewport() {
            return this._model.getDecorationsInViewport(this.visibleRange);
        }
    }
    exports.ViewportData = ViewportData;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[95/*vs/editor/common/viewModel*/], __M([1/*require*/,0/*exports*/,13/*vs/base/common/arrays*/,11/*vs/base/common/strings*/,4/*vs/editor/common/core/range*/]), function (require, exports, arrays, strings, range_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.OverviewRulerDecorationsGroup = exports.ViewModelDecoration = exports.SingleLineInlineDecoration = exports.InlineDecoration = exports.ViewLineRenderingData = exports.ViewLineData = exports.MinimapLinesRenderingData = exports.Viewport = void 0;
    class Viewport {
        constructor(top, left, width, height) {
            this._viewportBrand = undefined;
            this.top = top | 0;
            this.left = left | 0;
            this.width = width | 0;
            this.height = height | 0;
        }
    }
    exports.Viewport = Viewport;
    class MinimapLinesRenderingData {
        constructor(tabSize, data) {
            this.tabSize = tabSize;
            this.data = data;
        }
    }
    exports.MinimapLinesRenderingData = MinimapLinesRenderingData;
    class ViewLineData {
        constructor(content, continuesWithWrappedLine, minColumn, maxColumn, startVisibleColumn, tokens, inlineDecorations) {
            this._viewLineDataBrand = undefined;
            this.content = content;
            this.continuesWithWrappedLine = continuesWithWrappedLine;
            this.minColumn = minColumn;
            this.maxColumn = maxColumn;
            this.startVisibleColumn = startVisibleColumn;
            this.tokens = tokens;
            this.inlineDecorations = inlineDecorations;
        }
    }
    exports.ViewLineData = ViewLineData;
    class ViewLineRenderingData {
        constructor(minColumn, maxColumn, content, continuesWithWrappedLine, mightContainRTL, mightContainNonBasicASCII, tokens, inlineDecorations, tabSize, startVisibleColumn) {
            this.minColumn = minColumn;
            this.maxColumn = maxColumn;
            this.content = content;
            this.continuesWithWrappedLine = continuesWithWrappedLine;
            this.isBasicASCII = ViewLineRenderingData.isBasicASCII(content, mightContainNonBasicASCII);
            this.containsRTL = ViewLineRenderingData.containsRTL(content, this.isBasicASCII, mightContainRTL);
            this.tokens = tokens;
            this.inlineDecorations = inlineDecorations;
            this.tabSize = tabSize;
            this.startVisibleColumn = startVisibleColumn;
        }
        static isBasicASCII(lineContent, mightContainNonBasicASCII) {
            if (mightContainNonBasicASCII) {
                return strings.isBasicASCII(lineContent);
            }
            return true;
        }
        static containsRTL(lineContent, isBasicASCII, mightContainRTL) {
            if (!isBasicASCII && mightContainRTL) {
                return strings.containsRTL(lineContent);
            }
            return false;
        }
    }
    exports.ViewLineRenderingData = ViewLineRenderingData;
    class InlineDecoration {
        constructor(range, inlineClassName, type) {
            this.range = range;
            this.inlineClassName = inlineClassName;
            this.type = type;
        }
    }
    exports.InlineDecoration = InlineDecoration;
    class SingleLineInlineDecoration {
        constructor(startOffset, endOffset, inlineClassName, inlineClassNameAffectsLetterSpacing) {
            this.startOffset = startOffset;
            this.endOffset = endOffset;
            this.inlineClassName = inlineClassName;
            this.inlineClassNameAffectsLetterSpacing = inlineClassNameAffectsLetterSpacing;
        }
        toInlineDecoration(lineNumber) {
            return new InlineDecoration(new range_1.Range(lineNumber, this.startOffset + 1, lineNumber, this.endOffset + 1), this.inlineClassName, this.inlineClassNameAffectsLetterSpacing ? 3 /* InlineDecorationType.RegularAffectingLetterSpacing */ : 0 /* InlineDecorationType.Regular */);
        }
    }
    exports.SingleLineInlineDecoration = SingleLineInlineDecoration;
    class ViewModelDecoration {
        constructor(range, options) {
            this._viewModelDecorationBrand = undefined;
            this.range = range;
            this.options = options;
        }
    }
    exports.ViewModelDecoration = ViewModelDecoration;
    class OverviewRulerDecorationsGroup {
        constructor(color, zIndex, 
        /**
         * Decorations are encoded in a number array using the following scheme:
         *  - 3*i = lane
         *  - 3*i+1 = startLineNumber
         *  - 3*i+2 = endLineNumber
         */
        data) {
            this.color = color;
            this.zIndex = zIndex;
            this.data = data;
        }
        static compareByRenderingProps(a, b) {
            if (a.zIndex === b.zIndex) {
                if (a.color < b.color) {
                    return -1;
                }
                if (a.color > b.color) {
                    return 1;
                }
                return 0;
            }
            return a.zIndex - b.zIndex;
        }
        static equals(a, b) {
            return (a.color === b.color
                && a.zIndex === b.zIndex
                && arrays.equals(a.data, b.data));
        }
        static equalsArr(a, b) {
            return arrays.equals(a, b, OverviewRulerDecorationsGroup.equals);
        }
    }
    exports.OverviewRulerDecorationsGroup = OverviewRulerDecorationsGroup;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[601/*vs/editor/common/viewModel/glyphLanesModel*/], __M([1/*require*/,0/*exports*/,40/*vs/editor/common/model*/]), function (require, exports, model_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.GlyphMarginLanesModel = void 0;
    const MAX_LANE = model_1.GlyphMarginLane.Right;
    class GlyphMarginLanesModel {
        constructor(maxLine) {
            this.persist = 0;
            this._requiredLanes = 1; // always render at least one lane
            this.lanes = new Uint8Array(Math.ceil(((maxLine + 1) * MAX_LANE) / 8));
        }
        reset(maxLine) {
            const bytes = Math.ceil(((maxLine + 1) * MAX_LANE) / 8);
            if (this.lanes.length < bytes) {
                this.lanes = new Uint8Array(bytes);
            }
            else {
                this.lanes.fill(0);
            }
            this._requiredLanes = 1;
        }
        get requiredLanes() {
            return this._requiredLanes;
        }
        push(lane, range, persist) {
            if (persist) {
                this.persist |= (1 << (lane - 1));
            }
            for (let i = range.startLineNumber; i <= range.endLineNumber; i++) {
                const bit = (MAX_LANE * i) + (lane - 1);
                this.lanes[bit >>> 3] |= (1 << (bit % 8));
                this._requiredLanes = Math.max(this._requiredLanes, this.countAtLine(i));
            }
        }
        getLanesAtLine(lineNumber) {
            const lanes = [];
            let bit = MAX_LANE * lineNumber;
            for (let i = 0; i < MAX_LANE; i++) {
                if (this.persist & (1 << i) || this.lanes[bit >>> 3] & (1 << (bit % 8))) {
                    lanes.push(i + 1);
                }
                bit++;
            }
            return lanes.length ? lanes : [model_1.GlyphMarginLane.Center];
        }
        countAtLine(lineNumber) {
            let bit = MAX_LANE * lineNumber;
            let count = 0;
            for (let i = 0; i < MAX_LANE; i++) {
                if (this.persist & (1 << i) || this.lanes[bit >>> 3] & (1 << (bit % 8))) {
                    count++;
                }
                bit++;
            }
            return count;
        }
    }
    exports.GlyphMarginLanesModel = GlyphMarginLanesModel;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[602/*vs/editor/common/viewModel/modelLineProjection*/], __M([1/*require*/,0/*exports*/,83/*vs/editor/common/tokens/lineTokens*/,9/*vs/editor/common/core/position*/,132/*vs/editor/common/textModelEvents*/,95/*vs/editor/common/viewModel*/]), function (require, exports, lineTokens_1, position_1, textModelEvents_1, viewModel_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.createModelLineProjection = createModelLineProjection;
    function createModelLineProjection(lineBreakData, isVisible) {
        if (lineBreakData === null) {
            // No mapping needed
            if (isVisible) {
                return IdentityModelLineProjection.INSTANCE;
            }
            return HiddenModelLineProjection.INSTANCE;
        }
        else {
            return new ModelLineProjection(lineBreakData, isVisible);
        }
    }
    /**
     * This projection is used to
     * * wrap model lines
     * * inject text
     */
    class ModelLineProjection {
        constructor(lineBreakData, isVisible) {
            this._projectionData = lineBreakData;
            this._isVisible = isVisible;
        }
        isVisible() {
            return this._isVisible;
        }
        setVisible(isVisible) {
            this._isVisible = isVisible;
            return this;
        }
        getProjectionData() {
            return this._projectionData;
        }
        getViewLineCount() {
            if (!this._isVisible) {
                return 0;
            }
            return this._projectionData.getOutputLineCount();
        }
        getViewLineContent(model, modelLineNumber, outputLineIndex) {
            this._assertVisible();
            const startOffsetInInputWithInjections = outputLineIndex > 0 ? this._projectionData.breakOffsets[outputLineIndex - 1] : 0;
            const endOffsetInInputWithInjections = this._projectionData.breakOffsets[outputLineIndex];
            let r;
            if (this._projectionData.injectionOffsets !== null) {
                const injectedTexts = this._projectionData.injectionOffsets.map((offset, idx) => new textModelEvents_1.LineInjectedText(0, 0, offset + 1, this._projectionData.injectionOptions[idx], 0));
                const lineWithInjections = textModelEvents_1.LineInjectedText.applyInjectedText(model.getLineContent(modelLineNumber), injectedTexts);
                r = lineWithInjections.substring(startOffsetInInputWithInjections, endOffsetInInputWithInjections);
            }
            else {
                r = model.getValueInRange({
                    startLineNumber: modelLineNumber,
                    startColumn: startOffsetInInputWithInjections + 1,
                    endLineNumber: modelLineNumber,
                    endColumn: endOffsetInInputWithInjections + 1
                });
            }
            if (outputLineIndex > 0) {
                r = spaces(this._projectionData.wrappedTextIndentLength) + r;
            }
            return r;
        }
        getViewLineLength(model, modelLineNumber, outputLineIndex) {
            this._assertVisible();
            return this._projectionData.getLineLength(outputLineIndex);
        }
        getViewLineMinColumn(_model, _modelLineNumber, outputLineIndex) {
            this._assertVisible();
            return this._projectionData.getMinOutputOffset(outputLineIndex) + 1;
        }
        getViewLineMaxColumn(model, modelLineNumber, outputLineIndex) {
            this._assertVisible();
            return this._projectionData.getMaxOutputOffset(outputLineIndex) + 1;
        }
        /**
         * Try using {@link getViewLinesData} instead.
        */
        getViewLineData(model, modelLineNumber, outputLineIndex) {
            const arr = new Array();
            this.getViewLinesData(model, modelLineNumber, outputLineIndex, 1, 0, [true], arr);
            return arr[0];
        }
        getViewLinesData(model, modelLineNumber, outputLineIdx, lineCount, globalStartIndex, needed, result) {
            this._assertVisible();
            const lineBreakData = this._projectionData;
            const injectionOffsets = lineBreakData.injectionOffsets;
            const injectionOptions = lineBreakData.injectionOptions;
            let inlineDecorationsPerOutputLine = null;
            if (injectionOffsets) {
                inlineDecorationsPerOutputLine = [];
                let totalInjectedTextLengthBefore = 0;
                let currentInjectedOffset = 0;
                for (let outputLineIndex = 0; outputLineIndex < lineBreakData.getOutputLineCount(); outputLineIndex++) {
                    const inlineDecorations = new Array();
                    inlineDecorationsPerOutputLine[outputLineIndex] = inlineDecorations;
                    const lineStartOffsetInInputWithInjections = outputLineIndex > 0 ? lineBreakData.breakOffsets[outputLineIndex - 1] : 0;
                    const lineEndOffsetInInputWithInjections = lineBreakData.breakOffsets[outputLineIndex];
                    while (currentInjectedOffset < injectionOffsets.length) {
                        const length = injectionOptions[currentInjectedOffset].content.length;
                        const injectedTextStartOffsetInInputWithInjections = injectionOffsets[currentInjectedOffset] + totalInjectedTextLengthBefore;
                        const injectedTextEndOffsetInInputWithInjections = injectedTextStartOffsetInInputWithInjections + length;
                        if (injectedTextStartOffsetInInputWithInjections > lineEndOffsetInInputWithInjections) {
                            // Injected text only starts in later wrapped lines.
                            break;
                        }
                        if (lineStartOffsetInInputWithInjections < injectedTextEndOffsetInInputWithInjections) {
                            // Injected text ends after or in this line (but also starts in or before this line).
                            const options = injectionOptions[currentInjectedOffset];
                            if (options.inlineClassName) {
                                const offset = (outputLineIndex > 0 ? lineBreakData.wrappedTextIndentLength : 0);
                                const start = offset + Math.max(injectedTextStartOffsetInInputWithInjections - lineStartOffsetInInputWithInjections, 0);
                                const end = offset + Math.min(injectedTextEndOffsetInInputWithInjections - lineStartOffsetInInputWithInjections, lineEndOffsetInInputWithInjections - lineStartOffsetInInputWithInjections);
                                if (start !== end) {
                                    inlineDecorations.push(new viewModel_1.SingleLineInlineDecoration(start, end, options.inlineClassName, options.inlineClassNameAffectsLetterSpacing));
                                }
                            }
                        }
                        if (injectedTextEndOffsetInInputWithInjections <= lineEndOffsetInInputWithInjections) {
                            totalInjectedTextLengthBefore += length;
                            currentInjectedOffset++;
                        }
                        else {
                            // injected text breaks into next line, process it again
                            break;
                        }
                    }
                }
            }
            let lineWithInjections;
            if (injectionOffsets) {
                lineWithInjections = model.tokenization.getLineTokens(modelLineNumber).withInserted(injectionOffsets.map((offset, idx) => ({
                    offset,
                    text: injectionOptions[idx].content,
                    tokenMetadata: lineTokens_1.LineTokens.defaultTokenMetadata
                })));
            }
            else {
                lineWithInjections = model.tokenization.getLineTokens(modelLineNumber);
            }
            for (let outputLineIndex = outputLineIdx; outputLineIndex < outputLineIdx + lineCount; outputLineIndex++) {
                const globalIndex = globalStartIndex + outputLineIndex - outputLineIdx;
                if (!needed[globalIndex]) {
                    result[globalIndex] = null;
                    continue;
                }
                result[globalIndex] = this._getViewLineData(lineWithInjections, inlineDecorationsPerOutputLine ? inlineDecorationsPerOutputLine[outputLineIndex] : null, outputLineIndex);
            }
        }
        _getViewLineData(lineWithInjections, inlineDecorations, outputLineIndex) {
            this._assertVisible();
            const lineBreakData = this._projectionData;
            const deltaStartIndex = (outputLineIndex > 0 ? lineBreakData.wrappedTextIndentLength : 0);
            const lineStartOffsetInInputWithInjections = outputLineIndex > 0 ? lineBreakData.breakOffsets[outputLineIndex - 1] : 0;
            const lineEndOffsetInInputWithInjections = lineBreakData.breakOffsets[outputLineIndex];
            const tokens = lineWithInjections.sliceAndInflate(lineStartOffsetInInputWithInjections, lineEndOffsetInInputWithInjections, deltaStartIndex);
            let lineContent = tokens.getLineContent();
            if (outputLineIndex > 0) {
                lineContent = spaces(lineBreakData.wrappedTextIndentLength) + lineContent;
            }
            const minColumn = this._projectionData.getMinOutputOffset(outputLineIndex) + 1;
            const maxColumn = lineContent.length + 1;
            const continuesWithWrappedLine = (outputLineIndex + 1 < this.getViewLineCount());
            const startVisibleColumn = (outputLineIndex === 0 ? 0 : lineBreakData.breakOffsetsVisibleColumn[outputLineIndex - 1]);
            return new viewModel_1.ViewLineData(lineContent, continuesWithWrappedLine, minColumn, maxColumn, startVisibleColumn, tokens, inlineDecorations);
        }
        getModelColumnOfViewPosition(outputLineIndex, outputColumn) {
            this._assertVisible();
            return this._projectionData.translateToInputOffset(outputLineIndex, outputColumn - 1) + 1;
        }
        getViewPositionOfModelPosition(deltaLineNumber, inputColumn, affinity = 2 /* PositionAffinity.None */) {
            this._assertVisible();
            const r = this._projectionData.translateToOutputPosition(inputColumn - 1, affinity);
            return r.toPosition(deltaLineNumber);
        }
        getViewLineNumberOfModelPosition(deltaLineNumber, inputColumn) {
            this._assertVisible();
            const r = this._projectionData.translateToOutputPosition(inputColumn - 1);
            return deltaLineNumber + r.outputLineIndex;
        }
        normalizePosition(outputLineIndex, outputPosition, affinity) {
            const baseViewLineNumber = outputPosition.lineNumber - outputLineIndex;
            const normalizedOutputPosition = this._projectionData.normalizeOutputPosition(outputLineIndex, outputPosition.column - 1, affinity);
            const result = normalizedOutputPosition.toPosition(baseViewLineNumber);
            return result;
        }
        getInjectedTextAt(outputLineIndex, outputColumn) {
            return this._projectionData.getInjectedText(outputLineIndex, outputColumn - 1);
        }
        _assertVisible() {
            if (!this._isVisible) {
                throw new Error('Not supported');
            }
        }
    }
    /**
     * This projection does not change the model line.
    */
    class IdentityModelLineProjection {
        static { this.INSTANCE = new IdentityModelLineProjection(); }
        constructor() { }
        isVisible() {
            return true;
        }
        setVisible(isVisible) {
            if (isVisible) {
                return this;
            }
            return HiddenModelLineProjection.INSTANCE;
        }
        getProjectionData() {
            return null;
        }
        getViewLineCount() {
            return 1;
        }
        getViewLineContent(model, modelLineNumber, _outputLineIndex) {
            return model.getLineContent(modelLineNumber);
        }
        getViewLineLength(model, modelLineNumber, _outputLineIndex) {
            return model.getLineLength(modelLineNumber);
        }
        getViewLineMinColumn(model, modelLineNumber, _outputLineIndex) {
            return model.getLineMinColumn(modelLineNumber);
        }
        getViewLineMaxColumn(model, modelLineNumber, _outputLineIndex) {
            return model.getLineMaxColumn(modelLineNumber);
        }
        getViewLineData(model, modelLineNumber, _outputLineIndex) {
            const lineTokens = model.tokenization.getLineTokens(modelLineNumber);
            const lineContent = lineTokens.getLineContent();
            return new viewModel_1.ViewLineData(lineContent, false, 1, lineContent.length + 1, 0, lineTokens.inflate(), null);
        }
        getViewLinesData(model, modelLineNumber, _fromOuputLineIndex, _toOutputLineIndex, globalStartIndex, needed, result) {
            if (!needed[globalStartIndex]) {
                result[globalStartIndex] = null;
                return;
            }
            result[globalStartIndex] = this.getViewLineData(model, modelLineNumber, 0);
        }
        getModelColumnOfViewPosition(_outputLineIndex, outputColumn) {
            return outputColumn;
        }
        getViewPositionOfModelPosition(deltaLineNumber, inputColumn) {
            return new position_1.Position(deltaLineNumber, inputColumn);
        }
        getViewLineNumberOfModelPosition(deltaLineNumber, _inputColumn) {
            return deltaLineNumber;
        }
        normalizePosition(outputLineIndex, outputPosition, affinity) {
            return outputPosition;
        }
        getInjectedTextAt(_outputLineIndex, _outputColumn) {
            return null;
        }
    }
    /**
     * This projection hides the model line.
     */
    class HiddenModelLineProjection {
        static { this.INSTANCE = new HiddenModelLineProjection(); }
        constructor() { }
        isVisible() {
            return false;
        }
        setVisible(isVisible) {
            if (!isVisible) {
                return this;
            }
            return IdentityModelLineProjection.INSTANCE;
        }
        getProjectionData() {
            return null;
        }
        getViewLineCount() {
            return 0;
        }
        getViewLineContent(_model, _modelLineNumber, _outputLineIndex) {
            throw new Error('Not supported');
        }
        getViewLineLength(_model, _modelLineNumber, _outputLineIndex) {
            throw new Error('Not supported');
        }
        getViewLineMinColumn(_model, _modelLineNumber, _outputLineIndex) {
            throw new Error('Not supported');
        }
        getViewLineMaxColumn(_model, _modelLineNumber, _outputLineIndex) {
            throw new Error('Not supported');
        }
        getViewLineData(_model, _modelLineNumber, _outputLineIndex) {
            throw new Error('Not supported');
        }
        getViewLinesData(_model, _modelLineNumber, _fromOuputLineIndex, _toOutputLineIndex, _globalStartIndex, _needed, _result) {
            throw new Error('Not supported');
        }
        getModelColumnOfViewPosition(_outputLineIndex, _outputColumn) {
            throw new Error('Not supported');
        }
        getViewPositionOfModelPosition(_deltaLineNumber, _inputColumn) {
            throw new Error('Not supported');
        }
        getViewLineNumberOfModelPosition(_deltaLineNumber, _inputColumn) {
            throw new Error('Not supported');
        }
        normalizePosition(outputLineIndex, outputPosition, affinity) {
            throw new Error('Not supported');
        }
        getInjectedTextAt(_outputLineIndex, _outputColumn) {
            throw new Error('Not supported');
        }
    }
    const _spaces = [''];
    function spaces(count) {
        if (count >= _spaces.length) {
            for (let i = 1; i <= count; i++) {
                _spaces[i] = _makeSpaces(i);
            }
        }
        return _spaces[count];
    }
    function _makeSpaces(count) {
        return new Array(count + 1).join(' ');
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[603/*vs/editor/common/viewModel/monospaceLineBreaksComputer*/], __M([1/*require*/,0/*exports*/,11/*vs/base/common/strings*/,144/*vs/editor/common/core/characterClassifier*/,132/*vs/editor/common/textModelEvents*/,325/*vs/editor/common/modelLineProjectionData*/]), function (require, exports, strings, characterClassifier_1, textModelEvents_1, modelLineProjectionData_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MonospaceLineBreaksComputerFactory = void 0;
    class MonospaceLineBreaksComputerFactory {
        static create(options) {
            return new MonospaceLineBreaksComputerFactory(options.get(135 /* EditorOption.wordWrapBreakBeforeCharacters */), options.get(134 /* EditorOption.wordWrapBreakAfterCharacters */));
        }
        constructor(breakBeforeChars, breakAfterChars) {
            this.classifier = new WrappingCharacterClassifier(breakBeforeChars, breakAfterChars);
        }
        createLineBreaksComputer(fontInfo, tabSize, wrappingColumn, wrappingIndent, wordBreak) {
            const requests = [];
            const injectedTexts = [];
            const previousBreakingData = [];
            return {
                addRequest: (lineText, injectedText, previousLineBreakData) => {
                    requests.push(lineText);
                    injectedTexts.push(injectedText);
                    previousBreakingData.push(previousLineBreakData);
                },
                finalize: () => {
                    const columnsForFullWidthChar = fontInfo.typicalFullwidthCharacterWidth / fontInfo.typicalHalfwidthCharacterWidth;
                    const result = [];
                    for (let i = 0, len = requests.length; i < len; i++) {
                        const injectedText = injectedTexts[i];
                        const previousLineBreakData = previousBreakingData[i];
                        if (previousLineBreakData && !previousLineBreakData.injectionOptions && !injectedText) {
                            result[i] = createLineBreaksFromPreviousLineBreaks(this.classifier, previousLineBreakData, requests[i], tabSize, wrappingColumn, columnsForFullWidthChar, wrappingIndent, wordBreak);
                        }
                        else {
                            result[i] = createLineBreaks(this.classifier, requests[i], injectedText, tabSize, wrappingColumn, columnsForFullWidthChar, wrappingIndent, wordBreak);
                        }
                    }
                    arrPool1.length = 0;
                    arrPool2.length = 0;
                    return result;
                }
            };
        }
    }
    exports.MonospaceLineBreaksComputerFactory = MonospaceLineBreaksComputerFactory;
    class WrappingCharacterClassifier extends characterClassifier_1.CharacterClassifier {
        constructor(BREAK_BEFORE, BREAK_AFTER) {
            super(0 /* CharacterClass.NONE */);
            for (let i = 0; i < BREAK_BEFORE.length; i++) {
                this.set(BREAK_BEFORE.charCodeAt(i), 1 /* CharacterClass.BREAK_BEFORE */);
            }
            for (let i = 0; i < BREAK_AFTER.length; i++) {
                this.set(BREAK_AFTER.charCodeAt(i), 2 /* CharacterClass.BREAK_AFTER */);
            }
        }
        get(charCode) {
            if (charCode >= 0 && charCode < 256) {
                return this._asciiMap[charCode];
            }
            else {
                // Initialize CharacterClass.BREAK_IDEOGRAPHIC for these Unicode ranges:
                // 1. CJK Unified Ideographs (0x4E00 -- 0x9FFF)
                // 2. CJK Unified Ideographs Extension A (0x3400 -- 0x4DBF)
                // 3. Hiragana and Katakana (0x3040 -- 0x30FF)
                if ((charCode >= 0x3040 && charCode <= 0x30FF)
                    || (charCode >= 0x3400 && charCode <= 0x4DBF)
                    || (charCode >= 0x4E00 && charCode <= 0x9FFF)) {
                    return 3 /* CharacterClass.BREAK_IDEOGRAPHIC */;
                }
                return (this._map.get(charCode) || this._defaultValue);
            }
        }
    }
    let arrPool1 = [];
    let arrPool2 = [];
    function createLineBreaksFromPreviousLineBreaks(classifier, previousBreakingData, lineText, tabSize, firstLineBreakColumn, columnsForFullWidthChar, wrappingIndent, wordBreak) {
        if (firstLineBreakColumn === -1) {
            return null;
        }
        const len = lineText.length;
        if (len <= 1) {
            return null;
        }
        const isKeepAll = (wordBreak === 'keepAll');
        const prevBreakingOffsets = previousBreakingData.breakOffsets;
        const prevBreakingOffsetsVisibleColumn = previousBreakingData.breakOffsetsVisibleColumn;
        const wrappedTextIndentLength = computeWrappedTextIndentLength(lineText, tabSize, firstLineBreakColumn, columnsForFullWidthChar, wrappingIndent);
        const wrappedLineBreakColumn = firstLineBreakColumn - wrappedTextIndentLength;
        const breakingOffsets = arrPool1;
        const breakingOffsetsVisibleColumn = arrPool2;
        let breakingOffsetsCount = 0;
        let lastBreakingOffset = 0;
        let lastBreakingOffsetVisibleColumn = 0;
        let breakingColumn = firstLineBreakColumn;
        const prevLen = prevBreakingOffsets.length;
        let prevIndex = 0;
        if (prevIndex >= 0) {
            let bestDistance = Math.abs(prevBreakingOffsetsVisibleColumn[prevIndex] - breakingColumn);
            while (prevIndex + 1 < prevLen) {
                const distance = Math.abs(prevBreakingOffsetsVisibleColumn[prevIndex + 1] - breakingColumn);
                if (distance >= bestDistance) {
                    break;
                }
                bestDistance = distance;
                prevIndex++;
            }
        }
        while (prevIndex < prevLen) {
            // Allow for prevIndex to be -1 (for the case where we hit a tab when walking backwards from the first break)
            let prevBreakOffset = prevIndex < 0 ? 0 : prevBreakingOffsets[prevIndex];
            let prevBreakOffsetVisibleColumn = prevIndex < 0 ? 0 : prevBreakingOffsetsVisibleColumn[prevIndex];
            if (lastBreakingOffset > prevBreakOffset) {
                prevBreakOffset = lastBreakingOffset;
                prevBreakOffsetVisibleColumn = lastBreakingOffsetVisibleColumn;
            }
            let breakOffset = 0;
            let breakOffsetVisibleColumn = 0;
            let forcedBreakOffset = 0;
            let forcedBreakOffsetVisibleColumn = 0;
            // initially, we search as much as possible to the right (if it fits)
            if (prevBreakOffsetVisibleColumn <= breakingColumn) {
                let visibleColumn = prevBreakOffsetVisibleColumn;
                let prevCharCode = prevBreakOffset === 0 ? 0 /* CharCode.Null */ : lineText.charCodeAt(prevBreakOffset - 1);
                let prevCharCodeClass = prevBreakOffset === 0 ? 0 /* CharacterClass.NONE */ : classifier.get(prevCharCode);
                let entireLineFits = true;
                for (let i = prevBreakOffset; i < len; i++) {
                    const charStartOffset = i;
                    const charCode = lineText.charCodeAt(i);
                    let charCodeClass;
                    let charWidth;
                    if (strings.isHighSurrogate(charCode)) {
                        // A surrogate pair must always be considered as a single unit, so it is never to be broken
                        i++;
                        charCodeClass = 0 /* CharacterClass.NONE */;
                        charWidth = 2;
                    }
                    else {
                        charCodeClass = classifier.get(charCode);
                        charWidth = computeCharWidth(charCode, visibleColumn, tabSize, columnsForFullWidthChar);
                    }
                    if (charStartOffset > lastBreakingOffset && canBreak(prevCharCode, prevCharCodeClass, charCode, charCodeClass, isKeepAll)) {
                        breakOffset = charStartOffset;
                        breakOffsetVisibleColumn = visibleColumn;
                    }
                    visibleColumn += charWidth;
                    // check if adding character at `i` will go over the breaking column
                    if (visibleColumn > breakingColumn) {
                        // We need to break at least before character at `i`:
                        if (charStartOffset > lastBreakingOffset) {
                            forcedBreakOffset = charStartOffset;
                            forcedBreakOffsetVisibleColumn = visibleColumn - charWidth;
                        }
                        else {
                            // we need to advance at least by one character
                            forcedBreakOffset = i + 1;
                            forcedBreakOffsetVisibleColumn = visibleColumn;
                        }
                        if (visibleColumn - breakOffsetVisibleColumn > wrappedLineBreakColumn) {
                            // Cannot break at `breakOffset` => reset it if it was set
                            breakOffset = 0;
                        }
                        entireLineFits = false;
                        break;
                    }
                    prevCharCode = charCode;
                    prevCharCodeClass = charCodeClass;
                }
                if (entireLineFits) {
                    // there is no more need to break => stop the outer loop!
                    if (breakingOffsetsCount > 0) {
                        // Add last segment, no need to assign to `lastBreakingOffset` and `lastBreakingOffsetVisibleColumn`
                        breakingOffsets[breakingOffsetsCount] = prevBreakingOffsets[prevBreakingOffsets.length - 1];
                        breakingOffsetsVisibleColumn[breakingOffsetsCount] = prevBreakingOffsetsVisibleColumn[prevBreakingOffsets.length - 1];
                        breakingOffsetsCount++;
                    }
                    break;
                }
            }
            if (breakOffset === 0) {
                // must search left
                let visibleColumn = prevBreakOffsetVisibleColumn;
                let charCode = lineText.charCodeAt(prevBreakOffset);
                let charCodeClass = classifier.get(charCode);
                let hitATabCharacter = false;
                for (let i = prevBreakOffset - 1; i >= lastBreakingOffset; i--) {
                    const charStartOffset = i + 1;
                    const prevCharCode = lineText.charCodeAt(i);
                    if (prevCharCode === 9 /* CharCode.Tab */) {
                        // cannot determine the width of a tab when going backwards, so we must go forwards
                        hitATabCharacter = true;
                        break;
                    }
                    let prevCharCodeClass;
                    let prevCharWidth;
                    if (strings.isLowSurrogate(prevCharCode)) {
                        // A surrogate pair must always be considered as a single unit, so it is never to be broken
                        i--;
                        prevCharCodeClass = 0 /* CharacterClass.NONE */;
                        prevCharWidth = 2;
                    }
                    else {
                        prevCharCodeClass = classifier.get(prevCharCode);
                        prevCharWidth = (strings.isFullWidthCharacter(prevCharCode) ? columnsForFullWidthChar : 1);
                    }
                    if (visibleColumn <= breakingColumn) {
                        if (forcedBreakOffset === 0) {
                            forcedBreakOffset = charStartOffset;
                            forcedBreakOffsetVisibleColumn = visibleColumn;
                        }
                        if (visibleColumn <= breakingColumn - wrappedLineBreakColumn) {
                            // went too far!
                            break;
                        }
                        if (canBreak(prevCharCode, prevCharCodeClass, charCode, charCodeClass, isKeepAll)) {
                            breakOffset = charStartOffset;
                            breakOffsetVisibleColumn = visibleColumn;
                            break;
                        }
                    }
                    visibleColumn -= prevCharWidth;
                    charCode = prevCharCode;
                    charCodeClass = prevCharCodeClass;
                }
                if (breakOffset !== 0) {
                    const remainingWidthOfNextLine = wrappedLineBreakColumn - (forcedBreakOffsetVisibleColumn - breakOffsetVisibleColumn);
                    if (remainingWidthOfNextLine <= tabSize) {
                        const charCodeAtForcedBreakOffset = lineText.charCodeAt(forcedBreakOffset);
                        let charWidth;
                        if (strings.isHighSurrogate(charCodeAtForcedBreakOffset)) {
                            // A surrogate pair must always be considered as a single unit, so it is never to be broken
                            charWidth = 2;
                        }
                        else {
                            charWidth = computeCharWidth(charCodeAtForcedBreakOffset, forcedBreakOffsetVisibleColumn, tabSize, columnsForFullWidthChar);
                        }
                        if (remainingWidthOfNextLine - charWidth < 0) {
                            // it is not worth it to break at breakOffset, it just introduces an extra needless line!
                            breakOffset = 0;
                        }
                    }
                }
                if (hitATabCharacter) {
                    // cannot determine the width of a tab when going backwards, so we must go forwards from the previous break
                    prevIndex--;
                    continue;
                }
            }
            if (breakOffset === 0) {
                // Could not find a good breaking point
                breakOffset = forcedBreakOffset;
                breakOffsetVisibleColumn = forcedBreakOffsetVisibleColumn;
            }
            if (breakOffset <= lastBreakingOffset) {
                // Make sure that we are advancing (at least one character)
                const charCode = lineText.charCodeAt(lastBreakingOffset);
                if (strings.isHighSurrogate(charCode)) {
                    // A surrogate pair must always be considered as a single unit, so it is never to be broken
                    breakOffset = lastBreakingOffset + 2;
                    breakOffsetVisibleColumn = lastBreakingOffsetVisibleColumn + 2;
                }
                else {
                    breakOffset = lastBreakingOffset + 1;
                    breakOffsetVisibleColumn = lastBreakingOffsetVisibleColumn + computeCharWidth(charCode, lastBreakingOffsetVisibleColumn, tabSize, columnsForFullWidthChar);
                }
            }
            lastBreakingOffset = breakOffset;
            breakingOffsets[breakingOffsetsCount] = breakOffset;
            lastBreakingOffsetVisibleColumn = breakOffsetVisibleColumn;
            breakingOffsetsVisibleColumn[breakingOffsetsCount] = breakOffsetVisibleColumn;
            breakingOffsetsCount++;
            breakingColumn = breakOffsetVisibleColumn + wrappedLineBreakColumn;
            while (prevIndex < 0 || (prevIndex < prevLen && prevBreakingOffsetsVisibleColumn[prevIndex] < breakOffsetVisibleColumn)) {
                prevIndex++;
            }
            let bestDistance = Math.abs(prevBreakingOffsetsVisibleColumn[prevIndex] - breakingColumn);
            while (prevIndex + 1 < prevLen) {
                const distance = Math.abs(prevBreakingOffsetsVisibleColumn[prevIndex + 1] - breakingColumn);
                if (distance >= bestDistance) {
                    break;
                }
                bestDistance = distance;
                prevIndex++;
            }
        }
        if (breakingOffsetsCount === 0) {
            return null;
        }
        // Doing here some object reuse which ends up helping a huge deal with GC pauses!
        breakingOffsets.length = breakingOffsetsCount;
        breakingOffsetsVisibleColumn.length = breakingOffsetsCount;
        arrPool1 = previousBreakingData.breakOffsets;
        arrPool2 = previousBreakingData.breakOffsetsVisibleColumn;
        previousBreakingData.breakOffsets = breakingOffsets;
        previousBreakingData.breakOffsetsVisibleColumn = breakingOffsetsVisibleColumn;
        previousBreakingData.wrappedTextIndentLength = wrappedTextIndentLength;
        return previousBreakingData;
    }
    function createLineBreaks(classifier, _lineText, injectedTexts, tabSize, firstLineBreakColumn, columnsForFullWidthChar, wrappingIndent, wordBreak) {
        const lineText = textModelEvents_1.LineInjectedText.applyInjectedText(_lineText, injectedTexts);
        let injectionOptions;
        let injectionOffsets;
        if (injectedTexts && injectedTexts.length > 0) {
            injectionOptions = injectedTexts.map(t => t.options);
            injectionOffsets = injectedTexts.map(text => text.column - 1);
        }
        else {
            injectionOptions = null;
            injectionOffsets = null;
        }
        if (firstLineBreakColumn === -1) {
            if (!injectionOptions) {
                return null;
            }
            // creating a `LineBreakData` with an invalid `breakOffsetsVisibleColumn` is OK
            // because `breakOffsetsVisibleColumn` will never be used because it contains injected text
            return new modelLineProjectionData_1.ModelLineProjectionData(injectionOffsets, injectionOptions, [lineText.length], [], 0);
        }
        const len = lineText.length;
        if (len <= 1) {
            if (!injectionOptions) {
                return null;
            }
            // creating a `LineBreakData` with an invalid `breakOffsetsVisibleColumn` is OK
            // because `breakOffsetsVisibleColumn` will never be used because it contains injected text
            return new modelLineProjectionData_1.ModelLineProjectionData(injectionOffsets, injectionOptions, [lineText.length], [], 0);
        }
        const isKeepAll = (wordBreak === 'keepAll');
        const wrappedTextIndentLength = computeWrappedTextIndentLength(lineText, tabSize, firstLineBreakColumn, columnsForFullWidthChar, wrappingIndent);
        const wrappedLineBreakColumn = firstLineBreakColumn - wrappedTextIndentLength;
        const breakingOffsets = [];
        const breakingOffsetsVisibleColumn = [];
        let breakingOffsetsCount = 0;
        let breakOffset = 0;
        let breakOffsetVisibleColumn = 0;
        let breakingColumn = firstLineBreakColumn;
        let prevCharCode = lineText.charCodeAt(0);
        let prevCharCodeClass = classifier.get(prevCharCode);
        let visibleColumn = computeCharWidth(prevCharCode, 0, tabSize, columnsForFullWidthChar);
        let startOffset = 1;
        if (strings.isHighSurrogate(prevCharCode)) {
            // A surrogate pair must always be considered as a single unit, so it is never to be broken
            visibleColumn += 1;
            prevCharCode = lineText.charCodeAt(1);
            prevCharCodeClass = classifier.get(prevCharCode);
            startOffset++;
        }
        for (let i = startOffset; i < len; i++) {
            const charStartOffset = i;
            const charCode = lineText.charCodeAt(i);
            let charCodeClass;
            let charWidth;
            if (strings.isHighSurrogate(charCode)) {
                // A surrogate pair must always be considered as a single unit, so it is never to be broken
                i++;
                charCodeClass = 0 /* CharacterClass.NONE */;
                charWidth = 2;
            }
            else {
                charCodeClass = classifier.get(charCode);
                charWidth = computeCharWidth(charCode, visibleColumn, tabSize, columnsForFullWidthChar);
            }
            if (canBreak(prevCharCode, prevCharCodeClass, charCode, charCodeClass, isKeepAll)) {
                breakOffset = charStartOffset;
                breakOffsetVisibleColumn = visibleColumn;
            }
            visibleColumn += charWidth;
            // check if adding character at `i` will go over the breaking column
            if (visibleColumn > breakingColumn) {
                // We need to break at least before character at `i`:
                if (breakOffset === 0 || visibleColumn - breakOffsetVisibleColumn > wrappedLineBreakColumn) {
                    // Cannot break at `breakOffset`, must break at `i`
                    breakOffset = charStartOffset;
                    breakOffsetVisibleColumn = visibleColumn - charWidth;
                }
                breakingOffsets[breakingOffsetsCount] = breakOffset;
                breakingOffsetsVisibleColumn[breakingOffsetsCount] = breakOffsetVisibleColumn;
                breakingOffsetsCount++;
                breakingColumn = breakOffsetVisibleColumn + wrappedLineBreakColumn;
                breakOffset = 0;
            }
            prevCharCode = charCode;
            prevCharCodeClass = charCodeClass;
        }
        if (breakingOffsetsCount === 0 && (!injectedTexts || injectedTexts.length === 0)) {
            return null;
        }
        // Add last segment
        breakingOffsets[breakingOffsetsCount] = len;
        breakingOffsetsVisibleColumn[breakingOffsetsCount] = visibleColumn;
        return new modelLineProjectionData_1.ModelLineProjectionData(injectionOffsets, injectionOptions, breakingOffsets, breakingOffsetsVisibleColumn, wrappedTextIndentLength);
    }
    function computeCharWidth(charCode, visibleColumn, tabSize, columnsForFullWidthChar) {
        if (charCode === 9 /* CharCode.Tab */) {
            return (tabSize - (visibleColumn % tabSize));
        }
        if (strings.isFullWidthCharacter(charCode)) {
            return columnsForFullWidthChar;
        }
        if (charCode < 32) {
            // when using `editor.renderControlCharacters`, the substitutions are often wide
            return columnsForFullWidthChar;
        }
        return 1;
    }
    function tabCharacterWidth(visibleColumn, tabSize) {
        return (tabSize - (visibleColumn % tabSize));
    }
    /**
     * Kinsoku Shori : Don't break after a leading character, like an open bracket
     * Kinsoku Shori : Don't break before a trailing character, like a period
     */
    function canBreak(prevCharCode, prevCharCodeClass, charCode, charCodeClass, isKeepAll) {
        return (charCode !== 32 /* CharCode.Space */
            && ((prevCharCodeClass === 2 /* CharacterClass.BREAK_AFTER */ && charCodeClass !== 2 /* CharacterClass.BREAK_AFTER */) // break at the end of multiple BREAK_AFTER
                || (prevCharCodeClass !== 1 /* CharacterClass.BREAK_BEFORE */ && charCodeClass === 1 /* CharacterClass.BREAK_BEFORE */) // break at the start of multiple BREAK_BEFORE
                || (!isKeepAll && prevCharCodeClass === 3 /* CharacterClass.BREAK_IDEOGRAPHIC */ && charCodeClass !== 2 /* CharacterClass.BREAK_AFTER */)
                || (!isKeepAll && charCodeClass === 3 /* CharacterClass.BREAK_IDEOGRAPHIC */ && prevCharCodeClass !== 1 /* CharacterClass.BREAK_BEFORE */)));
    }
    function computeWrappedTextIndentLength(lineText, tabSize, firstLineBreakColumn, columnsForFullWidthChar, wrappingIndent) {
        let wrappedTextIndentLength = 0;
        if (wrappingIndent !== 0 /* WrappingIndent.None */) {
            const firstNonWhitespaceIndex = strings.firstNonWhitespaceIndex(lineText);
            if (firstNonWhitespaceIndex !== -1) {
                // Track existing indent
                for (let i = 0; i < firstNonWhitespaceIndex; i++) {
                    const charWidth = (lineText.charCodeAt(i) === 9 /* CharCode.Tab */ ? tabCharacterWidth(wrappedTextIndentLength, tabSize) : 1);
                    wrappedTextIndentLength += charWidth;
                }
                // Increase indent of continuation lines, if desired
                const numberOfAdditionalTabs = (wrappingIndent === 3 /* WrappingIndent.DeepIndent */ ? 2 : wrappingIndent === 2 /* WrappingIndent.Indent */ ? 1 : 0);
                for (let i = 0; i < numberOfAdditionalTabs; i++) {
                    const charWidth = tabCharacterWidth(wrappedTextIndentLength, tabSize);
                    wrappedTextIndentLength += charWidth;
                }
                // Force sticking to beginning of line if no character would fit except for the indentation
                if (wrappedTextIndentLength + columnsForFullWidthChar > firstLineBreakColumn) {
                    wrappedTextIndentLength = 0;
                }
            }
        }
        return wrappedTextIndentLength;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[332/*vs/editor/common/viewModel/overviewZoneManager*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.OverviewZoneManager = exports.OverviewRulerZone = exports.ColorZone = void 0;
    class ColorZone {
        constructor(from, to, colorId) {
            this._colorZoneBrand = undefined;
            this.from = from | 0;
            this.to = to | 0;
            this.colorId = colorId | 0;
        }
        static compare(a, b) {
            if (a.colorId === b.colorId) {
                if (a.from === b.from) {
                    return a.to - b.to;
                }
                return a.from - b.from;
            }
            return a.colorId - b.colorId;
        }
    }
    exports.ColorZone = ColorZone;
    /**
     * A zone in the overview ruler
     */
    class OverviewRulerZone {
        constructor(startLineNumber, endLineNumber, heightInLines, color) {
            this._overviewRulerZoneBrand = undefined;
            this.startLineNumber = startLineNumber;
            this.endLineNumber = endLineNumber;
            this.heightInLines = heightInLines;
            this.color = color;
            this._colorZone = null;
        }
        static compare(a, b) {
            if (a.color === b.color) {
                if (a.startLineNumber === b.startLineNumber) {
                    if (a.heightInLines === b.heightInLines) {
                        return a.endLineNumber - b.endLineNumber;
                    }
                    return a.heightInLines - b.heightInLines;
                }
                return a.startLineNumber - b.startLineNumber;
            }
            return a.color < b.color ? -1 : 1;
        }
        setColorZone(colorZone) {
            this._colorZone = colorZone;
        }
        getColorZones() {
            return this._colorZone;
        }
    }
    exports.OverviewRulerZone = OverviewRulerZone;
    class OverviewZoneManager {
        constructor(getVerticalOffsetForLine) {
            this._getVerticalOffsetForLine = getVerticalOffsetForLine;
            this._zones = [];
            this._colorZonesInvalid = false;
            this._lineHeight = 0;
            this._domWidth = 0;
            this._domHeight = 0;
            this._outerHeight = 0;
            this._pixelRatio = 1;
            this._lastAssignedId = 0;
            this._color2Id = Object.create(null);
            this._id2Color = [];
        }
        getId2Color() {
            return this._id2Color;
        }
        setZones(newZones) {
            this._zones = newZones;
            this._zones.sort(OverviewRulerZone.compare);
        }
        setLineHeight(lineHeight) {
            if (this._lineHeight === lineHeight) {
                return false;
            }
            this._lineHeight = lineHeight;
            this._colorZonesInvalid = true;
            return true;
        }
        setPixelRatio(pixelRatio) {
            this._pixelRatio = pixelRatio;
            this._colorZonesInvalid = true;
        }
        getDOMWidth() {
            return this._domWidth;
        }
        getCanvasWidth() {
            return this._domWidth * this._pixelRatio;
        }
        setDOMWidth(width) {
            if (this._domWidth === width) {
                return false;
            }
            this._domWidth = width;
            this._colorZonesInvalid = true;
            return true;
        }
        getDOMHeight() {
            return this._domHeight;
        }
        getCanvasHeight() {
            return this._domHeight * this._pixelRatio;
        }
        setDOMHeight(height) {
            if (this._domHeight === height) {
                return false;
            }
            this._domHeight = height;
            this._colorZonesInvalid = true;
            return true;
        }
        getOuterHeight() {
            return this._outerHeight;
        }
        setOuterHeight(outerHeight) {
            if (this._outerHeight === outerHeight) {
                return false;
            }
            this._outerHeight = outerHeight;
            this._colorZonesInvalid = true;
            return true;
        }
        resolveColorZones() {
            const colorZonesInvalid = this._colorZonesInvalid;
            const lineHeight = Math.floor(this._lineHeight);
            const totalHeight = Math.floor(this.getCanvasHeight());
            const outerHeight = Math.floor(this._outerHeight);
            const heightRatio = totalHeight / outerHeight;
            const halfMinimumHeight = Math.floor(4 /* Constants.MINIMUM_HEIGHT */ * this._pixelRatio / 2);
            const allColorZones = [];
            for (let i = 0, len = this._zones.length; i < len; i++) {
                const zone = this._zones[i];
                if (!colorZonesInvalid) {
                    const colorZone = zone.getColorZones();
                    if (colorZone) {
                        allColorZones.push(colorZone);
                        continue;
                    }
                }
                const offset1 = this._getVerticalOffsetForLine(zone.startLineNumber);
                const offset2 = (zone.heightInLines === 0
                    ? this._getVerticalOffsetForLine(zone.endLineNumber) + lineHeight
                    : offset1 + zone.heightInLines * lineHeight);
                const y1 = Math.floor(heightRatio * offset1);
                const y2 = Math.floor(heightRatio * offset2);
                let ycenter = Math.floor((y1 + y2) / 2);
                let halfHeight = (y2 - ycenter);
                if (halfHeight < halfMinimumHeight) {
                    halfHeight = halfMinimumHeight;
                }
                if (ycenter - halfHeight < 0) {
                    ycenter = halfHeight;
                }
                if (ycenter + halfHeight > totalHeight) {
                    ycenter = totalHeight - halfHeight;
                }
                const color = zone.color;
                let colorId = this._color2Id[color];
                if (!colorId) {
                    colorId = (++this._lastAssignedId);
                    this._color2Id[color] = colorId;
                    this._id2Color[colorId] = color;
                }
                const colorZone = new ColorZone(ycenter - halfHeight, ycenter + halfHeight, colorId);
                zone.setColorZone(colorZone);
                allColorZones.push(colorZone);
            }
            this._colorZonesInvalid = false;
            allColorZones.sort(ColorZone.compare);
            return allColorZones;
        }
    }
    exports.OverviewZoneManager = OverviewZoneManager;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[604/*vs/editor/browser/viewParts/overviewRuler/overviewRuler*/], __M([1/*require*/,0/*exports*/,39/*vs/base/browser/fastDomNode*/,332/*vs/editor/common/viewModel/overviewZoneManager*/,170/*vs/editor/common/viewEventHandler*/]), function (require, exports, fastDomNode_1, overviewZoneManager_1, viewEventHandler_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.OverviewRuler = void 0;
    class OverviewRuler extends viewEventHandler_1.ViewEventHandler {
        constructor(context, cssClassName) {
            super();
            this._context = context;
            const options = this._context.configuration.options;
            this._domNode = (0, fastDomNode_1.createFastDomNode)(document.createElement('canvas'));
            this._domNode.setClassName(cssClassName);
            this._domNode.setPosition('absolute');
            this._domNode.setLayerHinting(true);
            this._domNode.setContain('strict');
            this._zoneManager = new overviewZoneManager_1.OverviewZoneManager((lineNumber) => this._context.viewLayout.getVerticalOffsetForLineNumber(lineNumber));
            this._zoneManager.setDOMWidth(0);
            this._zoneManager.setDOMHeight(0);
            this._zoneManager.setOuterHeight(this._context.viewLayout.getScrollHeight());
            this._zoneManager.setLineHeight(options.get(67 /* EditorOption.lineHeight */));
            this._zoneManager.setPixelRatio(options.get(144 /* EditorOption.pixelRatio */));
            this._context.addEventHandler(this);
        }
        dispose() {
            this._context.removeEventHandler(this);
            super.dispose();
        }
        // ---- begin view event handlers
        onConfigurationChanged(e) {
            const options = this._context.configuration.options;
            if (e.hasChanged(67 /* EditorOption.lineHeight */)) {
                this._zoneManager.setLineHeight(options.get(67 /* EditorOption.lineHeight */));
                this._render();
            }
            if (e.hasChanged(144 /* EditorOption.pixelRatio */)) {
                this._zoneManager.setPixelRatio(options.get(144 /* EditorOption.pixelRatio */));
                this._domNode.setWidth(this._zoneManager.getDOMWidth());
                this._domNode.setHeight(this._zoneManager.getDOMHeight());
                this._domNode.domNode.width = this._zoneManager.getCanvasWidth();
                this._domNode.domNode.height = this._zoneManager.getCanvasHeight();
                this._render();
            }
            return true;
        }
        onFlushed(e) {
            this._render();
            return true;
        }
        onScrollChanged(e) {
            if (e.scrollHeightChanged) {
                this._zoneManager.setOuterHeight(e.scrollHeight);
                this._render();
            }
            return true;
        }
        onZonesChanged(e) {
            this._render();
            return true;
        }
        // ---- end view event handlers
        getDomNode() {
            return this._domNode.domNode;
        }
        setLayout(position) {
            this._domNode.setTop(position.top);
            this._domNode.setRight(position.right);
            let hasChanged = false;
            hasChanged = this._zoneManager.setDOMWidth(position.width) || hasChanged;
            hasChanged = this._zoneManager.setDOMHeight(position.height) || hasChanged;
            if (hasChanged) {
                this._domNode.setWidth(this._zoneManager.getDOMWidth());
                this._domNode.setHeight(this._zoneManager.getDOMHeight());
                this._domNode.domNode.width = this._zoneManager.getCanvasWidth();
                this._domNode.domNode.height = this._zoneManager.getCanvasHeight();
                this._render();
            }
        }
        setZones(zones) {
            this._zoneManager.setZones(zones);
            this._render();
        }
        _render() {
            if (this._zoneManager.getOuterHeight() === 0) {
                return false;
            }
            const width = this._zoneManager.getCanvasWidth();
            const height = this._zoneManager.getCanvasHeight();
            const colorZones = this._zoneManager.resolveColorZones();
            const id2Color = this._zoneManager.getId2Color();
            const ctx = this._domNode.domNode.getContext('2d');
            ctx.clearRect(0, 0, width, height);
            if (colorZones.length > 0) {
                this._renderOneLane(ctx, colorZones, id2Color, width);
            }
            return true;
        }
        _renderOneLane(ctx, colorZones, id2Color, width) {
            let currentColorId = 0;
            let currentFrom = 0;
            let currentTo = 0;
            for (const zone of colorZones) {
                const zoneColorId = zone.colorId;
                const zoneFrom = zone.from;
                const zoneTo = zone.to;
                if (zoneColorId !== currentColorId) {
                    ctx.fillRect(0, currentFrom, width, currentTo - currentFrom);
                    currentColorId = zoneColorId;
                    ctx.fillStyle = id2Color[currentColorId];
                    currentFrom = zoneFrom;
                    currentTo = zoneTo;
                }
                else {
                    if (currentTo >= zoneFrom) {
                        currentTo = Math.max(currentTo, zoneTo);
                    }
                    else {
                        ctx.fillRect(0, currentFrom, width, currentTo - currentFrom);
                        currentFrom = zoneFrom;
                        currentTo = zoneTo;
                    }
                }
            }
            ctx.fillRect(0, currentFrom, width, currentTo - currentFrom);
        }
    }
    exports.OverviewRuler = OverviewRuler;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[605/*vs/editor/common/viewModel/viewContext*/], __M([1/*require*/,0/*exports*/,562/*vs/editor/common/editorTheme*/]), function (require, exports, editorTheme_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ViewContext = void 0;
    class ViewContext {
        constructor(configuration, theme, model) {
            this.configuration = configuration;
            this.theme = new editorTheme_1.EditorTheme(theme);
            this.viewModel = model;
            this.viewLayout = model.viewLayout;
        }
        addEventHandler(eventHandler) {
            this.viewModel.addViewEventHandler(eventHandler);
        }
        removeEventHandler(eventHandler) {
            this.viewModel.removeViewEventHandler(eventHandler);
        }
    }
    exports.ViewContext = ViewContext;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[244/*vs/editor/common/viewModelEventDispatcher*/], __M([1/*require*/,0/*exports*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/]), function (require, exports, event_1, lifecycle_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ModelTokensChangedEvent = exports.ModelOptionsChangedEvent = exports.ModelContentChangedEvent = exports.ModelLanguageConfigurationChangedEvent = exports.ModelLanguageChangedEvent = exports.ModelDecorationsChangedEvent = exports.ReadOnlyEditAttemptEvent = exports.CursorStateChangedEvent = exports.HiddenAreasChangedEvent = exports.ViewZonesChangedEvent = exports.ScrollChangedEvent = exports.FocusChangedEvent = exports.ContentSizeChangedEvent = exports.ViewModelEventsCollector = exports.ViewModelEventDispatcher = void 0;
    class ViewModelEventDispatcher extends lifecycle_1.Disposable {
        constructor() {
            super();
            this._onEvent = this._register(new event_1.Emitter());
            this.onEvent = this._onEvent.event;
            this._eventHandlers = [];
            this._viewEventQueue = null;
            this._isConsumingViewEventQueue = false;
            this._collector = null;
            this._collectorCnt = 0;
            this._outgoingEvents = [];
        }
        emitOutgoingEvent(e) {
            this._addOutgoingEvent(e);
            this._emitOutgoingEvents();
        }
        _addOutgoingEvent(e) {
            for (let i = 0, len = this._outgoingEvents.length; i < len; i++) {
                const mergeResult = (this._outgoingEvents[i].kind === e.kind ? this._outgoingEvents[i].attemptToMerge(e) : null);
                if (mergeResult) {
                    this._outgoingEvents[i] = mergeResult;
                    return;
                }
            }
            // not merged
            this._outgoingEvents.push(e);
        }
        _emitOutgoingEvents() {
            while (this._outgoingEvents.length > 0) {
                if (this._collector || this._isConsumingViewEventQueue) {
                    // right now collecting or emitting view events, so let's postpone emitting
                    return;
                }
                const event = this._outgoingEvents.shift();
                if (event.isNoOp()) {
                    continue;
                }
                this._onEvent.fire(event);
            }
        }
        addViewEventHandler(eventHandler) {
            for (let i = 0, len = this._eventHandlers.length; i < len; i++) {
                if (this._eventHandlers[i] === eventHandler) {
                    console.warn('Detected duplicate listener in ViewEventDispatcher', eventHandler);
                }
            }
            this._eventHandlers.push(eventHandler);
        }
        removeViewEventHandler(eventHandler) {
            for (let i = 0; i < this._eventHandlers.length; i++) {
                if (this._eventHandlers[i] === eventHandler) {
                    this._eventHandlers.splice(i, 1);
                    break;
                }
            }
        }
        beginEmitViewEvents() {
            this._collectorCnt++;
            if (this._collectorCnt === 1) {
                this._collector = new ViewModelEventsCollector();
            }
            return this._collector;
        }
        endEmitViewEvents() {
            this._collectorCnt--;
            if (this._collectorCnt === 0) {
                const outgoingEvents = this._collector.outgoingEvents;
                const viewEvents = this._collector.viewEvents;
                this._collector = null;
                for (const outgoingEvent of outgoingEvents) {
                    this._addOutgoingEvent(outgoingEvent);
                }
                if (viewEvents.length > 0) {
                    this._emitMany(viewEvents);
                }
            }
            this._emitOutgoingEvents();
        }
        emitSingleViewEvent(event) {
            try {
                const eventsCollector = this.beginEmitViewEvents();
                eventsCollector.emitViewEvent(event);
            }
            finally {
                this.endEmitViewEvents();
            }
        }
        _emitMany(events) {
            if (this._viewEventQueue) {
                this._viewEventQueue = this._viewEventQueue.concat(events);
            }
            else {
                this._viewEventQueue = events;
            }
            if (!this._isConsumingViewEventQueue) {
                this._consumeViewEventQueue();
            }
        }
        _consumeViewEventQueue() {
            try {
                this._isConsumingViewEventQueue = true;
                this._doConsumeQueue();
            }
            finally {
                this._isConsumingViewEventQueue = false;
            }
        }
        _doConsumeQueue() {
            while (this._viewEventQueue) {
                // Empty event queue, as events might come in while sending these off
                const events = this._viewEventQueue;
                this._viewEventQueue = null;
                // Use a clone of the event handlers list, as they might remove themselves
                const eventHandlers = this._eventHandlers.slice(0);
                for (const eventHandler of eventHandlers) {
                    eventHandler.handleEvents(events);
                }
            }
        }
    }
    exports.ViewModelEventDispatcher = ViewModelEventDispatcher;
    class ViewModelEventsCollector {
        constructor() {
            this.viewEvents = [];
            this.outgoingEvents = [];
        }
        emitViewEvent(event) {
            this.viewEvents.push(event);
        }
        emitOutgoingEvent(e) {
            this.outgoingEvents.push(e);
        }
    }
    exports.ViewModelEventsCollector = ViewModelEventsCollector;
    class ContentSizeChangedEvent {
        constructor(oldContentWidth, oldContentHeight, contentWidth, contentHeight) {
            this.kind = 0 /* OutgoingViewModelEventKind.ContentSizeChanged */;
            this._oldContentWidth = oldContentWidth;
            this._oldContentHeight = oldContentHeight;
            this.contentWidth = contentWidth;
            this.contentHeight = contentHeight;
            this.contentWidthChanged = (this._oldContentWidth !== this.contentWidth);
            this.contentHeightChanged = (this._oldContentHeight !== this.contentHeight);
        }
        isNoOp() {
            return (!this.contentWidthChanged && !this.contentHeightChanged);
        }
        attemptToMerge(other) {
            if (other.kind !== this.kind) {
                return null;
            }
            return new ContentSizeChangedEvent(this._oldContentWidth, this._oldContentHeight, other.contentWidth, other.contentHeight);
        }
    }
    exports.ContentSizeChangedEvent = ContentSizeChangedEvent;
    class FocusChangedEvent {
        constructor(oldHasFocus, hasFocus) {
            this.kind = 1 /* OutgoingViewModelEventKind.FocusChanged */;
            this.oldHasFocus = oldHasFocus;
            this.hasFocus = hasFocus;
        }
        isNoOp() {
            return (this.oldHasFocus === this.hasFocus);
        }
        attemptToMerge(other) {
            if (other.kind !== this.kind) {
                return null;
            }
            return new FocusChangedEvent(this.oldHasFocus, other.hasFocus);
        }
    }
    exports.FocusChangedEvent = FocusChangedEvent;
    class ScrollChangedEvent {
        constructor(oldScrollWidth, oldScrollLeft, oldScrollHeight, oldScrollTop, scrollWidth, scrollLeft, scrollHeight, scrollTop) {
            this.kind = 2 /* OutgoingViewModelEventKind.ScrollChanged */;
            this._oldScrollWidth = oldScrollWidth;
            this._oldScrollLeft = oldScrollLeft;
            this._oldScrollHeight = oldScrollHeight;
            this._oldScrollTop = oldScrollTop;
            this.scrollWidth = scrollWidth;
            this.scrollLeft = scrollLeft;
            this.scrollHeight = scrollHeight;
            this.scrollTop = scrollTop;
            this.scrollWidthChanged = (this._oldScrollWidth !== this.scrollWidth);
            this.scrollLeftChanged = (this._oldScrollLeft !== this.scrollLeft);
            this.scrollHeightChanged = (this._oldScrollHeight !== this.scrollHeight);
            this.scrollTopChanged = (this._oldScrollTop !== this.scrollTop);
        }
        isNoOp() {
            return (!this.scrollWidthChanged && !this.scrollLeftChanged && !this.scrollHeightChanged && !this.scrollTopChanged);
        }
        attemptToMerge(other) {
            if (other.kind !== this.kind) {
                return null;
            }
            return new ScrollChangedEvent(this._oldScrollWidth, this._oldScrollLeft, this._oldScrollHeight, this._oldScrollTop, other.scrollWidth, other.scrollLeft, other.scrollHeight, other.scrollTop);
        }
    }
    exports.ScrollChangedEvent = ScrollChangedEvent;
    class ViewZonesChangedEvent {
        constructor() {
            this.kind = 3 /* OutgoingViewModelEventKind.ViewZonesChanged */;
        }
        isNoOp() {
            return false;
        }
        attemptToMerge(other) {
            if (other.kind !== this.kind) {
                return null;
            }
            return this;
        }
    }
    exports.ViewZonesChangedEvent = ViewZonesChangedEvent;
    class HiddenAreasChangedEvent {
        constructor() {
            this.kind = 4 /* OutgoingViewModelEventKind.HiddenAreasChanged */;
        }
        isNoOp() {
            return false;
        }
        attemptToMerge(other) {
            if (other.kind !== this.kind) {
                return null;
            }
            return this;
        }
    }
    exports.HiddenAreasChangedEvent = HiddenAreasChangedEvent;
    class CursorStateChangedEvent {
        constructor(oldSelections, selections, oldModelVersionId, modelVersionId, source, reason, reachedMaxCursorCount) {
            this.kind = 6 /* OutgoingViewModelEventKind.CursorStateChanged */;
            this.oldSelections = oldSelections;
            this.selections = selections;
            this.oldModelVersionId = oldModelVersionId;
            this.modelVersionId = modelVersionId;
            this.source = source;
            this.reason = reason;
            this.reachedMaxCursorCount = reachedMaxCursorCount;
        }
        static _selectionsAreEqual(a, b) {
            if (!a && !b) {
                return true;
            }
            if (!a || !b) {
                return false;
            }
            const aLen = a.length;
            const bLen = b.length;
            if (aLen !== bLen) {
                return false;
            }
            for (let i = 0; i < aLen; i++) {
                if (!a[i].equalsSelection(b[i])) {
                    return false;
                }
            }
            return true;
        }
        isNoOp() {
            return (CursorStateChangedEvent._selectionsAreEqual(this.oldSelections, this.selections)
                && this.oldModelVersionId === this.modelVersionId);
        }
        attemptToMerge(other) {
            if (other.kind !== this.kind) {
                return null;
            }
            return new CursorStateChangedEvent(this.oldSelections, other.selections, this.oldModelVersionId, other.modelVersionId, other.source, other.reason, this.reachedMaxCursorCount || other.reachedMaxCursorCount);
        }
    }
    exports.CursorStateChangedEvent = CursorStateChangedEvent;
    class ReadOnlyEditAttemptEvent {
        constructor() {
            this.kind = 5 /* OutgoingViewModelEventKind.ReadOnlyEditAttempt */;
        }
        isNoOp() {
            return false;
        }
        attemptToMerge(other) {
            if (other.kind !== this.kind) {
                return null;
            }
            return this;
        }
    }
    exports.ReadOnlyEditAttemptEvent = ReadOnlyEditAttemptEvent;
    class ModelDecorationsChangedEvent {
        constructor(event) {
            this.event = event;
            this.kind = 7 /* OutgoingViewModelEventKind.ModelDecorationsChanged */;
        }
        isNoOp() {
            return false;
        }
        attemptToMerge(other) {
            return null;
        }
    }
    exports.ModelDecorationsChangedEvent = ModelDecorationsChangedEvent;
    class ModelLanguageChangedEvent {
        constructor(event) {
            this.event = event;
            this.kind = 8 /* OutgoingViewModelEventKind.ModelLanguageChanged */;
        }
        isNoOp() {
            return false;
        }
        attemptToMerge(other) {
            return null;
        }
    }
    exports.ModelLanguageChangedEvent = ModelLanguageChangedEvent;
    class ModelLanguageConfigurationChangedEvent {
        constructor(event) {
            this.event = event;
            this.kind = 9 /* OutgoingViewModelEventKind.ModelLanguageConfigurationChanged */;
        }
        isNoOp() {
            return false;
        }
        attemptToMerge(other) {
            return null;
        }
    }
    exports.ModelLanguageConfigurationChangedEvent = ModelLanguageConfigurationChangedEvent;
    class ModelContentChangedEvent {
        constructor(event) {
            this.event = event;
            this.kind = 10 /* OutgoingViewModelEventKind.ModelContentChanged */;
        }
        isNoOp() {
            return false;
        }
        attemptToMerge(other) {
            return null;
        }
    }
    exports.ModelContentChangedEvent = ModelContentChangedEvent;
    class ModelOptionsChangedEvent {
        constructor(event) {
            this.event = event;
            this.kind = 11 /* OutgoingViewModelEventKind.ModelOptionsChanged */;
        }
        isNoOp() {
            return false;
        }
        attemptToMerge(other) {
            return null;
        }
    }
    exports.ModelOptionsChangedEvent = ModelOptionsChangedEvent;
    class ModelTokensChangedEvent {
        constructor(event) {
            this.event = event;
            this.kind = 12 /* OutgoingViewModelEventKind.ModelTokensChanged */;
        }
        isNoOp() {
            return false;
        }
        attemptToMerge(other) {
            return null;
        }
    }
    exports.ModelTokensChangedEvent = ModelTokensChangedEvent;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[606/*vs/editor/common/viewLayout/viewLayout*/], __M([1/*require*/,0/*exports*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,163/*vs/base/common/scrollable*/,599/*vs/editor/common/viewLayout/linesLayout*/,95/*vs/editor/common/viewModel*/,244/*vs/editor/common/viewModelEventDispatcher*/]), function (require, exports, event_1, lifecycle_1, scrollable_1, linesLayout_1, viewModel_1, viewModelEventDispatcher_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ViewLayout = void 0;
    const SMOOTH_SCROLLING_TIME = 125;
    class EditorScrollDimensions {
        constructor(width, contentWidth, height, contentHeight) {
            width = width | 0;
            contentWidth = contentWidth | 0;
            height = height | 0;
            contentHeight = contentHeight | 0;
            if (width < 0) {
                width = 0;
            }
            if (contentWidth < 0) {
                contentWidth = 0;
            }
            if (height < 0) {
                height = 0;
            }
            if (contentHeight < 0) {
                contentHeight = 0;
            }
            this.width = width;
            this.contentWidth = contentWidth;
            this.scrollWidth = Math.max(width, contentWidth);
            this.height = height;
            this.contentHeight = contentHeight;
            this.scrollHeight = Math.max(height, contentHeight);
        }
        equals(other) {
            return (this.width === other.width
                && this.contentWidth === other.contentWidth
                && this.height === other.height
                && this.contentHeight === other.contentHeight);
        }
    }
    class EditorScrollable extends lifecycle_1.Disposable {
        constructor(smoothScrollDuration, scheduleAtNextAnimationFrame) {
            super();
            this._onDidContentSizeChange = this._register(new event_1.Emitter());
            this.onDidContentSizeChange = this._onDidContentSizeChange.event;
            this._dimensions = new EditorScrollDimensions(0, 0, 0, 0);
            this._scrollable = this._register(new scrollable_1.Scrollable({
                forceIntegerValues: true,
                smoothScrollDuration,
                scheduleAtNextAnimationFrame
            }));
            this.onDidScroll = this._scrollable.onScroll;
        }
        getScrollable() {
            return this._scrollable;
        }
        setSmoothScrollDuration(smoothScrollDuration) {
            this._scrollable.setSmoothScrollDuration(smoothScrollDuration);
        }
        validateScrollPosition(scrollPosition) {
            return this._scrollable.validateScrollPosition(scrollPosition);
        }
        getScrollDimensions() {
            return this._dimensions;
        }
        setScrollDimensions(dimensions) {
            if (this._dimensions.equals(dimensions)) {
                return;
            }
            const oldDimensions = this._dimensions;
            this._dimensions = dimensions;
            this._scrollable.setScrollDimensions({
                width: dimensions.width,
                scrollWidth: dimensions.scrollWidth,
                height: dimensions.height,
                scrollHeight: dimensions.scrollHeight
            }, true);
            const contentWidthChanged = (oldDimensions.contentWidth !== dimensions.contentWidth);
            const contentHeightChanged = (oldDimensions.contentHeight !== dimensions.contentHeight);
            if (contentWidthChanged || contentHeightChanged) {
                this._onDidContentSizeChange.fire(new viewModelEventDispatcher_1.ContentSizeChangedEvent(oldDimensions.contentWidth, oldDimensions.contentHeight, dimensions.contentWidth, dimensions.contentHeight));
            }
        }
        getFutureScrollPosition() {
            return this._scrollable.getFutureScrollPosition();
        }
        getCurrentScrollPosition() {
            return this._scrollable.getCurrentScrollPosition();
        }
        setScrollPositionNow(update) {
            this._scrollable.setScrollPositionNow(update);
        }
        setScrollPositionSmooth(update) {
            this._scrollable.setScrollPositionSmooth(update);
        }
        hasPendingScrollAnimation() {
            return this._scrollable.hasPendingScrollAnimation();
        }
    }
    class ViewLayout extends lifecycle_1.Disposable {
        constructor(configuration, lineCount, scheduleAtNextAnimationFrame) {
            super();
            this._configuration = configuration;
            const options = this._configuration.options;
            const layoutInfo = options.get(146 /* EditorOption.layoutInfo */);
            const padding = options.get(84 /* EditorOption.padding */);
            this._linesLayout = new linesLayout_1.LinesLayout(lineCount, options.get(67 /* EditorOption.lineHeight */), padding.top, padding.bottom);
            this._maxLineWidth = 0;
            this._overlayWidgetsMinWidth = 0;
            this._scrollable = this._register(new EditorScrollable(0, scheduleAtNextAnimationFrame));
            this._configureSmoothScrollDuration();
            this._scrollable.setScrollDimensions(new EditorScrollDimensions(layoutInfo.contentWidth, 0, layoutInfo.height, 0));
            this.onDidScroll = this._scrollable.onDidScroll;
            this.onDidContentSizeChange = this._scrollable.onDidContentSizeChange;
            this._updateHeight();
        }
        dispose() {
            super.dispose();
        }
        getScrollable() {
            return this._scrollable.getScrollable();
        }
        onHeightMaybeChanged() {
            this._updateHeight();
        }
        _configureSmoothScrollDuration() {
            this._scrollable.setSmoothScrollDuration(this._configuration.options.get(115 /* EditorOption.smoothScrolling */) ? SMOOTH_SCROLLING_TIME : 0);
        }
        // ---- begin view event handlers
        onConfigurationChanged(e) {
            const options = this._configuration.options;
            if (e.hasChanged(67 /* EditorOption.lineHeight */)) {
                this._linesLayout.setLineHeight(options.get(67 /* EditorOption.lineHeight */));
            }
            if (e.hasChanged(84 /* EditorOption.padding */)) {
                const padding = options.get(84 /* EditorOption.padding */);
                this._linesLayout.setPadding(padding.top, padding.bottom);
            }
            if (e.hasChanged(146 /* EditorOption.layoutInfo */)) {
                const layoutInfo = options.get(146 /* EditorOption.layoutInfo */);
                const width = layoutInfo.contentWidth;
                const height = layoutInfo.height;
                const scrollDimensions = this._scrollable.getScrollDimensions();
                const contentWidth = scrollDimensions.contentWidth;
                this._scrollable.setScrollDimensions(new EditorScrollDimensions(width, scrollDimensions.contentWidth, height, this._getContentHeight(width, height, contentWidth)));
            }
            else {
                this._updateHeight();
            }
            if (e.hasChanged(115 /* EditorOption.smoothScrolling */)) {
                this._configureSmoothScrollDuration();
            }
        }
        onFlushed(lineCount) {
            this._linesLayout.onFlushed(lineCount);
        }
        onLinesDeleted(fromLineNumber, toLineNumber) {
            this._linesLayout.onLinesDeleted(fromLineNumber, toLineNumber);
        }
        onLinesInserted(fromLineNumber, toLineNumber) {
            this._linesLayout.onLinesInserted(fromLineNumber, toLineNumber);
        }
        // ---- end view event handlers
        _getHorizontalScrollbarHeight(width, scrollWidth) {
            const options = this._configuration.options;
            const scrollbar = options.get(104 /* EditorOption.scrollbar */);
            if (scrollbar.horizontal === 2 /* ScrollbarVisibility.Hidden */) {
                // horizontal scrollbar not visible
                return 0;
            }
            if (width >= scrollWidth) {
                // horizontal scrollbar not visible
                return 0;
            }
            return scrollbar.horizontalScrollbarSize;
        }
        _getContentHeight(width, height, contentWidth) {
            const options = this._configuration.options;
            let result = this._linesLayout.getLinesTotalHeight();
            if (options.get(106 /* EditorOption.scrollBeyondLastLine */)) {
                result += Math.max(0, height - options.get(67 /* EditorOption.lineHeight */) - options.get(84 /* EditorOption.padding */).bottom);
            }
            else if (!options.get(104 /* EditorOption.scrollbar */).ignoreHorizontalScrollbarInContentHeight) {
                result += this._getHorizontalScrollbarHeight(width, contentWidth);
            }
            return result;
        }
        _updateHeight() {
            const scrollDimensions = this._scrollable.getScrollDimensions();
            const width = scrollDimensions.width;
            const height = scrollDimensions.height;
            const contentWidth = scrollDimensions.contentWidth;
            this._scrollable.setScrollDimensions(new EditorScrollDimensions(width, scrollDimensions.contentWidth, height, this._getContentHeight(width, height, contentWidth)));
        }
        // ---- Layouting logic
        getCurrentViewport() {
            const scrollDimensions = this._scrollable.getScrollDimensions();
            const currentScrollPosition = this._scrollable.getCurrentScrollPosition();
            return new viewModel_1.Viewport(currentScrollPosition.scrollTop, currentScrollPosition.scrollLeft, scrollDimensions.width, scrollDimensions.height);
        }
        getFutureViewport() {
            const scrollDimensions = this._scrollable.getScrollDimensions();
            const currentScrollPosition = this._scrollable.getFutureScrollPosition();
            return new viewModel_1.Viewport(currentScrollPosition.scrollTop, currentScrollPosition.scrollLeft, scrollDimensions.width, scrollDimensions.height);
        }
        _computeContentWidth() {
            const options = this._configuration.options;
            const maxLineWidth = this._maxLineWidth;
            const wrappingInfo = options.get(147 /* EditorOption.wrappingInfo */);
            const fontInfo = options.get(50 /* EditorOption.fontInfo */);
            const layoutInfo = options.get(146 /* EditorOption.layoutInfo */);
            if (wrappingInfo.isViewportWrapping) {
                const minimap = options.get(73 /* EditorOption.minimap */);
                if (maxLineWidth > layoutInfo.contentWidth + fontInfo.typicalHalfwidthCharacterWidth) {
                    // This is a case where viewport wrapping is on, but the line extends above the viewport
                    if (minimap.enabled && minimap.side === 'right') {
                        // We need to accomodate the scrollbar width
                        return maxLineWidth + layoutInfo.verticalScrollbarWidth;
                    }
                }
                return maxLineWidth;
            }
            else {
                const extraHorizontalSpace = options.get(105 /* EditorOption.scrollBeyondLastColumn */) * fontInfo.typicalHalfwidthCharacterWidth;
                const whitespaceMinWidth = this._linesLayout.getWhitespaceMinWidth();
                return Math.max(maxLineWidth + extraHorizontalSpace + layoutInfo.verticalScrollbarWidth, whitespaceMinWidth, this._overlayWidgetsMinWidth);
            }
        }
        setMaxLineWidth(maxLineWidth) {
            this._maxLineWidth = maxLineWidth;
            this._updateContentWidth();
        }
        setOverlayWidgetsMinWidth(maxMinWidth) {
            this._overlayWidgetsMinWidth = maxMinWidth;
            this._updateContentWidth();
        }
        _updateContentWidth() {
            const scrollDimensions = this._scrollable.getScrollDimensions();
            this._scrollable.setScrollDimensions(new EditorScrollDimensions(scrollDimensions.width, this._computeContentWidth(), scrollDimensions.height, scrollDimensions.contentHeight));
            // The height might depend on the fact that there is a horizontal scrollbar or not
            this._updateHeight();
        }
        // ---- view state
        saveState() {
            const currentScrollPosition = this._scrollable.getFutureScrollPosition();
            const scrollTop = currentScrollPosition.scrollTop;
            const firstLineNumberInViewport = this._linesLayout.getLineNumberAtOrAfterVerticalOffset(scrollTop);
            const whitespaceAboveFirstLine = this._linesLayout.getWhitespaceAccumulatedHeightBeforeLineNumber(firstLineNumberInViewport);
            return {
                scrollTop: scrollTop,
                scrollTopWithoutViewZones: scrollTop - whitespaceAboveFirstLine,
                scrollLeft: currentScrollPosition.scrollLeft
            };
        }
        // ----
        changeWhitespace(callback) {
            const hadAChange = this._linesLayout.changeWhitespace(callback);
            if (hadAChange) {
                this.onHeightMaybeChanged();
            }
            return hadAChange;
        }
        getVerticalOffsetForLineNumber(lineNumber, includeViewZones = false) {
            return this._linesLayout.getVerticalOffsetForLineNumber(lineNumber, includeViewZones);
        }
        getVerticalOffsetAfterLineNumber(lineNumber, includeViewZones = false) {
            return this._linesLayout.getVerticalOffsetAfterLineNumber(lineNumber, includeViewZones);
        }
        isAfterLines(verticalOffset) {
            return this._linesLayout.isAfterLines(verticalOffset);
        }
        isInTopPadding(verticalOffset) {
            return this._linesLayout.isInTopPadding(verticalOffset);
        }
        isInBottomPadding(verticalOffset) {
            return this._linesLayout.isInBottomPadding(verticalOffset);
        }
        getLineNumberAtVerticalOffset(verticalOffset) {
            return this._linesLayout.getLineNumberAtOrAfterVerticalOffset(verticalOffset);
        }
        getWhitespaceAtVerticalOffset(verticalOffset) {
            return this._linesLayout.getWhitespaceAtVerticalOffset(verticalOffset);
        }
        getLinesViewportData() {
            const visibleBox = this.getCurrentViewport();
            return this._linesLayout.getLinesViewportData(visibleBox.top, visibleBox.top + visibleBox.height);
        }
        getLinesViewportDataAtScrollTop(scrollTop) {
            // do some minimal validations on scrollTop
            const scrollDimensions = this._scrollable.getScrollDimensions();
            if (scrollTop + scrollDimensions.height > scrollDimensions.scrollHeight) {
                scrollTop = scrollDimensions.scrollHeight - scrollDimensions.height;
            }
            if (scrollTop < 0) {
                scrollTop = 0;
            }
            return this._linesLayout.getLinesViewportData(scrollTop, scrollTop + scrollDimensions.height);
        }
        getWhitespaceViewportData() {
            const visibleBox = this.getCurrentViewport();
            return this._linesLayout.getWhitespaceViewportData(visibleBox.top, visibleBox.top + visibleBox.height);
        }
        getWhitespaces() {
            return this._linesLayout.getWhitespaces();
        }
        // ----
        getContentWidth() {
            const scrollDimensions = this._scrollable.getScrollDimensions();
            return scrollDimensions.contentWidth;
        }
        getScrollWidth() {
            const scrollDimensions = this._scrollable.getScrollDimensions();
            return scrollDimensions.scrollWidth;
        }
        getContentHeight() {
            const scrollDimensions = this._scrollable.getScrollDimensions();
            return scrollDimensions.contentHeight;
        }
        getScrollHeight() {
            const scrollDimensions = this._scrollable.getScrollDimensions();
            return scrollDimensions.scrollHeight;
        }
        getCurrentScrollLeft() {
            const currentScrollPosition = this._scrollable.getCurrentScrollPosition();
            return currentScrollPosition.scrollLeft;
        }
        getCurrentScrollTop() {
            const currentScrollPosition = this._scrollable.getCurrentScrollPosition();
            return currentScrollPosition.scrollTop;
        }
        validateScrollPosition(scrollPosition) {
            return this._scrollable.validateScrollPosition(scrollPosition);
        }
        setScrollPosition(position, type) {
            if (type === 1 /* ScrollType.Immediate */) {
                this._scrollable.setScrollPositionNow(position);
            }
            else {
                this._scrollable.setScrollPositionSmooth(position);
            }
        }
        hasPendingScrollAnimation() {
            return this._scrollable.hasPendingScrollAnimation();
        }
        deltaScrollNow(deltaScrollLeft, deltaScrollTop) {
            const currentScrollPosition = this._scrollable.getCurrentScrollPosition();
            this._scrollable.setScrollPositionNow({
                scrollLeft: currentScrollPosition.scrollLeft + deltaScrollLeft,
                scrollTop: currentScrollPosition.scrollTop + deltaScrollTop
            });
        }
    }
    exports.ViewLayout = ViewLayout;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[607/*vs/editor/contrib/caretOperations/browser/moveCaretCommand*/], __M([1/*require*/,0/*exports*/,4/*vs/editor/common/core/range*/,23/*vs/editor/common/core/selection*/]), function (require, exports, range_1, selection_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MoveCaretCommand = void 0;
    class MoveCaretCommand {
        constructor(selection, isMovingLeft) {
            this._selection = selection;
            this._isMovingLeft = isMovingLeft;
        }
        getEditOperations(model, builder) {
            if (this._selection.startLineNumber !== this._selection.endLineNumber || this._selection.isEmpty()) {
                return;
            }
            const lineNumber = this._selection.startLineNumber;
            const startColumn = this._selection.startColumn;
            const endColumn = this._selection.endColumn;
            if (this._isMovingLeft && startColumn === 1) {
                return;
            }
            if (!this._isMovingLeft && endColumn === model.getLineMaxColumn(lineNumber)) {
                return;
            }
            if (this._isMovingLeft) {
                const rangeBefore = new range_1.Range(lineNumber, startColumn - 1, lineNumber, startColumn);
                const charBefore = model.getValueInRange(rangeBefore);
                builder.addEditOperation(rangeBefore, null);
                builder.addEditOperation(new range_1.Range(lineNumber, endColumn, lineNumber, endColumn), charBefore);
            }
            else {
                const rangeAfter = new range_1.Range(lineNumber, endColumn, lineNumber, endColumn + 1);
                const charAfter = model.getValueInRange(rangeAfter);
                builder.addEditOperation(rangeAfter, null);
                builder.addEditOperation(new range_1.Range(lineNumber, startColumn, lineNumber, startColumn), charAfter);
            }
        }
        computeCursorState(model, helper) {
            if (this._isMovingLeft) {
                return new selection_1.Selection(this._selection.startLineNumber, this._selection.startColumn - 1, this._selection.endLineNumber, this._selection.endColumn - 1);
            }
            else {
                return new selection_1.Selection(this._selection.startLineNumber, this._selection.startColumn + 1, this._selection.endLineNumber, this._selection.endColumn + 1);
            }
        }
    }
    exports.MoveCaretCommand = MoveCaretCommand;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[134/*vs/editor/contrib/codeAction/common/types*/], __M([1/*require*/,0/*exports*/,8/*vs/base/common/errors*/,91/*vs/base/common/hierarchicalKind*/]), function (require, exports, errors_1, hierarchicalKind_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CodeActionItem = exports.CodeActionCommandArgs = exports.CodeActionTriggerSource = exports.CodeActionKind = void 0;
    exports.mayIncludeActionsOfKind = mayIncludeActionsOfKind;
    exports.filtersAction = filtersAction;
    exports.CodeActionKind = new class {
        constructor() {
            this.QuickFix = new hierarchicalKind_1.HierarchicalKind('quickfix');
            this.Refactor = new hierarchicalKind_1.HierarchicalKind('refactor');
            this.RefactorExtract = this.Refactor.append('extract');
            this.RefactorInline = this.Refactor.append('inline');
            this.RefactorMove = this.Refactor.append('move');
            this.RefactorRewrite = this.Refactor.append('rewrite');
            this.Notebook = new hierarchicalKind_1.HierarchicalKind('notebook');
            this.Source = new hierarchicalKind_1.HierarchicalKind('source');
            this.SourceOrganizeImports = this.Source.append('organizeImports');
            this.SourceFixAll = this.Source.append('fixAll');
            this.SurroundWith = this.Refactor.append('surround');
        }
    };
    var CodeActionTriggerSource;
    (function (CodeActionTriggerSource) {
        CodeActionTriggerSource["Refactor"] = "refactor";
        CodeActionTriggerSource["RefactorPreview"] = "refactor preview";
        CodeActionTriggerSource["Lightbulb"] = "lightbulb";
        CodeActionTriggerSource["Default"] = "other (default)";
        CodeActionTriggerSource["SourceAction"] = "source action";
        CodeActionTriggerSource["QuickFix"] = "quick fix action";
        CodeActionTriggerSource["FixAll"] = "fix all";
        CodeActionTriggerSource["OrganizeImports"] = "organize imports";
        CodeActionTriggerSource["AutoFix"] = "auto fix";
        CodeActionTriggerSource["QuickFixHover"] = "quick fix hover window";
        CodeActionTriggerSource["OnSave"] = "save participants";
        CodeActionTriggerSource["ProblemsView"] = "problems view";
    })(CodeActionTriggerSource || (exports.CodeActionTriggerSource = CodeActionTriggerSource = {}));
    function mayIncludeActionsOfKind(filter, providedKind) {
        // A provided kind may be a subset or superset of our filtered kind.
        if (filter.include && !filter.include.intersects(providedKind)) {
            return false;
        }
        if (filter.excludes) {
            if (filter.excludes.some(exclude => excludesAction(providedKind, exclude, filter.include))) {
                return false;
            }
        }
        // Don't return source actions unless they are explicitly requested
        if (!filter.includeSourceActions && exports.CodeActionKind.Source.contains(providedKind)) {
            return false;
        }
        return true;
    }
    function filtersAction(filter, action) {
        const actionKind = action.kind ? new hierarchicalKind_1.HierarchicalKind(action.kind) : undefined;
        // Filter out actions by kind
        if (filter.include) {
            if (!actionKind || !filter.include.contains(actionKind)) {
                return false;
            }
        }
        if (filter.excludes) {
            if (actionKind && filter.excludes.some(exclude => excludesAction(actionKind, exclude, filter.include))) {
                return false;
            }
        }
        // Don't return source actions unless they are explicitly requested
        if (!filter.includeSourceActions) {
            if (actionKind && exports.CodeActionKind.Source.contains(actionKind)) {
                return false;
            }
        }
        if (filter.onlyIncludePreferredActions) {
            if (!action.isPreferred) {
                return false;
            }
        }
        return true;
    }
    function excludesAction(providedKind, exclude, include) {
        if (!exclude.contains(providedKind)) {
            return false;
        }
        if (include && exclude.contains(include)) {
            // The include is more specific, don't filter out
            return false;
        }
        return true;
    }
    class CodeActionCommandArgs {
        static fromUser(arg, defaults) {
            if (!arg || typeof arg !== 'object') {
                return new CodeActionCommandArgs(defaults.kind, defaults.apply, false);
            }
            return new CodeActionCommandArgs(CodeActionCommandArgs.getKindFromUser(arg, defaults.kind), CodeActionCommandArgs.getApplyFromUser(arg, defaults.apply), CodeActionCommandArgs.getPreferredUser(arg));
        }
        static getApplyFromUser(arg, defaultAutoApply) {
            switch (typeof arg.apply === 'string' ? arg.apply.toLowerCase() : '') {
                case 'first': return "first" /* CodeActionAutoApply.First */;
                case 'never': return "never" /* CodeActionAutoApply.Never */;
                case 'ifsingle': return "ifSingle" /* CodeActionAutoApply.IfSingle */;
                default: return defaultAutoApply;
            }
        }
        static getKindFromUser(arg, defaultKind) {
            return typeof arg.kind === 'string'
                ? new hierarchicalKind_1.HierarchicalKind(arg.kind)
                : defaultKind;
        }
        static getPreferredUser(arg) {
            return typeof arg.preferred === 'boolean'
                ? arg.preferred
                : false;
        }
        constructor(kind, apply, preferred) {
            this.kind = kind;
            this.apply = apply;
            this.preferred = preferred;
        }
    }
    exports.CodeActionCommandArgs = CodeActionCommandArgs;
    class CodeActionItem {
        constructor(action, provider, highlightRange) {
            this.action = action;
            this.provider = provider;
            this.highlightRange = highlightRange;
        }
        async resolve(token) {
            if (this.provider?.resolveCodeAction && !this.action.edit) {
                let action;
                try {
                    action = await this.provider.resolveCodeAction(this.action, token);
                }
                catch (err) {
                    (0, errors_1.onUnexpectedExternalError)(err);
                }
                if (action) {
                    this.action.edit = action.edit;
                }
            }
            return this;
        }
    }
    exports.CodeActionItem = CodeActionItem;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[608/*vs/editor/contrib/colorPicker/browser/colorPickerModel*/], __M([1/*require*/,0/*exports*/,6/*vs/base/common/event*/]), function (require, exports, event_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ColorPickerModel = void 0;
    class ColorPickerModel {
        get color() {
            return this._color;
        }
        set color(color) {
            if (this._color.equals(color)) {
                return;
            }
            this._color = color;
            this._onDidChangeColor.fire(color);
        }
        get presentation() { return this.colorPresentations[this.presentationIndex]; }
        get colorPresentations() {
            return this._colorPresentations;
        }
        set colorPresentations(colorPresentations) {
            this._colorPresentations = colorPresentations;
            if (this.presentationIndex > colorPresentations.length - 1) {
                this.presentationIndex = 0;
            }
            this._onDidChangePresentation.fire(this.presentation);
        }
        constructor(color, availableColorPresentations, presentationIndex) {
            this.presentationIndex = presentationIndex;
            this._onColorFlushed = new event_1.Emitter();
            this.onColorFlushed = this._onColorFlushed.event;
            this._onDidChangeColor = new event_1.Emitter();
            this.onDidChangeColor = this._onDidChangeColor.event;
            this._onDidChangePresentation = new event_1.Emitter();
            this.onDidChangePresentation = this._onDidChangePresentation.event;
            this.originalColor = color;
            this._color = color;
            this._colorPresentations = availableColorPresentations;
        }
        selectNextColorPresentation() {
            this.presentationIndex = (this.presentationIndex + 1) % this.colorPresentations.length;
            this.flushColor();
            this._onDidChangePresentation.fire(this.presentation);
        }
        guessColorPresentation(color, originalText) {
            let presentationIndex = -1;
            for (let i = 0; i < this.colorPresentations.length; i++) {
                if (originalText.toLowerCase() === this.colorPresentations[i].label) {
                    presentationIndex = i;
                    break;
                }
            }
            if (presentationIndex === -1) {
                // check which color presentation text has same prefix as original text's prefix
                const originalTextPrefix = originalText.split('(')[0].toLowerCase();
                for (let i = 0; i < this.colorPresentations.length; i++) {
                    if (this.colorPresentations[i].label.toLowerCase().startsWith(originalTextPrefix)) {
                        presentationIndex = i;
                        break;
                    }
                }
            }
            if (presentationIndex !== -1 && presentationIndex !== this.presentationIndex) {
                this.presentationIndex = presentationIndex;
                this._onDidChangePresentation.fire(this.presentation);
            }
        }
        flushColor() {
            this._onColorFlushed.fire(this._color);
        }
    }
    exports.ColorPickerModel = ColorPickerModel;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[333/*vs/editor/contrib/comment/browser/blockCommentCommand*/], __M([1/*require*/,0/*exports*/,75/*vs/editor/common/core/editOperation*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/,23/*vs/editor/common/core/selection*/]), function (require, exports, editOperation_1, position_1, range_1, selection_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.BlockCommentCommand = void 0;
    class BlockCommentCommand {
        constructor(selection, insertSpace, languageConfigurationService) {
            this.languageConfigurationService = languageConfigurationService;
            this._selection = selection;
            this._insertSpace = insertSpace;
            this._usedEndToken = null;
        }
        static _haystackHasNeedleAtOffset(haystack, needle, offset) {
            if (offset < 0) {
                return false;
            }
            const needleLength = needle.length;
            const haystackLength = haystack.length;
            if (offset + needleLength > haystackLength) {
                return false;
            }
            for (let i = 0; i < needleLength; i++) {
                const codeA = haystack.charCodeAt(offset + i);
                const codeB = needle.charCodeAt(i);
                if (codeA === codeB) {
                    continue;
                }
                if (codeA >= 65 /* CharCode.A */ && codeA <= 90 /* CharCode.Z */ && codeA + 32 === codeB) {
                    // codeA is upper-case variant of codeB
                    continue;
                }
                if (codeB >= 65 /* CharCode.A */ && codeB <= 90 /* CharCode.Z */ && codeB + 32 === codeA) {
                    // codeB is upper-case variant of codeA
                    continue;
                }
                return false;
            }
            return true;
        }
        _createOperationsForBlockComment(selection, startToken, endToken, insertSpace, model, builder) {
            const startLineNumber = selection.startLineNumber;
            const startColumn = selection.startColumn;
            const endLineNumber = selection.endLineNumber;
            const endColumn = selection.endColumn;
            const startLineText = model.getLineContent(startLineNumber);
            const endLineText = model.getLineContent(endLineNumber);
            let startTokenIndex = startLineText.lastIndexOf(startToken, startColumn - 1 + startToken.length);
            let endTokenIndex = endLineText.indexOf(endToken, endColumn - 1 - endToken.length);
            if (startTokenIndex !== -1 && endTokenIndex !== -1) {
                if (startLineNumber === endLineNumber) {
                    const lineBetweenTokens = startLineText.substring(startTokenIndex + startToken.length, endTokenIndex);
                    if (lineBetweenTokens.indexOf(endToken) >= 0) {
                        // force to add a block comment
                        startTokenIndex = -1;
                        endTokenIndex = -1;
                    }
                }
                else {
                    const startLineAfterStartToken = startLineText.substring(startTokenIndex + startToken.length);
                    const endLineBeforeEndToken = endLineText.substring(0, endTokenIndex);
                    if (startLineAfterStartToken.indexOf(endToken) >= 0 || endLineBeforeEndToken.indexOf(endToken) >= 0) {
                        // force to add a block comment
                        startTokenIndex = -1;
                        endTokenIndex = -1;
                    }
                }
            }
            let ops;
            if (startTokenIndex !== -1 && endTokenIndex !== -1) {
                // Consider spaces as part of the comment tokens
                if (insertSpace && startTokenIndex + startToken.length < startLineText.length && startLineText.charCodeAt(startTokenIndex + startToken.length) === 32 /* CharCode.Space */) {
                    // Pretend the start token contains a trailing space
                    startToken = startToken + ' ';
                }
                if (insertSpace && endTokenIndex > 0 && endLineText.charCodeAt(endTokenIndex - 1) === 32 /* CharCode.Space */) {
                    // Pretend the end token contains a leading space
                    endToken = ' ' + endToken;
                    endTokenIndex -= 1;
                }
                ops = BlockCommentCommand._createRemoveBlockCommentOperations(new range_1.Range(startLineNumber, startTokenIndex + startToken.length + 1, endLineNumber, endTokenIndex + 1), startToken, endToken);
            }
            else {
                ops = BlockCommentCommand._createAddBlockCommentOperations(selection, startToken, endToken, this._insertSpace);
                this._usedEndToken = ops.length === 1 ? endToken : null;
            }
            for (const op of ops) {
                builder.addTrackedEditOperation(op.range, op.text);
            }
        }
        static _createRemoveBlockCommentOperations(r, startToken, endToken) {
            const res = [];
            if (!range_1.Range.isEmpty(r)) {
                // Remove block comment start
                res.push(editOperation_1.EditOperation.delete(new range_1.Range(r.startLineNumber, r.startColumn - startToken.length, r.startLineNumber, r.startColumn)));
                // Remove block comment end
                res.push(editOperation_1.EditOperation.delete(new range_1.Range(r.endLineNumber, r.endColumn, r.endLineNumber, r.endColumn + endToken.length)));
            }
            else {
                // Remove both continuously
                res.push(editOperation_1.EditOperation.delete(new range_1.Range(r.startLineNumber, r.startColumn - startToken.length, r.endLineNumber, r.endColumn + endToken.length)));
            }
            return res;
        }
        static _createAddBlockCommentOperations(r, startToken, endToken, insertSpace) {
            const res = [];
            if (!range_1.Range.isEmpty(r)) {
                // Insert block comment start
                res.push(editOperation_1.EditOperation.insert(new position_1.Position(r.startLineNumber, r.startColumn), startToken + (insertSpace ? ' ' : '')));
                // Insert block comment end
                res.push(editOperation_1.EditOperation.insert(new position_1.Position(r.endLineNumber, r.endColumn), (insertSpace ? ' ' : '') + endToken));
            }
            else {
                // Insert both continuously
                res.push(editOperation_1.EditOperation.replace(new range_1.Range(r.startLineNumber, r.startColumn, r.endLineNumber, r.endColumn), startToken + '  ' + endToken));
            }
            return res;
        }
        getEditOperations(model, builder) {
            const startLineNumber = this._selection.startLineNumber;
            const startColumn = this._selection.startColumn;
            model.tokenization.tokenizeIfCheap(startLineNumber);
            const languageId = model.getLanguageIdAtPosition(startLineNumber, startColumn);
            const config = this.languageConfigurationService.getLanguageConfiguration(languageId).comments;
            if (!config || !config.blockCommentStartToken || !config.blockCommentEndToken) {
                // Mode does not support block comments
                return;
            }
            this._createOperationsForBlockComment(this._selection, config.blockCommentStartToken, config.blockCommentEndToken, this._insertSpace, model, builder);
        }
        computeCursorState(model, helper) {
            const inverseEditOperations = helper.getInverseEditOperations();
            if (inverseEditOperations.length === 2) {
                const startTokenEditOperation = inverseEditOperations[0];
                const endTokenEditOperation = inverseEditOperations[1];
                return new selection_1.Selection(startTokenEditOperation.range.endLineNumber, startTokenEditOperation.range.endColumn, endTokenEditOperation.range.startLineNumber, endTokenEditOperation.range.startColumn);
            }
            else {
                const srcRange = inverseEditOperations[0].range;
                const deltaColumn = this._usedEndToken ? -this._usedEndToken.length - 1 : 0; // minus 1 space before endToken
                return new selection_1.Selection(srcRange.endLineNumber, srcRange.endColumn + deltaColumn, srcRange.endLineNumber, srcRange.endColumn + deltaColumn);
            }
        }
    }
    exports.BlockCommentCommand = BlockCommentCommand;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[609/*vs/editor/contrib/comment/browser/lineCommentCommand*/], __M([1/*require*/,0/*exports*/,11/*vs/base/common/strings*/,75/*vs/editor/common/core/editOperation*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/,23/*vs/editor/common/core/selection*/,333/*vs/editor/contrib/comment/browser/blockCommentCommand*/]), function (require, exports, strings, editOperation_1, position_1, range_1, selection_1, blockCommentCommand_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.LineCommentCommand = void 0;
    class LineCommentCommand {
        constructor(languageConfigurationService, selection, indentSize, type, insertSpace, ignoreEmptyLines, ignoreFirstLine) {
            this.languageConfigurationService = languageConfigurationService;
            this._selection = selection;
            this._indentSize = indentSize;
            this._type = type;
            this._insertSpace = insertSpace;
            this._selectionId = null;
            this._deltaColumn = 0;
            this._moveEndPositionDown = false;
            this._ignoreEmptyLines = ignoreEmptyLines;
            this._ignoreFirstLine = ignoreFirstLine || false;
        }
        /**
         * Do an initial pass over the lines and gather info about the line comment string.
         * Returns null if any of the lines doesn't support a line comment string.
         */
        static _gatherPreflightCommentStrings(model, startLineNumber, endLineNumber, languageConfigurationService) {
            model.tokenization.tokenizeIfCheap(startLineNumber);
            const languageId = model.getLanguageIdAtPosition(startLineNumber, 1);
            const config = languageConfigurationService.getLanguageConfiguration(languageId).comments;
            const commentStr = (config ? config.lineCommentToken : null);
            if (!commentStr) {
                // Mode does not support line comments
                return null;
            }
            const lines = [];
            for (let i = 0, lineCount = endLineNumber - startLineNumber + 1; i < lineCount; i++) {
                lines[i] = {
                    ignore: false,
                    commentStr: commentStr,
                    commentStrOffset: 0,
                    commentStrLength: commentStr.length
                };
            }
            return lines;
        }
        /**
         * Analyze lines and decide which lines are relevant and what the toggle should do.
         * Also, build up several offsets and lengths useful in the generation of editor operations.
         */
        static _analyzeLines(type, insertSpace, model, lines, startLineNumber, ignoreEmptyLines, ignoreFirstLine, languageConfigurationService) {
            let onlyWhitespaceLines = true;
            let shouldRemoveComments;
            if (type === 0 /* Type.Toggle */) {
                shouldRemoveComments = true;
            }
            else if (type === 1 /* Type.ForceAdd */) {
                shouldRemoveComments = false;
            }
            else {
                shouldRemoveComments = true;
            }
            for (let i = 0, lineCount = lines.length; i < lineCount; i++) {
                const lineData = lines[i];
                const lineNumber = startLineNumber + i;
                if (lineNumber === startLineNumber && ignoreFirstLine) {
                    // first line ignored
                    lineData.ignore = true;
                    continue;
                }
                const lineContent = model.getLineContent(lineNumber);
                const lineContentStartOffset = strings.firstNonWhitespaceIndex(lineContent);
                if (lineContentStartOffset === -1) {
                    // Empty or whitespace only line
                    lineData.ignore = ignoreEmptyLines;
                    lineData.commentStrOffset = lineContent.length;
                    continue;
                }
                onlyWhitespaceLines = false;
                lineData.ignore = false;
                lineData.commentStrOffset = lineContentStartOffset;
                if (shouldRemoveComments && !blockCommentCommand_1.BlockCommentCommand._haystackHasNeedleAtOffset(lineContent, lineData.commentStr, lineContentStartOffset)) {
                    if (type === 0 /* Type.Toggle */) {
                        // Every line so far has been a line comment, but this one is not
                        shouldRemoveComments = false;
                    }
                    else if (type === 1 /* Type.ForceAdd */) {
                        // Will not happen
                    }
                    else {
                        lineData.ignore = true;
                    }
                }
                if (shouldRemoveComments && insertSpace) {
                    // Remove a following space if present
                    const commentStrEndOffset = lineContentStartOffset + lineData.commentStrLength;
                    if (commentStrEndOffset < lineContent.length && lineContent.charCodeAt(commentStrEndOffset) === 32 /* CharCode.Space */) {
                        lineData.commentStrLength += 1;
                    }
                }
            }
            if (type === 0 /* Type.Toggle */ && onlyWhitespaceLines) {
                // For only whitespace lines, we insert comments
                shouldRemoveComments = false;
                // Also, no longer ignore them
                for (let i = 0, lineCount = lines.length; i < lineCount; i++) {
                    lines[i].ignore = false;
                }
            }
            return {
                supported: true,
                shouldRemoveComments: shouldRemoveComments,
                lines: lines
            };
        }
        /**
         * Analyze all lines and decide exactly what to do => not supported | insert line comments | remove line comments
         */
        static _gatherPreflightData(type, insertSpace, model, startLineNumber, endLineNumber, ignoreEmptyLines, ignoreFirstLine, languageConfigurationService) {
            const lines = LineCommentCommand._gatherPreflightCommentStrings(model, startLineNumber, endLineNumber, languageConfigurationService);
            if (lines === null) {
                return {
                    supported: false
                };
            }
            return LineCommentCommand._analyzeLines(type, insertSpace, model, lines, startLineNumber, ignoreEmptyLines, ignoreFirstLine, languageConfigurationService);
        }
        /**
         * Given a successful analysis, execute either insert line comments, either remove line comments
         */
        _executeLineComments(model, builder, data, s) {
            let ops;
            if (data.shouldRemoveComments) {
                ops = LineCommentCommand._createRemoveLineCommentsOperations(data.lines, s.startLineNumber);
            }
            else {
                LineCommentCommand._normalizeInsertionPoint(model, data.lines, s.startLineNumber, this._indentSize);
                ops = this._createAddLineCommentsOperations(data.lines, s.startLineNumber);
            }
            const cursorPosition = new position_1.Position(s.positionLineNumber, s.positionColumn);
            for (let i = 0, len = ops.length; i < len; i++) {
                builder.addEditOperation(ops[i].range, ops[i].text);
                if (range_1.Range.isEmpty(ops[i].range) && range_1.Range.getStartPosition(ops[i].range).equals(cursorPosition)) {
                    const lineContent = model.getLineContent(cursorPosition.lineNumber);
                    if (lineContent.length + 1 === cursorPosition.column) {
                        this._deltaColumn = (ops[i].text || '').length;
                    }
                }
            }
            this._selectionId = builder.trackSelection(s);
        }
        _attemptRemoveBlockComment(model, s, startToken, endToken) {
            let startLineNumber = s.startLineNumber;
            let endLineNumber = s.endLineNumber;
            const startTokenAllowedBeforeColumn = endToken.length + Math.max(model.getLineFirstNonWhitespaceColumn(s.startLineNumber), s.startColumn);
            let startTokenIndex = model.getLineContent(startLineNumber).lastIndexOf(startToken, startTokenAllowedBeforeColumn - 1);
            let endTokenIndex = model.getLineContent(endLineNumber).indexOf(endToken, s.endColumn - 1 - startToken.length);
            if (startTokenIndex !== -1 && endTokenIndex === -1) {
                endTokenIndex = model.getLineContent(startLineNumber).indexOf(endToken, startTokenIndex + startToken.length);
                endLineNumber = startLineNumber;
            }
            if (startTokenIndex === -1 && endTokenIndex !== -1) {
                startTokenIndex = model.getLineContent(endLineNumber).lastIndexOf(startToken, endTokenIndex);
                startLineNumber = endLineNumber;
            }
            if (s.isEmpty() && (startTokenIndex === -1 || endTokenIndex === -1)) {
                startTokenIndex = model.getLineContent(startLineNumber).indexOf(startToken);
                if (startTokenIndex !== -1) {
                    endTokenIndex = model.getLineContent(startLineNumber).indexOf(endToken, startTokenIndex + startToken.length);
                }
            }
            // We have to adjust to possible inner white space.
            // For Space after startToken, add Space to startToken - range math will work out.
            if (startTokenIndex !== -1 && model.getLineContent(startLineNumber).charCodeAt(startTokenIndex + startToken.length) === 32 /* CharCode.Space */) {
                startToken += ' ';
            }
            // For Space before endToken, add Space before endToken and shift index one left.
            if (endTokenIndex !== -1 && model.getLineContent(endLineNumber).charCodeAt(endTokenIndex - 1) === 32 /* CharCode.Space */) {
                endToken = ' ' + endToken;
                endTokenIndex -= 1;
            }
            if (startTokenIndex !== -1 && endTokenIndex !== -1) {
                return blockCommentCommand_1.BlockCommentCommand._createRemoveBlockCommentOperations(new range_1.Range(startLineNumber, startTokenIndex + startToken.length + 1, endLineNumber, endTokenIndex + 1), startToken, endToken);
            }
            return null;
        }
        /**
         * Given an unsuccessful analysis, delegate to the block comment command
         */
        _executeBlockComment(model, builder, s) {
            model.tokenization.tokenizeIfCheap(s.startLineNumber);
            const languageId = model.getLanguageIdAtPosition(s.startLineNumber, 1);
            const config = this.languageConfigurationService.getLanguageConfiguration(languageId).comments;
            if (!config || !config.blockCommentStartToken || !config.blockCommentEndToken) {
                // Mode does not support block comments
                return;
            }
            const startToken = config.blockCommentStartToken;
            const endToken = config.blockCommentEndToken;
            let ops = this._attemptRemoveBlockComment(model, s, startToken, endToken);
            if (!ops) {
                if (s.isEmpty()) {
                    const lineContent = model.getLineContent(s.startLineNumber);
                    let firstNonWhitespaceIndex = strings.firstNonWhitespaceIndex(lineContent);
                    if (firstNonWhitespaceIndex === -1) {
                        // Line is empty or contains only whitespace
                        firstNonWhitespaceIndex = lineContent.length;
                    }
                    ops = blockCommentCommand_1.BlockCommentCommand._createAddBlockCommentOperations(new range_1.Range(s.startLineNumber, firstNonWhitespaceIndex + 1, s.startLineNumber, lineContent.length + 1), startToken, endToken, this._insertSpace);
                }
                else {
                    ops = blockCommentCommand_1.BlockCommentCommand._createAddBlockCommentOperations(new range_1.Range(s.startLineNumber, model.getLineFirstNonWhitespaceColumn(s.startLineNumber), s.endLineNumber, model.getLineMaxColumn(s.endLineNumber)), startToken, endToken, this._insertSpace);
                }
                if (ops.length === 1) {
                    // Leave cursor after token and Space
                    this._deltaColumn = startToken.length + 1;
                }
            }
            this._selectionId = builder.trackSelection(s);
            for (const op of ops) {
                builder.addEditOperation(op.range, op.text);
            }
        }
        getEditOperations(model, builder) {
            let s = this._selection;
            this._moveEndPositionDown = false;
            if (s.startLineNumber === s.endLineNumber && this._ignoreFirstLine) {
                builder.addEditOperation(new range_1.Range(s.startLineNumber, model.getLineMaxColumn(s.startLineNumber), s.startLineNumber + 1, 1), s.startLineNumber === model.getLineCount() ? '' : '\n');
                this._selectionId = builder.trackSelection(s);
                return;
            }
            if (s.startLineNumber < s.endLineNumber && s.endColumn === 1) {
                this._moveEndPositionDown = true;
                s = s.setEndPosition(s.endLineNumber - 1, model.getLineMaxColumn(s.endLineNumber - 1));
            }
            const data = LineCommentCommand._gatherPreflightData(this._type, this._insertSpace, model, s.startLineNumber, s.endLineNumber, this._ignoreEmptyLines, this._ignoreFirstLine, this.languageConfigurationService);
            if (data.supported) {
                return this._executeLineComments(model, builder, data, s);
            }
            return this._executeBlockComment(model, builder, s);
        }
        computeCursorState(model, helper) {
            let result = helper.getTrackedSelection(this._selectionId);
            if (this._moveEndPositionDown) {
                result = result.setEndPosition(result.endLineNumber + 1, 1);
            }
            return new selection_1.Selection(result.selectionStartLineNumber, result.selectionStartColumn + this._deltaColumn, result.positionLineNumber, result.positionColumn + this._deltaColumn);
        }
        /**
         * Generate edit operations in the remove line comment case
         */
        static _createRemoveLineCommentsOperations(lines, startLineNumber) {
            const res = [];
            for (let i = 0, len = lines.length; i < len; i++) {
                const lineData = lines[i];
                if (lineData.ignore) {
                    continue;
                }
                res.push(editOperation_1.EditOperation.delete(new range_1.Range(startLineNumber + i, lineData.commentStrOffset + 1, startLineNumber + i, lineData.commentStrOffset + lineData.commentStrLength + 1)));
            }
            return res;
        }
        /**
         * Generate edit operations in the add line comment case
         */
        _createAddLineCommentsOperations(lines, startLineNumber) {
            const res = [];
            const afterCommentStr = this._insertSpace ? ' ' : '';
            for (let i = 0, len = lines.length; i < len; i++) {
                const lineData = lines[i];
                if (lineData.ignore) {
                    continue;
                }
                res.push(editOperation_1.EditOperation.insert(new position_1.Position(startLineNumber + i, lineData.commentStrOffset + 1), lineData.commentStr + afterCommentStr));
            }
            return res;
        }
        static nextVisibleColumn(currentVisibleColumn, indentSize, isTab, columnSize) {
            if (isTab) {
                return currentVisibleColumn + (indentSize - (currentVisibleColumn % indentSize));
            }
            return currentVisibleColumn + columnSize;
        }
        /**
         * Adjust insertion points to have them vertically aligned in the add line comment case
         */
        static _normalizeInsertionPoint(model, lines, startLineNumber, indentSize) {
            let minVisibleColumn = 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */;
            let j;
            let lenJ;
            for (let i = 0, len = lines.length; i < len; i++) {
                if (lines[i].ignore) {
                    continue;
                }
                const lineContent = model.getLineContent(startLineNumber + i);
                let currentVisibleColumn = 0;
                for (let j = 0, lenJ = lines[i].commentStrOffset; currentVisibleColumn < minVisibleColumn && j < lenJ; j++) {
                    currentVisibleColumn = LineCommentCommand.nextVisibleColumn(currentVisibleColumn, indentSize, lineContent.charCodeAt(j) === 9 /* CharCode.Tab */, 1);
                }
                if (currentVisibleColumn < minVisibleColumn) {
                    minVisibleColumn = currentVisibleColumn;
                }
            }
            minVisibleColumn = Math.floor(minVisibleColumn / indentSize) * indentSize;
            for (let i = 0, len = lines.length; i < len; i++) {
                if (lines[i].ignore) {
                    continue;
                }
                const lineContent = model.getLineContent(startLineNumber + i);
                let currentVisibleColumn = 0;
                for (j = 0, lenJ = lines[i].commentStrOffset; currentVisibleColumn < minVisibleColumn && j < lenJ; j++) {
                    currentVisibleColumn = LineCommentCommand.nextVisibleColumn(currentVisibleColumn, indentSize, lineContent.charCodeAt(j) === 9 /* CharCode.Tab */, 1);
                }
                if (currentVisibleColumn > minVisibleColumn) {
                    lines[i].commentStrOffset = j - 1;
                }
                else {
                    lines[i].commentStrOffset = j;
                }
            }
        }
    }
    exports.LineCommentCommand = LineCommentCommand;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[610/*vs/editor/contrib/dnd/browser/dragAndDropCommand*/], __M([1/*require*/,0/*exports*/,4/*vs/editor/common/core/range*/,23/*vs/editor/common/core/selection*/]), function (require, exports, range_1, selection_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DragAndDropCommand = void 0;
    class DragAndDropCommand {
        constructor(selection, targetPosition, copy) {
            this.selection = selection;
            this.targetPosition = targetPosition;
            this.copy = copy;
            this.targetSelection = null;
        }
        getEditOperations(model, builder) {
            const text = model.getValueInRange(this.selection);
            if (!this.copy) {
                builder.addEditOperation(this.selection, null);
            }
            builder.addEditOperation(new range_1.Range(this.targetPosition.lineNumber, this.targetPosition.column, this.targetPosition.lineNumber, this.targetPosition.column), text);
            if (this.selection.containsPosition(this.targetPosition) && !(this.copy && (this.selection.getEndPosition().equals(this.targetPosition) || this.selection.getStartPosition().equals(this.targetPosition)) // we allow users to paste content beside the selection
            )) {
                this.targetSelection = this.selection;
                return;
            }
            if (this.copy) {
                this.targetSelection = new selection_1.Selection(this.targetPosition.lineNumber, this.targetPosition.column, this.selection.endLineNumber - this.selection.startLineNumber + this.targetPosition.lineNumber, this.selection.startLineNumber === this.selection.endLineNumber ?
                    this.targetPosition.column + this.selection.endColumn - this.selection.startColumn :
                    this.selection.endColumn);
                return;
            }
            if (this.targetPosition.lineNumber > this.selection.endLineNumber) {
                // Drag the selection downwards
                this.targetSelection = new selection_1.Selection(this.targetPosition.lineNumber - this.selection.endLineNumber + this.selection.startLineNumber, this.targetPosition.column, this.targetPosition.lineNumber, this.selection.startLineNumber === this.selection.endLineNumber ?
                    this.targetPosition.column + this.selection.endColumn - this.selection.startColumn :
                    this.selection.endColumn);
                return;
            }
            if (this.targetPosition.lineNumber < this.selection.endLineNumber) {
                // Drag the selection upwards
                this.targetSelection = new selection_1.Selection(this.targetPosition.lineNumber, this.targetPosition.column, this.targetPosition.lineNumber + this.selection.endLineNumber - this.selection.startLineNumber, this.selection.startLineNumber === this.selection.endLineNumber ?
                    this.targetPosition.column + this.selection.endColumn - this.selection.startColumn :
                    this.selection.endColumn);
                return;
            }
            // The target position is at the same line as the selection's end position.
            if (this.selection.endColumn <= this.targetPosition.column) {
                // The target position is after the selection's end position
                this.targetSelection = new selection_1.Selection(this.targetPosition.lineNumber - this.selection.endLineNumber + this.selection.startLineNumber, this.selection.startLineNumber === this.selection.endLineNumber ?
                    this.targetPosition.column - this.selection.endColumn + this.selection.startColumn :
                    this.targetPosition.column - this.selection.endColumn + this.selection.startColumn, this.targetPosition.lineNumber, this.selection.startLineNumber === this.selection.endLineNumber ?
                    this.targetPosition.column :
                    this.selection.endColumn);
            }
            else {
                // The target position is before the selection's end position. Since the selection doesn't contain the target position, the selection is one-line and target position is before this selection.
                this.targetSelection = new selection_1.Selection(this.targetPosition.lineNumber - this.selection.endLineNumber + this.selection.startLineNumber, this.targetPosition.column, this.targetPosition.lineNumber, this.targetPosition.column + this.selection.endColumn - this.selection.startColumn);
            }
        }
        computeCursorState(model, helper) {
            return this.targetSelection;
        }
    }
    exports.DragAndDropCommand = DragAndDropCommand;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[611/*vs/editor/contrib/find/browser/replaceAllCommand*/], __M([1/*require*/,0/*exports*/,4/*vs/editor/common/core/range*/]), function (require, exports, range_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ReplaceAllCommand = void 0;
    class ReplaceAllCommand {
        constructor(editorSelection, ranges, replaceStrings) {
            this._editorSelection = editorSelection;
            this._ranges = ranges;
            this._replaceStrings = replaceStrings;
            this._trackedEditorSelectionId = null;
        }
        getEditOperations(model, builder) {
            if (this._ranges.length > 0) {
                // Collect all edit operations
                const ops = [];
                for (let i = 0; i < this._ranges.length; i++) {
                    ops.push({
                        range: this._ranges[i],
                        text: this._replaceStrings[i]
                    });
                }
                // Sort them in ascending order by range starts
                ops.sort((o1, o2) => {
                    return range_1.Range.compareRangesUsingStarts(o1.range, o2.range);
                });
                // Merge operations that touch each other
                const resultOps = [];
                let previousOp = ops[0];
                for (let i = 1; i < ops.length; i++) {
                    if (previousOp.range.endLineNumber === ops[i].range.startLineNumber && previousOp.range.endColumn === ops[i].range.startColumn) {
                        // These operations are one after another and can be merged
                        previousOp.range = previousOp.range.plusRange(ops[i].range);
                        previousOp.text = previousOp.text + ops[i].text;
                    }
                    else {
                        resultOps.push(previousOp);
                        previousOp = ops[i];
                    }
                }
                resultOps.push(previousOp);
                for (const op of resultOps) {
                    builder.addEditOperation(op.range, op.text);
                }
            }
            this._trackedEditorSelectionId = builder.trackSelection(this._editorSelection);
        }
        computeCursorState(model, helper) {
            return helper.getTrackedSelection(this._trackedEditorSelectionId);
        }
    }
    exports.ReplaceAllCommand = ReplaceAllCommand;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[612/*vs/editor/contrib/find/browser/replacePattern*/], __M([1/*require*/,0/*exports*/,455/*vs/base/common/search*/]), function (require, exports, search_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ReplacePiece = exports.ReplacePattern = void 0;
    exports.parseReplaceString = parseReplaceString;
    /**
     * Assigned when the replace pattern is entirely static.
     */
    class StaticValueReplacePattern {
        constructor(staticValue) {
            this.staticValue = staticValue;
            this.kind = 0 /* ReplacePatternKind.StaticValue */;
        }
    }
    /**
     * Assigned when the replace pattern has replacement patterns.
     */
    class DynamicPiecesReplacePattern {
        constructor(pieces) {
            this.pieces = pieces;
            this.kind = 1 /* ReplacePatternKind.DynamicPieces */;
        }
    }
    class ReplacePattern {
        static fromStaticValue(value) {
            return new ReplacePattern([ReplacePiece.staticValue(value)]);
        }
        get hasReplacementPatterns() {
            return (this._state.kind === 1 /* ReplacePatternKind.DynamicPieces */);
        }
        constructor(pieces) {
            if (!pieces || pieces.length === 0) {
                this._state = new StaticValueReplacePattern('');
            }
            else if (pieces.length === 1 && pieces[0].staticValue !== null) {
                this._state = new StaticValueReplacePattern(pieces[0].staticValue);
            }
            else {
                this._state = new DynamicPiecesReplacePattern(pieces);
            }
        }
        buildReplaceString(matches, preserveCase) {
            if (this._state.kind === 0 /* ReplacePatternKind.StaticValue */) {
                if (preserveCase) {
                    return (0, search_1.buildReplaceStringWithCasePreserved)(matches, this._state.staticValue);
                }
                else {
                    return this._state.staticValue;
                }
            }
            let result = '';
            for (let i = 0, len = this._state.pieces.length; i < len; i++) {
                const piece = this._state.pieces[i];
                if (piece.staticValue !== null) {
                    // static value ReplacePiece
                    result += piece.staticValue;
                    continue;
                }
                // match index ReplacePiece
                let match = ReplacePattern._substitute(piece.matchIndex, matches);
                if (piece.caseOps !== null && piece.caseOps.length > 0) {
                    const repl = [];
                    const lenOps = piece.caseOps.length;
                    let opIdx = 0;
                    for (let idx = 0, len = match.length; idx < len; idx++) {
                        if (opIdx >= lenOps) {
                            repl.push(match.slice(idx));
                            break;
                        }
                        switch (piece.caseOps[opIdx]) {
                            case 'U':
                                repl.push(match[idx].toUpperCase());
                                break;
                            case 'u':
                                repl.push(match[idx].toUpperCase());
                                opIdx++;
                                break;
                            case 'L':
                                repl.push(match[idx].toLowerCase());
                                break;
                            case 'l':
                                repl.push(match[idx].toLowerCase());
                                opIdx++;
                                break;
                            default:
                                repl.push(match[idx]);
                        }
                    }
                    match = repl.join('');
                }
                result += match;
            }
            return result;
        }
        static _substitute(matchIndex, matches) {
            if (matches === null) {
                return '';
            }
            if (matchIndex === 0) {
                return matches[0];
            }
            let remainder = '';
            while (matchIndex > 0) {
                if (matchIndex < matches.length) {
                    // A match can be undefined
                    const match = (matches[matchIndex] || '');
                    return match + remainder;
                }
                remainder = String(matchIndex % 10) + remainder;
                matchIndex = Math.floor(matchIndex / 10);
            }
            return '$' + remainder;
        }
    }
    exports.ReplacePattern = ReplacePattern;
    /**
     * A replace piece can either be a static string or an index to a specific match.
     */
    class ReplacePiece {
        static staticValue(value) {
            return new ReplacePiece(value, -1, null);
        }
        static caseOps(index, caseOps) {
            return new ReplacePiece(null, index, caseOps);
        }
        constructor(staticValue, matchIndex, caseOps) {
            this.staticValue = staticValue;
            this.matchIndex = matchIndex;
            if (!caseOps || caseOps.length === 0) {
                this.caseOps = null;
            }
            else {
                this.caseOps = caseOps.slice(0);
            }
        }
    }
    exports.ReplacePiece = ReplacePiece;
    class ReplacePieceBuilder {
        constructor(source) {
            this._source = source;
            this._lastCharIndex = 0;
            this._result = [];
            this._resultLen = 0;
            this._currentStaticPiece = '';
        }
        emitUnchanged(toCharIndex) {
            this._emitStatic(this._source.substring(this._lastCharIndex, toCharIndex));
            this._lastCharIndex = toCharIndex;
        }
        emitStatic(value, toCharIndex) {
            this._emitStatic(value);
            this._lastCharIndex = toCharIndex;
        }
        _emitStatic(value) {
            if (value.length === 0) {
                return;
            }
            this._currentStaticPiece += value;
        }
        emitMatchIndex(index, toCharIndex, caseOps) {
            if (this._currentStaticPiece.length !== 0) {
                this._result[this._resultLen++] = ReplacePiece.staticValue(this._currentStaticPiece);
                this._currentStaticPiece = '';
            }
            this._result[this._resultLen++] = ReplacePiece.caseOps(index, caseOps);
            this._lastCharIndex = toCharIndex;
        }
        finalize() {
            this.emitUnchanged(this._source.length);
            if (this._currentStaticPiece.length !== 0) {
                this._result[this._resultLen++] = ReplacePiece.staticValue(this._currentStaticPiece);
                this._currentStaticPiece = '';
            }
            return new ReplacePattern(this._result);
        }
    }
    /**
     * \n			=> inserts a LF
     * \t			=> inserts a TAB
     * \\			=> inserts a "\".
     * \u			=> upper-cases one character in a match.
     * \U			=> upper-cases ALL remaining characters in a match.
     * \l			=> lower-cases one character in a match.
     * \L			=> lower-cases ALL remaining characters in a match.
     * $$			=> inserts a "$".
     * $& and $0	=> inserts the matched substring.
     * $n			=> Where n is a non-negative integer lesser than 100, inserts the nth parenthesized submatch string
     * everything else stays untouched
     *
     * Also see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_string_as_a_parameter
     */
    function parseReplaceString(replaceString) {
        if (!replaceString || replaceString.length === 0) {
            return new ReplacePattern(null);
        }
        const caseOps = [];
        const result = new ReplacePieceBuilder(replaceString);
        for (let i = 0, len = replaceString.length; i < len; i++) {
            const chCode = replaceString.charCodeAt(i);
            if (chCode === 92 /* CharCode.Backslash */) {
                // move to next char
                i++;
                if (i >= len) {
                    // string ends with a \
                    break;
                }
                const nextChCode = replaceString.charCodeAt(i);
                // let replaceWithCharacter: string | null = null;
                switch (nextChCode) {
                    case 92 /* CharCode.Backslash */:
                        // \\ => inserts a "\"
                        result.emitUnchanged(i - 1);
                        result.emitStatic('\\', i + 1);
                        break;
                    case 110 /* CharCode.n */:
                        // \n => inserts a LF
                        result.emitUnchanged(i - 1);
                        result.emitStatic('\n', i + 1);
                        break;
                    case 116 /* CharCode.t */:
                        // \t => inserts a TAB
                        result.emitUnchanged(i - 1);
                        result.emitStatic('\t', i + 1);
                        break;
                    // Case modification of string replacements, patterned after Boost, but only applied
                    // to the replacement text, not subsequent content.
                    case 117 /* CharCode.u */:
                    // \u => upper-cases one character.
                    case 85 /* CharCode.U */:
                    // \U => upper-cases ALL following characters.
                    case 108 /* CharCode.l */:
                    // \l => lower-cases one character.
                    case 76 /* CharCode.L */:
                        // \L => lower-cases ALL following characters.
                        result.emitUnchanged(i - 1);
                        result.emitStatic('', i + 1);
                        caseOps.push(String.fromCharCode(nextChCode));
                        break;
                }
                continue;
            }
            if (chCode === 36 /* CharCode.DollarSign */) {
                // move to next char
                i++;
                if (i >= len) {
                    // string ends with a $
                    break;
                }
                const nextChCode = replaceString.charCodeAt(i);
                if (nextChCode === 36 /* CharCode.DollarSign */) {
                    // $$ => inserts a "$"
                    result.emitUnchanged(i - 1);
                    result.emitStatic('$', i + 1);
                    continue;
                }
                if (nextChCode === 48 /* CharCode.Digit0 */ || nextChCode === 38 /* CharCode.Ampersand */) {
                    // $& and $0 => inserts the matched substring.
                    result.emitUnchanged(i - 1);
                    result.emitMatchIndex(0, i + 1, caseOps);
                    caseOps.length = 0;
                    continue;
                }
                if (49 /* CharCode.Digit1 */ <= nextChCode && nextChCode <= 57 /* CharCode.Digit9 */) {
                    // $n
                    let matchIndex = nextChCode - 48 /* CharCode.Digit0 */;
                    // peek next char to probe for $nn
                    if (i + 1 < len) {
                        const nextNextChCode = replaceString.charCodeAt(i + 1);
                        if (48 /* CharCode.Digit0 */ <= nextNextChCode && nextNextChCode <= 57 /* CharCode.Digit9 */) {
                            // $nn
                            // move to next char
                            i++;
                            matchIndex = matchIndex * 10 + (nextNextChCode - 48 /* CharCode.Digit0 */);
                            result.emitUnchanged(i - 2);
                            result.emitMatchIndex(matchIndex, i + 1, caseOps);
                            caseOps.length = 0;
                            continue;
                        }
                    }
                    result.emitUnchanged(i - 1);
                    result.emitMatchIndex(matchIndex, i + 1, caseOps);
                    caseOps.length = 0;
                    continue;
                }
            }
        }
        return result.finalize();
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[203/*vs/editor/contrib/folding/browser/foldingRanges*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.FoldingRegion = exports.FoldingRegions = exports.MAX_LINE_NUMBER = exports.MAX_FOLDING_REGIONS = exports.foldSourceAbbr = void 0;
    exports.foldSourceAbbr = {
        [0 /* FoldSource.provider */]: ' ',
        [1 /* FoldSource.userDefined */]: 'u',
        [2 /* FoldSource.recovered */]: 'r',
    };
    exports.MAX_FOLDING_REGIONS = 0xFFFF;
    exports.MAX_LINE_NUMBER = 0xFFFFFF;
    const MASK_INDENT = 0xFF000000;
    class BitField {
        constructor(size) {
            const numWords = Math.ceil(size / 32);
            this._states = new Uint32Array(numWords);
        }
        get(index) {
            const arrayIndex = (index / 32) | 0;
            const bit = index % 32;
            return (this._states[arrayIndex] & (1 << bit)) !== 0;
        }
        set(index, newState) {
            const arrayIndex = (index / 32) | 0;
            const bit = index % 32;
            const value = this._states[arrayIndex];
            if (newState) {
                this._states[arrayIndex] = value | (1 << bit);
            }
            else {
                this._states[arrayIndex] = value & ~(1 << bit);
            }
        }
    }
    class FoldingRegions {
        constructor(startIndexes, endIndexes, types) {
            if (startIndexes.length !== endIndexes.length || startIndexes.length > exports.MAX_FOLDING_REGIONS) {
                throw new Error('invalid startIndexes or endIndexes size');
            }
            this._startIndexes = startIndexes;
            this._endIndexes = endIndexes;
            this._collapseStates = new BitField(startIndexes.length);
            this._userDefinedStates = new BitField(startIndexes.length);
            this._recoveredStates = new BitField(startIndexes.length);
            this._types = types;
            this._parentsComputed = false;
        }
        ensureParentIndices() {
            if (!this._parentsComputed) {
                this._parentsComputed = true;
                const parentIndexes = [];
                const isInsideLast = (startLineNumber, endLineNumber) => {
                    const index = parentIndexes[parentIndexes.length - 1];
                    return this.getStartLineNumber(index) <= startLineNumber && this.getEndLineNumber(index) >= endLineNumber;
                };
                for (let i = 0, len = this._startIndexes.length; i < len; i++) {
                    const startLineNumber = this._startIndexes[i];
                    const endLineNumber = this._endIndexes[i];
                    if (startLineNumber > exports.MAX_LINE_NUMBER || endLineNumber > exports.MAX_LINE_NUMBER) {
                        throw new Error('startLineNumber or endLineNumber must not exceed ' + exports.MAX_LINE_NUMBER);
                    }
                    while (parentIndexes.length > 0 && !isInsideLast(startLineNumber, endLineNumber)) {
                        parentIndexes.pop();
                    }
                    const parentIndex = parentIndexes.length > 0 ? parentIndexes[parentIndexes.length - 1] : -1;
                    parentIndexes.push(i);
                    this._startIndexes[i] = startLineNumber + ((parentIndex & 0xFF) << 24);
                    this._endIndexes[i] = endLineNumber + ((parentIndex & 0xFF00) << 16);
                }
            }
        }
        get length() {
            return this._startIndexes.length;
        }
        getStartLineNumber(index) {
            return this._startIndexes[index] & exports.MAX_LINE_NUMBER;
        }
        getEndLineNumber(index) {
            return this._endIndexes[index] & exports.MAX_LINE_NUMBER;
        }
        getType(index) {
            return this._types ? this._types[index] : undefined;
        }
        hasTypes() {
            return !!this._types;
        }
        isCollapsed(index) {
            return this._collapseStates.get(index);
        }
        setCollapsed(index, newState) {
            this._collapseStates.set(index, newState);
        }
        isUserDefined(index) {
            return this._userDefinedStates.get(index);
        }
        setUserDefined(index, newState) {
            return this._userDefinedStates.set(index, newState);
        }
        isRecovered(index) {
            return this._recoveredStates.get(index);
        }
        setRecovered(index, newState) {
            return this._recoveredStates.set(index, newState);
        }
        getSource(index) {
            if (this.isUserDefined(index)) {
                return 1 /* FoldSource.userDefined */;
            }
            else if (this.isRecovered(index)) {
                return 2 /* FoldSource.recovered */;
            }
            return 0 /* FoldSource.provider */;
        }
        setSource(index, source) {
            if (source === 1 /* FoldSource.userDefined */) {
                this.setUserDefined(index, true);
                this.setRecovered(index, false);
            }
            else if (source === 2 /* FoldSource.recovered */) {
                this.setUserDefined(index, false);
                this.setRecovered(index, true);
            }
            else {
                this.setUserDefined(index, false);
                this.setRecovered(index, false);
            }
        }
        setCollapsedAllOfType(type, newState) {
            let hasChanged = false;
            if (this._types) {
                for (let i = 0; i < this._types.length; i++) {
                    if (this._types[i] === type) {
                        this.setCollapsed(i, newState);
                        hasChanged = true;
                    }
                }
            }
            return hasChanged;
        }
        toRegion(index) {
            return new FoldingRegion(this, index);
        }
        getParentIndex(index) {
            this.ensureParentIndices();
            const parent = ((this._startIndexes[index] & MASK_INDENT) >>> 24) + ((this._endIndexes[index] & MASK_INDENT) >>> 16);
            if (parent === exports.MAX_FOLDING_REGIONS) {
                return -1;
            }
            return parent;
        }
        contains(index, line) {
            return this.getStartLineNumber(index) <= line && this.getEndLineNumber(index) >= line;
        }
        findIndex(line) {
            let low = 0, high = this._startIndexes.length;
            if (high === 0) {
                return -1; // no children
            }
            while (low < high) {
                const mid = Math.floor((low + high) / 2);
                if (line < this.getStartLineNumber(mid)) {
                    high = mid;
                }
                else {
                    low = mid + 1;
                }
            }
            return low - 1;
        }
        findRange(line) {
            let index = this.findIndex(line);
            if (index >= 0) {
                const endLineNumber = this.getEndLineNumber(index);
                if (endLineNumber >= line) {
                    return index;
                }
                index = this.getParentIndex(index);
                while (index !== -1) {
                    if (this.contains(index, line)) {
                        return index;
                    }
                    index = this.getParentIndex(index);
                }
            }
            return -1;
        }
        toString() {
            const res = [];
            for (let i = 0; i < this.length; i++) {
                res[i] = `[${exports.foldSourceAbbr[this.getSource(i)]}${this.isCollapsed(i) ? '+' : '-'}] ${this.getStartLineNumber(i)}/${this.getEndLineNumber(i)}`;
            }
            return res.join(', ');
        }
        toFoldRange(index) {
            return {
                startLineNumber: this._startIndexes[index] & exports.MAX_LINE_NUMBER,
                endLineNumber: this._endIndexes[index] & exports.MAX_LINE_NUMBER,
                type: this._types ? this._types[index] : undefined,
                isCollapsed: this.isCollapsed(index),
                source: this.getSource(index)
            };
        }
        static fromFoldRanges(ranges) {
            const rangesLength = ranges.length;
            const startIndexes = new Uint32Array(rangesLength);
            const endIndexes = new Uint32Array(rangesLength);
            let types = [];
            let gotTypes = false;
            for (let i = 0; i < rangesLength; i++) {
                const range = ranges[i];
                startIndexes[i] = range.startLineNumber;
                endIndexes[i] = range.endLineNumber;
                types.push(range.type);
                if (range.type) {
                    gotTypes = true;
                }
            }
            if (!gotTypes) {
                types = undefined;
            }
            const regions = new FoldingRegions(startIndexes, endIndexes, types);
            for (let i = 0; i < rangesLength; i++) {
                if (ranges[i].isCollapsed) {
                    regions.setCollapsed(i, true);
                }
                regions.setSource(i, ranges[i].source);
            }
            return regions;
        }
        /**
         * Two inputs, each a FoldingRegions or a FoldRange[], are merged.
         * Each input must be pre-sorted on startLineNumber.
         * The first list is assumed to always include all regions currently defined by range providers.
         * The second list only contains the previously collapsed and all manual ranges.
         * If the line position matches, the range of the new range is taken, and the range is no longer manual
         * When an entry in one list overlaps an entry in the other, the second list's entry "wins" and
         * overlapping entries in the first list are discarded.
         * Invalid entries are discarded. An entry is invalid if:
         * 		the start and end line numbers aren't a valid range of line numbers,
         * 		it is out of sequence or has the same start line as a preceding entry,
         * 		it overlaps a preceding entry and is not fully contained by that entry.
         */
        static sanitizeAndMerge(rangesA, rangesB, maxLineNumber, selection) {
            maxLineNumber = maxLineNumber ?? Number.MAX_VALUE;
            const getIndexedFunction = (r, limit) => {
                return Array.isArray(r)
                    ? ((i) => { return (i < limit) ? r[i] : undefined; })
                    : ((i) => { return (i < limit) ? r.toFoldRange(i) : undefined; });
            };
            const getA = getIndexedFunction(rangesA, rangesA.length);
            const getB = getIndexedFunction(rangesB, rangesB.length);
            let indexA = 0;
            let indexB = 0;
            let nextA = getA(0);
            let nextB = getB(0);
            const stackedRanges = [];
            let topStackedRange;
            let prevLineNumber = 0;
            const resultRanges = [];
            while (nextA || nextB) {
                let useRange = undefined;
                if (nextB && (!nextA || nextA.startLineNumber >= nextB.startLineNumber)) {
                    if (nextA && nextA.startLineNumber === nextB.startLineNumber) {
                        if (nextB.source === 1 /* FoldSource.userDefined */) {
                            // a user defined range (possibly unfolded)
                            useRange = nextB;
                        }
                        else {
                            // a previously folded range or a (possibly unfolded) recovered range
                            useRange = nextA;
                            // stays collapsed if the range still has the same number of lines or the selection is not in the range or after it
                            useRange.isCollapsed = nextB.isCollapsed && (nextA.endLineNumber === nextB.endLineNumber || !selection?.startsInside(nextA.startLineNumber + 1, nextA.endLineNumber + 1));
                            useRange.source = 0 /* FoldSource.provider */;
                        }
                        nextA = getA(++indexA); // not necessary, just for speed
                    }
                    else {
                        useRange = nextB;
                        if (nextB.isCollapsed && nextB.source === 0 /* FoldSource.provider */) {
                            // a previously collapsed range
                            useRange.source = 2 /* FoldSource.recovered */;
                        }
                    }
                    nextB = getB(++indexB);
                }
                else {
                    // nextA is next. The user folded B set takes precedence and we sometimes need to look
                    // ahead in it to check for an upcoming conflict.
                    let scanIndex = indexB;
                    let prescanB = nextB;
                    while (true) {
                        if (!prescanB || prescanB.startLineNumber > nextA.endLineNumber) {
                            useRange = nextA;
                            break; // no conflict, use this nextA
                        }
                        if (prescanB.source === 1 /* FoldSource.userDefined */ && prescanB.endLineNumber > nextA.endLineNumber) {
                            // we found a user folded range, it wins
                            break; // without setting nextResult, so this nextA gets skipped
                        }
                        prescanB = getB(++scanIndex);
                    }
                    nextA = getA(++indexA);
                }
                if (useRange) {
                    while (topStackedRange
                        && topStackedRange.endLineNumber < useRange.startLineNumber) {
                        topStackedRange = stackedRanges.pop();
                    }
                    if (useRange.endLineNumber > useRange.startLineNumber
                        && useRange.startLineNumber > prevLineNumber
                        && useRange.endLineNumber <= maxLineNumber
                        && (!topStackedRange
                            || topStackedRange.endLineNumber >= useRange.endLineNumber)) {
                        resultRanges.push(useRange);
                        prevLineNumber = useRange.startLineNumber;
                        if (topStackedRange) {
                            stackedRanges.push(topStackedRange);
                        }
                        topStackedRange = useRange;
                    }
                }
            }
            return resultRanges;
        }
    }
    exports.FoldingRegions = FoldingRegions;
    class FoldingRegion {
        constructor(ranges, index) {
            this.ranges = ranges;
            this.index = index;
        }
        get startLineNumber() {
            return this.ranges.getStartLineNumber(this.index);
        }
        get endLineNumber() {
            return this.ranges.getEndLineNumber(this.index);
        }
        get regionIndex() {
            return this.index;
        }
        get parentIndex() {
            return this.ranges.getParentIndex(this.index);
        }
        get isCollapsed() {
            return this.ranges.isCollapsed(this.index);
        }
        containedBy(range) {
            return range.startLineNumber <= this.startLineNumber && range.endLineNumber >= this.endLineNumber;
        }
        containsLine(lineNumber) {
            return this.startLineNumber <= lineNumber && lineNumber <= this.endLineNumber;
        }
    }
    exports.FoldingRegion = FoldingRegion;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[334/*vs/editor/contrib/folding/browser/foldingModel*/], __M([1/*require*/,0/*exports*/,6/*vs/base/common/event*/,203/*vs/editor/contrib/folding/browser/foldingRanges*/,129/*vs/base/common/hash*/]), function (require, exports, event_1, foldingRanges_1, hash_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.FoldingModel = void 0;
    exports.toggleCollapseState = toggleCollapseState;
    exports.setCollapseStateLevelsDown = setCollapseStateLevelsDown;
    exports.setCollapseStateLevelsUp = setCollapseStateLevelsUp;
    exports.setCollapseStateUp = setCollapseStateUp;
    exports.setCollapseStateAtLevel = setCollapseStateAtLevel;
    exports.setCollapseStateForRest = setCollapseStateForRest;
    exports.setCollapseStateForMatchingLines = setCollapseStateForMatchingLines;
    exports.setCollapseStateForType = setCollapseStateForType;
    exports.getParentFoldLine = getParentFoldLine;
    exports.getPreviousFoldLine = getPreviousFoldLine;
    exports.getNextFoldLine = getNextFoldLine;
    class FoldingModel {
        get regions() { return this._regions; }
        get textModel() { return this._textModel; }
        constructor(textModel, decorationProvider) {
            this._updateEventEmitter = new event_1.Emitter();
            this.onDidChange = this._updateEventEmitter.event;
            this._textModel = textModel;
            this._decorationProvider = decorationProvider;
            this._regions = new foldingRanges_1.FoldingRegions(new Uint32Array(0), new Uint32Array(0));
            this._editorDecorationIds = [];
        }
        toggleCollapseState(toggledRegions) {
            if (!toggledRegions.length) {
                return;
            }
            toggledRegions = toggledRegions.sort((r1, r2) => r1.regionIndex - r2.regionIndex);
            const processed = {};
            this._decorationProvider.changeDecorations(accessor => {
                let k = 0; // index from [0 ... this.regions.length]
                let dirtyRegionEndLine = -1; // end of the range where decorations need to be updated
                let lastHiddenLine = -1; // the end of the last hidden lines
                const updateDecorationsUntil = (index) => {
                    while (k < index) {
                        const endLineNumber = this._regions.getEndLineNumber(k);
                        const isCollapsed = this._regions.isCollapsed(k);
                        if (endLineNumber <= dirtyRegionEndLine) {
                            const isManual = this.regions.getSource(k) !== 0 /* FoldSource.provider */;
                            accessor.changeDecorationOptions(this._editorDecorationIds[k], this._decorationProvider.getDecorationOption(isCollapsed, endLineNumber <= lastHiddenLine, isManual));
                        }
                        if (isCollapsed && endLineNumber > lastHiddenLine) {
                            lastHiddenLine = endLineNumber;
                        }
                        k++;
                    }
                };
                for (const region of toggledRegions) {
                    const index = region.regionIndex;
                    const editorDecorationId = this._editorDecorationIds[index];
                    if (editorDecorationId && !processed[editorDecorationId]) {
                        processed[editorDecorationId] = true;
                        updateDecorationsUntil(index); // update all decorations up to current index using the old dirtyRegionEndLine
                        const newCollapseState = !this._regions.isCollapsed(index);
                        this._regions.setCollapsed(index, newCollapseState);
                        dirtyRegionEndLine = Math.max(dirtyRegionEndLine, this._regions.getEndLineNumber(index));
                    }
                }
                updateDecorationsUntil(this._regions.length);
            });
            this._updateEventEmitter.fire({ model: this, collapseStateChanged: toggledRegions });
        }
        removeManualRanges(ranges) {
            const newFoldingRanges = new Array();
            const intersects = (foldRange) => {
                for (const range of ranges) {
                    if (!(range.startLineNumber > foldRange.endLineNumber || foldRange.startLineNumber > range.endLineNumber)) {
                        return true;
                    }
                }
                return false;
            };
            for (let i = 0; i < this._regions.length; i++) {
                const foldRange = this._regions.toFoldRange(i);
                if (foldRange.source === 0 /* FoldSource.provider */ || !intersects(foldRange)) {
                    newFoldingRanges.push(foldRange);
                }
            }
            this.updatePost(foldingRanges_1.FoldingRegions.fromFoldRanges(newFoldingRanges));
        }
        update(newRegions, selection) {
            const foldedOrManualRanges = this._currentFoldedOrManualRanges(selection);
            const newRanges = foldingRanges_1.FoldingRegions.sanitizeAndMerge(newRegions, foldedOrManualRanges, this._textModel.getLineCount(), selection);
            this.updatePost(foldingRanges_1.FoldingRegions.fromFoldRanges(newRanges));
        }
        updatePost(newRegions) {
            const newEditorDecorations = [];
            let lastHiddenLine = -1;
            for (let index = 0, limit = newRegions.length; index < limit; index++) {
                const startLineNumber = newRegions.getStartLineNumber(index);
                const endLineNumber = newRegions.getEndLineNumber(index);
                const isCollapsed = newRegions.isCollapsed(index);
                const isManual = newRegions.getSource(index) !== 0 /* FoldSource.provider */;
                const decorationRange = {
                    startLineNumber: startLineNumber,
                    startColumn: this._textModel.getLineMaxColumn(startLineNumber),
                    endLineNumber: endLineNumber,
                    endColumn: this._textModel.getLineMaxColumn(endLineNumber) + 1
                };
                newEditorDecorations.push({ range: decorationRange, options: this._decorationProvider.getDecorationOption(isCollapsed, endLineNumber <= lastHiddenLine, isManual) });
                if (isCollapsed && endLineNumber > lastHiddenLine) {
                    lastHiddenLine = endLineNumber;
                }
            }
            this._decorationProvider.changeDecorations(accessor => this._editorDecorationIds = accessor.deltaDecorations(this._editorDecorationIds, newEditorDecorations));
            this._regions = newRegions;
            this._updateEventEmitter.fire({ model: this });
        }
        _currentFoldedOrManualRanges(selection) {
            const foldedRanges = [];
            for (let i = 0, limit = this._regions.length; i < limit; i++) {
                let isCollapsed = this.regions.isCollapsed(i);
                const source = this.regions.getSource(i);
                if (isCollapsed || source !== 0 /* FoldSource.provider */) {
                    const foldRange = this._regions.toFoldRange(i);
                    const decRange = this._textModel.getDecorationRange(this._editorDecorationIds[i]);
                    if (decRange) {
                        if (isCollapsed && selection?.startsInside(decRange.startLineNumber + 1, decRange.endLineNumber)) {
                            isCollapsed = false; // uncollapse is the range is blocked
                        }
                        foldedRanges.push({
                            startLineNumber: decRange.startLineNumber,
                            endLineNumber: decRange.endLineNumber,
                            type: foldRange.type,
                            isCollapsed,
                            source
                        });
                    }
                }
            }
            return foldedRanges;
        }
        /**
         * Collapse state memento, for persistence only
         */
        getMemento() {
            const foldedOrManualRanges = this._currentFoldedOrManualRanges();
            const result = [];
            const maxLineNumber = this._textModel.getLineCount();
            for (let i = 0, limit = foldedOrManualRanges.length; i < limit; i++) {
                const range = foldedOrManualRanges[i];
                if (range.startLineNumber >= range.endLineNumber || range.startLineNumber < 1 || range.endLineNumber > maxLineNumber) {
                    continue;
                }
                const checksum = this._getLinesChecksum(range.startLineNumber + 1, range.endLineNumber);
                result.push({
                    startLineNumber: range.startLineNumber,
                    endLineNumber: range.endLineNumber,
                    isCollapsed: range.isCollapsed,
                    source: range.source,
                    checksum: checksum
                });
            }
            return (result.length > 0) ? result : undefined;
        }
        /**
         * Apply persisted state, for persistence only
         */
        applyMemento(state) {
            if (!Array.isArray(state)) {
                return;
            }
            const rangesToRestore = [];
            const maxLineNumber = this._textModel.getLineCount();
            for (const range of state) {
                if (range.startLineNumber >= range.endLineNumber || range.startLineNumber < 1 || range.endLineNumber > maxLineNumber) {
                    continue;
                }
                const checksum = this._getLinesChecksum(range.startLineNumber + 1, range.endLineNumber);
                if (!range.checksum || checksum === range.checksum) {
                    rangesToRestore.push({
                        startLineNumber: range.startLineNumber,
                        endLineNumber: range.endLineNumber,
                        type: undefined,
                        isCollapsed: range.isCollapsed ?? true,
                        source: range.source ?? 0 /* FoldSource.provider */
                    });
                }
            }
            const newRanges = foldingRanges_1.FoldingRegions.sanitizeAndMerge(this._regions, rangesToRestore, maxLineNumber);
            this.updatePost(foldingRanges_1.FoldingRegions.fromFoldRanges(newRanges));
        }
        _getLinesChecksum(lineNumber1, lineNumber2) {
            const h = (0, hash_1.hash)(this._textModel.getLineContent(lineNumber1)
                + this._textModel.getLineContent(lineNumber2));
            return h % 1000000; // 6 digits is plenty
        }
        dispose() {
            this._decorationProvider.removeDecorations(this._editorDecorationIds);
        }
        getAllRegionsAtLine(lineNumber, filter) {
            const result = [];
            if (this._regions) {
                let index = this._regions.findRange(lineNumber);
                let level = 1;
                while (index >= 0) {
                    const current = this._regions.toRegion(index);
                    if (!filter || filter(current, level)) {
                        result.push(current);
                    }
                    level++;
                    index = current.parentIndex;
                }
            }
            return result;
        }
        getRegionAtLine(lineNumber) {
            if (this._regions) {
                const index = this._regions.findRange(lineNumber);
                if (index >= 0) {
                    return this._regions.toRegion(index);
                }
            }
            return null;
        }
        getRegionsInside(region, filter) {
            const result = [];
            const index = region ? region.regionIndex + 1 : 0;
            const endLineNumber = region ? region.endLineNumber : Number.MAX_VALUE;
            if (filter && filter.length === 2) {
                const levelStack = [];
                for (let i = index, len = this._regions.length; i < len; i++) {
                    const current = this._regions.toRegion(i);
                    if (this._regions.getStartLineNumber(i) < endLineNumber) {
                        while (levelStack.length > 0 && !current.containedBy(levelStack[levelStack.length - 1])) {
                            levelStack.pop();
                        }
                        levelStack.push(current);
                        if (filter(current, levelStack.length)) {
                            result.push(current);
                        }
                    }
                    else {
                        break;
                    }
                }
            }
            else {
                for (let i = index, len = this._regions.length; i < len; i++) {
                    const current = this._regions.toRegion(i);
                    if (this._regions.getStartLineNumber(i) < endLineNumber) {
                        if (!filter || filter(current)) {
                            result.push(current);
                        }
                    }
                    else {
                        break;
                    }
                }
            }
            return result;
        }
    }
    exports.FoldingModel = FoldingModel;
    /**
     * Collapse or expand the regions at the given locations
     * @param levels The number of levels. Use 1 to only impact the regions at the location, use Number.MAX_VALUE for all levels.
     * @param lineNumbers the location of the regions to collapse or expand, or if not set, all regions in the model.
     */
    function toggleCollapseState(foldingModel, levels, lineNumbers) {
        const toToggle = [];
        for (const lineNumber of lineNumbers) {
            const region = foldingModel.getRegionAtLine(lineNumber);
            if (region) {
                const doCollapse = !region.isCollapsed;
                toToggle.push(region);
                if (levels > 1) {
                    const regionsInside = foldingModel.getRegionsInside(region, (r, level) => r.isCollapsed !== doCollapse && level < levels);
                    toToggle.push(...regionsInside);
                }
            }
        }
        foldingModel.toggleCollapseState(toToggle);
    }
    /**
     * Collapse or expand the regions at the given locations including all children.
     * @param doCollapse Whether to collapse or expand
     * @param levels The number of levels. Use 1 to only impact the regions at the location, use Number.MAX_VALUE for all levels.
     * @param lineNumbers the location of the regions to collapse or expand, or if not set, all regions in the model.
     */
    function setCollapseStateLevelsDown(foldingModel, doCollapse, levels = Number.MAX_VALUE, lineNumbers) {
        const toToggle = [];
        if (lineNumbers && lineNumbers.length > 0) {
            for (const lineNumber of lineNumbers) {
                const region = foldingModel.getRegionAtLine(lineNumber);
                if (region) {
                    if (region.isCollapsed !== doCollapse) {
                        toToggle.push(region);
                    }
                    if (levels > 1) {
                        const regionsInside = foldingModel.getRegionsInside(region, (r, level) => r.isCollapsed !== doCollapse && level < levels);
                        toToggle.push(...regionsInside);
                    }
                }
            }
        }
        else {
            const regionsInside = foldingModel.getRegionsInside(null, (r, level) => r.isCollapsed !== doCollapse && level < levels);
            toToggle.push(...regionsInside);
        }
        foldingModel.toggleCollapseState(toToggle);
    }
    /**
     * Collapse or expand the regions at the given locations including all parents.
     * @param doCollapse Whether to collapse or expand
     * @param levels The number of levels. Use 1 to only impact the regions at the location, use Number.MAX_VALUE for all levels.
     * @param lineNumbers the location of the regions to collapse or expand.
     */
    function setCollapseStateLevelsUp(foldingModel, doCollapse, levels, lineNumbers) {
        const toToggle = [];
        for (const lineNumber of lineNumbers) {
            const regions = foldingModel.getAllRegionsAtLine(lineNumber, (region, level) => region.isCollapsed !== doCollapse && level <= levels);
            toToggle.push(...regions);
        }
        foldingModel.toggleCollapseState(toToggle);
    }
    /**
     * Collapse or expand a region at the given locations. If the inner most region is already collapsed/expanded, uses the first parent instead.
     * @param doCollapse Whether to collapse or expand
     * @param lineNumbers the location of the regions to collapse or expand.
     */
    function setCollapseStateUp(foldingModel, doCollapse, lineNumbers) {
        const toToggle = [];
        for (const lineNumber of lineNumbers) {
            const regions = foldingModel.getAllRegionsAtLine(lineNumber, (region) => region.isCollapsed !== doCollapse);
            if (regions.length > 0) {
                toToggle.push(regions[0]);
            }
        }
        foldingModel.toggleCollapseState(toToggle);
    }
    /**
     * Folds or unfolds all regions that have a given level, except if they contain one of the blocked lines.
     * @param foldLevel level. Level == 1 is the top level
     * @param doCollapse Whether to collapse or expand
    */
    function setCollapseStateAtLevel(foldingModel, foldLevel, doCollapse, blockedLineNumbers) {
        const filter = (region, level) => level === foldLevel && region.isCollapsed !== doCollapse && !blockedLineNumbers.some(line => region.containsLine(line));
        const toToggle = foldingModel.getRegionsInside(null, filter);
        foldingModel.toggleCollapseState(toToggle);
    }
    /**
     * Folds or unfolds all regions, except if they contain or are contained by a region of one of the blocked lines.
     * @param doCollapse Whether to collapse or expand
     * @param blockedLineNumbers the location of regions to not collapse or expand
     */
    function setCollapseStateForRest(foldingModel, doCollapse, blockedLineNumbers) {
        const filteredRegions = [];
        for (const lineNumber of blockedLineNumbers) {
            const regions = foldingModel.getAllRegionsAtLine(lineNumber, undefined);
            if (regions.length > 0) {
                filteredRegions.push(regions[0]);
            }
        }
        const filter = (region) => filteredRegions.every((filteredRegion) => !filteredRegion.containedBy(region) && !region.containedBy(filteredRegion)) && region.isCollapsed !== doCollapse;
        const toToggle = foldingModel.getRegionsInside(null, filter);
        foldingModel.toggleCollapseState(toToggle);
    }
    /**
     * Folds all regions for which the lines start with a given regex
     * @param foldingModel the folding model
     */
    function setCollapseStateForMatchingLines(foldingModel, regExp, doCollapse) {
        const editorModel = foldingModel.textModel;
        const regions = foldingModel.regions;
        const toToggle = [];
        for (let i = regions.length - 1; i >= 0; i--) {
            if (doCollapse !== regions.isCollapsed(i)) {
                const startLineNumber = regions.getStartLineNumber(i);
                if (regExp.test(editorModel.getLineContent(startLineNumber))) {
                    toToggle.push(regions.toRegion(i));
                }
            }
        }
        foldingModel.toggleCollapseState(toToggle);
    }
    /**
     * Folds all regions of the given type
     * @param foldingModel the folding model
     */
    function setCollapseStateForType(foldingModel, type, doCollapse) {
        const regions = foldingModel.regions;
        const toToggle = [];
        for (let i = regions.length - 1; i >= 0; i--) {
            if (doCollapse !== regions.isCollapsed(i) && type === regions.getType(i)) {
                toToggle.push(regions.toRegion(i));
            }
        }
        foldingModel.toggleCollapseState(toToggle);
    }
    /**
     * Get line to go to for parent fold of current line
     * @param lineNumber the current line number
     * @param foldingModel the folding model
     *
     * @return Parent fold start line
     */
    function getParentFoldLine(lineNumber, foldingModel) {
        let startLineNumber = null;
        const foldingRegion = foldingModel.getRegionAtLine(lineNumber);
        if (foldingRegion !== null) {
            startLineNumber = foldingRegion.startLineNumber;
            // If current line is not the start of the current fold, go to top line of current fold. If not, go to parent fold
            if (lineNumber === startLineNumber) {
                const parentFoldingIdx = foldingRegion.parentIndex;
                if (parentFoldingIdx !== -1) {
                    startLineNumber = foldingModel.regions.getStartLineNumber(parentFoldingIdx);
                }
                else {
                    startLineNumber = null;
                }
            }
        }
        return startLineNumber;
    }
    /**
     * Get line to go to for previous fold at the same level of current line
     * @param lineNumber the current line number
     * @param foldingModel the folding model
     *
     * @return Previous fold start line
     */
    function getPreviousFoldLine(lineNumber, foldingModel) {
        let foldingRegion = foldingModel.getRegionAtLine(lineNumber);
        // If on the folding range start line, go to previous sibling.
        if (foldingRegion !== null && foldingRegion.startLineNumber === lineNumber) {
            // If current line is not the start of the current fold, go to top line of current fold. If not, go to previous fold.
            if (lineNumber !== foldingRegion.startLineNumber) {
                return foldingRegion.startLineNumber;
            }
            else {
                // Find min line number to stay within parent.
                const expectedParentIndex = foldingRegion.parentIndex;
                let minLineNumber = 0;
                if (expectedParentIndex !== -1) {
                    minLineNumber = foldingModel.regions.getStartLineNumber(foldingRegion.parentIndex);
                }
                // Find fold at same level.
                while (foldingRegion !== null) {
                    if (foldingRegion.regionIndex > 0) {
                        foldingRegion = foldingModel.regions.toRegion(foldingRegion.regionIndex - 1);
                        // Keep at same level.
                        if (foldingRegion.startLineNumber <= minLineNumber) {
                            return null;
                        }
                        else if (foldingRegion.parentIndex === expectedParentIndex) {
                            return foldingRegion.startLineNumber;
                        }
                    }
                    else {
                        return null;
                    }
                }
            }
        }
        else {
            // Go to last fold that's before the current line.
            if (foldingModel.regions.length > 0) {
                foldingRegion = foldingModel.regions.toRegion(foldingModel.regions.length - 1);
                while (foldingRegion !== null) {
                    // Found fold before current line.
                    if (foldingRegion.startLineNumber < lineNumber) {
                        return foldingRegion.startLineNumber;
                    }
                    if (foldingRegion.regionIndex > 0) {
                        foldingRegion = foldingModel.regions.toRegion(foldingRegion.regionIndex - 1);
                    }
                    else {
                        foldingRegion = null;
                    }
                }
            }
        }
        return null;
    }
    /**
     * Get line to go to next fold at the same level of current line
     * @param lineNumber the current line number
     * @param foldingModel the folding model
     *
     * @return Next fold start line
     */
    function getNextFoldLine(lineNumber, foldingModel) {
        let foldingRegion = foldingModel.getRegionAtLine(lineNumber);
        // If on the folding range start line, go to next sibling.
        if (foldingRegion !== null && foldingRegion.startLineNumber === lineNumber) {
            // Find max line number to stay within parent.
            const expectedParentIndex = foldingRegion.parentIndex;
            let maxLineNumber = 0;
            if (expectedParentIndex !== -1) {
                maxLineNumber = foldingModel.regions.getEndLineNumber(foldingRegion.parentIndex);
            }
            else if (foldingModel.regions.length === 0) {
                return null;
            }
            else {
                maxLineNumber = foldingModel.regions.getEndLineNumber(foldingModel.regions.length - 1);
            }
            // Find fold at same level.
            while (foldingRegion !== null) {
                if (foldingRegion.regionIndex < foldingModel.regions.length) {
                    foldingRegion = foldingModel.regions.toRegion(foldingRegion.regionIndex + 1);
                    // Keep at same level.
                    if (foldingRegion.startLineNumber >= maxLineNumber) {
                        return null;
                    }
                    else if (foldingRegion.parentIndex === expectedParentIndex) {
                        return foldingRegion.startLineNumber;
                    }
                }
                else {
                    return null;
                }
            }
        }
        else {
            // Go to first fold that's after the current line.
            if (foldingModel.regions.length > 0) {
                foldingRegion = foldingModel.regions.toRegion(0);
                while (foldingRegion !== null) {
                    // Found fold after current line.
                    if (foldingRegion.startLineNumber > lineNumber) {
                        return foldingRegion.startLineNumber;
                    }
                    if (foldingRegion.regionIndex < foldingModel.regions.length) {
                        foldingRegion = foldingModel.regions.toRegion(foldingRegion.regionIndex + 1);
                    }
                    else {
                        foldingRegion = null;
                    }
                }
            }
        }
        return null;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[613/*vs/editor/contrib/folding/browser/hiddenRangeModel*/], __M([1/*require*/,0/*exports*/,67/*vs/base/common/arraysFind*/,6/*vs/base/common/event*/,4/*vs/editor/common/core/range*/,145/*vs/editor/common/core/eolCounter*/]), function (require, exports, arraysFind_1, event_1, range_1, eolCounter_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.HiddenRangeModel = void 0;
    class HiddenRangeModel {
        get onDidChange() { return this._updateEventEmitter.event; }
        get hiddenRanges() { return this._hiddenRanges; }
        constructor(model) {
            this._updateEventEmitter = new event_1.Emitter();
            this._hasLineChanges = false;
            this._foldingModel = model;
            this._foldingModelListener = model.onDidChange(_ => this.updateHiddenRanges());
            this._hiddenRanges = [];
            if (model.regions.length) {
                this.updateHiddenRanges();
            }
        }
        notifyChangeModelContent(e) {
            if (this._hiddenRanges.length && !this._hasLineChanges) {
                this._hasLineChanges = e.changes.some(change => {
                    return change.range.endLineNumber !== change.range.startLineNumber || (0, eolCounter_1.countEOL)(change.text)[0] !== 0;
                });
            }
        }
        updateHiddenRanges() {
            let updateHiddenAreas = false;
            const newHiddenAreas = [];
            let i = 0; // index into hidden
            let k = 0;
            let lastCollapsedStart = Number.MAX_VALUE;
            let lastCollapsedEnd = -1;
            const ranges = this._foldingModel.regions;
            for (; i < ranges.length; i++) {
                if (!ranges.isCollapsed(i)) {
                    continue;
                }
                const startLineNumber = ranges.getStartLineNumber(i) + 1; // the first line is not hidden
                const endLineNumber = ranges.getEndLineNumber(i);
                if (lastCollapsedStart <= startLineNumber && endLineNumber <= lastCollapsedEnd) {
                    // ignore ranges contained in collapsed regions
                    continue;
                }
                if (!updateHiddenAreas && k < this._hiddenRanges.length && this._hiddenRanges[k].startLineNumber === startLineNumber && this._hiddenRanges[k].endLineNumber === endLineNumber) {
                    // reuse the old ranges
                    newHiddenAreas.push(this._hiddenRanges[k]);
                    k++;
                }
                else {
                    updateHiddenAreas = true;
                    newHiddenAreas.push(new range_1.Range(startLineNumber, 1, endLineNumber, 1));
                }
                lastCollapsedStart = startLineNumber;
                lastCollapsedEnd = endLineNumber;
            }
            if (this._hasLineChanges || updateHiddenAreas || k < this._hiddenRanges.length) {
                this.applyHiddenRanges(newHiddenAreas);
            }
        }
        applyHiddenRanges(newHiddenAreas) {
            this._hiddenRanges = newHiddenAreas;
            this._hasLineChanges = false;
            this._updateEventEmitter.fire(newHiddenAreas);
        }
        hasRanges() {
            return this._hiddenRanges.length > 0;
        }
        isHidden(line) {
            return findRange(this._hiddenRanges, line) !== null;
        }
        adjustSelections(selections) {
            let hasChanges = false;
            const editorModel = this._foldingModel.textModel;
            let lastRange = null;
            const adjustLine = (line) => {
                if (!lastRange || !isInside(line, lastRange)) {
                    lastRange = findRange(this._hiddenRanges, line);
                }
                if (lastRange) {
                    return lastRange.startLineNumber - 1;
                }
                return null;
            };
            for (let i = 0, len = selections.length; i < len; i++) {
                let selection = selections[i];
                const adjustedStartLine = adjustLine(selection.startLineNumber);
                if (adjustedStartLine) {
                    selection = selection.setStartPosition(adjustedStartLine, editorModel.getLineMaxColumn(adjustedStartLine));
                    hasChanges = true;
                }
                const adjustedEndLine = adjustLine(selection.endLineNumber);
                if (adjustedEndLine) {
                    selection = selection.setEndPosition(adjustedEndLine, editorModel.getLineMaxColumn(adjustedEndLine));
                    hasChanges = true;
                }
                selections[i] = selection;
            }
            return hasChanges;
        }
        dispose() {
            if (this.hiddenRanges.length > 0) {
                this._hiddenRanges = [];
                this._updateEventEmitter.fire(this._hiddenRanges);
            }
            if (this._foldingModelListener) {
                this._foldingModelListener.dispose();
                this._foldingModelListener = null;
            }
        }
    }
    exports.HiddenRangeModel = HiddenRangeModel;
    function isInside(line, range) {
        return line >= range.startLineNumber && line <= range.endLineNumber;
    }
    function findRange(ranges, line) {
        const i = (0, arraysFind_1.findFirstIdxMonotonousOrArrLen)(ranges, r => line < r.startLineNumber) - 1;
        if (i >= 0 && ranges[i].endLineNumber >= line) {
            return ranges[i];
        }
        return null;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[335/*vs/editor/contrib/folding/browser/indentRangeProvider*/], __M([1/*require*/,0/*exports*/,237/*vs/editor/common/model/utils*/,203/*vs/editor/contrib/folding/browser/foldingRanges*/]), function (require, exports, utils_1, foldingRanges_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.RangesCollector = exports.IndentRangeProvider = void 0;
    exports.computeRanges = computeRanges;
    const MAX_FOLDING_REGIONS_FOR_INDENT_DEFAULT = 5000;
    const ID_INDENT_PROVIDER = 'indent';
    class IndentRangeProvider {
        constructor(editorModel, languageConfigurationService, foldingRangesLimit) {
            this.editorModel = editorModel;
            this.languageConfigurationService = languageConfigurationService;
            this.foldingRangesLimit = foldingRangesLimit;
            this.id = ID_INDENT_PROVIDER;
        }
        dispose() { }
        compute(cancelationToken) {
            const foldingRules = this.languageConfigurationService.getLanguageConfiguration(this.editorModel.getLanguageId()).foldingRules;
            const offSide = foldingRules && !!foldingRules.offSide;
            const markers = foldingRules && foldingRules.markers;
            return Promise.resolve(computeRanges(this.editorModel, offSide, markers, this.foldingRangesLimit));
        }
    }
    exports.IndentRangeProvider = IndentRangeProvider;
    // public only for testing
    class RangesCollector {
        constructor(foldingRangesLimit) {
            this._startIndexes = [];
            this._endIndexes = [];
            this._indentOccurrences = [];
            this._length = 0;
            this._foldingRangesLimit = foldingRangesLimit;
        }
        insertFirst(startLineNumber, endLineNumber, indent) {
            if (startLineNumber > foldingRanges_1.MAX_LINE_NUMBER || endLineNumber > foldingRanges_1.MAX_LINE_NUMBER) {
                return;
            }
            const index = this._length;
            this._startIndexes[index] = startLineNumber;
            this._endIndexes[index] = endLineNumber;
            this._length++;
            if (indent < 1000) {
                this._indentOccurrences[indent] = (this._indentOccurrences[indent] || 0) + 1;
            }
        }
        toIndentRanges(model) {
            const limit = this._foldingRangesLimit.limit;
            if (this._length <= limit) {
                this._foldingRangesLimit.update(this._length, false);
                // reverse and create arrays of the exact length
                const startIndexes = new Uint32Array(this._length);
                const endIndexes = new Uint32Array(this._length);
                for (let i = this._length - 1, k = 0; i >= 0; i--, k++) {
                    startIndexes[k] = this._startIndexes[i];
                    endIndexes[k] = this._endIndexes[i];
                }
                return new foldingRanges_1.FoldingRegions(startIndexes, endIndexes);
            }
            else {
                this._foldingRangesLimit.update(this._length, limit);
                let entries = 0;
                let maxIndent = this._indentOccurrences.length;
                for (let i = 0; i < this._indentOccurrences.length; i++) {
                    const n = this._indentOccurrences[i];
                    if (n) {
                        if (n + entries > limit) {
                            maxIndent = i;
                            break;
                        }
                        entries += n;
                    }
                }
                const tabSize = model.getOptions().tabSize;
                // reverse and create arrays of the exact length
                const startIndexes = new Uint32Array(limit);
                const endIndexes = new Uint32Array(limit);
                for (let i = this._length - 1, k = 0; i >= 0; i--) {
                    const startIndex = this._startIndexes[i];
                    const lineContent = model.getLineContent(startIndex);
                    const indent = (0, utils_1.computeIndentLevel)(lineContent, tabSize);
                    if (indent < maxIndent || (indent === maxIndent && entries++ < limit)) {
                        startIndexes[k] = startIndex;
                        endIndexes[k] = this._endIndexes[i];
                        k++;
                    }
                }
                return new foldingRanges_1.FoldingRegions(startIndexes, endIndexes);
            }
        }
    }
    exports.RangesCollector = RangesCollector;
    const foldingRangesLimitDefault = {
        limit: MAX_FOLDING_REGIONS_FOR_INDENT_DEFAULT,
        update: () => { }
    };
    function computeRanges(model, offSide, markers, foldingRangesLimit = foldingRangesLimitDefault) {
        const tabSize = model.getOptions().tabSize;
        const result = new RangesCollector(foldingRangesLimit);
        let pattern = undefined;
        if (markers) {
            pattern = new RegExp(`(${markers.start.source})|(?:${markers.end.source})`);
        }
        const previousRegions = [];
        const line = model.getLineCount() + 1;
        previousRegions.push({ indent: -1, endAbove: line, line }); // sentinel, to make sure there's at least one entry
        for (let line = model.getLineCount(); line > 0; line--) {
            const lineContent = model.getLineContent(line);
            const indent = (0, utils_1.computeIndentLevel)(lineContent, tabSize);
            let previous = previousRegions[previousRegions.length - 1];
            if (indent === -1) {
                if (offSide) {
                    // for offSide languages, empty lines are associated to the previous block
                    // note: the next block is already written to the results, so this only
                    // impacts the end position of the block before
                    previous.endAbove = line;
                }
                continue; // only whitespace
            }
            let m;
            if (pattern && (m = lineContent.match(pattern))) {
                // folding pattern match
                if (m[1]) { // start pattern match
                    // discard all regions until the folding pattern
                    let i = previousRegions.length - 1;
                    while (i > 0 && previousRegions[i].indent !== -2) {
                        i--;
                    }
                    if (i > 0) {
                        previousRegions.length = i + 1;
                        previous = previousRegions[i];
                        // new folding range from pattern, includes the end line
                        result.insertFirst(line, previous.line, indent);
                        previous.line = line;
                        previous.indent = indent;
                        previous.endAbove = line;
                        continue;
                    }
                    else {
                        // no end marker found, treat line as a regular line
                    }
                }
                else { // end pattern match
                    previousRegions.push({ indent: -2, endAbove: line, line });
                    continue;
                }
            }
            if (previous.indent > indent) {
                // discard all regions with larger indent
                do {
                    previousRegions.pop();
                    previous = previousRegions[previousRegions.length - 1];
                } while (previous.indent > indent);
                // new folding range
                const endLineNumber = previous.endAbove - 1;
                if (endLineNumber - line >= 1) { // needs at east size 1
                    result.insertFirst(line, endLineNumber, indent);
                }
            }
            if (previous.indent === indent) {
                previous.endAbove = line;
            }
            else { // previous.indent < indent
                // new region with a bigger indent
                previousRegions.push({ indent, endAbove: line, line });
            }
        }
        return result.toIndentRanges(model);
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[336/*vs/editor/contrib/folding/browser/syntaxRangeProvider*/], __M([1/*require*/,0/*exports*/,8/*vs/base/common/errors*/,2/*vs/base/common/lifecycle*/,203/*vs/editor/contrib/folding/browser/foldingRanges*/]), function (require, exports, errors_1, lifecycle_1, foldingRanges_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SyntaxRangeProvider = void 0;
    exports.sanitizeRanges = sanitizeRanges;
    const foldingContext = {};
    const ID_SYNTAX_PROVIDER = 'syntax';
    class SyntaxRangeProvider {
        constructor(editorModel, providers, handleFoldingRangesChange, foldingRangesLimit, fallbackRangeProvider // used when all providers return null
        ) {
            this.editorModel = editorModel;
            this.providers = providers;
            this.handleFoldingRangesChange = handleFoldingRangesChange;
            this.foldingRangesLimit = foldingRangesLimit;
            this.fallbackRangeProvider = fallbackRangeProvider;
            this.id = ID_SYNTAX_PROVIDER;
            this.disposables = new lifecycle_1.DisposableStore();
            if (fallbackRangeProvider) {
                this.disposables.add(fallbackRangeProvider);
            }
            for (const provider of providers) {
                if (typeof provider.onDidChange === 'function') {
                    this.disposables.add(provider.onDidChange(handleFoldingRangesChange));
                }
            }
        }
        compute(cancellationToken) {
            return collectSyntaxRanges(this.providers, this.editorModel, cancellationToken).then(ranges => {
                if (ranges) {
                    const res = sanitizeRanges(ranges, this.foldingRangesLimit);
                    return res;
                }
                return this.fallbackRangeProvider?.compute(cancellationToken) ?? null;
            });
        }
        dispose() {
            this.disposables.dispose();
        }
    }
    exports.SyntaxRangeProvider = SyntaxRangeProvider;
    function collectSyntaxRanges(providers, model, cancellationToken) {
        let rangeData = null;
        const promises = providers.map((provider, i) => {
            return Promise.resolve(provider.provideFoldingRanges(model, foldingContext, cancellationToken)).then(ranges => {
                if (cancellationToken.isCancellationRequested) {
                    return;
                }
                if (Array.isArray(ranges)) {
                    if (!Array.isArray(rangeData)) {
                        rangeData = [];
                    }
                    const nLines = model.getLineCount();
                    for (const r of ranges) {
                        if (r.start > 0 && r.end > r.start && r.end <= nLines) {
                            rangeData.push({ start: r.start, end: r.end, rank: i, kind: r.kind });
                        }
                    }
                }
            }, errors_1.onUnexpectedExternalError);
        });
        return Promise.all(promises).then(_ => {
            return rangeData;
        });
    }
    class RangesCollector {
        constructor(foldingRangesLimit) {
            this._startIndexes = [];
            this._endIndexes = [];
            this._nestingLevels = [];
            this._nestingLevelCounts = [];
            this._types = [];
            this._length = 0;
            this._foldingRangesLimit = foldingRangesLimit;
        }
        add(startLineNumber, endLineNumber, type, nestingLevel) {
            if (startLineNumber > foldingRanges_1.MAX_LINE_NUMBER || endLineNumber > foldingRanges_1.MAX_LINE_NUMBER) {
                return;
            }
            const index = this._length;
            this._startIndexes[index] = startLineNumber;
            this._endIndexes[index] = endLineNumber;
            this._nestingLevels[index] = nestingLevel;
            this._types[index] = type;
            this._length++;
            if (nestingLevel < 30) {
                this._nestingLevelCounts[nestingLevel] = (this._nestingLevelCounts[nestingLevel] || 0) + 1;
            }
        }
        toIndentRanges() {
            const limit = this._foldingRangesLimit.limit;
            if (this._length <= limit) {
                this._foldingRangesLimit.update(this._length, false);
                const startIndexes = new Uint32Array(this._length);
                const endIndexes = new Uint32Array(this._length);
                for (let i = 0; i < this._length; i++) {
                    startIndexes[i] = this._startIndexes[i];
                    endIndexes[i] = this._endIndexes[i];
                }
                return new foldingRanges_1.FoldingRegions(startIndexes, endIndexes, this._types);
            }
            else {
                this._foldingRangesLimit.update(this._length, limit);
                let entries = 0;
                let maxLevel = this._nestingLevelCounts.length;
                for (let i = 0; i < this._nestingLevelCounts.length; i++) {
                    const n = this._nestingLevelCounts[i];
                    if (n) {
                        if (n + entries > limit) {
                            maxLevel = i;
                            break;
                        }
                        entries += n;
                    }
                }
                const startIndexes = new Uint32Array(limit);
                const endIndexes = new Uint32Array(limit);
                const types = [];
                for (let i = 0, k = 0; i < this._length; i++) {
                    const level = this._nestingLevels[i];
                    if (level < maxLevel || (level === maxLevel && entries++ < limit)) {
                        startIndexes[k] = this._startIndexes[i];
                        endIndexes[k] = this._endIndexes[i];
                        types[k] = this._types[i];
                        k++;
                    }
                }
                return new foldingRanges_1.FoldingRegions(startIndexes, endIndexes, types);
            }
        }
    }
    function sanitizeRanges(rangeData, foldingRangesLimit) {
        const sorted = rangeData.sort((d1, d2) => {
            let diff = d1.start - d2.start;
            if (diff === 0) {
                diff = d1.rank - d2.rank;
            }
            return diff;
        });
        const collector = new RangesCollector(foldingRangesLimit);
        let top = undefined;
        const previous = [];
        for (const entry of sorted) {
            if (!top) {
                top = entry;
                collector.add(entry.start, entry.end, entry.kind && entry.kind.value, previous.length);
            }
            else {
                if (entry.start > top.start) {
                    if (entry.end <= top.end) {
                        previous.push(top);
                        top = entry;
                        collector.add(entry.start, entry.end, entry.kind && entry.kind.value, previous.length);
                    }
                    else {
                        if (entry.start > top.end) {
                            do {
                                top = previous.pop();
                            } while (top && entry.start > top.end);
                            if (top) {
                                previous.push(top);
                            }
                            top = entry;
                        }
                        collector.add(entry.start, entry.end, entry.kind && entry.kind.value, previous.length);
                    }
                }
            }
        }
        return collector.toIndentRanges();
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[337/*vs/editor/contrib/format/browser/formattingEdit*/], __M([1/*require*/,0/*exports*/,75/*vs/editor/common/core/editOperation*/,4/*vs/editor/common/core/range*/,143/*vs/editor/browser/stableEditorScroll*/]), function (require, exports, editOperation_1, range_1, stableEditorScroll_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.FormattingEdit = void 0;
    class FormattingEdit {
        static _handleEolEdits(editor, edits) {
            let newEol = undefined;
            const singleEdits = [];
            for (const edit of edits) {
                if (typeof edit.eol === 'number') {
                    newEol = edit.eol;
                }
                if (edit.range && typeof edit.text === 'string') {
                    singleEdits.push(edit);
                }
            }
            if (typeof newEol === 'number') {
                if (editor.hasModel()) {
                    editor.getModel().pushEOL(newEol);
                }
            }
            return singleEdits;
        }
        static _isFullModelReplaceEdit(editor, edit) {
            if (!editor.hasModel()) {
                return false;
            }
            const model = editor.getModel();
            const editRange = model.validateRange(edit.range);
            const fullModelRange = model.getFullModelRange();
            return fullModelRange.equalsRange(editRange);
        }
        static execute(editor, _edits, addUndoStops) {
            if (addUndoStops) {
                editor.pushUndoStop();
            }
            const scrollState = stableEditorScroll_1.StableEditorScrollState.capture(editor);
            const edits = FormattingEdit._handleEolEdits(editor, _edits);
            if (edits.length === 1 && FormattingEdit._isFullModelReplaceEdit(editor, edits[0])) {
                // We use replace semantics and hope that markers stay put...
                editor.executeEdits('formatEditsCommand', edits.map(edit => editOperation_1.EditOperation.replace(range_1.Range.lift(edit.range), edit.text)));
            }
            else {
                editor.executeEdits('formatEditsCommand', edits.map(edit => editOperation_1.EditOperation.replaceMove(range_1.Range.lift(edit.range), edit.text)));
            }
            if (addUndoStops) {
                editor.pushUndoStop();
            }
            scrollState.restoreRelativeVerticalPositionOfCursor(editor);
        }
    }
    exports.FormattingEdit = FormattingEdit;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[614/*vs/editor/contrib/hover/browser/contentHoverTypes*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.FilteredHoverResult = exports.HoverResult = void 0;
    class HoverResult {
        constructor(anchor, hoverParts, isComplete) {
            this.anchor = anchor;
            this.hoverParts = hoverParts;
            this.isComplete = isComplete;
        }
        filter(anchor) {
            const filteredHoverParts = this.hoverParts.filter((m) => m.isValidForHoverAnchor(anchor));
            if (filteredHoverParts.length === this.hoverParts.length) {
                return this;
            }
            return new FilteredHoverResult(this, this.anchor, filteredHoverParts, this.isComplete);
        }
    }
    exports.HoverResult = HoverResult;
    class FilteredHoverResult extends HoverResult {
        constructor(original, anchor, messages, isComplete) {
            super(anchor, messages, isComplete);
            this.original = original;
        }
        filter(anchor) {
            return this.original.filter(anchor);
        }
    }
    exports.FilteredHoverResult = FilteredHoverResult;
});

define(__m[615/*vs/editor/contrib/hover/browser/hoverAccessibleViews*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ExtHoverAccessibleView = exports.HoverAccessibilityHelp = exports.HoverAccessibleView = void 0;
    class HoverAccessibleView {
    }
    exports.HoverAccessibleView = HoverAccessibleView;
    class HoverAccessibilityHelp {
    }
    exports.HoverAccessibilityHelp = HoverAccessibilityHelp;
    class ExtHoverAccessibleView {
    }
    exports.ExtHoverAccessibleView = ExtHoverAccessibleView;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[84/*vs/editor/contrib/hover/browser/hoverTypes*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.HoverParticipantRegistry = exports.RenderedHoverParts = exports.HoverForeignElementAnchor = exports.HoverRangeAnchor = void 0;
    class HoverRangeAnchor {
        constructor(priority, range, initialMousePosX, initialMousePosY) {
            this.priority = priority;
            this.range = range;
            this.initialMousePosX = initialMousePosX;
            this.initialMousePosY = initialMousePosY;
            this.type = 1 /* HoverAnchorType.Range */;
        }
        equals(other) {
            return (other.type === 1 /* HoverAnchorType.Range */ && this.range.equalsRange(other.range));
        }
        canAdoptVisibleHover(lastAnchor, showAtPosition) {
            return (lastAnchor.type === 1 /* HoverAnchorType.Range */ && showAtPosition.lineNumber === this.range.startLineNumber);
        }
    }
    exports.HoverRangeAnchor = HoverRangeAnchor;
    class HoverForeignElementAnchor {
        constructor(priority, owner, range, initialMousePosX, initialMousePosY, supportsMarkerHover) {
            this.priority = priority;
            this.owner = owner;
            this.range = range;
            this.initialMousePosX = initialMousePosX;
            this.initialMousePosY = initialMousePosY;
            this.supportsMarkerHover = supportsMarkerHover;
            this.type = 2 /* HoverAnchorType.ForeignElement */;
        }
        equals(other) {
            return (other.type === 2 /* HoverAnchorType.ForeignElement */ && this.owner === other.owner);
        }
        canAdoptVisibleHover(lastAnchor, showAtPosition) {
            return (lastAnchor.type === 2 /* HoverAnchorType.ForeignElement */ && this.owner === lastAnchor.owner);
        }
    }
    exports.HoverForeignElementAnchor = HoverForeignElementAnchor;
    /**
     * Default implementation of IRenderedHoverParts.
     */
    class RenderedHoverParts {
        constructor(renderedHoverParts) {
            this.renderedHoverParts = renderedHoverParts;
        }
        dispose() {
            for (const part of this.renderedHoverParts) {
                part.dispose();
            }
        }
    }
    exports.RenderedHoverParts = RenderedHoverParts;
    exports.HoverParticipantRegistry = (new class HoverParticipantRegistry {
        constructor() {
            this._participants = [];
        }
        register(ctor) {
            this._participants.push(ctor);
        }
        getAll() {
            return this._participants;
        }
    }());
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[616/*vs/editor/contrib/inPlaceReplace/browser/inPlaceReplaceCommand*/], __M([1/*require*/,0/*exports*/,23/*vs/editor/common/core/selection*/]), function (require, exports, selection_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.InPlaceReplaceCommand = void 0;
    class InPlaceReplaceCommand {
        constructor(editRange, originalSelection, text) {
            this._editRange = editRange;
            this._originalSelection = originalSelection;
            this._text = text;
        }
        getEditOperations(model, builder) {
            builder.addTrackedEditOperation(this._editRange, this._text);
        }
        computeCursorState(model, helper) {
            const inverseEditOperations = helper.getInverseEditOperations();
            const srcRange = inverseEditOperations[0].range;
            if (!this._originalSelection.isEmpty()) {
                // Preserve selection and extends to typed text
                return new selection_1.Selection(srcRange.endLineNumber, srcRange.endColumn - this._text.length, srcRange.endLineNumber, srcRange.endColumn);
            }
            return new selection_1.Selection(srcRange.endLineNumber, Math.min(this._originalSelection.positionColumn, srcRange.endColumn), srcRange.endLineNumber, Math.min(this._originalSelection.positionColumn, srcRange.endColumn));
        }
    }
    exports.InPlaceReplaceCommand = InPlaceReplaceCommand;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[338/*vs/editor/contrib/indentation/common/indentUtils*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.getSpaceCnt = getSpaceCnt;
    exports.generateIndent = generateIndent;
    function getSpaceCnt(str, tabSize) {
        let spacesCnt = 0;
        for (let i = 0; i < str.length; i++) {
            if (str.charAt(i) === '\t') {
                spacesCnt += tabSize;
            }
            else {
                spacesCnt++;
            }
        }
        return spacesCnt;
    }
    function generateIndent(spacesCnt, tabSize, insertSpaces) {
        spacesCnt = spacesCnt < 0 ? 0 : spacesCnt;
        let result = '';
        if (!insertSpaces) {
            const tabsCnt = Math.floor(spacesCnt / tabSize);
            spacesCnt = spacesCnt % tabSize;
            for (let i = 0; i < tabsCnt; i++) {
                result += '\t';
            }
        }
        for (let i = 0; i < spacesCnt; i++) {
            result += ' ';
        }
        return result;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[245/*vs/editor/contrib/inlineCompletions/browser/controller/commandIds*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.showNextInlineSuggestionActionId = exports.showPreviousInlineSuggestionActionId = exports.inlineSuggestCommitId = void 0;
    exports.inlineSuggestCommitId = 'editor.action.inlineSuggest.commit';
    exports.showPreviousInlineSuggestionActionId = 'editor.action.inlineSuggest.showPrevious';
    exports.showNextInlineSuggestionActionId = 'editor.action.inlineSuggest.showNext';
});

define(__m[617/*vs/editor/contrib/inlineCompletions/browser/inlineCompletionsAccessibleView*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.InlineCompletionsAccessibleView = void 0;
    class InlineCompletionsAccessibleView {
    }
    exports.InlineCompletionsAccessibleView = InlineCompletionsAccessibleView;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[204/*vs/editor/contrib/inlineCompletions/browser/model/ghostText*/], __M([1/*require*/,0/*exports*/,13/*vs/base/common/arrays*/,11/*vs/base/common/strings*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/,104/*vs/editor/common/core/textEdit*/]), function (require, exports, arrays_1, strings_1, position_1, range_1, textEdit_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.GhostTextReplacement = exports.GhostTextPart = exports.GhostText = void 0;
    exports.ghostTextsOrReplacementsEqual = ghostTextsOrReplacementsEqual;
    exports.ghostTextOrReplacementEquals = ghostTextOrReplacementEquals;
    class GhostText {
        constructor(lineNumber, parts) {
            this.lineNumber = lineNumber;
            this.parts = parts;
        }
        equals(other) {
            return this.lineNumber === other.lineNumber &&
                this.parts.length === other.parts.length &&
                this.parts.every((part, index) => part.equals(other.parts[index]));
        }
        renderForScreenReader(lineText) {
            if (this.parts.length === 0) {
                return '';
            }
            const lastPart = this.parts[this.parts.length - 1];
            const cappedLineText = lineText.substr(0, lastPart.column - 1);
            const text = new textEdit_1.TextEdit([
                ...this.parts.map(p => new textEdit_1.SingleTextEdit(range_1.Range.fromPositions(new position_1.Position(1, p.column)), p.lines.join('\n'))),
            ]).applyToString(cappedLineText);
            return text.substring(this.parts[0].column - 1);
        }
        isEmpty() {
            return this.parts.every(p => p.lines.length === 0);
        }
        get lineCount() {
            return 1 + this.parts.reduce((r, p) => r + p.lines.length - 1, 0);
        }
    }
    exports.GhostText = GhostText;
    class GhostTextPart {
        constructor(column, text, 
        /**
         * Indicates if this part is a preview of an inline suggestion when a suggestion is previewed.
        */
        preview) {
            this.column = column;
            this.text = text;
            this.preview = preview;
            this.lines = (0, strings_1.splitLines)(this.text);
        }
        equals(other) {
            return this.column === other.column &&
                this.lines.length === other.lines.length &&
                this.lines.every((line, index) => line === other.lines[index]);
        }
    }
    exports.GhostTextPart = GhostTextPart;
    class GhostTextReplacement {
        constructor(lineNumber, columnRange, text, additionalReservedLineCount = 0) {
            this.lineNumber = lineNumber;
            this.columnRange = columnRange;
            this.text = text;
            this.additionalReservedLineCount = additionalReservedLineCount;
            this.parts = [
                new GhostTextPart(this.columnRange.endColumnExclusive, this.text, false),
            ];
            this.newLines = (0, strings_1.splitLines)(this.text);
        }
        renderForScreenReader(_lineText) {
            return this.newLines.join('\n');
        }
        get lineCount() {
            return this.newLines.length;
        }
        isEmpty() {
            return this.parts.every(p => p.lines.length === 0);
        }
        equals(other) {
            return this.lineNumber === other.lineNumber &&
                this.columnRange.equals(other.columnRange) &&
                this.newLines.length === other.newLines.length &&
                this.newLines.every((line, index) => line === other.newLines[index]) &&
                this.additionalReservedLineCount === other.additionalReservedLineCount;
        }
    }
    exports.GhostTextReplacement = GhostTextReplacement;
    function ghostTextsOrReplacementsEqual(a, b) {
        return (0, arrays_1.equals)(a, b, ghostTextOrReplacementEquals);
    }
    function ghostTextOrReplacementEquals(a, b) {
        if (a === b) {
            return true;
        }
        if (!a || !b) {
            return false;
        }
        if (a instanceof GhostText && b instanceof GhostText) {
            return a.equals(b);
        }
        if (a instanceof GhostTextReplacement && b instanceof GhostTextReplacement) {
            return a.equals(b);
        }
        return false;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[246/*vs/editor/contrib/inlineCompletions/browser/model/singleTextEdit*/], __M([1/*require*/,0/*exports*/,190/*vs/base/common/diff/diff*/,11/*vs/base/common/strings*/,4/*vs/editor/common/core/range*/,113/*vs/editor/common/core/textLength*/,104/*vs/editor/common/core/textEdit*/,204/*vs/editor/contrib/inlineCompletions/browser/model/ghostText*/]), function (require, exports, diff_1, strings_1, range_1, textLength_1, textEdit_1, ghostText_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.singleTextRemoveCommonPrefix = singleTextRemoveCommonPrefix;
    exports.singleTextEditAugments = singleTextEditAugments;
    exports.computeGhostText = computeGhostText;
    function singleTextRemoveCommonPrefix(edit, model, validModelRange) {
        const modelRange = validModelRange ? edit.range.intersectRanges(validModelRange) : edit.range;
        if (!modelRange) {
            return edit;
        }
        const valueToReplace = model.getValueInRange(modelRange, 1 /* EndOfLinePreference.LF */);
        const commonPrefixLen = (0, strings_1.commonPrefixLength)(valueToReplace, edit.text);
        const start = textLength_1.TextLength.ofText(valueToReplace.substring(0, commonPrefixLen)).addToPosition(edit.range.getStartPosition());
        const text = edit.text.substring(commonPrefixLen);
        const range = range_1.Range.fromPositions(start, edit.range.getEndPosition());
        return new textEdit_1.SingleTextEdit(range, text);
    }
    function singleTextEditAugments(edit, base) {
        // The augmented completion must replace the base range, but can replace even more
        return edit.text.startsWith(base.text) && rangeExtends(edit.range, base.range);
    }
    /**
     * @param previewSuffixLength Sets where to split `inlineCompletion.text`.
     * 	If the text is `hello` and the suffix length is 2, the non-preview part is `hel` and the preview-part is `lo`.
    */
    function computeGhostText(edit, model, mode, cursorPosition, previewSuffixLength = 0) {
        let e = singleTextRemoveCommonPrefix(edit, model);
        if (e.range.endLineNumber !== e.range.startLineNumber) {
            // This edit might span multiple lines, but the first lines must be a common prefix.
            return undefined;
        }
        const sourceLine = model.getLineContent(e.range.startLineNumber);
        const sourceIndentationLength = (0, strings_1.getLeadingWhitespace)(sourceLine).length;
        const suggestionTouchesIndentation = e.range.startColumn - 1 <= sourceIndentationLength;
        if (suggestionTouchesIndentation) {
            // source:      ··········[······abc]
            //                         ^^^^^^^^^ inlineCompletion.range
            //              ^^^^^^^^^^ ^^^^^^ sourceIndentationLength
            //                         ^^^^^^ replacedIndentation.length
            //                               ^^^ rangeThatDoesNotReplaceIndentation
            // inlineCompletion.text: '··foo'
            //                         ^^ suggestionAddedIndentationLength
            const suggestionAddedIndentationLength = (0, strings_1.getLeadingWhitespace)(e.text).length;
            const replacedIndentation = sourceLine.substring(e.range.startColumn - 1, sourceIndentationLength);
            const [startPosition, endPosition] = [e.range.getStartPosition(), e.range.getEndPosition()];
            const newStartPosition = startPosition.column + replacedIndentation.length <= endPosition.column
                ? startPosition.delta(0, replacedIndentation.length)
                : endPosition;
            const rangeThatDoesNotReplaceIndentation = range_1.Range.fromPositions(newStartPosition, endPosition);
            const suggestionWithoutIndentationChange = e.text.startsWith(replacedIndentation)
                // Adds more indentation without changing existing indentation: We can add ghost text for this
                ? e.text.substring(replacedIndentation.length)
                // Changes or removes existing indentation. Only add ghost text for the non-indentation part.
                : e.text.substring(suggestionAddedIndentationLength);
            e = new textEdit_1.SingleTextEdit(rangeThatDoesNotReplaceIndentation, suggestionWithoutIndentationChange);
        }
        // This is a single line string
        const valueToBeReplaced = model.getValueInRange(e.range);
        const changes = cachingDiff(valueToBeReplaced, e.text);
        if (!changes) {
            // No ghost text in case the diff would be too slow to compute
            return undefined;
        }
        const lineNumber = e.range.startLineNumber;
        const parts = new Array();
        if (mode === 'prefix') {
            const filteredChanges = changes.filter(c => c.originalLength === 0);
            if (filteredChanges.length > 1 || filteredChanges.length === 1 && filteredChanges[0].originalStart !== valueToBeReplaced.length) {
                // Prefixes only have a single change.
                return undefined;
            }
        }
        const previewStartInCompletionText = e.text.length - previewSuffixLength;
        for (const c of changes) {
            const insertColumn = e.range.startColumn + c.originalStart + c.originalLength;
            if (mode === 'subwordSmart' && cursorPosition && cursorPosition.lineNumber === e.range.startLineNumber && insertColumn < cursorPosition.column) {
                // No ghost text before cursor
                return undefined;
            }
            if (c.originalLength > 0) {
                return undefined;
            }
            if (c.modifiedLength === 0) {
                continue;
            }
            const modifiedEnd = c.modifiedStart + c.modifiedLength;
            const nonPreviewTextEnd = Math.max(c.modifiedStart, Math.min(modifiedEnd, previewStartInCompletionText));
            const nonPreviewText = e.text.substring(c.modifiedStart, nonPreviewTextEnd);
            const italicText = e.text.substring(nonPreviewTextEnd, Math.max(c.modifiedStart, modifiedEnd));
            if (nonPreviewText.length > 0) {
                parts.push(new ghostText_1.GhostTextPart(insertColumn, nonPreviewText, false));
            }
            if (italicText.length > 0) {
                parts.push(new ghostText_1.GhostTextPart(insertColumn, italicText, true));
            }
        }
        return new ghostText_1.GhostText(lineNumber, parts);
    }
    function rangeExtends(extendingRange, rangeToExtend) {
        return rangeToExtend.getStartPosition().equals(extendingRange.getStartPosition())
            && rangeToExtend.getEndPosition().isBeforeOrEqual(extendingRange.getEndPosition());
    }
    let lastRequest = undefined;
    function cachingDiff(originalValue, newValue) {
        if (lastRequest?.originalValue === originalValue && lastRequest?.newValue === newValue) {
            return lastRequest?.changes;
        }
        else {
            let changes = smartDiff(originalValue, newValue, true);
            if (changes) {
                const deletedChars = deletedCharacters(changes);
                if (deletedChars > 0) {
                    // For performance reasons, don't compute diff if there is nothing to improve
                    const newChanges = smartDiff(originalValue, newValue, false);
                    if (newChanges && deletedCharacters(newChanges) < deletedChars) {
                        // Disabling smartness seems to be better here
                        changes = newChanges;
                    }
                }
            }
            lastRequest = {
                originalValue,
                newValue,
                changes
            };
            return changes;
        }
    }
    function deletedCharacters(changes) {
        let sum = 0;
        for (const c of changes) {
            sum += c.originalLength;
        }
        return sum;
    }
    /**
     * When matching `if ()` with `if (f() = 1) { g(); }`,
     * align it like this:        `if (       )`
     * Not like this:			  `if (  )`
     * Also not like this:		  `if (             )`.
     *
     * The parenthesis are preprocessed to ensure that they match correctly.
     */
    function smartDiff(originalValue, newValue, smartBracketMatching) {
        if (originalValue.length > 5000 || newValue.length > 5000) {
            // We don't want to work on strings that are too big
            return undefined;
        }
        function getMaxCharCode(val) {
            let maxCharCode = 0;
            for (let i = 0, len = val.length; i < len; i++) {
                const charCode = val.charCodeAt(i);
                if (charCode > maxCharCode) {
                    maxCharCode = charCode;
                }
            }
            return maxCharCode;
        }
        const maxCharCode = Math.max(getMaxCharCode(originalValue), getMaxCharCode(newValue));
        function getUniqueCharCode(id) {
            if (id < 0) {
                throw new Error('unexpected');
            }
            return maxCharCode + id + 1;
        }
        function getElements(source) {
            let level = 0;
            let group = 0;
            const characters = new Int32Array(source.length);
            for (let i = 0, len = source.length; i < len; i++) {
                // TODO support more brackets
                if (smartBracketMatching && source[i] === '(') {
                    const id = group * 100 + level;
                    characters[i] = getUniqueCharCode(2 * id);
                    level++;
                }
                else if (smartBracketMatching && source[i] === ')') {
                    level = Math.max(level - 1, 0);
                    const id = group * 100 + level;
                    characters[i] = getUniqueCharCode(2 * id + 1);
                    if (level === 0) {
                        group++;
                    }
                }
                else {
                    characters[i] = source.charCodeAt(i);
                }
            }
            return characters;
        }
        const elements1 = getElements(originalValue);
        const elements2 = getElements(newValue);
        return new diff_1.LcsDiff({ getElements: () => elements1 }, { getElements: () => elements2 }).ComputeDiff(false).changes;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[205/*vs/editor/contrib/inlineCompletions/browser/utils*/], __M([1/*require*/,0/*exports*/,8/*vs/base/common/errors*/,2/*vs/base/common/lifecycle*/,21/*vs/base/common/observable*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/]), function (require, exports, errors_1, lifecycle_1, observable_1, position_1, range_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ColumnRange = void 0;
    exports.getReadonlyEmptyArray = getReadonlyEmptyArray;
    exports.applyObservableDecorations = applyObservableDecorations;
    exports.addPositions = addPositions;
    exports.subtractPositions = subtractPositions;
    const array = [];
    function getReadonlyEmptyArray() {
        return array;
    }
    class ColumnRange {
        constructor(startColumn, endColumnExclusive) {
            this.startColumn = startColumn;
            this.endColumnExclusive = endColumnExclusive;
            if (startColumn > endColumnExclusive) {
                throw new errors_1.BugIndicatingError(`startColumn ${startColumn} cannot be after endColumnExclusive ${endColumnExclusive}`);
            }
        }
        toRange(lineNumber) {
            return new range_1.Range(lineNumber, this.startColumn, lineNumber, this.endColumnExclusive);
        }
        equals(other) {
            return this.startColumn === other.startColumn
                && this.endColumnExclusive === other.endColumnExclusive;
        }
    }
    exports.ColumnRange = ColumnRange;
    function applyObservableDecorations(editor, decorations) {
        const d = new lifecycle_1.DisposableStore();
        const decorationsCollection = editor.createDecorationsCollection();
        d.add((0, observable_1.autorunOpts)({ debugName: () => `Apply decorations from ${decorations.debugName}` }, reader => {
            const d = decorations.read(reader);
            decorationsCollection.set(d);
        }));
        d.add({
            dispose: () => {
                decorationsCollection.clear();
            }
        });
        return d;
    }
    function addPositions(pos1, pos2) {
        return new position_1.Position(pos1.lineNumber + pos2.lineNumber - 1, pos2.lineNumber === 1 ? pos1.column + pos2.column - 1 : pos2.column);
    }
    function subtractPositions(pos1, pos2) {
        return new position_1.Position(pos1.lineNumber - pos2.lineNumber + 1, pos1.lineNumber - pos2.lineNumber === 0 ? pos1.column - pos2.column + 1 : pos1.column);
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[618/*vs/editor/contrib/inlineEdit/browser/commandIds*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.inlineEditJumpBackId = exports.inlineEditJumpToId = exports.inlineEditRejectId = exports.inlineEditAcceptId = void 0;
    exports.inlineEditAcceptId = 'editor.action.inlineEdit.accept';
    exports.inlineEditRejectId = 'editor.action.inlineEdit.reject';
    exports.inlineEditJumpToId = 'editor.action.inlineEdit.jumpTo';
    exports.inlineEditJumpBackId = 'editor.action.inlineEdit.jumpBack';
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[619/*vs/editor/contrib/linesOperations/browser/copyLinesCommand*/], __M([1/*require*/,0/*exports*/,4/*vs/editor/common/core/range*/,23/*vs/editor/common/core/selection*/]), function (require, exports, range_1, selection_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CopyLinesCommand = void 0;
    class CopyLinesCommand {
        constructor(selection, isCopyingDown, noop) {
            this._selection = selection;
            this._isCopyingDown = isCopyingDown;
            this._noop = noop || false;
            this._selectionDirection = 0 /* SelectionDirection.LTR */;
            this._selectionId = null;
            this._startLineNumberDelta = 0;
            this._endLineNumberDelta = 0;
        }
        getEditOperations(model, builder) {
            let s = this._selection;
            this._startLineNumberDelta = 0;
            this._endLineNumberDelta = 0;
            if (s.startLineNumber < s.endLineNumber && s.endColumn === 1) {
                this._endLineNumberDelta = 1;
                s = s.setEndPosition(s.endLineNumber - 1, model.getLineMaxColumn(s.endLineNumber - 1));
            }
            const sourceLines = [];
            for (let i = s.startLineNumber; i <= s.endLineNumber; i++) {
                sourceLines.push(model.getLineContent(i));
            }
            const sourceText = sourceLines.join('\n');
            if (sourceText === '') {
                // Duplicating empty line
                if (this._isCopyingDown) {
                    this._startLineNumberDelta++;
                    this._endLineNumberDelta++;
                }
            }
            if (this._noop) {
                builder.addEditOperation(new range_1.Range(s.endLineNumber, model.getLineMaxColumn(s.endLineNumber), s.endLineNumber + 1, 1), s.endLineNumber === model.getLineCount() ? '' : '\n');
            }
            else {
                if (!this._isCopyingDown) {
                    builder.addEditOperation(new range_1.Range(s.endLineNumber, model.getLineMaxColumn(s.endLineNumber), s.endLineNumber, model.getLineMaxColumn(s.endLineNumber)), '\n' + sourceText);
                }
                else {
                    builder.addEditOperation(new range_1.Range(s.startLineNumber, 1, s.startLineNumber, 1), sourceText + '\n');
                }
            }
            this._selectionId = builder.trackSelection(s);
            this._selectionDirection = this._selection.getDirection();
        }
        computeCursorState(model, helper) {
            let result = helper.getTrackedSelection(this._selectionId);
            if (this._startLineNumberDelta !== 0 || this._endLineNumberDelta !== 0) {
                let startLineNumber = result.startLineNumber;
                let startColumn = result.startColumn;
                let endLineNumber = result.endLineNumber;
                let endColumn = result.endColumn;
                if (this._startLineNumberDelta !== 0) {
                    startLineNumber = startLineNumber + this._startLineNumberDelta;
                    startColumn = 1;
                }
                if (this._endLineNumberDelta !== 0) {
                    endLineNumber = endLineNumber + this._endLineNumberDelta;
                    endColumn = 1;
                }
                result = selection_1.Selection.createWithDirection(startLineNumber, startColumn, endLineNumber, endColumn, this._selectionDirection);
            }
            return result;
        }
    }
    exports.CopyLinesCommand = CopyLinesCommand;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[620/*vs/editor/contrib/linesOperations/browser/sortLinesCommand*/], __M([1/*require*/,0/*exports*/,75/*vs/editor/common/core/editOperation*/,4/*vs/editor/common/core/range*/]), function (require, exports, editOperation_1, range_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SortLinesCommand = void 0;
    class SortLinesCommand {
        static { this._COLLATOR = null; }
        static getCollator() {
            if (!SortLinesCommand._COLLATOR) {
                SortLinesCommand._COLLATOR = new Intl.Collator();
            }
            return SortLinesCommand._COLLATOR;
        }
        constructor(selection, descending) {
            this.selection = selection;
            this.descending = descending;
            this.selectionId = null;
        }
        getEditOperations(model, builder) {
            const op = sortLines(model, this.selection, this.descending);
            if (op) {
                builder.addEditOperation(op.range, op.text);
            }
            this.selectionId = builder.trackSelection(this.selection);
        }
        computeCursorState(model, helper) {
            return helper.getTrackedSelection(this.selectionId);
        }
        static canRun(model, selection, descending) {
            if (model === null) {
                return false;
            }
            const data = getSortData(model, selection, descending);
            if (!data) {
                return false;
            }
            for (let i = 0, len = data.before.length; i < len; i++) {
                if (data.before[i] !== data.after[i]) {
                    return true;
                }
            }
            return false;
        }
    }
    exports.SortLinesCommand = SortLinesCommand;
    function getSortData(model, selection, descending) {
        const startLineNumber = selection.startLineNumber;
        let endLineNumber = selection.endLineNumber;
        if (selection.endColumn === 1) {
            endLineNumber--;
        }
        // Nothing to sort if user didn't select anything.
        if (startLineNumber >= endLineNumber) {
            return null;
        }
        const linesToSort = [];
        // Get the contents of the selection to be sorted.
        for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
            linesToSort.push(model.getLineContent(lineNumber));
        }
        let sorted = linesToSort.slice(0);
        sorted.sort(SortLinesCommand.getCollator().compare);
        // If descending, reverse the order.
        if (descending === true) {
            sorted = sorted.reverse();
        }
        return {
            startLineNumber: startLineNumber,
            endLineNumber: endLineNumber,
            before: linesToSort,
            after: sorted
        };
    }
    /**
     * Generate commands for sorting lines on a model.
     */
    function sortLines(model, selection, descending) {
        const data = getSortData(model, selection, descending);
        if (!data) {
            return null;
        }
        return editOperation_1.EditOperation.replace(new range_1.Range(data.startLineNumber, 1, data.endLineNumber, model.getLineMaxColumn(data.endLineNumber)), data.after.join('\n'));
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[339/*vs/editor/contrib/semanticTokens/common/semanticTokensConfig*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SEMANTIC_HIGHLIGHTING_SETTING_ID = void 0;
    exports.isSemanticColoringEnabled = isSemanticColoringEnabled;
    exports.SEMANTIC_HIGHLIGHTING_SETTING_ID = 'editor.semanticHighlighting';
    function isSemanticColoringEnabled(model, themeService, configurationService) {
        const setting = configurationService.getValue(exports.SEMANTIC_HIGHLIGHTING_SETTING_ID, { overrideIdentifier: model.getLanguageId(), resource: model.uri })?.enabled;
        if (typeof setting === 'boolean') {
            return setting;
        }
        return themeService.getColorTheme().semanticHighlighting;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[340/*vs/editor/contrib/smartSelect/browser/bracketSelections*/], __M([1/*require*/,0/*exports*/,73/*vs/base/common/linkedList*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/]), function (require, exports, linkedList_1, position_1, range_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.BracketSelectionRangeProvider = void 0;
    class BracketSelectionRangeProvider {
        async provideSelectionRanges(model, positions) {
            const result = [];
            for (const position of positions) {
                const bucket = [];
                result.push(bucket);
                const ranges = new Map();
                await new Promise(resolve => BracketSelectionRangeProvider._bracketsRightYield(resolve, 0, model, position, ranges));
                await new Promise(resolve => BracketSelectionRangeProvider._bracketsLeftYield(resolve, 0, model, position, ranges, bucket));
            }
            return result;
        }
        static { this._maxDuration = 30; }
        static { this._maxRounds = 2; }
        static _bracketsRightYield(resolve, round, model, pos, ranges) {
            const counts = new Map();
            const t1 = Date.now();
            while (true) {
                if (round >= BracketSelectionRangeProvider._maxRounds) {
                    resolve();
                    break;
                }
                if (!pos) {
                    resolve();
                    break;
                }
                const bracket = model.bracketPairs.findNextBracket(pos);
                if (!bracket) {
                    resolve();
                    break;
                }
                const d = Date.now() - t1;
                if (d > BracketSelectionRangeProvider._maxDuration) {
                    setTimeout(() => BracketSelectionRangeProvider._bracketsRightYield(resolve, round + 1, model, pos, ranges));
                    break;
                }
                if (bracket.bracketInfo.isOpeningBracket) {
                    const key = bracket.bracketInfo.bracketText;
                    // wait for closing
                    const val = counts.has(key) ? counts.get(key) : 0;
                    counts.set(key, val + 1);
                }
                else {
                    const key = bracket.bracketInfo.getOpeningBrackets()[0].bracketText;
                    // process closing
                    let val = counts.has(key) ? counts.get(key) : 0;
                    val -= 1;
                    counts.set(key, Math.max(0, val));
                    if (val < 0) {
                        let list = ranges.get(key);
                        if (!list) {
                            list = new linkedList_1.LinkedList();
                            ranges.set(key, list);
                        }
                        list.push(bracket.range);
                    }
                }
                pos = bracket.range.getEndPosition();
            }
        }
        static _bracketsLeftYield(resolve, round, model, pos, ranges, bucket) {
            const counts = new Map();
            const t1 = Date.now();
            while (true) {
                if (round >= BracketSelectionRangeProvider._maxRounds && ranges.size === 0) {
                    resolve();
                    break;
                }
                if (!pos) {
                    resolve();
                    break;
                }
                const bracket = model.bracketPairs.findPrevBracket(pos);
                if (!bracket) {
                    resolve();
                    break;
                }
                const d = Date.now() - t1;
                if (d > BracketSelectionRangeProvider._maxDuration) {
                    setTimeout(() => BracketSelectionRangeProvider._bracketsLeftYield(resolve, round + 1, model, pos, ranges, bucket));
                    break;
                }
                if (!bracket.bracketInfo.isOpeningBracket) {
                    const key = bracket.bracketInfo.getOpeningBrackets()[0].bracketText;
                    // wait for opening
                    const val = counts.has(key) ? counts.get(key) : 0;
                    counts.set(key, val + 1);
                }
                else {
                    const key = bracket.bracketInfo.bracketText;
                    // opening
                    let val = counts.has(key) ? counts.get(key) : 0;
                    val -= 1;
                    counts.set(key, Math.max(0, val));
                    if (val < 0) {
                        const list = ranges.get(key);
                        if (list) {
                            const closing = list.shift();
                            if (list.size === 0) {
                                ranges.delete(key);
                            }
                            const innerBracket = range_1.Range.fromPositions(bracket.range.getEndPosition(), closing.getStartPosition());
                            const outerBracket = range_1.Range.fromPositions(bracket.range.getStartPosition(), closing.getEndPosition());
                            bucket.push({ range: innerBracket });
                            bucket.push({ range: outerBracket });
                            BracketSelectionRangeProvider._addBracketLeading(model, outerBracket, bucket);
                        }
                    }
                }
                pos = bracket.range.getStartPosition();
            }
        }
        static _addBracketLeading(model, bracket, bucket) {
            if (bracket.startLineNumber === bracket.endLineNumber) {
                return;
            }
            // xxxxxxxx {
            //
            // }
            const startLine = bracket.startLineNumber;
            const column = model.getLineFirstNonWhitespaceColumn(startLine);
            if (column !== 0 && column !== bracket.startColumn) {
                bucket.push({ range: range_1.Range.fromPositions(new position_1.Position(startLine, column), bracket.getEndPosition()) });
                bucket.push({ range: range_1.Range.fromPositions(new position_1.Position(startLine, 1), bracket.getEndPosition()) });
            }
            // xxxxxxxx
            // {
            //
            // }
            const aboveLine = startLine - 1;
            if (aboveLine > 0) {
                const column = model.getLineFirstNonWhitespaceColumn(aboveLine);
                if (column === bracket.startColumn && column !== model.getLineLastNonWhitespaceColumn(aboveLine)) {
                    bucket.push({ range: range_1.Range.fromPositions(new position_1.Position(aboveLine, column), bracket.getEndPosition()) });
                    bucket.push({ range: range_1.Range.fromPositions(new position_1.Position(aboveLine, 1), bracket.getEndPosition()) });
                }
            }
        }
    }
    exports.BracketSelectionRangeProvider = BracketSelectionRangeProvider;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[621/*vs/editor/contrib/smartSelect/browser/wordSelections*/], __M([1/*require*/,0/*exports*/,11/*vs/base/common/strings*/,4/*vs/editor/common/core/range*/]), function (require, exports, strings_1, range_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.WordSelectionRangeProvider = void 0;
    class WordSelectionRangeProvider {
        constructor(selectSubwords = true) {
            this.selectSubwords = selectSubwords;
        }
        provideSelectionRanges(model, positions) {
            const result = [];
            for (const position of positions) {
                const bucket = [];
                result.push(bucket);
                if (this.selectSubwords) {
                    this._addInWordRanges(bucket, model, position);
                }
                this._addWordRanges(bucket, model, position);
                this._addWhitespaceLine(bucket, model, position);
                bucket.push({ range: model.getFullModelRange() });
            }
            return result;
        }
        _addInWordRanges(bucket, model, pos) {
            const obj = model.getWordAtPosition(pos);
            if (!obj) {
                return;
            }
            const { word, startColumn } = obj;
            const offset = pos.column - startColumn;
            let start = offset;
            let end = offset;
            let lastCh = 0;
            // LEFT anchor (start)
            for (; start >= 0; start--) {
                const ch = word.charCodeAt(start);
                if ((start !== offset) && (ch === 95 /* CharCode.Underline */ || ch === 45 /* CharCode.Dash */)) {
                    // foo-bar OR foo_bar
                    break;
                }
                else if ((0, strings_1.isLowerAsciiLetter)(ch) && (0, strings_1.isUpperAsciiLetter)(lastCh)) {
                    // fooBar
                    break;
                }
                lastCh = ch;
            }
            start += 1;
            // RIGHT anchor (end)
            for (; end < word.length; end++) {
                const ch = word.charCodeAt(end);
                if ((0, strings_1.isUpperAsciiLetter)(ch) && (0, strings_1.isLowerAsciiLetter)(lastCh)) {
                    // fooBar
                    break;
                }
                else if (ch === 95 /* CharCode.Underline */ || ch === 45 /* CharCode.Dash */) {
                    // foo-bar OR foo_bar
                    break;
                }
                lastCh = ch;
            }
            if (start < end) {
                bucket.push({ range: new range_1.Range(pos.lineNumber, startColumn + start, pos.lineNumber, startColumn + end) });
            }
        }
        _addWordRanges(bucket, model, pos) {
            const word = model.getWordAtPosition(pos);
            if (word) {
                bucket.push({ range: new range_1.Range(pos.lineNumber, word.startColumn, pos.lineNumber, word.endColumn) });
            }
        }
        _addWhitespaceLine(bucket, model, pos) {
            if (model.getLineLength(pos.lineNumber) > 0
                && model.getLineFirstNonWhitespaceColumn(pos.lineNumber) === 0
                && model.getLineLastNonWhitespaceColumn(pos.lineNumber) === 0) {
                bucket.push({ range: new range_1.Range(pos.lineNumber, 1, pos.lineNumber, model.getLineMaxColumn(pos.lineNumber)) });
            }
        }
    }
    exports.WordSelectionRangeProvider = WordSelectionRangeProvider;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[135/*vs/editor/contrib/snippet/browser/snippetParser*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SnippetParser = exports.TextmateSnippet = exports.Variable = exports.FormatString = exports.Transform = exports.Choice = exports.Placeholder = exports.TransformableMarker = exports.Text = exports.Marker = exports.Scanner = void 0;
    class Scanner {
        constructor() {
            this.value = '';
            this.pos = 0;
        }
        static { this._table = {
            [36 /* CharCode.DollarSign */]: 0 /* TokenType.Dollar */,
            [58 /* CharCode.Colon */]: 1 /* TokenType.Colon */,
            [44 /* CharCode.Comma */]: 2 /* TokenType.Comma */,
            [123 /* CharCode.OpenCurlyBrace */]: 3 /* TokenType.CurlyOpen */,
            [125 /* CharCode.CloseCurlyBrace */]: 4 /* TokenType.CurlyClose */,
            [92 /* CharCode.Backslash */]: 5 /* TokenType.Backslash */,
            [47 /* CharCode.Slash */]: 6 /* TokenType.Forwardslash */,
            [124 /* CharCode.Pipe */]: 7 /* TokenType.Pipe */,
            [43 /* CharCode.Plus */]: 11 /* TokenType.Plus */,
            [45 /* CharCode.Dash */]: 12 /* TokenType.Dash */,
            [63 /* CharCode.QuestionMark */]: 13 /* TokenType.QuestionMark */,
        }; }
        static isDigitCharacter(ch) {
            return ch >= 48 /* CharCode.Digit0 */ && ch <= 57 /* CharCode.Digit9 */;
        }
        static isVariableCharacter(ch) {
            return ch === 95 /* CharCode.Underline */
                || (ch >= 97 /* CharCode.a */ && ch <= 122 /* CharCode.z */)
                || (ch >= 65 /* CharCode.A */ && ch <= 90 /* CharCode.Z */);
        }
        text(value) {
            this.value = value;
            this.pos = 0;
        }
        tokenText(token) {
            return this.value.substr(token.pos, token.len);
        }
        next() {
            if (this.pos >= this.value.length) {
                return { type: 14 /* TokenType.EOF */, pos: this.pos, len: 0 };
            }
            const pos = this.pos;
            let len = 0;
            let ch = this.value.charCodeAt(pos);
            let type;
            // static types
            type = Scanner._table[ch];
            if (typeof type === 'number') {
                this.pos += 1;
                return { type, pos, len: 1 };
            }
            // number
            if (Scanner.isDigitCharacter(ch)) {
                type = 8 /* TokenType.Int */;
                do {
                    len += 1;
                    ch = this.value.charCodeAt(pos + len);
                } while (Scanner.isDigitCharacter(ch));
                this.pos += len;
                return { type, pos, len };
            }
            // variable name
            if (Scanner.isVariableCharacter(ch)) {
                type = 9 /* TokenType.VariableName */;
                do {
                    ch = this.value.charCodeAt(pos + (++len));
                } while (Scanner.isVariableCharacter(ch) || Scanner.isDigitCharacter(ch));
                this.pos += len;
                return { type, pos, len };
            }
            // format
            type = 10 /* TokenType.Format */;
            do {
                len += 1;
                ch = this.value.charCodeAt(pos + len);
            } while (!isNaN(ch)
                && typeof Scanner._table[ch] === 'undefined' // not static token
                && !Scanner.isDigitCharacter(ch) // not number
                && !Scanner.isVariableCharacter(ch) // not variable
            );
            this.pos += len;
            return { type, pos, len };
        }
    }
    exports.Scanner = Scanner;
    class Marker {
        constructor() {
            this._children = [];
        }
        appendChild(child) {
            if (child instanceof Text && this._children[this._children.length - 1] instanceof Text) {
                // this and previous child are text -> merge them
                this._children[this._children.length - 1].value += child.value;
            }
            else {
                // normal adoption of child
                child.parent = this;
                this._children.push(child);
            }
            return this;
        }
        replace(child, others) {
            const { parent } = child;
            const idx = parent.children.indexOf(child);
            const newChildren = parent.children.slice(0);
            newChildren.splice(idx, 1, ...others);
            parent._children = newChildren;
            (function _fixParent(children, parent) {
                for (const child of children) {
                    child.parent = parent;
                    _fixParent(child.children, child);
                }
            })(others, parent);
        }
        get children() {
            return this._children;
        }
        get rightMostDescendant() {
            if (this._children.length > 0) {
                return this._children[this._children.length - 1].rightMostDescendant;
            }
            return this;
        }
        get snippet() {
            let candidate = this;
            while (true) {
                if (!candidate) {
                    return undefined;
                }
                if (candidate instanceof TextmateSnippet) {
                    return candidate;
                }
                candidate = candidate.parent;
            }
        }
        toString() {
            return this.children.reduce((prev, cur) => prev + cur.toString(), '');
        }
        len() {
            return 0;
        }
    }
    exports.Marker = Marker;
    class Text extends Marker {
        constructor(value) {
            super();
            this.value = value;
        }
        toString() {
            return this.value;
        }
        len() {
            return this.value.length;
        }
        clone() {
            return new Text(this.value);
        }
    }
    exports.Text = Text;
    class TransformableMarker extends Marker {
    }
    exports.TransformableMarker = TransformableMarker;
    class Placeholder extends TransformableMarker {
        static compareByIndex(a, b) {
            if (a.index === b.index) {
                return 0;
            }
            else if (a.isFinalTabstop) {
                return 1;
            }
            else if (b.isFinalTabstop) {
                return -1;
            }
            else if (a.index < b.index) {
                return -1;
            }
            else if (a.index > b.index) {
                return 1;
            }
            else {
                return 0;
            }
        }
        constructor(index) {
            super();
            this.index = index;
        }
        get isFinalTabstop() {
            return this.index === 0;
        }
        get choice() {
            return this._children.length === 1 && this._children[0] instanceof Choice
                ? this._children[0]
                : undefined;
        }
        clone() {
            const ret = new Placeholder(this.index);
            if (this.transform) {
                ret.transform = this.transform.clone();
            }
            ret._children = this.children.map(child => child.clone());
            return ret;
        }
    }
    exports.Placeholder = Placeholder;
    class Choice extends Marker {
        constructor() {
            super(...arguments);
            this.options = [];
        }
        appendChild(marker) {
            if (marker instanceof Text) {
                marker.parent = this;
                this.options.push(marker);
            }
            return this;
        }
        toString() {
            return this.options[0].value;
        }
        len() {
            return this.options[0].len();
        }
        clone() {
            const ret = new Choice();
            this.options.forEach(ret.appendChild, ret);
            return ret;
        }
    }
    exports.Choice = Choice;
    class Transform extends Marker {
        constructor() {
            super(...arguments);
            this.regexp = new RegExp('');
        }
        resolve(value) {
            const _this = this;
            let didMatch = false;
            let ret = value.replace(this.regexp, function () {
                didMatch = true;
                return _this._replace(Array.prototype.slice.call(arguments, 0, -2));
            });
            // when the regex didn't match and when the transform has
            // else branches, then run those
            if (!didMatch && this._children.some(child => child instanceof FormatString && Boolean(child.elseValue))) {
                ret = this._replace([]);
            }
            return ret;
        }
        _replace(groups) {
            let ret = '';
            for (const marker of this._children) {
                if (marker instanceof FormatString) {
                    let value = groups[marker.index] || '';
                    value = marker.resolve(value);
                    ret += value;
                }
                else {
                    ret += marker.toString();
                }
            }
            return ret;
        }
        toString() {
            return '';
        }
        clone() {
            const ret = new Transform();
            ret.regexp = new RegExp(this.regexp.source, '' + (this.regexp.ignoreCase ? 'i' : '') + (this.regexp.global ? 'g' : ''));
            ret._children = this.children.map(child => child.clone());
            return ret;
        }
    }
    exports.Transform = Transform;
    class FormatString extends Marker {
        constructor(index, shorthandName, ifValue, elseValue) {
            super();
            this.index = index;
            this.shorthandName = shorthandName;
            this.ifValue = ifValue;
            this.elseValue = elseValue;
        }
        resolve(value) {
            if (this.shorthandName === 'upcase') {
                return !value ? '' : value.toLocaleUpperCase();
            }
            else if (this.shorthandName === 'downcase') {
                return !value ? '' : value.toLocaleLowerCase();
            }
            else if (this.shorthandName === 'capitalize') {
                return !value ? '' : (value[0].toLocaleUpperCase() + value.substr(1));
            }
            else if (this.shorthandName === 'pascalcase') {
                return !value ? '' : this._toPascalCase(value);
            }
            else if (this.shorthandName === 'camelcase') {
                return !value ? '' : this._toCamelCase(value);
            }
            else if (Boolean(value) && typeof this.ifValue === 'string') {
                return this.ifValue;
            }
            else if (!Boolean(value) && typeof this.elseValue === 'string') {
                return this.elseValue;
            }
            else {
                return value || '';
            }
        }
        _toPascalCase(value) {
            const match = value.match(/[a-z0-9]+/gi);
            if (!match) {
                return value;
            }
            return match.map(word => {
                return word.charAt(0).toUpperCase() + word.substr(1);
            })
                .join('');
        }
        _toCamelCase(value) {
            const match = value.match(/[a-z0-9]+/gi);
            if (!match) {
                return value;
            }
            return match.map((word, index) => {
                if (index === 0) {
                    return word.charAt(0).toLowerCase() + word.substr(1);
                }
                return word.charAt(0).toUpperCase() + word.substr(1);
            })
                .join('');
        }
        clone() {
            const ret = new FormatString(this.index, this.shorthandName, this.ifValue, this.elseValue);
            return ret;
        }
    }
    exports.FormatString = FormatString;
    class Variable extends TransformableMarker {
        constructor(name) {
            super();
            this.name = name;
        }
        resolve(resolver) {
            let value = resolver.resolve(this);
            if (this.transform) {
                value = this.transform.resolve(value || '');
            }
            if (value !== undefined) {
                this._children = [new Text(value)];
                return true;
            }
            return false;
        }
        clone() {
            const ret = new Variable(this.name);
            if (this.transform) {
                ret.transform = this.transform.clone();
            }
            ret._children = this.children.map(child => child.clone());
            return ret;
        }
    }
    exports.Variable = Variable;
    function walk(marker, visitor) {
        const stack = [...marker];
        while (stack.length > 0) {
            const marker = stack.shift();
            const recurse = visitor(marker);
            if (!recurse) {
                break;
            }
            stack.unshift(...marker.children);
        }
    }
    class TextmateSnippet extends Marker {
        get placeholderInfo() {
            if (!this._placeholders) {
                // fill in placeholders
                const all = [];
                let last;
                this.walk(function (candidate) {
                    if (candidate instanceof Placeholder) {
                        all.push(candidate);
                        last = !last || last.index < candidate.index ? candidate : last;
                    }
                    return true;
                });
                this._placeholders = { all, last };
            }
            return this._placeholders;
        }
        get placeholders() {
            const { all } = this.placeholderInfo;
            return all;
        }
        offset(marker) {
            let pos = 0;
            let found = false;
            this.walk(candidate => {
                if (candidate === marker) {
                    found = true;
                    return false;
                }
                pos += candidate.len();
                return true;
            });
            if (!found) {
                return -1;
            }
            return pos;
        }
        fullLen(marker) {
            let ret = 0;
            walk([marker], marker => {
                ret += marker.len();
                return true;
            });
            return ret;
        }
        enclosingPlaceholders(placeholder) {
            const ret = [];
            let { parent } = placeholder;
            while (parent) {
                if (parent instanceof Placeholder) {
                    ret.push(parent);
                }
                parent = parent.parent;
            }
            return ret;
        }
        resolveVariables(resolver) {
            this.walk(candidate => {
                if (candidate instanceof Variable) {
                    if (candidate.resolve(resolver)) {
                        this._placeholders = undefined;
                    }
                }
                return true;
            });
            return this;
        }
        appendChild(child) {
            this._placeholders = undefined;
            return super.appendChild(child);
        }
        replace(child, others) {
            this._placeholders = undefined;
            return super.replace(child, others);
        }
        clone() {
            const ret = new TextmateSnippet();
            this._children = this.children.map(child => child.clone());
            return ret;
        }
        walk(visitor) {
            walk(this.children, visitor);
        }
    }
    exports.TextmateSnippet = TextmateSnippet;
    class SnippetParser {
        constructor() {
            this._scanner = new Scanner();
            this._token = { type: 14 /* TokenType.EOF */, pos: 0, len: 0 };
        }
        static escape(value) {
            return value.replace(/\$|}|\\/g, '\\$&');
        }
        static guessNeedsClipboard(template) {
            return /\${?CLIPBOARD/.test(template);
        }
        parse(value, insertFinalTabstop, enforceFinalTabstop) {
            const snippet = new TextmateSnippet();
            this.parseFragment(value, snippet);
            this.ensureFinalTabstop(snippet, enforceFinalTabstop ?? false, insertFinalTabstop ?? false);
            return snippet;
        }
        parseFragment(value, snippet) {
            const offset = snippet.children.length;
            this._scanner.text(value);
            this._token = this._scanner.next();
            while (this._parse(snippet)) {
                // nothing
            }
            // fill in values for placeholders. the first placeholder of an index
            // that has a value defines the value for all placeholders with that index
            const placeholderDefaultValues = new Map();
            const incompletePlaceholders = [];
            snippet.walk(marker => {
                if (marker instanceof Placeholder) {
                    if (marker.isFinalTabstop) {
                        placeholderDefaultValues.set(0, undefined);
                    }
                    else if (!placeholderDefaultValues.has(marker.index) && marker.children.length > 0) {
                        placeholderDefaultValues.set(marker.index, marker.children);
                    }
                    else {
                        incompletePlaceholders.push(marker);
                    }
                }
                return true;
            });
            const fillInIncompletePlaceholder = (placeholder, stack) => {
                const defaultValues = placeholderDefaultValues.get(placeholder.index);
                if (!defaultValues) {
                    return;
                }
                const clone = new Placeholder(placeholder.index);
                clone.transform = placeholder.transform;
                for (const child of defaultValues) {
                    const newChild = child.clone();
                    clone.appendChild(newChild);
                    // "recurse" on children that are again placeholders
                    if (newChild instanceof Placeholder && placeholderDefaultValues.has(newChild.index) && !stack.has(newChild.index)) {
                        stack.add(newChild.index);
                        fillInIncompletePlaceholder(newChild, stack);
                        stack.delete(newChild.index);
                    }
                }
                snippet.replace(placeholder, [clone]);
            };
            const stack = new Set();
            for (const placeholder of incompletePlaceholders) {
                fillInIncompletePlaceholder(placeholder, stack);
            }
            return snippet.children.slice(offset);
        }
        ensureFinalTabstop(snippet, enforceFinalTabstop, insertFinalTabstop) {
            if (enforceFinalTabstop || insertFinalTabstop && snippet.placeholders.length > 0) {
                const finalTabstop = snippet.placeholders.find(p => p.index === 0);
                if (!finalTabstop) {
                    // the snippet uses placeholders but has no
                    // final tabstop defined -> insert at the end
                    snippet.appendChild(new Placeholder(0));
                }
            }
        }
        _accept(type, value) {
            if (type === undefined || this._token.type === type) {
                const ret = !value ? true : this._scanner.tokenText(this._token);
                this._token = this._scanner.next();
                return ret;
            }
            return false;
        }
        _backTo(token) {
            this._scanner.pos = token.pos + token.len;
            this._token = token;
            return false;
        }
        _until(type) {
            const start = this._token;
            while (this._token.type !== type) {
                if (this._token.type === 14 /* TokenType.EOF */) {
                    return false;
                }
                else if (this._token.type === 5 /* TokenType.Backslash */) {
                    const nextToken = this._scanner.next();
                    if (nextToken.type !== 0 /* TokenType.Dollar */
                        && nextToken.type !== 4 /* TokenType.CurlyClose */
                        && nextToken.type !== 5 /* TokenType.Backslash */) {
                        return false;
                    }
                }
                this._token = this._scanner.next();
            }
            const value = this._scanner.value.substring(start.pos, this._token.pos).replace(/\\(\$|}|\\)/g, '$1');
            this._token = this._scanner.next();
            return value;
        }
        _parse(marker) {
            return this._parseEscaped(marker)
                || this._parseTabstopOrVariableName(marker)
                || this._parseComplexPlaceholder(marker)
                || this._parseComplexVariable(marker)
                || this._parseAnything(marker);
        }
        // \$, \\, \} -> just text
        _parseEscaped(marker) {
            let value;
            if (value = this._accept(5 /* TokenType.Backslash */, true)) {
                // saw a backslash, append escaped token or that backslash
                value = this._accept(0 /* TokenType.Dollar */, true)
                    || this._accept(4 /* TokenType.CurlyClose */, true)
                    || this._accept(5 /* TokenType.Backslash */, true)
                    || value;
                marker.appendChild(new Text(value));
                return true;
            }
            return false;
        }
        // $foo -> variable, $1 -> tabstop
        _parseTabstopOrVariableName(parent) {
            let value;
            const token = this._token;
            const match = this._accept(0 /* TokenType.Dollar */)
                && (value = this._accept(9 /* TokenType.VariableName */, true) || this._accept(8 /* TokenType.Int */, true));
            if (!match) {
                return this._backTo(token);
            }
            parent.appendChild(/^\d+$/.test(value)
                ? new Placeholder(Number(value))
                : new Variable(value));
            return true;
        }
        // ${1:<children>}, ${1} -> placeholder
        _parseComplexPlaceholder(parent) {
            let index;
            const token = this._token;
            const match = this._accept(0 /* TokenType.Dollar */)
                && this._accept(3 /* TokenType.CurlyOpen */)
                && (index = this._accept(8 /* TokenType.Int */, true));
            if (!match) {
                return this._backTo(token);
            }
            const placeholder = new Placeholder(Number(index));
            if (this._accept(1 /* TokenType.Colon */)) {
                // ${1:<children>}
                while (true) {
                    // ...} -> done
                    if (this._accept(4 /* TokenType.CurlyClose */)) {
                        parent.appendChild(placeholder);
                        return true;
                    }
                    if (this._parse(placeholder)) {
                        continue;
                    }
                    // fallback
                    parent.appendChild(new Text('${' + index + ':'));
                    placeholder.children.forEach(parent.appendChild, parent);
                    return true;
                }
            }
            else if (placeholder.index > 0 && this._accept(7 /* TokenType.Pipe */)) {
                // ${1|one,two,three|}
                const choice = new Choice();
                while (true) {
                    if (this._parseChoiceElement(choice)) {
                        if (this._accept(2 /* TokenType.Comma */)) {
                            // opt, -> more
                            continue;
                        }
                        if (this._accept(7 /* TokenType.Pipe */)) {
                            placeholder.appendChild(choice);
                            if (this._accept(4 /* TokenType.CurlyClose */)) {
                                // ..|} -> done
                                parent.appendChild(placeholder);
                                return true;
                            }
                        }
                    }
                    this._backTo(token);
                    return false;
                }
            }
            else if (this._accept(6 /* TokenType.Forwardslash */)) {
                // ${1/<regex>/<format>/<options>}
                if (this._parseTransform(placeholder)) {
                    parent.appendChild(placeholder);
                    return true;
                }
                this._backTo(token);
                return false;
            }
            else if (this._accept(4 /* TokenType.CurlyClose */)) {
                // ${1}
                parent.appendChild(placeholder);
                return true;
            }
            else {
                // ${1 <- missing curly or colon
                return this._backTo(token);
            }
        }
        _parseChoiceElement(parent) {
            const token = this._token;
            const values = [];
            while (true) {
                if (this._token.type === 2 /* TokenType.Comma */ || this._token.type === 7 /* TokenType.Pipe */) {
                    break;
                }
                let value;
                if (value = this._accept(5 /* TokenType.Backslash */, true)) {
                    // \, \|, or \\
                    value = this._accept(2 /* TokenType.Comma */, true)
                        || this._accept(7 /* TokenType.Pipe */, true)
                        || this._accept(5 /* TokenType.Backslash */, true)
                        || value;
                }
                else {
                    value = this._accept(undefined, true);
                }
                if (!value) {
                    // EOF
                    this._backTo(token);
                    return false;
                }
                values.push(value);
            }
            if (values.length === 0) {
                this._backTo(token);
                return false;
            }
            parent.appendChild(new Text(values.join('')));
            return true;
        }
        // ${foo:<children>}, ${foo} -> variable
        _parseComplexVariable(parent) {
            let name;
            const token = this._token;
            const match = this._accept(0 /* TokenType.Dollar */)
                && this._accept(3 /* TokenType.CurlyOpen */)
                && (name = this._accept(9 /* TokenType.VariableName */, true));
            if (!match) {
                return this._backTo(token);
            }
            const variable = new Variable(name);
            if (this._accept(1 /* TokenType.Colon */)) {
                // ${foo:<children>}
                while (true) {
                    // ...} -> done
                    if (this._accept(4 /* TokenType.CurlyClose */)) {
                        parent.appendChild(variable);
                        return true;
                    }
                    if (this._parse(variable)) {
                        continue;
                    }
                    // fallback
                    parent.appendChild(new Text('${' + name + ':'));
                    variable.children.forEach(parent.appendChild, parent);
                    return true;
                }
            }
            else if (this._accept(6 /* TokenType.Forwardslash */)) {
                // ${foo/<regex>/<format>/<options>}
                if (this._parseTransform(variable)) {
                    parent.appendChild(variable);
                    return true;
                }
                this._backTo(token);
                return false;
            }
            else if (this._accept(4 /* TokenType.CurlyClose */)) {
                // ${foo}
                parent.appendChild(variable);
                return true;
            }
            else {
                // ${foo <- missing curly or colon
                return this._backTo(token);
            }
        }
        _parseTransform(parent) {
            // ...<regex>/<format>/<options>}
            const transform = new Transform();
            let regexValue = '';
            let regexOptions = '';
            // (1) /regex
            while (true) {
                if (this._accept(6 /* TokenType.Forwardslash */)) {
                    break;
                }
                let escaped;
                if (escaped = this._accept(5 /* TokenType.Backslash */, true)) {
                    escaped = this._accept(6 /* TokenType.Forwardslash */, true) || escaped;
                    regexValue += escaped;
                    continue;
                }
                if (this._token.type !== 14 /* TokenType.EOF */) {
                    regexValue += this._accept(undefined, true);
                    continue;
                }
                return false;
            }
            // (2) /format
            while (true) {
                if (this._accept(6 /* TokenType.Forwardslash */)) {
                    break;
                }
                let escaped;
                if (escaped = this._accept(5 /* TokenType.Backslash */, true)) {
                    escaped = this._accept(5 /* TokenType.Backslash */, true) || this._accept(6 /* TokenType.Forwardslash */, true) || escaped;
                    transform.appendChild(new Text(escaped));
                    continue;
                }
                if (this._parseFormatString(transform) || this._parseAnything(transform)) {
                    continue;
                }
                return false;
            }
            // (3) /option
            while (true) {
                if (this._accept(4 /* TokenType.CurlyClose */)) {
                    break;
                }
                if (this._token.type !== 14 /* TokenType.EOF */) {
                    regexOptions += this._accept(undefined, true);
                    continue;
                }
                return false;
            }
            try {
                transform.regexp = new RegExp(regexValue, regexOptions);
            }
            catch (e) {
                // invalid regexp
                return false;
            }
            parent.transform = transform;
            return true;
        }
        _parseFormatString(parent) {
            const token = this._token;
            if (!this._accept(0 /* TokenType.Dollar */)) {
                return false;
            }
            let complex = false;
            if (this._accept(3 /* TokenType.CurlyOpen */)) {
                complex = true;
            }
            const index = this._accept(8 /* TokenType.Int */, true);
            if (!index) {
                this._backTo(token);
                return false;
            }
            else if (!complex) {
                // $1
                parent.appendChild(new FormatString(Number(index)));
                return true;
            }
            else if (this._accept(4 /* TokenType.CurlyClose */)) {
                // ${1}
                parent.appendChild(new FormatString(Number(index)));
                return true;
            }
            else if (!this._accept(1 /* TokenType.Colon */)) {
                this._backTo(token);
                return false;
            }
            if (this._accept(6 /* TokenType.Forwardslash */)) {
                // ${1:/upcase}
                const shorthand = this._accept(9 /* TokenType.VariableName */, true);
                if (!shorthand || !this._accept(4 /* TokenType.CurlyClose */)) {
                    this._backTo(token);
                    return false;
                }
                else {
                    parent.appendChild(new FormatString(Number(index), shorthand));
                    return true;
                }
            }
            else if (this._accept(11 /* TokenType.Plus */)) {
                // ${1:+<if>}
                const ifValue = this._until(4 /* TokenType.CurlyClose */);
                if (ifValue) {
                    parent.appendChild(new FormatString(Number(index), undefined, ifValue, undefined));
                    return true;
                }
            }
            else if (this._accept(12 /* TokenType.Dash */)) {
                // ${2:-<else>}
                const elseValue = this._until(4 /* TokenType.CurlyClose */);
                if (elseValue) {
                    parent.appendChild(new FormatString(Number(index), undefined, undefined, elseValue));
                    return true;
                }
            }
            else if (this._accept(13 /* TokenType.QuestionMark */)) {
                // ${2:?<if>:<else>}
                const ifValue = this._until(1 /* TokenType.Colon */);
                if (ifValue) {
                    const elseValue = this._until(4 /* TokenType.CurlyClose */);
                    if (elseValue) {
                        parent.appendChild(new FormatString(Number(index), undefined, ifValue, elseValue));
                        return true;
                    }
                }
            }
            else {
                // ${1:<else>}
                const elseValue = this._until(4 /* TokenType.CurlyClose */);
                if (elseValue) {
                    parent.appendChild(new FormatString(Number(index), undefined, undefined, elseValue));
                    return true;
                }
            }
            this._backTo(token);
            return false;
        }
        _parseAnything(marker) {
            if (this._token.type !== 14 /* TokenType.EOF */) {
                marker.appendChild(new Text(this._scanner.tokenText(this._token)));
                this._accept(undefined);
                return true;
            }
            return false;
        }
    }
    exports.SnippetParser = SnippetParser;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[341/*vs/editor/contrib/stickyScroll/browser/stickyScrollElement*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.StickyModel = exports.StickyElement = exports.StickyRange = void 0;
    class StickyRange {
        constructor(startLineNumber, endLineNumber) {
            this.startLineNumber = startLineNumber;
            this.endLineNumber = endLineNumber;
        }
    }
    exports.StickyRange = StickyRange;
    class StickyElement {
        constructor(
        /**
         * Range of line numbers spanned by the current scope
         */
        range, 
        /**
         * Must be sorted by start line number
        */
        children, 
        /**
         * Parent sticky outline element
         */
        parent) {
            this.range = range;
            this.children = children;
            this.parent = parent;
        }
    }
    exports.StickyElement = StickyElement;
    class StickyModel {
        constructor(uri, version, element, outlineProviderId) {
            this.uri = uri;
            this.version = version;
            this.element = element;
            this.outlineProviderId = outlineProviderId;
        }
    }
    exports.StickyModel = StickyModel;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[342/*vs/editor/contrib/suggest/browser/completionModel*/], __M([1/*require*/,0/*exports*/,13/*vs/base/common/arrays*/,82/*vs/base/common/filters*/,11/*vs/base/common/strings*/]), function (require, exports, arrays_1, filters_1, strings_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CompletionModel = exports.LineContext = void 0;
    class LineContext {
        constructor(leadingLineContent, characterCountDelta) {
            this.leadingLineContent = leadingLineContent;
            this.characterCountDelta = characterCountDelta;
        }
    }
    exports.LineContext = LineContext;
    /**
     * Sorted, filtered completion view model
     * */
    class CompletionModel {
        constructor(items, column, lineContext, wordDistance, options, snippetSuggestions, fuzzyScoreOptions = filters_1.FuzzyScoreOptions.default, clipboardText = undefined) {
            this.clipboardText = clipboardText;
            this._snippetCompareFn = CompletionModel._compareCompletionItems;
            this._items = items;
            this._column = column;
            this._wordDistance = wordDistance;
            this._options = options;
            this._refilterKind = 1 /* Refilter.All */;
            this._lineContext = lineContext;
            this._fuzzyScoreOptions = fuzzyScoreOptions;
            if (snippetSuggestions === 'top') {
                this._snippetCompareFn = CompletionModel._compareCompletionItemsSnippetsUp;
            }
            else if (snippetSuggestions === 'bottom') {
                this._snippetCompareFn = CompletionModel._compareCompletionItemsSnippetsDown;
            }
        }
        get lineContext() {
            return this._lineContext;
        }
        set lineContext(value) {
            if (this._lineContext.leadingLineContent !== value.leadingLineContent
                || this._lineContext.characterCountDelta !== value.characterCountDelta) {
                this._refilterKind = this._lineContext.characterCountDelta < value.characterCountDelta && this._filteredItems ? 2 /* Refilter.Incr */ : 1 /* Refilter.All */;
                this._lineContext = value;
            }
        }
        get items() {
            this._ensureCachedState();
            return this._filteredItems;
        }
        getItemsByProvider() {
            this._ensureCachedState();
            return this._itemsByProvider;
        }
        getIncompleteProvider() {
            this._ensureCachedState();
            const result = new Set();
            for (const [provider, items] of this.getItemsByProvider()) {
                if (items.length > 0 && items[0].container.incomplete) {
                    result.add(provider);
                }
            }
            return result;
        }
        get stats() {
            this._ensureCachedState();
            return this._stats;
        }
        _ensureCachedState() {
            if (this._refilterKind !== 0 /* Refilter.Nothing */) {
                this._createCachedState();
            }
        }
        _createCachedState() {
            this._itemsByProvider = new Map();
            const labelLengths = [];
            const { leadingLineContent, characterCountDelta } = this._lineContext;
            let word = '';
            let wordLow = '';
            // incrementally filter less
            const source = this._refilterKind === 1 /* Refilter.All */ ? this._items : this._filteredItems;
            const target = [];
            // picks a score function based on the number of
            // items that we have to score/filter and based on the
            // user-configuration
            const scoreFn = (!this._options.filterGraceful || source.length > 2000) ? filters_1.fuzzyScore : filters_1.fuzzyScoreGracefulAggressive;
            for (let i = 0; i < source.length; i++) {
                const item = source[i];
                if (item.isInvalid) {
                    continue; // SKIP invalid items
                }
                // keep all items by their provider
                const arr = this._itemsByProvider.get(item.provider);
                if (arr) {
                    arr.push(item);
                }
                else {
                    this._itemsByProvider.set(item.provider, [item]);
                }
                // 'word' is that remainder of the current line that we
                // filter and score against. In theory each suggestion uses a
                // different word, but in practice not - that's why we cache
                const overwriteBefore = item.position.column - item.editStart.column;
                const wordLen = overwriteBefore + characterCountDelta - (item.position.column - this._column);
                if (word.length !== wordLen) {
                    word = wordLen === 0 ? '' : leadingLineContent.slice(-wordLen);
                    wordLow = word.toLowerCase();
                }
                // remember the word against which this item was
                // scored
                item.word = word;
                if (wordLen === 0) {
                    // when there is nothing to score against, don't
                    // event try to do. Use a const rank and rely on
                    // the fallback-sort using the initial sort order.
                    // use a score of `-100` because that is out of the
                    // bound of values `fuzzyScore` will return
                    item.score = filters_1.FuzzyScore.Default;
                }
                else {
                    // skip word characters that are whitespace until
                    // we have hit the replace range (overwriteBefore)
                    let wordPos = 0;
                    while (wordPos < overwriteBefore) {
                        const ch = word.charCodeAt(wordPos);
                        if (ch === 32 /* CharCode.Space */ || ch === 9 /* CharCode.Tab */) {
                            wordPos += 1;
                        }
                        else {
                            break;
                        }
                    }
                    if (wordPos >= wordLen) {
                        // the wordPos at which scoring starts is the whole word
                        // and therefore the same rules as not having a word apply
                        item.score = filters_1.FuzzyScore.Default;
                    }
                    else if (typeof item.completion.filterText === 'string') {
                        // when there is a `filterText` it must match the `word`.
                        // if it matches we check with the label to compute highlights
                        // and if that doesn't yield a result we have no highlights,
                        // despite having the match
                        const match = scoreFn(word, wordLow, wordPos, item.completion.filterText, item.filterTextLow, 0, this._fuzzyScoreOptions);
                        if (!match) {
                            continue; // NO match
                        }
                        if ((0, strings_1.compareIgnoreCase)(item.completion.filterText, item.textLabel) === 0) {
                            // filterText and label are actually the same -> use good highlights
                            item.score = match;
                        }
                        else {
                            // re-run the scorer on the label in the hope of a result BUT use the rank
                            // of the filterText-match
                            item.score = (0, filters_1.anyScore)(word, wordLow, wordPos, item.textLabel, item.labelLow, 0);
                            item.score[0] = match[0]; // use score from filterText
                        }
                    }
                    else {
                        // by default match `word` against the `label`
                        const match = scoreFn(word, wordLow, wordPos, item.textLabel, item.labelLow, 0, this._fuzzyScoreOptions);
                        if (!match) {
                            continue; // NO match
                        }
                        item.score = match;
                    }
                }
                item.idx = i;
                item.distance = this._wordDistance.distance(item.position, item.completion);
                target.push(item);
                // update stats
                labelLengths.push(item.textLabel.length);
            }
            this._filteredItems = target.sort(this._snippetCompareFn);
            this._refilterKind = 0 /* Refilter.Nothing */;
            this._stats = {
                pLabelLen: labelLengths.length ?
                    (0, arrays_1.quickSelect)(labelLengths.length - .85, labelLengths, (a, b) => a - b)
                    : 0
            };
        }
        static _compareCompletionItems(a, b) {
            if (a.score[0] > b.score[0]) {
                return -1;
            }
            else if (a.score[0] < b.score[0]) {
                return 1;
            }
            else if (a.distance < b.distance) {
                return -1;
            }
            else if (a.distance > b.distance) {
                return 1;
            }
            else if (a.idx < b.idx) {
                return -1;
            }
            else if (a.idx > b.idx) {
                return 1;
            }
            else {
                return 0;
            }
        }
        static _compareCompletionItemsSnippetsDown(a, b) {
            if (a.completion.kind !== b.completion.kind) {
                if (a.completion.kind === 27 /* CompletionItemKind.Snippet */) {
                    return 1;
                }
                else if (b.completion.kind === 27 /* CompletionItemKind.Snippet */) {
                    return -1;
                }
            }
            return CompletionModel._compareCompletionItems(a, b);
        }
        static _compareCompletionItemsSnippetsUp(a, b) {
            if (a.completion.kind !== b.completion.kind) {
                if (a.completion.kind === 27 /* CompletionItemKind.Snippet */) {
                    return -1;
                }
                else if (b.completion.kind === 27 /* CompletionItemKind.Snippet */) {
                    return 1;
                }
            }
            return CompletionModel._compareCompletionItems(a, b);
        }
    }
    exports.CompletionModel = CompletionModel;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[622/*vs/editor/contrib/suggest/browser/suggestCommitCharacters*/], __M([1/*require*/,0/*exports*/,13/*vs/base/common/arrays*/,2/*vs/base/common/lifecycle*/,144/*vs/editor/common/core/characterClassifier*/]), function (require, exports, arrays_1, lifecycle_1, characterClassifier_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CommitCharacterController = void 0;
    class CommitCharacterController {
        constructor(editor, widget, model, accept) {
            this._disposables = new lifecycle_1.DisposableStore();
            this._disposables.add(model.onDidSuggest(e => {
                if (e.completionModel.items.length === 0) {
                    this.reset();
                }
            }));
            this._disposables.add(model.onDidCancel(e => {
                this.reset();
            }));
            this._disposables.add(widget.onDidShow(() => this._onItem(widget.getFocusedItem())));
            this._disposables.add(widget.onDidFocus(this._onItem, this));
            this._disposables.add(widget.onDidHide(this.reset, this));
            this._disposables.add(editor.onWillType(text => {
                if (this._active && !widget.isFrozen() && model.state !== 0 /* State.Idle */) {
                    const ch = text.charCodeAt(text.length - 1);
                    if (this._active.acceptCharacters.has(ch) && editor.getOption(0 /* EditorOption.acceptSuggestionOnCommitCharacter */)) {
                        accept(this._active.item);
                    }
                }
            }));
        }
        _onItem(selected) {
            if (!selected || !(0, arrays_1.isNonEmptyArray)(selected.item.completion.commitCharacters)) {
                // no item or no commit characters
                this.reset();
                return;
            }
            if (this._active && this._active.item.item === selected.item) {
                // still the same item
                return;
            }
            // keep item and its commit characters
            const acceptCharacters = new characterClassifier_1.CharacterSet();
            for (const ch of selected.item.completion.commitCharacters) {
                if (ch.length > 0) {
                    acceptCharacters.add(ch.charCodeAt(0));
                }
            }
            this._active = { acceptCharacters, item: selected };
        }
        reset() {
            this._active = undefined;
        }
        dispose() {
            this._disposables.dispose();
        }
    }
    exports.CommitCharacterController = CommitCharacterController;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[623/*vs/editor/contrib/suggest/browser/suggestOvertypingCapturer*/], __M([1/*require*/,0/*exports*/,2/*vs/base/common/lifecycle*/]), function (require, exports, lifecycle_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.OvertypingCapturer = void 0;
    class OvertypingCapturer {
        static { this._maxSelectionLength = 51200; }
        constructor(editor, suggestModel) {
            this._disposables = new lifecycle_1.DisposableStore();
            this._lastOvertyped = [];
            this._locked = false;
            this._disposables.add(editor.onWillType(() => {
                if (this._locked || !editor.hasModel()) {
                    return;
                }
                const selections = editor.getSelections();
                const selectionsLength = selections.length;
                // Check if it will overtype any selections
                let willOvertype = false;
                for (let i = 0; i < selectionsLength; i++) {
                    if (!selections[i].isEmpty()) {
                        willOvertype = true;
                        break;
                    }
                }
                if (!willOvertype) {
                    if (this._lastOvertyped.length !== 0) {
                        this._lastOvertyped.length = 0;
                    }
                    return;
                }
                this._lastOvertyped = [];
                const model = editor.getModel();
                for (let i = 0; i < selectionsLength; i++) {
                    const selection = selections[i];
                    // Check for overtyping capturer restrictions
                    if (model.getValueLengthInRange(selection) > OvertypingCapturer._maxSelectionLength) {
                        return;
                    }
                    this._lastOvertyped[i] = { value: model.getValueInRange(selection), multiline: selection.startLineNumber !== selection.endLineNumber };
                }
            }));
            this._disposables.add(suggestModel.onDidTrigger(e => {
                this._locked = true;
            }));
            this._disposables.add(suggestModel.onDidCancel(e => {
                this._locked = false;
            }));
        }
        getLastOvertypedInfo(idx) {
            if (idx >= 0 && idx < this._lastOvertyped.length) {
                return this._lastOvertyped[idx];
            }
            return undefined;
        }
        dispose() {
            this._disposables.dispose();
        }
    }
    exports.OvertypingCapturer = OvertypingCapturer;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[343/*vs/editor/contrib/suggest/browser/wordDistance*/], __M([1/*require*/,0/*exports*/,13/*vs/base/common/arrays*/,4/*vs/editor/common/core/range*/,340/*vs/editor/contrib/smartSelect/browser/bracketSelections*/]), function (require, exports, arrays_1, range_1, bracketSelections_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.WordDistance = void 0;
    class WordDistance {
        static { this.None = new class extends WordDistance {
            distance() { return 0; }
        }; }
        static async create(service, editor) {
            if (!editor.getOption(119 /* EditorOption.suggest */).localityBonus) {
                return WordDistance.None;
            }
            if (!editor.hasModel()) {
                return WordDistance.None;
            }
            const model = editor.getModel();
            const position = editor.getPosition();
            if (!service.canComputeWordRanges(model.uri)) {
                return WordDistance.None;
            }
            const [ranges] = await new bracketSelections_1.BracketSelectionRangeProvider().provideSelectionRanges(model, [position]);
            if (ranges.length === 0) {
                return WordDistance.None;
            }
            const wordRanges = await service.computeWordRanges(model.uri, ranges[0].range);
            if (!wordRanges) {
                return WordDistance.None;
            }
            // remove current word
            const wordUntilPos = model.getWordUntilPosition(position);
            delete wordRanges[wordUntilPos.word];
            return new class extends WordDistance {
                distance(anchor, item) {
                    if (!position.equals(editor.getPosition())) {
                        return 0;
                    }
                    if (item.kind === 17 /* CompletionItemKind.Keyword */) {
                        return 2 << 20;
                    }
                    const word = typeof item.label === 'string' ? item.label : item.label.label;
                    const wordLines = wordRanges[word];
                    if ((0, arrays_1.isFalsyOrEmpty)(wordLines)) {
                        return 2 << 20;
                    }
                    const idx = (0, arrays_1.binarySearch)(wordLines, range_1.Range.fromPositions(anchor), range_1.Range.compareRangesUsingStarts);
                    const bestWordRange = idx >= 0 ? wordLines[idx] : wordLines[Math.max(0, ~idx - 1)];
                    let blockDistance = ranges.length;
                    for (const range of ranges) {
                        if (!range_1.Range.containsRange(range.range, bestWordRange)) {
                            break;
                        }
                        blockDistance -= 1;
                    }
                    return blockDistance;
                }
            };
        }
    }
    exports.WordDistance = WordDistance;
});

define(__m[624/*vs/editor/standalone/browser/standaloneTreeSitterService*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.StandaloneTreeSitterParserService = void 0;
    /**
     * The monaco build doesn't like the dynamic import of tree sitter in the real service.
     * We use a dummy sertive here to make the build happy.
     */
    class StandaloneTreeSitterParserService {
        getParseResult(textModel) {
            return undefined;
        }
    }
    exports.StandaloneTreeSitterParserService = StandaloneTreeSitterParserService;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[344/*vs/editor/standalone/common/monarch/monarchCommon*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.isFuzzyActionArr = isFuzzyActionArr;
    exports.isFuzzyAction = isFuzzyAction;
    exports.isString = isString;
    exports.isIAction = isIAction;
    exports.empty = empty;
    exports.fixCase = fixCase;
    exports.sanitize = sanitize;
    exports.log = log;
    exports.createError = createError;
    exports.substituteMatches = substituteMatches;
    exports.substituteMatchesRe = substituteMatchesRe;
    exports.findRules = findRules;
    exports.stateExists = stateExists;
    function isFuzzyActionArr(what) {
        return (Array.isArray(what));
    }
    function isFuzzyAction(what) {
        return !isFuzzyActionArr(what);
    }
    function isString(what) {
        return (typeof what === 'string');
    }
    function isIAction(what) {
        return !isString(what);
    }
    // Small helper functions
    /**
     * Is a string null, undefined, or empty?
     */
    function empty(s) {
        return (s ? false : true);
    }
    /**
     * Puts a string to lower case if 'ignoreCase' is set.
     */
    function fixCase(lexer, str) {
        return (lexer.ignoreCase && str ? str.toLowerCase() : str);
    }
    /**
     * Ensures there are no bad characters in a CSS token class.
     */
    function sanitize(s) {
        return s.replace(/[&<>'"_]/g, '-'); // used on all output token CSS classes
    }
    // Logging
    /**
     * Logs a message.
     */
    function log(lexer, msg) {
        console.log(`${lexer.languageId}: ${msg}`);
    }
    // Throwing errors
    function createError(lexer, msg) {
        return new Error(`${lexer.languageId}: ${msg}`);
    }
    // Helper functions for rule finding and substitution
    /**
     * substituteMatches is used on lexer strings and can substitutes predefined patterns:
     * 		$$  => $
     * 		$#  => id
     * 		$n  => matched entry n
     * 		@attr => contents of lexer[attr]
     *
     * See documentation for more info
     */
    function substituteMatches(lexer, str, id, matches, state) {
        const re = /\$((\$)|(#)|(\d\d?)|[sS](\d\d?)|@(\w+))/g;
        let stateMatches = null;
        return str.replace(re, function (full, sub, dollar, hash, n, s, attr, ofs, total) {
            if (!empty(dollar)) {
                return '$'; // $$
            }
            if (!empty(hash)) {
                return fixCase(lexer, id); // default $#
            }
            if (!empty(n) && n < matches.length) {
                return fixCase(lexer, matches[n]); // $n
            }
            if (!empty(attr) && lexer && typeof (lexer[attr]) === 'string') {
                return lexer[attr]; //@attribute
            }
            if (stateMatches === null) { // split state on demand
                stateMatches = state.split('.');
                stateMatches.unshift(state);
            }
            if (!empty(s) && s < stateMatches.length) {
                return fixCase(lexer, stateMatches[s]); //$Sn
            }
            return '';
        });
    }
    /**
     * substituteMatchesRe is used on lexer regex rules and can substitutes predefined patterns:
     * 		$Sn => n'th part of state
     *
     */
    function substituteMatchesRe(lexer, str, state) {
        const re = /\$[sS](\d\d?)/g;
        let stateMatches = null;
        return str.replace(re, function (full, s) {
            if (stateMatches === null) { // split state on demand
                stateMatches = state.split('.');
                stateMatches.unshift(state);
            }
            if (!empty(s) && s < stateMatches.length) {
                return fixCase(lexer, stateMatches[s]); //$Sn
            }
            return '';
        });
    }
    /**
     * Find the tokenizer rules for a specific state (i.e. next action)
     */
    function findRules(lexer, inState) {
        let state = inState;
        while (state && state.length > 0) {
            const rules = lexer.tokenizer[state];
            if (rules) {
                return rules;
            }
            const idx = state.lastIndexOf('.');
            if (idx < 0) {
                state = null; // no further parent
            }
            else {
                state = state.substr(0, idx);
            }
        }
        return null;
    }
    /**
     * Is a certain state defined? In contrast to 'findRules' this works on a ILexerMin.
     * This is used during compilation where we may know the defined states
     * but not yet whether the corresponding rules are correct.
     */
    function stateExists(lexer, inState) {
        let state = inState;
        while (state && state.length > 0) {
            const exist = lexer.stateNames[state];
            if (exist) {
                return true;
            }
            const idx = state.lastIndexOf('.');
            if (idx < 0) {
                state = null; // no further parent
            }
            else {
                state = state.substr(0, idx);
            }
        }
        return false;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[625/*vs/editor/standalone/common/monarch/monarchCompile*/], __M([1/*require*/,0/*exports*/,344/*vs/editor/standalone/common/monarch/monarchCommon*/]), function (require, exports, monarchCommon) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.compile = compile;
    /*
     * Type helpers
     *
     * Note: this is just for sanity checks on the JSON description which is
     * helpful for the programmer. No checks are done anymore once the lexer is
     * already 'compiled and checked'.
     *
     */
    function isArrayOf(elemType, obj) {
        if (!obj) {
            return false;
        }
        if (!(Array.isArray(obj))) {
            return false;
        }
        for (const el of obj) {
            if (!(elemType(el))) {
                return false;
            }
        }
        return true;
    }
    function bool(prop, defValue) {
        if (typeof prop === 'boolean') {
            return prop;
        }
        return defValue;
    }
    function string(prop, defValue) {
        if (typeof (prop) === 'string') {
            return prop;
        }
        return defValue;
    }
    function arrayToHash(array) {
        const result = {};
        for (const e of array) {
            result[e] = true;
        }
        return result;
    }
    function createKeywordMatcher(arr, caseInsensitive = false) {
        if (caseInsensitive) {
            arr = arr.map(function (x) { return x.toLowerCase(); });
        }
        const hash = arrayToHash(arr);
        if (caseInsensitive) {
            return function (word) {
                return hash[word.toLowerCase()] !== undefined && hash.hasOwnProperty(word.toLowerCase());
            };
        }
        else {
            return function (word) {
                return hash[word] !== undefined && hash.hasOwnProperty(word);
            };
        }
    }
    function compileRegExp(lexer, str, handleSn) {
        // @@ must be interpreted as a literal @, so we replace all occurences of @@ with a placeholder character
        str = str.replace(/@@/g, `\x01`);
        let n = 0;
        let hadExpansion;
        do {
            hadExpansion = false;
            str = str.replace(/@(\w+)/g, function (s, attr) {
                hadExpansion = true;
                let sub = '';
                if (typeof (lexer[attr]) === 'string') {
                    sub = lexer[attr];
                }
                else if (lexer[attr] && lexer[attr] instanceof RegExp) {
                    sub = lexer[attr].source;
                }
                else {
                    if (lexer[attr] === undefined) {
                        throw monarchCommon.createError(lexer, 'language definition does not contain attribute \'' + attr + '\', used at: ' + str);
                    }
                    else {
                        throw monarchCommon.createError(lexer, 'attribute reference \'' + attr + '\' must be a string, used at: ' + str);
                    }
                }
                return (monarchCommon.empty(sub) ? '' : '(?:' + sub + ')');
            });
            n++;
        } while (hadExpansion && n < 5);
        // handle escaped @@
        str = str.replace(/\x01/g, '@');
        const flags = (lexer.ignoreCase ? 'i' : '') + (lexer.unicode ? 'u' : '');
        // handle $Sn
        if (handleSn) {
            const match = str.match(/\$[sS](\d\d?)/g);
            if (match) {
                let lastState = null;
                let lastRegEx = null;
                return (state) => {
                    if (lastRegEx && lastState === state) {
                        return lastRegEx;
                    }
                    lastState = state;
                    lastRegEx = new RegExp(monarchCommon.substituteMatchesRe(lexer, str, state), flags);
                    return lastRegEx;
                };
            }
        }
        return new RegExp(str, flags);
    }
    /**
     * Compiles guard functions for case matches.
     * This compiles 'cases' attributes into efficient match functions.
     *
     */
    function selectScrutinee(id, matches, state, num) {
        if (num < 0) {
            return id;
        }
        if (num < matches.length) {
            return matches[num];
        }
        if (num >= 100) {
            num = num - 100;
            const parts = state.split('.');
            parts.unshift(state);
            if (num < parts.length) {
                return parts[num];
            }
        }
        return null;
    }
    function createGuard(lexer, ruleName, tkey, val) {
        // get the scrutinee and pattern
        let scrut = -1; // -1: $!, 0-99: $n, 100+n: $Sn
        let oppat = tkey;
        let matches = tkey.match(/^\$(([sS]?)(\d\d?)|#)(.*)$/);
        if (matches) {
            if (matches[3]) { // if digits
                scrut = parseInt(matches[3]);
                if (matches[2]) {
                    scrut = scrut + 100; // if [sS] present
                }
            }
            oppat = matches[4];
        }
        // get operator
        let op = '~';
        let pat = oppat;
        if (!oppat || oppat.length === 0) {
            op = '!=';
            pat = '';
        }
        else if (/^\w*$/.test(pat)) { // just a word
            op = '==';
        }
        else {
            matches = oppat.match(/^(@|!@|~|!~|==|!=)(.*)$/);
            if (matches) {
                op = matches[1];
                pat = matches[2];
            }
        }
        // set the tester function
        let tester;
        // special case a regexp that matches just words
        if ((op === '~' || op === '!~') && /^(\w|\|)*$/.test(pat)) {
            const inWords = createKeywordMatcher(pat.split('|'), lexer.ignoreCase);
            tester = function (s) { return (op === '~' ? inWords(s) : !inWords(s)); };
        }
        else if (op === '@' || op === '!@') {
            const words = lexer[pat];
            if (!words) {
                throw monarchCommon.createError(lexer, 'the @ match target \'' + pat + '\' is not defined, in rule: ' + ruleName);
            }
            if (!(isArrayOf(function (elem) { return (typeof (elem) === 'string'); }, words))) {
                throw monarchCommon.createError(lexer, 'the @ match target \'' + pat + '\' must be an array of strings, in rule: ' + ruleName);
            }
            const inWords = createKeywordMatcher(words, lexer.ignoreCase);
            tester = function (s) { return (op === '@' ? inWords(s) : !inWords(s)); };
        }
        else if (op === '~' || op === '!~') {
            if (pat.indexOf('$') < 0) {
                // precompile regular expression
                const re = compileRegExp(lexer, '^' + pat + '$', false);
                tester = function (s) { return (op === '~' ? re.test(s) : !re.test(s)); };
            }
            else {
                tester = function (s, id, matches, state) {
                    const re = compileRegExp(lexer, '^' + monarchCommon.substituteMatches(lexer, pat, id, matches, state) + '$', false);
                    return re.test(s);
                };
            }
        }
        else { // if (op==='==' || op==='!=') {
            if (pat.indexOf('$') < 0) {
                const patx = monarchCommon.fixCase(lexer, pat);
                tester = function (s) { return (op === '==' ? s === patx : s !== patx); };
            }
            else {
                const patx = monarchCommon.fixCase(lexer, pat);
                tester = function (s, id, matches, state, eos) {
                    const patexp = monarchCommon.substituteMatches(lexer, patx, id, matches, state);
                    return (op === '==' ? s === patexp : s !== patexp);
                };
            }
        }
        // return the branch object
        if (scrut === -1) {
            return {
                name: tkey, value: val, test: function (id, matches, state, eos) {
                    return tester(id, id, matches, state, eos);
                }
            };
        }
        else {
            return {
                name: tkey, value: val, test: function (id, matches, state, eos) {
                    const scrutinee = selectScrutinee(id, matches, state, scrut);
                    return tester(!scrutinee ? '' : scrutinee, id, matches, state, eos);
                }
            };
        }
    }
    /**
     * Compiles an action: i.e. optimize regular expressions and case matches
     * and do many sanity checks.
     *
     * This is called only during compilation but if the lexer definition
     * contains user functions as actions (which is usually not allowed), then this
     * may be called during lexing. It is important therefore to compile common cases efficiently
     */
    function compileAction(lexer, ruleName, action) {
        if (!action) {
            return { token: '' };
        }
        else if (typeof (action) === 'string') {
            return action; // { token: action };
        }
        else if (action.token || action.token === '') {
            if (typeof (action.token) !== 'string') {
                throw monarchCommon.createError(lexer, 'a \'token\' attribute must be of type string, in rule: ' + ruleName);
            }
            else {
                // only copy specific typed fields (only happens once during compile Lexer)
                const newAction = { token: action.token };
                if (action.token.indexOf('$') >= 0) {
                    newAction.tokenSubst = true;
                }
                if (typeof (action.bracket) === 'string') {
                    if (action.bracket === '@open') {
                        newAction.bracket = 1 /* monarchCommon.MonarchBracket.Open */;
                    }
                    else if (action.bracket === '@close') {
                        newAction.bracket = -1 /* monarchCommon.MonarchBracket.Close */;
                    }
                    else {
                        throw monarchCommon.createError(lexer, 'a \'bracket\' attribute must be either \'@open\' or \'@close\', in rule: ' + ruleName);
                    }
                }
                if (action.next) {
                    if (typeof (action.next) !== 'string') {
                        throw monarchCommon.createError(lexer, 'the next state must be a string value in rule: ' + ruleName);
                    }
                    else {
                        let next = action.next;
                        if (!/^(@pop|@push|@popall)$/.test(next)) {
                            if (next[0] === '@') {
                                next = next.substr(1); // peel off starting @ sign
                            }
                            if (next.indexOf('$') < 0) { // no dollar substitution, we can check if the state exists
                                if (!monarchCommon.stateExists(lexer, monarchCommon.substituteMatches(lexer, next, '', [], ''))) {
                                    throw monarchCommon.createError(lexer, 'the next state \'' + action.next + '\' is not defined in rule: ' + ruleName);
                                }
                            }
                        }
                        newAction.next = next;
                    }
                }
                if (typeof (action.goBack) === 'number') {
                    newAction.goBack = action.goBack;
                }
                if (typeof (action.switchTo) === 'string') {
                    newAction.switchTo = action.switchTo;
                }
                if (typeof (action.log) === 'string') {
                    newAction.log = action.log;
                }
                if (typeof (action.nextEmbedded) === 'string') {
                    newAction.nextEmbedded = action.nextEmbedded;
                    lexer.usesEmbedded = true;
                }
                return newAction;
            }
        }
        else if (Array.isArray(action)) {
            const results = [];
            for (let i = 0, len = action.length; i < len; i++) {
                results[i] = compileAction(lexer, ruleName, action[i]);
            }
            return { group: results };
        }
        else if (action.cases) {
            // build an array of test cases
            const cases = [];
            // for each case, push a test function and result value
            for (const tkey in action.cases) {
                if (action.cases.hasOwnProperty(tkey)) {
                    const val = compileAction(lexer, ruleName, action.cases[tkey]);
                    // what kind of case
                    if (tkey === '@default' || tkey === '@' || tkey === '') {
                        cases.push({ test: undefined, value: val, name: tkey });
                    }
                    else if (tkey === '@eos') {
                        cases.push({ test: function (id, matches, state, eos) { return eos; }, value: val, name: tkey });
                    }
                    else {
                        cases.push(createGuard(lexer, ruleName, tkey, val)); // call separate function to avoid local variable capture
                    }
                }
            }
            // create a matching function
            const def = lexer.defaultToken;
            return {
                test: function (id, matches, state, eos) {
                    for (const _case of cases) {
                        const didmatch = (!_case.test || _case.test(id, matches, state, eos));
                        if (didmatch) {
                            return _case.value;
                        }
                    }
                    return def;
                }
            };
        }
        else {
            throw monarchCommon.createError(lexer, 'an action must be a string, an object with a \'token\' or \'cases\' attribute, or an array of actions; in rule: ' + ruleName);
        }
    }
    /**
     * Helper class for creating matching rules
     */
    class Rule {
        constructor(name) {
            this.regex = new RegExp('');
            this.action = { token: '' };
            this.matchOnlyAtLineStart = false;
            this.name = '';
            this.name = name;
        }
        setRegex(lexer, re) {
            let sregex;
            if (typeof (re) === 'string') {
                sregex = re;
            }
            else if (re instanceof RegExp) {
                sregex = re.source;
            }
            else {
                throw monarchCommon.createError(lexer, 'rules must start with a match string or regular expression: ' + this.name);
            }
            this.matchOnlyAtLineStart = (sregex.length > 0 && sregex[0] === '^');
            this.name = this.name + ': ' + sregex;
            this.regex = compileRegExp(lexer, '^(?:' + (this.matchOnlyAtLineStart ? sregex.substr(1) : sregex) + ')', true);
        }
        setAction(lexer, act) {
            this.action = compileAction(lexer, this.name, act);
        }
        resolveRegex(state) {
            if (this.regex instanceof RegExp) {
                return this.regex;
            }
            else {
                return this.regex(state);
            }
        }
    }
    /**
     * Compiles a json description function into json where all regular expressions,
     * case matches etc, are compiled and all include rules are expanded.
     * We also compile the bracket definitions, supply defaults, and do many sanity checks.
     * If the 'jsonStrict' parameter is 'false', we allow at certain locations
     * regular expression objects and functions that get called during lexing.
     * (Currently we have no samples that need this so perhaps we should always have
     * jsonStrict to true).
     */
    function compile(languageId, json) {
        if (!json || typeof (json) !== 'object') {
            throw new Error('Monarch: expecting a language definition object');
        }
        // Create our lexer
        const lexer = {
            languageId: languageId,
            includeLF: bool(json.includeLF, false),
            noThrow: false, // raise exceptions during compilation
            maxStack: 100,
            start: (typeof json.start === 'string' ? json.start : null),
            ignoreCase: bool(json.ignoreCase, false),
            unicode: bool(json.unicode, false),
            tokenPostfix: string(json.tokenPostfix, '.' + languageId),
            defaultToken: string(json.defaultToken, 'source'),
            usesEmbedded: false, // becomes true if we find a nextEmbedded action
            stateNames: {},
            tokenizer: {},
            brackets: []
        };
        // For calling compileAction later on
        const lexerMin = json;
        lexerMin.languageId = languageId;
        lexerMin.includeLF = lexer.includeLF;
        lexerMin.ignoreCase = lexer.ignoreCase;
        lexerMin.unicode = lexer.unicode;
        lexerMin.noThrow = lexer.noThrow;
        lexerMin.usesEmbedded = lexer.usesEmbedded;
        lexerMin.stateNames = json.tokenizer;
        lexerMin.defaultToken = lexer.defaultToken;
        // Compile an array of rules into newrules where RegExp objects are created.
        function addRules(state, newrules, rules) {
            for (const rule of rules) {
                let include = rule.include;
                if (include) {
                    if (typeof (include) !== 'string') {
                        throw monarchCommon.createError(lexer, 'an \'include\' attribute must be a string at: ' + state);
                    }
                    if (include[0] === '@') {
                        include = include.substr(1); // peel off starting @
                    }
                    if (!json.tokenizer[include]) {
                        throw monarchCommon.createError(lexer, 'include target \'' + include + '\' is not defined at: ' + state);
                    }
                    addRules(state + '.' + include, newrules, json.tokenizer[include]);
                }
                else {
                    const newrule = new Rule(state);
                    // Set up new rule attributes
                    if (Array.isArray(rule) && rule.length >= 1 && rule.length <= 3) {
                        newrule.setRegex(lexerMin, rule[0]);
                        if (rule.length >= 3) {
                            if (typeof (rule[1]) === 'string') {
                                newrule.setAction(lexerMin, { token: rule[1], next: rule[2] });
                            }
                            else if (typeof (rule[1]) === 'object') {
                                const rule1 = rule[1];
                                rule1.next = rule[2];
                                newrule.setAction(lexerMin, rule1);
                            }
                            else {
                                throw monarchCommon.createError(lexer, 'a next state as the last element of a rule can only be given if the action is either an object or a string, at: ' + state);
                            }
                        }
                        else {
                            newrule.setAction(lexerMin, rule[1]);
                        }
                    }
                    else {
                        if (!rule.regex) {
                            throw monarchCommon.createError(lexer, 'a rule must either be an array, or an object with a \'regex\' or \'include\' field at: ' + state);
                        }
                        if (rule.name) {
                            if (typeof rule.name === 'string') {
                                newrule.name = rule.name;
                            }
                        }
                        if (rule.matchOnlyAtStart) {
                            newrule.matchOnlyAtLineStart = bool(rule.matchOnlyAtLineStart, false);
                        }
                        newrule.setRegex(lexerMin, rule.regex);
                        newrule.setAction(lexerMin, rule.action);
                    }
                    newrules.push(newrule);
                }
            }
        }
        // compile the tokenizer rules
        if (!json.tokenizer || typeof (json.tokenizer) !== 'object') {
            throw monarchCommon.createError(lexer, 'a language definition must define the \'tokenizer\' attribute as an object');
        }
        lexer.tokenizer = [];
        for (const key in json.tokenizer) {
            if (json.tokenizer.hasOwnProperty(key)) {
                if (!lexer.start) {
                    lexer.start = key;
                }
                const rules = json.tokenizer[key];
                lexer.tokenizer[key] = new Array();
                addRules('tokenizer.' + key, lexer.tokenizer[key], rules);
            }
        }
        lexer.usesEmbedded = lexerMin.usesEmbedded; // can be set during compileAction
        // Set simple brackets
        if (json.brackets) {
            if (!(Array.isArray(json.brackets))) {
                throw monarchCommon.createError(lexer, 'the \'brackets\' attribute must be defined as an array');
            }
        }
        else {
            json.brackets = [
                { open: '{', close: '}', token: 'delimiter.curly' },
                { open: '[', close: ']', token: 'delimiter.square' },
                { open: '(', close: ')', token: 'delimiter.parenthesis' },
                { open: '<', close: '>', token: 'delimiter.angle' }
            ];
        }
        const brackets = [];
        for (const el of json.brackets) {
            let desc = el;
            if (desc && Array.isArray(desc) && desc.length === 3) {
                desc = { token: desc[2], open: desc[0], close: desc[1] };
            }
            if (desc.open === desc.close) {
                throw monarchCommon.createError(lexer, 'open and close brackets in a \'brackets\' attribute must be different: ' + desc.open +
                    '\n hint: use the \'bracket\' attribute if matching on equal brackets is required.');
            }
            if (typeof desc.open === 'string' && typeof desc.token === 'string' && typeof desc.close === 'string') {
                brackets.push({
                    token: desc.token + lexer.tokenPostfix,
                    open: monarchCommon.fixCase(lexer, desc.open),
                    close: monarchCommon.fixCase(lexer, desc.close)
                });
            }
            else {
                throw monarchCommon.createError(lexer, 'every element in the \'brackets\' array must be a \'{open,close,token}\' object or array');
            }
        }
        lexer.brackets = brackets;
        // Disable throw so the syntax highlighter goes, no matter what
        lexer.noThrow = true;
        return lexer;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[345/*vs/nls.messages*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.getNLSMessages = getNLSMessages;
    exports.getNLSLanguage = getNLSLanguage;
    /*
     * This module exists so that the AMD build of the monaco editor can replace this with an async loader plugin.
     * If you add new functions to this module make sure that they are also provided in the AMD build of the monaco editor.
     */
    function getNLSMessages() {
        return globalThis._VSCODE_NLS_MESSAGES;
    }
    function getNLSLanguage() {
        return globalThis._VSCODE_NLS_LANGUAGE;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[3/*vs/nls*/], __M([1/*require*/,0/*exports*/,345/*vs/nls.messages*/,345/*vs/nls.messages*/]), function (require, exports, nls_messages_1, nls_messages_2) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.getNLSMessages = exports.getNLSLanguage = void 0;
    exports.localize = localize;
    exports.localize2 = localize2;
    Object.defineProperty(exports, "getNLSLanguage", { enumerable: true, get: function () { return nls_messages_2.getNLSLanguage; } });
    Object.defineProperty(exports, "getNLSMessages", { enumerable: true, get: function () { return nls_messages_2.getNLSMessages; } });
    const isPseudo = (0, nls_messages_1.getNLSLanguage)() === 'pseudo' || (typeof document !== 'undefined' && document.location && document.location.hash.indexOf('pseudo=true') >= 0);
    function _format(message, args) {
        let result;
        if (args.length === 0) {
            result = message;
        }
        else {
            result = message.replace(/\{(\d+)\}/g, (match, rest) => {
                const index = rest[0];
                const arg = args[index];
                let result = match;
                if (typeof arg === 'string') {
                    result = arg;
                }
                else if (typeof arg === 'number' || typeof arg === 'boolean' || arg === void 0 || arg === null) {
                    result = String(arg);
                }
                return result;
            });
        }
        if (isPseudo) {
            // FF3B and FF3D is the Unicode zenkaku representation for [ and ]
            result = '\uFF3B' + result.replace(/[aouei]/g, '$&$&') + '\uFF3D';
        }
        return result;
    }
    /**
     * @skipMangle
     */
    function localize(data /* | number when built */, message /* | null when built */, ...args) {
        if (typeof data === 'number') {
            return _format(lookupMessage(data, message), args);
        }
        return _format(message, args);
    }
    /**
     * Only used when built: Looks up the message in the global NLS table.
     * This table is being made available as a global through bootstrapping
     * depending on the target context.
     */
    function lookupMessage(index, fallback) {
        const message = (0, nls_messages_1.getNLSMessages)()?.[index];
        if (typeof message !== 'string') {
            if (typeof fallback === 'string') {
                return fallback;
            }
            throw new Error(`!!! NLS MISSING: ${index} !!!`);
        }
        return message;
    }
    /**
     * @skipMangle
     */
    function localize2(data /* | number when built */, originalMessage, ...args) {
        let message;
        if (typeof data === 'number') {
            message = lookupMessage(data, originalMessage);
        }
        else {
            message = originalMessage;
        }
        const value = _format(message, args);
        return {
            value,
            original: originalMessage === message ? value : _format(originalMessage, args)
        };
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[41/*vs/base/common/actions*/], __M([1/*require*/,0/*exports*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,3/*vs/nls*/]), function (require, exports, event_1, lifecycle_1, nls) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.EmptySubmenuAction = exports.SubmenuAction = exports.Separator = exports.ActionRunner = exports.Action = void 0;
    exports.toAction = toAction;
    class Action extends lifecycle_1.Disposable {
        constructor(id, label = '', cssClass = '', enabled = true, actionCallback) {
            super();
            this._onDidChange = this._register(new event_1.Emitter());
            this.onDidChange = this._onDidChange.event;
            this._enabled = true;
            this._id = id;
            this._label = label;
            this._cssClass = cssClass;
            this._enabled = enabled;
            this._actionCallback = actionCallback;
        }
        get id() {
            return this._id;
        }
        get label() {
            return this._label;
        }
        set label(value) {
            this._setLabel(value);
        }
        _setLabel(value) {
            if (this._label !== value) {
                this._label = value;
                this._onDidChange.fire({ label: value });
            }
        }
        get tooltip() {
            return this._tooltip || '';
        }
        set tooltip(value) {
            this._setTooltip(value);
        }
        _setTooltip(value) {
            if (this._tooltip !== value) {
                this._tooltip = value;
                this._onDidChange.fire({ tooltip: value });
            }
        }
        get class() {
            return this._cssClass;
        }
        set class(value) {
            this._setClass(value);
        }
        _setClass(value) {
            if (this._cssClass !== value) {
                this._cssClass = value;
                this._onDidChange.fire({ class: value });
            }
        }
        get enabled() {
            return this._enabled;
        }
        set enabled(value) {
            this._setEnabled(value);
        }
        _setEnabled(value) {
            if (this._enabled !== value) {
                this._enabled = value;
                this._onDidChange.fire({ enabled: value });
            }
        }
        get checked() {
            return this._checked;
        }
        set checked(value) {
            this._setChecked(value);
        }
        _setChecked(value) {
            if (this._checked !== value) {
                this._checked = value;
                this._onDidChange.fire({ checked: value });
            }
        }
        async run(event, data) {
            if (this._actionCallback) {
                await this._actionCallback(event);
            }
        }
    }
    exports.Action = Action;
    class ActionRunner extends lifecycle_1.Disposable {
        constructor() {
            super(...arguments);
            this._onWillRun = this._register(new event_1.Emitter());
            this.onWillRun = this._onWillRun.event;
            this._onDidRun = this._register(new event_1.Emitter());
            this.onDidRun = this._onDidRun.event;
        }
        async run(action, context) {
            if (!action.enabled) {
                return;
            }
            this._onWillRun.fire({ action });
            let error = undefined;
            try {
                await this.runAction(action, context);
            }
            catch (e) {
                error = e;
            }
            this._onDidRun.fire({ action, error });
        }
        async runAction(action, context) {
            await action.run(context);
        }
    }
    exports.ActionRunner = ActionRunner;
    class Separator {
        constructor() {
            this.id = Separator.ID;
            this.label = '';
            this.tooltip = '';
            this.class = 'separator';
            this.enabled = false;
            this.checked = false;
        }
        /**
         * Joins all non-empty lists of actions with separators.
         */
        static join(...actionLists) {
            let out = [];
            for (const list of actionLists) {
                if (!list.length) {
                    // skip
                }
                else if (out.length) {
                    out = [...out, new Separator(), ...list];
                }
                else {
                    out = list;
                }
            }
            return out;
        }
        static { this.ID = 'vs.actions.separator'; }
        async run() { }
    }
    exports.Separator = Separator;
    class SubmenuAction {
        get actions() { return this._actions; }
        constructor(id, label, actions, cssClass) {
            this.tooltip = '';
            this.enabled = true;
            this.checked = undefined;
            this.id = id;
            this.label = label;
            this.class = cssClass;
            this._actions = actions;
        }
        async run() { }
    }
    exports.SubmenuAction = SubmenuAction;
    class EmptySubmenuAction extends Action {
        static { this.ID = 'vs.actions.empty'; }
        constructor() {
            super(EmptySubmenuAction.ID, nls.localize(27, '(empty)'), undefined, false);
        }
    }
    exports.EmptySubmenuAction = EmptySubmenuAction;
    function toAction(props) {
        return {
            id: props.id,
            label: props.label,
            tooltip: props.tooltip ?? props.label,
            class: props.class,
            enabled: props.enabled ?? true,
            checked: props.checked,
            run: async (...args) => props.run(...args),
        };
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[346/*vs/base/common/errorMessage*/], __M([1/*require*/,0/*exports*/,13/*vs/base/common/arrays*/,19/*vs/base/common/types*/,3/*vs/nls*/]), function (require, exports, arrays, types, nls) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.toErrorMessage = toErrorMessage;
    function exceptionToErrorMessage(exception, verbose) {
        if (verbose && (exception.stack || exception.stacktrace)) {
            return nls.localize(28, "{0}: {1}", detectSystemErrorMessage(exception), stackToString(exception.stack) || stackToString(exception.stacktrace));
        }
        return detectSystemErrorMessage(exception);
    }
    function stackToString(stack) {
        if (Array.isArray(stack)) {
            return stack.join('\n');
        }
        return stack;
    }
    function detectSystemErrorMessage(exception) {
        // Custom node.js error from us
        if (exception.code === 'ERR_UNC_HOST_NOT_ALLOWED') {
            return `${exception.message}. Please update the 'security.allowedUNCHosts' setting if you want to allow this host.`;
        }
        // See https://nodejs.org/api/errors.html#errors_class_system_error
        if (typeof exception.code === 'string' && typeof exception.errno === 'number' && typeof exception.syscall === 'string') {
            return nls.localize(29, "A system error occurred ({0})", exception.message);
        }
        return exception.message || nls.localize(30, "An unknown error occurred. Please consult the log for more details.");
    }
    /**
     * Tries to generate a human readable error message out of the error. If the verbose parameter
     * is set to true, the error message will include stacktrace details if provided.
     *
     * @returns A string containing the error message.
     */
    function toErrorMessage(error = null, verbose = false) {
        if (!error) {
            return nls.localize(31, "An unknown error occurred. Please consult the log for more details.");
        }
        if (Array.isArray(error)) {
            const errors = arrays.coalesce(error);
            const msg = toErrorMessage(errors[0], verbose);
            if (errors.length > 1) {
                return nls.localize(32, "{0} ({1} errors in total)", msg, errors.length);
            }
            return msg;
        }
        if (types.isString(error)) {
            return error;
        }
        if (error.detail) {
            const detail = error.detail;
            if (detail.error) {
                return exceptionToErrorMessage(detail.error, verbose);
            }
            if (detail.exception) {
                return exceptionToErrorMessage(detail.exception, verbose);
            }
        }
        if (error.stack) {
            return exceptionToErrorMessage(error, verbose);
        }
        if (error.message) {
            return error.message;
        }
        return nls.localize(33, "An unknown error occurred. Please consult the log for more details.");
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[247/*vs/base/common/keybindingLabels*/], __M([1/*require*/,0/*exports*/,3/*vs/nls*/]), function (require, exports, nls) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.UserSettingsLabelProvider = exports.ElectronAcceleratorLabelProvider = exports.AriaLabelProvider = exports.UILabelProvider = exports.ModifierLabelProvider = void 0;
    class ModifierLabelProvider {
        constructor(mac, windows, linux = windows) {
            this.modifierLabels = [null]; // index 0 will never me accessed.
            this.modifierLabels[2 /* OperatingSystem.Macintosh */] = mac;
            this.modifierLabels[1 /* OperatingSystem.Windows */] = windows;
            this.modifierLabels[3 /* OperatingSystem.Linux */] = linux;
        }
        toLabel(OS, chords, keyLabelProvider) {
            if (chords.length === 0) {
                return null;
            }
            const result = [];
            for (let i = 0, len = chords.length; i < len; i++) {
                const chord = chords[i];
                const keyLabel = keyLabelProvider(chord);
                if (keyLabel === null) {
                    // this keybinding cannot be expressed...
                    return null;
                }
                result[i] = _simpleAsString(chord, keyLabel, this.modifierLabels[OS]);
            }
            return result.join(' ');
        }
    }
    exports.ModifierLabelProvider = ModifierLabelProvider;
    /**
     * A label provider that prints modifiers in a suitable format for displaying in the UI.
     */
    exports.UILabelProvider = new ModifierLabelProvider({
        ctrlKey: '\u2303',
        shiftKey: '⇧',
        altKey: '⌥',
        metaKey: '⌘',
        separator: '',
    }, {
        ctrlKey: nls.localize(34, "Ctrl"),
        shiftKey: nls.localize(35, "Shift"),
        altKey: nls.localize(36, "Alt"),
        metaKey: nls.localize(37, "Windows"),
        separator: '+',
    }, {
        ctrlKey: nls.localize(38, "Ctrl"),
        shiftKey: nls.localize(39, "Shift"),
        altKey: nls.localize(40, "Alt"),
        metaKey: nls.localize(41, "Super"),
        separator: '+',
    });
    /**
     * A label provider that prints modifiers in a suitable format for ARIA.
     */
    exports.AriaLabelProvider = new ModifierLabelProvider({
        ctrlKey: nls.localize(42, "Control"),
        shiftKey: nls.localize(43, "Shift"),
        altKey: nls.localize(44, "Option"),
        metaKey: nls.localize(45, "Command"),
        separator: '+',
    }, {
        ctrlKey: nls.localize(46, "Control"),
        shiftKey: nls.localize(47, "Shift"),
        altKey: nls.localize(48, "Alt"),
        metaKey: nls.localize(49, "Windows"),
        separator: '+',
    }, {
        ctrlKey: nls.localize(50, "Control"),
        shiftKey: nls.localize(51, "Shift"),
        altKey: nls.localize(52, "Alt"),
        metaKey: nls.localize(53, "Super"),
        separator: '+',
    });
    /**
     * A label provider that prints modifiers in a suitable format for Electron Accelerators.
     * See https://github.com/electron/electron/blob/master/docs/api/accelerator.md
     */
    exports.ElectronAcceleratorLabelProvider = new ModifierLabelProvider({
        ctrlKey: 'Ctrl',
        shiftKey: 'Shift',
        altKey: 'Alt',
        metaKey: 'Cmd',
        separator: '+',
    }, {
        ctrlKey: 'Ctrl',
        shiftKey: 'Shift',
        altKey: 'Alt',
        metaKey: 'Super',
        separator: '+',
    });
    /**
     * A label provider that prints modifiers in a suitable format for user settings.
     */
    exports.UserSettingsLabelProvider = new ModifierLabelProvider({
        ctrlKey: 'ctrl',
        shiftKey: 'shift',
        altKey: 'alt',
        metaKey: 'cmd',
        separator: '+',
    }, {
        ctrlKey: 'ctrl',
        shiftKey: 'shift',
        altKey: 'alt',
        metaKey: 'win',
        separator: '+',
    }, {
        ctrlKey: 'ctrl',
        shiftKey: 'shift',
        altKey: 'alt',
        metaKey: 'meta',
        separator: '+',
    });
    function _simpleAsString(modifiers, key, labels) {
        if (key === null) {
            return '';
        }
        const result = [];
        // translate modifier keys: Ctrl-Shift-Alt-Meta
        if (modifiers.ctrlKey) {
            result.push(labels.ctrlKey);
        }
        if (modifiers.shiftKey) {
            result.push(labels.shiftKey);
        }
        if (modifiers.altKey) {
            result.push(labels.altKey);
        }
        if (modifiers.metaKey) {
            result.push(labels.metaKey);
        }
        // the actual key
        if (key !== '') {
            result.push(key);
        }
        return result.join(labels.separator);
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[16/*vs/base/common/platform*/], __M([1/*require*/,0/*exports*/,3/*vs/nls*/]), function (require, exports, nls) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.isAndroid = exports.isEdge = exports.isSafari = exports.isFirefox = exports.isChrome = exports.OS = exports.setTimeout0 = exports.setTimeout0IsFaster = exports.language = exports.userAgent = exports.isMobile = exports.isIOS = exports.webWorkerOrigin = exports.isWebWorker = exports.isWeb = exports.isNative = exports.isLinux = exports.isMacintosh = exports.isWindows = exports.LANGUAGE_DEFAULT = void 0;
    exports.isLittleEndian = isLittleEndian;
    exports.LANGUAGE_DEFAULT = 'en';
    let _isWindows = false;
    let _isMacintosh = false;
    let _isLinux = false;
    let _isLinuxSnap = false;
    let _isNative = false;
    let _isWeb = false;
    let _isElectron = false;
    let _isIOS = false;
    let _isCI = false;
    let _isMobile = false;
    let _locale = undefined;
    let _language = exports.LANGUAGE_DEFAULT;
    let _platformLocale = exports.LANGUAGE_DEFAULT;
    let _translationsConfigFile = undefined;
    let _userAgent = undefined;
    const $globalThis = globalThis;
    let nodeProcess = undefined;
    if (typeof $globalThis.vscode !== 'undefined' && typeof $globalThis.vscode.process !== 'undefined') {
        // Native environment (sandboxed)
        nodeProcess = $globalThis.vscode.process;
    }
    else if (typeof process !== 'undefined' && typeof process?.versions?.node === 'string') {
        // Native environment (non-sandboxed)
        nodeProcess = process;
    }
    const isElectronProcess = typeof nodeProcess?.versions?.electron === 'string';
    const isElectronRenderer = isElectronProcess && nodeProcess?.type === 'renderer';
    // Native environment
    if (typeof nodeProcess === 'object') {
        _isWindows = (nodeProcess.platform === 'win32');
        _isMacintosh = (nodeProcess.platform === 'darwin');
        _isLinux = (nodeProcess.platform === 'linux');
        _isLinuxSnap = _isLinux && !!nodeProcess.env['SNAP'] && !!nodeProcess.env['SNAP_REVISION'];
        _isElectron = isElectronProcess;
        _isCI = !!nodeProcess.env['CI'] || !!nodeProcess.env['BUILD_ARTIFACTSTAGINGDIRECTORY'];
        _locale = exports.LANGUAGE_DEFAULT;
        _language = exports.LANGUAGE_DEFAULT;
        const rawNlsConfig = nodeProcess.env['VSCODE_NLS_CONFIG'];
        if (rawNlsConfig) {
            try {
                const nlsConfig = JSON.parse(rawNlsConfig);
                _locale = nlsConfig.userLocale;
                _platformLocale = nlsConfig.osLocale;
                _language = nlsConfig.resolvedLanguage || exports.LANGUAGE_DEFAULT;
                _translationsConfigFile = nlsConfig.languagePack?.translationsConfigFile;
            }
            catch (e) {
            }
        }
        _isNative = true;
    }
    // Web environment
    else if (typeof navigator === 'object' && !isElectronRenderer) {
        _userAgent = navigator.userAgent;
        _isWindows = _userAgent.indexOf('Windows') >= 0;
        _isMacintosh = _userAgent.indexOf('Macintosh') >= 0;
        _isIOS = (_userAgent.indexOf('Macintosh') >= 0 || _userAgent.indexOf('iPad') >= 0 || _userAgent.indexOf('iPhone') >= 0) && !!navigator.maxTouchPoints && navigator.maxTouchPoints > 0;
        _isLinux = _userAgent.indexOf('Linux') >= 0;
        _isMobile = _userAgent?.indexOf('Mobi') >= 0;
        _isWeb = true;
        _language = nls.getNLSLanguage() || exports.LANGUAGE_DEFAULT;
        _locale = navigator.language.toLowerCase();
        _platformLocale = _locale;
    }
    // Unknown environment
    else {
        console.error('Unable to resolve platform.');
    }
    let _platform = 0 /* Platform.Web */;
    if (_isMacintosh) {
        _platform = 1 /* Platform.Mac */;
    }
    else if (_isWindows) {
        _platform = 3 /* Platform.Windows */;
    }
    else if (_isLinux) {
        _platform = 2 /* Platform.Linux */;
    }
    exports.isWindows = _isWindows;
    exports.isMacintosh = _isMacintosh;
    exports.isLinux = _isLinux;
    exports.isNative = _isNative;
    exports.isWeb = _isWeb;
    exports.isWebWorker = (_isWeb && typeof $globalThis.importScripts === 'function');
    exports.webWorkerOrigin = exports.isWebWorker ? $globalThis.origin : undefined;
    exports.isIOS = _isIOS;
    exports.isMobile = _isMobile;
    exports.userAgent = _userAgent;
    /**
     * The language used for the user interface. The format of
     * the string is all lower case (e.g. zh-tw for Traditional
     * Chinese or de for German)
     */
    exports.language = _language;
    exports.setTimeout0IsFaster = (typeof $globalThis.postMessage === 'function' && !$globalThis.importScripts);
    /**
     * See https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#:~:text=than%204%2C%20then-,set%20timeout%20to%204,-.
     *
     * Works similarly to `setTimeout(0)` but doesn't suffer from the 4ms artificial delay
     * that browsers set when the nesting level is > 5.
     */
    exports.setTimeout0 = (() => {
        if (exports.setTimeout0IsFaster) {
            const pending = [];
            $globalThis.addEventListener('message', (e) => {
                if (e.data && e.data.vscodeScheduleAsyncWork) {
                    for (let i = 0, len = pending.length; i < len; i++) {
                        const candidate = pending[i];
                        if (candidate.id === e.data.vscodeScheduleAsyncWork) {
                            pending.splice(i, 1);
                            candidate.callback();
                            return;
                        }
                    }
                }
            });
            let lastId = 0;
            return (callback) => {
                const myId = ++lastId;
                pending.push({
                    id: myId,
                    callback: callback
                });
                $globalThis.postMessage({ vscodeScheduleAsyncWork: myId }, '*');
            };
        }
        return (callback) => setTimeout(callback);
    })();
    exports.OS = (_isMacintosh || _isIOS ? 2 /* OperatingSystem.Macintosh */ : (_isWindows ? 1 /* OperatingSystem.Windows */ : 3 /* OperatingSystem.Linux */));
    let _isLittleEndian = true;
    let _isLittleEndianComputed = false;
    function isLittleEndian() {
        if (!_isLittleEndianComputed) {
            _isLittleEndianComputed = true;
            const test = new Uint8Array(2);
            test[0] = 1;
            test[1] = 2;
            const view = new Uint16Array(test.buffer);
            _isLittleEndian = (view[0] === (2 << 8) + 1);
        }
        return _isLittleEndian;
    }
    exports.isChrome = !!(exports.userAgent && exports.userAgent.indexOf('Chrome') >= 0);
    exports.isFirefox = !!(exports.userAgent && exports.userAgent.indexOf('Firefox') >= 0);
    exports.isSafari = !!(!exports.isChrome && (exports.userAgent && exports.userAgent.indexOf('Safari') >= 0));
    exports.isEdge = !!(exports.userAgent && exports.userAgent.indexOf('Edg/') >= 0);
    exports.isAndroid = !!(exports.userAgent && exports.userAgent.indexOf('Android') >= 0);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[248/*vs/base/browser/canIUse*/], __M([1/*require*/,0/*exports*/,64/*vs/base/browser/browser*/,52/*vs/base/browser/window*/,16/*vs/base/common/platform*/]), function (require, exports, browser, window_1, platform) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.BrowserFeatures = void 0;
    /**
     * Browser feature we can support in current platform, browser and environment.
     */
    exports.BrowserFeatures = {
        clipboard: {
            writeText: (platform.isNative
                || (document.queryCommandSupported && document.queryCommandSupported('copy'))
                || !!(navigator && navigator.clipboard && navigator.clipboard.writeText)),
            readText: (platform.isNative
                || !!(navigator && navigator.clipboard && navigator.clipboard.readText))
        },
        keyboard: (() => {
            if (platform.isNative || browser.isStandalone()) {
                return 0 /* KeyboardSupport.Always */;
            }
            if (navigator.keyboard || browser.isSafari) {
                return 1 /* KeyboardSupport.FullScreen */;
            }
            return 2 /* KeyboardSupport.None */;
        })(),
        // 'ontouchstart' in window always evaluates to true with typescript's modern typings. This causes `window` to be
        // `never` later in `window.navigator`. That's why we need the explicit `window as Window` cast
        touch: 'ontouchstart' in window_1.mainWindow || navigator.maxTouchPoints > 0,
        pointerEvents: window_1.mainWindow.PointerEvent && ('ontouchstart' in window_1.mainWindow || navigator.maxTouchPoints > 0)
    };
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[347/*vs/base/browser/fonts*/], __M([1/*require*/,0/*exports*/,16/*vs/base/common/platform*/]), function (require, exports, platform_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DEFAULT_FONT_FAMILY = void 0;
    /**
     * The best font-family to be used in CSS based on the platform:
     * - Windows: Segoe preferred, fallback to sans-serif
     * - macOS: standard system font, fallback to sans-serif
     * - Linux: standard system font preferred, fallback to Ubuntu fonts
     *
     * Note: this currently does not adjust for different locales.
     */
    exports.DEFAULT_FONT_FAMILY = platform_1.isWindows ? '"Segoe WPC", "Segoe UI", sans-serif' : platform_1.isMacintosh ? '-apple-system, BlinkMacSystemFont, sans-serif' : 'system-ui, "Ubuntu", "Droid Sans", sans-serif';
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[47/*vs/base/browser/keyboardEvent*/], __M([1/*require*/,0/*exports*/,64/*vs/base/browser/browser*/,72/*vs/base/common/keyCodes*/,140/*vs/base/common/keybindings*/,16/*vs/base/common/platform*/]), function (require, exports, browser, keyCodes_1, keybindings_1, platform) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.StandardKeyboardEvent = void 0;
    function extractKeyCode(e) {
        if (e.charCode) {
            // "keypress" events mostly
            const char = String.fromCharCode(e.charCode).toUpperCase();
            return keyCodes_1.KeyCodeUtils.fromString(char);
        }
        const keyCode = e.keyCode;
        // browser quirks
        if (keyCode === 3) {
            return 7 /* KeyCode.PauseBreak */;
        }
        else if (browser.isFirefox) {
            switch (keyCode) {
                case 59: return 85 /* KeyCode.Semicolon */;
                case 60:
                    if (platform.isLinux) {
                        return 97 /* KeyCode.IntlBackslash */;
                    }
                    break;
                case 61: return 86 /* KeyCode.Equal */;
                // based on: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode#numpad_keys
                case 107: return 109 /* KeyCode.NumpadAdd */;
                case 109: return 111 /* KeyCode.NumpadSubtract */;
                case 173: return 88 /* KeyCode.Minus */;
                case 224:
                    if (platform.isMacintosh) {
                        return 57 /* KeyCode.Meta */;
                    }
                    break;
            }
        }
        else if (browser.isWebKit) {
            if (platform.isMacintosh && keyCode === 93) {
                // the two meta keys in the Mac have different key codes (91 and 93)
                return 57 /* KeyCode.Meta */;
            }
            else if (!platform.isMacintosh && keyCode === 92) {
                return 57 /* KeyCode.Meta */;
            }
        }
        // cross browser keycodes:
        return keyCodes_1.EVENT_KEY_CODE_MAP[keyCode] || 0 /* KeyCode.Unknown */;
    }
    const ctrlKeyMod = (platform.isMacintosh ? 256 /* KeyMod.WinCtrl */ : 2048 /* KeyMod.CtrlCmd */);
    const altKeyMod = 512 /* KeyMod.Alt */;
    const shiftKeyMod = 1024 /* KeyMod.Shift */;
    const metaKeyMod = (platform.isMacintosh ? 2048 /* KeyMod.CtrlCmd */ : 256 /* KeyMod.WinCtrl */);
    class StandardKeyboardEvent {
        constructor(source) {
            this._standardKeyboardEventBrand = true;
            const e = source;
            this.browserEvent = e;
            this.target = e.target;
            this.ctrlKey = e.ctrlKey;
            this.shiftKey = e.shiftKey;
            this.altKey = e.altKey;
            this.metaKey = e.metaKey;
            this.altGraphKey = e.getModifierState?.('AltGraph');
            this.keyCode = extractKeyCode(e);
            this.code = e.code;
            // console.info(e.type + ": keyCode: " + e.keyCode + ", which: " + e.which + ", charCode: " + e.charCode + ", detail: " + e.detail + " ====> " + this.keyCode + ' -- ' + KeyCode[this.keyCode]);
            this.ctrlKey = this.ctrlKey || this.keyCode === 5 /* KeyCode.Ctrl */;
            this.altKey = this.altKey || this.keyCode === 6 /* KeyCode.Alt */;
            this.shiftKey = this.shiftKey || this.keyCode === 4 /* KeyCode.Shift */;
            this.metaKey = this.metaKey || this.keyCode === 57 /* KeyCode.Meta */;
            this._asKeybinding = this._computeKeybinding();
            this._asKeyCodeChord = this._computeKeyCodeChord();
            // console.log(`code: ${e.code}, keyCode: ${e.keyCode}, key: ${e.key}`);
        }
        preventDefault() {
            if (this.browserEvent && this.browserEvent.preventDefault) {
                this.browserEvent.preventDefault();
            }
        }
        stopPropagation() {
            if (this.browserEvent && this.browserEvent.stopPropagation) {
                this.browserEvent.stopPropagation();
            }
        }
        toKeyCodeChord() {
            return this._asKeyCodeChord;
        }
        equals(other) {
            return this._asKeybinding === other;
        }
        _computeKeybinding() {
            let key = 0 /* KeyCode.Unknown */;
            if (this.keyCode !== 5 /* KeyCode.Ctrl */ && this.keyCode !== 4 /* KeyCode.Shift */ && this.keyCode !== 6 /* KeyCode.Alt */ && this.keyCode !== 57 /* KeyCode.Meta */) {
                key = this.keyCode;
            }
            let result = 0;
            if (this.ctrlKey) {
                result |= ctrlKeyMod;
            }
            if (this.altKey) {
                result |= altKeyMod;
            }
            if (this.shiftKey) {
                result |= shiftKeyMod;
            }
            if (this.metaKey) {
                result |= metaKeyMod;
            }
            result |= key;
            return result;
        }
        _computeKeyCodeChord() {
            let key = 0 /* KeyCode.Unknown */;
            if (this.keyCode !== 5 /* KeyCode.Ctrl */ && this.keyCode !== 4 /* KeyCode.Shift */ && this.keyCode !== 6 /* KeyCode.Alt */ && this.keyCode !== 57 /* KeyCode.Meta */) {
                key = this.keyCode;
            }
            return new keybindings_1.KeyCodeChord(this.ctrlKey, this.shiftKey, this.altKey, this.metaKey, key);
        }
    }
    exports.StandardKeyboardEvent = StandardKeyboardEvent;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[77/*vs/base/browser/mouseEvent*/], __M([1/*require*/,0/*exports*/,64/*vs/base/browser/browser*/,441/*vs/base/browser/iframe*/,16/*vs/base/common/platform*/]), function (require, exports, browser, iframe_1, platform) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.StandardWheelEvent = exports.StandardMouseEvent = void 0;
    class StandardMouseEvent {
        constructor(targetWindow, e) {
            this.timestamp = Date.now();
            this.browserEvent = e;
            this.leftButton = e.button === 0;
            this.middleButton = e.button === 1;
            this.rightButton = e.button === 2;
            this.buttons = e.buttons;
            this.target = e.target;
            this.detail = e.detail || 1;
            if (e.type === 'dblclick') {
                this.detail = 2;
            }
            this.ctrlKey = e.ctrlKey;
            this.shiftKey = e.shiftKey;
            this.altKey = e.altKey;
            this.metaKey = e.metaKey;
            if (typeof e.pageX === 'number') {
                this.posx = e.pageX;
                this.posy = e.pageY;
            }
            else {
                // Probably hit by MSGestureEvent
                this.posx = e.clientX + this.target.ownerDocument.body.scrollLeft + this.target.ownerDocument.documentElement.scrollLeft;
                this.posy = e.clientY + this.target.ownerDocument.body.scrollTop + this.target.ownerDocument.documentElement.scrollTop;
            }
            // Find the position of the iframe this code is executing in relative to the iframe where the event was captured.
            const iframeOffsets = iframe_1.IframeUtils.getPositionOfChildWindowRelativeToAncestorWindow(targetWindow, e.view);
            this.posx -= iframeOffsets.left;
            this.posy -= iframeOffsets.top;
        }
        preventDefault() {
            this.browserEvent.preventDefault();
        }
        stopPropagation() {
            this.browserEvent.stopPropagation();
        }
    }
    exports.StandardMouseEvent = StandardMouseEvent;
    class StandardWheelEvent {
        constructor(e, deltaX = 0, deltaY = 0) {
            this.browserEvent = e || null;
            this.target = e ? (e.target || e.targetNode || e.srcElement) : null;
            this.deltaY = deltaY;
            this.deltaX = deltaX;
            let shouldFactorDPR = false;
            if (browser.isChrome) {
                // Chrome version >= 123 contains the fix to factor devicePixelRatio into the wheel event.
                // See https://chromium.googlesource.com/chromium/src.git/+/be51b448441ff0c9d1f17e0f25c4bf1ab3f11f61
                const chromeVersionMatch = navigator.userAgent.match(/Chrome\/(\d+)/);
                const chromeMajorVersion = chromeVersionMatch ? parseInt(chromeVersionMatch[1]) : 123;
                shouldFactorDPR = chromeMajorVersion <= 122;
            }
            if (e) {
                // Old (deprecated) wheel events
                const e1 = e;
                const e2 = e;
                const devicePixelRatio = e.view?.devicePixelRatio || 1;
                // vertical delta scroll
                if (typeof e1.wheelDeltaY !== 'undefined') {
                    if (shouldFactorDPR) {
                        // Refs https://github.com/microsoft/vscode/issues/146403#issuecomment-1854538928
                        this.deltaY = e1.wheelDeltaY / (120 * devicePixelRatio);
                    }
                    else {
                        this.deltaY = e1.wheelDeltaY / 120;
                    }
                }
                else if (typeof e2.VERTICAL_AXIS !== 'undefined' && e2.axis === e2.VERTICAL_AXIS) {
                    this.deltaY = -e2.detail / 3;
                }
                else if (e.type === 'wheel') {
                    // Modern wheel event
                    // https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent
                    const ev = e;
                    if (ev.deltaMode === ev.DOM_DELTA_LINE) {
                        // the deltas are expressed in lines
                        if (browser.isFirefox && !platform.isMacintosh) {
                            this.deltaY = -e.deltaY / 3;
                        }
                        else {
                            this.deltaY = -e.deltaY;
                        }
                    }
                    else {
                        this.deltaY = -e.deltaY / 40;
                    }
                }
                // horizontal delta scroll
                if (typeof e1.wheelDeltaX !== 'undefined') {
                    if (browser.isSafari && platform.isWindows) {
                        this.deltaX = -(e1.wheelDeltaX / 120);
                    }
                    else if (shouldFactorDPR) {
                        // Refs https://github.com/microsoft/vscode/issues/146403#issuecomment-1854538928
                        this.deltaX = e1.wheelDeltaX / (120 * devicePixelRatio);
                    }
                    else {
                        this.deltaX = e1.wheelDeltaX / 120;
                    }
                }
                else if (typeof e2.HORIZONTAL_AXIS !== 'undefined' && e2.axis === e2.HORIZONTAL_AXIS) {
                    this.deltaX = -e.detail / 3;
                }
                else if (e.type === 'wheel') {
                    // Modern wheel event
                    // https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent
                    const ev = e;
                    if (ev.deltaMode === ev.DOM_DELTA_LINE) {
                        // the deltas are expressed in lines
                        if (browser.isFirefox && !platform.isMacintosh) {
                            this.deltaX = -e.deltaX / 3;
                        }
                        else {
                            this.deltaX = -e.deltaX;
                        }
                    }
                    else {
                        this.deltaX = -e.deltaX / 40;
                    }
                }
                // Assume a vertical scroll if nothing else worked
                if (this.deltaY === 0 && this.deltaX === 0 && e.wheelDelta) {
                    if (shouldFactorDPR) {
                        // Refs https://github.com/microsoft/vscode/issues/146403#issuecomment-1854538928
                        this.deltaY = e.wheelDelta / (120 * devicePixelRatio);
                    }
                    else {
                        this.deltaY = e.wheelDelta / 120;
                    }
                }
            }
        }
        preventDefault() {
            this.browserEvent?.preventDefault();
        }
        stopPropagation() {
            this.browserEvent?.stopPropagation();
        }
    }
    exports.StandardWheelEvent = StandardWheelEvent;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[14/*vs/base/common/async*/], __M([1/*require*/,0/*exports*/,18/*vs/base/common/cancellation*/,8/*vs/base/common/errors*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,16/*vs/base/common/platform*/,301/*vs/base/common/symbols*/]), function (require, exports, cancellation_1, errors_1, event_1, lifecycle_1, platform_1, symbols_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CancelableAsyncIterableObject = exports.AsyncIterableObject = exports.Promises = exports.DeferredPromise = exports.GlobalIdleValue = exports.AbstractIdleValue = exports._runWhenIdle = exports.runWhenGlobalIdle = exports.RunOnceScheduler = exports.IntervalTimer = exports.TimeoutTimer = exports.ThrottledDelayer = exports.Delayer = exports.Throttler = void 0;
    exports.isThenable = isThenable;
    exports.createCancelablePromise = createCancelablePromise;
    exports.raceCancellation = raceCancellation;
    exports.timeout = timeout;
    exports.disposableTimeout = disposableTimeout;
    exports.first = first;
    exports.createCancelableAsyncIterable = createCancelableAsyncIterable;
    function isThenable(obj) {
        return !!obj && typeof obj.then === 'function';
    }
    function createCancelablePromise(callback) {
        const source = new cancellation_1.CancellationTokenSource();
        const thenable = callback(source.token);
        const promise = new Promise((resolve, reject) => {
            const subscription = source.token.onCancellationRequested(() => {
                subscription.dispose();
                reject(new errors_1.CancellationError());
            });
            Promise.resolve(thenable).then(value => {
                subscription.dispose();
                source.dispose();
                resolve(value);
            }, err => {
                subscription.dispose();
                source.dispose();
                reject(err);
            });
        });
        return new class {
            cancel() {
                source.cancel();
                source.dispose();
            }
            then(resolve, reject) {
                return promise.then(resolve, reject);
            }
            catch(reject) {
                return this.then(undefined, reject);
            }
            finally(onfinally) {
                return promise.finally(onfinally);
            }
        };
    }
    function raceCancellation(promise, token, defaultValue) {
        return new Promise((resolve, reject) => {
            const ref = token.onCancellationRequested(() => {
                ref.dispose();
                resolve(defaultValue);
            });
            promise.then(resolve, reject).finally(() => ref.dispose());
        });
    }
    /**
     * A helper to prevent accumulation of sequential async tasks.
     *
     * Imagine a mail man with the sole task of delivering letters. As soon as
     * a letter submitted for delivery, he drives to the destination, delivers it
     * and returns to his base. Imagine that during the trip, N more letters were submitted.
     * When the mail man returns, he picks those N letters and delivers them all in a
     * single trip. Even though N+1 submissions occurred, only 2 deliveries were made.
     *
     * The throttler implements this via the queue() method, by providing it a task
     * factory. Following the example:
     *
     * 		const throttler = new Throttler();
     * 		const letters = [];
     *
     * 		function deliver() {
     * 			const lettersToDeliver = letters;
     * 			letters = [];
     * 			return makeTheTrip(lettersToDeliver);
     * 		}
     *
     * 		function onLetterReceived(l) {
     * 			letters.push(l);
     * 			throttler.queue(deliver);
     * 		}
     */
    class Throttler {
        constructor() {
            this.isDisposed = false;
            this.activePromise = null;
            this.queuedPromise = null;
            this.queuedPromiseFactory = null;
        }
        queue(promiseFactory) {
            if (this.isDisposed) {
                return Promise.reject(new Error('Throttler is disposed'));
            }
            if (this.activePromise) {
                this.queuedPromiseFactory = promiseFactory;
                if (!this.queuedPromise) {
                    const onComplete = () => {
                        this.queuedPromise = null;
                        if (this.isDisposed) {
                            return;
                        }
                        const result = this.queue(this.queuedPromiseFactory);
                        this.queuedPromiseFactory = null;
                        return result;
                    };
                    this.queuedPromise = new Promise(resolve => {
                        this.activePromise.then(onComplete, onComplete).then(resolve);
                    });
                }
                return new Promise((resolve, reject) => {
                    this.queuedPromise.then(resolve, reject);
                });
            }
            this.activePromise = promiseFactory();
            return new Promise((resolve, reject) => {
                this.activePromise.then((result) => {
                    this.activePromise = null;
                    resolve(result);
                }, (err) => {
                    this.activePromise = null;
                    reject(err);
                });
            });
        }
        dispose() {
            this.isDisposed = true;
        }
    }
    exports.Throttler = Throttler;
    const timeoutDeferred = (timeout, fn) => {
        let scheduled = true;
        const handle = setTimeout(() => {
            scheduled = false;
            fn();
        }, timeout);
        return {
            isTriggered: () => scheduled,
            dispose: () => {
                clearTimeout(handle);
                scheduled = false;
            },
        };
    };
    const microtaskDeferred = (fn) => {
        let scheduled = true;
        queueMicrotask(() => {
            if (scheduled) {
                scheduled = false;
                fn();
            }
        });
        return {
            isTriggered: () => scheduled,
            dispose: () => { scheduled = false; },
        };
    };
    /**
     * A helper to delay (debounce) execution of a task that is being requested often.
     *
     * Following the throttler, now imagine the mail man wants to optimize the number of
     * trips proactively. The trip itself can be long, so he decides not to make the trip
     * as soon as a letter is submitted. Instead he waits a while, in case more
     * letters are submitted. After said waiting period, if no letters were submitted, he
     * decides to make the trip. Imagine that N more letters were submitted after the first
     * one, all within a short period of time between each other. Even though N+1
     * submissions occurred, only 1 delivery was made.
     *
     * The delayer offers this behavior via the trigger() method, into which both the task
     * to be executed and the waiting period (delay) must be passed in as arguments. Following
     * the example:
     *
     * 		const delayer = new Delayer(WAITING_PERIOD);
     * 		const letters = [];
     *
     * 		function letterReceived(l) {
     * 			letters.push(l);
     * 			delayer.trigger(() => { return makeTheTrip(); });
     * 		}
     */
    class Delayer {
        constructor(defaultDelay) {
            this.defaultDelay = defaultDelay;
            this.deferred = null;
            this.completionPromise = null;
            this.doResolve = null;
            this.doReject = null;
            this.task = null;
        }
        trigger(task, delay = this.defaultDelay) {
            this.task = task;
            this.cancelTimeout();
            if (!this.completionPromise) {
                this.completionPromise = new Promise((resolve, reject) => {
                    this.doResolve = resolve;
                    this.doReject = reject;
                }).then(() => {
                    this.completionPromise = null;
                    this.doResolve = null;
                    if (this.task) {
                        const task = this.task;
                        this.task = null;
                        return task();
                    }
                    return undefined;
                });
            }
            const fn = () => {
                this.deferred = null;
                this.doResolve?.(null);
            };
            this.deferred = delay === symbols_1.MicrotaskDelay ? microtaskDeferred(fn) : timeoutDeferred(delay, fn);
            return this.completionPromise;
        }
        isTriggered() {
            return !!this.deferred?.isTriggered();
        }
        cancel() {
            this.cancelTimeout();
            if (this.completionPromise) {
                this.doReject?.(new errors_1.CancellationError());
                this.completionPromise = null;
            }
        }
        cancelTimeout() {
            this.deferred?.dispose();
            this.deferred = null;
        }
        dispose() {
            this.cancel();
        }
    }
    exports.Delayer = Delayer;
    /**
     * A helper to delay execution of a task that is being requested often, while
     * preventing accumulation of consecutive executions, while the task runs.
     *
     * The mail man is clever and waits for a certain amount of time, before going
     * out to deliver letters. While the mail man is going out, more letters arrive
     * and can only be delivered once he is back. Once he is back the mail man will
     * do one more trip to deliver the letters that have accumulated while he was out.
     */
    class ThrottledDelayer {
        constructor(defaultDelay) {
            this.delayer = new Delayer(defaultDelay);
            this.throttler = new Throttler();
        }
        trigger(promiseFactory, delay) {
            return this.delayer.trigger(() => this.throttler.queue(promiseFactory), delay);
        }
        cancel() {
            this.delayer.cancel();
        }
        dispose() {
            this.delayer.dispose();
            this.throttler.dispose();
        }
    }
    exports.ThrottledDelayer = ThrottledDelayer;
    function timeout(millis, token) {
        if (!token) {
            return createCancelablePromise(token => timeout(millis, token));
        }
        return new Promise((resolve, reject) => {
            const handle = setTimeout(() => {
                disposable.dispose();
                resolve();
            }, millis);
            const disposable = token.onCancellationRequested(() => {
                clearTimeout(handle);
                disposable.dispose();
                reject(new errors_1.CancellationError());
            });
        });
    }
    /**
     * Creates a timeout that can be disposed using its returned value.
     * @param handler The timeout handler.
     * @param timeout An optional timeout in milliseconds.
     * @param store An optional {@link DisposableStore} that will have the timeout disposable managed automatically.
     *
     * @example
     * const store = new DisposableStore;
     * // Call the timeout after 1000ms at which point it will be automatically
     * // evicted from the store.
     * const timeoutDisposable = disposableTimeout(() => {}, 1000, store);
     *
     * if (foo) {
     *   // Cancel the timeout and evict it from store.
     *   timeoutDisposable.dispose();
     * }
     */
    function disposableTimeout(handler, timeout = 0, store) {
        const timer = setTimeout(() => {
            handler();
            if (store) {
                disposable.dispose();
            }
        }, timeout);
        const disposable = (0, lifecycle_1.toDisposable)(() => {
            clearTimeout(timer);
            store?.deleteAndLeak(disposable);
        });
        store?.add(disposable);
        return disposable;
    }
    function first(promiseFactories, shouldStop = t => !!t, defaultValue = null) {
        let index = 0;
        const len = promiseFactories.length;
        const loop = () => {
            if (index >= len) {
                return Promise.resolve(defaultValue);
            }
            const factory = promiseFactories[index++];
            const promise = Promise.resolve(factory());
            return promise.then(result => {
                if (shouldStop(result)) {
                    return Promise.resolve(result);
                }
                return loop();
            });
        };
        return loop();
    }
    class TimeoutTimer {
        constructor(runner, timeout) {
            this._isDisposed = false;
            this._token = -1;
            if (typeof runner === 'function' && typeof timeout === 'number') {
                this.setIfNotSet(runner, timeout);
            }
        }
        dispose() {
            this.cancel();
            this._isDisposed = true;
        }
        cancel() {
            if (this._token !== -1) {
                clearTimeout(this._token);
                this._token = -1;
            }
        }
        cancelAndSet(runner, timeout) {
            if (this._isDisposed) {
                throw new errors_1.BugIndicatingError(`Calling 'cancelAndSet' on a disposed TimeoutTimer`);
            }
            this.cancel();
            this._token = setTimeout(() => {
                this._token = -1;
                runner();
            }, timeout);
        }
        setIfNotSet(runner, timeout) {
            if (this._isDisposed) {
                throw new errors_1.BugIndicatingError(`Calling 'setIfNotSet' on a disposed TimeoutTimer`);
            }
            if (this._token !== -1) {
                // timer is already set
                return;
            }
            this._token = setTimeout(() => {
                this._token = -1;
                runner();
            }, timeout);
        }
    }
    exports.TimeoutTimer = TimeoutTimer;
    class IntervalTimer {
        constructor() {
            this.disposable = undefined;
            this.isDisposed = false;
        }
        cancel() {
            this.disposable?.dispose();
            this.disposable = undefined;
        }
        cancelAndSet(runner, interval, context = globalThis) {
            if (this.isDisposed) {
                throw new errors_1.BugIndicatingError(`Calling 'cancelAndSet' on a disposed IntervalTimer`);
            }
            this.cancel();
            const handle = context.setInterval(() => {
                runner();
            }, interval);
            this.disposable = (0, lifecycle_1.toDisposable)(() => {
                context.clearInterval(handle);
                this.disposable = undefined;
            });
        }
        dispose() {
            this.cancel();
            this.isDisposed = true;
        }
    }
    exports.IntervalTimer = IntervalTimer;
    class RunOnceScheduler {
        constructor(runner, delay) {
            this.timeoutToken = -1;
            this.runner = runner;
            this.timeout = delay;
            this.timeoutHandler = this.onTimeout.bind(this);
        }
        /**
         * Dispose RunOnceScheduler
         */
        dispose() {
            this.cancel();
            this.runner = null;
        }
        /**
         * Cancel current scheduled runner (if any).
         */
        cancel() {
            if (this.isScheduled()) {
                clearTimeout(this.timeoutToken);
                this.timeoutToken = -1;
            }
        }
        /**
         * Cancel previous runner (if any) & schedule a new runner.
         */
        schedule(delay = this.timeout) {
            this.cancel();
            this.timeoutToken = setTimeout(this.timeoutHandler, delay);
        }
        get delay() {
            return this.timeout;
        }
        set delay(value) {
            this.timeout = value;
        }
        /**
         * Returns true if scheduled.
         */
        isScheduled() {
            return this.timeoutToken !== -1;
        }
        onTimeout() {
            this.timeoutToken = -1;
            if (this.runner) {
                this.doRun();
            }
        }
        doRun() {
            this.runner?.();
        }
    }
    exports.RunOnceScheduler = RunOnceScheduler;
    (function () {
        if (typeof globalThis.requestIdleCallback !== 'function' || typeof globalThis.cancelIdleCallback !== 'function') {
            exports._runWhenIdle = (_targetWindow, runner) => {
                (0, platform_1.setTimeout0)(() => {
                    if (disposed) {
                        return;
                    }
                    const end = Date.now() + 15; // one frame at 64fps
                    const deadline = {
                        didTimeout: true,
                        timeRemaining() {
                            return Math.max(0, end - Date.now());
                        }
                    };
                    runner(Object.freeze(deadline));
                });
                let disposed = false;
                return {
                    dispose() {
                        if (disposed) {
                            return;
                        }
                        disposed = true;
                    }
                };
            };
        }
        else {
            exports._runWhenIdle = (targetWindow, runner, timeout) => {
                const handle = targetWindow.requestIdleCallback(runner, typeof timeout === 'number' ? { timeout } : undefined);
                let disposed = false;
                return {
                    dispose() {
                        if (disposed) {
                            return;
                        }
                        disposed = true;
                        targetWindow.cancelIdleCallback(handle);
                    }
                };
            };
        }
        exports.runWhenGlobalIdle = (runner) => (0, exports._runWhenIdle)(globalThis, runner);
    })();
    class AbstractIdleValue {
        constructor(targetWindow, executor) {
            this._didRun = false;
            this._executor = () => {
                try {
                    this._value = executor();
                }
                catch (err) {
                    this._error = err;
                }
                finally {
                    this._didRun = true;
                }
            };
            this._handle = (0, exports._runWhenIdle)(targetWindow, () => this._executor());
        }
        dispose() {
            this._handle.dispose();
        }
        get value() {
            if (!this._didRun) {
                this._handle.dispose();
                this._executor();
            }
            if (this._error) {
                throw this._error;
            }
            return this._value;
        }
        get isInitialized() {
            return this._didRun;
        }
    }
    exports.AbstractIdleValue = AbstractIdleValue;
    /**
     * An `IdleValue` that always uses the current window (which might be throttled or inactive)
     *
     * **Note** that there is `dom.ts#WindowIdleValue` which is better suited when running inside a browser
     * context
     */
    class GlobalIdleValue extends AbstractIdleValue {
        constructor(executor) {
            super(globalThis, executor);
        }
    }
    exports.GlobalIdleValue = GlobalIdleValue;
    /**
     * Creates a promise whose resolution or rejection can be controlled imperatively.
     */
    class DeferredPromise {
        get isRejected() {
            return this.outcome?.outcome === 1 /* DeferredOutcome.Rejected */;
        }
        get isSettled() {
            return !!this.outcome;
        }
        constructor() {
            this.p = new Promise((c, e) => {
                this.completeCallback = c;
                this.errorCallback = e;
            });
        }
        complete(value) {
            return new Promise(resolve => {
                this.completeCallback(value);
                this.outcome = { outcome: 0 /* DeferredOutcome.Resolved */, value };
                resolve();
            });
        }
        error(err) {
            return new Promise(resolve => {
                this.errorCallback(err);
                this.outcome = { outcome: 1 /* DeferredOutcome.Rejected */, value: err };
                resolve();
            });
        }
        cancel() {
            return this.error(new errors_1.CancellationError());
        }
    }
    exports.DeferredPromise = DeferredPromise;
    //#endregion
    //#region Promises
    var Promises;
    (function (Promises) {
        /**
         * A drop-in replacement for `Promise.all` with the only difference
         * that the method awaits every promise to either fulfill or reject.
         *
         * Similar to `Promise.all`, only the first error will be returned
         * if any.
         */
        async function settled(promises) {
            let firstError = undefined;
            const result = await Promise.all(promises.map(promise => promise.then(value => value, error => {
                if (!firstError) {
                    firstError = error;
                }
                return undefined; // do not rethrow so that other promises can settle
            })));
            if (typeof firstError !== 'undefined') {
                throw firstError;
            }
            return result; // cast is needed and protected by the `throw` above
        }
        Promises.settled = settled;
        /**
         * A helper to create a new `Promise<T>` with a body that is a promise
         * itself. By default, an error that raises from the async body will
         * end up as a unhandled rejection, so this utility properly awaits the
         * body and rejects the promise as a normal promise does without async
         * body.
         *
         * This method should only be used in rare cases where otherwise `async`
         * cannot be used (e.g. when callbacks are involved that require this).
         */
        function withAsyncBody(bodyFn) {
            // eslint-disable-next-line no-async-promise-executor
            return new Promise(async (resolve, reject) => {
                try {
                    await bodyFn(resolve, reject);
                }
                catch (error) {
                    reject(error);
                }
            });
        }
        Promises.withAsyncBody = withAsyncBody;
    })(Promises || (exports.Promises = Promises = {}));
    /**
     * A rich implementation for an `AsyncIterable<T>`.
     */
    class AsyncIterableObject {
        static fromArray(items) {
            return new AsyncIterableObject((writer) => {
                writer.emitMany(items);
            });
        }
        static fromPromise(promise) {
            return new AsyncIterableObject(async (emitter) => {
                emitter.emitMany(await promise);
            });
        }
        static fromPromises(promises) {
            return new AsyncIterableObject(async (emitter) => {
                await Promise.all(promises.map(async (p) => emitter.emitOne(await p)));
            });
        }
        static merge(iterables) {
            return new AsyncIterableObject(async (emitter) => {
                await Promise.all(iterables.map(async (iterable) => {
                    for await (const item of iterable) {
                        emitter.emitOne(item);
                    }
                }));
            });
        }
        static { this.EMPTY = AsyncIterableObject.fromArray([]); }
        constructor(executor, onReturn) {
            this._state = 0 /* AsyncIterableSourceState.Initial */;
            this._results = [];
            this._error = null;
            this._onReturn = onReturn;
            this._onStateChanged = new event_1.Emitter();
            queueMicrotask(async () => {
                const writer = {
                    emitOne: (item) => this.emitOne(item),
                    emitMany: (items) => this.emitMany(items),
                    reject: (error) => this.reject(error)
                };
                try {
                    await Promise.resolve(executor(writer));
                    this.resolve();
                }
                catch (err) {
                    this.reject(err);
                }
                finally {
                    writer.emitOne = undefined;
                    writer.emitMany = undefined;
                    writer.reject = undefined;
                }
            });
        }
        [Symbol.asyncIterator]() {
            let i = 0;
            return {
                next: async () => {
                    do {
                        if (this._state === 2 /* AsyncIterableSourceState.DoneError */) {
                            throw this._error;
                        }
                        if (i < this._results.length) {
                            return { done: false, value: this._results[i++] };
                        }
                        if (this._state === 1 /* AsyncIterableSourceState.DoneOK */) {
                            return { done: true, value: undefined };
                        }
                        await event_1.Event.toPromise(this._onStateChanged.event);
                    } while (true);
                },
                return: async () => {
                    this._onReturn?.();
                    return { done: true, value: undefined };
                }
            };
        }
        static map(iterable, mapFn) {
            return new AsyncIterableObject(async (emitter) => {
                for await (const item of iterable) {
                    emitter.emitOne(mapFn(item));
                }
            });
        }
        map(mapFn) {
            return AsyncIterableObject.map(this, mapFn);
        }
        static filter(iterable, filterFn) {
            return new AsyncIterableObject(async (emitter) => {
                for await (const item of iterable) {
                    if (filterFn(item)) {
                        emitter.emitOne(item);
                    }
                }
            });
        }
        filter(filterFn) {
            return AsyncIterableObject.filter(this, filterFn);
        }
        static coalesce(iterable) {
            return AsyncIterableObject.filter(iterable, item => !!item);
        }
        coalesce() {
            return AsyncIterableObject.coalesce(this);
        }
        static async toPromise(iterable) {
            const result = [];
            for await (const item of iterable) {
                result.push(item);
            }
            return result;
        }
        toPromise() {
            return AsyncIterableObject.toPromise(this);
        }
        /**
         * The value will be appended at the end.
         *
         * **NOTE** If `resolve()` or `reject()` have already been called, this method has no effect.
         */
        emitOne(value) {
            if (this._state !== 0 /* AsyncIterableSourceState.Initial */) {
                return;
            }
            // it is important to add new values at the end,
            // as we may have iterators already running on the array
            this._results.push(value);
            this._onStateChanged.fire();
        }
        /**
         * The values will be appended at the end.
         *
         * **NOTE** If `resolve()` or `reject()` have already been called, this method has no effect.
         */
        emitMany(values) {
            if (this._state !== 0 /* AsyncIterableSourceState.Initial */) {
                return;
            }
            // it is important to add new values at the end,
            // as we may have iterators already running on the array
            this._results = this._results.concat(values);
            this._onStateChanged.fire();
        }
        /**
         * Calling `resolve()` will mark the result array as complete.
         *
         * **NOTE** `resolve()` must be called, otherwise all consumers of this iterable will hang indefinitely, similar to a non-resolved promise.
         * **NOTE** If `resolve()` or `reject()` have already been called, this method has no effect.
         */
        resolve() {
            if (this._state !== 0 /* AsyncIterableSourceState.Initial */) {
                return;
            }
            this._state = 1 /* AsyncIterableSourceState.DoneOK */;
            this._onStateChanged.fire();
        }
        /**
         * Writing an error will permanently invalidate this iterable.
         * The current users will receive an error thrown, as will all future users.
         *
         * **NOTE** If `resolve()` or `reject()` have already been called, this method has no effect.
         */
        reject(error) {
            if (this._state !== 0 /* AsyncIterableSourceState.Initial */) {
                return;
            }
            this._state = 2 /* AsyncIterableSourceState.DoneError */;
            this._error = error;
            this._onStateChanged.fire();
        }
    }
    exports.AsyncIterableObject = AsyncIterableObject;
    class CancelableAsyncIterableObject extends AsyncIterableObject {
        constructor(_source, executor) {
            super(executor);
            this._source = _source;
        }
        cancel() {
            this._source.cancel();
        }
    }
    exports.CancelableAsyncIterableObject = CancelableAsyncIterableObject;
    function createCancelableAsyncIterable(callback) {
        const source = new cancellation_1.CancellationTokenSource();
        const innerIterable = callback(source.token);
        return new CancelableAsyncIterableObject(source, async (emitter) => {
            const subscription = source.token.onCancellationRequested(() => {
                subscription.dispose();
                source.dispose();
                emitter.reject(new errors_1.CancellationError());
            });
            try {
                for await (const item of innerIterable) {
                    if (source.token.isCancellationRequested) {
                        // canceled in the meantime
                        return;
                    }
                    emitter.emitOne(item);
                }
                subscription.dispose();
                source.dispose();
            }
            catch (err) {
                subscription.dispose();
                source.dispose();
                emitter.reject(err);
            }
        });
    }
});
//#endregion

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[626/*vs/base/browser/ui/scrollbar/scrollbarVisibilityController*/], __M([1/*require*/,0/*exports*/,14/*vs/base/common/async*/,2/*vs/base/common/lifecycle*/]), function (require, exports, async_1, lifecycle_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ScrollbarVisibilityController = void 0;
    class ScrollbarVisibilityController extends lifecycle_1.Disposable {
        constructor(visibility, visibleClassName, invisibleClassName) {
            super();
            this._visibility = visibility;
            this._visibleClassName = visibleClassName;
            this._invisibleClassName = invisibleClassName;
            this._domNode = null;
            this._isVisible = false;
            this._isNeeded = false;
            this._rawShouldBeVisible = false;
            this._shouldBeVisible = false;
            this._revealTimer = this._register(new async_1.TimeoutTimer());
        }
        setVisibility(visibility) {
            if (this._visibility !== visibility) {
                this._visibility = visibility;
                this._updateShouldBeVisible();
            }
        }
        // ----------------- Hide / Reveal
        setShouldBeVisible(rawShouldBeVisible) {
            this._rawShouldBeVisible = rawShouldBeVisible;
            this._updateShouldBeVisible();
        }
        _applyVisibilitySetting() {
            if (this._visibility === 2 /* ScrollbarVisibility.Hidden */) {
                return false;
            }
            if (this._visibility === 3 /* ScrollbarVisibility.Visible */) {
                return true;
            }
            return this._rawShouldBeVisible;
        }
        _updateShouldBeVisible() {
            const shouldBeVisible = this._applyVisibilitySetting();
            if (this._shouldBeVisible !== shouldBeVisible) {
                this._shouldBeVisible = shouldBeVisible;
                this.ensureVisibility();
            }
        }
        setIsNeeded(isNeeded) {
            if (this._isNeeded !== isNeeded) {
                this._isNeeded = isNeeded;
                this.ensureVisibility();
            }
        }
        setDomNode(domNode) {
            this._domNode = domNode;
            this._domNode.setClassName(this._invisibleClassName);
            // Now that the flags & the dom node are in a consistent state, ensure the Hidden/Visible configuration
            this.setShouldBeVisible(false);
        }
        ensureVisibility() {
            if (!this._isNeeded) {
                // Nothing to be rendered
                this._hide(false);
                return;
            }
            if (this._shouldBeVisible) {
                this._reveal();
            }
            else {
                this._hide(true);
            }
        }
        _reveal() {
            if (this._isVisible) {
                return;
            }
            this._isVisible = true;
            // The CSS animation doesn't play otherwise
            this._revealTimer.setIfNotSet(() => {
                this._domNode?.setClassName(this._visibleClassName);
            }, 0);
        }
        _hide(withFadeAway) {
            this._revealTimer.cancel();
            if (!this._isVisible) {
                return;
            }
            this._isVisible = false;
            this._domNode?.setClassName(this._invisibleClassName + (withFadeAway ? ' fade' : ''));
        }
    }
    exports.ScrollbarVisibilityController = ScrollbarVisibilityController;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[249/*vs/base/browser/ui/tree/indexTreeModel*/], __M([1/*require*/,0/*exports*/,159/*vs/base/browser/ui/tree/tree*/,13/*vs/base/common/arrays*/,14/*vs/base/common/async*/,301/*vs/base/common/symbols*/,190/*vs/base/common/diff/diff*/,6/*vs/base/common/event*/,53/*vs/base/common/iterator*/]), function (require, exports, tree_1, arrays_1, async_1, symbols_1, diff_1, event_1, iterator_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.IndexTreeModel = void 0;
    exports.isFilterResult = isFilterResult;
    exports.getVisibleState = getVisibleState;
    function isFilterResult(obj) {
        return typeof obj === 'object' && 'visibility' in obj && 'data' in obj;
    }
    function getVisibleState(visibility) {
        switch (visibility) {
            case true: return 1 /* TreeVisibility.Visible */;
            case false: return 0 /* TreeVisibility.Hidden */;
            default: return visibility;
        }
    }
    function isCollapsibleStateUpdate(update) {
        return typeof update.collapsible === 'boolean';
    }
    class IndexTreeModel {
        constructor(user, list, rootElement, options = {}) {
            this.user = user;
            this.list = list;
            this.rootRef = [];
            this.eventBufferer = new event_1.EventBufferer();
            this._onDidChangeCollapseState = new event_1.Emitter();
            this.onDidChangeCollapseState = this.eventBufferer.wrapEvent(this._onDidChangeCollapseState.event);
            this._onDidChangeRenderNodeCount = new event_1.Emitter();
            this.onDidChangeRenderNodeCount = this.eventBufferer.wrapEvent(this._onDidChangeRenderNodeCount.event);
            this._onDidSplice = new event_1.Emitter();
            this.onDidSplice = this._onDidSplice.event;
            this.refilterDelayer = new async_1.Delayer(symbols_1.MicrotaskDelay);
            this.collapseByDefault = typeof options.collapseByDefault === 'undefined' ? false : options.collapseByDefault;
            this.allowNonCollapsibleParents = options.allowNonCollapsibleParents ?? false;
            this.filter = options.filter;
            this.autoExpandSingleChildren = typeof options.autoExpandSingleChildren === 'undefined' ? false : options.autoExpandSingleChildren;
            this.root = {
                parent: undefined,
                element: rootElement,
                children: [],
                depth: 0,
                visibleChildrenCount: 0,
                visibleChildIndex: -1,
                collapsible: false,
                collapsed: false,
                renderNodeCount: 0,
                visibility: 1 /* TreeVisibility.Visible */,
                visible: true,
                filterData: undefined
            };
        }
        splice(location, deleteCount, toInsert = iterator_1.Iterable.empty(), options = {}) {
            if (location.length === 0) {
                throw new tree_1.TreeError(this.user, 'Invalid tree location');
            }
            if (options.diffIdentityProvider) {
                this.spliceSmart(options.diffIdentityProvider, location, deleteCount, toInsert, options);
            }
            else {
                this.spliceSimple(location, deleteCount, toInsert, options);
            }
        }
        spliceSmart(identity, location, deleteCount, toInsertIterable = iterator_1.Iterable.empty(), options, recurseLevels = options.diffDepth ?? 0) {
            const { parentNode } = this.getParentNodeWithListIndex(location);
            if (!parentNode.lastDiffIds) {
                return this.spliceSimple(location, deleteCount, toInsertIterable, options);
            }
            const toInsert = [...toInsertIterable];
            const index = location[location.length - 1];
            const diff = new diff_1.LcsDiff({ getElements: () => parentNode.lastDiffIds }, {
                getElements: () => [
                    ...parentNode.children.slice(0, index),
                    ...toInsert,
                    ...parentNode.children.slice(index + deleteCount),
                ].map(e => identity.getId(e.element).toString())
            }).ComputeDiff(false);
            // if we were given a 'best effort' diff, use default behavior
            if (diff.quitEarly) {
                parentNode.lastDiffIds = undefined;
                return this.spliceSimple(location, deleteCount, toInsert, options);
            }
            const locationPrefix = location.slice(0, -1);
            const recurseSplice = (fromOriginal, fromModified, count) => {
                if (recurseLevels > 0) {
                    for (let i = 0; i < count; i++) {
                        fromOriginal--;
                        fromModified--;
                        this.spliceSmart(identity, [...locationPrefix, fromOriginal, 0], Number.MAX_SAFE_INTEGER, toInsert[fromModified].children, options, recurseLevels - 1);
                    }
                }
            };
            let lastStartO = Math.min(parentNode.children.length, index + deleteCount);
            let lastStartM = toInsert.length;
            for (const change of diff.changes.sort((a, b) => b.originalStart - a.originalStart)) {
                recurseSplice(lastStartO, lastStartM, lastStartO - (change.originalStart + change.originalLength));
                lastStartO = change.originalStart;
                lastStartM = change.modifiedStart - index;
                this.spliceSimple([...locationPrefix, lastStartO], change.originalLength, iterator_1.Iterable.slice(toInsert, lastStartM, lastStartM + change.modifiedLength), options);
            }
            // at this point, startO === startM === count since any remaining prefix should match
            recurseSplice(lastStartO, lastStartM, lastStartO);
        }
        spliceSimple(location, deleteCount, toInsert = iterator_1.Iterable.empty(), { onDidCreateNode, onDidDeleteNode, diffIdentityProvider }) {
            const { parentNode, listIndex, revealed, visible } = this.getParentNodeWithListIndex(location);
            const treeListElementsToInsert = [];
            const nodesToInsertIterator = iterator_1.Iterable.map(toInsert, el => this.createTreeNode(el, parentNode, parentNode.visible ? 1 /* TreeVisibility.Visible */ : 0 /* TreeVisibility.Hidden */, revealed, treeListElementsToInsert, onDidCreateNode));
            const lastIndex = location[location.length - 1];
            // figure out what's the visible child start index right before the
            // splice point
            let visibleChildStartIndex = 0;
            for (let i = lastIndex; i >= 0 && i < parentNode.children.length; i--) {
                const child = parentNode.children[i];
                if (child.visible) {
                    visibleChildStartIndex = child.visibleChildIndex;
                    break;
                }
            }
            const nodesToInsert = [];
            let insertedVisibleChildrenCount = 0;
            let renderNodeCount = 0;
            for (const child of nodesToInsertIterator) {
                nodesToInsert.push(child);
                renderNodeCount += child.renderNodeCount;
                if (child.visible) {
                    child.visibleChildIndex = visibleChildStartIndex + insertedVisibleChildrenCount++;
                }
            }
            const deletedNodes = (0, arrays_1.splice)(parentNode.children, lastIndex, deleteCount, nodesToInsert);
            if (!diffIdentityProvider) {
                parentNode.lastDiffIds = undefined;
            }
            else if (parentNode.lastDiffIds) {
                (0, arrays_1.splice)(parentNode.lastDiffIds, lastIndex, deleteCount, nodesToInsert.map(n => diffIdentityProvider.getId(n.element).toString()));
            }
            else {
                parentNode.lastDiffIds = parentNode.children.map(n => diffIdentityProvider.getId(n.element).toString());
            }
            // figure out what is the count of deleted visible children
            let deletedVisibleChildrenCount = 0;
            for (const child of deletedNodes) {
                if (child.visible) {
                    deletedVisibleChildrenCount++;
                }
            }
            // and adjust for all visible children after the splice point
            if (deletedVisibleChildrenCount !== 0) {
                for (let i = lastIndex + nodesToInsert.length; i < parentNode.children.length; i++) {
                    const child = parentNode.children[i];
                    if (child.visible) {
                        child.visibleChildIndex -= deletedVisibleChildrenCount;
                    }
                }
            }
            // update parent's visible children count
            parentNode.visibleChildrenCount += insertedVisibleChildrenCount - deletedVisibleChildrenCount;
            if (revealed && visible) {
                const visibleDeleteCount = deletedNodes.reduce((r, node) => r + (node.visible ? node.renderNodeCount : 0), 0);
                this._updateAncestorsRenderNodeCount(parentNode, renderNodeCount - visibleDeleteCount);
                this.list.splice(listIndex, visibleDeleteCount, treeListElementsToInsert);
            }
            if (deletedNodes.length > 0 && onDidDeleteNode) {
                const visit = (node) => {
                    onDidDeleteNode(node);
                    node.children.forEach(visit);
                };
                deletedNodes.forEach(visit);
            }
            this._onDidSplice.fire({ insertedNodes: nodesToInsert, deletedNodes });
            let node = parentNode;
            while (node) {
                if (node.visibility === 2 /* TreeVisibility.Recurse */) {
                    // delayed to avoid excessive refiltering, see #135941
                    this.refilterDelayer.trigger(() => this.refilter());
                    break;
                }
                node = node.parent;
            }
        }
        rerender(location) {
            if (location.length === 0) {
                throw new tree_1.TreeError(this.user, 'Invalid tree location');
            }
            const { node, listIndex, revealed } = this.getTreeNodeWithListIndex(location);
            if (node.visible && revealed) {
                this.list.splice(listIndex, 1, [node]);
            }
        }
        has(location) {
            return this.hasTreeNode(location);
        }
        getListIndex(location) {
            const { listIndex, visible, revealed } = this.getTreeNodeWithListIndex(location);
            return visible && revealed ? listIndex : -1;
        }
        getListRenderCount(location) {
            return this.getTreeNode(location).renderNodeCount;
        }
        isCollapsible(location) {
            return this.getTreeNode(location).collapsible;
        }
        setCollapsible(location, collapsible) {
            const node = this.getTreeNode(location);
            if (typeof collapsible === 'undefined') {
                collapsible = !node.collapsible;
            }
            const update = { collapsible };
            return this.eventBufferer.bufferEvents(() => this._setCollapseState(location, update));
        }
        isCollapsed(location) {
            return this.getTreeNode(location).collapsed;
        }
        setCollapsed(location, collapsed, recursive) {
            const node = this.getTreeNode(location);
            if (typeof collapsed === 'undefined') {
                collapsed = !node.collapsed;
            }
            const update = { collapsed, recursive: recursive || false };
            return this.eventBufferer.bufferEvents(() => this._setCollapseState(location, update));
        }
        _setCollapseState(location, update) {
            const { node, listIndex, revealed } = this.getTreeNodeWithListIndex(location);
            const result = this._setListNodeCollapseState(node, listIndex, revealed, update);
            if (node !== this.root && this.autoExpandSingleChildren && result && !isCollapsibleStateUpdate(update) && node.collapsible && !node.collapsed && !update.recursive) {
                let onlyVisibleChildIndex = -1;
                for (let i = 0; i < node.children.length; i++) {
                    const child = node.children[i];
                    if (child.visible) {
                        if (onlyVisibleChildIndex > -1) {
                            onlyVisibleChildIndex = -1;
                            break;
                        }
                        else {
                            onlyVisibleChildIndex = i;
                        }
                    }
                }
                if (onlyVisibleChildIndex > -1) {
                    this._setCollapseState([...location, onlyVisibleChildIndex], update);
                }
            }
            return result;
        }
        _setListNodeCollapseState(node, listIndex, revealed, update) {
            const result = this._setNodeCollapseState(node, update, false);
            if (!revealed || !node.visible || !result) {
                return result;
            }
            const previousRenderNodeCount = node.renderNodeCount;
            const toInsert = this.updateNodeAfterCollapseChange(node);
            const deleteCount = previousRenderNodeCount - (listIndex === -1 ? 0 : 1);
            this.list.splice(listIndex + 1, deleteCount, toInsert.slice(1));
            return result;
        }
        _setNodeCollapseState(node, update, deep) {
            let result;
            if (node === this.root) {
                result = false;
            }
            else {
                if (isCollapsibleStateUpdate(update)) {
                    result = node.collapsible !== update.collapsible;
                    node.collapsible = update.collapsible;
                }
                else if (!node.collapsible) {
                    result = false;
                }
                else {
                    result = node.collapsed !== update.collapsed;
                    node.collapsed = update.collapsed;
                }
                if (result) {
                    this._onDidChangeCollapseState.fire({ node, deep });
                }
            }
            if (!isCollapsibleStateUpdate(update) && update.recursive) {
                for (const child of node.children) {
                    result = this._setNodeCollapseState(child, update, true) || result;
                }
            }
            return result;
        }
        expandTo(location) {
            this.eventBufferer.bufferEvents(() => {
                let node = this.getTreeNode(location);
                while (node.parent) {
                    node = node.parent;
                    location = location.slice(0, location.length - 1);
                    if (node.collapsed) {
                        this._setCollapseState(location, { collapsed: false, recursive: false });
                    }
                }
            });
        }
        refilter() {
            const previousRenderNodeCount = this.root.renderNodeCount;
            const toInsert = this.updateNodeAfterFilterChange(this.root);
            this.list.splice(0, previousRenderNodeCount, toInsert);
            this.refilterDelayer.cancel();
        }
        createTreeNode(treeElement, parent, parentVisibility, revealed, treeListElements, onDidCreateNode) {
            const node = {
                parent,
                element: treeElement.element,
                children: [],
                depth: parent.depth + 1,
                visibleChildrenCount: 0,
                visibleChildIndex: -1,
                collapsible: typeof treeElement.collapsible === 'boolean' ? treeElement.collapsible : (typeof treeElement.collapsed !== 'undefined'),
                collapsed: typeof treeElement.collapsed === 'undefined' ? this.collapseByDefault : treeElement.collapsed,
                renderNodeCount: 1,
                visibility: 1 /* TreeVisibility.Visible */,
                visible: true,
                filterData: undefined
            };
            const visibility = this._filterNode(node, parentVisibility);
            node.visibility = visibility;
            if (revealed) {
                treeListElements.push(node);
            }
            const childElements = treeElement.children || iterator_1.Iterable.empty();
            const childRevealed = revealed && visibility !== 0 /* TreeVisibility.Hidden */ && !node.collapsed;
            let visibleChildrenCount = 0;
            let renderNodeCount = 1;
            for (const el of childElements) {
                const child = this.createTreeNode(el, node, visibility, childRevealed, treeListElements, onDidCreateNode);
                node.children.push(child);
                renderNodeCount += child.renderNodeCount;
                if (child.visible) {
                    child.visibleChildIndex = visibleChildrenCount++;
                }
            }
            if (!this.allowNonCollapsibleParents) {
                node.collapsible = node.collapsible || node.children.length > 0;
            }
            node.visibleChildrenCount = visibleChildrenCount;
            node.visible = visibility === 2 /* TreeVisibility.Recurse */ ? visibleChildrenCount > 0 : (visibility === 1 /* TreeVisibility.Visible */);
            if (!node.visible) {
                node.renderNodeCount = 0;
                if (revealed) {
                    treeListElements.pop();
                }
            }
            else if (!node.collapsed) {
                node.renderNodeCount = renderNodeCount;
            }
            onDidCreateNode?.(node);
            return node;
        }
        updateNodeAfterCollapseChange(node) {
            const previousRenderNodeCount = node.renderNodeCount;
            const result = [];
            this._updateNodeAfterCollapseChange(node, result);
            this._updateAncestorsRenderNodeCount(node.parent, result.length - previousRenderNodeCount);
            return result;
        }
        _updateNodeAfterCollapseChange(node, result) {
            if (node.visible === false) {
                return 0;
            }
            result.push(node);
            node.renderNodeCount = 1;
            if (!node.collapsed) {
                for (const child of node.children) {
                    node.renderNodeCount += this._updateNodeAfterCollapseChange(child, result);
                }
            }
            this._onDidChangeRenderNodeCount.fire(node);
            return node.renderNodeCount;
        }
        updateNodeAfterFilterChange(node) {
            const previousRenderNodeCount = node.renderNodeCount;
            const result = [];
            this._updateNodeAfterFilterChange(node, node.visible ? 1 /* TreeVisibility.Visible */ : 0 /* TreeVisibility.Hidden */, result);
            this._updateAncestorsRenderNodeCount(node.parent, result.length - previousRenderNodeCount);
            return result;
        }
        _updateNodeAfterFilterChange(node, parentVisibility, result, revealed = true) {
            let visibility;
            if (node !== this.root) {
                visibility = this._filterNode(node, parentVisibility);
                if (visibility === 0 /* TreeVisibility.Hidden */) {
                    node.visible = false;
                    node.renderNodeCount = 0;
                    return false;
                }
                if (revealed) {
                    result.push(node);
                }
            }
            const resultStartLength = result.length;
            node.renderNodeCount = node === this.root ? 0 : 1;
            let hasVisibleDescendants = false;
            if (!node.collapsed || visibility !== 0 /* TreeVisibility.Hidden */) {
                let visibleChildIndex = 0;
                for (const child of node.children) {
                    hasVisibleDescendants = this._updateNodeAfterFilterChange(child, visibility, result, revealed && !node.collapsed) || hasVisibleDescendants;
                    if (child.visible) {
                        child.visibleChildIndex = visibleChildIndex++;
                    }
                }
                node.visibleChildrenCount = visibleChildIndex;
            }
            else {
                node.visibleChildrenCount = 0;
            }
            if (node !== this.root) {
                node.visible = visibility === 2 /* TreeVisibility.Recurse */ ? hasVisibleDescendants : (visibility === 1 /* TreeVisibility.Visible */);
                node.visibility = visibility;
            }
            if (!node.visible) {
                node.renderNodeCount = 0;
                if (revealed) {
                    result.pop();
                }
            }
            else if (!node.collapsed) {
                node.renderNodeCount += result.length - resultStartLength;
            }
            this._onDidChangeRenderNodeCount.fire(node);
            return node.visible;
        }
        _updateAncestorsRenderNodeCount(node, diff) {
            if (diff === 0) {
                return;
            }
            while (node) {
                node.renderNodeCount += diff;
                this._onDidChangeRenderNodeCount.fire(node);
                node = node.parent;
            }
        }
        _filterNode(node, parentVisibility) {
            const result = this.filter ? this.filter.filter(node.element, parentVisibility) : 1 /* TreeVisibility.Visible */;
            if (typeof result === 'boolean') {
                node.filterData = undefined;
                return result ? 1 /* TreeVisibility.Visible */ : 0 /* TreeVisibility.Hidden */;
            }
            else if (isFilterResult(result)) {
                node.filterData = result.data;
                return getVisibleState(result.visibility);
            }
            else {
                node.filterData = undefined;
                return getVisibleState(result);
            }
        }
        // cheap
        hasTreeNode(location, node = this.root) {
            if (!location || location.length === 0) {
                return true;
            }
            const [index, ...rest] = location;
            if (index < 0 || index > node.children.length) {
                return false;
            }
            return this.hasTreeNode(rest, node.children[index]);
        }
        // cheap
        getTreeNode(location, node = this.root) {
            if (!location || location.length === 0) {
                return node;
            }
            const [index, ...rest] = location;
            if (index < 0 || index > node.children.length) {
                throw new tree_1.TreeError(this.user, 'Invalid tree location');
            }
            return this.getTreeNode(rest, node.children[index]);
        }
        // expensive
        getTreeNodeWithListIndex(location) {
            if (location.length === 0) {
                return { node: this.root, listIndex: -1, revealed: true, visible: false };
            }
            const { parentNode, listIndex, revealed, visible } = this.getParentNodeWithListIndex(location);
            const index = location[location.length - 1];
            if (index < 0 || index > parentNode.children.length) {
                throw new tree_1.TreeError(this.user, 'Invalid tree location');
            }
            const node = parentNode.children[index];
            return { node, listIndex, revealed, visible: visible && node.visible };
        }
        getParentNodeWithListIndex(location, node = this.root, listIndex = 0, revealed = true, visible = true) {
            const [index, ...rest] = location;
            if (index < 0 || index > node.children.length) {
                throw new tree_1.TreeError(this.user, 'Invalid tree location');
            }
            // TODO@joao perf!
            for (let i = 0; i < index; i++) {
                listIndex += node.children[i].renderNodeCount;
            }
            revealed = revealed && !node.collapsed;
            visible = visible && node.visible;
            if (rest.length === 0) {
                return { parentNode: node, listIndex, revealed, visible };
            }
            return this.getParentNodeWithListIndex(rest, node.children[index], listIndex + 1, revealed, visible);
        }
        getNode(location = []) {
            return this.getTreeNode(location);
        }
        // TODO@joao perf!
        getNodeLocation(node) {
            const location = [];
            let indexTreeNode = node; // typing woes
            while (indexTreeNode.parent) {
                location.push(indexTreeNode.parent.children.indexOf(indexTreeNode));
                indexTreeNode = indexTreeNode.parent;
            }
            return location.reverse();
        }
        getParentNodeLocation(location) {
            if (location.length === 0) {
                return undefined;
            }
            else if (location.length === 1) {
                return [];
            }
            else {
                return (0, arrays_1.tail2)(location)[0];
            }
        }
        getFirstElementChild(location) {
            const node = this.getTreeNode(location);
            if (node.children.length === 0) {
                return undefined;
            }
            return node.children[0].element;
        }
    }
    exports.IndexTreeModel = IndexTreeModel;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[250/*vs/base/browser/ui/tree/objectTreeModel*/], __M([1/*require*/,0/*exports*/,249/*vs/base/browser/ui/tree/indexTreeModel*/,159/*vs/base/browser/ui/tree/tree*/,53/*vs/base/common/iterator*/]), function (require, exports, indexTreeModel_1, tree_1, iterator_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ObjectTreeModel = void 0;
    class ObjectTreeModel {
        constructor(user, list, options = {}) {
            this.user = user;
            this.rootRef = null;
            this.nodes = new Map();
            this.nodesByIdentity = new Map();
            this.model = new indexTreeModel_1.IndexTreeModel(user, list, null, options);
            this.onDidSplice = this.model.onDidSplice;
            this.onDidChangeCollapseState = this.model.onDidChangeCollapseState;
            this.onDidChangeRenderNodeCount = this.model.onDidChangeRenderNodeCount;
            if (options.sorter) {
                this.sorter = {
                    compare(a, b) {
                        return options.sorter.compare(a.element, b.element);
                    }
                };
            }
            this.identityProvider = options.identityProvider;
        }
        setChildren(element, children = iterator_1.Iterable.empty(), options = {}) {
            const location = this.getElementLocation(element);
            this._setChildren(location, this.preserveCollapseState(children), options);
        }
        _setChildren(location, children = iterator_1.Iterable.empty(), options) {
            const insertedElements = new Set();
            const insertedElementIds = new Set();
            const onDidCreateNode = (node) => {
                if (node.element === null) {
                    return;
                }
                const tnode = node;
                insertedElements.add(tnode.element);
                this.nodes.set(tnode.element, tnode);
                if (this.identityProvider) {
                    const id = this.identityProvider.getId(tnode.element).toString();
                    insertedElementIds.add(id);
                    this.nodesByIdentity.set(id, tnode);
                }
                options.onDidCreateNode?.(tnode);
            };
            const onDidDeleteNode = (node) => {
                if (node.element === null) {
                    return;
                }
                const tnode = node;
                if (!insertedElements.has(tnode.element)) {
                    this.nodes.delete(tnode.element);
                }
                if (this.identityProvider) {
                    const id = this.identityProvider.getId(tnode.element).toString();
                    if (!insertedElementIds.has(id)) {
                        this.nodesByIdentity.delete(id);
                    }
                }
                options.onDidDeleteNode?.(tnode);
            };
            this.model.splice([...location, 0], Number.MAX_VALUE, children, { ...options, onDidCreateNode, onDidDeleteNode });
        }
        preserveCollapseState(elements = iterator_1.Iterable.empty()) {
            if (this.sorter) {
                elements = [...elements].sort(this.sorter.compare.bind(this.sorter));
            }
            return iterator_1.Iterable.map(elements, treeElement => {
                let node = this.nodes.get(treeElement.element);
                if (!node && this.identityProvider) {
                    const id = this.identityProvider.getId(treeElement.element).toString();
                    node = this.nodesByIdentity.get(id);
                }
                if (!node) {
                    let collapsed;
                    if (typeof treeElement.collapsed === 'undefined') {
                        collapsed = undefined;
                    }
                    else if (treeElement.collapsed === tree_1.ObjectTreeElementCollapseState.Collapsed || treeElement.collapsed === tree_1.ObjectTreeElementCollapseState.PreserveOrCollapsed) {
                        collapsed = true;
                    }
                    else if (treeElement.collapsed === tree_1.ObjectTreeElementCollapseState.Expanded || treeElement.collapsed === tree_1.ObjectTreeElementCollapseState.PreserveOrExpanded) {
                        collapsed = false;
                    }
                    else {
                        collapsed = Boolean(treeElement.collapsed);
                    }
                    return {
                        ...treeElement,
                        children: this.preserveCollapseState(treeElement.children),
                        collapsed
                    };
                }
                const collapsible = typeof treeElement.collapsible === 'boolean' ? treeElement.collapsible : node.collapsible;
                let collapsed;
                if (typeof treeElement.collapsed === 'undefined' || treeElement.collapsed === tree_1.ObjectTreeElementCollapseState.PreserveOrCollapsed || treeElement.collapsed === tree_1.ObjectTreeElementCollapseState.PreserveOrExpanded) {
                    collapsed = node.collapsed;
                }
                else if (treeElement.collapsed === tree_1.ObjectTreeElementCollapseState.Collapsed) {
                    collapsed = true;
                }
                else if (treeElement.collapsed === tree_1.ObjectTreeElementCollapseState.Expanded) {
                    collapsed = false;
                }
                else {
                    collapsed = Boolean(treeElement.collapsed);
                }
                return {
                    ...treeElement,
                    collapsible,
                    collapsed,
                    children: this.preserveCollapseState(treeElement.children)
                };
            });
        }
        rerender(element) {
            const location = this.getElementLocation(element);
            this.model.rerender(location);
        }
        getFirstElementChild(ref = null) {
            const location = this.getElementLocation(ref);
            return this.model.getFirstElementChild(location);
        }
        has(element) {
            return this.nodes.has(element);
        }
        getListIndex(element) {
            const location = this.getElementLocation(element);
            return this.model.getListIndex(location);
        }
        getListRenderCount(element) {
            const location = this.getElementLocation(element);
            return this.model.getListRenderCount(location);
        }
        isCollapsible(element) {
            const location = this.getElementLocation(element);
            return this.model.isCollapsible(location);
        }
        setCollapsible(element, collapsible) {
            const location = this.getElementLocation(element);
            return this.model.setCollapsible(location, collapsible);
        }
        isCollapsed(element) {
            const location = this.getElementLocation(element);
            return this.model.isCollapsed(location);
        }
        setCollapsed(element, collapsed, recursive) {
            const location = this.getElementLocation(element);
            return this.model.setCollapsed(location, collapsed, recursive);
        }
        expandTo(element) {
            const location = this.getElementLocation(element);
            this.model.expandTo(location);
        }
        refilter() {
            this.model.refilter();
        }
        getNode(element = null) {
            if (element === null) {
                return this.model.getNode(this.model.rootRef);
            }
            const node = this.nodes.get(element);
            if (!node) {
                throw new tree_1.TreeError(this.user, `Tree element not found: ${element}`);
            }
            return node;
        }
        getNodeLocation(node) {
            return node.element;
        }
        getParentNodeLocation(element) {
            if (element === null) {
                throw new tree_1.TreeError(this.user, `Invalid getParentNodeLocation call`);
            }
            const node = this.nodes.get(element);
            if (!node) {
                throw new tree_1.TreeError(this.user, `Tree element not found: ${element}`);
            }
            const location = this.model.getNodeLocation(node);
            const parentLocation = this.model.getParentNodeLocation(location);
            const parent = this.model.getNode(parentLocation);
            return parent.element;
        }
        getElementLocation(element) {
            if (element === null) {
                return [];
            }
            const node = this.nodes.get(element);
            if (!node) {
                throw new tree_1.TreeError(this.user, `Tree element not found: ${element}`);
            }
            return this.model.getNodeLocation(node);
        }
    }
    exports.ObjectTreeModel = ObjectTreeModel;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[627/*vs/base/browser/ui/tree/compressedObjectTreeModel*/], __M([1/*require*/,0/*exports*/,250/*vs/base/browser/ui/tree/objectTreeModel*/,159/*vs/base/browser/ui/tree/tree*/,13/*vs/base/common/arrays*/,6/*vs/base/common/event*/,53/*vs/base/common/iterator*/]), function (require, exports, objectTreeModel_1, tree_1, arrays_1, event_1, iterator_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CompressibleObjectTreeModel = exports.DefaultElementMapper = exports.CompressedObjectTreeModel = void 0;
    exports.compress = compress;
    exports.decompress = decompress;
    function noCompress(element) {
        const elements = [element.element];
        const incompressible = element.incompressible || false;
        return {
            element: { elements, incompressible },
            children: iterator_1.Iterable.map(iterator_1.Iterable.from(element.children), noCompress),
            collapsible: element.collapsible,
            collapsed: element.collapsed
        };
    }
    // Exported only for test reasons, do not use directly
    function compress(element) {
        const elements = [element.element];
        const incompressible = element.incompressible || false;
        let childrenIterator;
        let children;
        while (true) {
            [children, childrenIterator] = iterator_1.Iterable.consume(iterator_1.Iterable.from(element.children), 2);
            if (children.length !== 1) {
                break;
            }
            if (children[0].incompressible) {
                break;
            }
            element = children[0];
            elements.push(element.element);
        }
        return {
            element: { elements, incompressible },
            children: iterator_1.Iterable.map(iterator_1.Iterable.concat(children, childrenIterator), compress),
            collapsible: element.collapsible,
            collapsed: element.collapsed
        };
    }
    function _decompress(element, index = 0) {
        let children;
        if (index < element.element.elements.length - 1) {
            children = [_decompress(element, index + 1)];
        }
        else {
            children = iterator_1.Iterable.map(iterator_1.Iterable.from(element.children), el => _decompress(el, 0));
        }
        if (index === 0 && element.element.incompressible) {
            return {
                element: element.element.elements[index],
                children,
                incompressible: true,
                collapsible: element.collapsible,
                collapsed: element.collapsed
            };
        }
        return {
            element: element.element.elements[index],
            children,
            collapsible: element.collapsible,
            collapsed: element.collapsed
        };
    }
    // Exported only for test reasons, do not use directly
    function decompress(element) {
        return _decompress(element, 0);
    }
    function splice(treeElement, element, children) {
        if (treeElement.element === element) {
            return { ...treeElement, children };
        }
        return { ...treeElement, children: iterator_1.Iterable.map(iterator_1.Iterable.from(treeElement.children), e => splice(e, element, children)) };
    }
    const wrapIdentityProvider = (base) => ({
        getId(node) {
            return node.elements.map(e => base.getId(e).toString()).join('\0');
        }
    });
    // Exported only for test reasons, do not use directly
    class CompressedObjectTreeModel {
        get onDidSplice() { return this.model.onDidSplice; }
        get onDidChangeCollapseState() { return this.model.onDidChangeCollapseState; }
        get onDidChangeRenderNodeCount() { return this.model.onDidChangeRenderNodeCount; }
        constructor(user, list, options = {}) {
            this.user = user;
            this.rootRef = null;
            this.nodes = new Map();
            this.model = new objectTreeModel_1.ObjectTreeModel(user, list, options);
            this.enabled = typeof options.compressionEnabled === 'undefined' ? true : options.compressionEnabled;
            this.identityProvider = options.identityProvider;
        }
        setChildren(element, children = iterator_1.Iterable.empty(), options) {
            // Diffs must be deep, since the compression can affect nested elements.
            // @see https://github.com/microsoft/vscode/pull/114237#issuecomment-759425034
            const diffIdentityProvider = options.diffIdentityProvider && wrapIdentityProvider(options.diffIdentityProvider);
            if (element === null) {
                const compressedChildren = iterator_1.Iterable.map(children, this.enabled ? compress : noCompress);
                this._setChildren(null, compressedChildren, { diffIdentityProvider, diffDepth: Infinity });
                return;
            }
            const compressedNode = this.nodes.get(element);
            if (!compressedNode) {
                throw new tree_1.TreeError(this.user, 'Unknown compressed tree node');
            }
            const node = this.model.getNode(compressedNode);
            const compressedParentNode = this.model.getParentNodeLocation(compressedNode);
            const parent = this.model.getNode(compressedParentNode);
            const decompressedElement = decompress(node);
            const splicedElement = splice(decompressedElement, element, children);
            const recompressedElement = (this.enabled ? compress : noCompress)(splicedElement);
            // If the recompressed node is identical to the original, just set its children.
            // Saves work and churn diffing the parent element.
            const elementComparator = options.diffIdentityProvider
                ? ((a, b) => options.diffIdentityProvider.getId(a) === options.diffIdentityProvider.getId(b))
                : undefined;
            if ((0, arrays_1.equals)(recompressedElement.element.elements, node.element.elements, elementComparator)) {
                this._setChildren(compressedNode, recompressedElement.children || iterator_1.Iterable.empty(), { diffIdentityProvider, diffDepth: 1 });
                return;
            }
            const parentChildren = parent.children
                .map(child => child === node ? recompressedElement : child);
            this._setChildren(parent.element, parentChildren, {
                diffIdentityProvider,
                diffDepth: node.depth - parent.depth,
            });
        }
        isCompressionEnabled() {
            return this.enabled;
        }
        setCompressionEnabled(enabled) {
            if (enabled === this.enabled) {
                return;
            }
            this.enabled = enabled;
            const root = this.model.getNode();
            const rootChildren = root.children;
            const decompressedRootChildren = iterator_1.Iterable.map(rootChildren, decompress);
            const recompressedRootChildren = iterator_1.Iterable.map(decompressedRootChildren, enabled ? compress : noCompress);
            // it should be safe to always use deep diff mode here if an identity
            // provider is available, since we know the raw nodes are unchanged.
            this._setChildren(null, recompressedRootChildren, {
                diffIdentityProvider: this.identityProvider,
                diffDepth: Infinity,
            });
        }
        _setChildren(node, children, options) {
            const insertedElements = new Set();
            const onDidCreateNode = (node) => {
                for (const element of node.element.elements) {
                    insertedElements.add(element);
                    this.nodes.set(element, node.element);
                }
            };
            const onDidDeleteNode = (node) => {
                for (const element of node.element.elements) {
                    if (!insertedElements.has(element)) {
                        this.nodes.delete(element);
                    }
                }
            };
            this.model.setChildren(node, children, { ...options, onDidCreateNode, onDidDeleteNode });
        }
        has(element) {
            return this.nodes.has(element);
        }
        getListIndex(location) {
            const node = this.getCompressedNode(location);
            return this.model.getListIndex(node);
        }
        getListRenderCount(location) {
            const node = this.getCompressedNode(location);
            return this.model.getListRenderCount(node);
        }
        getNode(location) {
            if (typeof location === 'undefined') {
                return this.model.getNode();
            }
            const node = this.getCompressedNode(location);
            return this.model.getNode(node);
        }
        // TODO: review this
        getNodeLocation(node) {
            const compressedNode = this.model.getNodeLocation(node);
            if (compressedNode === null) {
                return null;
            }
            return compressedNode.elements[compressedNode.elements.length - 1];
        }
        // TODO: review this
        getParentNodeLocation(location) {
            const compressedNode = this.getCompressedNode(location);
            const parentNode = this.model.getParentNodeLocation(compressedNode);
            if (parentNode === null) {
                return null;
            }
            return parentNode.elements[parentNode.elements.length - 1];
        }
        getFirstElementChild(location) {
            const compressedNode = this.getCompressedNode(location);
            return this.model.getFirstElementChild(compressedNode);
        }
        isCollapsible(location) {
            const compressedNode = this.getCompressedNode(location);
            return this.model.isCollapsible(compressedNode);
        }
        setCollapsible(location, collapsible) {
            const compressedNode = this.getCompressedNode(location);
            return this.model.setCollapsible(compressedNode, collapsible);
        }
        isCollapsed(location) {
            const compressedNode = this.getCompressedNode(location);
            return this.model.isCollapsed(compressedNode);
        }
        setCollapsed(location, collapsed, recursive) {
            const compressedNode = this.getCompressedNode(location);
            return this.model.setCollapsed(compressedNode, collapsed, recursive);
        }
        expandTo(location) {
            const compressedNode = this.getCompressedNode(location);
            this.model.expandTo(compressedNode);
        }
        rerender(location) {
            const compressedNode = this.getCompressedNode(location);
            this.model.rerender(compressedNode);
        }
        refilter() {
            this.model.refilter();
        }
        getCompressedNode(element) {
            if (element === null) {
                return null;
            }
            const node = this.nodes.get(element);
            if (!node) {
                throw new tree_1.TreeError(this.user, `Tree element not found: ${element}`);
            }
            return node;
        }
    }
    exports.CompressedObjectTreeModel = CompressedObjectTreeModel;
    const DefaultElementMapper = elements => elements[elements.length - 1];
    exports.DefaultElementMapper = DefaultElementMapper;
    class CompressedTreeNodeWrapper {
        get element() { return this.node.element === null ? null : this.unwrapper(this.node.element); }
        get children() { return this.node.children.map(node => new CompressedTreeNodeWrapper(this.unwrapper, node)); }
        get depth() { return this.node.depth; }
        get visibleChildrenCount() { return this.node.visibleChildrenCount; }
        get visibleChildIndex() { return this.node.visibleChildIndex; }
        get collapsible() { return this.node.collapsible; }
        get collapsed() { return this.node.collapsed; }
        get visible() { return this.node.visible; }
        get filterData() { return this.node.filterData; }
        constructor(unwrapper, node) {
            this.unwrapper = unwrapper;
            this.node = node;
        }
    }
    function mapList(nodeMapper, list) {
        return {
            splice(start, deleteCount, toInsert) {
                list.splice(start, deleteCount, toInsert.map(node => nodeMapper.map(node)));
            },
            updateElementHeight(index, height) {
                list.updateElementHeight(index, height);
            }
        };
    }
    function mapOptions(compressedNodeUnwrapper, options) {
        return {
            ...options,
            identityProvider: options.identityProvider && {
                getId(node) {
                    return options.identityProvider.getId(compressedNodeUnwrapper(node));
                }
            },
            sorter: options.sorter && {
                compare(node, otherNode) {
                    return options.sorter.compare(node.elements[0], otherNode.elements[0]);
                }
            },
            filter: options.filter && {
                filter(node, parentVisibility) {
                    return options.filter.filter(compressedNodeUnwrapper(node), parentVisibility);
                }
            }
        };
    }
    class CompressibleObjectTreeModel {
        get onDidSplice() {
            return event_1.Event.map(this.model.onDidSplice, ({ insertedNodes, deletedNodes }) => ({
                insertedNodes: insertedNodes.map(node => this.nodeMapper.map(node)),
                deletedNodes: deletedNodes.map(node => this.nodeMapper.map(node)),
            }));
        }
        get onDidChangeCollapseState() {
            return event_1.Event.map(this.model.onDidChangeCollapseState, ({ node, deep }) => ({
                node: this.nodeMapper.map(node),
                deep
            }));
        }
        get onDidChangeRenderNodeCount() {
            return event_1.Event.map(this.model.onDidChangeRenderNodeCount, node => this.nodeMapper.map(node));
        }
        constructor(user, list, options = {}) {
            this.rootRef = null;
            this.elementMapper = options.elementMapper || exports.DefaultElementMapper;
            const compressedNodeUnwrapper = node => this.elementMapper(node.elements);
            this.nodeMapper = new tree_1.WeakMapper(node => new CompressedTreeNodeWrapper(compressedNodeUnwrapper, node));
            this.model = new CompressedObjectTreeModel(user, mapList(this.nodeMapper, list), mapOptions(compressedNodeUnwrapper, options));
        }
        setChildren(element, children = iterator_1.Iterable.empty(), options = {}) {
            this.model.setChildren(element, children, options);
        }
        isCompressionEnabled() {
            return this.model.isCompressionEnabled();
        }
        setCompressionEnabled(enabled) {
            this.model.setCompressionEnabled(enabled);
        }
        has(location) {
            return this.model.has(location);
        }
        getListIndex(location) {
            return this.model.getListIndex(location);
        }
        getListRenderCount(location) {
            return this.model.getListRenderCount(location);
        }
        getNode(location) {
            return this.nodeMapper.map(this.model.getNode(location));
        }
        getNodeLocation(node) {
            return node.element;
        }
        getParentNodeLocation(location) {
            return this.model.getParentNodeLocation(location);
        }
        getFirstElementChild(location) {
            const result = this.model.getFirstElementChild(location);
            if (result === null || typeof result === 'undefined') {
                return result;
            }
            return this.elementMapper(result.elements);
        }
        isCollapsible(location) {
            return this.model.isCollapsible(location);
        }
        setCollapsible(location, collapsed) {
            return this.model.setCollapsible(location, collapsed);
        }
        isCollapsed(location) {
            return this.model.isCollapsed(location);
        }
        setCollapsed(location, collapsed, recursive) {
            return this.model.setCollapsed(location, collapsed, recursive);
        }
        expandTo(location) {
            return this.model.expandTo(location);
        }
        rerender(location) {
            return this.model.rerender(location);
        }
        refilter() {
            return this.model.refilter();
        }
        getCompressedTreeNode(location = null) {
            return this.model.getNode(location);
        }
    }
    exports.CompressibleObjectTreeModel = CompressibleObjectTreeModel;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[348/*vs/base/common/process*/], __M([1/*require*/,0/*exports*/,16/*vs/base/common/platform*/]), function (require, exports, platform_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.platform = exports.env = exports.cwd = void 0;
    let safeProcess;
    // Native sandbox environment
    const vscodeGlobal = globalThis.vscode;
    if (typeof vscodeGlobal !== 'undefined' && typeof vscodeGlobal.process !== 'undefined') {
        const sandboxProcess = vscodeGlobal.process;
        safeProcess = {
            get platform() { return sandboxProcess.platform; },
            get arch() { return sandboxProcess.arch; },
            get env() { return sandboxProcess.env; },
            cwd() { return sandboxProcess.cwd(); }
        };
    }
    // Native node.js environment
    else if (typeof process !== 'undefined' && typeof process?.versions?.node === 'string') {
        safeProcess = {
            get platform() { return process.platform; },
            get arch() { return process.arch; },
            get env() { return process.env; },
            cwd() { return process.env['VSCODE_CWD'] || process.cwd(); }
        };
    }
    // Web environment
    else {
        safeProcess = {
            // Supported
            get platform() { return platform_1.isWindows ? 'win32' : platform_1.isMacintosh ? 'darwin' : 'linux'; },
            get arch() { return undefined; /* arch is undefined in web */ },
            // Unsupported
            get env() { return {}; },
            cwd() { return '/'; }
        };
    }
    /**
     * Provides safe access to the `cwd` property in node.js, sandboxed or web
     * environments.
     *
     * Note: in web, this property is hardcoded to be `/`.
     *
     * @skipMangle
     */
    exports.cwd = safeProcess.cwd;
    /**
     * Provides safe access to the `env` property in node.js, sandboxed or web
     * environments.
     *
     * Note: in web, this property is hardcoded to be `{}`.
     */
    exports.env = safeProcess.env;
    /**
     * Provides safe access to the `platform` property in node.js, sandboxed or web
     * environments.
     */
    exports.platform = safeProcess.platform;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[349/*vs/base/common/hotReload*/], __M([1/*require*/,0/*exports*/,348/*vs/base/common/process*/]), function (require, exports, process_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.isHotReloadEnabled = isHotReloadEnabled;
    exports.registerHotReloadHandler = registerHotReloadHandler;
    function isHotReloadEnabled() {
        return process_1.env && !!process_1.env['VSCODE_DEV'];
    }
    function registerHotReloadHandler(handler) {
        if (!isHotReloadEnabled()) {
            return { dispose() { } };
        }
        else {
            const handlers = registerGlobalHotReloadHandler();
            handlers.add(handler);
            return {
                dispose() { handlers.delete(handler); }
            };
        }
    }
    function registerGlobalHotReloadHandler() {
        if (!hotReloadHandlers) {
            hotReloadHandlers = new Set();
        }
        const g = globalThis;
        if (!g.$hotReload_applyNewExports) {
            g.$hotReload_applyNewExports = args => {
                const args2 = { config: { mode: undefined }, ...args };
                const results = [];
                for (const h of hotReloadHandlers) {
                    const result = h(args2);
                    if (result) {
                        results.push(result);
                    }
                }
                if (results.length > 0) {
                    return newExports => {
                        let result = false;
                        for (const r of results) {
                            if (r(newExports)) {
                                result = true;
                            }
                        }
                        return result;
                    };
                }
                return undefined;
            };
        }
        return hotReloadHandlers;
    }
    let hotReloadHandlers = undefined;
    if (isHotReloadEnabled()) {
        // This code does not run in production.
        registerHotReloadHandler(({ oldExports, newSrc, config }) => {
            if (config.mode !== 'patch-prototype') {
                return undefined;
            }
            return newExports => {
                for (const key in newExports) {
                    const exportedItem = newExports[key];
                    console.log(`[hot-reload] Patching prototype methods of '${key}'`, { exportedItem });
                    if (typeof exportedItem === 'function' && exportedItem.prototype) {
                        const oldExportedItem = oldExports[key];
                        if (oldExportedItem) {
                            for (const prop of Object.getOwnPropertyNames(exportedItem.prototype)) {
                                const descriptor = Object.getOwnPropertyDescriptor(exportedItem.prototype, prop);
                                const oldDescriptor = Object.getOwnPropertyDescriptor(oldExportedItem.prototype, prop);
                                if (descriptor?.value?.toString() !== oldDescriptor?.value?.toString()) {
                                    console.log(`[hot-reload] Patching prototype method '${key}.${prop}'`);
                                }
                                Object.defineProperty(oldExportedItem.prototype, prop, descriptor);
                            }
                            newExports[key] = oldExportedItem;
                        }
                    }
                }
                return true;
            };
        });
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[171/*vs/base/common/hotReloadHelpers*/], __M([1/*require*/,0/*exports*/,349/*vs/base/common/hotReload*/,21/*vs/base/common/observable*/]), function (require, exports, hotReload_1, observable_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.readHotReloadableExport = readHotReloadableExport;
    exports.observeHotReloadableExports = observeHotReloadableExports;
    function readHotReloadableExport(value, reader) {
        observeHotReloadableExports([value], reader);
        return value;
    }
    function observeHotReloadableExports(values, reader) {
        if ((0, hotReload_1.isHotReloadEnabled)()) {
            const o = (0, observable_1.observableSignalFromEvent)('reload', event => (0, hotReload_1.registerHotReloadHandler)(({ oldExports }) => {
                if (![...Object.values(oldExports)].some(v => values.includes(v))) {
                    return undefined;
                }
                return (_newExports) => {
                    event(undefined);
                    return true;
                };
            }));
            o.read(reader);
        }
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[99/*vs/base/common/path*/], __M([1/*require*/,0/*exports*/,348/*vs/base/common/process*/]), function (require, exports, process) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.sep = exports.extname = exports.basename = exports.dirname = exports.relative = exports.resolve = exports.join = exports.normalize = exports.posix = exports.win32 = void 0;
    const CHAR_UPPERCASE_A = 65; /* A */
    const CHAR_LOWERCASE_A = 97; /* a */
    const CHAR_UPPERCASE_Z = 90; /* Z */
    const CHAR_LOWERCASE_Z = 122; /* z */
    const CHAR_DOT = 46; /* . */
    const CHAR_FORWARD_SLASH = 47; /* / */
    const CHAR_BACKWARD_SLASH = 92; /* \ */
    const CHAR_COLON = 58; /* : */
    const CHAR_QUESTION_MARK = 63; /* ? */
    class ErrorInvalidArgType extends Error {
        constructor(name, expected, actual) {
            // determiner: 'must be' or 'must not be'
            let determiner;
            if (typeof expected === 'string' && expected.indexOf('not ') === 0) {
                determiner = 'must not be';
                expected = expected.replace(/^not /, '');
            }
            else {
                determiner = 'must be';
            }
            const type = name.indexOf('.') !== -1 ? 'property' : 'argument';
            let msg = `The "${name}" ${type} ${determiner} of type ${expected}`;
            msg += `. Received type ${typeof actual}`;
            super(msg);
            this.code = 'ERR_INVALID_ARG_TYPE';
        }
    }
    function validateObject(pathObject, name) {
        if (pathObject === null || typeof pathObject !== 'object') {
            throw new ErrorInvalidArgType(name, 'Object', pathObject);
        }
    }
    function validateString(value, name) {
        if (typeof value !== 'string') {
            throw new ErrorInvalidArgType(name, 'string', value);
        }
    }
    const platformIsWin32 = (process.platform === 'win32');
    function isPathSeparator(code) {
        return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
    }
    function isPosixPathSeparator(code) {
        return code === CHAR_FORWARD_SLASH;
    }
    function isWindowsDeviceRoot(code) {
        return (code >= CHAR_UPPERCASE_A && code <= CHAR_UPPERCASE_Z) ||
            (code >= CHAR_LOWERCASE_A && code <= CHAR_LOWERCASE_Z);
    }
    // Resolves . and .. elements in a path with directory names
    function normalizeString(path, allowAboveRoot, separator, isPathSeparator) {
        let res = '';
        let lastSegmentLength = 0;
        let lastSlash = -1;
        let dots = 0;
        let code = 0;
        for (let i = 0; i <= path.length; ++i) {
            if (i < path.length) {
                code = path.charCodeAt(i);
            }
            else if (isPathSeparator(code)) {
                break;
            }
            else {
                code = CHAR_FORWARD_SLASH;
            }
            if (isPathSeparator(code)) {
                if (lastSlash === i - 1 || dots === 1) {
                    // NOOP
                }
                else if (dots === 2) {
                    if (res.length < 2 || lastSegmentLength !== 2 ||
                        res.charCodeAt(res.length - 1) !== CHAR_DOT ||
                        res.charCodeAt(res.length - 2) !== CHAR_DOT) {
                        if (res.length > 2) {
                            const lastSlashIndex = res.lastIndexOf(separator);
                            if (lastSlashIndex === -1) {
                                res = '';
                                lastSegmentLength = 0;
                            }
                            else {
                                res = res.slice(0, lastSlashIndex);
                                lastSegmentLength = res.length - 1 - res.lastIndexOf(separator);
                            }
                            lastSlash = i;
                            dots = 0;
                            continue;
                        }
                        else if (res.length !== 0) {
                            res = '';
                            lastSegmentLength = 0;
                            lastSlash = i;
                            dots = 0;
                            continue;
                        }
                    }
                    if (allowAboveRoot) {
                        res += res.length > 0 ? `${separator}..` : '..';
                        lastSegmentLength = 2;
                    }
                }
                else {
                    if (res.length > 0) {
                        res += `${separator}${path.slice(lastSlash + 1, i)}`;
                    }
                    else {
                        res = path.slice(lastSlash + 1, i);
                    }
                    lastSegmentLength = i - lastSlash - 1;
                }
                lastSlash = i;
                dots = 0;
            }
            else if (code === CHAR_DOT && dots !== -1) {
                ++dots;
            }
            else {
                dots = -1;
            }
        }
        return res;
    }
    function formatExt(ext) {
        return ext ? `${ext[0] === '.' ? '' : '.'}${ext}` : '';
    }
    function _format(sep, pathObject) {
        validateObject(pathObject, 'pathObject');
        const dir = pathObject.dir || pathObject.root;
        const base = pathObject.base ||
            `${pathObject.name || ''}${formatExt(pathObject.ext)}`;
        if (!dir) {
            return base;
        }
        return dir === pathObject.root ? `${dir}${base}` : `${dir}${sep}${base}`;
    }
    exports.win32 = {
        // path.resolve([from ...], to)
        resolve(...pathSegments) {
            let resolvedDevice = '';
            let resolvedTail = '';
            let resolvedAbsolute = false;
            for (let i = pathSegments.length - 1; i >= -1; i--) {
                let path;
                if (i >= 0) {
                    path = pathSegments[i];
                    validateString(path, `paths[${i}]`);
                    // Skip empty entries
                    if (path.length === 0) {
                        continue;
                    }
                }
                else if (resolvedDevice.length === 0) {
                    path = process.cwd();
                }
                else {
                    // Windows has the concept of drive-specific current working
                    // directories. If we've resolved a drive letter but not yet an
                    // absolute path, get cwd for that drive, or the process cwd if
                    // the drive cwd is not available. We're sure the device is not
                    // a UNC path at this points, because UNC paths are always absolute.
                    path = process.env[`=${resolvedDevice}`] || process.cwd();
                    // Verify that a cwd was found and that it actually points
                    // to our drive. If not, default to the drive's root.
                    if (path === undefined ||
                        (path.slice(0, 2).toLowerCase() !== resolvedDevice.toLowerCase() &&
                            path.charCodeAt(2) === CHAR_BACKWARD_SLASH)) {
                        path = `${resolvedDevice}\\`;
                    }
                }
                const len = path.length;
                let rootEnd = 0;
                let device = '';
                let isAbsolute = false;
                const code = path.charCodeAt(0);
                // Try to match a root
                if (len === 1) {
                    if (isPathSeparator(code)) {
                        // `path` contains just a path separator
                        rootEnd = 1;
                        isAbsolute = true;
                    }
                }
                else if (isPathSeparator(code)) {
                    // Possible UNC root
                    // If we started with a separator, we know we at least have an
                    // absolute path of some kind (UNC or otherwise)
                    isAbsolute = true;
                    if (isPathSeparator(path.charCodeAt(1))) {
                        // Matched double path separator at beginning
                        let j = 2;
                        let last = j;
                        // Match 1 or more non-path separators
                        while (j < len && !isPathSeparator(path.charCodeAt(j))) {
                            j++;
                        }
                        if (j < len && j !== last) {
                            const firstPart = path.slice(last, j);
                            // Matched!
                            last = j;
                            // Match 1 or more path separators
                            while (j < len && isPathSeparator(path.charCodeAt(j))) {
                                j++;
                            }
                            if (j < len && j !== last) {
                                // Matched!
                                last = j;
                                // Match 1 or more non-path separators
                                while (j < len && !isPathSeparator(path.charCodeAt(j))) {
                                    j++;
                                }
                                if (j === len || j !== last) {
                                    // We matched a UNC root
                                    device = `\\\\${firstPart}\\${path.slice(last, j)}`;
                                    rootEnd = j;
                                }
                            }
                        }
                    }
                    else {
                        rootEnd = 1;
                    }
                }
                else if (isWindowsDeviceRoot(code) &&
                    path.charCodeAt(1) === CHAR_COLON) {
                    // Possible device root
                    device = path.slice(0, 2);
                    rootEnd = 2;
                    if (len > 2 && isPathSeparator(path.charCodeAt(2))) {
                        // Treat separator following drive name as an absolute path
                        // indicator
                        isAbsolute = true;
                        rootEnd = 3;
                    }
                }
                if (device.length > 0) {
                    if (resolvedDevice.length > 0) {
                        if (device.toLowerCase() !== resolvedDevice.toLowerCase()) {
                            // This path points to another device so it is not applicable
                            continue;
                        }
                    }
                    else {
                        resolvedDevice = device;
                    }
                }
                if (resolvedAbsolute) {
                    if (resolvedDevice.length > 0) {
                        break;
                    }
                }
                else {
                    resolvedTail = `${path.slice(rootEnd)}\\${resolvedTail}`;
                    resolvedAbsolute = isAbsolute;
                    if (isAbsolute && resolvedDevice.length > 0) {
                        break;
                    }
                }
            }
            // At this point the path should be resolved to a full absolute path,
            // but handle relative paths to be safe (might happen when process.cwd()
            // fails)
            // Normalize the tail path
            resolvedTail = normalizeString(resolvedTail, !resolvedAbsolute, '\\', isPathSeparator);
            return resolvedAbsolute ?
                `${resolvedDevice}\\${resolvedTail}` :
                `${resolvedDevice}${resolvedTail}` || '.';
        },
        normalize(path) {
            validateString(path, 'path');
            const len = path.length;
            if (len === 0) {
                return '.';
            }
            let rootEnd = 0;
            let device;
            let isAbsolute = false;
            const code = path.charCodeAt(0);
            // Try to match a root
            if (len === 1) {
                // `path` contains just a single char, exit early to avoid
                // unnecessary work
                return isPosixPathSeparator(code) ? '\\' : path;
            }
            if (isPathSeparator(code)) {
                // Possible UNC root
                // If we started with a separator, we know we at least have an absolute
                // path of some kind (UNC or otherwise)
                isAbsolute = true;
                if (isPathSeparator(path.charCodeAt(1))) {
                    // Matched double path separator at beginning
                    let j = 2;
                    let last = j;
                    // Match 1 or more non-path separators
                    while (j < len && !isPathSeparator(path.charCodeAt(j))) {
                        j++;
                    }
                    if (j < len && j !== last) {
                        const firstPart = path.slice(last, j);
                        // Matched!
                        last = j;
                        // Match 1 or more path separators
                        while (j < len && isPathSeparator(path.charCodeAt(j))) {
                            j++;
                        }
                        if (j < len && j !== last) {
                            // Matched!
                            last = j;
                            // Match 1 or more non-path separators
                            while (j < len && !isPathSeparator(path.charCodeAt(j))) {
                                j++;
                            }
                            if (j === len) {
                                // We matched a UNC root only
                                // Return the normalized version of the UNC root since there
                                // is nothing left to process
                                return `\\\\${firstPart}\\${path.slice(last)}\\`;
                            }
                            if (j !== last) {
                                // We matched a UNC root with leftovers
                                device = `\\\\${firstPart}\\${path.slice(last, j)}`;
                                rootEnd = j;
                            }
                        }
                    }
                }
                else {
                    rootEnd = 1;
                }
            }
            else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
                // Possible device root
                device = path.slice(0, 2);
                rootEnd = 2;
                if (len > 2 && isPathSeparator(path.charCodeAt(2))) {
                    // Treat separator following drive name as an absolute path
                    // indicator
                    isAbsolute = true;
                    rootEnd = 3;
                }
            }
            let tail = rootEnd < len ?
                normalizeString(path.slice(rootEnd), !isAbsolute, '\\', isPathSeparator) :
                '';
            if (tail.length === 0 && !isAbsolute) {
                tail = '.';
            }
            if (tail.length > 0 && isPathSeparator(path.charCodeAt(len - 1))) {
                tail += '\\';
            }
            if (device === undefined) {
                return isAbsolute ? `\\${tail}` : tail;
            }
            return isAbsolute ? `${device}\\${tail}` : `${device}${tail}`;
        },
        isAbsolute(path) {
            validateString(path, 'path');
            const len = path.length;
            if (len === 0) {
                return false;
            }
            const code = path.charCodeAt(0);
            return isPathSeparator(code) ||
                // Possible device root
                (len > 2 &&
                    isWindowsDeviceRoot(code) &&
                    path.charCodeAt(1) === CHAR_COLON &&
                    isPathSeparator(path.charCodeAt(2)));
        },
        join(...paths) {
            if (paths.length === 0) {
                return '.';
            }
            let joined;
            let firstPart;
            for (let i = 0; i < paths.length; ++i) {
                const arg = paths[i];
                validateString(arg, 'path');
                if (arg.length > 0) {
                    if (joined === undefined) {
                        joined = firstPart = arg;
                    }
                    else {
                        joined += `\\${arg}`;
                    }
                }
            }
            if (joined === undefined) {
                return '.';
            }
            // Make sure that the joined path doesn't start with two slashes, because
            // normalize() will mistake it for a UNC path then.
            //
            // This step is skipped when it is very clear that the user actually
            // intended to point at a UNC path. This is assumed when the first
            // non-empty string arguments starts with exactly two slashes followed by
            // at least one more non-slash character.
            //
            // Note that for normalize() to treat a path as a UNC path it needs to
            // have at least 2 components, so we don't filter for that here.
            // This means that the user can use join to construct UNC paths from
            // a server name and a share name; for example:
            //   path.join('//server', 'share') -> '\\\\server\\share\\')
            let needsReplace = true;
            let slashCount = 0;
            if (typeof firstPart === 'string' && isPathSeparator(firstPart.charCodeAt(0))) {
                ++slashCount;
                const firstLen = firstPart.length;
                if (firstLen > 1 && isPathSeparator(firstPart.charCodeAt(1))) {
                    ++slashCount;
                    if (firstLen > 2) {
                        if (isPathSeparator(firstPart.charCodeAt(2))) {
                            ++slashCount;
                        }
                        else {
                            // We matched a UNC path in the first part
                            needsReplace = false;
                        }
                    }
                }
            }
            if (needsReplace) {
                // Find any more consecutive slashes we need to replace
                while (slashCount < joined.length &&
                    isPathSeparator(joined.charCodeAt(slashCount))) {
                    slashCount++;
                }
                // Replace the slashes if needed
                if (slashCount >= 2) {
                    joined = `\\${joined.slice(slashCount)}`;
                }
            }
            return exports.win32.normalize(joined);
        },
        // It will solve the relative path from `from` to `to`, for instance:
        //  from = 'C:\\orandea\\test\\aaa'
        //  to = 'C:\\orandea\\impl\\bbb'
        // The output of the function should be: '..\\..\\impl\\bbb'
        relative(from, to) {
            validateString(from, 'from');
            validateString(to, 'to');
            if (from === to) {
                return '';
            }
            const fromOrig = exports.win32.resolve(from);
            const toOrig = exports.win32.resolve(to);
            if (fromOrig === toOrig) {
                return '';
            }
            from = fromOrig.toLowerCase();
            to = toOrig.toLowerCase();
            if (from === to) {
                return '';
            }
            // Trim any leading backslashes
            let fromStart = 0;
            while (fromStart < from.length &&
                from.charCodeAt(fromStart) === CHAR_BACKWARD_SLASH) {
                fromStart++;
            }
            // Trim trailing backslashes (applicable to UNC paths only)
            let fromEnd = from.length;
            while (fromEnd - 1 > fromStart &&
                from.charCodeAt(fromEnd - 1) === CHAR_BACKWARD_SLASH) {
                fromEnd--;
            }
            const fromLen = fromEnd - fromStart;
            // Trim any leading backslashes
            let toStart = 0;
            while (toStart < to.length &&
                to.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) {
                toStart++;
            }
            // Trim trailing backslashes (applicable to UNC paths only)
            let toEnd = to.length;
            while (toEnd - 1 > toStart &&
                to.charCodeAt(toEnd - 1) === CHAR_BACKWARD_SLASH) {
                toEnd--;
            }
            const toLen = toEnd - toStart;
            // Compare paths to find the longest common path from root
            const length = fromLen < toLen ? fromLen : toLen;
            let lastCommonSep = -1;
            let i = 0;
            for (; i < length; i++) {
                const fromCode = from.charCodeAt(fromStart + i);
                if (fromCode !== to.charCodeAt(toStart + i)) {
                    break;
                }
                else if (fromCode === CHAR_BACKWARD_SLASH) {
                    lastCommonSep = i;
                }
            }
            // We found a mismatch before the first common path separator was seen, so
            // return the original `to`.
            if (i !== length) {
                if (lastCommonSep === -1) {
                    return toOrig;
                }
            }
            else {
                if (toLen > length) {
                    if (to.charCodeAt(toStart + i) === CHAR_BACKWARD_SLASH) {
                        // We get here if `from` is the exact base path for `to`.
                        // For example: from='C:\\foo\\bar'; to='C:\\foo\\bar\\baz'
                        return toOrig.slice(toStart + i + 1);
                    }
                    if (i === 2) {
                        // We get here if `from` is the device root.
                        // For example: from='C:\\'; to='C:\\foo'
                        return toOrig.slice(toStart + i);
                    }
                }
                if (fromLen > length) {
                    if (from.charCodeAt(fromStart + i) === CHAR_BACKWARD_SLASH) {
                        // We get here if `to` is the exact base path for `from`.
                        // For example: from='C:\\foo\\bar'; to='C:\\foo'
                        lastCommonSep = i;
                    }
                    else if (i === 2) {
                        // We get here if `to` is the device root.
                        // For example: from='C:\\foo\\bar'; to='C:\\'
                        lastCommonSep = 3;
                    }
                }
                if (lastCommonSep === -1) {
                    lastCommonSep = 0;
                }
            }
            let out = '';
            // Generate the relative path based on the path difference between `to` and
            // `from`
            for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
                if (i === fromEnd || from.charCodeAt(i) === CHAR_BACKWARD_SLASH) {
                    out += out.length === 0 ? '..' : '\\..';
                }
            }
            toStart += lastCommonSep;
            // Lastly, append the rest of the destination (`to`) path that comes after
            // the common path parts
            if (out.length > 0) {
                return `${out}${toOrig.slice(toStart, toEnd)}`;
            }
            if (toOrig.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) {
                ++toStart;
            }
            return toOrig.slice(toStart, toEnd);
        },
        toNamespacedPath(path) {
            // Note: this will *probably* throw somewhere.
            if (typeof path !== 'string' || path.length === 0) {
                return path;
            }
            const resolvedPath = exports.win32.resolve(path);
            if (resolvedPath.length <= 2) {
                return path;
            }
            if (resolvedPath.charCodeAt(0) === CHAR_BACKWARD_SLASH) {
                // Possible UNC root
                if (resolvedPath.charCodeAt(1) === CHAR_BACKWARD_SLASH) {
                    const code = resolvedPath.charCodeAt(2);
                    if (code !== CHAR_QUESTION_MARK && code !== CHAR_DOT) {
                        // Matched non-long UNC root, convert the path to a long UNC path
                        return `\\\\?\\UNC\\${resolvedPath.slice(2)}`;
                    }
                }
            }
            else if (isWindowsDeviceRoot(resolvedPath.charCodeAt(0)) &&
                resolvedPath.charCodeAt(1) === CHAR_COLON &&
                resolvedPath.charCodeAt(2) === CHAR_BACKWARD_SLASH) {
                // Matched device root, convert the path to a long UNC path
                return `\\\\?\\${resolvedPath}`;
            }
            return path;
        },
        dirname(path) {
            validateString(path, 'path');
            const len = path.length;
            if (len === 0) {
                return '.';
            }
            let rootEnd = -1;
            let offset = 0;
            const code = path.charCodeAt(0);
            if (len === 1) {
                // `path` contains just a path separator, exit early to avoid
                // unnecessary work or a dot.
                return isPathSeparator(code) ? path : '.';
            }
            // Try to match a root
            if (isPathSeparator(code)) {
                // Possible UNC root
                rootEnd = offset = 1;
                if (isPathSeparator(path.charCodeAt(1))) {
                    // Matched double path separator at beginning
                    let j = 2;
                    let last = j;
                    // Match 1 or more non-path separators
                    while (j < len && !isPathSeparator(path.charCodeAt(j))) {
                        j++;
                    }
                    if (j < len && j !== last) {
                        // Matched!
                        last = j;
                        // Match 1 or more path separators
                        while (j < len && isPathSeparator(path.charCodeAt(j))) {
                            j++;
                        }
                        if (j < len && j !== last) {
                            // Matched!
                            last = j;
                            // Match 1 or more non-path separators
                            while (j < len && !isPathSeparator(path.charCodeAt(j))) {
                                j++;
                            }
                            if (j === len) {
                                // We matched a UNC root only
                                return path;
                            }
                            if (j !== last) {
                                // We matched a UNC root with leftovers
                                // Offset by 1 to include the separator after the UNC root to
                                // treat it as a "normal root" on top of a (UNC) root
                                rootEnd = offset = j + 1;
                            }
                        }
                    }
                }
                // Possible device root
            }
            else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
                rootEnd = len > 2 && isPathSeparator(path.charCodeAt(2)) ? 3 : 2;
                offset = rootEnd;
            }
            let end = -1;
            let matchedSlash = true;
            for (let i = len - 1; i >= offset; --i) {
                if (isPathSeparator(path.charCodeAt(i))) {
                    if (!matchedSlash) {
                        end = i;
                        break;
                    }
                }
                else {
                    // We saw the first non-path separator
                    matchedSlash = false;
                }
            }
            if (end === -1) {
                if (rootEnd === -1) {
                    return '.';
                }
                end = rootEnd;
            }
            return path.slice(0, end);
        },
        basename(path, suffix) {
            if (suffix !== undefined) {
                validateString(suffix, 'suffix');
            }
            validateString(path, 'path');
            let start = 0;
            let end = -1;
            let matchedSlash = true;
            let i;
            // Check for a drive letter prefix so as not to mistake the following
            // path separator as an extra separator at the end of the path that can be
            // disregarded
            if (path.length >= 2 &&
                isWindowsDeviceRoot(path.charCodeAt(0)) &&
                path.charCodeAt(1) === CHAR_COLON) {
                start = 2;
            }
            if (suffix !== undefined && suffix.length > 0 && suffix.length <= path.length) {
                if (suffix === path) {
                    return '';
                }
                let extIdx = suffix.length - 1;
                let firstNonSlashEnd = -1;
                for (i = path.length - 1; i >= start; --i) {
                    const code = path.charCodeAt(i);
                    if (isPathSeparator(code)) {
                        // If we reached a path separator that was not part of a set of path
                        // separators at the end of the string, stop now
                        if (!matchedSlash) {
                            start = i + 1;
                            break;
                        }
                    }
                    else {
                        if (firstNonSlashEnd === -1) {
                            // We saw the first non-path separator, remember this index in case
                            // we need it if the extension ends up not matching
                            matchedSlash = false;
                            firstNonSlashEnd = i + 1;
                        }
                        if (extIdx >= 0) {
                            // Try to match the explicit extension
                            if (code === suffix.charCodeAt(extIdx)) {
                                if (--extIdx === -1) {
                                    // We matched the extension, so mark this as the end of our path
                                    // component
                                    end = i;
                                }
                            }
                            else {
                                // Extension does not match, so our result is the entire path
                                // component
                                extIdx = -1;
                                end = firstNonSlashEnd;
                            }
                        }
                    }
                }
                if (start === end) {
                    end = firstNonSlashEnd;
                }
                else if (end === -1) {
                    end = path.length;
                }
                return path.slice(start, end);
            }
            for (i = path.length - 1; i >= start; --i) {
                if (isPathSeparator(path.charCodeAt(i))) {
                    // If we reached a path separator that was not part of a set of path
                    // separators at the end of the string, stop now
                    if (!matchedSlash) {
                        start = i + 1;
                        break;
                    }
                }
                else if (end === -1) {
                    // We saw the first non-path separator, mark this as the end of our
                    // path component
                    matchedSlash = false;
                    end = i + 1;
                }
            }
            if (end === -1) {
                return '';
            }
            return path.slice(start, end);
        },
        extname(path) {
            validateString(path, 'path');
            let start = 0;
            let startDot = -1;
            let startPart = 0;
            let end = -1;
            let matchedSlash = true;
            // Track the state of characters (if any) we see before our first dot and
            // after any path separator we find
            let preDotState = 0;
            // Check for a drive letter prefix so as not to mistake the following
            // path separator as an extra separator at the end of the path that can be
            // disregarded
            if (path.length >= 2 &&
                path.charCodeAt(1) === CHAR_COLON &&
                isWindowsDeviceRoot(path.charCodeAt(0))) {
                start = startPart = 2;
            }
            for (let i = path.length - 1; i >= start; --i) {
                const code = path.charCodeAt(i);
                if (isPathSeparator(code)) {
                    // If we reached a path separator that was not part of a set of path
                    // separators at the end of the string, stop now
                    if (!matchedSlash) {
                        startPart = i + 1;
                        break;
                    }
                    continue;
                }
                if (end === -1) {
                    // We saw the first non-path separator, mark this as the end of our
                    // extension
                    matchedSlash = false;
                    end = i + 1;
                }
                if (code === CHAR_DOT) {
                    // If this is our first dot, mark it as the start of our extension
                    if (startDot === -1) {
                        startDot = i;
                    }
                    else if (preDotState !== 1) {
                        preDotState = 1;
                    }
                }
                else if (startDot !== -1) {
                    // We saw a non-dot and non-path separator before our dot, so we should
                    // have a good chance at having a non-empty extension
                    preDotState = -1;
                }
            }
            if (startDot === -1 ||
                end === -1 ||
                // We saw a non-dot character immediately before the dot
                preDotState === 0 ||
                // The (right-most) trimmed path component is exactly '..'
                (preDotState === 1 &&
                    startDot === end - 1 &&
                    startDot === startPart + 1)) {
                return '';
            }
            return path.slice(startDot, end);
        },
        format: _format.bind(null, '\\'),
        parse(path) {
            validateString(path, 'path');
            const ret = { root: '', dir: '', base: '', ext: '', name: '' };
            if (path.length === 0) {
                return ret;
            }
            const len = path.length;
            let rootEnd = 0;
            let code = path.charCodeAt(0);
            if (len === 1) {
                if (isPathSeparator(code)) {
                    // `path` contains just a path separator, exit early to avoid
                    // unnecessary work
                    ret.root = ret.dir = path;
                    return ret;
                }
                ret.base = ret.name = path;
                return ret;
            }
            // Try to match a root
            if (isPathSeparator(code)) {
                // Possible UNC root
                rootEnd = 1;
                if (isPathSeparator(path.charCodeAt(1))) {
                    // Matched double path separator at beginning
                    let j = 2;
                    let last = j;
                    // Match 1 or more non-path separators
                    while (j < len && !isPathSeparator(path.charCodeAt(j))) {
                        j++;
                    }
                    if (j < len && j !== last) {
                        // Matched!
                        last = j;
                        // Match 1 or more path separators
                        while (j < len && isPathSeparator(path.charCodeAt(j))) {
                            j++;
                        }
                        if (j < len && j !== last) {
                            // Matched!
                            last = j;
                            // Match 1 or more non-path separators
                            while (j < len && !isPathSeparator(path.charCodeAt(j))) {
                                j++;
                            }
                            if (j === len) {
                                // We matched a UNC root only
                                rootEnd = j;
                            }
                            else if (j !== last) {
                                // We matched a UNC root with leftovers
                                rootEnd = j + 1;
                            }
                        }
                    }
                }
            }
            else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
                // Possible device root
                if (len <= 2) {
                    // `path` contains just a drive root, exit early to avoid
                    // unnecessary work
                    ret.root = ret.dir = path;
                    return ret;
                }
                rootEnd = 2;
                if (isPathSeparator(path.charCodeAt(2))) {
                    if (len === 3) {
                        // `path` contains just a drive root, exit early to avoid
                        // unnecessary work
                        ret.root = ret.dir = path;
                        return ret;
                    }
                    rootEnd = 3;
                }
            }
            if (rootEnd > 0) {
                ret.root = path.slice(0, rootEnd);
            }
            let startDot = -1;
            let startPart = rootEnd;
            let end = -1;
            let matchedSlash = true;
            let i = path.length - 1;
            // Track the state of characters (if any) we see before our first dot and
            // after any path separator we find
            let preDotState = 0;
            // Get non-dir info
            for (; i >= rootEnd; --i) {
                code = path.charCodeAt(i);
                if (isPathSeparator(code)) {
                    // If we reached a path separator that was not part of a set of path
                    // separators at the end of the string, stop now
                    if (!matchedSlash) {
                        startPart = i + 1;
                        break;
                    }
                    continue;
                }
                if (end === -1) {
                    // We saw the first non-path separator, mark this as the end of our
                    // extension
                    matchedSlash = false;
                    end = i + 1;
                }
                if (code === CHAR_DOT) {
                    // If this is our first dot, mark it as the start of our extension
                    if (startDot === -1) {
                        startDot = i;
                    }
                    else if (preDotState !== 1) {
                        preDotState = 1;
                    }
                }
                else if (startDot !== -1) {
                    // We saw a non-dot and non-path separator before our dot, so we should
                    // have a good chance at having a non-empty extension
                    preDotState = -1;
                }
            }
            if (end !== -1) {
                if (startDot === -1 ||
                    // We saw a non-dot character immediately before the dot
                    preDotState === 0 ||
                    // The (right-most) trimmed path component is exactly '..'
                    (preDotState === 1 &&
                        startDot === end - 1 &&
                        startDot === startPart + 1)) {
                    ret.base = ret.name = path.slice(startPart, end);
                }
                else {
                    ret.name = path.slice(startPart, startDot);
                    ret.base = path.slice(startPart, end);
                    ret.ext = path.slice(startDot, end);
                }
            }
            // If the directory is the root, use the entire root as the `dir` including
            // the trailing slash if any (`C:\abc` -> `C:\`). Otherwise, strip out the
            // trailing slash (`C:\abc\def` -> `C:\abc`).
            if (startPart > 0 && startPart !== rootEnd) {
                ret.dir = path.slice(0, startPart - 1);
            }
            else {
                ret.dir = ret.root;
            }
            return ret;
        },
        sep: '\\',
        delimiter: ';',
        win32: null,
        posix: null
    };
    const posixCwd = (() => {
        if (platformIsWin32) {
            // Converts Windows' backslash path separators to POSIX forward slashes
            // and truncates any drive indicator
            const regexp = /\\/g;
            return () => {
                const cwd = process.cwd().replace(regexp, '/');
                return cwd.slice(cwd.indexOf('/'));
            };
        }
        // We're already on POSIX, no need for any transformations
        return () => process.cwd();
    })();
    exports.posix = {
        // path.resolve([from ...], to)
        resolve(...pathSegments) {
            let resolvedPath = '';
            let resolvedAbsolute = false;
            for (let i = pathSegments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
                const path = i >= 0 ? pathSegments[i] : posixCwd();
                validateString(path, `paths[${i}]`);
                // Skip empty entries
                if (path.length === 0) {
                    continue;
                }
                resolvedPath = `${path}/${resolvedPath}`;
                resolvedAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH;
            }
            // At this point the path should be resolved to a full absolute path, but
            // handle relative paths to be safe (might happen when process.cwd() fails)
            // Normalize the path
            resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute, '/', isPosixPathSeparator);
            if (resolvedAbsolute) {
                return `/${resolvedPath}`;
            }
            return resolvedPath.length > 0 ? resolvedPath : '.';
        },
        normalize(path) {
            validateString(path, 'path');
            if (path.length === 0) {
                return '.';
            }
            const isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH;
            const trailingSeparator = path.charCodeAt(path.length - 1) === CHAR_FORWARD_SLASH;
            // Normalize the path
            path = normalizeString(path, !isAbsolute, '/', isPosixPathSeparator);
            if (path.length === 0) {
                if (isAbsolute) {
                    return '/';
                }
                return trailingSeparator ? './' : '.';
            }
            if (trailingSeparator) {
                path += '/';
            }
            return isAbsolute ? `/${path}` : path;
        },
        isAbsolute(path) {
            validateString(path, 'path');
            return path.length > 0 && path.charCodeAt(0) === CHAR_FORWARD_SLASH;
        },
        join(...paths) {
            if (paths.length === 0) {
                return '.';
            }
            let joined;
            for (let i = 0; i < paths.length; ++i) {
                const arg = paths[i];
                validateString(arg, 'path');
                if (arg.length > 0) {
                    if (joined === undefined) {
                        joined = arg;
                    }
                    else {
                        joined += `/${arg}`;
                    }
                }
            }
            if (joined === undefined) {
                return '.';
            }
            return exports.posix.normalize(joined);
        },
        relative(from, to) {
            validateString(from, 'from');
            validateString(to, 'to');
            if (from === to) {
                return '';
            }
            // Trim leading forward slashes.
            from = exports.posix.resolve(from);
            to = exports.posix.resolve(to);
            if (from === to) {
                return '';
            }
            const fromStart = 1;
            const fromEnd = from.length;
            const fromLen = fromEnd - fromStart;
            const toStart = 1;
            const toLen = to.length - toStart;
            // Compare paths to find the longest common path from root
            const length = (fromLen < toLen ? fromLen : toLen);
            let lastCommonSep = -1;
            let i = 0;
            for (; i < length; i++) {
                const fromCode = from.charCodeAt(fromStart + i);
                if (fromCode !== to.charCodeAt(toStart + i)) {
                    break;
                }
                else if (fromCode === CHAR_FORWARD_SLASH) {
                    lastCommonSep = i;
                }
            }
            if (i === length) {
                if (toLen > length) {
                    if (to.charCodeAt(toStart + i) === CHAR_FORWARD_SLASH) {
                        // We get here if `from` is the exact base path for `to`.
                        // For example: from='/foo/bar'; to='/foo/bar/baz'
                        return to.slice(toStart + i + 1);
                    }
                    if (i === 0) {
                        // We get here if `from` is the root
                        // For example: from='/'; to='/foo'
                        return to.slice(toStart + i);
                    }
                }
                else if (fromLen > length) {
                    if (from.charCodeAt(fromStart + i) === CHAR_FORWARD_SLASH) {
                        // We get here if `to` is the exact base path for `from`.
                        // For example: from='/foo/bar/baz'; to='/foo/bar'
                        lastCommonSep = i;
                    }
                    else if (i === 0) {
                        // We get here if `to` is the root.
                        // For example: from='/foo/bar'; to='/'
                        lastCommonSep = 0;
                    }
                }
            }
            let out = '';
            // Generate the relative path based on the path difference between `to`
            // and `from`.
            for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
                if (i === fromEnd || from.charCodeAt(i) === CHAR_FORWARD_SLASH) {
                    out += out.length === 0 ? '..' : '/..';
                }
            }
            // Lastly, append the rest of the destination (`to`) path that comes after
            // the common path parts.
            return `${out}${to.slice(toStart + lastCommonSep)}`;
        },
        toNamespacedPath(path) {
            // Non-op on posix systems
            return path;
        },
        dirname(path) {
            validateString(path, 'path');
            if (path.length === 0) {
                return '.';
            }
            const hasRoot = path.charCodeAt(0) === CHAR_FORWARD_SLASH;
            let end = -1;
            let matchedSlash = true;
            for (let i = path.length - 1; i >= 1; --i) {
                if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) {
                    if (!matchedSlash) {
                        end = i;
                        break;
                    }
                }
                else {
                    // We saw the first non-path separator
                    matchedSlash = false;
                }
            }
            if (end === -1) {
                return hasRoot ? '/' : '.';
            }
            if (hasRoot && end === 1) {
                return '//';
            }
            return path.slice(0, end);
        },
        basename(path, suffix) {
            if (suffix !== undefined) {
                validateString(suffix, 'ext');
            }
            validateString(path, 'path');
            let start = 0;
            let end = -1;
            let matchedSlash = true;
            let i;
            if (suffix !== undefined && suffix.length > 0 && suffix.length <= path.length) {
                if (suffix === path) {
                    return '';
                }
                let extIdx = suffix.length - 1;
                let firstNonSlashEnd = -1;
                for (i = path.length - 1; i >= 0; --i) {
                    const code = path.charCodeAt(i);
                    if (code === CHAR_FORWARD_SLASH) {
                        // If we reached a path separator that was not part of a set of path
                        // separators at the end of the string, stop now
                        if (!matchedSlash) {
                            start = i + 1;
                            break;
                        }
                    }
                    else {
                        if (firstNonSlashEnd === -1) {
                            // We saw the first non-path separator, remember this index in case
                            // we need it if the extension ends up not matching
                            matchedSlash = false;
                            firstNonSlashEnd = i + 1;
                        }
                        if (extIdx >= 0) {
                            // Try to match the explicit extension
                            if (code === suffix.charCodeAt(extIdx)) {
                                if (--extIdx === -1) {
                                    // We matched the extension, so mark this as the end of our path
                                    // component
                                    end = i;
                                }
                            }
                            else {
                                // Extension does not match, so our result is the entire path
                                // component
                                extIdx = -1;
                                end = firstNonSlashEnd;
                            }
                        }
                    }
                }
                if (start === end) {
                    end = firstNonSlashEnd;
                }
                else if (end === -1) {
                    end = path.length;
                }
                return path.slice(start, end);
            }
            for (i = path.length - 1; i >= 0; --i) {
                if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) {
                    // If we reached a path separator that was not part of a set of path
                    // separators at the end of the string, stop now
                    if (!matchedSlash) {
                        start = i + 1;
                        break;
                    }
                }
                else if (end === -1) {
                    // We saw the first non-path separator, mark this as the end of our
                    // path component
                    matchedSlash = false;
                    end = i + 1;
                }
            }
            if (end === -1) {
                return '';
            }
            return path.slice(start, end);
        },
        extname(path) {
            validateString(path, 'path');
            let startDot = -1;
            let startPart = 0;
            let end = -1;
            let matchedSlash = true;
            // Track the state of characters (if any) we see before our first dot and
            // after any path separator we find
            let preDotState = 0;
            for (let i = path.length - 1; i >= 0; --i) {
                const code = path.charCodeAt(i);
                if (code === CHAR_FORWARD_SLASH) {
                    // If we reached a path separator that was not part of a set of path
                    // separators at the end of the string, stop now
                    if (!matchedSlash) {
                        startPart = i + 1;
                        break;
                    }
                    continue;
                }
                if (end === -1) {
                    // We saw the first non-path separator, mark this as the end of our
                    // extension
                    matchedSlash = false;
                    end = i + 1;
                }
                if (code === CHAR_DOT) {
                    // If this is our first dot, mark it as the start of our extension
                    if (startDot === -1) {
                        startDot = i;
                    }
                    else if (preDotState !== 1) {
                        preDotState = 1;
                    }
                }
                else if (startDot !== -1) {
                    // We saw a non-dot and non-path separator before our dot, so we should
                    // have a good chance at having a non-empty extension
                    preDotState = -1;
                }
            }
            if (startDot === -1 ||
                end === -1 ||
                // We saw a non-dot character immediately before the dot
                preDotState === 0 ||
                // The (right-most) trimmed path component is exactly '..'
                (preDotState === 1 &&
                    startDot === end - 1 &&
                    startDot === startPart + 1)) {
                return '';
            }
            return path.slice(startDot, end);
        },
        format: _format.bind(null, '/'),
        parse(path) {
            validateString(path, 'path');
            const ret = { root: '', dir: '', base: '', ext: '', name: '' };
            if (path.length === 0) {
                return ret;
            }
            const isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH;
            let start;
            if (isAbsolute) {
                ret.root = '/';
                start = 1;
            }
            else {
                start = 0;
            }
            let startDot = -1;
            let startPart = 0;
            let end = -1;
            let matchedSlash = true;
            let i = path.length - 1;
            // Track the state of characters (if any) we see before our first dot and
            // after any path separator we find
            let preDotState = 0;
            // Get non-dir info
            for (; i >= start; --i) {
                const code = path.charCodeAt(i);
                if (code === CHAR_FORWARD_SLASH) {
                    // If we reached a path separator that was not part of a set of path
                    // separators at the end of the string, stop now
                    if (!matchedSlash) {
                        startPart = i + 1;
                        break;
                    }
                    continue;
                }
                if (end === -1) {
                    // We saw the first non-path separator, mark this as the end of our
                    // extension
                    matchedSlash = false;
                    end = i + 1;
                }
                if (code === CHAR_DOT) {
                    // If this is our first dot, mark it as the start of our extension
                    if (startDot === -1) {
                        startDot = i;
                    }
                    else if (preDotState !== 1) {
                        preDotState = 1;
                    }
                }
                else if (startDot !== -1) {
                    // We saw a non-dot and non-path separator before our dot, so we should
                    // have a good chance at having a non-empty extension
                    preDotState = -1;
                }
            }
            if (end !== -1) {
                const start = startPart === 0 && isAbsolute ? 1 : startPart;
                if (startDot === -1 ||
                    // We saw a non-dot character immediately before the dot
                    preDotState === 0 ||
                    // The (right-most) trimmed path component is exactly '..'
                    (preDotState === 1 &&
                        startDot === end - 1 &&
                        startDot === startPart + 1)) {
                    ret.base = ret.name = path.slice(start, end);
                }
                else {
                    ret.name = path.slice(start, startDot);
                    ret.base = path.slice(start, end);
                    ret.ext = path.slice(startDot, end);
                }
            }
            if (startPart > 0) {
                ret.dir = path.slice(0, startPart - 1);
            }
            else if (isAbsolute) {
                ret.dir = '/';
            }
            return ret;
        },
        sep: '/',
        delimiter: ':',
        win32: null,
        posix: null
    };
    exports.posix.win32 = exports.win32.win32 = exports.win32;
    exports.posix.posix = exports.win32.posix = exports.posix;
    exports.normalize = (platformIsWin32 ? exports.win32.normalize : exports.posix.normalize);
    exports.join = (platformIsWin32 ? exports.win32.join : exports.posix.join);
    exports.resolve = (platformIsWin32 ? exports.win32.resolve : exports.posix.resolve);
    exports.relative = (platformIsWin32 ? exports.win32.relative : exports.posix.relative);
    exports.dirname = (platformIsWin32 ? exports.win32.dirname : exports.posix.dirname);
    exports.basename = (platformIsWin32 ? exports.win32.basename : exports.posix.basename);
    exports.extname = (platformIsWin32 ? exports.win32.extname : exports.posix.extname);
    exports.sep = (platformIsWin32 ? exports.win32.sep : exports.posix.sep);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[251/*vs/base/common/extpath*/], __M([1/*require*/,0/*exports*/,99/*vs/base/common/path*/,16/*vs/base/common/platform*/,11/*vs/base/common/strings*/]), function (require, exports, path_1, platform_1, strings_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.isPathSeparator = isPathSeparator;
    exports.toSlashes = toSlashes;
    exports.toPosixPath = toPosixPath;
    exports.getRoot = getRoot;
    exports.isEqualOrParent = isEqualOrParent;
    exports.isWindowsDriveLetter = isWindowsDriveLetter;
    exports.hasDriveLetter = hasDriveLetter;
    function isPathSeparator(code) {
        return code === 47 /* CharCode.Slash */ || code === 92 /* CharCode.Backslash */;
    }
    /**
     * Takes a Windows OS path and changes backward slashes to forward slashes.
     * This should only be done for OS paths from Windows (or user provided paths potentially from Windows).
     * Using it on a Linux or MaxOS path might change it.
     */
    function toSlashes(osPath) {
        return osPath.replace(/[\\/]/g, path_1.posix.sep);
    }
    /**
     * Takes a Windows OS path (using backward or forward slashes) and turns it into a posix path:
     * - turns backward slashes into forward slashes
     * - makes it absolute if it starts with a drive letter
     * This should only be done for OS paths from Windows (or user provided paths potentially from Windows).
     * Using it on a Linux or MaxOS path might change it.
     */
    function toPosixPath(osPath) {
        if (osPath.indexOf('/') === -1) {
            osPath = toSlashes(osPath);
        }
        if (/^[a-zA-Z]:(\/|$)/.test(osPath)) { // starts with a drive letter
            osPath = '/' + osPath;
        }
        return osPath;
    }
    /**
     * Computes the _root_ this path, like `getRoot('c:\files') === c:\`,
     * `getRoot('files:///files/path') === files:///`,
     * or `getRoot('\\server\shares\path') === \\server\shares\`
     */
    function getRoot(path, sep = path_1.posix.sep) {
        if (!path) {
            return '';
        }
        const len = path.length;
        const firstLetter = path.charCodeAt(0);
        if (isPathSeparator(firstLetter)) {
            if (isPathSeparator(path.charCodeAt(1))) {
                // UNC candidate \\localhost\shares\ddd
                //               ^^^^^^^^^^^^^^^^^^^
                if (!isPathSeparator(path.charCodeAt(2))) {
                    let pos = 3;
                    const start = pos;
                    for (; pos < len; pos++) {
                        if (isPathSeparator(path.charCodeAt(pos))) {
                            break;
                        }
                    }
                    if (start !== pos && !isPathSeparator(path.charCodeAt(pos + 1))) {
                        pos += 1;
                        for (; pos < len; pos++) {
                            if (isPathSeparator(path.charCodeAt(pos))) {
                                return path.slice(0, pos + 1) // consume this separator
                                    .replace(/[\\/]/g, sep);
                            }
                        }
                    }
                }
            }
            // /user/far
            // ^
            return sep;
        }
        else if (isWindowsDriveLetter(firstLetter)) {
            // check for windows drive letter c:\ or c:
            if (path.charCodeAt(1) === 58 /* CharCode.Colon */) {
                if (isPathSeparator(path.charCodeAt(2))) {
                    // C:\fff
                    // ^^^
                    return path.slice(0, 2) + sep;
                }
                else {
                    // C:
                    // ^^
                    return path.slice(0, 2);
                }
            }
        }
        // check for URI
        // scheme://authority/path
        // ^^^^^^^^^^^^^^^^^^^
        let pos = path.indexOf('://');
        if (pos !== -1) {
            pos += 3; // 3 -> "://".length
            for (; pos < len; pos++) {
                if (isPathSeparator(path.charCodeAt(pos))) {
                    return path.slice(0, pos + 1); // consume this separator
                }
            }
        }
        return '';
    }
    /**
     * @deprecated please use `IUriIdentityService.extUri.isEqualOrParent` instead. If
     * you are in a context without services, consider to pass down the `extUri` from the
     * outside, or use `extUriBiasedIgnorePathCase` if you know what you are doing.
     */
    function isEqualOrParent(base, parentCandidate, ignoreCase, separator = path_1.sep) {
        if (base === parentCandidate) {
            return true;
        }
        if (!base || !parentCandidate) {
            return false;
        }
        if (parentCandidate.length > base.length) {
            return false;
        }
        if (ignoreCase) {
            const beginsWith = (0, strings_1.startsWithIgnoreCase)(base, parentCandidate);
            if (!beginsWith) {
                return false;
            }
            if (parentCandidate.length === base.length) {
                return true; // same path, different casing
            }
            let sepOffset = parentCandidate.length;
            if (parentCandidate.charAt(parentCandidate.length - 1) === separator) {
                sepOffset--; // adjust the expected sep offset in case our candidate already ends in separator character
            }
            return base.charAt(sepOffset) === separator;
        }
        if (parentCandidate.charAt(parentCandidate.length - 1) !== separator) {
            parentCandidate += separator;
        }
        return base.indexOf(parentCandidate) === 0;
    }
    function isWindowsDriveLetter(char0) {
        return char0 >= 65 /* CharCode.A */ && char0 <= 90 /* CharCode.Z */ || char0 >= 97 /* CharCode.a */ && char0 <= 122 /* CharCode.z */;
    }
    function hasDriveLetter(path, isWindowsOS = platform_1.isWindows) {
        if (isWindowsOS) {
            return isWindowsDriveLetter(path.charCodeAt(0)) && path.charCodeAt(1) === 58 /* CharCode.Colon */;
        }
        return false;
    }
});

define(__m[628/*vs/base/common/fuzzyScorer*/], __M([1/*require*/,0/*exports*/,82/*vs/base/common/filters*/,99/*vs/base/common/path*/,16/*vs/base/common/platform*/,11/*vs/base/common/strings*/]), function (require, exports, filters_1, path_1, platform_1, strings_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.scoreFuzzy2 = scoreFuzzy2;
    exports.prepareQuery = prepareQuery;
    exports.pieceToQuery = pieceToQuery;
    const NO_SCORE2 = [undefined, []];
    function scoreFuzzy2(target, query, patternStart = 0, wordStart = 0) {
        // Score: multiple inputs
        const preparedQuery = query;
        if (preparedQuery.values && preparedQuery.values.length > 1) {
            return doScoreFuzzy2Multiple(target, preparedQuery.values, patternStart, wordStart);
        }
        // Score: single input
        return doScoreFuzzy2Single(target, query, patternStart, wordStart);
    }
    function doScoreFuzzy2Multiple(target, query, patternStart, wordStart) {
        let totalScore = 0;
        const totalMatches = [];
        for (const queryPiece of query) {
            const [score, matches] = doScoreFuzzy2Single(target, queryPiece, patternStart, wordStart);
            if (typeof score !== 'number') {
                // if a single query value does not match, return with
                // no score entirely, we require all queries to match
                return NO_SCORE2;
            }
            totalScore += score;
            totalMatches.push(...matches);
        }
        // if we have a score, ensure that the positions are
        // sorted in ascending order and distinct
        return [totalScore, normalizeMatches(totalMatches)];
    }
    function doScoreFuzzy2Single(target, query, patternStart, wordStart) {
        const score = (0, filters_1.fuzzyScore)(query.original, query.originalLowercase, patternStart, target, target.toLowerCase(), wordStart, { firstMatchCanBeWeak: true, boostFullMatch: true });
        if (!score) {
            return NO_SCORE2;
        }
        return [score[0], (0, filters_1.createMatches)(score)];
    }
    const NO_ITEM_SCORE = Object.freeze({ score: 0 });
    function normalizeMatches(matches) {
        // sort matches by start to be able to normalize
        const sortedMatches = matches.sort((matchA, matchB) => {
            return matchA.start - matchB.start;
        });
        // merge matches that overlap
        const normalizedMatches = [];
        let currentMatch = undefined;
        for (const match of sortedMatches) {
            // if we have no current match or the matches
            // do not overlap, we take it as is and remember
            // it for future merging
            if (!currentMatch || !matchOverlaps(currentMatch, match)) {
                currentMatch = match;
                normalizedMatches.push(match);
            }
            // otherwise we merge the matches
            else {
                currentMatch.start = Math.min(currentMatch.start, match.start);
                currentMatch.end = Math.max(currentMatch.end, match.end);
            }
        }
        return normalizedMatches;
    }
    function matchOverlaps(matchA, matchB) {
        if (matchA.end < matchB.start) {
            return false; // A ends before B starts
        }
        if (matchB.end < matchA.start) {
            return false; // B ends before A starts
        }
        return true;
    }
    /*
     * If a query is wrapped in quotes, the user does not want to
     * use fuzzy search for this query.
     */
    function queryExpectsExactMatch(query) {
        return query.startsWith('"') && query.endsWith('"');
    }
    /**
     * Helper function to prepare a search value for scoring by removing unwanted characters
     * and allowing to score on multiple pieces separated by whitespace character.
     */
    const MULTIPLE_QUERY_VALUES_SEPARATOR = ' ';
    function prepareQuery(original) {
        if (typeof original !== 'string') {
            original = '';
        }
        const originalLowercase = original.toLowerCase();
        const { pathNormalized, normalized, normalizedLowercase } = normalizeQuery(original);
        const containsPathSeparator = pathNormalized.indexOf(path_1.sep) >= 0;
        const expectExactMatch = queryExpectsExactMatch(original);
        let values = undefined;
        const originalSplit = original.split(MULTIPLE_QUERY_VALUES_SEPARATOR);
        if (originalSplit.length > 1) {
            for (const originalPiece of originalSplit) {
                const expectExactMatchPiece = queryExpectsExactMatch(originalPiece);
                const { pathNormalized: pathNormalizedPiece, normalized: normalizedPiece, normalizedLowercase: normalizedLowercasePiece } = normalizeQuery(originalPiece);
                if (normalizedPiece) {
                    if (!values) {
                        values = [];
                    }
                    values.push({
                        original: originalPiece,
                        originalLowercase: originalPiece.toLowerCase(),
                        pathNormalized: pathNormalizedPiece,
                        normalized: normalizedPiece,
                        normalizedLowercase: normalizedLowercasePiece,
                        expectContiguousMatch: expectExactMatchPiece
                    });
                }
            }
        }
        return { original, originalLowercase, pathNormalized, normalized, normalizedLowercase, values, containsPathSeparator, expectContiguousMatch: expectExactMatch };
    }
    function normalizeQuery(original) {
        let pathNormalized;
        if (platform_1.isWindows) {
            pathNormalized = original.replace(/\//g, path_1.sep); // Help Windows users to search for paths when using slash
        }
        else {
            pathNormalized = original.replace(/\\/g, path_1.sep); // Help macOS/Linux users to search for paths when using backslash
        }
        // we remove quotes here because quotes are used for exact match search
        const normalized = (0, strings_1.stripWildcards)(pathNormalized).replace(/\s|"/g, '');
        return {
            pathNormalized,
            normalized,
            normalizedLowercase: normalized.toLowerCase()
        };
    }
    function pieceToQuery(arg1) {
        if (Array.isArray(arg1)) {
            return prepareQuery(arg1.map(piece => piece.original).join(MULTIPLE_QUERY_VALUES_SEPARATOR));
        }
        return prepareQuery(arg1.original);
    }
});
//#endregion

define(__m[350/*vs/base/common/glob*/], __M([1/*require*/,0/*exports*/,14/*vs/base/common/async*/,251/*vs/base/common/extpath*/,45/*vs/base/common/map*/,99/*vs/base/common/path*/,16/*vs/base/common/platform*/,11/*vs/base/common/strings*/]), function (require, exports, async_1, extpath_1, map_1, path_1, platform_1, strings_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.GLOB_SPLIT = exports.GLOBSTAR = void 0;
    exports.splitGlobAware = splitGlobAware;
    exports.match = match;
    exports.parse = parse;
    exports.isRelativePattern = isRelativePattern;
    exports.GLOBSTAR = '**';
    exports.GLOB_SPLIT = '/';
    const PATH_REGEX = '[/\\\\]'; // any slash or backslash
    const NO_PATH_REGEX = '[^/\\\\]'; // any non-slash and non-backslash
    const ALL_FORWARD_SLASHES = /\//g;
    function starsToRegExp(starCount, isLastPattern) {
        switch (starCount) {
            case 0:
                return '';
            case 1:
                return `${NO_PATH_REGEX}*?`; // 1 star matches any number of characters except path separator (/ and \) - non greedy (?)
            default:
                // Matches:  (Path Sep OR Path Val followed by Path Sep) 0-many times except when it's the last pattern
                //           in which case also matches (Path Sep followed by Path Val)
                // Group is non capturing because we don't need to capture at all (?:...)
                // Overall we use non-greedy matching because it could be that we match too much
                return `(?:${PATH_REGEX}|${NO_PATH_REGEX}+${PATH_REGEX}${isLastPattern ? `|${PATH_REGEX}${NO_PATH_REGEX}+` : ''})*?`;
        }
    }
    function splitGlobAware(pattern, splitChar) {
        if (!pattern) {
            return [];
        }
        const segments = [];
        let inBraces = false;
        let inBrackets = false;
        let curVal = '';
        for (const char of pattern) {
            switch (char) {
                case splitChar:
                    if (!inBraces && !inBrackets) {
                        segments.push(curVal);
                        curVal = '';
                        continue;
                    }
                    break;
                case '{':
                    inBraces = true;
                    break;
                case '}':
                    inBraces = false;
                    break;
                case '[':
                    inBrackets = true;
                    break;
                case ']':
                    inBrackets = false;
                    break;
            }
            curVal += char;
        }
        // Tail
        if (curVal) {
            segments.push(curVal);
        }
        return segments;
    }
    function parseRegExp(pattern) {
        if (!pattern) {
            return '';
        }
        let regEx = '';
        // Split up into segments for each slash found
        const segments = splitGlobAware(pattern, exports.GLOB_SPLIT);
        // Special case where we only have globstars
        if (segments.every(segment => segment === exports.GLOBSTAR)) {
            regEx = '.*';
        }
        // Build regex over segments
        else {
            let previousSegmentWasGlobStar = false;
            segments.forEach((segment, index) => {
                // Treat globstar specially
                if (segment === exports.GLOBSTAR) {
                    // if we have more than one globstar after another, just ignore it
                    if (previousSegmentWasGlobStar) {
                        return;
                    }
                    regEx += starsToRegExp(2, index === segments.length - 1);
                }
                // Anything else, not globstar
                else {
                    // States
                    let inBraces = false;
                    let braceVal = '';
                    let inBrackets = false;
                    let bracketVal = '';
                    for (const char of segment) {
                        // Support brace expansion
                        if (char !== '}' && inBraces) {
                            braceVal += char;
                            continue;
                        }
                        // Support brackets
                        if (inBrackets && (char !== ']' || !bracketVal) /* ] is literally only allowed as first character in brackets to match it */) {
                            let res;
                            // range operator
                            if (char === '-') {
                                res = char;
                            }
                            // negation operator (only valid on first index in bracket)
                            else if ((char === '^' || char === '!') && !bracketVal) {
                                res = '^';
                            }
                            // glob split matching is not allowed within character ranges
                            // see http://man7.org/linux/man-pages/man7/glob.7.html
                            else if (char === exports.GLOB_SPLIT) {
                                res = '';
                            }
                            // anything else gets escaped
                            else {
                                res = (0, strings_1.escapeRegExpCharacters)(char);
                            }
                            bracketVal += res;
                            continue;
                        }
                        switch (char) {
                            case '{':
                                inBraces = true;
                                continue;
                            case '[':
                                inBrackets = true;
                                continue;
                            case '}': {
                                const choices = splitGlobAware(braceVal, ',');
                                // Converts {foo,bar} => [foo|bar]
                                const braceRegExp = `(?:${choices.map(choice => parseRegExp(choice)).join('|')})`;
                                regEx += braceRegExp;
                                inBraces = false;
                                braceVal = '';
                                break;
                            }
                            case ']': {
                                regEx += ('[' + bracketVal + ']');
                                inBrackets = false;
                                bracketVal = '';
                                break;
                            }
                            case '?':
                                regEx += NO_PATH_REGEX; // 1 ? matches any single character except path separator (/ and \)
                                continue;
                            case '*':
                                regEx += starsToRegExp(1);
                                continue;
                            default:
                                regEx += (0, strings_1.escapeRegExpCharacters)(char);
                        }
                    }
                    // Tail: Add the slash we had split on if there is more to
                    // come and the remaining pattern is not a globstar
                    // For example if pattern: some/**/*.js we want the "/" after
                    // some to be included in the RegEx to prevent a folder called
                    // "something" to match as well.
                    if (index < segments.length - 1 && // more segments to come after this
                        (segments[index + 1] !== exports.GLOBSTAR || // next segment is not **, or...
                            index + 2 < segments.length // ...next segment is ** but there is more segments after that
                        )) {
                        regEx += PATH_REGEX;
                    }
                }
                // update globstar state
                previousSegmentWasGlobStar = (segment === exports.GLOBSTAR);
            });
        }
        return regEx;
    }
    // regexes to check for trivial glob patterns that just check for String#endsWith
    const T1 = /^\*\*\/\*\.[\w\.-]+$/; // **/*.something
    const T2 = /^\*\*\/([\w\.-]+)\/?$/; // **/something
    const T3 = /^{\*\*\/\*?[\w\.-]+\/?(,\*\*\/\*?[\w\.-]+\/?)*}$/; // {**/*.something,**/*.else} or {**/package.json,**/project.json}
    const T3_2 = /^{\*\*\/\*?[\w\.-]+(\/(\*\*)?)?(,\*\*\/\*?[\w\.-]+(\/(\*\*)?)?)*}$/; // Like T3, with optional trailing /**
    const T4 = /^\*\*((\/[\w\.-]+)+)\/?$/; // **/something/else
    const T5 = /^([\w\.-]+(\/[\w\.-]+)*)\/?$/; // something/else
    const CACHE = new map_1.LRUCache(10000); // bounded to 10000 elements
    const FALSE = function () {
        return false;
    };
    const NULL = function () {
        return null;
    };
    function parsePattern(arg1, options) {
        if (!arg1) {
            return NULL;
        }
        // Handle relative patterns
        let pattern;
        if (typeof arg1 !== 'string') {
            pattern = arg1.pattern;
        }
        else {
            pattern = arg1;
        }
        // Whitespace trimming
        pattern = pattern.trim();
        // Check cache
        const patternKey = `${pattern}_${!!options.trimForExclusions}`;
        let parsedPattern = CACHE.get(patternKey);
        if (parsedPattern) {
            return wrapRelativePattern(parsedPattern, arg1);
        }
        // Check for Trivials
        let match;
        if (T1.test(pattern)) {
            parsedPattern = trivia1(pattern.substr(4), pattern); // common pattern: **/*.txt just need endsWith check
        }
        else if (match = T2.exec(trimForExclusions(pattern, options))) { // common pattern: **/some.txt just need basename check
            parsedPattern = trivia2(match[1], pattern);
        }
        else if ((options.trimForExclusions ? T3_2 : T3).test(pattern)) { // repetition of common patterns (see above) {**/*.txt,**/*.png}
            parsedPattern = trivia3(pattern, options);
        }
        else if (match = T4.exec(trimForExclusions(pattern, options))) { // common pattern: **/something/else just need endsWith check
            parsedPattern = trivia4and5(match[1].substr(1), pattern, true);
        }
        else if (match = T5.exec(trimForExclusions(pattern, options))) { // common pattern: something/else just need equals check
            parsedPattern = trivia4and5(match[1], pattern, false);
        }
        // Otherwise convert to pattern
        else {
            parsedPattern = toRegExp(pattern);
        }
        // Cache
        CACHE.set(patternKey, parsedPattern);
        return wrapRelativePattern(parsedPattern, arg1);
    }
    function wrapRelativePattern(parsedPattern, arg2) {
        if (typeof arg2 === 'string') {
            return parsedPattern;
        }
        const wrappedPattern = function (path, basename) {
            if (!(0, extpath_1.isEqualOrParent)(path, arg2.base, !platform_1.isLinux)) {
                // skip glob matching if `base` is not a parent of `path`
                return null;
            }
            // Given we have checked `base` being a parent of `path`,
            // we can now remove the `base` portion of the `path`
            // and only match on the remaining path components
            // For that we try to extract the portion of the `path`
            // that comes after the `base` portion. We have to account
            // for the fact that `base` might end in a path separator
            // (https://github.com/microsoft/vscode/issues/162498)
            return parsedPattern((0, strings_1.ltrim)(path.substr(arg2.base.length), path_1.sep), basename);
        };
        // Make sure to preserve associated metadata
        wrappedPattern.allBasenames = parsedPattern.allBasenames;
        wrappedPattern.allPaths = parsedPattern.allPaths;
        wrappedPattern.basenames = parsedPattern.basenames;
        wrappedPattern.patterns = parsedPattern.patterns;
        return wrappedPattern;
    }
    function trimForExclusions(pattern, options) {
        return options.trimForExclusions && pattern.endsWith('/**') ? pattern.substr(0, pattern.length - 2) : pattern; // dropping **, tailing / is dropped later
    }
    // common pattern: **/*.txt just need endsWith check
    function trivia1(base, pattern) {
        return function (path, basename) {
            return typeof path === 'string' && path.endsWith(base) ? pattern : null;
        };
    }
    // common pattern: **/some.txt just need basename check
    function trivia2(base, pattern) {
        const slashBase = `/${base}`;
        const backslashBase = `\\${base}`;
        const parsedPattern = function (path, basename) {
            if (typeof path !== 'string') {
                return null;
            }
            if (basename) {
                return basename === base ? pattern : null;
            }
            return path === base || path.endsWith(slashBase) || path.endsWith(backslashBase) ? pattern : null;
        };
        const basenames = [base];
        parsedPattern.basenames = basenames;
        parsedPattern.patterns = [pattern];
        parsedPattern.allBasenames = basenames;
        return parsedPattern;
    }
    // repetition of common patterns (see above) {**/*.txt,**/*.png}
    function trivia3(pattern, options) {
        const parsedPatterns = aggregateBasenameMatches(pattern.slice(1, -1)
            .split(',')
            .map(pattern => parsePattern(pattern, options))
            .filter(pattern => pattern !== NULL), pattern);
        const patternsLength = parsedPatterns.length;
        if (!patternsLength) {
            return NULL;
        }
        if (patternsLength === 1) {
            return parsedPatterns[0];
        }
        const parsedPattern = function (path, basename) {
            for (let i = 0, n = parsedPatterns.length; i < n; i++) {
                if (parsedPatterns[i](path, basename)) {
                    return pattern;
                }
            }
            return null;
        };
        const withBasenames = parsedPatterns.find(pattern => !!pattern.allBasenames);
        if (withBasenames) {
            parsedPattern.allBasenames = withBasenames.allBasenames;
        }
        const allPaths = parsedPatterns.reduce((all, current) => current.allPaths ? all.concat(current.allPaths) : all, []);
        if (allPaths.length) {
            parsedPattern.allPaths = allPaths;
        }
        return parsedPattern;
    }
    // common patterns: **/something/else just need endsWith check, something/else just needs and equals check
    function trivia4and5(targetPath, pattern, matchPathEnds) {
        const usingPosixSep = path_1.sep === path_1.posix.sep;
        const nativePath = usingPosixSep ? targetPath : targetPath.replace(ALL_FORWARD_SLASHES, path_1.sep);
        const nativePathEnd = path_1.sep + nativePath;
        const targetPathEnd = path_1.posix.sep + targetPath;
        let parsedPattern;
        if (matchPathEnds) {
            parsedPattern = function (path, basename) {
                return typeof path === 'string' && ((path === nativePath || path.endsWith(nativePathEnd)) || !usingPosixSep && (path === targetPath || path.endsWith(targetPathEnd))) ? pattern : null;
            };
        }
        else {
            parsedPattern = function (path, basename) {
                return typeof path === 'string' && (path === nativePath || (!usingPosixSep && path === targetPath)) ? pattern : null;
            };
        }
        parsedPattern.allPaths = [(matchPathEnds ? '*/' : './') + targetPath];
        return parsedPattern;
    }
    function toRegExp(pattern) {
        try {
            const regExp = new RegExp(`^${parseRegExp(pattern)}$`);
            return function (path) {
                regExp.lastIndex = 0; // reset RegExp to its initial state to reuse it!
                return typeof path === 'string' && regExp.test(path) ? pattern : null;
            };
        }
        catch (error) {
            return NULL;
        }
    }
    function match(arg1, path, hasSibling) {
        if (!arg1 || typeof path !== 'string') {
            return false;
        }
        return parse(arg1)(path, undefined, hasSibling);
    }
    function parse(arg1, options = {}) {
        if (!arg1) {
            return FALSE;
        }
        // Glob with String
        if (typeof arg1 === 'string' || isRelativePattern(arg1)) {
            const parsedPattern = parsePattern(arg1, options);
            if (parsedPattern === NULL) {
                return FALSE;
            }
            const resultPattern = function (path, basename) {
                return !!parsedPattern(path, basename);
            };
            if (parsedPattern.allBasenames) {
                resultPattern.allBasenames = parsedPattern.allBasenames;
            }
            if (parsedPattern.allPaths) {
                resultPattern.allPaths = parsedPattern.allPaths;
            }
            return resultPattern;
        }
        // Glob with Expression
        return parsedExpression(arg1, options);
    }
    function isRelativePattern(obj) {
        const rp = obj;
        if (!rp) {
            return false;
        }
        return typeof rp.base === 'string' && typeof rp.pattern === 'string';
    }
    function parsedExpression(expression, options) {
        const parsedPatterns = aggregateBasenameMatches(Object.getOwnPropertyNames(expression)
            .map(pattern => parseExpressionPattern(pattern, expression[pattern], options))
            .filter(pattern => pattern !== NULL));
        const patternsLength = parsedPatterns.length;
        if (!patternsLength) {
            return NULL;
        }
        if (!parsedPatterns.some(parsedPattern => !!parsedPattern.requiresSiblings)) {
            if (patternsLength === 1) {
                return parsedPatterns[0];
            }
            const resultExpression = function (path, basename) {
                let resultPromises = undefined;
                for (let i = 0, n = parsedPatterns.length; i < n; i++) {
                    const result = parsedPatterns[i](path, basename);
                    if (typeof result === 'string') {
                        return result; // immediately return as soon as the first expression matches
                    }
                    // If the result is a promise, we have to keep it for
                    // later processing and await the result properly.
                    if ((0, async_1.isThenable)(result)) {
                        if (!resultPromises) {
                            resultPromises = [];
                        }
                        resultPromises.push(result);
                    }
                }
                // With result promises, we have to loop over each and
                // await the result before we can return any result.
                if (resultPromises) {
                    return (async () => {
                        for (const resultPromise of resultPromises) {
                            const result = await resultPromise;
                            if (typeof result === 'string') {
                                return result;
                            }
                        }
                        return null;
                    })();
                }
                return null;
            };
            const withBasenames = parsedPatterns.find(pattern => !!pattern.allBasenames);
            if (withBasenames) {
                resultExpression.allBasenames = withBasenames.allBasenames;
            }
            const allPaths = parsedPatterns.reduce((all, current) => current.allPaths ? all.concat(current.allPaths) : all, []);
            if (allPaths.length) {
                resultExpression.allPaths = allPaths;
            }
            return resultExpression;
        }
        const resultExpression = function (path, base, hasSibling) {
            let name = undefined;
            let resultPromises = undefined;
            for (let i = 0, n = parsedPatterns.length; i < n; i++) {
                // Pattern matches path
                const parsedPattern = parsedPatterns[i];
                if (parsedPattern.requiresSiblings && hasSibling) {
                    if (!base) {
                        base = (0, path_1.basename)(path);
                    }
                    if (!name) {
                        name = base.substr(0, base.length - (0, path_1.extname)(path).length);
                    }
                }
                const result = parsedPattern(path, base, name, hasSibling);
                if (typeof result === 'string') {
                    return result; // immediately return as soon as the first expression matches
                }
                // If the result is a promise, we have to keep it for
                // later processing and await the result properly.
                if ((0, async_1.isThenable)(result)) {
                    if (!resultPromises) {
                        resultPromises = [];
                    }
                    resultPromises.push(result);
                }
            }
            // With result promises, we have to loop over each and
            // await the result before we can return any result.
            if (resultPromises) {
                return (async () => {
                    for (const resultPromise of resultPromises) {
                        const result = await resultPromise;
                        if (typeof result === 'string') {
                            return result;
                        }
                    }
                    return null;
                })();
            }
            return null;
        };
        const withBasenames = parsedPatterns.find(pattern => !!pattern.allBasenames);
        if (withBasenames) {
            resultExpression.allBasenames = withBasenames.allBasenames;
        }
        const allPaths = parsedPatterns.reduce((all, current) => current.allPaths ? all.concat(current.allPaths) : all, []);
        if (allPaths.length) {
            resultExpression.allPaths = allPaths;
        }
        return resultExpression;
    }
    function parseExpressionPattern(pattern, value, options) {
        if (value === false) {
            return NULL; // pattern is disabled
        }
        const parsedPattern = parsePattern(pattern, options);
        if (parsedPattern === NULL) {
            return NULL;
        }
        // Expression Pattern is <boolean>
        if (typeof value === 'boolean') {
            return parsedPattern;
        }
        // Expression Pattern is <SiblingClause>
        if (value) {
            const when = value.when;
            if (typeof when === 'string') {
                const result = (path, basename, name, hasSibling) => {
                    if (!hasSibling || !parsedPattern(path, basename)) {
                        return null;
                    }
                    const clausePattern = when.replace('$(basename)', () => name);
                    const matched = hasSibling(clausePattern);
                    return (0, async_1.isThenable)(matched) ?
                        matched.then(match => match ? pattern : null) :
                        matched ? pattern : null;
                };
                result.requiresSiblings = true;
                return result;
            }
        }
        // Expression is anything
        return parsedPattern;
    }
    function aggregateBasenameMatches(parsedPatterns, result) {
        const basenamePatterns = parsedPatterns.filter(parsedPattern => !!parsedPattern.basenames);
        if (basenamePatterns.length < 2) {
            return parsedPatterns;
        }
        const basenames = basenamePatterns.reduce((all, current) => {
            const basenames = current.basenames;
            return basenames ? all.concat(basenames) : all;
        }, []);
        let patterns;
        if (result) {
            patterns = [];
            for (let i = 0, n = basenames.length; i < n; i++) {
                patterns.push(result);
            }
        }
        else {
            patterns = basenamePatterns.reduce((all, current) => {
                const patterns = current.patterns;
                return patterns ? all.concat(patterns) : all;
            }, []);
        }
        const aggregate = function (path, basename) {
            if (typeof path !== 'string') {
                return null;
            }
            if (!basename) {
                let i;
                for (i = path.length; i > 0; i--) {
                    const ch = path.charCodeAt(i - 1);
                    if (ch === 47 /* CharCode.Slash */ || ch === 92 /* CharCode.Backslash */) {
                        break;
                    }
                }
                basename = path.substr(i);
            }
            const index = basenames.indexOf(basename);
            return index !== -1 ? patterns[index] : null;
        };
        aggregate.basenames = basenames;
        aggregate.patterns = patterns;
        aggregate.allBasenames = basenames;
        const aggregatedPatterns = parsedPatterns.filter(parsedPattern => !parsedPattern.basenames);
        aggregatedPatterns.push(aggregate);
        return aggregatedPatterns;
    }
});

define(__m[629/*vs/base/common/labels*/], __M([1/*require*/,0/*exports*/,251/*vs/base/common/extpath*/,16/*vs/base/common/platform*/]), function (require, exports, extpath_1, platform_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.normalizeDriveLetter = normalizeDriveLetter;
    function normalizeDriveLetter(path, isWindowsOS = platform_1.isWindows) {
        if ((0, extpath_1.hasDriveLetter)(path, isWindowsOS)) {
            return path.charAt(0).toUpperCase() + path.slice(1);
        }
        return path;
    }
    let normalizedUserHomeCached = Object.create(null);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[22/*vs/base/common/uri*/], __M([1/*require*/,0/*exports*/,99/*vs/base/common/path*/,16/*vs/base/common/platform*/]), function (require, exports, paths, platform_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.URI = void 0;
    exports.uriToFsPath = uriToFsPath;
    const _schemePattern = /^\w[\w\d+.-]*$/;
    const _singleSlashStart = /^\//;
    const _doubleSlashStart = /^\/\//;
    function _validateUri(ret, _strict) {
        // scheme, must be set
        if (!ret.scheme && _strict) {
            throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${ret.authority}", path: "${ret.path}", query: "${ret.query}", fragment: "${ret.fragment}"}`);
        }
        // scheme, https://tools.ietf.org/html/rfc3986#section-3.1
        // ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
        if (ret.scheme && !_schemePattern.test(ret.scheme)) {
            throw new Error('[UriError]: Scheme contains illegal characters.');
        }
        // path, http://tools.ietf.org/html/rfc3986#section-3.3
        // If a URI contains an authority component, then the path component
        // must either be empty or begin with a slash ("/") character.  If a URI
        // does not contain an authority component, then the path cannot begin
        // with two slash characters ("//").
        if (ret.path) {
            if (ret.authority) {
                if (!_singleSlashStart.test(ret.path)) {
                    throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character');
                }
            }
            else {
                if (_doubleSlashStart.test(ret.path)) {
                    throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")');
                }
            }
        }
    }
    // for a while we allowed uris *without* schemes and this is the migration
    // for them, e.g. an uri without scheme and without strict-mode warns and falls
    // back to the file-scheme. that should cause the least carnage and still be a
    // clear warning
    function _schemeFix(scheme, _strict) {
        if (!scheme && !_strict) {
            return 'file';
        }
        return scheme;
    }
    // implements a bit of https://tools.ietf.org/html/rfc3986#section-5
    function _referenceResolution(scheme, path) {
        // the slash-character is our 'default base' as we don't
        // support constructing URIs relative to other URIs. This
        // also means that we alter and potentially break paths.
        // see https://tools.ietf.org/html/rfc3986#section-5.1.4
        switch (scheme) {
            case 'https':
            case 'http':
            case 'file':
                if (!path) {
                    path = _slash;
                }
                else if (path[0] !== _slash) {
                    path = _slash + path;
                }
                break;
        }
        return path;
    }
    const _empty = '';
    const _slash = '/';
    const _regexp = /^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;
    /**
     * Uniform Resource Identifier (URI) http://tools.ietf.org/html/rfc3986.
     * This class is a simple parser which creates the basic component parts
     * (http://tools.ietf.org/html/rfc3986#section-3) with minimal validation
     * and encoding.
     *
     * ```txt
     *       foo://example.com:8042/over/there?name=ferret#nose
     *       \_/   \______________/\_________/ \_________/ \__/
     *        |           |            |            |        |
     *     scheme     authority       path        query   fragment
     *        |   _____________________|__
     *       / \ /                        \
     *       urn:example:animal:ferret:nose
     * ```
     */
    class URI {
        static isUri(thing) {
            if (thing instanceof URI) {
                return true;
            }
            if (!thing) {
                return false;
            }
            return typeof thing.authority === 'string'
                && typeof thing.fragment === 'string'
                && typeof thing.path === 'string'
                && typeof thing.query === 'string'
                && typeof thing.scheme === 'string'
                && typeof thing.fsPath === 'string'
                && typeof thing.with === 'function'
                && typeof thing.toString === 'function';
        }
        /**
         * @internal
         */
        constructor(schemeOrData, authority, path, query, fragment, _strict = false) {
            if (typeof schemeOrData === 'object') {
                this.scheme = schemeOrData.scheme || _empty;
                this.authority = schemeOrData.authority || _empty;
                this.path = schemeOrData.path || _empty;
                this.query = schemeOrData.query || _empty;
                this.fragment = schemeOrData.fragment || _empty;
                // no validation because it's this URI
                // that creates uri components.
                // _validateUri(this);
            }
            else {
                this.scheme = _schemeFix(schemeOrData, _strict);
                this.authority = authority || _empty;
                this.path = _referenceResolution(this.scheme, path || _empty);
                this.query = query || _empty;
                this.fragment = fragment || _empty;
                _validateUri(this, _strict);
            }
        }
        // ---- filesystem path -----------------------
        /**
         * Returns a string representing the corresponding file system path of this URI.
         * Will handle UNC paths, normalizes windows drive letters to lower-case, and uses the
         * platform specific path separator.
         *
         * * Will *not* validate the path for invalid characters and semantics.
         * * Will *not* look at the scheme of this URI.
         * * The result shall *not* be used for display purposes but for accessing a file on disk.
         *
         *
         * The *difference* to `URI#path` is the use of the platform specific separator and the handling
         * of UNC paths. See the below sample of a file-uri with an authority (UNC path).
         *
         * ```ts
            const u = URI.parse('file://server/c$/folder/file.txt')
            u.authority === 'server'
            u.path === '/shares/c$/file.txt'
            u.fsPath === '\\server\c$\folder\file.txt'
        ```
         *
         * Using `URI#path` to read a file (using fs-apis) would not be enough because parts of the path,
         * namely the server name, would be missing. Therefore `URI#fsPath` exists - it's sugar to ease working
         * with URIs that represent files on disk (`file` scheme).
         */
        get fsPath() {
            // if (this.scheme !== 'file') {
            // 	console.warn(`[UriError] calling fsPath with scheme ${this.scheme}`);
            // }
            return uriToFsPath(this, false);
        }
        // ---- modify to new -------------------------
        with(change) {
            if (!change) {
                return this;
            }
            let { scheme, authority, path, query, fragment } = change;
            if (scheme === undefined) {
                scheme = this.scheme;
            }
            else if (scheme === null) {
                scheme = _empty;
            }
            if (authority === undefined) {
                authority = this.authority;
            }
            else if (authority === null) {
                authority = _empty;
            }
            if (path === undefined) {
                path = this.path;
            }
            else if (path === null) {
                path = _empty;
            }
            if (query === undefined) {
                query = this.query;
            }
            else if (query === null) {
                query = _empty;
            }
            if (fragment === undefined) {
                fragment = this.fragment;
            }
            else if (fragment === null) {
                fragment = _empty;
            }
            if (scheme === this.scheme
                && authority === this.authority
                && path === this.path
                && query === this.query
                && fragment === this.fragment) {
                return this;
            }
            return new Uri(scheme, authority, path, query, fragment);
        }
        // ---- parse & validate ------------------------
        /**
         * Creates a new URI from a string, e.g. `http://www.example.com/some/path`,
         * `file:///usr/home`, or `scheme:with/path`.
         *
         * @param value A string which represents an URI (see `URI#toString`).
         */
        static parse(value, _strict = false) {
            const match = _regexp.exec(value);
            if (!match) {
                return new Uri(_empty, _empty, _empty, _empty, _empty);
            }
            return new Uri(match[2] || _empty, percentDecode(match[4] || _empty), percentDecode(match[5] || _empty), percentDecode(match[7] || _empty), percentDecode(match[9] || _empty), _strict);
        }
        /**
         * Creates a new URI from a file system path, e.g. `c:\my\files`,
         * `/usr/home`, or `\\server\share\some\path`.
         *
         * The *difference* between `URI#parse` and `URI#file` is that the latter treats the argument
         * as path, not as stringified-uri. E.g. `URI.file(path)` is **not the same as**
         * `URI.parse('file://' + path)` because the path might contain characters that are
         * interpreted (# and ?). See the following sample:
         * ```ts
        const good = URI.file('/coding/c#/project1');
        good.scheme === 'file';
        good.path === '/coding/c#/project1';
        good.fragment === '';
        const bad = URI.parse('file://' + '/coding/c#/project1');
        bad.scheme === 'file';
        bad.path === '/coding/c'; // path is now broken
        bad.fragment === '/project1';
        ```
         *
         * @param path A file system path (see `URI#fsPath`)
         */
        static file(path) {
            let authority = _empty;
            // normalize to fwd-slashes on windows,
            // on other systems bwd-slashes are valid
            // filename character, eg /f\oo/ba\r.txt
            if (platform_1.isWindows) {
                path = path.replace(/\\/g, _slash);
            }
            // check for authority as used in UNC shares
            // or use the path as given
            if (path[0] === _slash && path[1] === _slash) {
                const idx = path.indexOf(_slash, 2);
                if (idx === -1) {
                    authority = path.substring(2);
                    path = _slash;
                }
                else {
                    authority = path.substring(2, idx);
                    path = path.substring(idx) || _slash;
                }
            }
            return new Uri('file', authority, path, _empty, _empty);
        }
        /**
         * Creates new URI from uri components.
         *
         * Unless `strict` is `true` the scheme is defaults to be `file`. This function performs
         * validation and should be used for untrusted uri components retrieved from storage,
         * user input, command arguments etc
         */
        static from(components, strict) {
            const result = new Uri(components.scheme, components.authority, components.path, components.query, components.fragment, strict);
            return result;
        }
        /**
         * Join a URI path with path fragments and normalizes the resulting path.
         *
         * @param uri The input URI.
         * @param pathFragment The path fragment to add to the URI path.
         * @returns The resulting URI.
         */
        static joinPath(uri, ...pathFragment) {
            if (!uri.path) {
                throw new Error(`[UriError]: cannot call joinPath on URI without path`);
            }
            let newPath;
            if (platform_1.isWindows && uri.scheme === 'file') {
                newPath = URI.file(paths.win32.join(uriToFsPath(uri, true), ...pathFragment)).path;
            }
            else {
                newPath = paths.posix.join(uri.path, ...pathFragment);
            }
            return uri.with({ path: newPath });
        }
        // ---- printing/externalize ---------------------------
        /**
         * Creates a string representation for this URI. It's guaranteed that calling
         * `URI.parse` with the result of this function creates an URI which is equal
         * to this URI.
         *
         * * The result shall *not* be used for display purposes but for externalization or transport.
         * * The result will be encoded using the percentage encoding and encoding happens mostly
         * ignore the scheme-specific encoding rules.
         *
         * @param skipEncoding Do not encode the result, default is `false`
         */
        toString(skipEncoding = false) {
            return _asFormatted(this, skipEncoding);
        }
        toJSON() {
            return this;
        }
        static revive(data) {
            if (!data) {
                return data;
            }
            else if (data instanceof URI) {
                return data;
            }
            else {
                const result = new Uri(data);
                result._formatted = data.external ?? null;
                result._fsPath = data._sep === _pathSepMarker ? data.fsPath ?? null : null;
                return result;
            }
        }
    }
    exports.URI = URI;
    const _pathSepMarker = platform_1.isWindows ? 1 : undefined;
    // This class exists so that URI is compatible with vscode.Uri (API).
    class Uri extends URI {
        constructor() {
            super(...arguments);
            this._formatted = null;
            this._fsPath = null;
        }
        get fsPath() {
            if (!this._fsPath) {
                this._fsPath = uriToFsPath(this, false);
            }
            return this._fsPath;
        }
        toString(skipEncoding = false) {
            if (!skipEncoding) {
                if (!this._formatted) {
                    this._formatted = _asFormatted(this, false);
                }
                return this._formatted;
            }
            else {
                // we don't cache that
                return _asFormatted(this, true);
            }
        }
        toJSON() {
            const res = {
                $mid: 1 /* MarshalledId.Uri */
            };
            // cached state
            if (this._fsPath) {
                res.fsPath = this._fsPath;
                res._sep = _pathSepMarker;
            }
            if (this._formatted) {
                res.external = this._formatted;
            }
            //--- uri components
            if (this.path) {
                res.path = this.path;
            }
            // TODO
            // this isn't correct and can violate the UriComponents contract but
            // this is part of the vscode.Uri API and we shouldn't change how that
            // works anymore
            if (this.scheme) {
                res.scheme = this.scheme;
            }
            if (this.authority) {
                res.authority = this.authority;
            }
            if (this.query) {
                res.query = this.query;
            }
            if (this.fragment) {
                res.fragment = this.fragment;
            }
            return res;
        }
    }
    // reserved characters: https://tools.ietf.org/html/rfc3986#section-2.2
    const encodeTable = {
        [58 /* CharCode.Colon */]: '%3A', // gen-delims
        [47 /* CharCode.Slash */]: '%2F',
        [63 /* CharCode.QuestionMark */]: '%3F',
        [35 /* CharCode.Hash */]: '%23',
        [91 /* CharCode.OpenSquareBracket */]: '%5B',
        [93 /* CharCode.CloseSquareBracket */]: '%5D',
        [64 /* CharCode.AtSign */]: '%40',
        [33 /* CharCode.ExclamationMark */]: '%21', // sub-delims
        [36 /* CharCode.DollarSign */]: '%24',
        [38 /* CharCode.Ampersand */]: '%26',
        [39 /* CharCode.SingleQuote */]: '%27',
        [40 /* CharCode.OpenParen */]: '%28',
        [41 /* CharCode.CloseParen */]: '%29',
        [42 /* CharCode.Asterisk */]: '%2A',
        [43 /* CharCode.Plus */]: '%2B',
        [44 /* CharCode.Comma */]: '%2C',
        [59 /* CharCode.Semicolon */]: '%3B',
        [61 /* CharCode.Equals */]: '%3D',
        [32 /* CharCode.Space */]: '%20',
    };
    function encodeURIComponentFast(uriComponent, isPath, isAuthority) {
        let res = undefined;
        let nativeEncodePos = -1;
        for (let pos = 0; pos < uriComponent.length; pos++) {
            const code = uriComponent.charCodeAt(pos);
            // unreserved characters: https://tools.ietf.org/html/rfc3986#section-2.3
            if ((code >= 97 /* CharCode.a */ && code <= 122 /* CharCode.z */)
                || (code >= 65 /* CharCode.A */ && code <= 90 /* CharCode.Z */)
                || (code >= 48 /* CharCode.Digit0 */ && code <= 57 /* CharCode.Digit9 */)
                || code === 45 /* CharCode.Dash */
                || code === 46 /* CharCode.Period */
                || code === 95 /* CharCode.Underline */
                || code === 126 /* CharCode.Tilde */
                || (isPath && code === 47 /* CharCode.Slash */)
                || (isAuthority && code === 91 /* CharCode.OpenSquareBracket */)
                || (isAuthority && code === 93 /* CharCode.CloseSquareBracket */)
                || (isAuthority && code === 58 /* CharCode.Colon */)) {
                // check if we are delaying native encode
                if (nativeEncodePos !== -1) {
                    res += encodeURIComponent(uriComponent.substring(nativeEncodePos, pos));
                    nativeEncodePos = -1;
                }
                // check if we write into a new string (by default we try to return the param)
                if (res !== undefined) {
                    res += uriComponent.charAt(pos);
                }
            }
            else {
                // encoding needed, we need to allocate a new string
                if (res === undefined) {
                    res = uriComponent.substr(0, pos);
                }
                // check with default table first
                const escaped = encodeTable[code];
                if (escaped !== undefined) {
                    // check if we are delaying native encode
                    if (nativeEncodePos !== -1) {
                        res += encodeURIComponent(uriComponent.substring(nativeEncodePos, pos));
                        nativeEncodePos = -1;
                    }
                    // append escaped variant to result
                    res += escaped;
                }
                else if (nativeEncodePos === -1) {
                    // use native encode only when needed
                    nativeEncodePos = pos;
                }
            }
        }
        if (nativeEncodePos !== -1) {
            res += encodeURIComponent(uriComponent.substring(nativeEncodePos));
        }
        return res !== undefined ? res : uriComponent;
    }
    function encodeURIComponentMinimal(path) {
        let res = undefined;
        for (let pos = 0; pos < path.length; pos++) {
            const code = path.charCodeAt(pos);
            if (code === 35 /* CharCode.Hash */ || code === 63 /* CharCode.QuestionMark */) {
                if (res === undefined) {
                    res = path.substr(0, pos);
                }
                res += encodeTable[code];
            }
            else {
                if (res !== undefined) {
                    res += path[pos];
                }
            }
        }
        return res !== undefined ? res : path;
    }
    /**
     * Compute `fsPath` for the given uri
     */
    function uriToFsPath(uri, keepDriveLetterCasing) {
        let value;
        if (uri.authority && uri.path.length > 1 && uri.scheme === 'file') {
            // unc path: file://shares/c$/far/boo
            value = `//${uri.authority}${uri.path}`;
        }
        else if (uri.path.charCodeAt(0) === 47 /* CharCode.Slash */
            && (uri.path.charCodeAt(1) >= 65 /* CharCode.A */ && uri.path.charCodeAt(1) <= 90 /* CharCode.Z */ || uri.path.charCodeAt(1) >= 97 /* CharCode.a */ && uri.path.charCodeAt(1) <= 122 /* CharCode.z */)
            && uri.path.charCodeAt(2) === 58 /* CharCode.Colon */) {
            if (!keepDriveLetterCasing) {
                // windows drive letter: file:///c:/far/boo
                value = uri.path[1].toLowerCase() + uri.path.substr(2);
            }
            else {
                value = uri.path.substr(1);
            }
        }
        else {
            // other path
            value = uri.path;
        }
        if (platform_1.isWindows) {
            value = value.replace(/\//g, '\\');
        }
        return value;
    }
    /**
     * Create the external version of a uri
     */
    function _asFormatted(uri, skipEncoding) {
        const encoder = !skipEncoding
            ? encodeURIComponentFast
            : encodeURIComponentMinimal;
        let res = '';
        let { scheme, authority, path, query, fragment } = uri;
        if (scheme) {
            res += scheme;
            res += ':';
        }
        if (authority || scheme === 'file') {
            res += _slash;
            res += _slash;
        }
        if (authority) {
            let idx = authority.indexOf('@');
            if (idx !== -1) {
                // <user>@<auth>
                const userinfo = authority.substr(0, idx);
                authority = authority.substr(idx + 1);
                idx = userinfo.lastIndexOf(':');
                if (idx === -1) {
                    res += encoder(userinfo, false, false);
                }
                else {
                    // <user>:<pass>@<auth>
                    res += encoder(userinfo.substr(0, idx), false, false);
                    res += ':';
                    res += encoder(userinfo.substr(idx + 1), false, true);
                }
                res += '@';
            }
            authority = authority.toLowerCase();
            idx = authority.lastIndexOf(':');
            if (idx === -1) {
                res += encoder(authority, false, true);
            }
            else {
                // <auth>:<port>
                res += encoder(authority.substr(0, idx), false, true);
                res += authority.substr(idx);
            }
        }
        if (path) {
            // lower-case windows drive letters in /C:/fff or C:/fff
            if (path.length >= 3 && path.charCodeAt(0) === 47 /* CharCode.Slash */ && path.charCodeAt(2) === 58 /* CharCode.Colon */) {
                const code = path.charCodeAt(1);
                if (code >= 65 /* CharCode.A */ && code <= 90 /* CharCode.Z */) {
                    path = `/${String.fromCharCode(code + 32)}:${path.substr(3)}`; // "/c:".length === 3
                }
            }
            else if (path.length >= 2 && path.charCodeAt(1) === 58 /* CharCode.Colon */) {
                const code = path.charCodeAt(0);
                if (code >= 65 /* CharCode.A */ && code <= 90 /* CharCode.Z */) {
                    path = `${String.fromCharCode(code + 32)}:${path.substr(2)}`; // "/c:".length === 3
                }
            }
            // encode the rest of the path
            res += encoder(path, true, false);
        }
        if (query) {
            res += '?';
            res += encoder(query, false, false);
        }
        if (fragment) {
            res += '#';
            res += !skipEncoding ? encodeURIComponentFast(fragment, false, false) : fragment;
        }
        return res;
    }
    // --- decode
    function decodeURIComponentGraceful(str) {
        try {
            return decodeURIComponent(str);
        }
        catch {
            if (str.length > 3) {
                return str.substr(0, 3) + decodeURIComponentGraceful(str.substr(3));
            }
            else {
                return str;
            }
        }
    }
    const _rEncodedAsHex = /(%[0-9A-Za-z][0-9A-Za-z])+/g;
    function percentDecode(str) {
        if (!str.match(_rEncodedAsHex)) {
            return str;
        }
        return str.replace(_rEncodedAsHex, (match) => decodeURIComponentGraceful(match));
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[252/*vs/base/common/marshalling*/], __M([1/*require*/,0/*exports*/,160/*vs/base/common/buffer*/,22/*vs/base/common/uri*/]), function (require, exports, buffer_1, uri_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.stringify = stringify;
    exports.parse = parse;
    exports.revive = revive;
    function stringify(obj) {
        return JSON.stringify(obj, replacer);
    }
    function parse(text) {
        let data = JSON.parse(text);
        data = revive(data);
        return data;
    }
    function replacer(key, value) {
        // URI is done via toJSON-member
        if (value instanceof RegExp) {
            return {
                $mid: 2 /* MarshalledId.Regexp */,
                source: value.source,
                flags: value.flags,
            };
        }
        return value;
    }
    function revive(obj, depth = 0) {
        if (!obj || depth > 200) {
            return obj;
        }
        if (typeof obj === 'object') {
            switch (obj.$mid) {
                case 1 /* MarshalledId.Uri */: return uri_1.URI.revive(obj);
                case 2 /* MarshalledId.Regexp */: return new RegExp(obj.source, obj.flags);
                case 17 /* MarshalledId.Date */: return new Date(obj.source);
            }
            if (obj instanceof buffer_1.VSBuffer
                || obj instanceof Uint8Array) {
                return obj;
            }
            if (Array.isArray(obj)) {
                for (let i = 0; i < obj.length; ++i) {
                    obj[i] = revive(obj[i], depth + 1);
                }
            }
            else {
                // walk object
                for (const key in obj) {
                    if (Object.hasOwnProperty.call(obj, key)) {
                        obj[key] = revive(obj[key], depth + 1);
                    }
                }
            }
        }
        return obj;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[42/*vs/base/common/network*/], __M([1/*require*/,0/*exports*/,8/*vs/base/common/errors*/,16/*vs/base/common/platform*/,11/*vs/base/common/strings*/,22/*vs/base/common/uri*/,99/*vs/base/common/path*/]), function (require, exports, errors, platform, strings_1, uri_1, paths) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.COI = exports.FileAccess = exports.VSCODE_AUTHORITY = exports.RemoteAuthorities = exports.connectionTokenQueryName = exports.Schemas = void 0;
    exports.matchesScheme = matchesScheme;
    exports.matchesSomeScheme = matchesSomeScheme;
    var Schemas;
    (function (Schemas) {
        /**
         * A schema that is used for models that exist in memory
         * only and that have no correspondence on a server or such.
         */
        Schemas.inMemory = 'inmemory';
        /**
         * A schema that is used for setting files
         */
        Schemas.vscode = 'vscode';
        /**
         * A schema that is used for internal private files
         */
        Schemas.internal = 'private';
        /**
         * A walk-through document.
         */
        Schemas.walkThrough = 'walkThrough';
        /**
         * An embedded code snippet.
         */
        Schemas.walkThroughSnippet = 'walkThroughSnippet';
        Schemas.http = 'http';
        Schemas.https = 'https';
        Schemas.file = 'file';
        Schemas.mailto = 'mailto';
        Schemas.untitled = 'untitled';
        Schemas.data = 'data';
        Schemas.command = 'command';
        Schemas.vscodeRemote = 'vscode-remote';
        Schemas.vscodeRemoteResource = 'vscode-remote-resource';
        Schemas.vscodeManagedRemoteResource = 'vscode-managed-remote-resource';
        Schemas.vscodeUserData = 'vscode-userdata';
        Schemas.vscodeCustomEditor = 'vscode-custom-editor';
        Schemas.vscodeNotebookCell = 'vscode-notebook-cell';
        Schemas.vscodeNotebookCellMetadata = 'vscode-notebook-cell-metadata';
        Schemas.vscodeNotebookCellMetadataDiff = 'vscode-notebook-cell-metadata-diff';
        Schemas.vscodeNotebookCellOutput = 'vscode-notebook-cell-output';
        Schemas.vscodeNotebookCellOutputDiff = 'vscode-notebook-cell-output-diff';
        Schemas.vscodeNotebookMetadata = 'vscode-notebook-metadata';
        Schemas.vscodeInteractiveInput = 'vscode-interactive-input';
        Schemas.vscodeSettings = 'vscode-settings';
        Schemas.vscodeWorkspaceTrust = 'vscode-workspace-trust';
        Schemas.vscodeTerminal = 'vscode-terminal';
        /** Scheme used for code blocks in chat. */
        Schemas.vscodeChatCodeBlock = 'vscode-chat-code-block';
        /** Scheme used for LHS of code compare (aka diff) blocks in chat. */
        Schemas.vscodeChatCodeCompareBlock = 'vscode-chat-code-compare-block';
        /** Scheme used for the chat input editor. */
        Schemas.vscodeChatSesssion = 'vscode-chat-editor';
        /**
         * Scheme used internally for webviews that aren't linked to a resource (i.e. not custom editors)
         */
        Schemas.webviewPanel = 'webview-panel';
        /**
         * Scheme used for loading the wrapper html and script in webviews.
         */
        Schemas.vscodeWebview = 'vscode-webview';
        /**
         * Scheme used for extension pages
         */
        Schemas.extension = 'extension';
        /**
         * Scheme used as a replacement of `file` scheme to load
         * files with our custom protocol handler (desktop only).
         */
        Schemas.vscodeFileResource = 'vscode-file';
        /**
         * Scheme used for temporary resources
         */
        Schemas.tmp = 'tmp';
        /**
         * Scheme used vs live share
         */
        Schemas.vsls = 'vsls';
        /**
         * Scheme used for the Source Control commit input's text document
         */
        Schemas.vscodeSourceControl = 'vscode-scm';
        /**
         * Scheme used for input box for creating comments.
         */
        Schemas.commentsInput = 'comment';
        /**
         * Scheme used for special rendering of settings in the release notes
         */
        Schemas.codeSetting = 'code-setting';
        /**
         * Scheme used for output panel resources
         */
        Schemas.outputChannel = 'output';
    })(Schemas || (exports.Schemas = Schemas = {}));
    function matchesScheme(target, scheme) {
        if (uri_1.URI.isUri(target)) {
            return (0, strings_1.equalsIgnoreCase)(target.scheme, scheme);
        }
        else {
            return (0, strings_1.startsWithIgnoreCase)(target, scheme + ':');
        }
    }
    function matchesSomeScheme(target, ...schemes) {
        return schemes.some(scheme => matchesScheme(target, scheme));
    }
    exports.connectionTokenQueryName = 'tkn';
    class RemoteAuthoritiesImpl {
        constructor() {
            this._hosts = Object.create(null);
            this._ports = Object.create(null);
            this._connectionTokens = Object.create(null);
            this._preferredWebSchema = 'http';
            this._delegate = null;
            this._serverRootPath = '/';
        }
        setPreferredWebSchema(schema) {
            this._preferredWebSchema = schema;
        }
        get _remoteResourcesPath() {
            return paths.posix.join(this._serverRootPath, Schemas.vscodeRemoteResource);
        }
        rewrite(uri) {
            if (this._delegate) {
                try {
                    return this._delegate(uri);
                }
                catch (err) {
                    errors.onUnexpectedError(err);
                    return uri;
                }
            }
            const authority = uri.authority;
            let host = this._hosts[authority];
            if (host && host.indexOf(':') !== -1 && host.indexOf('[') === -1) {
                host = `[${host}]`;
            }
            const port = this._ports[authority];
            const connectionToken = this._connectionTokens[authority];
            let query = `path=${encodeURIComponent(uri.path)}`;
            if (typeof connectionToken === 'string') {
                query += `&${exports.connectionTokenQueryName}=${encodeURIComponent(connectionToken)}`;
            }
            return uri_1.URI.from({
                scheme: platform.isWeb ? this._preferredWebSchema : Schemas.vscodeRemoteResource,
                authority: `${host}:${port}`,
                path: this._remoteResourcesPath,
                query
            });
        }
    }
    exports.RemoteAuthorities = new RemoteAuthoritiesImpl();
    exports.VSCODE_AUTHORITY = 'vscode-app';
    class FileAccessImpl {
        static { this.FALLBACK_AUTHORITY = exports.VSCODE_AUTHORITY; }
        /**
         * Returns a URI to use in contexts where the browser is responsible
         * for loading (e.g. fetch()) or when used within the DOM.
         *
         * **Note:** use `dom.ts#asCSSUrl` whenever the URL is to be used in CSS context.
         */
        asBrowserUri(resourcePath) {
            // ESM-comment-begin
            const uri = this.toUri(resourcePath, require);
            // ESM-comment-end
            // ESM-uncomment-begin
            // const uri = this.toUri(resourcePath);
            // ESM-uncomment-end
            return this.uriToBrowserUri(uri);
        }
        /**
         * Returns a URI to use in contexts where the browser is responsible
         * for loading (e.g. fetch()) or when used within the DOM.
         *
         * **Note:** use `dom.ts#asCSSUrl` whenever the URL is to be used in CSS context.
         */
        uriToBrowserUri(uri) {
            // Handle remote URIs via `RemoteAuthorities`
            if (uri.scheme === Schemas.vscodeRemote) {
                return exports.RemoteAuthorities.rewrite(uri);
            }
            // Convert to `vscode-file` resource..
            if (
            // ...only ever for `file` resources
            uri.scheme === Schemas.file &&
                (
                // ...and we run in native environments
                platform.isNative ||
                    // ...or web worker extensions on desktop
                    (platform.webWorkerOrigin === `${Schemas.vscodeFileResource}://${FileAccessImpl.FALLBACK_AUTHORITY}`))) {
                return uri.with({
                    scheme: Schemas.vscodeFileResource,
                    // We need to provide an authority here so that it can serve
                    // as origin for network and loading matters in chromium.
                    // If the URI is not coming with an authority already, we
                    // add our own
                    authority: uri.authority || FileAccessImpl.FALLBACK_AUTHORITY,
                    query: null,
                    fragment: null
                });
            }
            return uri;
        }
        toUri(uriOrModule, moduleIdToUrl) {
            if (uri_1.URI.isUri(uriOrModule)) {
                return uriOrModule;
            }
            if (globalThis._VSCODE_FILE_ROOT) {
                const rootUriOrPath = globalThis._VSCODE_FILE_ROOT;
                // File URL (with scheme)
                if (/^\w[\w\d+.-]*:\/\//.test(rootUriOrPath)) {
                    return uri_1.URI.joinPath(uri_1.URI.parse(rootUriOrPath, true), uriOrModule);
                }
                // File Path (no scheme)
                const modulePath = paths.join(rootUriOrPath, uriOrModule);
                return uri_1.URI.file(modulePath);
            }
            return uri_1.URI.parse(moduleIdToUrl.toUrl(uriOrModule));
        }
    }
    exports.FileAccess = new FileAccessImpl();
    var COI;
    (function (COI) {
        const coiHeaders = new Map([
            ['1', { 'Cross-Origin-Opener-Policy': 'same-origin' }],
            ['2', { 'Cross-Origin-Embedder-Policy': 'require-corp' }],
            ['3', { 'Cross-Origin-Opener-Policy': 'same-origin', 'Cross-Origin-Embedder-Policy': 'require-corp' }],
        ]);
        COI.CoopAndCoep = Object.freeze(coiHeaders.get('3'));
        const coiSearchParamName = 'vscode-coi';
        /**
         * Extract desired headers from `vscode-coi` invocation
         */
        function getHeadersFromQuery(url) {
            let params;
            if (typeof url === 'string') {
                params = new URL(url).searchParams;
            }
            else if (url instanceof URL) {
                params = url.searchParams;
            }
            else if (uri_1.URI.isUri(url)) {
                params = new URL(url.toString(true)).searchParams;
            }
            const value = params?.get(coiSearchParamName);
            if (!value) {
                return undefined;
            }
            return coiHeaders.get(value);
        }
        COI.getHeadersFromQuery = getHeadersFromQuery;
        /**
         * Add the `vscode-coi` query attribute based on wanting `COOP` and `COEP`. Will be a noop when `crossOriginIsolated`
         * isn't enabled the current context
         */
        function addSearchParam(urlOrSearch, coop, coep) {
            if (!globalThis.crossOriginIsolated) {
                // depends on the current context being COI
                return;
            }
            const value = coop && coep ? '3' : coep ? '2' : '1';
            if (urlOrSearch instanceof URLSearchParams) {
                urlOrSearch.set(coiSearchParamName, value);
            }
            else {
                urlOrSearch[coiSearchParamName] = value;
            }
        }
        COI.addSearchParam = addSearchParam;
    })(COI || (exports.COI = COI = {}));
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[5/*vs/base/browser/dom*/], __M([1/*require*/,0/*exports*/,64/*vs/base/browser/browser*/,248/*vs/base/browser/canIUse*/,47/*vs/base/browser/keyboardEvent*/,77/*vs/base/browser/mouseEvent*/,14/*vs/base/common/async*/,8/*vs/base/common/errors*/,6/*vs/base/common/event*/,351/*vs/base/browser/dompurify/dompurify*/,2/*vs/base/common/lifecycle*/,42/*vs/base/common/network*/,16/*vs/base/common/platform*/,129/*vs/base/common/hash*/,52/*vs/base/browser/window*/]), function (require, exports, browser, canIUse_1, keyboardEvent_1, mouseEvent_1, async_1, errors_1, event, dompurify, lifecycle_1, network_1, platform, hash_1, window_1) {
    "use strict";
    var _a;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DragAndDropObserver = exports.ModifierKeyEmitter = exports.basicMarkupHtmlTags = exports.Namespace = exports.EventHelper = exports.EventType = exports.sharedMutationObserver = exports.Dimension = exports.WindowIntervalTimer = exports.scheduleAtNextAnimationFrame = exports.runAtThisOrScheduleAtNextAnimationFrame = exports.WindowIdleValue = exports.addStandardDisposableGenericMouseUpListener = exports.addStandardDisposableGenericMouseDownListener = exports.addStandardDisposableListener = exports.onDidUnregisterWindow = exports.onWillUnregisterWindow = exports.onDidRegisterWindow = exports.hasWindow = exports.getWindowById = exports.getWindowId = exports.getWindowsCount = exports.getWindows = exports.getDocument = exports.getWindow = exports.registerWindow = void 0;
    exports.clearNode = clearNode;
    exports.addDisposableListener = addDisposableListener;
    exports.addDisposableGenericMouseDownListener = addDisposableGenericMouseDownListener;
    exports.addDisposableGenericMouseUpListener = addDisposableGenericMouseUpListener;
    exports.runWhenWindowIdle = runWhenWindowIdle;
    exports.getComputedStyle = getComputedStyle;
    exports.getClientArea = getClientArea;
    exports.getTopLeftOffset = getTopLeftOffset;
    exports.size = size;
    exports.getDomNodePagePosition = getDomNodePagePosition;
    exports.getDomNodeZoomLevel = getDomNodeZoomLevel;
    exports.getTotalWidth = getTotalWidth;
    exports.getContentWidth = getContentWidth;
    exports.getContentHeight = getContentHeight;
    exports.getTotalHeight = getTotalHeight;
    exports.isAncestor = isAncestor;
    exports.findParentWithClass = findParentWithClass;
    exports.hasParentWithClass = hasParentWithClass;
    exports.isShadowRoot = isShadowRoot;
    exports.isInShadowDOM = isInShadowDOM;
    exports.getShadowRoot = getShadowRoot;
    exports.getActiveElement = getActiveElement;
    exports.isActiveElement = isActiveElement;
    exports.isAncestorOfActiveElement = isAncestorOfActiveElement;
    exports.getActiveDocument = getActiveDocument;
    exports.getActiveWindow = getActiveWindow;
    exports.createStyleSheet2 = createStyleSheet2;
    exports.createStyleSheet = createStyleSheet;
    exports.createCSSRule = createCSSRule;
    exports.removeCSSRulesContainingSelector = removeCSSRulesContainingSelector;
    exports.isHTMLElement = isHTMLElement;
    exports.isHTMLAnchorElement = isHTMLAnchorElement;
    exports.isSVGElement = isSVGElement;
    exports.isMouseEvent = isMouseEvent;
    exports.isKeyboardEvent = isKeyboardEvent;
    exports.isEventLike = isEventLike;
    exports.saveParentsScrollTop = saveParentsScrollTop;
    exports.restoreParentsScrollTop = restoreParentsScrollTop;
    exports.trackFocus = trackFocus;
    exports.after = after;
    exports.append = append;
    exports.prepend = prepend;
    exports.reset = reset;
    exports.$ = $;
    exports.setVisibility = setVisibility;
    exports.show = show;
    exports.hide = hide;
    exports.computeScreenAwareSize = computeScreenAwareSize;
    exports.windowOpenNoOpener = windowOpenNoOpener;
    exports.animate = animate;
    exports.asCSSUrl = asCSSUrl;
    exports.asCSSPropertyValue = asCSSPropertyValue;
    exports.asCssValueWithDefault = asCssValueWithDefault;
    exports.hookDomPurifyHrefAndSrcSanitizer = hookDomPurifyHrefAndSrcSanitizer;
    exports.h = h;
    exports.svgElem = svgElem;
    //# region Multi-Window Support Utilities
    _a = (function () {
        const windows = new Map();
        (0, window_1.ensureCodeWindow)(window_1.mainWindow, 1);
        const mainWindowRegistration = { window: window_1.mainWindow, disposables: new lifecycle_1.DisposableStore() };
        windows.set(window_1.mainWindow.vscodeWindowId, mainWindowRegistration);
        const onDidRegisterWindow = new event.Emitter();
        const onDidUnregisterWindow = new event.Emitter();
        const onWillUnregisterWindow = new event.Emitter();
        function getWindowById(windowId, fallbackToMain) {
            const window = typeof windowId === 'number' ? windows.get(windowId) : undefined;
            return window ?? (fallbackToMain ? mainWindowRegistration : undefined);
        }
        return {
            onDidRegisterWindow: onDidRegisterWindow.event,
            onWillUnregisterWindow: onWillUnregisterWindow.event,
            onDidUnregisterWindow: onDidUnregisterWindow.event,
            registerWindow(window) {
                if (windows.has(window.vscodeWindowId)) {
                    return lifecycle_1.Disposable.None;
                }
                const disposables = new lifecycle_1.DisposableStore();
                const registeredWindow = {
                    window,
                    disposables: disposables.add(new lifecycle_1.DisposableStore())
                };
                windows.set(window.vscodeWindowId, registeredWindow);
                disposables.add((0, lifecycle_1.toDisposable)(() => {
                    windows.delete(window.vscodeWindowId);
                    onDidUnregisterWindow.fire(window);
                }));
                disposables.add(addDisposableListener(window, exports.EventType.BEFORE_UNLOAD, () => {
                    onWillUnregisterWindow.fire(window);
                }));
                onDidRegisterWindow.fire(registeredWindow);
                return disposables;
            },
            getWindows() {
                return windows.values();
            },
            getWindowsCount() {
                return windows.size;
            },
            getWindowId(targetWindow) {
                return targetWindow.vscodeWindowId;
            },
            hasWindow(windowId) {
                return windows.has(windowId);
            },
            getWindowById,
            getWindow(e) {
                const candidateNode = e;
                if (candidateNode?.ownerDocument?.defaultView) {
                    return candidateNode.ownerDocument.defaultView.window;
                }
                const candidateEvent = e;
                if (candidateEvent?.view) {
                    return candidateEvent.view.window;
                }
                return window_1.mainWindow;
            },
            getDocument(e) {
                const candidateNode = e;
                return (0, exports.getWindow)(candidateNode).document;
            }
        };
    })(), exports.registerWindow = _a.registerWindow, exports.getWindow = _a.getWindow, exports.getDocument = _a.getDocument, exports.getWindows = _a.getWindows, exports.getWindowsCount = _a.getWindowsCount, exports.getWindowId = _a.getWindowId, exports.getWindowById = _a.getWindowById, exports.hasWindow = _a.hasWindow, exports.onDidRegisterWindow = _a.onDidRegisterWindow, exports.onWillUnregisterWindow = _a.onWillUnregisterWindow, exports.onDidUnregisterWindow = _a.onDidUnregisterWindow;
    //#endregion
    function clearNode(node) {
        while (node.firstChild) {
            node.firstChild.remove();
        }
    }
    class DomListener {
        constructor(node, type, handler, options) {
            this._node = node;
            this._type = type;
            this._handler = handler;
            this._options = (options || false);
            this._node.addEventListener(this._type, this._handler, this._options);
        }
        dispose() {
            if (!this._handler) {
                // Already disposed
                return;
            }
            this._node.removeEventListener(this._type, this._handler, this._options);
            // Prevent leakers from holding on to the dom or handler func
            this._node = null;
            this._handler = null;
        }
    }
    function addDisposableListener(node, type, handler, useCaptureOrOptions) {
        return new DomListener(node, type, handler, useCaptureOrOptions);
    }
    function _wrapAsStandardMouseEvent(targetWindow, handler) {
        return function (e) {
            return handler(new mouseEvent_1.StandardMouseEvent(targetWindow, e));
        };
    }
    function _wrapAsStandardKeyboardEvent(handler) {
        return function (e) {
            return handler(new keyboardEvent_1.StandardKeyboardEvent(e));
        };
    }
    const addStandardDisposableListener = function addStandardDisposableListener(node, type, handler, useCapture) {
        let wrapHandler = handler;
        if (type === 'click' || type === 'mousedown' || type === 'contextmenu') {
            wrapHandler = _wrapAsStandardMouseEvent((0, exports.getWindow)(node), handler);
        }
        else if (type === 'keydown' || type === 'keypress' || type === 'keyup') {
            wrapHandler = _wrapAsStandardKeyboardEvent(handler);
        }
        return addDisposableListener(node, type, wrapHandler, useCapture);
    };
    exports.addStandardDisposableListener = addStandardDisposableListener;
    const addStandardDisposableGenericMouseDownListener = function addStandardDisposableListener(node, handler, useCapture) {
        const wrapHandler = _wrapAsStandardMouseEvent((0, exports.getWindow)(node), handler);
        return addDisposableGenericMouseDownListener(node, wrapHandler, useCapture);
    };
    exports.addStandardDisposableGenericMouseDownListener = addStandardDisposableGenericMouseDownListener;
    const addStandardDisposableGenericMouseUpListener = function addStandardDisposableListener(node, handler, useCapture) {
        const wrapHandler = _wrapAsStandardMouseEvent((0, exports.getWindow)(node), handler);
        return addDisposableGenericMouseUpListener(node, wrapHandler, useCapture);
    };
    exports.addStandardDisposableGenericMouseUpListener = addStandardDisposableGenericMouseUpListener;
    function addDisposableGenericMouseDownListener(node, handler, useCapture) {
        return addDisposableListener(node, platform.isIOS && canIUse_1.BrowserFeatures.pointerEvents ? exports.EventType.POINTER_DOWN : exports.EventType.MOUSE_DOWN, handler, useCapture);
    }
    function addDisposableGenericMouseUpListener(node, handler, useCapture) {
        return addDisposableListener(node, platform.isIOS && canIUse_1.BrowserFeatures.pointerEvents ? exports.EventType.POINTER_UP : exports.EventType.MOUSE_UP, handler, useCapture);
    }
    /**
     * Execute the callback the next time the browser is idle, returning an
     * {@link IDisposable} that will cancel the callback when disposed. This wraps
     * [requestIdleCallback] so it will fallback to [setTimeout] if the environment
     * doesn't support it.
     *
     * @param targetWindow The window for which to run the idle callback
     * @param callback The callback to run when idle, this includes an
     * [IdleDeadline] that provides the time alloted for the idle callback by the
     * browser. Not respecting this deadline will result in a degraded user
     * experience.
     * @param timeout A timeout at which point to queue no longer wait for an idle
     * callback but queue it on the regular event loop (like setTimeout). Typically
     * this should not be used.
     *
     * [IdleDeadline]: https://developer.mozilla.org/en-US/docs/Web/API/IdleDeadline
     * [requestIdleCallback]: https://developer.mozilla.org/en-US/docs/Web/API/Window/requestIdleCallback
     * [setTimeout]: https://developer.mozilla.org/en-US/docs/Web/API/Window/setTimeout
     */
    function runWhenWindowIdle(targetWindow, callback, timeout) {
        return (0, async_1._runWhenIdle)(targetWindow, callback, timeout);
    }
    /**
     * An implementation of the "idle-until-urgent"-strategy as introduced
     * here: https://philipwalton.com/articles/idle-until-urgent/
     */
    class WindowIdleValue extends async_1.AbstractIdleValue {
        constructor(targetWindow, executor) {
            super(targetWindow, executor);
        }
    }
    exports.WindowIdleValue = WindowIdleValue;
    class WindowIntervalTimer extends async_1.IntervalTimer {
        /**
         *
         * @param node The optional node from which the target window is determined
         */
        constructor(node) {
            super();
            this.defaultTarget = node && (0, exports.getWindow)(node);
        }
        cancelAndSet(runner, interval, targetWindow) {
            return super.cancelAndSet(runner, interval, targetWindow ?? this.defaultTarget);
        }
    }
    exports.WindowIntervalTimer = WindowIntervalTimer;
    class AnimationFrameQueueItem {
        constructor(runner, priority = 0) {
            this._runner = runner;
            this.priority = priority;
            this._canceled = false;
        }
        dispose() {
            this._canceled = true;
        }
        execute() {
            if (this._canceled) {
                return;
            }
            try {
                this._runner();
            }
            catch (e) {
                (0, errors_1.onUnexpectedError)(e);
            }
        }
        // Sort by priority (largest to lowest)
        static sort(a, b) {
            return b.priority - a.priority;
        }
    }
    (function () {
        /**
         * The runners scheduled at the next animation frame
         */
        const NEXT_QUEUE = new Map();
        /**
         * The runners scheduled at the current animation frame
         */
        const CURRENT_QUEUE = new Map();
        /**
         * A flag to keep track if the native requestAnimationFrame was already called
         */
        const animFrameRequested = new Map();
        /**
         * A flag to indicate if currently handling a native requestAnimationFrame callback
         */
        const inAnimationFrameRunner = new Map();
        const animationFrameRunner = (targetWindowId) => {
            animFrameRequested.set(targetWindowId, false);
            const currentQueue = NEXT_QUEUE.get(targetWindowId) ?? [];
            CURRENT_QUEUE.set(targetWindowId, currentQueue);
            NEXT_QUEUE.set(targetWindowId, []);
            inAnimationFrameRunner.set(targetWindowId, true);
            while (currentQueue.length > 0) {
                currentQueue.sort(AnimationFrameQueueItem.sort);
                const top = currentQueue.shift();
                top.execute();
            }
            inAnimationFrameRunner.set(targetWindowId, false);
        };
        exports.scheduleAtNextAnimationFrame = (targetWindow, runner, priority = 0) => {
            const targetWindowId = (0, exports.getWindowId)(targetWindow);
            const item = new AnimationFrameQueueItem(runner, priority);
            let nextQueue = NEXT_QUEUE.get(targetWindowId);
            if (!nextQueue) {
                nextQueue = [];
                NEXT_QUEUE.set(targetWindowId, nextQueue);
            }
            nextQueue.push(item);
            if (!animFrameRequested.get(targetWindowId)) {
                animFrameRequested.set(targetWindowId, true);
                targetWindow.requestAnimationFrame(() => animationFrameRunner(targetWindowId));
            }
            return item;
        };
        exports.runAtThisOrScheduleAtNextAnimationFrame = (targetWindow, runner, priority) => {
            const targetWindowId = (0, exports.getWindowId)(targetWindow);
            if (inAnimationFrameRunner.get(targetWindowId)) {
                const item = new AnimationFrameQueueItem(runner, priority);
                let currentQueue = CURRENT_QUEUE.get(targetWindowId);
                if (!currentQueue) {
                    currentQueue = [];
                    CURRENT_QUEUE.set(targetWindowId, currentQueue);
                }
                currentQueue.push(item);
                return item;
            }
            else {
                return (0, exports.scheduleAtNextAnimationFrame)(targetWindow, runner, priority);
            }
        };
    })();
    function getComputedStyle(el) {
        return (0, exports.getWindow)(el).getComputedStyle(el, null);
    }
    function getClientArea(element, fallback) {
        const elWindow = (0, exports.getWindow)(element);
        const elDocument = elWindow.document;
        // Try with DOM clientWidth / clientHeight
        if (element !== elDocument.body) {
            return new Dimension(element.clientWidth, element.clientHeight);
        }
        // If visual view port exits and it's on mobile, it should be used instead of window innerWidth / innerHeight, or document.body.clientWidth / document.body.clientHeight
        if (platform.isIOS && elWindow?.visualViewport) {
            return new Dimension(elWindow.visualViewport.width, elWindow.visualViewport.height);
        }
        // Try innerWidth / innerHeight
        if (elWindow?.innerWidth && elWindow.innerHeight) {
            return new Dimension(elWindow.innerWidth, elWindow.innerHeight);
        }
        // Try with document.body.clientWidth / document.body.clientHeight
        if (elDocument.body && elDocument.body.clientWidth && elDocument.body.clientHeight) {
            return new Dimension(elDocument.body.clientWidth, elDocument.body.clientHeight);
        }
        // Try with document.documentElement.clientWidth / document.documentElement.clientHeight
        if (elDocument.documentElement && elDocument.documentElement.clientWidth && elDocument.documentElement.clientHeight) {
            return new Dimension(elDocument.documentElement.clientWidth, elDocument.documentElement.clientHeight);
        }
        if (fallback) {
            return getClientArea(fallback);
        }
        throw new Error('Unable to figure out browser width and height');
    }
    class SizeUtils {
        // Adapted from WinJS
        // Converts a CSS positioning string for the specified element to pixels.
        static convertToPixels(element, value) {
            return parseFloat(value) || 0;
        }
        static getDimension(element, cssPropertyName, jsPropertyName) {
            const computedStyle = getComputedStyle(element);
            const value = computedStyle ? computedStyle.getPropertyValue(cssPropertyName) : '0';
            return SizeUtils.convertToPixels(element, value);
        }
        static getBorderLeftWidth(element) {
            return SizeUtils.getDimension(element, 'border-left-width', 'borderLeftWidth');
        }
        static getBorderRightWidth(element) {
            return SizeUtils.getDimension(element, 'border-right-width', 'borderRightWidth');
        }
        static getBorderTopWidth(element) {
            return SizeUtils.getDimension(element, 'border-top-width', 'borderTopWidth');
        }
        static getBorderBottomWidth(element) {
            return SizeUtils.getDimension(element, 'border-bottom-width', 'borderBottomWidth');
        }
        static getPaddingLeft(element) {
            return SizeUtils.getDimension(element, 'padding-left', 'paddingLeft');
        }
        static getPaddingRight(element) {
            return SizeUtils.getDimension(element, 'padding-right', 'paddingRight');
        }
        static getPaddingTop(element) {
            return SizeUtils.getDimension(element, 'padding-top', 'paddingTop');
        }
        static getPaddingBottom(element) {
            return SizeUtils.getDimension(element, 'padding-bottom', 'paddingBottom');
        }
        static getMarginLeft(element) {
            return SizeUtils.getDimension(element, 'margin-left', 'marginLeft');
        }
        static getMarginTop(element) {
            return SizeUtils.getDimension(element, 'margin-top', 'marginTop');
        }
        static getMarginRight(element) {
            return SizeUtils.getDimension(element, 'margin-right', 'marginRight');
        }
        static getMarginBottom(element) {
            return SizeUtils.getDimension(element, 'margin-bottom', 'marginBottom');
        }
    }
    class Dimension {
        static { this.None = new Dimension(0, 0); }
        constructor(width, height) {
            this.width = width;
            this.height = height;
        }
        with(width = this.width, height = this.height) {
            if (width !== this.width || height !== this.height) {
                return new Dimension(width, height);
            }
            else {
                return this;
            }
        }
        static is(obj) {
            return typeof obj === 'object' && typeof obj.height === 'number' && typeof obj.width === 'number';
        }
        static lift(obj) {
            if (obj instanceof Dimension) {
                return obj;
            }
            else {
                return new Dimension(obj.width, obj.height);
            }
        }
        static equals(a, b) {
            if (a === b) {
                return true;
            }
            if (!a || !b) {
                return false;
            }
            return a.width === b.width && a.height === b.height;
        }
    }
    exports.Dimension = Dimension;
    function getTopLeftOffset(element) {
        // Adapted from WinJS.Utilities.getPosition
        // and added borders to the mix
        let offsetParent = element.offsetParent;
        let top = element.offsetTop;
        let left = element.offsetLeft;
        while ((element = element.parentNode) !== null
            && element !== element.ownerDocument.body
            && element !== element.ownerDocument.documentElement) {
            top -= element.scrollTop;
            const c = isShadowRoot(element) ? null : getComputedStyle(element);
            if (c) {
                left -= c.direction !== 'rtl' ? element.scrollLeft : -element.scrollLeft;
            }
            if (element === offsetParent) {
                left += SizeUtils.getBorderLeftWidth(element);
                top += SizeUtils.getBorderTopWidth(element);
                top += element.offsetTop;
                left += element.offsetLeft;
                offsetParent = element.offsetParent;
            }
        }
        return {
            left: left,
            top: top
        };
    }
    function size(element, width, height) {
        if (typeof width === 'number') {
            element.style.width = `${width}px`;
        }
        if (typeof height === 'number') {
            element.style.height = `${height}px`;
        }
    }
    /**
     * Returns the position of a dom node relative to the entire page.
     */
    function getDomNodePagePosition(domNode) {
        const bb = domNode.getBoundingClientRect();
        const window = (0, exports.getWindow)(domNode);
        return {
            left: bb.left + window.scrollX,
            top: bb.top + window.scrollY,
            width: bb.width,
            height: bb.height
        };
    }
    /**
     * Returns the effective zoom on a given element before window zoom level is applied
     */
    function getDomNodeZoomLevel(domNode) {
        let testElement = domNode;
        let zoom = 1.0;
        do {
            const elementZoomLevel = getComputedStyle(testElement).zoom;
            if (elementZoomLevel !== null && elementZoomLevel !== undefined && elementZoomLevel !== '1') {
                zoom *= elementZoomLevel;
            }
            testElement = testElement.parentElement;
        } while (testElement !== null && testElement !== testElement.ownerDocument.documentElement);
        return zoom;
    }
    // Adapted from WinJS
    // Gets the width of the element, including margins.
    function getTotalWidth(element) {
        const margin = SizeUtils.getMarginLeft(element) + SizeUtils.getMarginRight(element);
        return element.offsetWidth + margin;
    }
    function getContentWidth(element) {
        const border = SizeUtils.getBorderLeftWidth(element) + SizeUtils.getBorderRightWidth(element);
        const padding = SizeUtils.getPaddingLeft(element) + SizeUtils.getPaddingRight(element);
        return element.offsetWidth - border - padding;
    }
    // Adapted from WinJS
    // Gets the height of the content of the specified element. The content height does not include borders or padding.
    function getContentHeight(element) {
        const border = SizeUtils.getBorderTopWidth(element) + SizeUtils.getBorderBottomWidth(element);
        const padding = SizeUtils.getPaddingTop(element) + SizeUtils.getPaddingBottom(element);
        return element.offsetHeight - border - padding;
    }
    // Adapted from WinJS
    // Gets the height of the element, including its margins.
    function getTotalHeight(element) {
        const margin = SizeUtils.getMarginTop(element) + SizeUtils.getMarginBottom(element);
        return element.offsetHeight + margin;
    }
    // ----------------------------------------------------------------------------------------
    function isAncestor(testChild, testAncestor) {
        return Boolean(testAncestor?.contains(testChild));
    }
    function findParentWithClass(node, clazz, stopAtClazzOrNode) {
        while (node && node.nodeType === node.ELEMENT_NODE) {
            if (node.classList.contains(clazz)) {
                return node;
            }
            if (stopAtClazzOrNode) {
                if (typeof stopAtClazzOrNode === 'string') {
                    if (node.classList.contains(stopAtClazzOrNode)) {
                        return null;
                    }
                }
                else {
                    if (node === stopAtClazzOrNode) {
                        return null;
                    }
                }
            }
            node = node.parentNode;
        }
        return null;
    }
    function hasParentWithClass(node, clazz, stopAtClazzOrNode) {
        return !!findParentWithClass(node, clazz, stopAtClazzOrNode);
    }
    function isShadowRoot(node) {
        return (node && !!node.host && !!node.mode);
    }
    function isInShadowDOM(domNode) {
        return !!getShadowRoot(domNode);
    }
    function getShadowRoot(domNode) {
        while (domNode.parentNode) {
            if (domNode === domNode.ownerDocument?.body) {
                // reached the body
                return null;
            }
            domNode = domNode.parentNode;
        }
        return isShadowRoot(domNode) ? domNode : null;
    }
    /**
     * Returns the active element across all child windows
     * based on document focus. Falls back to the main
     * window if no window has focus.
     */
    function getActiveElement() {
        let result = getActiveDocument().activeElement;
        while (result?.shadowRoot) {
            result = result.shadowRoot.activeElement;
        }
        return result;
    }
    /**
     * Returns true if the focused window active element matches
     * the provided element. Falls back to the main window if no
     * window has focus.
     */
    function isActiveElement(element) {
        return getActiveElement() === element;
    }
    /**
     * Returns true if the focused window active element is contained in
     * `ancestor`. Falls back to the main window if no window has focus.
     */
    function isAncestorOfActiveElement(ancestor) {
        return isAncestor(getActiveElement(), ancestor);
    }
    /**
     * Returns the active document across main and child windows.
     * Prefers the window with focus, otherwise falls back to
     * the main windows document.
     */
    function getActiveDocument() {
        if ((0, exports.getWindowsCount)() <= 1) {
            return window_1.mainWindow.document;
        }
        const documents = Array.from((0, exports.getWindows)()).map(({ window }) => window.document);
        return documents.find(doc => doc.hasFocus()) ?? window_1.mainWindow.document;
    }
    /**
     * Returns the active window across main and child windows.
     * Prefers the window with focus, otherwise falls back to
     * the main window.
     */
    function getActiveWindow() {
        const document = getActiveDocument();
        return (document.defaultView?.window ?? window_1.mainWindow);
    }
    const globalStylesheets = new Map();
    /**
     * A version of createStyleSheet which has a unified API to initialize/set the style content.
     */
    function createStyleSheet2() {
        return new WrappedStyleElement();
    }
    class WrappedStyleElement {
        constructor() {
            this._currentCssStyle = '';
            this._styleSheet = undefined;
        }
        setStyle(cssStyle) {
            if (cssStyle === this._currentCssStyle) {
                return;
            }
            this._currentCssStyle = cssStyle;
            if (!this._styleSheet) {
                this._styleSheet = createStyleSheet(window_1.mainWindow.document.head, (s) => s.innerText = cssStyle);
            }
            else {
                this._styleSheet.innerText = cssStyle;
            }
        }
        dispose() {
            if (this._styleSheet) {
                this._styleSheet.remove();
                this._styleSheet = undefined;
            }
        }
    }
    function createStyleSheet(container = window_1.mainWindow.document.head, beforeAppend, disposableStore) {
        const style = document.createElement('style');
        style.type = 'text/css';
        style.media = 'screen';
        beforeAppend?.(style);
        container.appendChild(style);
        if (disposableStore) {
            disposableStore.add((0, lifecycle_1.toDisposable)(() => style.remove()));
        }
        // With <head> as container, the stylesheet becomes global and is tracked
        // to support auxiliary windows to clone the stylesheet.
        if (container === window_1.mainWindow.document.head) {
            const globalStylesheetClones = new Set();
            globalStylesheets.set(style, globalStylesheetClones);
            for (const { window: targetWindow, disposables } of (0, exports.getWindows)()) {
                if (targetWindow === window_1.mainWindow) {
                    continue; // main window is already tracked
                }
                const cloneDisposable = disposables.add(cloneGlobalStyleSheet(style, globalStylesheetClones, targetWindow));
                disposableStore?.add(cloneDisposable);
            }
        }
        return style;
    }
    function cloneGlobalStyleSheet(globalStylesheet, globalStylesheetClones, targetWindow) {
        const disposables = new lifecycle_1.DisposableStore();
        const clone = globalStylesheet.cloneNode(true);
        targetWindow.document.head.appendChild(clone);
        disposables.add((0, lifecycle_1.toDisposable)(() => clone.remove()));
        for (const rule of getDynamicStyleSheetRules(globalStylesheet)) {
            clone.sheet?.insertRule(rule.cssText, clone.sheet?.cssRules.length);
        }
        disposables.add(exports.sharedMutationObserver.observe(globalStylesheet, disposables, { childList: true })(() => {
            clone.textContent = globalStylesheet.textContent;
        }));
        globalStylesheetClones.add(clone);
        disposables.add((0, lifecycle_1.toDisposable)(() => globalStylesheetClones.delete(clone)));
        return disposables;
    }
    exports.sharedMutationObserver = new class {
        constructor() {
            this.mutationObservers = new Map();
        }
        observe(target, disposables, options) {
            let mutationObserversPerTarget = this.mutationObservers.get(target);
            if (!mutationObserversPerTarget) {
                mutationObserversPerTarget = new Map();
                this.mutationObservers.set(target, mutationObserversPerTarget);
            }
            const optionsHash = (0, hash_1.hash)(options);
            let mutationObserverPerOptions = mutationObserversPerTarget.get(optionsHash);
            if (!mutationObserverPerOptions) {
                const onDidMutate = new event.Emitter();
                const observer = new MutationObserver(mutations => onDidMutate.fire(mutations));
                observer.observe(target, options);
                const resolvedMutationObserverPerOptions = mutationObserverPerOptions = {
                    users: 1,
                    observer,
                    onDidMutate: onDidMutate.event
                };
                disposables.add((0, lifecycle_1.toDisposable)(() => {
                    resolvedMutationObserverPerOptions.users -= 1;
                    if (resolvedMutationObserverPerOptions.users === 0) {
                        onDidMutate.dispose();
                        observer.disconnect();
                        mutationObserversPerTarget?.delete(optionsHash);
                        if (mutationObserversPerTarget?.size === 0) {
                            this.mutationObservers.delete(target);
                        }
                    }
                }));
                mutationObserversPerTarget.set(optionsHash, mutationObserverPerOptions);
            }
            else {
                mutationObserverPerOptions.users += 1;
            }
            return mutationObserverPerOptions.onDidMutate;
        }
    };
    let _sharedStyleSheet = null;
    function getSharedStyleSheet() {
        if (!_sharedStyleSheet) {
            _sharedStyleSheet = createStyleSheet();
        }
        return _sharedStyleSheet;
    }
    function getDynamicStyleSheetRules(style) {
        if (style?.sheet?.rules) {
            // Chrome, IE
            return style.sheet.rules;
        }
        if (style?.sheet?.cssRules) {
            // FF
            return style.sheet.cssRules;
        }
        return [];
    }
    function createCSSRule(selector, cssText, style = getSharedStyleSheet()) {
        if (!style || !cssText) {
            return;
        }
        style.sheet?.insertRule(`${selector} {${cssText}}`, 0);
        // Apply rule also to all cloned global stylesheets
        for (const clonedGlobalStylesheet of globalStylesheets.get(style) ?? []) {
            createCSSRule(selector, cssText, clonedGlobalStylesheet);
        }
    }
    function removeCSSRulesContainingSelector(ruleName, style = getSharedStyleSheet()) {
        if (!style) {
            return;
        }
        const rules = getDynamicStyleSheetRules(style);
        const toDelete = [];
        for (let i = 0; i < rules.length; i++) {
            const rule = rules[i];
            if (isCSSStyleRule(rule) && rule.selectorText.indexOf(ruleName) !== -1) {
                toDelete.push(i);
            }
        }
        for (let i = toDelete.length - 1; i >= 0; i--) {
            style.sheet?.deleteRule(toDelete[i]);
        }
        // Remove rules also from all cloned global stylesheets
        for (const clonedGlobalStylesheet of globalStylesheets.get(style) ?? []) {
            removeCSSRulesContainingSelector(ruleName, clonedGlobalStylesheet);
        }
    }
    function isCSSStyleRule(rule) {
        return typeof rule.selectorText === 'string';
    }
    function isHTMLElement(e) {
        // eslint-disable-next-line no-restricted-syntax
        return e instanceof HTMLElement || e instanceof (0, exports.getWindow)(e).HTMLElement;
    }
    function isHTMLAnchorElement(e) {
        // eslint-disable-next-line no-restricted-syntax
        return e instanceof HTMLAnchorElement || e instanceof (0, exports.getWindow)(e).HTMLAnchorElement;
    }
    function isSVGElement(e) {
        // eslint-disable-next-line no-restricted-syntax
        return e instanceof SVGElement || e instanceof (0, exports.getWindow)(e).SVGElement;
    }
    function isMouseEvent(e) {
        // eslint-disable-next-line no-restricted-syntax
        return e instanceof MouseEvent || e instanceof (0, exports.getWindow)(e).MouseEvent;
    }
    function isKeyboardEvent(e) {
        // eslint-disable-next-line no-restricted-syntax
        return e instanceof KeyboardEvent || e instanceof (0, exports.getWindow)(e).KeyboardEvent;
    }
    exports.EventType = {
        // Mouse
        CLICK: 'click',
        AUXCLICK: 'auxclick',
        DBLCLICK: 'dblclick',
        MOUSE_UP: 'mouseup',
        MOUSE_DOWN: 'mousedown',
        MOUSE_OVER: 'mouseover',
        MOUSE_MOVE: 'mousemove',
        MOUSE_OUT: 'mouseout',
        MOUSE_ENTER: 'mouseenter',
        MOUSE_LEAVE: 'mouseleave',
        MOUSE_WHEEL: 'wheel',
        POINTER_UP: 'pointerup',
        POINTER_DOWN: 'pointerdown',
        POINTER_MOVE: 'pointermove',
        POINTER_LEAVE: 'pointerleave',
        CONTEXT_MENU: 'contextmenu',
        WHEEL: 'wheel',
        // Keyboard
        KEY_DOWN: 'keydown',
        KEY_PRESS: 'keypress',
        KEY_UP: 'keyup',
        // HTML Document
        LOAD: 'load',
        BEFORE_UNLOAD: 'beforeunload',
        UNLOAD: 'unload',
        PAGE_SHOW: 'pageshow',
        PAGE_HIDE: 'pagehide',
        PASTE: 'paste',
        ABORT: 'abort',
        ERROR: 'error',
        RESIZE: 'resize',
        SCROLL: 'scroll',
        FULLSCREEN_CHANGE: 'fullscreenchange',
        WK_FULLSCREEN_CHANGE: 'webkitfullscreenchange',
        // Form
        SELECT: 'select',
        CHANGE: 'change',
        SUBMIT: 'submit',
        RESET: 'reset',
        FOCUS: 'focus',
        FOCUS_IN: 'focusin',
        FOCUS_OUT: 'focusout',
        BLUR: 'blur',
        INPUT: 'input',
        // Local Storage
        STORAGE: 'storage',
        // Drag
        DRAG_START: 'dragstart',
        DRAG: 'drag',
        DRAG_ENTER: 'dragenter',
        DRAG_LEAVE: 'dragleave',
        DRAG_OVER: 'dragover',
        DROP: 'drop',
        DRAG_END: 'dragend',
        // Animation
        ANIMATION_START: browser.isWebKit ? 'webkitAnimationStart' : 'animationstart',
        ANIMATION_END: browser.isWebKit ? 'webkitAnimationEnd' : 'animationend',
        ANIMATION_ITERATION: browser.isWebKit ? 'webkitAnimationIteration' : 'animationiteration'
    };
    function isEventLike(obj) {
        const candidate = obj;
        return !!(candidate && typeof candidate.preventDefault === 'function' && typeof candidate.stopPropagation === 'function');
    }
    exports.EventHelper = {
        stop: (e, cancelBubble) => {
            e.preventDefault();
            if (cancelBubble) {
                e.stopPropagation();
            }
            return e;
        }
    };
    function saveParentsScrollTop(node) {
        const r = [];
        for (let i = 0; node && node.nodeType === node.ELEMENT_NODE; i++) {
            r[i] = node.scrollTop;
            node = node.parentNode;
        }
        return r;
    }
    function restoreParentsScrollTop(node, state) {
        for (let i = 0; node && node.nodeType === node.ELEMENT_NODE; i++) {
            if (node.scrollTop !== state[i]) {
                node.scrollTop = state[i];
            }
            node = node.parentNode;
        }
    }
    class FocusTracker extends lifecycle_1.Disposable {
        static hasFocusWithin(element) {
            if (isHTMLElement(element)) {
                const shadowRoot = getShadowRoot(element);
                const activeElement = (shadowRoot ? shadowRoot.activeElement : element.ownerDocument.activeElement);
                return isAncestor(activeElement, element);
            }
            else {
                const window = element;
                return isAncestor(window.document.activeElement, window.document);
            }
        }
        constructor(element) {
            super();
            this._onDidFocus = this._register(new event.Emitter());
            this.onDidFocus = this._onDidFocus.event;
            this._onDidBlur = this._register(new event.Emitter());
            this.onDidBlur = this._onDidBlur.event;
            let hasFocus = FocusTracker.hasFocusWithin(element);
            let loosingFocus = false;
            const onFocus = () => {
                loosingFocus = false;
                if (!hasFocus) {
                    hasFocus = true;
                    this._onDidFocus.fire();
                }
            };
            const onBlur = () => {
                if (hasFocus) {
                    loosingFocus = true;
                    (isHTMLElement(element) ? (0, exports.getWindow)(element) : element).setTimeout(() => {
                        if (loosingFocus) {
                            loosingFocus = false;
                            hasFocus = false;
                            this._onDidBlur.fire();
                        }
                    }, 0);
                }
            };
            this._refreshStateHandler = () => {
                const currentNodeHasFocus = FocusTracker.hasFocusWithin(element);
                if (currentNodeHasFocus !== hasFocus) {
                    if (hasFocus) {
                        onBlur();
                    }
                    else {
                        onFocus();
                    }
                }
            };
            this._register(addDisposableListener(element, exports.EventType.FOCUS, onFocus, true));
            this._register(addDisposableListener(element, exports.EventType.BLUR, onBlur, true));
            if (isHTMLElement(element)) {
                this._register(addDisposableListener(element, exports.EventType.FOCUS_IN, () => this._refreshStateHandler()));
                this._register(addDisposableListener(element, exports.EventType.FOCUS_OUT, () => this._refreshStateHandler()));
            }
        }
    }
    /**
     * Creates a new `IFocusTracker` instance that tracks focus changes on the given `element` and its descendants.
     *
     * @param element The `HTMLElement` or `Window` to track focus changes on.
     * @returns An `IFocusTracker` instance.
     */
    function trackFocus(element) {
        return new FocusTracker(element);
    }
    function after(sibling, child) {
        sibling.after(child);
        return child;
    }
    function append(parent, ...children) {
        parent.append(...children);
        if (children.length === 1 && typeof children[0] !== 'string') {
            return children[0];
        }
    }
    function prepend(parent, child) {
        parent.insertBefore(child, parent.firstChild);
        return child;
    }
    /**
     * Removes all children from `parent` and appends `children`
     */
    function reset(parent, ...children) {
        parent.innerText = '';
        append(parent, ...children);
    }
    const SELECTOR_REGEX = /([\w\-]+)?(#([\w\-]+))?((\.([\w\-]+))*)/;
    var Namespace;
    (function (Namespace) {
        Namespace["HTML"] = "http://www.w3.org/1999/xhtml";
        Namespace["SVG"] = "http://www.w3.org/2000/svg";
    })(Namespace || (exports.Namespace = Namespace = {}));
    function _$(namespace, description, attrs, ...children) {
        const match = SELECTOR_REGEX.exec(description);
        if (!match) {
            throw new Error('Bad use of emmet');
        }
        const tagName = match[1] || 'div';
        let result;
        if (namespace !== Namespace.HTML) {
            result = document.createElementNS(namespace, tagName);
        }
        else {
            result = document.createElement(tagName);
        }
        if (match[3]) {
            result.id = match[3];
        }
        if (match[4]) {
            result.className = match[4].replace(/\./g, ' ').trim();
        }
        if (attrs) {
            Object.entries(attrs).forEach(([name, value]) => {
                if (typeof value === 'undefined') {
                    return;
                }
                if (/^on\w+$/.test(name)) {
                    result[name] = value;
                }
                else if (name === 'selected') {
                    if (value) {
                        result.setAttribute(name, 'true');
                    }
                }
                else {
                    result.setAttribute(name, value);
                }
            });
        }
        result.append(...children);
        return result;
    }
    function $(description, attrs, ...children) {
        return _$(Namespace.HTML, description, attrs, ...children);
    }
    $.SVG = function (description, attrs, ...children) {
        return _$(Namespace.SVG, description, attrs, ...children);
    };
    function setVisibility(visible, ...elements) {
        if (visible) {
            show(...elements);
        }
        else {
            hide(...elements);
        }
    }
    function show(...elements) {
        for (const element of elements) {
            element.style.display = '';
            element.removeAttribute('aria-hidden');
        }
    }
    function hide(...elements) {
        for (const element of elements) {
            element.style.display = 'none';
            element.setAttribute('aria-hidden', 'true');
        }
    }
    /**
     * Find a value usable for a dom node size such that the likelihood that it would be
     * displayed with constant screen pixels size is as high as possible.
     *
     * e.g. We would desire for the cursors to be 2px (CSS px) wide. Under a devicePixelRatio
     * of 1.25, the cursor will be 2.5 screen pixels wide. Depending on how the dom node aligns/"snaps"
     * with the screen pixels, it will sometimes be rendered with 2 screen pixels, and sometimes with 3 screen pixels.
     */
    function computeScreenAwareSize(window, cssPx) {
        const screenPx = window.devicePixelRatio * cssPx;
        return Math.max(1, Math.floor(screenPx)) / window.devicePixelRatio;
    }
    /**
     * Open safely a new window. This is the best way to do so, but you cannot tell
     * if the window was opened or if it was blocked by the browser's popup blocker.
     * If you want to tell if the browser blocked the new window, use {@link windowOpenWithSuccess}.
     *
     * See https://github.com/microsoft/monaco-editor/issues/601
     * To protect against malicious code in the linked site, particularly phishing attempts,
     * the window.opener should be set to null to prevent the linked site from having access
     * to change the location of the current page.
     * See https://mathiasbynens.github.io/rel-noopener/
     */
    function windowOpenNoOpener(url) {
        // By using 'noopener' in the `windowFeatures` argument, the newly created window will
        // not be able to use `window.opener` to reach back to the current page.
        // See https://stackoverflow.com/a/46958731
        // See https://developer.mozilla.org/en-US/docs/Web/API/Window/open#noopener
        // However, this also doesn't allow us to realize if the browser blocked
        // the creation of the window.
        window_1.mainWindow.open(url, '_blank', 'noopener');
    }
    function animate(targetWindow, fn) {
        const step = () => {
            fn();
            stepDisposable = (0, exports.scheduleAtNextAnimationFrame)(targetWindow, step);
        };
        let stepDisposable = (0, exports.scheduleAtNextAnimationFrame)(targetWindow, step);
        return (0, lifecycle_1.toDisposable)(() => stepDisposable.dispose());
    }
    network_1.RemoteAuthorities.setPreferredWebSchema(/^https:/.test(window_1.mainWindow.location.href) ? 'https' : 'http');
    /**
     * returns url('...')
     */
    function asCSSUrl(uri) {
        if (!uri) {
            return `url('')`;
        }
        return `url('${network_1.FileAccess.uriToBrowserUri(uri).toString(true).replace(/'/g, '%27')}')`;
    }
    function asCSSPropertyValue(value) {
        return `'${value.replace(/'/g, '%27')}'`;
    }
    function asCssValueWithDefault(cssPropertyValue, dflt) {
        if (cssPropertyValue !== undefined) {
            const variableMatch = cssPropertyValue.match(/^\s*var\((.+)\)$/);
            if (variableMatch) {
                const varArguments = variableMatch[1].split(',', 2);
                if (varArguments.length === 2) {
                    dflt = asCssValueWithDefault(varArguments[1].trim(), dflt);
                }
                return `var(${varArguments[0]}, ${dflt})`;
            }
            return cssPropertyValue;
        }
        return dflt;
    }
    // -- sanitize and trusted html
    /**
     * Hooks dompurify using `afterSanitizeAttributes` to check that all `href` and `src`
     * attributes are valid.
     */
    function hookDomPurifyHrefAndSrcSanitizer(allowedProtocols, allowDataImages = false) {
        // https://github.com/cure53/DOMPurify/blob/main/demos/hooks-scheme-allowlist.html
        // build an anchor to map URLs to
        const anchor = document.createElement('a');
        dompurify.addHook('afterSanitizeAttributes', (node) => {
            // check all href/src attributes for validity
            for (const attr of ['href', 'src']) {
                if (node.hasAttribute(attr)) {
                    const attrValue = node.getAttribute(attr);
                    if (attr === 'href' && attrValue.startsWith('#')) {
                        // Allow fragment links
                        continue;
                    }
                    anchor.href = attrValue;
                    if (!allowedProtocols.includes(anchor.protocol.replace(/:$/, ''))) {
                        if (allowDataImages && attr === 'src' && anchor.href.startsWith('data:')) {
                            continue;
                        }
                        node.removeAttribute(attr);
                    }
                }
            }
        });
        return (0, lifecycle_1.toDisposable)(() => {
            dompurify.removeHook('afterSanitizeAttributes');
        });
    }
    /**
     * List of safe, non-input html tags.
     */
    exports.basicMarkupHtmlTags = Object.freeze([
        'a',
        'abbr',
        'b',
        'bdo',
        'blockquote',
        'br',
        'caption',
        'cite',
        'code',
        'col',
        'colgroup',
        'dd',
        'del',
        'details',
        'dfn',
        'div',
        'dl',
        'dt',
        'em',
        'figcaption',
        'figure',
        'h1',
        'h2',
        'h3',
        'h4',
        'h5',
        'h6',
        'hr',
        'i',
        'img',
        'input',
        'ins',
        'kbd',
        'label',
        'li',
        'mark',
        'ol',
        'p',
        'pre',
        'q',
        'rp',
        'rt',
        'ruby',
        'samp',
        'small',
        'small',
        'source',
        'span',
        'strike',
        'strong',
        'sub',
        'summary',
        'sup',
        'table',
        'tbody',
        'td',
        'tfoot',
        'th',
        'thead',
        'time',
        'tr',
        'tt',
        'u',
        'ul',
        'var',
        'video',
        'wbr',
    ]);
    const defaultDomPurifyConfig = Object.freeze({
        ALLOWED_TAGS: ['a', 'button', 'blockquote', 'code', 'div', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'input', 'label', 'li', 'p', 'pre', 'select', 'small', 'span', 'strong', 'textarea', 'ul', 'ol'],
        ALLOWED_ATTR: ['href', 'data-href', 'data-command', 'target', 'title', 'name', 'src', 'alt', 'class', 'id', 'role', 'tabindex', 'style', 'data-code', 'width', 'height', 'align', 'x-dispatch', 'required', 'checked', 'placeholder', 'type', 'start'],
        RETURN_DOM: false,
        RETURN_DOM_FRAGMENT: false,
        RETURN_TRUSTED_TYPE: true
    });
    class ModifierKeyEmitter extends event.Emitter {
        constructor() {
            super();
            this._subscriptions = new lifecycle_1.DisposableStore();
            this._keyStatus = {
                altKey: false,
                shiftKey: false,
                ctrlKey: false,
                metaKey: false
            };
            this._subscriptions.add(event.Event.runAndSubscribe(exports.onDidRegisterWindow, ({ window, disposables }) => this.registerListeners(window, disposables), { window: window_1.mainWindow, disposables: this._subscriptions }));
        }
        registerListeners(window, disposables) {
            disposables.add(addDisposableListener(window, 'keydown', e => {
                if (e.defaultPrevented) {
                    return;
                }
                const event = new keyboardEvent_1.StandardKeyboardEvent(e);
                // If Alt-key keydown event is repeated, ignore it #112347
                // Only known to be necessary for Alt-Key at the moment #115810
                if (event.keyCode === 6 /* KeyCode.Alt */ && e.repeat) {
                    return;
                }
                if (e.altKey && !this._keyStatus.altKey) {
                    this._keyStatus.lastKeyPressed = 'alt';
                }
                else if (e.ctrlKey && !this._keyStatus.ctrlKey) {
                    this._keyStatus.lastKeyPressed = 'ctrl';
                }
                else if (e.metaKey && !this._keyStatus.metaKey) {
                    this._keyStatus.lastKeyPressed = 'meta';
                }
                else if (e.shiftKey && !this._keyStatus.shiftKey) {
                    this._keyStatus.lastKeyPressed = 'shift';
                }
                else if (event.keyCode !== 6 /* KeyCode.Alt */) {
                    this._keyStatus.lastKeyPressed = undefined;
                }
                else {
                    return;
                }
                this._keyStatus.altKey = e.altKey;
                this._keyStatus.ctrlKey = e.ctrlKey;
                this._keyStatus.metaKey = e.metaKey;
                this._keyStatus.shiftKey = e.shiftKey;
                if (this._keyStatus.lastKeyPressed) {
                    this._keyStatus.event = e;
                    this.fire(this._keyStatus);
                }
            }, true));
            disposables.add(addDisposableListener(window, 'keyup', e => {
                if (e.defaultPrevented) {
                    return;
                }
                if (!e.altKey && this._keyStatus.altKey) {
                    this._keyStatus.lastKeyReleased = 'alt';
                }
                else if (!e.ctrlKey && this._keyStatus.ctrlKey) {
                    this._keyStatus.lastKeyReleased = 'ctrl';
                }
                else if (!e.metaKey && this._keyStatus.metaKey) {
                    this._keyStatus.lastKeyReleased = 'meta';
                }
                else if (!e.shiftKey && this._keyStatus.shiftKey) {
                    this._keyStatus.lastKeyReleased = 'shift';
                }
                else {
                    this._keyStatus.lastKeyReleased = undefined;
                }
                if (this._keyStatus.lastKeyPressed !== this._keyStatus.lastKeyReleased) {
                    this._keyStatus.lastKeyPressed = undefined;
                }
                this._keyStatus.altKey = e.altKey;
                this._keyStatus.ctrlKey = e.ctrlKey;
                this._keyStatus.metaKey = e.metaKey;
                this._keyStatus.shiftKey = e.shiftKey;
                if (this._keyStatus.lastKeyReleased) {
                    this._keyStatus.event = e;
                    this.fire(this._keyStatus);
                }
            }, true));
            disposables.add(addDisposableListener(window.document.body, 'mousedown', () => {
                this._keyStatus.lastKeyPressed = undefined;
            }, true));
            disposables.add(addDisposableListener(window.document.body, 'mouseup', () => {
                this._keyStatus.lastKeyPressed = undefined;
            }, true));
            disposables.add(addDisposableListener(window.document.body, 'mousemove', e => {
                if (e.buttons) {
                    this._keyStatus.lastKeyPressed = undefined;
                }
            }, true));
            disposables.add(addDisposableListener(window, 'blur', () => {
                this.resetKeyStatus();
            }));
        }
        get keyStatus() {
            return this._keyStatus;
        }
        /**
         * Allows to explicitly reset the key status based on more knowledge (#109062)
         */
        resetKeyStatus() {
            this.doResetKeyStatus();
            this.fire(this._keyStatus);
        }
        doResetKeyStatus() {
            this._keyStatus = {
                altKey: false,
                shiftKey: false,
                ctrlKey: false,
                metaKey: false
            };
        }
        static getInstance() {
            if (!ModifierKeyEmitter.instance) {
                ModifierKeyEmitter.instance = new ModifierKeyEmitter();
            }
            return ModifierKeyEmitter.instance;
        }
        dispose() {
            super.dispose();
            this._subscriptions.dispose();
        }
    }
    exports.ModifierKeyEmitter = ModifierKeyEmitter;
    class DragAndDropObserver extends lifecycle_1.Disposable {
        constructor(element, callbacks) {
            super();
            this.element = element;
            this.callbacks = callbacks;
            // A helper to fix issues with repeated DRAG_ENTER / DRAG_LEAVE
            // calls see https://github.com/microsoft/vscode/issues/14470
            // when the element has child elements where the events are fired
            // repeadedly.
            this.counter = 0;
            // Allows to measure the duration of the drag operation.
            this.dragStartTime = 0;
            this.registerListeners();
        }
        registerListeners() {
            if (this.callbacks.onDragStart) {
                this._register(addDisposableListener(this.element, exports.EventType.DRAG_START, (e) => {
                    this.callbacks.onDragStart?.(e);
                }));
            }
            if (this.callbacks.onDrag) {
                this._register(addDisposableListener(this.element, exports.EventType.DRAG, (e) => {
                    this.callbacks.onDrag?.(e);
                }));
            }
            this._register(addDisposableListener(this.element, exports.EventType.DRAG_ENTER, (e) => {
                this.counter++;
                this.dragStartTime = e.timeStamp;
                this.callbacks.onDragEnter?.(e);
            }));
            this._register(addDisposableListener(this.element, exports.EventType.DRAG_OVER, (e) => {
                e.preventDefault(); // needed so that the drop event fires (https://stackoverflow.com/questions/21339924/drop-event-not-firing-in-chrome)
                this.callbacks.onDragOver?.(e, e.timeStamp - this.dragStartTime);
            }));
            this._register(addDisposableListener(this.element, exports.EventType.DRAG_LEAVE, (e) => {
                this.counter--;
                if (this.counter === 0) {
                    this.dragStartTime = 0;
                    this.callbacks.onDragLeave?.(e);
                }
            }));
            this._register(addDisposableListener(this.element, exports.EventType.DRAG_END, (e) => {
                this.counter = 0;
                this.dragStartTime = 0;
                this.callbacks.onDragEnd?.(e);
            }));
            this._register(addDisposableListener(this.element, exports.EventType.DROP, (e) => {
                this.counter = 0;
                this.dragStartTime = 0;
                this.callbacks.onDrop?.(e);
            }));
        }
    }
    exports.DragAndDropObserver = DragAndDropObserver;
    const H_REGEX = /(?<tag>[\w\-]+)?(?:#(?<id>[\w\-]+))?(?<class>(?:\.(?:[\w\-]+))*)(?:@(?<name>(?:[\w\_])+))?/;
    function h(tag, ...args) {
        let attributes;
        let children;
        if (Array.isArray(args[0])) {
            attributes = {};
            children = args[0];
        }
        else {
            attributes = args[0] || {};
            children = args[1];
        }
        const match = H_REGEX.exec(tag);
        if (!match || !match.groups) {
            throw new Error('Bad use of h');
        }
        const tagName = match.groups['tag'] || 'div';
        const el = document.createElement(tagName);
        if (match.groups['id']) {
            el.id = match.groups['id'];
        }
        const classNames = [];
        if (match.groups['class']) {
            for (const className of match.groups['class'].split('.')) {
                if (className !== '') {
                    classNames.push(className);
                }
            }
        }
        if (attributes.className !== undefined) {
            for (const className of attributes.className.split('.')) {
                if (className !== '') {
                    classNames.push(className);
                }
            }
        }
        if (classNames.length > 0) {
            el.className = classNames.join(' ');
        }
        const result = {};
        if (match.groups['name']) {
            result[match.groups['name']] = el;
        }
        if (children) {
            for (const c of children) {
                if (isHTMLElement(c)) {
                    el.appendChild(c);
                }
                else if (typeof c === 'string') {
                    el.append(c);
                }
                else if ('root' in c) {
                    Object.assign(result, c);
                    el.appendChild(c.root);
                }
            }
        }
        for (const [key, value] of Object.entries(attributes)) {
            if (key === 'className') {
                continue;
            }
            else if (key === 'style') {
                for (const [cssKey, cssValue] of Object.entries(value)) {
                    el.style.setProperty(camelCaseToHyphenCase(cssKey), typeof cssValue === 'number' ? cssValue + 'px' : '' + cssValue);
                }
            }
            else if (key === 'tabIndex') {
                el.tabIndex = value;
            }
            else {
                el.setAttribute(camelCaseToHyphenCase(key), value.toString());
            }
        }
        result['root'] = el;
        return result;
    }
    function svgElem(tag, ...args) {
        let attributes;
        let children;
        if (Array.isArray(args[0])) {
            attributes = {};
            children = args[0];
        }
        else {
            attributes = args[0] || {};
            children = args[1];
        }
        const match = H_REGEX.exec(tag);
        if (!match || !match.groups) {
            throw new Error('Bad use of h');
        }
        const tagName = match.groups['tag'] || 'div';
        const el = document.createElementNS('http://www.w3.org/2000/svg', tagName);
        if (match.groups['id']) {
            el.id = match.groups['id'];
        }
        const classNames = [];
        if (match.groups['class']) {
            for (const className of match.groups['class'].split('.')) {
                if (className !== '') {
                    classNames.push(className);
                }
            }
        }
        if (attributes.className !== undefined) {
            for (const className of attributes.className.split('.')) {
                if (className !== '') {
                    classNames.push(className);
                }
            }
        }
        if (classNames.length > 0) {
            el.className = classNames.join(' ');
        }
        const result = {};
        if (match.groups['name']) {
            result[match.groups['name']] = el;
        }
        if (children) {
            for (const c of children) {
                if (isHTMLElement(c)) {
                    el.appendChild(c);
                }
                else if (typeof c === 'string') {
                    el.append(c);
                }
                else if ('root' in c) {
                    Object.assign(result, c);
                    el.appendChild(c.root);
                }
            }
        }
        for (const [key, value] of Object.entries(attributes)) {
            if (key === 'className') {
                continue;
            }
            else if (key === 'style') {
                for (const [cssKey, cssValue] of Object.entries(value)) {
                    el.style.setProperty(camelCaseToHyphenCase(cssKey), typeof cssValue === 'number' ? cssValue + 'px' : '' + cssValue);
                }
            }
            else if (key === 'tabIndex') {
                el.tabIndex = value;
            }
            else {
                el.setAttribute(camelCaseToHyphenCase(key), value.toString());
            }
        }
        result['root'] = el;
        return result;
    }
    function camelCaseToHyphenCase(str) {
        return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[630/*vs/base/browser/domObservable*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,2/*vs/base/common/lifecycle*/,21/*vs/base/common/observable*/]), function (require, exports, dom_1, lifecycle_1, observable_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.createStyleSheetFromObservable = createStyleSheetFromObservable;
    function createStyleSheetFromObservable(css) {
        const store = new lifecycle_1.DisposableStore();
        const w = store.add((0, dom_1.createStyleSheet2)());
        store.add((0, observable_1.autorun)(reader => {
            w.setStyle(css.read(reader));
        }));
        return store;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[352/*vs/base/browser/formattedTextRenderer*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/]), function (require, exports, DOM) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.renderText = renderText;
    exports.renderFormattedText = renderFormattedText;
    exports.createElement = createElement;
    function renderText(text, options = {}) {
        const element = createElement(options);
        element.textContent = text;
        return element;
    }
    function renderFormattedText(formattedText, options = {}) {
        const element = createElement(options);
        _renderFormattedText(element, parseFormattedText(formattedText, !!options.renderCodeSegments), options.actionHandler, options.renderCodeSegments);
        return element;
    }
    function createElement(options) {
        const tagName = options.inline ? 'span' : 'div';
        const element = document.createElement(tagName);
        if (options.className) {
            element.className = options.className;
        }
        return element;
    }
    class StringStream {
        constructor(source) {
            this.source = source;
            this.index = 0;
        }
        eos() {
            return this.index >= this.source.length;
        }
        next() {
            const next = this.peek();
            this.advance();
            return next;
        }
        peek() {
            return this.source[this.index];
        }
        advance() {
            this.index++;
        }
    }
    function _renderFormattedText(element, treeNode, actionHandler, renderCodeSegments) {
        let child;
        if (treeNode.type === 2 /* FormatType.Text */) {
            child = document.createTextNode(treeNode.content || '');
        }
        else if (treeNode.type === 3 /* FormatType.Bold */) {
            child = document.createElement('b');
        }
        else if (treeNode.type === 4 /* FormatType.Italics */) {
            child = document.createElement('i');
        }
        else if (treeNode.type === 7 /* FormatType.Code */ && renderCodeSegments) {
            child = document.createElement('code');
        }
        else if (treeNode.type === 5 /* FormatType.Action */ && actionHandler) {
            const a = document.createElement('a');
            actionHandler.disposables.add(DOM.addStandardDisposableListener(a, 'click', (event) => {
                actionHandler.callback(String(treeNode.index), event);
            }));
            child = a;
        }
        else if (treeNode.type === 8 /* FormatType.NewLine */) {
            child = document.createElement('br');
        }
        else if (treeNode.type === 1 /* FormatType.Root */) {
            child = element;
        }
        if (child && element !== child) {
            element.appendChild(child);
        }
        if (child && Array.isArray(treeNode.children)) {
            treeNode.children.forEach((nodeChild) => {
                _renderFormattedText(child, nodeChild, actionHandler, renderCodeSegments);
            });
        }
    }
    function parseFormattedText(content, parseCodeSegments) {
        const root = {
            type: 1 /* FormatType.Root */,
            children: []
        };
        let actionViewItemIndex = 0;
        let current = root;
        const stack = [];
        const stream = new StringStream(content);
        while (!stream.eos()) {
            let next = stream.next();
            const isEscapedFormatType = (next === '\\' && formatTagType(stream.peek(), parseCodeSegments) !== 0 /* FormatType.Invalid */);
            if (isEscapedFormatType) {
                next = stream.next(); // unread the backslash if it escapes a format tag type
            }
            if (!isEscapedFormatType && isFormatTag(next, parseCodeSegments) && next === stream.peek()) {
                stream.advance();
                if (current.type === 2 /* FormatType.Text */) {
                    current = stack.pop();
                }
                const type = formatTagType(next, parseCodeSegments);
                if (current.type === type || (current.type === 5 /* FormatType.Action */ && type === 6 /* FormatType.ActionClose */)) {
                    current = stack.pop();
                }
                else {
                    const newCurrent = {
                        type: type,
                        children: []
                    };
                    if (type === 5 /* FormatType.Action */) {
                        newCurrent.index = actionViewItemIndex;
                        actionViewItemIndex++;
                    }
                    current.children.push(newCurrent);
                    stack.push(current);
                    current = newCurrent;
                }
            }
            else if (next === '\n') {
                if (current.type === 2 /* FormatType.Text */) {
                    current = stack.pop();
                }
                current.children.push({
                    type: 8 /* FormatType.NewLine */
                });
            }
            else {
                if (current.type !== 2 /* FormatType.Text */) {
                    const textCurrent = {
                        type: 2 /* FormatType.Text */,
                        content: next
                    };
                    current.children.push(textCurrent);
                    stack.push(current);
                    current = textCurrent;
                }
                else {
                    current.content += next;
                }
            }
        }
        if (current.type === 2 /* FormatType.Text */) {
            current = stack.pop();
        }
        if (stack.length) {
            // incorrectly formatted string literal
        }
        return root;
    }
    function isFormatTag(char, supportCodeSegments) {
        return formatTagType(char, supportCodeSegments) !== 0 /* FormatType.Invalid */;
    }
    function formatTagType(char, supportCodeSegments) {
        switch (char) {
            case '*':
                return 3 /* FormatType.Bold */;
            case '_':
                return 4 /* FormatType.Italics */;
            case '[':
                return 5 /* FormatType.Action */;
            case ']':
                return 6 /* FormatType.ActionClose */;
            case '`':
                return supportCodeSegments ? 7 /* FormatType.Code */ : 0 /* FormatType.Invalid */;
            default:
                return 0 /* FormatType.Invalid */;
        }
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[172/*vs/base/browser/globalPointerMoveMonitor*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,2/*vs/base/common/lifecycle*/]), function (require, exports, dom, lifecycle_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.GlobalPointerMoveMonitor = void 0;
    class GlobalPointerMoveMonitor {
        constructor() {
            this._hooks = new lifecycle_1.DisposableStore();
            this._pointerMoveCallback = null;
            this._onStopCallback = null;
        }
        dispose() {
            this.stopMonitoring(false);
            this._hooks.dispose();
        }
        stopMonitoring(invokeStopCallback, browserEvent) {
            if (!this.isMonitoring()) {
                // Not monitoring
                return;
            }
            // Unhook
            this._hooks.clear();
            this._pointerMoveCallback = null;
            const onStopCallback = this._onStopCallback;
            this._onStopCallback = null;
            if (invokeStopCallback && onStopCallback) {
                onStopCallback(browserEvent);
            }
        }
        isMonitoring() {
            return !!this._pointerMoveCallback;
        }
        startMonitoring(initialElement, pointerId, initialButtons, pointerMoveCallback, onStopCallback) {
            if (this.isMonitoring()) {
                this.stopMonitoring(false);
            }
            this._pointerMoveCallback = pointerMoveCallback;
            this._onStopCallback = onStopCallback;
            let eventSource = initialElement;
            try {
                initialElement.setPointerCapture(pointerId);
                this._hooks.add((0, lifecycle_1.toDisposable)(() => {
                    try {
                        initialElement.releasePointerCapture(pointerId);
                    }
                    catch (err) {
                        // See https://github.com/microsoft/vscode/issues/161731
                        //
                        // `releasePointerCapture` sometimes fails when being invoked with the exception:
                        //     DOMException: Failed to execute 'releasePointerCapture' on 'Element':
                        //     No active pointer with the given id is found.
                        //
                        // There's no need to do anything in case of failure
                    }
                }));
            }
            catch (err) {
                // See https://github.com/microsoft/vscode/issues/144584
                // See https://github.com/microsoft/vscode/issues/146947
                // `setPointerCapture` sometimes fails when being invoked
                // from a `mousedown` listener on macOS and Windows
                // and it always fails on Linux with the exception:
                //     DOMException: Failed to execute 'setPointerCapture' on 'Element':
                //     No active pointer with the given id is found.
                // In case of failure, we bind the listeners on the window
                eventSource = dom.getWindow(initialElement);
            }
            this._hooks.add(dom.addDisposableListener(eventSource, dom.EventType.POINTER_MOVE, (e) => {
                if (e.buttons !== initialButtons) {
                    // Buttons state has changed in the meantime
                    this.stopMonitoring(true);
                    return;
                }
                e.preventDefault();
                this._pointerMoveCallback(e);
            }));
            this._hooks.add(dom.addDisposableListener(eventSource, dom.EventType.POINTER_UP, (e) => this.stopMonitoring(true)));
        }
    }
    exports.GlobalPointerMoveMonitor = GlobalPointerMoveMonitor;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[253/*vs/base/browser/pixelRatio*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/]), function (require, exports, dom_1, event_1, lifecycle_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.PixelRatio = void 0;
    /**
     * See https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio#monitoring_screen_resolution_or_zoom_level_changes
     */
    class DevicePixelRatioMonitor extends lifecycle_1.Disposable {
        constructor(targetWindow) {
            super();
            this._onDidChange = this._register(new event_1.Emitter());
            this.onDidChange = this._onDidChange.event;
            this._listener = () => this._handleChange(targetWindow, true);
            this._mediaQueryList = null;
            this._handleChange(targetWindow, false);
        }
        _handleChange(targetWindow, fireEvent) {
            this._mediaQueryList?.removeEventListener('change', this._listener);
            this._mediaQueryList = targetWindow.matchMedia(`(resolution: ${targetWindow.devicePixelRatio}dppx)`);
            this._mediaQueryList.addEventListener('change', this._listener);
            if (fireEvent) {
                this._onDidChange.fire();
            }
        }
    }
    class PixelRatioMonitorImpl extends lifecycle_1.Disposable {
        get value() {
            return this._value;
        }
        constructor(targetWindow) {
            super();
            this._onDidChange = this._register(new event_1.Emitter());
            this.onDidChange = this._onDidChange.event;
            this._value = this._getPixelRatio(targetWindow);
            const dprMonitor = this._register(new DevicePixelRatioMonitor(targetWindow));
            this._register(dprMonitor.onDidChange(() => {
                this._value = this._getPixelRatio(targetWindow);
                this._onDidChange.fire(this._value);
            }));
        }
        _getPixelRatio(targetWindow) {
            const ctx = document.createElement('canvas').getContext('2d');
            const dpr = targetWindow.devicePixelRatio || 1;
            const bsr = ctx.webkitBackingStorePixelRatio ||
                ctx.mozBackingStorePixelRatio ||
                ctx.msBackingStorePixelRatio ||
                ctx.oBackingStorePixelRatio ||
                ctx.backingStorePixelRatio || 1;
            return dpr / bsr;
        }
    }
    class PixelRatioMonitorFacade {
        constructor() {
            this.mapWindowIdToPixelRatioMonitor = new Map();
        }
        _getOrCreatePixelRatioMonitor(targetWindow) {
            const targetWindowId = (0, dom_1.getWindowId)(targetWindow);
            let pixelRatioMonitor = this.mapWindowIdToPixelRatioMonitor.get(targetWindowId);
            if (!pixelRatioMonitor) {
                pixelRatioMonitor = (0, lifecycle_1.markAsSingleton)(new PixelRatioMonitorImpl(targetWindow));
                this.mapWindowIdToPixelRatioMonitor.set(targetWindowId, pixelRatioMonitor);
                (0, lifecycle_1.markAsSingleton)(event_1.Event.once(dom_1.onDidUnregisterWindow)(({ vscodeWindowId }) => {
                    if (vscodeWindowId === targetWindowId) {
                        pixelRatioMonitor?.dispose();
                        this.mapWindowIdToPixelRatioMonitor.delete(targetWindowId);
                    }
                }));
            }
            return pixelRatioMonitor;
        }
        getInstance(targetWindow) {
            return this._getOrCreatePixelRatioMonitor(targetWindow);
        }
    }
    /**
     * Returns the pixel ratio.
     *
     * This is useful for rendering <canvas> elements at native screen resolution or for being used as
     * a cache key when storing font measurements. Fonts might render differently depending on resolution
     * and any measurements need to be discarded for example when a window is moved from a monitor to another.
     */
    exports.PixelRatio = new PixelRatioMonitorFacade();
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/






define(__m[69/*vs/base/browser/touch*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,52/*vs/base/browser/window*/,13/*vs/base/common/arrays*/,126/*vs/base/common/decorators*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,73/*vs/base/common/linkedList*/]), function (require, exports, DomUtils, window_1, arrays, decorators_1, event_1, lifecycle_1, linkedList_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Gesture = exports.EventType = void 0;
    var EventType;
    (function (EventType) {
        EventType.Tap = '-monaco-gesturetap';
        EventType.Change = '-monaco-gesturechange';
        EventType.Start = '-monaco-gesturestart';
        EventType.End = '-monaco-gesturesend';
        EventType.Contextmenu = '-monaco-gesturecontextmenu';
    })(EventType || (exports.EventType = EventType = {}));
    class Gesture extends lifecycle_1.Disposable {
        static { this.SCROLL_FRICTION = -0.005; }
        static { this.HOLD_DELAY = 700; }
        static { this.CLEAR_TAP_COUNT_TIME = 400; } // ms
        constructor() {
            super();
            this.dispatched = false;
            this.targets = new linkedList_1.LinkedList();
            this.ignoreTargets = new linkedList_1.LinkedList();
            this.activeTouches = {};
            this.handle = null;
            this._lastSetTapCountTime = 0;
            this._register(event_1.Event.runAndSubscribe(DomUtils.onDidRegisterWindow, ({ window, disposables }) => {
                disposables.add(DomUtils.addDisposableListener(window.document, 'touchstart', (e) => this.onTouchStart(e), { passive: false }));
                disposables.add(DomUtils.addDisposableListener(window.document, 'touchend', (e) => this.onTouchEnd(window, e)));
                disposables.add(DomUtils.addDisposableListener(window.document, 'touchmove', (e) => this.onTouchMove(e), { passive: false }));
            }, { window: window_1.mainWindow, disposables: this._store }));
        }
        static addTarget(element) {
            if (!Gesture.isTouchDevice()) {
                return lifecycle_1.Disposable.None;
            }
            if (!Gesture.INSTANCE) {
                Gesture.INSTANCE = (0, lifecycle_1.markAsSingleton)(new Gesture());
            }
            const remove = Gesture.INSTANCE.targets.push(element);
            return (0, lifecycle_1.toDisposable)(remove);
        }
        static ignoreTarget(element) {
            if (!Gesture.isTouchDevice()) {
                return lifecycle_1.Disposable.None;
            }
            if (!Gesture.INSTANCE) {
                Gesture.INSTANCE = (0, lifecycle_1.markAsSingleton)(new Gesture());
            }
            const remove = Gesture.INSTANCE.ignoreTargets.push(element);
            return (0, lifecycle_1.toDisposable)(remove);
        }
        static isTouchDevice() {
            // `'ontouchstart' in window` always evaluates to true with typescript's modern typings. This causes `window` to be
            // `never` later in `window.navigator`. That's why we need the explicit `window as Window` cast
            return 'ontouchstart' in window_1.mainWindow || navigator.maxTouchPoints > 0;
        }
        dispose() {
            if (this.handle) {
                this.handle.dispose();
                this.handle = null;
            }
            super.dispose();
        }
        onTouchStart(e) {
            const timestamp = Date.now(); // use Date.now() because on FF e.timeStamp is not epoch based.
            if (this.handle) {
                this.handle.dispose();
                this.handle = null;
            }
            for (let i = 0, len = e.targetTouches.length; i < len; i++) {
                const touch = e.targetTouches.item(i);
                this.activeTouches[touch.identifier] = {
                    id: touch.identifier,
                    initialTarget: touch.target,
                    initialTimeStamp: timestamp,
                    initialPageX: touch.pageX,
                    initialPageY: touch.pageY,
                    rollingTimestamps: [timestamp],
                    rollingPageX: [touch.pageX],
                    rollingPageY: [touch.pageY]
                };
                const evt = this.newGestureEvent(EventType.Start, touch.target);
                evt.pageX = touch.pageX;
                evt.pageY = touch.pageY;
                this.dispatchEvent(evt);
            }
            if (this.dispatched) {
                e.preventDefault();
                e.stopPropagation();
                this.dispatched = false;
            }
        }
        onTouchEnd(targetWindow, e) {
            const timestamp = Date.now(); // use Date.now() because on FF e.timeStamp is not epoch based.
            const activeTouchCount = Object.keys(this.activeTouches).length;
            for (let i = 0, len = e.changedTouches.length; i < len; i++) {
                const touch = e.changedTouches.item(i);
                if (!this.activeTouches.hasOwnProperty(String(touch.identifier))) {
                    console.warn('move of an UNKNOWN touch', touch);
                    continue;
                }
                const data = this.activeTouches[touch.identifier], holdTime = Date.now() - data.initialTimeStamp;
                if (holdTime < Gesture.HOLD_DELAY
                    && Math.abs(data.initialPageX - arrays.tail(data.rollingPageX)) < 30
                    && Math.abs(data.initialPageY - arrays.tail(data.rollingPageY)) < 30) {
                    const evt = this.newGestureEvent(EventType.Tap, data.initialTarget);
                    evt.pageX = arrays.tail(data.rollingPageX);
                    evt.pageY = arrays.tail(data.rollingPageY);
                    this.dispatchEvent(evt);
                }
                else if (holdTime >= Gesture.HOLD_DELAY
                    && Math.abs(data.initialPageX - arrays.tail(data.rollingPageX)) < 30
                    && Math.abs(data.initialPageY - arrays.tail(data.rollingPageY)) < 30) {
                    const evt = this.newGestureEvent(EventType.Contextmenu, data.initialTarget);
                    evt.pageX = arrays.tail(data.rollingPageX);
                    evt.pageY = arrays.tail(data.rollingPageY);
                    this.dispatchEvent(evt);
                }
                else if (activeTouchCount === 1) {
                    const finalX = arrays.tail(data.rollingPageX);
                    const finalY = arrays.tail(data.rollingPageY);
                    const deltaT = arrays.tail(data.rollingTimestamps) - data.rollingTimestamps[0];
                    const deltaX = finalX - data.rollingPageX[0];
                    const deltaY = finalY - data.rollingPageY[0];
                    // We need to get all the dispatch targets on the start of the inertia event
                    const dispatchTo = [...this.targets].filter(t => data.initialTarget instanceof Node && t.contains(data.initialTarget));
                    this.inertia(targetWindow, dispatchTo, timestamp, // time now
                    Math.abs(deltaX) / deltaT, // speed
                    deltaX > 0 ? 1 : -1, // x direction
                    finalX, // x now
                    Math.abs(deltaY) / deltaT, // y speed
                    deltaY > 0 ? 1 : -1, // y direction
                    finalY // y now
                    );
                }
                this.dispatchEvent(this.newGestureEvent(EventType.End, data.initialTarget));
                // forget about this touch
                delete this.activeTouches[touch.identifier];
            }
            if (this.dispatched) {
                e.preventDefault();
                e.stopPropagation();
                this.dispatched = false;
            }
        }
        newGestureEvent(type, initialTarget) {
            const event = document.createEvent('CustomEvent');
            event.initEvent(type, false, true);
            event.initialTarget = initialTarget;
            event.tapCount = 0;
            return event;
        }
        dispatchEvent(event) {
            if (event.type === EventType.Tap) {
                const currentTime = (new Date()).getTime();
                let setTapCount = 0;
                if (currentTime - this._lastSetTapCountTime > Gesture.CLEAR_TAP_COUNT_TIME) {
                    setTapCount = 1;
                }
                else {
                    setTapCount = 2;
                }
                this._lastSetTapCountTime = currentTime;
                event.tapCount = setTapCount;
            }
            else if (event.type === EventType.Change || event.type === EventType.Contextmenu) {
                // tap is canceled by scrolling or context menu
                this._lastSetTapCountTime = 0;
            }
            if (event.initialTarget instanceof Node) {
                for (const ignoreTarget of this.ignoreTargets) {
                    if (ignoreTarget.contains(event.initialTarget)) {
                        return;
                    }
                }
                const targets = [];
                for (const target of this.targets) {
                    if (target.contains(event.initialTarget)) {
                        let depth = 0;
                        let now = event.initialTarget;
                        while (now && now !== target) {
                            depth++;
                            now = now.parentElement;
                        }
                        targets.push([depth, target]);
                    }
                }
                targets.sort((a, b) => a[0] - b[0]);
                for (const [_, target] of targets) {
                    target.dispatchEvent(event);
                    this.dispatched = true;
                }
            }
        }
        inertia(targetWindow, dispatchTo, t1, vX, dirX, x, vY, dirY, y) {
            this.handle = DomUtils.scheduleAtNextAnimationFrame(targetWindow, () => {
                const now = Date.now();
                // velocity: old speed + accel_over_time
                const deltaT = now - t1;
                let delta_pos_x = 0, delta_pos_y = 0;
                let stopped = true;
                vX += Gesture.SCROLL_FRICTION * deltaT;
                vY += Gesture.SCROLL_FRICTION * deltaT;
                if (vX > 0) {
                    stopped = false;
                    delta_pos_x = dirX * vX * deltaT;
                }
                if (vY > 0) {
                    stopped = false;
                    delta_pos_y = dirY * vY * deltaT;
                }
                // dispatch translation event
                const evt = this.newGestureEvent(EventType.Change);
                evt.translationX = delta_pos_x;
                evt.translationY = delta_pos_y;
                dispatchTo.forEach(d => d.dispatchEvent(evt));
                if (!stopped) {
                    this.inertia(targetWindow, dispatchTo, now, vX, dirX, x + delta_pos_x, vY, dirY, y + delta_pos_y);
                }
            });
        }
        onTouchMove(e) {
            const timestamp = Date.now(); // use Date.now() because on FF e.timeStamp is not epoch based.
            for (let i = 0, len = e.changedTouches.length; i < len; i++) {
                const touch = e.changedTouches.item(i);
                if (!this.activeTouches.hasOwnProperty(String(touch.identifier))) {
                    console.warn('end of an UNKNOWN touch', touch);
                    continue;
                }
                const data = this.activeTouches[touch.identifier];
                const evt = this.newGestureEvent(EventType.Change, data.initialTarget);
                evt.translationX = touch.pageX - arrays.tail(data.rollingPageX);
                evt.translationY = touch.pageY - arrays.tail(data.rollingPageY);
                evt.pageX = touch.pageX;
                evt.pageY = touch.pageY;
                this.dispatchEvent(evt);
                // only keep a few data points, to average the final speed
                if (data.rollingPageX.length > 3) {
                    data.rollingPageX.shift();
                    data.rollingPageY.shift();
                    data.rollingTimestamps.shift();
                }
                data.rollingPageX.push(touch.pageX);
                data.rollingPageY.push(touch.pageY);
                data.rollingTimestamps.push(timestamp);
            }
            if (this.dispatched) {
                e.preventDefault();
                e.stopPropagation();
                this.dispatched = false;
            }
        }
    }
    exports.Gesture = Gesture;
    __decorate([
        decorators_1.memoize
    ], Gesture, "isTouchDevice", null);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[46/*vs/base/browser/ui/aria/aria*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,458/*vs/css!vs/base/browser/ui/aria/aria*/]), function (require, exports, dom) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.setARIAContainer = setARIAContainer;
    exports.alert = alert;
    exports.status = status;
    // Use a max length since we are inserting the whole msg in the DOM and that can cause browsers to freeze for long messages #94233
    const MAX_MESSAGE_LENGTH = 20000;
    let ariaContainer;
    let alertContainer;
    let alertContainer2;
    let statusContainer;
    let statusContainer2;
    function setARIAContainer(parent) {
        ariaContainer = document.createElement('div');
        ariaContainer.className = 'monaco-aria-container';
        const createAlertContainer = () => {
            const element = document.createElement('div');
            element.className = 'monaco-alert';
            element.setAttribute('role', 'alert');
            element.setAttribute('aria-atomic', 'true');
            ariaContainer.appendChild(element);
            return element;
        };
        alertContainer = createAlertContainer();
        alertContainer2 = createAlertContainer();
        const createStatusContainer = () => {
            const element = document.createElement('div');
            element.className = 'monaco-status';
            element.setAttribute('aria-live', 'polite');
            element.setAttribute('aria-atomic', 'true');
            ariaContainer.appendChild(element);
            return element;
        };
        statusContainer = createStatusContainer();
        statusContainer2 = createStatusContainer();
        parent.appendChild(ariaContainer);
    }
    /**
     * Given the provided message, will make sure that it is read as alert to screen readers.
     */
    function alert(msg) {
        if (!ariaContainer) {
            return;
        }
        // Use alternate containers such that duplicated messages get read out by screen readers #99466
        if (alertContainer.textContent !== msg) {
            dom.clearNode(alertContainer2);
            insertMessage(alertContainer, msg);
        }
        else {
            dom.clearNode(alertContainer);
            insertMessage(alertContainer2, msg);
        }
    }
    /**
     * Given the provided message, will make sure that it is read as status to screen readers.
     */
    function status(msg) {
        if (!ariaContainer) {
            return;
        }
        if (statusContainer.textContent !== msg) {
            dom.clearNode(statusContainer2);
            insertMessage(statusContainer, msg);
        }
        else {
            dom.clearNode(statusContainer);
            insertMessage(statusContainer2, msg);
        }
    }
    function insertMessage(target, msg) {
        dom.clearNode(target);
        if (msg.length > MAX_MESSAGE_LENGTH) {
            msg = msg.substr(0, MAX_MESSAGE_LENGTH);
        }
        target.textContent = msg;
        // See https://www.paciellogroup.com/blog/2012/06/html5-accessibility-chops-aria-rolealert-browser-support/
        target.style.visibility = 'hidden';
        target.style.visibility = 'visible';
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[353/*vs/base/browser/ui/contextview/contextview*/], __M([1/*require*/,0/*exports*/,248/*vs/base/browser/canIUse*/,5/*vs/base/browser/dom*/,2/*vs/base/common/lifecycle*/,16/*vs/base/common/platform*/,188/*vs/base/common/range*/,462/*vs/css!vs/base/browser/ui/contextview/contextview*/]), function (require, exports, canIUse_1, DOM, lifecycle_1, platform, range_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ContextView = exports.LayoutAnchorMode = void 0;
    exports.isAnchor = isAnchor;
    exports.layout = layout;
    function isAnchor(obj) {
        const anchor = obj;
        return !!anchor && typeof anchor.x === 'number' && typeof anchor.y === 'number';
    }
    var LayoutAnchorMode;
    (function (LayoutAnchorMode) {
        LayoutAnchorMode[LayoutAnchorMode["AVOID"] = 0] = "AVOID";
        LayoutAnchorMode[LayoutAnchorMode["ALIGN"] = 1] = "ALIGN";
    })(LayoutAnchorMode || (exports.LayoutAnchorMode = LayoutAnchorMode = {}));
    /**
     * Lays out a one dimensional view next to an anchor in a viewport.
     *
     * @returns The view offset within the viewport.
     */
    function layout(viewportSize, viewSize, anchor) {
        const layoutAfterAnchorBoundary = anchor.mode === LayoutAnchorMode.ALIGN ? anchor.offset : anchor.offset + anchor.size;
        const layoutBeforeAnchorBoundary = anchor.mode === LayoutAnchorMode.ALIGN ? anchor.offset + anchor.size : anchor.offset;
        if (anchor.position === 0 /* LayoutAnchorPosition.Before */) {
            if (viewSize <= viewportSize - layoutAfterAnchorBoundary) {
                return layoutAfterAnchorBoundary; // happy case, lay it out after the anchor
            }
            if (viewSize <= layoutBeforeAnchorBoundary) {
                return layoutBeforeAnchorBoundary - viewSize; // ok case, lay it out before the anchor
            }
            return Math.max(viewportSize - viewSize, 0); // sad case, lay it over the anchor
        }
        else {
            if (viewSize <= layoutBeforeAnchorBoundary) {
                return layoutBeforeAnchorBoundary - viewSize; // happy case, lay it out before the anchor
            }
            if (viewSize <= viewportSize - layoutAfterAnchorBoundary) {
                return layoutAfterAnchorBoundary; // ok case, lay it out after the anchor
            }
            return 0; // sad case, lay it over the anchor
        }
    }
    class ContextView extends lifecycle_1.Disposable {
        static { this.BUBBLE_UP_EVENTS = ['click', 'keydown', 'focus', 'blur']; }
        static { this.BUBBLE_DOWN_EVENTS = ['click']; }
        constructor(container, domPosition) {
            super();
            this.container = null;
            this.useFixedPosition = false;
            this.useShadowDOM = false;
            this.delegate = null;
            this.toDisposeOnClean = lifecycle_1.Disposable.None;
            this.toDisposeOnSetContainer = lifecycle_1.Disposable.None;
            this.shadowRoot = null;
            this.shadowRootHostElement = null;
            this.view = DOM.$('.context-view');
            DOM.hide(this.view);
            this.setContainer(container, domPosition);
            this._register((0, lifecycle_1.toDisposable)(() => this.setContainer(null, 1 /* ContextViewDOMPosition.ABSOLUTE */)));
        }
        setContainer(container, domPosition) {
            this.useFixedPosition = domPosition !== 1 /* ContextViewDOMPosition.ABSOLUTE */;
            const usedShadowDOM = this.useShadowDOM;
            this.useShadowDOM = domPosition === 3 /* ContextViewDOMPosition.FIXED_SHADOW */;
            if (container === this.container && usedShadowDOM === this.useShadowDOM) {
                return; // container is the same and no shadow DOM usage has changed
            }
            if (this.container) {
                this.toDisposeOnSetContainer.dispose();
                this.view.remove();
                if (this.shadowRoot) {
                    this.shadowRoot = null;
                    this.shadowRootHostElement?.remove();
                    this.shadowRootHostElement = null;
                }
                this.container = null;
            }
            if (container) {
                this.container = container;
                if (this.useShadowDOM) {
                    this.shadowRootHostElement = DOM.$('.shadow-root-host');
                    this.container.appendChild(this.shadowRootHostElement);
                    this.shadowRoot = this.shadowRootHostElement.attachShadow({ mode: 'open' });
                    const style = document.createElement('style');
                    style.textContent = SHADOW_ROOT_CSS;
                    this.shadowRoot.appendChild(style);
                    this.shadowRoot.appendChild(this.view);
                    this.shadowRoot.appendChild(DOM.$('slot'));
                }
                else {
                    this.container.appendChild(this.view);
                }
                const toDisposeOnSetContainer = new lifecycle_1.DisposableStore();
                ContextView.BUBBLE_UP_EVENTS.forEach(event => {
                    toDisposeOnSetContainer.add(DOM.addStandardDisposableListener(this.container, event, e => {
                        this.onDOMEvent(e, false);
                    }));
                });
                ContextView.BUBBLE_DOWN_EVENTS.forEach(event => {
                    toDisposeOnSetContainer.add(DOM.addStandardDisposableListener(this.container, event, e => {
                        this.onDOMEvent(e, true);
                    }, true));
                });
                this.toDisposeOnSetContainer = toDisposeOnSetContainer;
            }
        }
        show(delegate) {
            if (this.isVisible()) {
                this.hide();
            }
            // Show static box
            DOM.clearNode(this.view);
            this.view.className = 'context-view monaco-component';
            this.view.style.top = '0px';
            this.view.style.left = '0px';
            this.view.style.zIndex = `${2575 + (delegate.layer ?? 0)}`;
            this.view.style.position = this.useFixedPosition ? 'fixed' : 'absolute';
            DOM.show(this.view);
            // Render content
            this.toDisposeOnClean = delegate.render(this.view) || lifecycle_1.Disposable.None;
            // Set active delegate
            this.delegate = delegate;
            // Layout
            this.doLayout();
            // Focus
            this.delegate.focus?.();
        }
        getViewElement() {
            return this.view;
        }
        layout() {
            if (!this.isVisible()) {
                return;
            }
            if (this.delegate.canRelayout === false && !(platform.isIOS && canIUse_1.BrowserFeatures.pointerEvents)) {
                this.hide();
                return;
            }
            this.delegate?.layout?.();
            this.doLayout();
        }
        doLayout() {
            // Check that we still have a delegate - this.delegate.layout may have hidden
            if (!this.isVisible()) {
                return;
            }
            // Get anchor
            const anchor = this.delegate.getAnchor();
            // Compute around
            let around;
            // Get the element's position and size (to anchor the view)
            if (DOM.isHTMLElement(anchor)) {
                const elementPosition = DOM.getDomNodePagePosition(anchor);
                // In areas where zoom is applied to the element or its ancestors, we need to adjust the size of the element
                // e.g. The title bar has counter zoom behavior meaning it applies the inverse of zoom level.
                // Window Zoom Level: 1.5, Title Bar Zoom: 1/1.5, Size Multiplier: 1.5
                const zoom = DOM.getDomNodeZoomLevel(anchor);
                around = {
                    top: elementPosition.top * zoom,
                    left: elementPosition.left * zoom,
                    width: elementPosition.width * zoom,
                    height: elementPosition.height * zoom
                };
            }
            else if (isAnchor(anchor)) {
                around = {
                    top: anchor.y,
                    left: anchor.x,
                    width: anchor.width || 1,
                    height: anchor.height || 2
                };
            }
            else {
                around = {
                    top: anchor.posy,
                    left: anchor.posx,
                    // We are about to position the context view where the mouse
                    // cursor is. To prevent the view being exactly under the mouse
                    // when showing and thus potentially triggering an action within,
                    // we treat the mouse location like a small sized block element.
                    width: 2,
                    height: 2
                };
            }
            const viewSizeWidth = DOM.getTotalWidth(this.view);
            const viewSizeHeight = DOM.getTotalHeight(this.view);
            const anchorPosition = this.delegate.anchorPosition || 0 /* AnchorPosition.BELOW */;
            const anchorAlignment = this.delegate.anchorAlignment || 0 /* AnchorAlignment.LEFT */;
            const anchorAxisAlignment = this.delegate.anchorAxisAlignment || 0 /* AnchorAxisAlignment.VERTICAL */;
            let top;
            let left;
            const activeWindow = DOM.getActiveWindow();
            if (anchorAxisAlignment === 0 /* AnchorAxisAlignment.VERTICAL */) {
                const verticalAnchor = { offset: around.top - activeWindow.pageYOffset, size: around.height, position: anchorPosition === 0 /* AnchorPosition.BELOW */ ? 0 /* LayoutAnchorPosition.Before */ : 1 /* LayoutAnchorPosition.After */ };
                const horizontalAnchor = { offset: around.left, size: around.width, position: anchorAlignment === 0 /* AnchorAlignment.LEFT */ ? 0 /* LayoutAnchorPosition.Before */ : 1 /* LayoutAnchorPosition.After */, mode: LayoutAnchorMode.ALIGN };
                top = layout(activeWindow.innerHeight, viewSizeHeight, verticalAnchor) + activeWindow.pageYOffset;
                // if view intersects vertically with anchor,  we must avoid the anchor
                if (range_1.Range.intersects({ start: top, end: top + viewSizeHeight }, { start: verticalAnchor.offset, end: verticalAnchor.offset + verticalAnchor.size })) {
                    horizontalAnchor.mode = LayoutAnchorMode.AVOID;
                }
                left = layout(activeWindow.innerWidth, viewSizeWidth, horizontalAnchor);
            }
            else {
                const horizontalAnchor = { offset: around.left, size: around.width, position: anchorAlignment === 0 /* AnchorAlignment.LEFT */ ? 0 /* LayoutAnchorPosition.Before */ : 1 /* LayoutAnchorPosition.After */ };
                const verticalAnchor = { offset: around.top, size: around.height, position: anchorPosition === 0 /* AnchorPosition.BELOW */ ? 0 /* LayoutAnchorPosition.Before */ : 1 /* LayoutAnchorPosition.After */, mode: LayoutAnchorMode.ALIGN };
                left = layout(activeWindow.innerWidth, viewSizeWidth, horizontalAnchor);
                // if view intersects horizontally with anchor, we must avoid the anchor
                if (range_1.Range.intersects({ start: left, end: left + viewSizeWidth }, { start: horizontalAnchor.offset, end: horizontalAnchor.offset + horizontalAnchor.size })) {
                    verticalAnchor.mode = LayoutAnchorMode.AVOID;
                }
                top = layout(activeWindow.innerHeight, viewSizeHeight, verticalAnchor) + activeWindow.pageYOffset;
            }
            this.view.classList.remove('top', 'bottom', 'left', 'right');
            this.view.classList.add(anchorPosition === 0 /* AnchorPosition.BELOW */ ? 'bottom' : 'top');
            this.view.classList.add(anchorAlignment === 0 /* AnchorAlignment.LEFT */ ? 'left' : 'right');
            this.view.classList.toggle('fixed', this.useFixedPosition);
            const containerPosition = DOM.getDomNodePagePosition(this.container);
            this.view.style.top = `${top - (this.useFixedPosition ? DOM.getDomNodePagePosition(this.view).top : containerPosition.top)}px`;
            this.view.style.left = `${left - (this.useFixedPosition ? DOM.getDomNodePagePosition(this.view).left : containerPosition.left)}px`;
            this.view.style.width = 'initial';
        }
        hide(data) {
            const delegate = this.delegate;
            this.delegate = null;
            if (delegate?.onHide) {
                delegate.onHide(data);
            }
            this.toDisposeOnClean.dispose();
            DOM.hide(this.view);
        }
        isVisible() {
            return !!this.delegate;
        }
        onDOMEvent(e, onCapture) {
            if (this.delegate) {
                if (this.delegate.onDOMEvent) {
                    this.delegate.onDOMEvent(e, DOM.getWindow(e).document.activeElement);
                }
                else if (onCapture && !DOM.isAncestor(e.target, this.container)) {
                    this.hide();
                }
            }
        }
        dispose() {
            this.hide();
            super.dispose();
        }
    }
    exports.ContextView = ContextView;
    const SHADOW_ROOT_CSS = /* css */ `
	:host {
		all: initial; /* 1st rule so subsequent properties are reset. */
	}

	.codicon[class*='codicon-'] {
		font: normal normal normal 16px/1 codicon;
		display: inline-block;
		text-decoration: none;
		text-rendering: auto;
		text-align: center;
		-webkit-font-smoothing: antialiased;
		-moz-osx-font-smoothing: grayscale;
		user-select: none;
		-webkit-user-select: none;
		-ms-user-select: none;
	}

	:host {
		font-family: -apple-system, BlinkMacSystemFont, "Segoe WPC", "Segoe UI", "HelveticaNeue-Light", system-ui, "Ubuntu", "Droid Sans", sans-serif;
	}

	:host-context(.mac) { font-family: -apple-system, BlinkMacSystemFont, sans-serif; }
	:host-context(.mac:lang(zh-Hans)) { font-family: -apple-system, BlinkMacSystemFont, "PingFang SC", "Hiragino Sans GB", sans-serif; }
	:host-context(.mac:lang(zh-Hant)) { font-family: -apple-system, BlinkMacSystemFont, "PingFang TC", sans-serif; }
	:host-context(.mac:lang(ja)) { font-family: -apple-system, BlinkMacSystemFont, "Hiragino Kaku Gothic Pro", sans-serif; }
	:host-context(.mac:lang(ko)) { font-family: -apple-system, BlinkMacSystemFont, "Nanum Gothic", "Apple SD Gothic Neo", "AppleGothic", sans-serif; }

	:host-context(.windows) { font-family: "Segoe WPC", "Segoe UI", sans-serif; }
	:host-context(.windows:lang(zh-Hans)) { font-family: "Segoe WPC", "Segoe UI", "Microsoft YaHei", sans-serif; }
	:host-context(.windows:lang(zh-Hant)) { font-family: "Segoe WPC", "Segoe UI", "Microsoft Jhenghei", sans-serif; }
	:host-context(.windows:lang(ja)) { font-family: "Segoe WPC", "Segoe UI", "Yu Gothic UI", "Meiryo UI", sans-serif; }
	:host-context(.windows:lang(ko)) { font-family: "Segoe WPC", "Segoe UI", "Malgun Gothic", "Dotom", sans-serif; }

	:host-context(.linux) { font-family: system-ui, "Ubuntu", "Droid Sans", sans-serif; }
	:host-context(.linux:lang(zh-Hans)) { font-family: system-ui, "Ubuntu", "Droid Sans", "Source Han Sans SC", "Source Han Sans CN", "Source Han Sans", sans-serif; }
	:host-context(.linux:lang(zh-Hant)) { font-family: system-ui, "Ubuntu", "Droid Sans", "Source Han Sans TC", "Source Han Sans TW", "Source Han Sans", sans-serif; }
	:host-context(.linux:lang(ja)) { font-family: system-ui, "Ubuntu", "Droid Sans", "Source Han Sans J", "Source Han Sans JP", "Source Han Sans", sans-serif; }
	:host-context(.linux:lang(ko)) { font-family: system-ui, "Ubuntu", "Droid Sans", "Source Han Sans K", "Source Han Sans JR", "Source Han Sans", "UnDotum", "FBaekmuk Gulim", sans-serif; }
`;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[354/*vs/base/browser/ui/countBadge/countBadge*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,11/*vs/base/common/strings*/,463/*vs/css!vs/base/browser/ui/countBadge/countBadge*/]), function (require, exports, dom_1, strings_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CountBadge = void 0;
    class CountBadge {
        constructor(container, options, styles) {
            this.options = options;
            this.styles = styles;
            this.count = 0;
            this.element = (0, dom_1.append)(container, (0, dom_1.$)('.monaco-count-badge'));
            this.countFormat = this.options.countFormat || '{0}';
            this.titleFormat = this.options.titleFormat || '';
            this.setCount(this.options.count || 0);
        }
        setCount(count) {
            this.count = count;
            this.render();
        }
        setTitleFormat(titleFormat) {
            this.titleFormat = titleFormat;
            this.render();
        }
        render() {
            this.element.textContent = (0, strings_1.format)(this.countFormat, this.count);
            this.element.title = (0, strings_1.format)(this.titleFormat, this.count);
            this.element.style.backgroundColor = this.styles.badgeBackground ?? '';
            this.element.style.color = this.styles.badgeForeground ?? '';
            if (this.styles.badgeBorder) {
                this.element.style.border = `1px solid ${this.styles.badgeBorder}`;
            }
        }
    }
    exports.CountBadge = CountBadge;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[631/*vs/base/browser/ui/dropdown/dropdown*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,47/*vs/base/browser/keyboardEvent*/,69/*vs/base/browser/touch*/,41/*vs/base/common/actions*/,6/*vs/base/common/event*/,303/*vs/css!vs/base/browser/ui/dropdown/dropdown*/]), function (require, exports, dom_1, keyboardEvent_1, touch_1, actions_1, event_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DropdownMenu = void 0;
    class BaseDropdown extends actions_1.ActionRunner {
        constructor(container, options) {
            super();
            this._onDidChangeVisibility = this._register(new event_1.Emitter());
            this.onDidChangeVisibility = this._onDidChangeVisibility.event;
            this._element = (0, dom_1.append)(container, (0, dom_1.$)('.monaco-dropdown'));
            this._label = (0, dom_1.append)(this._element, (0, dom_1.$)('.dropdown-label'));
            let labelRenderer = options.labelRenderer;
            if (!labelRenderer) {
                labelRenderer = (container) => {
                    container.textContent = options.label || '';
                    return null;
                };
            }
            for (const event of [dom_1.EventType.CLICK, dom_1.EventType.MOUSE_DOWN, touch_1.EventType.Tap]) {
                this._register((0, dom_1.addDisposableListener)(this.element, event, e => dom_1.EventHelper.stop(e, true))); // prevent default click behaviour to trigger
            }
            for (const event of [dom_1.EventType.MOUSE_DOWN, touch_1.EventType.Tap]) {
                this._register((0, dom_1.addDisposableListener)(this._label, event, e => {
                    if ((0, dom_1.isMouseEvent)(e) && (e.detail > 1 || e.button !== 0)) {
                        // prevent right click trigger to allow separate context menu (https://github.com/microsoft/vscode/issues/151064)
                        // prevent multiple clicks to open multiple context menus (https://github.com/microsoft/vscode/issues/41363)
                        return;
                    }
                    if (this.visible) {
                        this.hide();
                    }
                    else {
                        this.show();
                    }
                }));
            }
            this._register((0, dom_1.addDisposableListener)(this._label, dom_1.EventType.KEY_UP, e => {
                const event = new keyboardEvent_1.StandardKeyboardEvent(e);
                if (event.equals(3 /* KeyCode.Enter */) || event.equals(10 /* KeyCode.Space */)) {
                    dom_1.EventHelper.stop(e, true); // https://github.com/microsoft/vscode/issues/57997
                    if (this.visible) {
                        this.hide();
                    }
                    else {
                        this.show();
                    }
                }
            }));
            const cleanupFn = labelRenderer(this._label);
            if (cleanupFn) {
                this._register(cleanupFn);
            }
            this._register(touch_1.Gesture.addTarget(this._label));
        }
        get element() {
            return this._element;
        }
        show() {
            if (!this.visible) {
                this.visible = true;
                this._onDidChangeVisibility.fire(true);
            }
        }
        hide() {
            if (this.visible) {
                this.visible = false;
                this._onDidChangeVisibility.fire(false);
            }
        }
        dispose() {
            super.dispose();
            this.hide();
            if (this.boxContainer) {
                this.boxContainer.remove();
                this.boxContainer = undefined;
            }
            if (this.contents) {
                this.contents.remove();
                this.contents = undefined;
            }
            if (this._label) {
                this._label.remove();
                this._label = undefined;
            }
        }
    }
    class DropdownMenu extends BaseDropdown {
        constructor(container, _options) {
            super(container, _options);
            this._options = _options;
            this._actions = [];
            this.actions = _options.actions || [];
        }
        set menuOptions(options) {
            this._menuOptions = options;
        }
        get menuOptions() {
            return this._menuOptions;
        }
        get actions() {
            if (this._options.actionProvider) {
                return this._options.actionProvider.getActions();
            }
            return this._actions;
        }
        set actions(actions) {
            this._actions = actions;
        }
        show() {
            super.show();
            this.element.classList.add('active');
            this._options.contextMenuProvider.showContextMenu({
                getAnchor: () => this.element,
                getActions: () => this.actions,
                getActionsContext: () => this.menuOptions ? this.menuOptions.context : null,
                getActionViewItem: (action, options) => this.menuOptions && this.menuOptions.actionViewItemProvider ? this.menuOptions.actionViewItemProvider(action, options) : undefined,
                getKeyBinding: action => this.menuOptions && this.menuOptions.getKeyBinding ? this.menuOptions.getKeyBinding(action) : undefined,
                getMenuClassName: () => this._options.menuClassName || '',
                onHide: () => this.onHide(),
                actionRunner: this.menuOptions ? this.menuOptions.actionRunner : undefined,
                anchorAlignment: this.menuOptions ? this.menuOptions.anchorAlignment : 0 /* AnchorAlignment.LEFT */,
                domForShadowRoot: this._options.menuAsChild ? this.element : undefined,
                skipTelemetry: this._options.skipTelemetry
            });
        }
        hide() {
            super.hide();
        }
        onHide() {
            this.hide();
            this.element.classList.remove('active');
        }
    }
    exports.DropdownMenu = DropdownMenu;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[114/*vs/base/browser/ui/iconLabel/iconLabels*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,30/*vs/base/common/themables*/]), function (require, exports, dom, themables_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.renderLabelWithIcons = renderLabelWithIcons;
    exports.renderIcon = renderIcon;
    const labelWithIconsRegex = new RegExp(`(\\\\)?\\$\\((${themables_1.ThemeIcon.iconNameExpression}(?:${themables_1.ThemeIcon.iconModifierExpression})?)\\)`, 'g');
    function renderLabelWithIcons(text) {
        const elements = new Array();
        let match;
        let textStart = 0, textStop = 0;
        while ((match = labelWithIconsRegex.exec(text)) !== null) {
            textStop = match.index || 0;
            if (textStart < textStop) {
                elements.push(text.substring(textStart, textStop));
            }
            textStart = (match.index || 0) + match[0].length;
            const [, escaped, codicon] = match;
            elements.push(escaped ? `$(${codicon})` : renderIcon({ id: codicon }));
        }
        if (textStart < text.length) {
            elements.push(text.substring(textStart));
        }
        return elements;
    }
    function renderIcon(icon) {
        const node = dom.$(`span`);
        node.classList.add(...themables_1.ThemeIcon.asClassNameArray(icon));
        return node;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[355/*vs/base/browser/ui/highlightedlabel/highlightedLabel*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,81/*vs/base/browser/ui/hover/hoverDelegate2*/,44/*vs/base/browser/ui/hover/hoverDelegateFactory*/,114/*vs/base/browser/ui/iconLabel/iconLabels*/,2/*vs/base/common/lifecycle*/,60/*vs/base/common/objects*/]), function (require, exports, dom, hoverDelegate2_1, hoverDelegateFactory_1, iconLabels_1, lifecycle_1, objects) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.HighlightedLabel = void 0;
    /**
     * A widget which can render a label with substring highlights, often
     * originating from a filter function like the fuzzy matcher.
     */
    class HighlightedLabel extends lifecycle_1.Disposable {
        /**
         * Create a new {@link HighlightedLabel}.
         *
         * @param container The parent container to append to.
         */
        constructor(container, options) {
            super();
            this.options = options;
            this.text = '';
            this.title = '';
            this.highlights = [];
            this.didEverRender = false;
            this.supportIcons = options?.supportIcons ?? false;
            this.domNode = dom.append(container, dom.$('span.monaco-highlighted-label'));
        }
        /**
         * The label's DOM node.
         */
        get element() {
            return this.domNode;
        }
        /**
         * Set the label and highlights.
         *
         * @param text The label to display.
         * @param highlights The ranges to highlight.
         * @param title An optional title for the hover tooltip.
         * @param escapeNewLines Whether to escape new lines.
         * @returns
         */
        set(text, highlights = [], title = '', escapeNewLines) {
            if (!text) {
                text = '';
            }
            if (escapeNewLines) {
                // adjusts highlights inplace
                text = HighlightedLabel.escapeNewLines(text, highlights);
            }
            if (this.didEverRender && this.text === text && this.title === title && objects.equals(this.highlights, highlights)) {
                return;
            }
            this.text = text;
            this.title = title;
            this.highlights = highlights;
            this.render();
        }
        render() {
            const children = [];
            let pos = 0;
            for (const highlight of this.highlights) {
                if (highlight.end === highlight.start) {
                    continue;
                }
                if (pos < highlight.start) {
                    const substring = this.text.substring(pos, highlight.start);
                    if (this.supportIcons) {
                        children.push(...(0, iconLabels_1.renderLabelWithIcons)(substring));
                    }
                    else {
                        children.push(substring);
                    }
                    pos = highlight.start;
                }
                const substring = this.text.substring(pos, highlight.end);
                const element = dom.$('span.highlight', undefined, ...this.supportIcons ? (0, iconLabels_1.renderLabelWithIcons)(substring) : [substring]);
                if (highlight.extraClasses) {
                    element.classList.add(...highlight.extraClasses);
                }
                children.push(element);
                pos = highlight.end;
            }
            if (pos < this.text.length) {
                const substring = this.text.substring(pos);
                if (this.supportIcons) {
                    children.push(...(0, iconLabels_1.renderLabelWithIcons)(substring));
                }
                else {
                    children.push(substring);
                }
            }
            dom.reset(this.domNode, ...children);
            if (this.options?.hoverDelegate?.showNativeHover) {
                /* While custom hover is not inside custom hover */
                this.domNode.title = this.title;
            }
            else {
                if (!this.customHover && this.title !== '') {
                    const hoverDelegate = this.options?.hoverDelegate ?? (0, hoverDelegateFactory_1.getDefaultHoverDelegate)('mouse');
                    this.customHover = this._register((0, hoverDelegate2_1.getBaseLayerHoverDelegate)().setupManagedHover(hoverDelegate, this.domNode, this.title));
                }
                else if (this.customHover) {
                    this.customHover.update(this.title);
                }
            }
            this.didEverRender = true;
        }
        static escapeNewLines(text, highlights) {
            let total = 0;
            let extra = 0;
            return text.replace(/\r\n|\r|\n/g, (match, offset) => {
                extra = match === '\r\n' ? -1 : 0;
                offset += total;
                for (const highlight of highlights) {
                    if (highlight.end <= offset) {
                        continue;
                    }
                    if (highlight.start >= offset) {
                        highlight.start += extra;
                    }
                    if (highlight.end >= offset) {
                        highlight.end += extra;
                    }
                }
                total += extra;
                return '\u23CE';
            });
        }
    }
    exports.HighlightedLabel = HighlightedLabel;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[254/*vs/base/browser/ui/iconLabel/iconLabel*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,355/*vs/base/browser/ui/highlightedlabel/highlightedLabel*/,2/*vs/base/common/lifecycle*/,60/*vs/base/common/objects*/,188/*vs/base/common/range*/,44/*vs/base/browser/ui/hover/hoverDelegateFactory*/,81/*vs/base/browser/ui/hover/hoverDelegate2*/,19/*vs/base/common/types*/,142/*vs/base/common/iconLabels*/,465/*vs/css!vs/base/browser/ui/iconLabel/iconlabel*/]), function (require, exports, dom, highlightedLabel_1, lifecycle_1, objects_1, range_1, hoverDelegateFactory_1, hoverDelegate2_1, types_1, iconLabels_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.IconLabel = void 0;
    class FastLabelNode {
        constructor(_element) {
            this._element = _element;
        }
        get element() {
            return this._element;
        }
        set textContent(content) {
            if (this.disposed || content === this._textContent) {
                return;
            }
            this._textContent = content;
            this._element.textContent = content;
        }
        set classNames(classNames) {
            if (this.disposed || (0, objects_1.equals)(classNames, this._classNames)) {
                return;
            }
            this._classNames = classNames;
            this._element.classList.value = '';
            this._element.classList.add(...classNames);
        }
        set empty(empty) {
            if (this.disposed || empty === this._empty) {
                return;
            }
            this._empty = empty;
            this._element.style.marginLeft = empty ? '0' : '';
        }
        dispose() {
            this.disposed = true;
        }
    }
    class IconLabel extends lifecycle_1.Disposable {
        constructor(container, options) {
            super();
            this.customHovers = new Map();
            this.creationOptions = options;
            this.domNode = this._register(new FastLabelNode(dom.append(container, dom.$('.monaco-icon-label'))));
            this.labelContainer = dom.append(this.domNode.element, dom.$('.monaco-icon-label-container'));
            this.nameContainer = dom.append(this.labelContainer, dom.$('span.monaco-icon-name-container'));
            if (options?.supportHighlights || options?.supportIcons) {
                this.nameNode = this._register(new LabelWithHighlights(this.nameContainer, !!options.supportIcons));
            }
            else {
                this.nameNode = new Label(this.nameContainer);
            }
            this.hoverDelegate = options?.hoverDelegate ?? (0, hoverDelegateFactory_1.getDefaultHoverDelegate)('mouse');
        }
        get element() {
            return this.domNode.element;
        }
        setLabel(label, description, options) {
            const labelClasses = ['monaco-icon-label'];
            const containerClasses = ['monaco-icon-label-container'];
            let ariaLabel = '';
            if (options) {
                if (options.extraClasses) {
                    labelClasses.push(...options.extraClasses);
                }
                if (options.italic) {
                    labelClasses.push('italic');
                }
                if (options.strikethrough) {
                    labelClasses.push('strikethrough');
                }
                if (options.disabledCommand) {
                    containerClasses.push('disabled');
                }
                if (options.title) {
                    if (typeof options.title === 'string') {
                        ariaLabel += options.title;
                    }
                    else {
                        ariaLabel += label;
                    }
                }
            }
            const existingIconNode = this.domNode.element.querySelector('.monaco-icon-label-iconpath');
            if (options?.iconPath) {
                let iconNode;
                if (!existingIconNode || !(dom.isHTMLElement(existingIconNode))) {
                    iconNode = dom.$('.monaco-icon-label-iconpath');
                    this.domNode.element.prepend(iconNode);
                }
                else {
                    iconNode = existingIconNode;
                }
                iconNode.style.backgroundImage = dom.asCSSUrl(options?.iconPath);
            }
            else if (existingIconNode) {
                existingIconNode.remove();
            }
            this.domNode.classNames = labelClasses;
            this.domNode.element.setAttribute('aria-label', ariaLabel);
            this.labelContainer.classList.value = '';
            this.labelContainer.classList.add(...containerClasses);
            this.setupHover(options?.descriptionTitle ? this.labelContainer : this.element, options?.title);
            this.nameNode.setLabel(label, options);
            if (description || this.descriptionNode) {
                const descriptionNode = this.getOrCreateDescriptionNode();
                if (descriptionNode instanceof highlightedLabel_1.HighlightedLabel) {
                    descriptionNode.set(description || '', options ? options.descriptionMatches : undefined, undefined, options?.labelEscapeNewLines);
                    this.setupHover(descriptionNode.element, options?.descriptionTitle);
                }
                else {
                    descriptionNode.textContent = description && options?.labelEscapeNewLines ? highlightedLabel_1.HighlightedLabel.escapeNewLines(description, []) : (description || '');
                    this.setupHover(descriptionNode.element, options?.descriptionTitle || '');
                    descriptionNode.empty = !description;
                }
            }
            if (options?.suffix || this.suffixNode) {
                const suffixNode = this.getOrCreateSuffixNode();
                suffixNode.textContent = options?.suffix ?? '';
            }
        }
        setupHover(htmlElement, tooltip) {
            const previousCustomHover = this.customHovers.get(htmlElement);
            if (previousCustomHover) {
                previousCustomHover.dispose();
                this.customHovers.delete(htmlElement);
            }
            if (!tooltip) {
                htmlElement.removeAttribute('title');
                return;
            }
            if (this.hoverDelegate.showNativeHover) {
                function setupNativeHover(htmlElement, tooltip) {
                    if ((0, types_1.isString)(tooltip)) {
                        // Icons don't render in the native hover so we strip them out
                        htmlElement.title = (0, iconLabels_1.stripIcons)(tooltip);
                    }
                    else if (tooltip?.markdownNotSupportedFallback) {
                        htmlElement.title = tooltip.markdownNotSupportedFallback;
                    }
                    else {
                        htmlElement.removeAttribute('title');
                    }
                }
                setupNativeHover(htmlElement, tooltip);
            }
            else {
                const hoverDisposable = (0, hoverDelegate2_1.getBaseLayerHoverDelegate)().setupManagedHover(this.hoverDelegate, htmlElement, tooltip);
                if (hoverDisposable) {
                    this.customHovers.set(htmlElement, hoverDisposable);
                }
            }
        }
        dispose() {
            super.dispose();
            for (const disposable of this.customHovers.values()) {
                disposable.dispose();
            }
            this.customHovers.clear();
        }
        getOrCreateSuffixNode() {
            if (!this.suffixNode) {
                const suffixContainer = this._register(new FastLabelNode(dom.after(this.nameContainer, dom.$('span.monaco-icon-suffix-container'))));
                this.suffixNode = this._register(new FastLabelNode(dom.append(suffixContainer.element, dom.$('span.label-suffix'))));
            }
            return this.suffixNode;
        }
        getOrCreateDescriptionNode() {
            if (!this.descriptionNode) {
                const descriptionContainer = this._register(new FastLabelNode(dom.append(this.labelContainer, dom.$('span.monaco-icon-description-container'))));
                if (this.creationOptions?.supportDescriptionHighlights) {
                    this.descriptionNode = this._register(new highlightedLabel_1.HighlightedLabel(dom.append(descriptionContainer.element, dom.$('span.label-description')), { supportIcons: !!this.creationOptions.supportIcons }));
                }
                else {
                    this.descriptionNode = this._register(new FastLabelNode(dom.append(descriptionContainer.element, dom.$('span.label-description'))));
                }
            }
            return this.descriptionNode;
        }
    }
    exports.IconLabel = IconLabel;
    class Label {
        constructor(container) {
            this.container = container;
            this.label = undefined;
            this.singleLabel = undefined;
        }
        setLabel(label, options) {
            if (this.label === label && (0, objects_1.equals)(this.options, options)) {
                return;
            }
            this.label = label;
            this.options = options;
            if (typeof label === 'string') {
                if (!this.singleLabel) {
                    this.container.innerText = '';
                    this.container.classList.remove('multiple');
                    this.singleLabel = dom.append(this.container, dom.$('a.label-name', { id: options?.domId }));
                }
                this.singleLabel.textContent = label;
            }
            else {
                this.container.innerText = '';
                this.container.classList.add('multiple');
                this.singleLabel = undefined;
                for (let i = 0; i < label.length; i++) {
                    const l = label[i];
                    const id = options?.domId && `${options?.domId}_${i}`;
                    dom.append(this.container, dom.$('a.label-name', { id, 'data-icon-label-count': label.length, 'data-icon-label-index': i, 'role': 'treeitem' }, l));
                    if (i < label.length - 1) {
                        dom.append(this.container, dom.$('span.label-separator', undefined, options?.separator || '/'));
                    }
                }
            }
        }
    }
    function splitMatches(labels, separator, matches) {
        if (!matches) {
            return undefined;
        }
        let labelStart = 0;
        return labels.map(label => {
            const labelRange = { start: labelStart, end: labelStart + label.length };
            const result = matches
                .map(match => range_1.Range.intersect(labelRange, match))
                .filter(range => !range_1.Range.isEmpty(range))
                .map(({ start, end }) => ({ start: start - labelStart, end: end - labelStart }));
            labelStart = labelRange.end + separator.length;
            return result;
        });
    }
    class LabelWithHighlights extends lifecycle_1.Disposable {
        constructor(container, supportIcons) {
            super();
            this.container = container;
            this.supportIcons = supportIcons;
            this.label = undefined;
            this.singleLabel = undefined;
        }
        setLabel(label, options) {
            if (this.label === label && (0, objects_1.equals)(this.options, options)) {
                return;
            }
            this.label = label;
            this.options = options;
            if (typeof label === 'string') {
                if (!this.singleLabel) {
                    this.container.innerText = '';
                    this.container.classList.remove('multiple');
                    this.singleLabel = this._register(new highlightedLabel_1.HighlightedLabel(dom.append(this.container, dom.$('a.label-name', { id: options?.domId })), { supportIcons: this.supportIcons }));
                }
                this.singleLabel.set(label, options?.matches, undefined, options?.labelEscapeNewLines);
            }
            else {
                this.container.innerText = '';
                this.container.classList.add('multiple');
                this.singleLabel = undefined;
                const separator = options?.separator || '/';
                const matches = splitMatches(label, separator, options?.matches);
                for (let i = 0; i < label.length; i++) {
                    const l = label[i];
                    const m = matches ? matches[i] : undefined;
                    const id = options?.domId && `${options?.domId}_${i}`;
                    const name = dom.$('a.label-name', { id, 'data-icon-label-count': label.length, 'data-icon-label-index': i, 'role': 'treeitem' });
                    const highlightedLabel = this._register(new highlightedLabel_1.HighlightedLabel(dom.append(this.container, name), { supportIcons: this.supportIcons }));
                    highlightedLabel.set(l, m, undefined, options?.labelEscapeNewLines);
                    if (i < label.length - 1) {
                        dom.append(name, dom.$('span.label-separator', undefined, separator));
                    }
                }
            }
        }
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[206/*vs/base/browser/ui/keybindingLabel/keybindingLabel*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,81/*vs/base/browser/ui/hover/hoverDelegate2*/,44/*vs/base/browser/ui/hover/hoverDelegateFactory*/,247/*vs/base/common/keybindingLabels*/,2/*vs/base/common/lifecycle*/,60/*vs/base/common/objects*/,3/*vs/nls*/,467/*vs/css!vs/base/browser/ui/keybindingLabel/keybindingLabel*/]), function (require, exports, dom, hoverDelegate2_1, hoverDelegateFactory_1, keybindingLabels_1, lifecycle_1, objects_1, nls_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.KeybindingLabel = exports.unthemedKeybindingLabelOptions = void 0;
    const $ = dom.$;
    exports.unthemedKeybindingLabelOptions = {
        keybindingLabelBackground: undefined,
        keybindingLabelForeground: undefined,
        keybindingLabelBorder: undefined,
        keybindingLabelBottomBorder: undefined,
        keybindingLabelShadow: undefined
    };
    class KeybindingLabel extends lifecycle_1.Disposable {
        constructor(container, os, options) {
            super();
            this.os = os;
            this.keyElements = new Set();
            this.options = options || Object.create(null);
            const labelForeground = this.options.keybindingLabelForeground;
            this.domNode = dom.append(container, $('.monaco-keybinding'));
            if (labelForeground) {
                this.domNode.style.color = labelForeground;
            }
            this.hover = this._register((0, hoverDelegate2_1.getBaseLayerHoverDelegate)().setupManagedHover((0, hoverDelegateFactory_1.getDefaultHoverDelegate)('mouse'), this.domNode, ''));
            this.didEverRender = false;
            container.appendChild(this.domNode);
        }
        get element() {
            return this.domNode;
        }
        set(keybinding, matches) {
            if (this.didEverRender && this.keybinding === keybinding && KeybindingLabel.areSame(this.matches, matches)) {
                return;
            }
            this.keybinding = keybinding;
            this.matches = matches;
            this.render();
        }
        render() {
            this.clear();
            if (this.keybinding) {
                const chords = this.keybinding.getChords();
                if (chords[0]) {
                    this.renderChord(this.domNode, chords[0], this.matches ? this.matches.firstPart : null);
                }
                for (let i = 1; i < chords.length; i++) {
                    dom.append(this.domNode, $('span.monaco-keybinding-key-chord-separator', undefined, ' '));
                    this.renderChord(this.domNode, chords[i], this.matches ? this.matches.chordPart : null);
                }
                const title = (this.options.disableTitle ?? false) ? undefined : this.keybinding.getAriaLabel() || undefined;
                this.hover.update(title);
                this.domNode.setAttribute('aria-label', title || '');
            }
            else if (this.options && this.options.renderUnboundKeybindings) {
                this.renderUnbound(this.domNode);
            }
            this.didEverRender = true;
        }
        clear() {
            dom.clearNode(this.domNode);
            this.keyElements.clear();
        }
        renderChord(parent, chord, match) {
            const modifierLabels = keybindingLabels_1.UILabelProvider.modifierLabels[this.os];
            if (chord.ctrlKey) {
                this.renderKey(parent, modifierLabels.ctrlKey, Boolean(match?.ctrlKey), modifierLabels.separator);
            }
            if (chord.shiftKey) {
                this.renderKey(parent, modifierLabels.shiftKey, Boolean(match?.shiftKey), modifierLabels.separator);
            }
            if (chord.altKey) {
                this.renderKey(parent, modifierLabels.altKey, Boolean(match?.altKey), modifierLabels.separator);
            }
            if (chord.metaKey) {
                this.renderKey(parent, modifierLabels.metaKey, Boolean(match?.metaKey), modifierLabels.separator);
            }
            const keyLabel = chord.keyLabel;
            if (keyLabel) {
                this.renderKey(parent, keyLabel, Boolean(match?.keyCode), '');
            }
        }
        renderKey(parent, label, highlight, separator) {
            dom.append(parent, this.createKeyElement(label, highlight ? '.highlight' : ''));
            if (separator) {
                dom.append(parent, $('span.monaco-keybinding-key-separator', undefined, separator));
            }
        }
        renderUnbound(parent) {
            dom.append(parent, this.createKeyElement((0, nls_1.localize)(15, "Unbound")));
        }
        createKeyElement(label, extraClass = '') {
            const keyElement = $('span.monaco-keybinding-key' + extraClass, undefined, label);
            this.keyElements.add(keyElement);
            if (this.options.keybindingLabelBackground) {
                keyElement.style.backgroundColor = this.options.keybindingLabelBackground;
            }
            if (this.options.keybindingLabelBorder) {
                keyElement.style.borderColor = this.options.keybindingLabelBorder;
            }
            if (this.options.keybindingLabelBottomBorder) {
                keyElement.style.borderBottomColor = this.options.keybindingLabelBottomBorder;
            }
            if (this.options.keybindingLabelShadow) {
                keyElement.style.boxShadow = `inset 0 -1px 0 ${this.options.keybindingLabelShadow}`;
            }
            return keyElement;
        }
        static areSame(a, b) {
            if (a === b || (!a && !b)) {
                return true;
            }
            return !!a && !!b && (0, objects_1.equals)(a.firstPart, b.firstPart) && (0, objects_1.equals)(a.chordPart, b.chordPart);
        }
    }
    exports.KeybindingLabel = KeybindingLabel;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[632/*vs/base/browser/ui/list/rowCache*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/]), function (require, exports, dom_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.RowCache = void 0;
    class RowCache {
        constructor(renderers) {
            this.renderers = renderers;
            this.cache = new Map();
            this.transactionNodesPendingRemoval = new Set();
            this.inTransaction = false;
        }
        /**
         * Returns a row either by creating a new one or reusing
         * a previously released row which shares the same templateId.
         *
         * @returns A row and `isReusingConnectedDomNode` if the row's node is already in the dom in a stale position.
         */
        alloc(templateId) {
            let result = this.getTemplateCache(templateId).pop();
            let isStale = false;
            if (result) {
                isStale = this.transactionNodesPendingRemoval.has(result.domNode);
                if (isStale) {
                    this.transactionNodesPendingRemoval.delete(result.domNode);
                }
            }
            else {
                const domNode = (0, dom_1.$)('.monaco-list-row');
                const renderer = this.getRenderer(templateId);
                const templateData = renderer.renderTemplate(domNode);
                result = { domNode, templateId, templateData };
            }
            return { row: result, isReusingConnectedDomNode: isStale };
        }
        /**
         * Releases the row for eventual reuse.
         */
        release(row) {
            if (!row) {
                return;
            }
            this.releaseRow(row);
        }
        /**
         * Begin a set of changes that use the cache. This lets us skip work when a row is removed and then inserted again.
         */
        transact(makeChanges) {
            if (this.inTransaction) {
                throw new Error('Already in transaction');
            }
            this.inTransaction = true;
            try {
                makeChanges();
            }
            finally {
                for (const domNode of this.transactionNodesPendingRemoval) {
                    this.doRemoveNode(domNode);
                }
                this.transactionNodesPendingRemoval.clear();
                this.inTransaction = false;
            }
        }
        releaseRow(row) {
            const { domNode, templateId } = row;
            if (domNode) {
                if (this.inTransaction) {
                    this.transactionNodesPendingRemoval.add(domNode);
                }
                else {
                    this.doRemoveNode(domNode);
                }
            }
            const cache = this.getTemplateCache(templateId);
            cache.push(row);
        }
        doRemoveNode(domNode) {
            domNode.classList.remove('scrolling');
            domNode.remove();
        }
        getTemplateCache(templateId) {
            let result = this.cache.get(templateId);
            if (!result) {
                result = [];
                this.cache.set(templateId, result);
            }
            return result;
        }
        dispose() {
            this.cache.forEach((cachedRows, templateId) => {
                for (const cachedRow of cachedRows) {
                    const renderer = this.getRenderer(templateId);
                    renderer.disposeTemplate(cachedRow.templateData);
                    cachedRow.templateData = null;
                }
            });
            this.cache.clear();
            this.transactionNodesPendingRemoval.clear();
        }
        getRenderer(templateId) {
            const renderer = this.renderers.get(templateId);
            if (!renderer) {
                throw new Error(`No renderer found for ${templateId}`);
            }
            return renderer;
        }
    }
    exports.RowCache = RowCache;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[633/*vs/base/browser/ui/progressbar/progressbar*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,14/*vs/base/common/async*/,2/*vs/base/common/lifecycle*/,469/*vs/css!vs/base/browser/ui/progressbar/progressbar*/]), function (require, exports, dom_1, async_1, lifecycle_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ProgressBar = void 0;
    const CSS_DONE = 'done';
    const CSS_ACTIVE = 'active';
    const CSS_INFINITE = 'infinite';
    const CSS_INFINITE_LONG_RUNNING = 'infinite-long-running';
    const CSS_DISCRETE = 'discrete';
    /**
     * A progress bar with support for infinite or discrete progress.
     */
    class ProgressBar extends lifecycle_1.Disposable {
        /**
         * After a certain time of showing the progress bar, switch
         * to long-running mode and throttle animations to reduce
         * the pressure on the GPU process.
         *
         * https://github.com/microsoft/vscode/issues/97900
         * https://github.com/microsoft/vscode/issues/138396
         */
        static { this.LONG_RUNNING_INFINITE_THRESHOLD = 10000; }
        constructor(container, options) {
            super();
            this.progressSignal = this._register(new lifecycle_1.MutableDisposable());
            this.workedVal = 0;
            this.showDelayedScheduler = this._register(new async_1.RunOnceScheduler(() => (0, dom_1.show)(this.element), 0));
            this.longRunningScheduler = this._register(new async_1.RunOnceScheduler(() => this.infiniteLongRunning(), ProgressBar.LONG_RUNNING_INFINITE_THRESHOLD));
            this.create(container, options);
        }
        create(container, options) {
            this.element = document.createElement('div');
            this.element.classList.add('monaco-progress-container');
            this.element.setAttribute('role', 'progressbar');
            this.element.setAttribute('aria-valuemin', '0');
            container.appendChild(this.element);
            this.bit = document.createElement('div');
            this.bit.classList.add('progress-bit');
            this.bit.style.backgroundColor = options?.progressBarBackground || '#0E70C0';
            this.element.appendChild(this.bit);
        }
        off() {
            this.bit.style.width = 'inherit';
            this.bit.style.opacity = '1';
            this.element.classList.remove(CSS_ACTIVE, CSS_INFINITE, CSS_INFINITE_LONG_RUNNING, CSS_DISCRETE);
            this.workedVal = 0;
            this.totalWork = undefined;
            this.longRunningScheduler.cancel();
            this.progressSignal.clear();
        }
        /**
         * Stops the progressbar from showing any progress instantly without fading out.
         */
        stop() {
            return this.doDone(false);
        }
        doDone(delayed) {
            this.element.classList.add(CSS_DONE);
            // discrete: let it grow to 100% width and hide afterwards
            if (!this.element.classList.contains(CSS_INFINITE)) {
                this.bit.style.width = 'inherit';
                if (delayed) {
                    setTimeout(() => this.off(), 200);
                }
                else {
                    this.off();
                }
            }
            // infinite: let it fade out and hide afterwards
            else {
                this.bit.style.opacity = '0';
                if (delayed) {
                    setTimeout(() => this.off(), 200);
                }
                else {
                    this.off();
                }
            }
            return this;
        }
        /**
         * Use this mode to indicate progress that has no total number of work units.
         */
        infinite() {
            this.bit.style.width = '2%';
            this.bit.style.opacity = '1';
            this.element.classList.remove(CSS_DISCRETE, CSS_DONE, CSS_INFINITE_LONG_RUNNING);
            this.element.classList.add(CSS_ACTIVE, CSS_INFINITE);
            this.longRunningScheduler.schedule();
            return this;
        }
        infiniteLongRunning() {
            this.element.classList.add(CSS_INFINITE_LONG_RUNNING);
        }
        getContainer() {
            return this.element;
        }
    }
    exports.ProgressBar = ProgressBar;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/






define(__m[173/*vs/base/browser/ui/sash/sash*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,93/*vs/base/browser/event*/,69/*vs/base/browser/touch*/,14/*vs/base/common/async*/,126/*vs/base/common/decorators*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,16/*vs/base/common/platform*/,470/*vs/css!vs/base/browser/ui/sash/sash*/]), function (require, exports, dom_1, event_1, touch_1, async_1, decorators_1, event_2, lifecycle_1, platform_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Sash = exports.OrthogonalEdge = void 0;
    /**
     * Allow the sashes to be visible at runtime.
     * @remark Use for development purposes only.
     */
    const DEBUG = false;
    var OrthogonalEdge;
    (function (OrthogonalEdge) {
        OrthogonalEdge["North"] = "north";
        OrthogonalEdge["South"] = "south";
        OrthogonalEdge["East"] = "east";
        OrthogonalEdge["West"] = "west";
    })(OrthogonalEdge || (exports.OrthogonalEdge = OrthogonalEdge = {}));
    let globalSize = 4;
    const onDidChangeGlobalSize = new event_2.Emitter();
    let globalHoverDelay = 300;
    const onDidChangeHoverDelay = new event_2.Emitter();
    class MouseEventFactory {
        constructor(el) {
            this.el = el;
            this.disposables = new lifecycle_1.DisposableStore();
        }
        get onPointerMove() {
            return this.disposables.add(new event_1.DomEmitter((0, dom_1.getWindow)(this.el), 'mousemove')).event;
        }
        get onPointerUp() {
            return this.disposables.add(new event_1.DomEmitter((0, dom_1.getWindow)(this.el), 'mouseup')).event;
        }
        dispose() {
            this.disposables.dispose();
        }
    }
    __decorate([
        decorators_1.memoize
    ], MouseEventFactory.prototype, "onPointerMove", null);
    __decorate([
        decorators_1.memoize
    ], MouseEventFactory.prototype, "onPointerUp", null);
    class GestureEventFactory {
        get onPointerMove() {
            return this.disposables.add(new event_1.DomEmitter(this.el, touch_1.EventType.Change)).event;
        }
        get onPointerUp() {
            return this.disposables.add(new event_1.DomEmitter(this.el, touch_1.EventType.End)).event;
        }
        constructor(el) {
            this.el = el;
            this.disposables = new lifecycle_1.DisposableStore();
        }
        dispose() {
            this.disposables.dispose();
        }
    }
    __decorate([
        decorators_1.memoize
    ], GestureEventFactory.prototype, "onPointerMove", null);
    __decorate([
        decorators_1.memoize
    ], GestureEventFactory.prototype, "onPointerUp", null);
    class OrthogonalPointerEventFactory {
        get onPointerMove() {
            return this.factory.onPointerMove;
        }
        get onPointerUp() {
            return this.factory.onPointerUp;
        }
        constructor(factory) {
            this.factory = factory;
        }
        dispose() {
            // noop
        }
    }
    __decorate([
        decorators_1.memoize
    ], OrthogonalPointerEventFactory.prototype, "onPointerMove", null);
    __decorate([
        decorators_1.memoize
    ], OrthogonalPointerEventFactory.prototype, "onPointerUp", null);
    const PointerEventsDisabledCssClass = 'pointer-events-disabled';
    /**
     * The {@link Sash} is the UI component which allows the user to resize other
     * components. It's usually an invisible horizontal or vertical line which, when
     * hovered, becomes highlighted and can be dragged along the perpendicular dimension
     * to its direction.
     *
     * Features:
     * - Touch event handling
     * - Corner sash support
     * - Hover with different mouse cursor support
     * - Configurable hover size
     * - Linked sash support, for 2x2 corner sashes
     */
    class Sash extends lifecycle_1.Disposable {
        get state() { return this._state; }
        get orthogonalStartSash() { return this._orthogonalStartSash; }
        get orthogonalEndSash() { return this._orthogonalEndSash; }
        /**
         * The state of a sash defines whether it can be interacted with by the user
         * as well as what mouse cursor to use, when hovered.
         */
        set state(state) {
            if (this._state === state) {
                return;
            }
            this.el.classList.toggle('disabled', state === 0 /* SashState.Disabled */);
            this.el.classList.toggle('minimum', state === 1 /* SashState.AtMinimum */);
            this.el.classList.toggle('maximum', state === 2 /* SashState.AtMaximum */);
            this._state = state;
            this.onDidEnablementChange.fire(state);
        }
        /**
         * A reference to another sash, perpendicular to this one, which
         * aligns at the start of this one. A corner sash will be created
         * automatically at that location.
         *
         * The start of a horizontal sash is its left-most position.
         * The start of a vertical sash is its top-most position.
         */
        set orthogonalStartSash(sash) {
            if (this._orthogonalStartSash === sash) {
                return;
            }
            this.orthogonalStartDragHandleDisposables.clear();
            this.orthogonalStartSashDisposables.clear();
            if (sash) {
                const onChange = (state) => {
                    this.orthogonalStartDragHandleDisposables.clear();
                    if (state !== 0 /* SashState.Disabled */) {
                        this._orthogonalStartDragHandle = (0, dom_1.append)(this.el, (0, dom_1.$)('.orthogonal-drag-handle.start'));
                        this.orthogonalStartDragHandleDisposables.add((0, lifecycle_1.toDisposable)(() => this._orthogonalStartDragHandle.remove()));
                        this.orthogonalStartDragHandleDisposables.add(new event_1.DomEmitter(this._orthogonalStartDragHandle, 'mouseenter')).event(() => Sash.onMouseEnter(sash), undefined, this.orthogonalStartDragHandleDisposables);
                        this.orthogonalStartDragHandleDisposables.add(new event_1.DomEmitter(this._orthogonalStartDragHandle, 'mouseleave')).event(() => Sash.onMouseLeave(sash), undefined, this.orthogonalStartDragHandleDisposables);
                    }
                };
                this.orthogonalStartSashDisposables.add(sash.onDidEnablementChange.event(onChange, this));
                onChange(sash.state);
            }
            this._orthogonalStartSash = sash;
        }
        /**
         * A reference to another sash, perpendicular to this one, which
         * aligns at the end of this one. A corner sash will be created
         * automatically at that location.
         *
         * The end of a horizontal sash is its right-most position.
         * The end of a vertical sash is its bottom-most position.
         */
        set orthogonalEndSash(sash) {
            if (this._orthogonalEndSash === sash) {
                return;
            }
            this.orthogonalEndDragHandleDisposables.clear();
            this.orthogonalEndSashDisposables.clear();
            if (sash) {
                const onChange = (state) => {
                    this.orthogonalEndDragHandleDisposables.clear();
                    if (state !== 0 /* SashState.Disabled */) {
                        this._orthogonalEndDragHandle = (0, dom_1.append)(this.el, (0, dom_1.$)('.orthogonal-drag-handle.end'));
                        this.orthogonalEndDragHandleDisposables.add((0, lifecycle_1.toDisposable)(() => this._orthogonalEndDragHandle.remove()));
                        this.orthogonalEndDragHandleDisposables.add(new event_1.DomEmitter(this._orthogonalEndDragHandle, 'mouseenter')).event(() => Sash.onMouseEnter(sash), undefined, this.orthogonalEndDragHandleDisposables);
                        this.orthogonalEndDragHandleDisposables.add(new event_1.DomEmitter(this._orthogonalEndDragHandle, 'mouseleave')).event(() => Sash.onMouseLeave(sash), undefined, this.orthogonalEndDragHandleDisposables);
                    }
                };
                this.orthogonalEndSashDisposables.add(sash.onDidEnablementChange.event(onChange, this));
                onChange(sash.state);
            }
            this._orthogonalEndSash = sash;
        }
        constructor(container, layoutProvider, options) {
            super();
            this.hoverDelay = globalHoverDelay;
            this.hoverDelayer = this._register(new async_1.Delayer(this.hoverDelay));
            this._state = 3 /* SashState.Enabled */;
            this.onDidEnablementChange = this._register(new event_2.Emitter());
            this._onDidStart = this._register(new event_2.Emitter());
            this._onDidChange = this._register(new event_2.Emitter());
            this._onDidReset = this._register(new event_2.Emitter());
            this._onDidEnd = this._register(new event_2.Emitter());
            this.orthogonalStartSashDisposables = this._register(new lifecycle_1.DisposableStore());
            this.orthogonalStartDragHandleDisposables = this._register(new lifecycle_1.DisposableStore());
            this.orthogonalEndSashDisposables = this._register(new lifecycle_1.DisposableStore());
            this.orthogonalEndDragHandleDisposables = this._register(new lifecycle_1.DisposableStore());
            /**
             * An event which fires whenever the user starts dragging this sash.
             */
            this.onDidStart = this._onDidStart.event;
            /**
             * An event which fires whenever the user moves the mouse while
             * dragging this sash.
             */
            this.onDidChange = this._onDidChange.event;
            /**
             * An event which fires whenever the user double clicks this sash.
             */
            this.onDidReset = this._onDidReset.event;
            /**
             * An event which fires whenever the user stops dragging this sash.
             */
            this.onDidEnd = this._onDidEnd.event;
            /**
             * A linked sash will be forwarded the same user interactions and events
             * so it moves exactly the same way as this sash.
             *
             * Useful in 2x2 grids. Not meant for widespread usage.
             */
            this.linkedSash = undefined;
            this.el = (0, dom_1.append)(container, (0, dom_1.$)('.monaco-sash'));
            if (options.orthogonalEdge) {
                this.el.classList.add(`orthogonal-edge-${options.orthogonalEdge}`);
            }
            if (platform_1.isMacintosh) {
                this.el.classList.add('mac');
            }
            const onMouseDown = this._register(new event_1.DomEmitter(this.el, 'mousedown')).event;
            this._register(onMouseDown(e => this.onPointerStart(e, new MouseEventFactory(container)), this));
            const onMouseDoubleClick = this._register(new event_1.DomEmitter(this.el, 'dblclick')).event;
            this._register(onMouseDoubleClick(this.onPointerDoublePress, this));
            const onMouseEnter = this._register(new event_1.DomEmitter(this.el, 'mouseenter')).event;
            this._register(onMouseEnter(() => Sash.onMouseEnter(this)));
            const onMouseLeave = this._register(new event_1.DomEmitter(this.el, 'mouseleave')).event;
            this._register(onMouseLeave(() => Sash.onMouseLeave(this)));
            this._register(touch_1.Gesture.addTarget(this.el));
            const onTouchStart = this._register(new event_1.DomEmitter(this.el, touch_1.EventType.Start)).event;
            this._register(onTouchStart(e => this.onPointerStart(e, new GestureEventFactory(this.el)), this));
            const onTap = this._register(new event_1.DomEmitter(this.el, touch_1.EventType.Tap)).event;
            let doubleTapTimeout = undefined;
            this._register(onTap(event => {
                if (doubleTapTimeout) {
                    clearTimeout(doubleTapTimeout);
                    doubleTapTimeout = undefined;
                    this.onPointerDoublePress(event);
                    return;
                }
                clearTimeout(doubleTapTimeout);
                doubleTapTimeout = setTimeout(() => doubleTapTimeout = undefined, 250);
            }, this));
            if (typeof options.size === 'number') {
                this.size = options.size;
                if (options.orientation === 0 /* Orientation.VERTICAL */) {
                    this.el.style.width = `${this.size}px`;
                }
                else {
                    this.el.style.height = `${this.size}px`;
                }
            }
            else {
                this.size = globalSize;
                this._register(onDidChangeGlobalSize.event(size => {
                    this.size = size;
                    this.layout();
                }));
            }
            this._register(onDidChangeHoverDelay.event(delay => this.hoverDelay = delay));
            this.layoutProvider = layoutProvider;
            this.orthogonalStartSash = options.orthogonalStartSash;
            this.orthogonalEndSash = options.orthogonalEndSash;
            this.orientation = options.orientation || 0 /* Orientation.VERTICAL */;
            if (this.orientation === 1 /* Orientation.HORIZONTAL */) {
                this.el.classList.add('horizontal');
                this.el.classList.remove('vertical');
            }
            else {
                this.el.classList.remove('horizontal');
                this.el.classList.add('vertical');
            }
            this.el.classList.toggle('debug', DEBUG);
            this.layout();
        }
        onPointerStart(event, pointerEventFactory) {
            dom_1.EventHelper.stop(event);
            let isMultisashResize = false;
            if (!event.__orthogonalSashEvent) {
                const orthogonalSash = this.getOrthogonalSash(event);
                if (orthogonalSash) {
                    isMultisashResize = true;
                    event.__orthogonalSashEvent = true;
                    orthogonalSash.onPointerStart(event, new OrthogonalPointerEventFactory(pointerEventFactory));
                }
            }
            if (this.linkedSash && !event.__linkedSashEvent) {
                event.__linkedSashEvent = true;
                this.linkedSash.onPointerStart(event, new OrthogonalPointerEventFactory(pointerEventFactory));
            }
            if (!this.state) {
                return;
            }
            const iframes = this.el.ownerDocument.getElementsByTagName('iframe');
            for (const iframe of iframes) {
                iframe.classList.add(PointerEventsDisabledCssClass); // disable mouse events on iframes as long as we drag the sash
            }
            const startX = event.pageX;
            const startY = event.pageY;
            const altKey = event.altKey;
            const startEvent = { startX, currentX: startX, startY, currentY: startY, altKey };
            this.el.classList.add('active');
            this._onDidStart.fire(startEvent);
            // fix https://github.com/microsoft/vscode/issues/21675
            const style = (0, dom_1.createStyleSheet)(this.el);
            const updateStyle = () => {
                let cursor = '';
                if (isMultisashResize) {
                    cursor = 'all-scroll';
                }
                else if (this.orientation === 1 /* Orientation.HORIZONTAL */) {
                    if (this.state === 1 /* SashState.AtMinimum */) {
                        cursor = 's-resize';
                    }
                    else if (this.state === 2 /* SashState.AtMaximum */) {
                        cursor = 'n-resize';
                    }
                    else {
                        cursor = platform_1.isMacintosh ? 'row-resize' : 'ns-resize';
                    }
                }
                else {
                    if (this.state === 1 /* SashState.AtMinimum */) {
                        cursor = 'e-resize';
                    }
                    else if (this.state === 2 /* SashState.AtMaximum */) {
                        cursor = 'w-resize';
                    }
                    else {
                        cursor = platform_1.isMacintosh ? 'col-resize' : 'ew-resize';
                    }
                }
                style.textContent = `* { cursor: ${cursor} !important; }`;
            };
            const disposables = new lifecycle_1.DisposableStore();
            updateStyle();
            if (!isMultisashResize) {
                this.onDidEnablementChange.event(updateStyle, null, disposables);
            }
            const onPointerMove = (e) => {
                dom_1.EventHelper.stop(e, false);
                const event = { startX, currentX: e.pageX, startY, currentY: e.pageY, altKey };
                this._onDidChange.fire(event);
            };
            const onPointerUp = (e) => {
                dom_1.EventHelper.stop(e, false);
                style.remove();
                this.el.classList.remove('active');
                this._onDidEnd.fire();
                disposables.dispose();
                for (const iframe of iframes) {
                    iframe.classList.remove(PointerEventsDisabledCssClass);
                }
            };
            pointerEventFactory.onPointerMove(onPointerMove, null, disposables);
            pointerEventFactory.onPointerUp(onPointerUp, null, disposables);
            disposables.add(pointerEventFactory);
        }
        onPointerDoublePress(e) {
            const orthogonalSash = this.getOrthogonalSash(e);
            if (orthogonalSash) {
                orthogonalSash._onDidReset.fire();
            }
            if (this.linkedSash) {
                this.linkedSash._onDidReset.fire();
            }
            this._onDidReset.fire();
        }
        static onMouseEnter(sash, fromLinkedSash = false) {
            if (sash.el.classList.contains('active')) {
                sash.hoverDelayer.cancel();
                sash.el.classList.add('hover');
            }
            else {
                sash.hoverDelayer.trigger(() => sash.el.classList.add('hover'), sash.hoverDelay).then(undefined, () => { });
            }
            if (!fromLinkedSash && sash.linkedSash) {
                Sash.onMouseEnter(sash.linkedSash, true);
            }
        }
        static onMouseLeave(sash, fromLinkedSash = false) {
            sash.hoverDelayer.cancel();
            sash.el.classList.remove('hover');
            if (!fromLinkedSash && sash.linkedSash) {
                Sash.onMouseLeave(sash.linkedSash, true);
            }
        }
        /**
         * Forcefully stop any user interactions with this sash.
         * Useful when hiding a parent component, while the user is still
         * interacting with the sash.
         */
        clearSashHoverState() {
            Sash.onMouseLeave(this);
        }
        /**
         * Layout the sash. The sash will size and position itself
         * based on its provided {@link ISashLayoutProvider layout provider}.
         */
        layout() {
            if (this.orientation === 0 /* Orientation.VERTICAL */) {
                const verticalProvider = this.layoutProvider;
                this.el.style.left = verticalProvider.getVerticalSashLeft(this) - (this.size / 2) + 'px';
                if (verticalProvider.getVerticalSashTop) {
                    this.el.style.top = verticalProvider.getVerticalSashTop(this) + 'px';
                }
                if (verticalProvider.getVerticalSashHeight) {
                    this.el.style.height = verticalProvider.getVerticalSashHeight(this) + 'px';
                }
            }
            else {
                const horizontalProvider = this.layoutProvider;
                this.el.style.top = horizontalProvider.getHorizontalSashTop(this) - (this.size / 2) + 'px';
                if (horizontalProvider.getHorizontalSashLeft) {
                    this.el.style.left = horizontalProvider.getHorizontalSashLeft(this) + 'px';
                }
                if (horizontalProvider.getHorizontalSashWidth) {
                    this.el.style.width = horizontalProvider.getHorizontalSashWidth(this) + 'px';
                }
            }
        }
        getOrthogonalSash(e) {
            const target = e.initialTarget ?? e.target;
            if (!target || !((0, dom_1.isHTMLElement)(target))) {
                return undefined;
            }
            if (target.classList.contains('orthogonal-drag-handle')) {
                return target.classList.contains('start') ? this.orthogonalStartSash : this.orthogonalEndSash;
            }
            return undefined;
        }
        dispose() {
            super.dispose();
            this.el.remove();
        }
    }
    exports.Sash = Sash;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[255/*vs/base/browser/ui/resizable/resizable*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,173/*vs/base/browser/ui/sash/sash*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/]), function (require, exports, dom_1, sash_1, event_1, lifecycle_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ResizableHTMLElement = void 0;
    class ResizableHTMLElement {
        constructor() {
            this._onDidWillResize = new event_1.Emitter();
            this.onDidWillResize = this._onDidWillResize.event;
            this._onDidResize = new event_1.Emitter();
            this.onDidResize = this._onDidResize.event;
            this._sashListener = new lifecycle_1.DisposableStore();
            this._size = new dom_1.Dimension(0, 0);
            this._minSize = new dom_1.Dimension(0, 0);
            this._maxSize = new dom_1.Dimension(Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER);
            this.domNode = document.createElement('div');
            this._eastSash = new sash_1.Sash(this.domNode, { getVerticalSashLeft: () => this._size.width }, { orientation: 0 /* Orientation.VERTICAL */ });
            this._westSash = new sash_1.Sash(this.domNode, { getVerticalSashLeft: () => 0 }, { orientation: 0 /* Orientation.VERTICAL */ });
            this._northSash = new sash_1.Sash(this.domNode, { getHorizontalSashTop: () => 0 }, { orientation: 1 /* Orientation.HORIZONTAL */, orthogonalEdge: sash_1.OrthogonalEdge.North });
            this._southSash = new sash_1.Sash(this.domNode, { getHorizontalSashTop: () => this._size.height }, { orientation: 1 /* Orientation.HORIZONTAL */, orthogonalEdge: sash_1.OrthogonalEdge.South });
            this._northSash.orthogonalStartSash = this._westSash;
            this._northSash.orthogonalEndSash = this._eastSash;
            this._southSash.orthogonalStartSash = this._westSash;
            this._southSash.orthogonalEndSash = this._eastSash;
            let currentSize;
            let deltaY = 0;
            let deltaX = 0;
            this._sashListener.add(event_1.Event.any(this._northSash.onDidStart, this._eastSash.onDidStart, this._southSash.onDidStart, this._westSash.onDidStart)(() => {
                if (currentSize === undefined) {
                    this._onDidWillResize.fire();
                    currentSize = this._size;
                    deltaY = 0;
                    deltaX = 0;
                }
            }));
            this._sashListener.add(event_1.Event.any(this._northSash.onDidEnd, this._eastSash.onDidEnd, this._southSash.onDidEnd, this._westSash.onDidEnd)(() => {
                if (currentSize !== undefined) {
                    currentSize = undefined;
                    deltaY = 0;
                    deltaX = 0;
                    this._onDidResize.fire({ dimension: this._size, done: true });
                }
            }));
            this._sashListener.add(this._eastSash.onDidChange(e => {
                if (currentSize) {
                    deltaX = e.currentX - e.startX;
                    this.layout(currentSize.height + deltaY, currentSize.width + deltaX);
                    this._onDidResize.fire({ dimension: this._size, done: false, east: true });
                }
            }));
            this._sashListener.add(this._westSash.onDidChange(e => {
                if (currentSize) {
                    deltaX = -(e.currentX - e.startX);
                    this.layout(currentSize.height + deltaY, currentSize.width + deltaX);
                    this._onDidResize.fire({ dimension: this._size, done: false, west: true });
                }
            }));
            this._sashListener.add(this._northSash.onDidChange(e => {
                if (currentSize) {
                    deltaY = -(e.currentY - e.startY);
                    this.layout(currentSize.height + deltaY, currentSize.width + deltaX);
                    this._onDidResize.fire({ dimension: this._size, done: false, north: true });
                }
            }));
            this._sashListener.add(this._southSash.onDidChange(e => {
                if (currentSize) {
                    deltaY = e.currentY - e.startY;
                    this.layout(currentSize.height + deltaY, currentSize.width + deltaX);
                    this._onDidResize.fire({ dimension: this._size, done: false, south: true });
                }
            }));
            this._sashListener.add(event_1.Event.any(this._eastSash.onDidReset, this._westSash.onDidReset)(e => {
                if (this._preferredSize) {
                    this.layout(this._size.height, this._preferredSize.width);
                    this._onDidResize.fire({ dimension: this._size, done: true });
                }
            }));
            this._sashListener.add(event_1.Event.any(this._northSash.onDidReset, this._southSash.onDidReset)(e => {
                if (this._preferredSize) {
                    this.layout(this._preferredSize.height, this._size.width);
                    this._onDidResize.fire({ dimension: this._size, done: true });
                }
            }));
        }
        dispose() {
            this._northSash.dispose();
            this._southSash.dispose();
            this._eastSash.dispose();
            this._westSash.dispose();
            this._sashListener.dispose();
            this._onDidResize.dispose();
            this._onDidWillResize.dispose();
            this.domNode.remove();
        }
        enableSashes(north, east, south, west) {
            this._northSash.state = north ? 3 /* SashState.Enabled */ : 0 /* SashState.Disabled */;
            this._eastSash.state = east ? 3 /* SashState.Enabled */ : 0 /* SashState.Disabled */;
            this._southSash.state = south ? 3 /* SashState.Enabled */ : 0 /* SashState.Disabled */;
            this._westSash.state = west ? 3 /* SashState.Enabled */ : 0 /* SashState.Disabled */;
        }
        layout(height = this.size.height, width = this.size.width) {
            const { height: minHeight, width: minWidth } = this._minSize;
            const { height: maxHeight, width: maxWidth } = this._maxSize;
            height = Math.max(minHeight, Math.min(maxHeight, height));
            width = Math.max(minWidth, Math.min(maxWidth, width));
            const newSize = new dom_1.Dimension(width, height);
            if (!dom_1.Dimension.equals(newSize, this._size)) {
                this.domNode.style.height = height + 'px';
                this.domNode.style.width = width + 'px';
                this._size = newSize;
                this._northSash.layout();
                this._eastSash.layout();
                this._southSash.layout();
                this._westSash.layout();
            }
        }
        clearSashHoverState() {
            this._eastSash.clearSashHoverState();
            this._westSash.clearSashHoverState();
            this._northSash.clearSashHoverState();
            this._southSash.clearSashHoverState();
        }
        get size() {
            return this._size;
        }
        set maxSize(value) {
            this._maxSize = value;
        }
        get maxSize() {
            return this._maxSize;
        }
        set minSize(value) {
            this._minSize = value;
        }
        get minSize() {
            return this._minSize;
        }
        set preferredSize(value) {
            this._preferredSize = value;
        }
        get preferredSize() {
            return this._preferredSize;
        }
    }
    exports.ResizableHTMLElement = ResizableHTMLElement;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[634/*vs/base/browser/ui/selectBox/selectBoxNative*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,69/*vs/base/browser/touch*/,13/*vs/base/common/arrays*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,16/*vs/base/common/platform*/]), function (require, exports, dom, touch_1, arrays, event_1, lifecycle_1, platform_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SelectBoxNative = void 0;
    class SelectBoxNative extends lifecycle_1.Disposable {
        constructor(options, selected, styles, selectBoxOptions) {
            super();
            this.selected = 0;
            this.selectBoxOptions = selectBoxOptions || Object.create(null);
            this.options = [];
            this.selectElement = document.createElement('select');
            this.selectElement.className = 'monaco-select-box';
            if (typeof this.selectBoxOptions.ariaLabel === 'string') {
                this.selectElement.setAttribute('aria-label', this.selectBoxOptions.ariaLabel);
            }
            if (typeof this.selectBoxOptions.ariaDescription === 'string') {
                this.selectElement.setAttribute('aria-description', this.selectBoxOptions.ariaDescription);
            }
            this._onDidSelect = this._register(new event_1.Emitter());
            this.styles = styles;
            this.registerListeners();
            this.setOptions(options, selected);
        }
        registerListeners() {
            this._register(touch_1.Gesture.addTarget(this.selectElement));
            [touch_1.EventType.Tap].forEach(eventType => {
                this._register(dom.addDisposableListener(this.selectElement, eventType, (e) => {
                    this.selectElement.focus();
                }));
            });
            this._register(dom.addStandardDisposableListener(this.selectElement, 'click', (e) => {
                dom.EventHelper.stop(e, true);
            }));
            this._register(dom.addStandardDisposableListener(this.selectElement, 'change', (e) => {
                this.selectElement.title = e.target.value;
                this._onDidSelect.fire({
                    index: e.target.selectedIndex,
                    selected: e.target.value
                });
            }));
            this._register(dom.addStandardDisposableListener(this.selectElement, 'keydown', (e) => {
                let showSelect = false;
                if (platform_1.isMacintosh) {
                    if (e.keyCode === 18 /* KeyCode.DownArrow */ || e.keyCode === 16 /* KeyCode.UpArrow */ || e.keyCode === 10 /* KeyCode.Space */) {
                        showSelect = true;
                    }
                }
                else {
                    if (e.keyCode === 18 /* KeyCode.DownArrow */ && e.altKey || e.keyCode === 10 /* KeyCode.Space */ || e.keyCode === 3 /* KeyCode.Enter */) {
                        showSelect = true;
                    }
                }
                if (showSelect) {
                    // Space, Enter, is used to expand select box, do not propagate it (prevent action bar action run)
                    e.stopPropagation();
                }
            }));
        }
        get onDidSelect() {
            return this._onDidSelect.event;
        }
        setOptions(options, selected) {
            if (!this.options || !arrays.equals(this.options, options)) {
                this.options = options;
                this.selectElement.options.length = 0;
                this.options.forEach((option, index) => {
                    this.selectElement.add(this.createOption(option.text, index, option.isDisabled));
                });
            }
            if (selected !== undefined) {
                this.select(selected);
            }
        }
        select(index) {
            if (this.options.length === 0) {
                this.selected = 0;
            }
            else if (index >= 0 && index < this.options.length) {
                this.selected = index;
            }
            else if (index > this.options.length - 1) {
                // Adjust index to end of list
                // This could make client out of sync with the select
                this.select(this.options.length - 1);
            }
            else if (this.selected < 0) {
                this.selected = 0;
            }
            this.selectElement.selectedIndex = this.selected;
            if ((this.selected < this.options.length) && typeof this.options[this.selected].text === 'string') {
                this.selectElement.title = this.options[this.selected].text;
            }
            else {
                this.selectElement.title = '';
            }
        }
        focus() {
            if (this.selectElement) {
                this.selectElement.tabIndex = 0;
                this.selectElement.focus();
            }
        }
        blur() {
            if (this.selectElement) {
                this.selectElement.tabIndex = -1;
                this.selectElement.blur();
            }
        }
        setFocusable(focusable) {
            this.selectElement.tabIndex = focusable ? 0 : -1;
        }
        render(container) {
            container.classList.add('select-container');
            container.appendChild(this.selectElement);
            this.setOptions(this.options, this.selected);
            this.applyStyles();
        }
        applyStyles() {
            // Style native select
            if (this.selectElement) {
                this.selectElement.style.backgroundColor = this.styles.selectBackground ?? '';
                this.selectElement.style.color = this.styles.selectForeground ?? '';
                this.selectElement.style.borderColor = this.styles.selectBorder ?? '';
            }
        }
        createOption(value, index, disabled) {
            const option = document.createElement('option');
            option.value = value;
            option.text = value;
            option.disabled = !!disabled;
            return option;
        }
    }
    exports.SelectBoxNative = SelectBoxNative;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[85/*vs/base/browser/ui/widget*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,47/*vs/base/browser/keyboardEvent*/,77/*vs/base/browser/mouseEvent*/,69/*vs/base/browser/touch*/,2/*vs/base/common/lifecycle*/]), function (require, exports, dom, keyboardEvent_1, mouseEvent_1, touch_1, lifecycle_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Widget = void 0;
    class Widget extends lifecycle_1.Disposable {
        onclick(domNode, listener) {
            this._register(dom.addDisposableListener(domNode, dom.EventType.CLICK, (e) => listener(new mouseEvent_1.StandardMouseEvent(dom.getWindow(domNode), e))));
        }
        onmousedown(domNode, listener) {
            this._register(dom.addDisposableListener(domNode, dom.EventType.MOUSE_DOWN, (e) => listener(new mouseEvent_1.StandardMouseEvent(dom.getWindow(domNode), e))));
        }
        onmouseover(domNode, listener) {
            this._register(dom.addDisposableListener(domNode, dom.EventType.MOUSE_OVER, (e) => listener(new mouseEvent_1.StandardMouseEvent(dom.getWindow(domNode), e))));
        }
        onmouseleave(domNode, listener) {
            this._register(dom.addDisposableListener(domNode, dom.EventType.MOUSE_LEAVE, (e) => listener(new mouseEvent_1.StandardMouseEvent(dom.getWindow(domNode), e))));
        }
        onkeydown(domNode, listener) {
            this._register(dom.addDisposableListener(domNode, dom.EventType.KEY_DOWN, (e) => listener(new keyboardEvent_1.StandardKeyboardEvent(e))));
        }
        onkeyup(domNode, listener) {
            this._register(dom.addDisposableListener(domNode, dom.EventType.KEY_UP, (e) => listener(new keyboardEvent_1.StandardKeyboardEvent(e))));
        }
        oninput(domNode, listener) {
            this._register(dom.addDisposableListener(domNode, dom.EventType.INPUT, listener));
        }
        onblur(domNode, listener) {
            this._register(dom.addDisposableListener(domNode, dom.EventType.BLUR, listener));
        }
        onfocus(domNode, listener) {
            this._register(dom.addDisposableListener(domNode, dom.EventType.FOCUS, listener));
        }
        ignoreGesture(domNode) {
            return touch_1.Gesture.ignoreTarget(domNode);
        }
    }
    exports.Widget = Widget;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[256/*vs/base/browser/ui/scrollbar/scrollbarArrow*/], __M([1/*require*/,0/*exports*/,172/*vs/base/browser/globalPointerMoveMonitor*/,85/*vs/base/browser/ui/widget*/,14/*vs/base/common/async*/,30/*vs/base/common/themables*/,5/*vs/base/browser/dom*/]), function (require, exports, globalPointerMoveMonitor_1, widget_1, async_1, themables_1, dom) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ScrollbarArrow = exports.ARROW_IMG_SIZE = void 0;
    /**
     * The arrow image size.
     */
    exports.ARROW_IMG_SIZE = 11;
    class ScrollbarArrow extends widget_1.Widget {
        constructor(opts) {
            super();
            this._onActivate = opts.onActivate;
            this.bgDomNode = document.createElement('div');
            this.bgDomNode.className = 'arrow-background';
            this.bgDomNode.style.position = 'absolute';
            this.bgDomNode.style.width = opts.bgWidth + 'px';
            this.bgDomNode.style.height = opts.bgHeight + 'px';
            if (typeof opts.top !== 'undefined') {
                this.bgDomNode.style.top = '0px';
            }
            if (typeof opts.left !== 'undefined') {
                this.bgDomNode.style.left = '0px';
            }
            if (typeof opts.bottom !== 'undefined') {
                this.bgDomNode.style.bottom = '0px';
            }
            if (typeof opts.right !== 'undefined') {
                this.bgDomNode.style.right = '0px';
            }
            this.domNode = document.createElement('div');
            this.domNode.className = opts.className;
            this.domNode.classList.add(...themables_1.ThemeIcon.asClassNameArray(opts.icon));
            this.domNode.style.position = 'absolute';
            this.domNode.style.width = exports.ARROW_IMG_SIZE + 'px';
            this.domNode.style.height = exports.ARROW_IMG_SIZE + 'px';
            if (typeof opts.top !== 'undefined') {
                this.domNode.style.top = opts.top + 'px';
            }
            if (typeof opts.left !== 'undefined') {
                this.domNode.style.left = opts.left + 'px';
            }
            if (typeof opts.bottom !== 'undefined') {
                this.domNode.style.bottom = opts.bottom + 'px';
            }
            if (typeof opts.right !== 'undefined') {
                this.domNode.style.right = opts.right + 'px';
            }
            this._pointerMoveMonitor = this._register(new globalPointerMoveMonitor_1.GlobalPointerMoveMonitor());
            this._register(dom.addStandardDisposableListener(this.bgDomNode, dom.EventType.POINTER_DOWN, (e) => this._arrowPointerDown(e)));
            this._register(dom.addStandardDisposableListener(this.domNode, dom.EventType.POINTER_DOWN, (e) => this._arrowPointerDown(e)));
            this._pointerdownRepeatTimer = this._register(new dom.WindowIntervalTimer());
            this._pointerdownScheduleRepeatTimer = this._register(new async_1.TimeoutTimer());
        }
        _arrowPointerDown(e) {
            if (!e.target || !(e.target instanceof Element)) {
                return;
            }
            const scheduleRepeater = () => {
                this._pointerdownRepeatTimer.cancelAndSet(() => this._onActivate(), 1000 / 24, dom.getWindow(e));
            };
            this._onActivate();
            this._pointerdownRepeatTimer.cancel();
            this._pointerdownScheduleRepeatTimer.cancelAndSet(scheduleRepeater, 200);
            this._pointerMoveMonitor.startMonitoring(e.target, e.pointerId, e.buttons, (pointerMoveData) => { }, () => {
                this._pointerdownRepeatTimer.cancel();
                this._pointerdownScheduleRepeatTimer.cancel();
            });
            e.preventDefault();
        }
    }
    exports.ScrollbarArrow = ScrollbarArrow;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[356/*vs/base/browser/ui/scrollbar/abstractScrollbar*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,39/*vs/base/browser/fastDomNode*/,172/*vs/base/browser/globalPointerMoveMonitor*/,256/*vs/base/browser/ui/scrollbar/scrollbarArrow*/,626/*vs/base/browser/ui/scrollbar/scrollbarVisibilityController*/,85/*vs/base/browser/ui/widget*/,16/*vs/base/common/platform*/]), function (require, exports, dom, fastDomNode_1, globalPointerMoveMonitor_1, scrollbarArrow_1, scrollbarVisibilityController_1, widget_1, platform) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AbstractScrollbar = void 0;
    /**
     * The orthogonal distance to the slider at which dragging "resets". This implements "snapping"
     */
    const POINTER_DRAG_RESET_DISTANCE = 140;
    class AbstractScrollbar extends widget_1.Widget {
        constructor(opts) {
            super();
            this._lazyRender = opts.lazyRender;
            this._host = opts.host;
            this._scrollable = opts.scrollable;
            this._scrollByPage = opts.scrollByPage;
            this._scrollbarState = opts.scrollbarState;
            this._visibilityController = this._register(new scrollbarVisibilityController_1.ScrollbarVisibilityController(opts.visibility, 'visible scrollbar ' + opts.extraScrollbarClassName, 'invisible scrollbar ' + opts.extraScrollbarClassName));
            this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded());
            this._pointerMoveMonitor = this._register(new globalPointerMoveMonitor_1.GlobalPointerMoveMonitor());
            this._shouldRender = true;
            this.domNode = (0, fastDomNode_1.createFastDomNode)(document.createElement('div'));
            this.domNode.setAttribute('role', 'presentation');
            this.domNode.setAttribute('aria-hidden', 'true');
            this._visibilityController.setDomNode(this.domNode);
            this.domNode.setPosition('absolute');
            this._register(dom.addDisposableListener(this.domNode.domNode, dom.EventType.POINTER_DOWN, (e) => this._domNodePointerDown(e)));
        }
        // ----------------- creation
        /**
         * Creates the dom node for an arrow & adds it to the container
         */
        _createArrow(opts) {
            const arrow = this._register(new scrollbarArrow_1.ScrollbarArrow(opts));
            this.domNode.domNode.appendChild(arrow.bgDomNode);
            this.domNode.domNode.appendChild(arrow.domNode);
        }
        /**
         * Creates the slider dom node, adds it to the container & hooks up the events
         */
        _createSlider(top, left, width, height) {
            this.slider = (0, fastDomNode_1.createFastDomNode)(document.createElement('div'));
            this.slider.setClassName('slider');
            this.slider.setPosition('absolute');
            this.slider.setTop(top);
            this.slider.setLeft(left);
            if (typeof width === 'number') {
                this.slider.setWidth(width);
            }
            if (typeof height === 'number') {
                this.slider.setHeight(height);
            }
            this.slider.setLayerHinting(true);
            this.slider.setContain('strict');
            this.domNode.domNode.appendChild(this.slider.domNode);
            this._register(dom.addDisposableListener(this.slider.domNode, dom.EventType.POINTER_DOWN, (e) => {
                if (e.button === 0) {
                    e.preventDefault();
                    this._sliderPointerDown(e);
                }
            }));
            this.onclick(this.slider.domNode, e => {
                if (e.leftButton) {
                    e.stopPropagation();
                }
            });
        }
        // ----------------- Update state
        _onElementSize(visibleSize) {
            if (this._scrollbarState.setVisibleSize(visibleSize)) {
                this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded());
                this._shouldRender = true;
                if (!this._lazyRender) {
                    this.render();
                }
            }
            return this._shouldRender;
        }
        _onElementScrollSize(elementScrollSize) {
            if (this._scrollbarState.setScrollSize(elementScrollSize)) {
                this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded());
                this._shouldRender = true;
                if (!this._lazyRender) {
                    this.render();
                }
            }
            return this._shouldRender;
        }
        _onElementScrollPosition(elementScrollPosition) {
            if (this._scrollbarState.setScrollPosition(elementScrollPosition)) {
                this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded());
                this._shouldRender = true;
                if (!this._lazyRender) {
                    this.render();
                }
            }
            return this._shouldRender;
        }
        // ----------------- rendering
        beginReveal() {
            this._visibilityController.setShouldBeVisible(true);
        }
        beginHide() {
            this._visibilityController.setShouldBeVisible(false);
        }
        render() {
            if (!this._shouldRender) {
                return;
            }
            this._shouldRender = false;
            this._renderDomNode(this._scrollbarState.getRectangleLargeSize(), this._scrollbarState.getRectangleSmallSize());
            this._updateSlider(this._scrollbarState.getSliderSize(), this._scrollbarState.getArrowSize() + this._scrollbarState.getSliderPosition());
        }
        // ----------------- DOM events
        _domNodePointerDown(e) {
            if (e.target !== this.domNode.domNode) {
                return;
            }
            this._onPointerDown(e);
        }
        delegatePointerDown(e) {
            const domTop = this.domNode.domNode.getClientRects()[0].top;
            const sliderStart = domTop + this._scrollbarState.getSliderPosition();
            const sliderStop = domTop + this._scrollbarState.getSliderPosition() + this._scrollbarState.getSliderSize();
            const pointerPos = this._sliderPointerPosition(e);
            if (sliderStart <= pointerPos && pointerPos <= sliderStop) {
                // Act as if it was a pointer down on the slider
                if (e.button === 0) {
                    e.preventDefault();
                    this._sliderPointerDown(e);
                }
            }
            else {
                // Act as if it was a pointer down on the scrollbar
                this._onPointerDown(e);
            }
        }
        _onPointerDown(e) {
            let offsetX;
            let offsetY;
            if (e.target === this.domNode.domNode && typeof e.offsetX === 'number' && typeof e.offsetY === 'number') {
                offsetX = e.offsetX;
                offsetY = e.offsetY;
            }
            else {
                const domNodePosition = dom.getDomNodePagePosition(this.domNode.domNode);
                offsetX = e.pageX - domNodePosition.left;
                offsetY = e.pageY - domNodePosition.top;
            }
            const offset = this._pointerDownRelativePosition(offsetX, offsetY);
            this._setDesiredScrollPositionNow(this._scrollByPage
                ? this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(offset)
                : this._scrollbarState.getDesiredScrollPositionFromOffset(offset));
            if (e.button === 0) {
                // left button
                e.preventDefault();
                this._sliderPointerDown(e);
            }
        }
        _sliderPointerDown(e) {
            if (!e.target || !(e.target instanceof Element)) {
                return;
            }
            const initialPointerPosition = this._sliderPointerPosition(e);
            const initialPointerOrthogonalPosition = this._sliderOrthogonalPointerPosition(e);
            const initialScrollbarState = this._scrollbarState.clone();
            this.slider.toggleClassName('active', true);
            this._pointerMoveMonitor.startMonitoring(e.target, e.pointerId, e.buttons, (pointerMoveData) => {
                const pointerOrthogonalPosition = this._sliderOrthogonalPointerPosition(pointerMoveData);
                const pointerOrthogonalDelta = Math.abs(pointerOrthogonalPosition - initialPointerOrthogonalPosition);
                if (platform.isWindows && pointerOrthogonalDelta > POINTER_DRAG_RESET_DISTANCE) {
                    // The pointer has wondered away from the scrollbar => reset dragging
                    this._setDesiredScrollPositionNow(initialScrollbarState.getScrollPosition());
                    return;
                }
                const pointerPosition = this._sliderPointerPosition(pointerMoveData);
                const pointerDelta = pointerPosition - initialPointerPosition;
                this._setDesiredScrollPositionNow(initialScrollbarState.getDesiredScrollPositionFromDelta(pointerDelta));
            }, () => {
                this.slider.toggleClassName('active', false);
                this._host.onDragEnd();
            });
            this._host.onDragStart();
        }
        _setDesiredScrollPositionNow(_desiredScrollPosition) {
            const desiredScrollPosition = {};
            this.writeScrollPosition(desiredScrollPosition, _desiredScrollPosition);
            this._scrollable.setScrollPositionNow(desiredScrollPosition);
        }
        updateScrollbarSize(scrollbarSize) {
            this._updateScrollbarSize(scrollbarSize);
            this._scrollbarState.setScrollbarSize(scrollbarSize);
            this._shouldRender = true;
            if (!this._lazyRender) {
                this.render();
            }
        }
        isNeeded() {
            return this._scrollbarState.isNeeded();
        }
    }
    exports.AbstractScrollbar = AbstractScrollbar;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[635/*vs/base/browser/ui/scrollbar/horizontalScrollbar*/], __M([1/*require*/,0/*exports*/,77/*vs/base/browser/mouseEvent*/,356/*vs/base/browser/ui/scrollbar/abstractScrollbar*/,256/*vs/base/browser/ui/scrollbar/scrollbarArrow*/,223/*vs/base/browser/ui/scrollbar/scrollbarState*/,26/*vs/base/common/codicons*/]), function (require, exports, mouseEvent_1, abstractScrollbar_1, scrollbarArrow_1, scrollbarState_1, codicons_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.HorizontalScrollbar = void 0;
    class HorizontalScrollbar extends abstractScrollbar_1.AbstractScrollbar {
        constructor(scrollable, options, host) {
            const scrollDimensions = scrollable.getScrollDimensions();
            const scrollPosition = scrollable.getCurrentScrollPosition();
            super({
                lazyRender: options.lazyRender,
                host: host,
                scrollbarState: new scrollbarState_1.ScrollbarState((options.horizontalHasArrows ? options.arrowSize : 0), (options.horizontal === 2 /* ScrollbarVisibility.Hidden */ ? 0 : options.horizontalScrollbarSize), (options.vertical === 2 /* ScrollbarVisibility.Hidden */ ? 0 : options.verticalScrollbarSize), scrollDimensions.width, scrollDimensions.scrollWidth, scrollPosition.scrollLeft),
                visibility: options.horizontal,
                extraScrollbarClassName: 'horizontal',
                scrollable: scrollable,
                scrollByPage: options.scrollByPage
            });
            if (options.horizontalHasArrows) {
                const arrowDelta = (options.arrowSize - scrollbarArrow_1.ARROW_IMG_SIZE) / 2;
                const scrollbarDelta = (options.horizontalScrollbarSize - scrollbarArrow_1.ARROW_IMG_SIZE) / 2;
                this._createArrow({
                    className: 'scra',
                    icon: codicons_1.Codicon.scrollbarButtonLeft,
                    top: scrollbarDelta,
                    left: arrowDelta,
                    bottom: undefined,
                    right: undefined,
                    bgWidth: options.arrowSize,
                    bgHeight: options.horizontalScrollbarSize,
                    onActivate: () => this._host.onMouseWheel(new mouseEvent_1.StandardWheelEvent(null, 1, 0)),
                });
                this._createArrow({
                    className: 'scra',
                    icon: codicons_1.Codicon.scrollbarButtonRight,
                    top: scrollbarDelta,
                    left: undefined,
                    bottom: undefined,
                    right: arrowDelta,
                    bgWidth: options.arrowSize,
                    bgHeight: options.horizontalScrollbarSize,
                    onActivate: () => this._host.onMouseWheel(new mouseEvent_1.StandardWheelEvent(null, -1, 0)),
                });
            }
            this._createSlider(Math.floor((options.horizontalScrollbarSize - options.horizontalSliderSize) / 2), 0, undefined, options.horizontalSliderSize);
        }
        _updateSlider(sliderSize, sliderPosition) {
            this.slider.setWidth(sliderSize);
            this.slider.setLeft(sliderPosition);
        }
        _renderDomNode(largeSize, smallSize) {
            this.domNode.setWidth(largeSize);
            this.domNode.setHeight(smallSize);
            this.domNode.setLeft(0);
            this.domNode.setBottom(0);
        }
        onDidScroll(e) {
            this._shouldRender = this._onElementScrollSize(e.scrollWidth) || this._shouldRender;
            this._shouldRender = this._onElementScrollPosition(e.scrollLeft) || this._shouldRender;
            this._shouldRender = this._onElementSize(e.width) || this._shouldRender;
            return this._shouldRender;
        }
        _pointerDownRelativePosition(offsetX, offsetY) {
            return offsetX;
        }
        _sliderPointerPosition(e) {
            return e.pageX;
        }
        _sliderOrthogonalPointerPosition(e) {
            return e.pageY;
        }
        _updateScrollbarSize(size) {
            this.slider.setHeight(size);
        }
        writeScrollPosition(target, scrollPosition) {
            target.scrollLeft = scrollPosition;
        }
        updateOptions(options) {
            this.updateScrollbarSize(options.horizontal === 2 /* ScrollbarVisibility.Hidden */ ? 0 : options.horizontalScrollbarSize);
            this._scrollbarState.setOppositeScrollbarSize(options.vertical === 2 /* ScrollbarVisibility.Hidden */ ? 0 : options.verticalScrollbarSize);
            this._visibilityController.setVisibility(options.horizontal);
            this._scrollByPage = options.scrollByPage;
        }
    }
    exports.HorizontalScrollbar = HorizontalScrollbar;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[636/*vs/base/browser/ui/scrollbar/verticalScrollbar*/], __M([1/*require*/,0/*exports*/,77/*vs/base/browser/mouseEvent*/,356/*vs/base/browser/ui/scrollbar/abstractScrollbar*/,256/*vs/base/browser/ui/scrollbar/scrollbarArrow*/,223/*vs/base/browser/ui/scrollbar/scrollbarState*/,26/*vs/base/common/codicons*/]), function (require, exports, mouseEvent_1, abstractScrollbar_1, scrollbarArrow_1, scrollbarState_1, codicons_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.VerticalScrollbar = void 0;
    class VerticalScrollbar extends abstractScrollbar_1.AbstractScrollbar {
        constructor(scrollable, options, host) {
            const scrollDimensions = scrollable.getScrollDimensions();
            const scrollPosition = scrollable.getCurrentScrollPosition();
            super({
                lazyRender: options.lazyRender,
                host: host,
                scrollbarState: new scrollbarState_1.ScrollbarState((options.verticalHasArrows ? options.arrowSize : 0), (options.vertical === 2 /* ScrollbarVisibility.Hidden */ ? 0 : options.verticalScrollbarSize), 
                // give priority to vertical scroll bar over horizontal and let it scroll all the way to the bottom
                0, scrollDimensions.height, scrollDimensions.scrollHeight, scrollPosition.scrollTop),
                visibility: options.vertical,
                extraScrollbarClassName: 'vertical',
                scrollable: scrollable,
                scrollByPage: options.scrollByPage
            });
            if (options.verticalHasArrows) {
                const arrowDelta = (options.arrowSize - scrollbarArrow_1.ARROW_IMG_SIZE) / 2;
                const scrollbarDelta = (options.verticalScrollbarSize - scrollbarArrow_1.ARROW_IMG_SIZE) / 2;
                this._createArrow({
                    className: 'scra',
                    icon: codicons_1.Codicon.scrollbarButtonUp,
                    top: arrowDelta,
                    left: scrollbarDelta,
                    bottom: undefined,
                    right: undefined,
                    bgWidth: options.verticalScrollbarSize,
                    bgHeight: options.arrowSize,
                    onActivate: () => this._host.onMouseWheel(new mouseEvent_1.StandardWheelEvent(null, 0, 1)),
                });
                this._createArrow({
                    className: 'scra',
                    icon: codicons_1.Codicon.scrollbarButtonDown,
                    top: undefined,
                    left: scrollbarDelta,
                    bottom: arrowDelta,
                    right: undefined,
                    bgWidth: options.verticalScrollbarSize,
                    bgHeight: options.arrowSize,
                    onActivate: () => this._host.onMouseWheel(new mouseEvent_1.StandardWheelEvent(null, 0, -1)),
                });
            }
            this._createSlider(0, Math.floor((options.verticalScrollbarSize - options.verticalSliderSize) / 2), options.verticalSliderSize, undefined);
        }
        _updateSlider(sliderSize, sliderPosition) {
            this.slider.setHeight(sliderSize);
            this.slider.setTop(sliderPosition);
        }
        _renderDomNode(largeSize, smallSize) {
            this.domNode.setWidth(smallSize);
            this.domNode.setHeight(largeSize);
            this.domNode.setRight(0);
            this.domNode.setTop(0);
        }
        onDidScroll(e) {
            this._shouldRender = this._onElementScrollSize(e.scrollHeight) || this._shouldRender;
            this._shouldRender = this._onElementScrollPosition(e.scrollTop) || this._shouldRender;
            this._shouldRender = this._onElementSize(e.height) || this._shouldRender;
            return this._shouldRender;
        }
        _pointerDownRelativePosition(offsetX, offsetY) {
            return offsetY;
        }
        _sliderPointerPosition(e) {
            return e.pageY;
        }
        _sliderOrthogonalPointerPosition(e) {
            return e.pageX;
        }
        _updateScrollbarSize(size) {
            this.slider.setWidth(size);
        }
        writeScrollPosition(target, scrollPosition) {
            target.scrollTop = scrollPosition;
        }
        updateOptions(options) {
            this.updateScrollbarSize(options.vertical === 2 /* ScrollbarVisibility.Hidden */ ? 0 : options.verticalScrollbarSize);
            // give priority to vertical scroll bar over horizontal and let it scroll all the way to the bottom
            this._scrollbarState.setOppositeScrollbarSize(0);
            this._visibilityController.setVisibility(options.vertical);
            this._scrollByPage = options.scrollByPage;
        }
    }
    exports.VerticalScrollbar = VerticalScrollbar;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[86/*vs/base/browser/ui/scrollbar/scrollableElement*/], __M([1/*require*/,0/*exports*/,64/*vs/base/browser/browser*/,5/*vs/base/browser/dom*/,39/*vs/base/browser/fastDomNode*/,77/*vs/base/browser/mouseEvent*/,635/*vs/base/browser/ui/scrollbar/horizontalScrollbar*/,636/*vs/base/browser/ui/scrollbar/verticalScrollbar*/,85/*vs/base/browser/ui/widget*/,14/*vs/base/common/async*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,16/*vs/base/common/platform*/,163/*vs/base/common/scrollable*/,471/*vs/css!vs/base/browser/ui/scrollbar/media/scrollbars*/]), function (require, exports, browser_1, dom, fastDomNode_1, mouseEvent_1, horizontalScrollbar_1, verticalScrollbar_1, widget_1, async_1, event_1, lifecycle_1, platform, scrollable_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DomScrollableElement = exports.SmoothScrollableElement = exports.ScrollableElement = exports.AbstractScrollableElement = exports.MouseWheelClassifier = void 0;
    const HIDE_TIMEOUT = 500;
    const SCROLL_WHEEL_SENSITIVITY = 50;
    const SCROLL_WHEEL_SMOOTH_SCROLL_ENABLED = true;
    class MouseWheelClassifierItem {
        constructor(timestamp, deltaX, deltaY) {
            this.timestamp = timestamp;
            this.deltaX = deltaX;
            this.deltaY = deltaY;
            this.score = 0;
        }
    }
    class MouseWheelClassifier {
        static { this.INSTANCE = new MouseWheelClassifier(); }
        constructor() {
            this._capacity = 5;
            this._memory = [];
            this._front = -1;
            this._rear = -1;
        }
        isPhysicalMouseWheel() {
            if (this._front === -1 && this._rear === -1) {
                // no elements
                return false;
            }
            // 0.5 * last + 0.25 * 2nd last + 0.125 * 3rd last + ...
            let remainingInfluence = 1;
            let score = 0;
            let iteration = 1;
            let index = this._rear;
            do {
                const influence = (index === this._front ? remainingInfluence : Math.pow(2, -iteration));
                remainingInfluence -= influence;
                score += this._memory[index].score * influence;
                if (index === this._front) {
                    break;
                }
                index = (this._capacity + index - 1) % this._capacity;
                iteration++;
            } while (true);
            return (score <= 0.5);
        }
        acceptStandardWheelEvent(e) {
            if (browser_1.isChrome) {
                const targetWindow = dom.getWindow(e.browserEvent);
                const pageZoomFactor = (0, browser_1.getZoomFactor)(targetWindow);
                // On Chrome, the incoming delta events are multiplied with the OS zoom factor.
                // The OS zoom factor can be reverse engineered by using the device pixel ratio and the configured zoom factor into account.
                this.accept(Date.now(), e.deltaX * pageZoomFactor, e.deltaY * pageZoomFactor);
            }
            else {
                this.accept(Date.now(), e.deltaX, e.deltaY);
            }
        }
        accept(timestamp, deltaX, deltaY) {
            let previousItem = null;
            const item = new MouseWheelClassifierItem(timestamp, deltaX, deltaY);
            if (this._front === -1 && this._rear === -1) {
                this._memory[0] = item;
                this._front = 0;
                this._rear = 0;
            }
            else {
                previousItem = this._memory[this._rear];
                this._rear = (this._rear + 1) % this._capacity;
                if (this._rear === this._front) {
                    // Drop oldest
                    this._front = (this._front + 1) % this._capacity;
                }
                this._memory[this._rear] = item;
            }
            item.score = this._computeScore(item, previousItem);
        }
        /**
         * A score between 0 and 1 for `item`.
         *  - a score towards 0 indicates that the source appears to be a physical mouse wheel
         *  - a score towards 1 indicates that the source appears to be a touchpad or magic mouse, etc.
         */
        _computeScore(item, previousItem) {
            if (Math.abs(item.deltaX) > 0 && Math.abs(item.deltaY) > 0) {
                // both axes exercised => definitely not a physical mouse wheel
                return 1;
            }
            let score = 0.5;
            if (!this._isAlmostInt(item.deltaX) || !this._isAlmostInt(item.deltaY)) {
                // non-integer deltas => indicator that this is not a physical mouse wheel
                score += 0.25;
            }
            // Non-accelerating scroll => indicator that this is a physical mouse wheel
            // These can be identified by seeing whether they are the module of one another.
            if (previousItem) {
                const absDeltaX = Math.abs(item.deltaX);
                const absDeltaY = Math.abs(item.deltaY);
                const absPreviousDeltaX = Math.abs(previousItem.deltaX);
                const absPreviousDeltaY = Math.abs(previousItem.deltaY);
                // Min 1 to avoid division by zero, module 1 will still be 0.
                const minDeltaX = Math.max(Math.min(absDeltaX, absPreviousDeltaX), 1);
                const minDeltaY = Math.max(Math.min(absDeltaY, absPreviousDeltaY), 1);
                const maxDeltaX = Math.max(absDeltaX, absPreviousDeltaX);
                const maxDeltaY = Math.max(absDeltaY, absPreviousDeltaY);
                const isSameModulo = (maxDeltaX % minDeltaX === 0 && maxDeltaY % minDeltaY === 0);
                if (isSameModulo) {
                    score -= 0.5;
                }
            }
            return Math.min(Math.max(score, 0), 1);
        }
        _isAlmostInt(value) {
            const delta = Math.abs(Math.round(value) - value);
            return (delta < 0.01);
        }
    }
    exports.MouseWheelClassifier = MouseWheelClassifier;
    class AbstractScrollableElement extends widget_1.Widget {
        get options() {
            return this._options;
        }
        constructor(element, options, scrollable) {
            super();
            this._onScroll = this._register(new event_1.Emitter());
            this.onScroll = this._onScroll.event;
            this._onWillScroll = this._register(new event_1.Emitter());
            element.style.overflow = 'hidden';
            this._options = resolveOptions(options);
            this._scrollable = scrollable;
            this._register(this._scrollable.onScroll((e) => {
                this._onWillScroll.fire(e);
                this._onDidScroll(e);
                this._onScroll.fire(e);
            }));
            const scrollbarHost = {
                onMouseWheel: (mouseWheelEvent) => this._onMouseWheel(mouseWheelEvent),
                onDragStart: () => this._onDragStart(),
                onDragEnd: () => this._onDragEnd(),
            };
            this._verticalScrollbar = this._register(new verticalScrollbar_1.VerticalScrollbar(this._scrollable, this._options, scrollbarHost));
            this._horizontalScrollbar = this._register(new horizontalScrollbar_1.HorizontalScrollbar(this._scrollable, this._options, scrollbarHost));
            this._domNode = document.createElement('div');
            this._domNode.className = 'monaco-scrollable-element ' + this._options.className;
            this._domNode.setAttribute('role', 'presentation');
            this._domNode.style.position = 'relative';
            this._domNode.style.overflow = 'hidden';
            this._domNode.appendChild(element);
            this._domNode.appendChild(this._horizontalScrollbar.domNode.domNode);
            this._domNode.appendChild(this._verticalScrollbar.domNode.domNode);
            if (this._options.useShadows) {
                this._leftShadowDomNode = (0, fastDomNode_1.createFastDomNode)(document.createElement('div'));
                this._leftShadowDomNode.setClassName('shadow');
                this._domNode.appendChild(this._leftShadowDomNode.domNode);
                this._topShadowDomNode = (0, fastDomNode_1.createFastDomNode)(document.createElement('div'));
                this._topShadowDomNode.setClassName('shadow');
                this._domNode.appendChild(this._topShadowDomNode.domNode);
                this._topLeftShadowDomNode = (0, fastDomNode_1.createFastDomNode)(document.createElement('div'));
                this._topLeftShadowDomNode.setClassName('shadow');
                this._domNode.appendChild(this._topLeftShadowDomNode.domNode);
            }
            else {
                this._leftShadowDomNode = null;
                this._topShadowDomNode = null;
                this._topLeftShadowDomNode = null;
            }
            this._listenOnDomNode = this._options.listenOnDomNode || this._domNode;
            this._mouseWheelToDispose = [];
            this._setListeningToMouseWheel(this._options.handleMouseWheel);
            this.onmouseover(this._listenOnDomNode, (e) => this._onMouseOver(e));
            this.onmouseleave(this._listenOnDomNode, (e) => this._onMouseLeave(e));
            this._hideTimeout = this._register(new async_1.TimeoutTimer());
            this._isDragging = false;
            this._mouseIsOver = false;
            this._shouldRender = true;
            this._revealOnScroll = true;
        }
        dispose() {
            this._mouseWheelToDispose = (0, lifecycle_1.dispose)(this._mouseWheelToDispose);
            super.dispose();
        }
        /**
         * Get the generated 'scrollable' dom node
         */
        getDomNode() {
            return this._domNode;
        }
        getOverviewRulerLayoutInfo() {
            return {
                parent: this._domNode,
                insertBefore: this._verticalScrollbar.domNode.domNode,
            };
        }
        /**
         * Delegate a pointer down event to the vertical scrollbar.
         * This is to help with clicking somewhere else and having the scrollbar react.
         */
        delegateVerticalScrollbarPointerDown(browserEvent) {
            this._verticalScrollbar.delegatePointerDown(browserEvent);
        }
        getScrollDimensions() {
            return this._scrollable.getScrollDimensions();
        }
        setScrollDimensions(dimensions) {
            this._scrollable.setScrollDimensions(dimensions, false);
        }
        /**
         * Update the class name of the scrollable element.
         */
        updateClassName(newClassName) {
            this._options.className = newClassName;
            // Defaults are different on Macs
            if (platform.isMacintosh) {
                this._options.className += ' mac';
            }
            this._domNode.className = 'monaco-scrollable-element ' + this._options.className;
        }
        /**
         * Update configuration options for the scrollbar.
         */
        updateOptions(newOptions) {
            if (typeof newOptions.handleMouseWheel !== 'undefined') {
                this._options.handleMouseWheel = newOptions.handleMouseWheel;
                this._setListeningToMouseWheel(this._options.handleMouseWheel);
            }
            if (typeof newOptions.mouseWheelScrollSensitivity !== 'undefined') {
                this._options.mouseWheelScrollSensitivity = newOptions.mouseWheelScrollSensitivity;
            }
            if (typeof newOptions.fastScrollSensitivity !== 'undefined') {
                this._options.fastScrollSensitivity = newOptions.fastScrollSensitivity;
            }
            if (typeof newOptions.scrollPredominantAxis !== 'undefined') {
                this._options.scrollPredominantAxis = newOptions.scrollPredominantAxis;
            }
            if (typeof newOptions.horizontal !== 'undefined') {
                this._options.horizontal = newOptions.horizontal;
            }
            if (typeof newOptions.vertical !== 'undefined') {
                this._options.vertical = newOptions.vertical;
            }
            if (typeof newOptions.horizontalScrollbarSize !== 'undefined') {
                this._options.horizontalScrollbarSize = newOptions.horizontalScrollbarSize;
            }
            if (typeof newOptions.verticalScrollbarSize !== 'undefined') {
                this._options.verticalScrollbarSize = newOptions.verticalScrollbarSize;
            }
            if (typeof newOptions.scrollByPage !== 'undefined') {
                this._options.scrollByPage = newOptions.scrollByPage;
            }
            this._horizontalScrollbar.updateOptions(this._options);
            this._verticalScrollbar.updateOptions(this._options);
            if (!this._options.lazyRender) {
                this._render();
            }
        }
        delegateScrollFromMouseWheelEvent(browserEvent) {
            this._onMouseWheel(new mouseEvent_1.StandardWheelEvent(browserEvent));
        }
        // -------------------- mouse wheel scrolling --------------------
        _setListeningToMouseWheel(shouldListen) {
            const isListening = (this._mouseWheelToDispose.length > 0);
            if (isListening === shouldListen) {
                // No change
                return;
            }
            // Stop listening (if necessary)
            this._mouseWheelToDispose = (0, lifecycle_1.dispose)(this._mouseWheelToDispose);
            // Start listening (if necessary)
            if (shouldListen) {
                const onMouseWheel = (browserEvent) => {
                    this._onMouseWheel(new mouseEvent_1.StandardWheelEvent(browserEvent));
                };
                this._mouseWheelToDispose.push(dom.addDisposableListener(this._listenOnDomNode, dom.EventType.MOUSE_WHEEL, onMouseWheel, { passive: false }));
            }
        }
        _onMouseWheel(e) {
            if (e.browserEvent?.defaultPrevented) {
                return;
            }
            const classifier = MouseWheelClassifier.INSTANCE;
            if (SCROLL_WHEEL_SMOOTH_SCROLL_ENABLED) {
                classifier.acceptStandardWheelEvent(e);
            }
            // useful for creating unit tests:
            // console.log(`${Date.now()}, ${e.deltaY}, ${e.deltaX}`);
            let didScroll = false;
            if (e.deltaY || e.deltaX) {
                let deltaY = e.deltaY * this._options.mouseWheelScrollSensitivity;
                let deltaX = e.deltaX * this._options.mouseWheelScrollSensitivity;
                if (this._options.scrollPredominantAxis) {
                    if (this._options.scrollYToX && deltaX + deltaY === 0) {
                        // when configured to map Y to X and we both see
                        // no dominant axis and X and Y are competing with
                        // identical values into opposite directions, we
                        // ignore the delta as we cannot make a decision then
                        deltaX = deltaY = 0;
                    }
                    else if (Math.abs(deltaY) >= Math.abs(deltaX)) {
                        deltaX = 0;
                    }
                    else {
                        deltaY = 0;
                    }
                }
                if (this._options.flipAxes) {
                    [deltaY, deltaX] = [deltaX, deltaY];
                }
                // Convert vertical scrolling to horizontal if shift is held, this
                // is handled at a higher level on Mac
                const shiftConvert = !platform.isMacintosh && e.browserEvent && e.browserEvent.shiftKey;
                if ((this._options.scrollYToX || shiftConvert) && !deltaX) {
                    deltaX = deltaY;
                    deltaY = 0;
                }
                if (e.browserEvent && e.browserEvent.altKey) {
                    // fastScrolling
                    deltaX = deltaX * this._options.fastScrollSensitivity;
                    deltaY = deltaY * this._options.fastScrollSensitivity;
                }
                const futureScrollPosition = this._scrollable.getFutureScrollPosition();
                let desiredScrollPosition = {};
                if (deltaY) {
                    const deltaScrollTop = SCROLL_WHEEL_SENSITIVITY * deltaY;
                    // Here we convert values such as -0.3 to -1 or 0.3 to 1, otherwise low speed scrolling will never scroll
                    const desiredScrollTop = futureScrollPosition.scrollTop - (deltaScrollTop < 0 ? Math.floor(deltaScrollTop) : Math.ceil(deltaScrollTop));
                    this._verticalScrollbar.writeScrollPosition(desiredScrollPosition, desiredScrollTop);
                }
                if (deltaX) {
                    const deltaScrollLeft = SCROLL_WHEEL_SENSITIVITY * deltaX;
                    // Here we convert values such as -0.3 to -1 or 0.3 to 1, otherwise low speed scrolling will never scroll
                    const desiredScrollLeft = futureScrollPosition.scrollLeft - (deltaScrollLeft < 0 ? Math.floor(deltaScrollLeft) : Math.ceil(deltaScrollLeft));
                    this._horizontalScrollbar.writeScrollPosition(desiredScrollPosition, desiredScrollLeft);
                }
                // Check that we are scrolling towards a location which is valid
                desiredScrollPosition = this._scrollable.validateScrollPosition(desiredScrollPosition);
                if (futureScrollPosition.scrollLeft !== desiredScrollPosition.scrollLeft || futureScrollPosition.scrollTop !== desiredScrollPosition.scrollTop) {
                    const canPerformSmoothScroll = (SCROLL_WHEEL_SMOOTH_SCROLL_ENABLED
                        && this._options.mouseWheelSmoothScroll
                        && classifier.isPhysicalMouseWheel());
                    if (canPerformSmoothScroll) {
                        this._scrollable.setScrollPositionSmooth(desiredScrollPosition);
                    }
                    else {
                        this._scrollable.setScrollPositionNow(desiredScrollPosition);
                    }
                    didScroll = true;
                }
            }
            let consumeMouseWheel = didScroll;
            if (!consumeMouseWheel && this._options.alwaysConsumeMouseWheel) {
                consumeMouseWheel = true;
            }
            if (!consumeMouseWheel && this._options.consumeMouseWheelIfScrollbarIsNeeded && (this._verticalScrollbar.isNeeded() || this._horizontalScrollbar.isNeeded())) {
                consumeMouseWheel = true;
            }
            if (consumeMouseWheel) {
                e.preventDefault();
                e.stopPropagation();
            }
        }
        _onDidScroll(e) {
            this._shouldRender = this._horizontalScrollbar.onDidScroll(e) || this._shouldRender;
            this._shouldRender = this._verticalScrollbar.onDidScroll(e) || this._shouldRender;
            if (this._options.useShadows) {
                this._shouldRender = true;
            }
            if (this._revealOnScroll) {
                this._reveal();
            }
            if (!this._options.lazyRender) {
                this._render();
            }
        }
        /**
         * Render / mutate the DOM now.
         * Should be used together with the ctor option `lazyRender`.
         */
        renderNow() {
            if (!this._options.lazyRender) {
                throw new Error('Please use `lazyRender` together with `renderNow`!');
            }
            this._render();
        }
        _render() {
            if (!this._shouldRender) {
                return;
            }
            this._shouldRender = false;
            this._horizontalScrollbar.render();
            this._verticalScrollbar.render();
            if (this._options.useShadows) {
                const scrollState = this._scrollable.getCurrentScrollPosition();
                const enableTop = scrollState.scrollTop > 0;
                const enableLeft = scrollState.scrollLeft > 0;
                const leftClassName = (enableLeft ? ' left' : '');
                const topClassName = (enableTop ? ' top' : '');
                const topLeftClassName = (enableLeft || enableTop ? ' top-left-corner' : '');
                this._leftShadowDomNode.setClassName(`shadow${leftClassName}`);
                this._topShadowDomNode.setClassName(`shadow${topClassName}`);
                this._topLeftShadowDomNode.setClassName(`shadow${topLeftClassName}${topClassName}${leftClassName}`);
            }
        }
        // -------------------- fade in / fade out --------------------
        _onDragStart() {
            this._isDragging = true;
            this._reveal();
        }
        _onDragEnd() {
            this._isDragging = false;
            this._hide();
        }
        _onMouseLeave(e) {
            this._mouseIsOver = false;
            this._hide();
        }
        _onMouseOver(e) {
            this._mouseIsOver = true;
            this._reveal();
        }
        _reveal() {
            this._verticalScrollbar.beginReveal();
            this._horizontalScrollbar.beginReveal();
            this._scheduleHide();
        }
        _hide() {
            if (!this._mouseIsOver && !this._isDragging) {
                this._verticalScrollbar.beginHide();
                this._horizontalScrollbar.beginHide();
            }
        }
        _scheduleHide() {
            if (!this._mouseIsOver && !this._isDragging) {
                this._hideTimeout.cancelAndSet(() => this._hide(), HIDE_TIMEOUT);
            }
        }
    }
    exports.AbstractScrollableElement = AbstractScrollableElement;
    class ScrollableElement extends AbstractScrollableElement {
        constructor(element, options) {
            options = options || {};
            options.mouseWheelSmoothScroll = false;
            const scrollable = new scrollable_1.Scrollable({
                forceIntegerValues: true,
                smoothScrollDuration: 0,
                scheduleAtNextAnimationFrame: (callback) => dom.scheduleAtNextAnimationFrame(dom.getWindow(element), callback)
            });
            super(element, options, scrollable);
            this._register(scrollable);
        }
        setScrollPosition(update) {
            this._scrollable.setScrollPositionNow(update);
        }
    }
    exports.ScrollableElement = ScrollableElement;
    class SmoothScrollableElement extends AbstractScrollableElement {
        constructor(element, options, scrollable) {
            super(element, options, scrollable);
        }
        setScrollPosition(update) {
            if (update.reuseAnimation) {
                this._scrollable.setScrollPositionSmooth(update, update.reuseAnimation);
            }
            else {
                this._scrollable.setScrollPositionNow(update);
            }
        }
        getScrollPosition() {
            return this._scrollable.getCurrentScrollPosition();
        }
    }
    exports.SmoothScrollableElement = SmoothScrollableElement;
    class DomScrollableElement extends AbstractScrollableElement {
        constructor(element, options) {
            options = options || {};
            options.mouseWheelSmoothScroll = false;
            const scrollable = new scrollable_1.Scrollable({
                forceIntegerValues: false, // See https://github.com/microsoft/vscode/issues/139877
                smoothScrollDuration: 0,
                scheduleAtNextAnimationFrame: (callback) => dom.scheduleAtNextAnimationFrame(dom.getWindow(element), callback)
            });
            super(element, options, scrollable);
            this._register(scrollable);
            this._element = element;
            this._register(this.onScroll((e) => {
                if (e.scrollTopChanged) {
                    this._element.scrollTop = e.scrollTop;
                }
                if (e.scrollLeftChanged) {
                    this._element.scrollLeft = e.scrollLeft;
                }
            }));
            this.scanDomNode();
        }
        setScrollPosition(update) {
            this._scrollable.setScrollPositionNow(update);
        }
        getScrollPosition() {
            return this._scrollable.getCurrentScrollPosition();
        }
        scanDomNode() {
            // width, scrollLeft, scrollWidth, height, scrollTop, scrollHeight
            this.setScrollDimensions({
                width: this._element.clientWidth,
                scrollWidth: this._element.scrollWidth,
                height: this._element.clientHeight,
                scrollHeight: this._element.scrollHeight
            });
            this.setScrollPosition({
                scrollLeft: this._element.scrollLeft,
                scrollTop: this._element.scrollTop,
            });
        }
    }
    exports.DomScrollableElement = DomScrollableElement;
    function resolveOptions(opts) {
        const result = {
            lazyRender: (typeof opts.lazyRender !== 'undefined' ? opts.lazyRender : false),
            className: (typeof opts.className !== 'undefined' ? opts.className : ''),
            useShadows: (typeof opts.useShadows !== 'undefined' ? opts.useShadows : true),
            handleMouseWheel: (typeof opts.handleMouseWheel !== 'undefined' ? opts.handleMouseWheel : true),
            flipAxes: (typeof opts.flipAxes !== 'undefined' ? opts.flipAxes : false),
            consumeMouseWheelIfScrollbarIsNeeded: (typeof opts.consumeMouseWheelIfScrollbarIsNeeded !== 'undefined' ? opts.consumeMouseWheelIfScrollbarIsNeeded : false),
            alwaysConsumeMouseWheel: (typeof opts.alwaysConsumeMouseWheel !== 'undefined' ? opts.alwaysConsumeMouseWheel : false),
            scrollYToX: (typeof opts.scrollYToX !== 'undefined' ? opts.scrollYToX : false),
            mouseWheelScrollSensitivity: (typeof opts.mouseWheelScrollSensitivity !== 'undefined' ? opts.mouseWheelScrollSensitivity : 1),
            fastScrollSensitivity: (typeof opts.fastScrollSensitivity !== 'undefined' ? opts.fastScrollSensitivity : 5),
            scrollPredominantAxis: (typeof opts.scrollPredominantAxis !== 'undefined' ? opts.scrollPredominantAxis : true),
            mouseWheelSmoothScroll: (typeof opts.mouseWheelSmoothScroll !== 'undefined' ? opts.mouseWheelSmoothScroll : true),
            arrowSize: (typeof opts.arrowSize !== 'undefined' ? opts.arrowSize : 11),
            listenOnDomNode: (typeof opts.listenOnDomNode !== 'undefined' ? opts.listenOnDomNode : null),
            horizontal: (typeof opts.horizontal !== 'undefined' ? opts.horizontal : 1 /* ScrollbarVisibility.Auto */),
            horizontalScrollbarSize: (typeof opts.horizontalScrollbarSize !== 'undefined' ? opts.horizontalScrollbarSize : 10),
            horizontalSliderSize: (typeof opts.horizontalSliderSize !== 'undefined' ? opts.horizontalSliderSize : 0),
            horizontalHasArrows: (typeof opts.horizontalHasArrows !== 'undefined' ? opts.horizontalHasArrows : false),
            vertical: (typeof opts.vertical !== 'undefined' ? opts.vertical : 1 /* ScrollbarVisibility.Auto */),
            verticalScrollbarSize: (typeof opts.verticalScrollbarSize !== 'undefined' ? opts.verticalScrollbarSize : 10),
            verticalHasArrows: (typeof opts.verticalHasArrows !== 'undefined' ? opts.verticalHasArrows : false),
            verticalSliderSize: (typeof opts.verticalSliderSize !== 'undefined' ? opts.verticalSliderSize : 0),
            scrollByPage: (typeof opts.scrollByPage !== 'undefined' ? opts.scrollByPage : false)
        };
        result.horizontalSliderSize = (typeof opts.horizontalSliderSize !== 'undefined' ? opts.horizontalSliderSize : result.horizontalScrollbarSize);
        result.verticalSliderSize = (typeof opts.verticalSliderSize !== 'undefined' ? opts.verticalSliderSize : result.verticalScrollbarSize);
        // Defaults are different on Macs
        if (platform.isMacintosh) {
            result.className += ' mac';
        }
        return result;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[174/*vs/base/browser/ui/hover/hoverWidget*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,47/*vs/base/browser/keyboardEvent*/,86/*vs/base/browser/ui/scrollbar/scrollableElement*/,2/*vs/base/common/lifecycle*/,3/*vs/nls*/,464/*vs/css!vs/base/browser/ui/hover/hoverWidget*/]), function (require, exports, dom, keyboardEvent_1, scrollableElement_1, lifecycle_1, nls_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.KeyDownAction = exports.ClickAction = exports.HoverAction = exports.HoverWidget = void 0;
    exports.getHoverAccessibleViewHint = getHoverAccessibleViewHint;
    const $ = dom.$;
    class HoverWidget extends lifecycle_1.Disposable {
        constructor() {
            super();
            this.containerDomNode = document.createElement('div');
            this.containerDomNode.className = 'monaco-hover';
            this.containerDomNode.tabIndex = 0;
            this.containerDomNode.setAttribute('role', 'tooltip');
            this.contentsDomNode = document.createElement('div');
            this.contentsDomNode.className = 'monaco-hover-content';
            this.scrollbar = this._register(new scrollableElement_1.DomScrollableElement(this.contentsDomNode, {
                consumeMouseWheelIfScrollbarIsNeeded: true
            }));
            this.containerDomNode.appendChild(this.scrollbar.getDomNode());
        }
        onContentsChanged() {
            this.scrollbar.scanDomNode();
        }
    }
    exports.HoverWidget = HoverWidget;
    class HoverAction extends lifecycle_1.Disposable {
        static render(parent, actionOptions, keybindingLabel) {
            return new HoverAction(parent, actionOptions, keybindingLabel);
        }
        constructor(parent, actionOptions, keybindingLabel) {
            super();
            this.actionLabel = actionOptions.label;
            this.actionKeybindingLabel = keybindingLabel;
            this.actionContainer = dom.append(parent, $('div.action-container'));
            this.actionContainer.setAttribute('tabindex', '0');
            this.action = dom.append(this.actionContainer, $('a.action'));
            this.action.setAttribute('role', 'button');
            if (actionOptions.iconClass) {
                dom.append(this.action, $(`span.icon.${actionOptions.iconClass}`));
            }
            const label = dom.append(this.action, $('span'));
            label.textContent = keybindingLabel ? `${actionOptions.label} (${keybindingLabel})` : actionOptions.label;
            this._store.add(new ClickAction(this.actionContainer, actionOptions.run));
            this._store.add(new KeyDownAction(this.actionContainer, actionOptions.run, [3 /* KeyCode.Enter */, 10 /* KeyCode.Space */]));
            this.setEnabled(true);
        }
        setEnabled(enabled) {
            if (enabled) {
                this.actionContainer.classList.remove('disabled');
                this.actionContainer.removeAttribute('aria-disabled');
            }
            else {
                this.actionContainer.classList.add('disabled');
                this.actionContainer.setAttribute('aria-disabled', 'true');
            }
        }
    }
    exports.HoverAction = HoverAction;
    function getHoverAccessibleViewHint(shouldHaveHint, keybinding) {
        return shouldHaveHint && keybinding ? (0, nls_1.localize)(7, "Inspect this in the accessible view with {0}.", keybinding) : shouldHaveHint ? (0, nls_1.localize)(8, "Inspect this in the accessible view via the command Open Accessible View which is currently not triggerable via keybinding.") : '';
    }
    class ClickAction extends lifecycle_1.Disposable {
        constructor(container, run) {
            super();
            this._register(dom.addDisposableListener(container, dom.EventType.CLICK, e => {
                e.stopPropagation();
                e.preventDefault();
                run(container);
            }));
        }
    }
    exports.ClickAction = ClickAction;
    class KeyDownAction extends lifecycle_1.Disposable {
        constructor(container, run, keyCodes) {
            super();
            this._register(dom.addDisposableListener(container, dom.EventType.KEY_DOWN, e => {
                const event = new keyboardEvent_1.StandardKeyboardEvent(e);
                if (keyCodes.some(keyCode => event.equals(keyCode))) {
                    e.stopPropagation();
                    e.preventDefault();
                    run(container);
                }
            }));
        }
    }
    exports.KeyDownAction = KeyDownAction;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/






define(__m[257/*vs/base/browser/ui/list/listView*/], __M([1/*require*/,0/*exports*/,224/*vs/base/browser/dnd*/,5/*vs/base/browser/dom*/,93/*vs/base/browser/event*/,69/*vs/base/browser/touch*/,86/*vs/base/browser/ui/scrollbar/scrollableElement*/,13/*vs/base/common/arrays*/,14/*vs/base/common/async*/,126/*vs/base/common/decorators*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,188/*vs/base/common/range*/,163/*vs/base/common/scrollable*/,454/*vs/base/browser/ui/list/rangeMap*/,632/*vs/base/browser/ui/list/rowCache*/,8/*vs/base/common/errors*/,141/*vs/base/common/numbers*/]), function (require, exports, dnd_1, dom_1, event_1, touch_1, scrollableElement_1, arrays_1, async_1, decorators_1, event_2, lifecycle_1, range_1, scrollable_1, rangeMap_1, rowCache_1, errors_1, numbers_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ListView = exports.NativeDragAndDropData = exports.ExternalElementsDragAndDropData = exports.ElementsDragAndDropData = void 0;
    const StaticDND = {
        CurrentDragAndDropData: undefined
    };
    const DefaultOptions = {
        useShadows: true,
        verticalScrollMode: 1 /* ScrollbarVisibility.Auto */,
        setRowLineHeight: true,
        setRowHeight: true,
        supportDynamicHeights: false,
        dnd: {
            getDragElements(e) { return [e]; },
            getDragURI() { return null; },
            onDragStart() { },
            onDragOver() { return false; },
            drop() { },
            dispose() { }
        },
        horizontalScrolling: false,
        transformOptimization: true,
        alwaysConsumeMouseWheel: true,
    };
    class ElementsDragAndDropData {
        constructor(elements) {
            this.elements = elements;
        }
        update() { }
        getData() {
            return this.elements;
        }
    }
    exports.ElementsDragAndDropData = ElementsDragAndDropData;
    class ExternalElementsDragAndDropData {
        constructor(elements) {
            this.elements = elements;
        }
        update() { }
        getData() {
            return this.elements;
        }
    }
    exports.ExternalElementsDragAndDropData = ExternalElementsDragAndDropData;
    class NativeDragAndDropData {
        constructor() {
            this.types = [];
            this.files = [];
        }
        update(dataTransfer) {
            if (dataTransfer.types) {
                this.types.splice(0, this.types.length, ...dataTransfer.types);
            }
            if (dataTransfer.files) {
                this.files.splice(0, this.files.length);
                for (let i = 0; i < dataTransfer.files.length; i++) {
                    const file = dataTransfer.files.item(i);
                    if (file && (file.size || file.type)) {
                        this.files.push(file);
                    }
                }
            }
        }
        getData() {
            return {
                types: this.types,
                files: this.files
            };
        }
    }
    exports.NativeDragAndDropData = NativeDragAndDropData;
    function equalsDragFeedback(f1, f2) {
        if (Array.isArray(f1) && Array.isArray(f2)) {
            return (0, arrays_1.equals)(f1, f2);
        }
        return f1 === f2;
    }
    class ListViewAccessibilityProvider {
        constructor(accessibilityProvider) {
            if (accessibilityProvider?.getSetSize) {
                this.getSetSize = accessibilityProvider.getSetSize.bind(accessibilityProvider);
            }
            else {
                this.getSetSize = (e, i, l) => l;
            }
            if (accessibilityProvider?.getPosInSet) {
                this.getPosInSet = accessibilityProvider.getPosInSet.bind(accessibilityProvider);
            }
            else {
                this.getPosInSet = (e, i) => i + 1;
            }
            if (accessibilityProvider?.getRole) {
                this.getRole = accessibilityProvider.getRole.bind(accessibilityProvider);
            }
            else {
                this.getRole = _ => 'listitem';
            }
            if (accessibilityProvider?.isChecked) {
                this.isChecked = accessibilityProvider.isChecked.bind(accessibilityProvider);
            }
            else {
                this.isChecked = _ => undefined;
            }
        }
    }
    /**
     * The {@link ListView} is a virtual scrolling engine.
     *
     * Given that it only renders elements within its viewport, it can hold large
     * collections of elements and stay very performant. The performance bottleneck
     * usually lies within the user's rendering code for each element.
     *
     * @remarks It is a low-level widget, not meant to be used directly. Refer to the
     * List widget instead.
     */
    class ListView {
        static { this.InstanceCount = 0; }
        get contentHeight() { return this.rangeMap.size; }
        get onDidScroll() { return this.scrollableElement.onScroll; }
        get scrollableElementDomNode() { return this.scrollableElement.getDomNode(); }
        get horizontalScrolling() { return this._horizontalScrolling; }
        set horizontalScrolling(value) {
            if (value === this._horizontalScrolling) {
                return;
            }
            if (value && this.supportDynamicHeights) {
                throw new Error('Horizontal scrolling and dynamic heights not supported simultaneously');
            }
            this._horizontalScrolling = value;
            this.domNode.classList.toggle('horizontal-scrolling', this._horizontalScrolling);
            if (this._horizontalScrolling) {
                for (const item of this.items) {
                    this.measureItemWidth(item);
                }
                this.updateScrollWidth();
                this.scrollableElement.setScrollDimensions({ width: (0, dom_1.getContentWidth)(this.domNode) });
                this.rowsContainer.style.width = `${Math.max(this.scrollWidth || 0, this.renderWidth)}px`;
            }
            else {
                this.scrollableElementWidthDelayer.cancel();
                this.scrollableElement.setScrollDimensions({ width: this.renderWidth, scrollWidth: this.renderWidth });
                this.rowsContainer.style.width = '';
            }
        }
        constructor(container, virtualDelegate, renderers, options = DefaultOptions) {
            this.virtualDelegate = virtualDelegate;
            this.domId = `list_id_${++ListView.InstanceCount}`;
            this.renderers = new Map();
            this.renderWidth = 0;
            this._scrollHeight = 0;
            this.scrollableElementUpdateDisposable = null;
            this.scrollableElementWidthDelayer = new async_1.Delayer(50);
            this.splicing = false;
            this.dragOverAnimationStopDisposable = lifecycle_1.Disposable.None;
            this.dragOverMouseY = 0;
            this.canDrop = false;
            this.currentDragFeedbackDisposable = lifecycle_1.Disposable.None;
            this.onDragLeaveTimeout = lifecycle_1.Disposable.None;
            this.disposables = new lifecycle_1.DisposableStore();
            this._onDidChangeContentHeight = new event_2.Emitter();
            this._onDidChangeContentWidth = new event_2.Emitter();
            this.onDidChangeContentHeight = event_2.Event.latch(this._onDidChangeContentHeight.event, undefined, this.disposables);
            this._horizontalScrolling = false;
            if (options.horizontalScrolling && options.supportDynamicHeights) {
                throw new Error('Horizontal scrolling and dynamic heights not supported simultaneously');
            }
            this.items = [];
            this.itemId = 0;
            this.rangeMap = this.createRangeMap(options.paddingTop ?? 0);
            for (const renderer of renderers) {
                this.renderers.set(renderer.templateId, renderer);
            }
            this.cache = this.disposables.add(new rowCache_1.RowCache(this.renderers));
            this.lastRenderTop = 0;
            this.lastRenderHeight = 0;
            this.domNode = document.createElement('div');
            this.domNode.className = 'monaco-list';
            this.domNode.classList.add(this.domId);
            this.domNode.tabIndex = 0;
            this.domNode.classList.toggle('mouse-support', typeof options.mouseSupport === 'boolean' ? options.mouseSupport : true);
            this._horizontalScrolling = options.horizontalScrolling ?? DefaultOptions.horizontalScrolling;
            this.domNode.classList.toggle('horizontal-scrolling', this._horizontalScrolling);
            this.paddingBottom = typeof options.paddingBottom === 'undefined' ? 0 : options.paddingBottom;
            this.accessibilityProvider = new ListViewAccessibilityProvider(options.accessibilityProvider);
            this.rowsContainer = document.createElement('div');
            this.rowsContainer.className = 'monaco-list-rows';
            const transformOptimization = options.transformOptimization ?? DefaultOptions.transformOptimization;
            if (transformOptimization) {
                this.rowsContainer.style.transform = 'translate3d(0px, 0px, 0px)';
                this.rowsContainer.style.overflow = 'hidden';
                this.rowsContainer.style.contain = 'strict';
            }
            this.disposables.add(touch_1.Gesture.addTarget(this.rowsContainer));
            this.scrollable = this.disposables.add(new scrollable_1.Scrollable({
                forceIntegerValues: true,
                smoothScrollDuration: (options.smoothScrolling ?? false) ? 125 : 0,
                scheduleAtNextAnimationFrame: cb => (0, dom_1.scheduleAtNextAnimationFrame)((0, dom_1.getWindow)(this.domNode), cb)
            }));
            this.scrollableElement = this.disposables.add(new scrollableElement_1.SmoothScrollableElement(this.rowsContainer, {
                alwaysConsumeMouseWheel: options.alwaysConsumeMouseWheel ?? DefaultOptions.alwaysConsumeMouseWheel,
                horizontal: 1 /* ScrollbarVisibility.Auto */,
                vertical: options.verticalScrollMode ?? DefaultOptions.verticalScrollMode,
                useShadows: options.useShadows ?? DefaultOptions.useShadows,
                mouseWheelScrollSensitivity: options.mouseWheelScrollSensitivity,
                fastScrollSensitivity: options.fastScrollSensitivity,
                scrollByPage: options.scrollByPage
            }, this.scrollable));
            this.domNode.appendChild(this.scrollableElement.getDomNode());
            container.appendChild(this.domNode);
            this.scrollableElement.onScroll(this.onScroll, this, this.disposables);
            this.disposables.add((0, dom_1.addDisposableListener)(this.rowsContainer, touch_1.EventType.Change, e => this.onTouchChange(e)));
            // Prevent the monaco-scrollable-element from scrolling
            // https://github.com/microsoft/vscode/issues/44181
            this.disposables.add((0, dom_1.addDisposableListener)(this.scrollableElement.getDomNode(), 'scroll', e => e.target.scrollTop = 0));
            this.disposables.add((0, dom_1.addDisposableListener)(this.domNode, 'dragover', e => this.onDragOver(this.toDragEvent(e))));
            this.disposables.add((0, dom_1.addDisposableListener)(this.domNode, 'drop', e => this.onDrop(this.toDragEvent(e))));
            this.disposables.add((0, dom_1.addDisposableListener)(this.domNode, 'dragleave', e => this.onDragLeave(this.toDragEvent(e))));
            this.disposables.add((0, dom_1.addDisposableListener)(this.domNode, 'dragend', e => this.onDragEnd(e)));
            this.setRowLineHeight = options.setRowLineHeight ?? DefaultOptions.setRowLineHeight;
            this.setRowHeight = options.setRowHeight ?? DefaultOptions.setRowHeight;
            this.supportDynamicHeights = options.supportDynamicHeights ?? DefaultOptions.supportDynamicHeights;
            this.dnd = options.dnd ?? this.disposables.add(DefaultOptions.dnd);
            this.layout(options.initialSize?.height, options.initialSize?.width);
        }
        updateOptions(options) {
            if (options.paddingBottom !== undefined) {
                this.paddingBottom = options.paddingBottom;
                this.scrollableElement.setScrollDimensions({ scrollHeight: this.scrollHeight });
            }
            if (options.smoothScrolling !== undefined) {
                this.scrollable.setSmoothScrollDuration(options.smoothScrolling ? 125 : 0);
            }
            if (options.horizontalScrolling !== undefined) {
                this.horizontalScrolling = options.horizontalScrolling;
            }
            let scrollableOptions;
            if (options.scrollByPage !== undefined) {
                scrollableOptions = { ...(scrollableOptions ?? {}), scrollByPage: options.scrollByPage };
            }
            if (options.mouseWheelScrollSensitivity !== undefined) {
                scrollableOptions = { ...(scrollableOptions ?? {}), mouseWheelScrollSensitivity: options.mouseWheelScrollSensitivity };
            }
            if (options.fastScrollSensitivity !== undefined) {
                scrollableOptions = { ...(scrollableOptions ?? {}), fastScrollSensitivity: options.fastScrollSensitivity };
            }
            if (scrollableOptions) {
                this.scrollableElement.updateOptions(scrollableOptions);
            }
            if (options.paddingTop !== undefined && options.paddingTop !== this.rangeMap.paddingTop) {
                // trigger a rerender
                const lastRenderRange = this.getRenderRange(this.lastRenderTop, this.lastRenderHeight);
                const offset = options.paddingTop - this.rangeMap.paddingTop;
                this.rangeMap.paddingTop = options.paddingTop;
                this.render(lastRenderRange, Math.max(0, this.lastRenderTop + offset), this.lastRenderHeight, undefined, undefined, true);
                this.setScrollTop(this.lastRenderTop);
                this.eventuallyUpdateScrollDimensions();
                if (this.supportDynamicHeights) {
                    this._rerender(this.lastRenderTop, this.lastRenderHeight);
                }
            }
        }
        createRangeMap(paddingTop) {
            return new rangeMap_1.RangeMap(paddingTop);
        }
        splice(start, deleteCount, elements = []) {
            if (this.splicing) {
                throw new Error('Can\'t run recursive splices.');
            }
            this.splicing = true;
            try {
                return this._splice(start, deleteCount, elements);
            }
            finally {
                this.splicing = false;
                this._onDidChangeContentHeight.fire(this.contentHeight);
            }
        }
        _splice(start, deleteCount, elements = []) {
            const previousRenderRange = this.getRenderRange(this.lastRenderTop, this.lastRenderHeight);
            const deleteRange = { start, end: start + deleteCount };
            const removeRange = range_1.Range.intersect(previousRenderRange, deleteRange);
            // try to reuse rows, avoid removing them from DOM
            const rowsToDispose = new Map();
            for (let i = removeRange.end - 1; i >= removeRange.start; i--) {
                const item = this.items[i];
                item.dragStartDisposable.dispose();
                item.checkedDisposable.dispose();
                if (item.row) {
                    let rows = rowsToDispose.get(item.templateId);
                    if (!rows) {
                        rows = [];
                        rowsToDispose.set(item.templateId, rows);
                    }
                    const renderer = this.renderers.get(item.templateId);
                    if (renderer && renderer.disposeElement) {
                        renderer.disposeElement(item.element, i, item.row.templateData, item.size);
                    }
                    rows.unshift(item.row);
                }
                item.row = null;
                item.stale = true;
            }
            const previousRestRange = { start: start + deleteCount, end: this.items.length };
            const previousRenderedRestRange = range_1.Range.intersect(previousRestRange, previousRenderRange);
            const previousUnrenderedRestRanges = range_1.Range.relativeComplement(previousRestRange, previousRenderRange);
            const inserted = elements.map(element => ({
                id: String(this.itemId++),
                element,
                templateId: this.virtualDelegate.getTemplateId(element),
                size: this.virtualDelegate.getHeight(element),
                width: undefined,
                hasDynamicHeight: !!this.virtualDelegate.hasDynamicHeight && this.virtualDelegate.hasDynamicHeight(element),
                lastDynamicHeightWidth: undefined,
                row: null,
                uri: undefined,
                dropTarget: false,
                dragStartDisposable: lifecycle_1.Disposable.None,
                checkedDisposable: lifecycle_1.Disposable.None,
                stale: false
            }));
            let deleted;
            // TODO@joao: improve this optimization to catch even more cases
            if (start === 0 && deleteCount >= this.items.length) {
                this.rangeMap = this.createRangeMap(this.rangeMap.paddingTop);
                this.rangeMap.splice(0, 0, inserted);
                deleted = this.items;
                this.items = inserted;
            }
            else {
                this.rangeMap.splice(start, deleteCount, inserted);
                deleted = this.items.splice(start, deleteCount, ...inserted);
            }
            const delta = elements.length - deleteCount;
            const renderRange = this.getRenderRange(this.lastRenderTop, this.lastRenderHeight);
            const renderedRestRange = (0, rangeMap_1.shift)(previousRenderedRestRange, delta);
            const updateRange = range_1.Range.intersect(renderRange, renderedRestRange);
            for (let i = updateRange.start; i < updateRange.end; i++) {
                this.updateItemInDOM(this.items[i], i);
            }
            const removeRanges = range_1.Range.relativeComplement(renderedRestRange, renderRange);
            for (const range of removeRanges) {
                for (let i = range.start; i < range.end; i++) {
                    this.removeItemFromDOM(i);
                }
            }
            const unrenderedRestRanges = previousUnrenderedRestRanges.map(r => (0, rangeMap_1.shift)(r, delta));
            const elementsRange = { start, end: start + elements.length };
            const insertRanges = [elementsRange, ...unrenderedRestRanges].map(r => range_1.Range.intersect(renderRange, r)).reverse();
            for (const range of insertRanges) {
                for (let i = range.end - 1; i >= range.start; i--) {
                    const item = this.items[i];
                    const rows = rowsToDispose.get(item.templateId);
                    const row = rows?.pop();
                    this.insertItemInDOM(i, row);
                }
            }
            for (const rows of rowsToDispose.values()) {
                for (const row of rows) {
                    this.cache.release(row);
                }
            }
            this.eventuallyUpdateScrollDimensions();
            if (this.supportDynamicHeights) {
                this._rerender(this.scrollTop, this.renderHeight);
            }
            return deleted.map(i => i.element);
        }
        eventuallyUpdateScrollDimensions() {
            this._scrollHeight = this.contentHeight;
            this.rowsContainer.style.height = `${this._scrollHeight}px`;
            if (!this.scrollableElementUpdateDisposable) {
                this.scrollableElementUpdateDisposable = (0, dom_1.scheduleAtNextAnimationFrame)((0, dom_1.getWindow)(this.domNode), () => {
                    this.scrollableElement.setScrollDimensions({ scrollHeight: this.scrollHeight });
                    this.updateScrollWidth();
                    this.scrollableElementUpdateDisposable = null;
                });
            }
        }
        eventuallyUpdateScrollWidth() {
            if (!this.horizontalScrolling) {
                this.scrollableElementWidthDelayer.cancel();
                return;
            }
            this.scrollableElementWidthDelayer.trigger(() => this.updateScrollWidth());
        }
        updateScrollWidth() {
            if (!this.horizontalScrolling) {
                return;
            }
            let scrollWidth = 0;
            for (const item of this.items) {
                if (typeof item.width !== 'undefined') {
                    scrollWidth = Math.max(scrollWidth, item.width);
                }
            }
            this.scrollWidth = scrollWidth;
            this.scrollableElement.setScrollDimensions({ scrollWidth: scrollWidth === 0 ? 0 : (scrollWidth + 10) });
            this._onDidChangeContentWidth.fire(this.scrollWidth);
        }
        rerender() {
            if (!this.supportDynamicHeights) {
                return;
            }
            for (const item of this.items) {
                item.lastDynamicHeightWidth = undefined;
            }
            this._rerender(this.lastRenderTop, this.lastRenderHeight);
        }
        get length() {
            return this.items.length;
        }
        get renderHeight() {
            const scrollDimensions = this.scrollableElement.getScrollDimensions();
            return scrollDimensions.height;
        }
        get firstVisibleIndex() {
            const range = this.getRenderRange(this.lastRenderTop, this.lastRenderHeight);
            return range.start;
        }
        element(index) {
            return this.items[index].element;
        }
        indexOf(element) {
            return this.items.findIndex(item => item.element === element);
        }
        domElement(index) {
            const row = this.items[index].row;
            return row && row.domNode;
        }
        elementHeight(index) {
            return this.items[index].size;
        }
        elementTop(index) {
            return this.rangeMap.positionAt(index);
        }
        indexAt(position) {
            return this.rangeMap.indexAt(position);
        }
        indexAfter(position) {
            return this.rangeMap.indexAfter(position);
        }
        layout(height, width) {
            const scrollDimensions = {
                height: typeof height === 'number' ? height : (0, dom_1.getContentHeight)(this.domNode)
            };
            if (this.scrollableElementUpdateDisposable) {
                this.scrollableElementUpdateDisposable.dispose();
                this.scrollableElementUpdateDisposable = null;
                scrollDimensions.scrollHeight = this.scrollHeight;
            }
            this.scrollableElement.setScrollDimensions(scrollDimensions);
            if (typeof width !== 'undefined') {
                this.renderWidth = width;
                if (this.supportDynamicHeights) {
                    this._rerender(this.scrollTop, this.renderHeight);
                }
            }
            if (this.horizontalScrolling) {
                this.scrollableElement.setScrollDimensions({
                    width: typeof width === 'number' ? width : (0, dom_1.getContentWidth)(this.domNode)
                });
            }
        }
        // Render
        render(previousRenderRange, renderTop, renderHeight, renderLeft, scrollWidth, updateItemsInDOM = false) {
            const renderRange = this.getRenderRange(renderTop, renderHeight);
            const rangesToInsert = range_1.Range.relativeComplement(renderRange, previousRenderRange).reverse();
            const rangesToRemove = range_1.Range.relativeComplement(previousRenderRange, renderRange);
            if (updateItemsInDOM) {
                const rangesToUpdate = range_1.Range.intersect(previousRenderRange, renderRange);
                for (let i = rangesToUpdate.start; i < rangesToUpdate.end; i++) {
                    this.updateItemInDOM(this.items[i], i);
                }
            }
            this.cache.transact(() => {
                for (const range of rangesToRemove) {
                    for (let i = range.start; i < range.end; i++) {
                        this.removeItemFromDOM(i);
                    }
                }
                for (const range of rangesToInsert) {
                    for (let i = range.end - 1; i >= range.start; i--) {
                        this.insertItemInDOM(i);
                    }
                }
            });
            if (renderLeft !== undefined) {
                this.rowsContainer.style.left = `-${renderLeft}px`;
            }
            this.rowsContainer.style.top = `-${renderTop}px`;
            if (this.horizontalScrolling && scrollWidth !== undefined) {
                this.rowsContainer.style.width = `${Math.max(scrollWidth, this.renderWidth)}px`;
            }
            this.lastRenderTop = renderTop;
            this.lastRenderHeight = renderHeight;
        }
        // DOM operations
        insertItemInDOM(index, row) {
            const item = this.items[index];
            if (!item.row) {
                if (row) {
                    item.row = row;
                    item.stale = true;
                }
                else {
                    const result = this.cache.alloc(item.templateId);
                    item.row = result.row;
                    item.stale ||= result.isReusingConnectedDomNode;
                }
            }
            const role = this.accessibilityProvider.getRole(item.element) || 'listitem';
            item.row.domNode.setAttribute('role', role);
            const checked = this.accessibilityProvider.isChecked(item.element);
            if (typeof checked === 'boolean') {
                item.row.domNode.setAttribute('aria-checked', String(!!checked));
            }
            else if (checked) {
                const update = (checked) => item.row.domNode.setAttribute('aria-checked', String(!!checked));
                update(checked.value);
                item.checkedDisposable = checked.onDidChange(() => update(checked.value));
            }
            if (item.stale || !item.row.domNode.parentElement) {
                const referenceNode = this.items.at(index + 1)?.row?.domNode ?? null;
                if (item.row.domNode.parentElement !== this.rowsContainer || item.row.domNode.nextElementSibling !== referenceNode) {
                    this.rowsContainer.insertBefore(item.row.domNode, referenceNode);
                }
                item.stale = false;
            }
            this.updateItemInDOM(item, index);
            const renderer = this.renderers.get(item.templateId);
            if (!renderer) {
                throw new Error(`No renderer found for template id ${item.templateId}`);
            }
            renderer?.renderElement(item.element, index, item.row.templateData, item.size);
            const uri = this.dnd.getDragURI(item.element);
            item.dragStartDisposable.dispose();
            item.row.domNode.draggable = !!uri;
            if (uri) {
                item.dragStartDisposable = (0, dom_1.addDisposableListener)(item.row.domNode, 'dragstart', event => this.onDragStart(item.element, uri, event));
            }
            if (this.horizontalScrolling) {
                this.measureItemWidth(item);
                this.eventuallyUpdateScrollWidth();
            }
        }
        measureItemWidth(item) {
            if (!item.row || !item.row.domNode) {
                return;
            }
            item.row.domNode.style.width = 'fit-content';
            item.width = (0, dom_1.getContentWidth)(item.row.domNode);
            const style = (0, dom_1.getWindow)(item.row.domNode).getComputedStyle(item.row.domNode);
            if (style.paddingLeft) {
                item.width += parseFloat(style.paddingLeft);
            }
            if (style.paddingRight) {
                item.width += parseFloat(style.paddingRight);
            }
            item.row.domNode.style.width = '';
        }
        updateItemInDOM(item, index) {
            item.row.domNode.style.top = `${this.elementTop(index)}px`;
            if (this.setRowHeight) {
                item.row.domNode.style.height = `${item.size}px`;
            }
            if (this.setRowLineHeight) {
                item.row.domNode.style.lineHeight = `${item.size}px`;
            }
            item.row.domNode.setAttribute('data-index', `${index}`);
            item.row.domNode.setAttribute('data-last-element', index === this.length - 1 ? 'true' : 'false');
            item.row.domNode.setAttribute('data-parity', index % 2 === 0 ? 'even' : 'odd');
            item.row.domNode.setAttribute('aria-setsize', String(this.accessibilityProvider.getSetSize(item.element, index, this.length)));
            item.row.domNode.setAttribute('aria-posinset', String(this.accessibilityProvider.getPosInSet(item.element, index)));
            item.row.domNode.setAttribute('id', this.getElementDomId(index));
            item.row.domNode.classList.toggle('drop-target', item.dropTarget);
        }
        removeItemFromDOM(index) {
            const item = this.items[index];
            item.dragStartDisposable.dispose();
            item.checkedDisposable.dispose();
            if (item.row) {
                const renderer = this.renderers.get(item.templateId);
                if (renderer && renderer.disposeElement) {
                    renderer.disposeElement(item.element, index, item.row.templateData, item.size);
                }
                this.cache.release(item.row);
                item.row = null;
            }
            if (this.horizontalScrolling) {
                this.eventuallyUpdateScrollWidth();
            }
        }
        getScrollTop() {
            const scrollPosition = this.scrollableElement.getScrollPosition();
            return scrollPosition.scrollTop;
        }
        setScrollTop(scrollTop, reuseAnimation) {
            if (this.scrollableElementUpdateDisposable) {
                this.scrollableElementUpdateDisposable.dispose();
                this.scrollableElementUpdateDisposable = null;
                this.scrollableElement.setScrollDimensions({ scrollHeight: this.scrollHeight });
            }
            this.scrollableElement.setScrollPosition({ scrollTop, reuseAnimation });
        }
        get scrollTop() {
            return this.getScrollTop();
        }
        set scrollTop(scrollTop) {
            this.setScrollTop(scrollTop);
        }
        get scrollHeight() {
            return this._scrollHeight + (this.horizontalScrolling ? 10 : 0) + this.paddingBottom;
        }
        // Events
        get onMouseClick() { return event_2.Event.map(this.disposables.add(new event_1.DomEmitter(this.domNode, 'click')).event, e => this.toMouseEvent(e), this.disposables); }
        get onMouseDblClick() { return event_2.Event.map(this.disposables.add(new event_1.DomEmitter(this.domNode, 'dblclick')).event, e => this.toMouseEvent(e), this.disposables); }
        get onMouseMiddleClick() { return event_2.Event.filter(event_2.Event.map(this.disposables.add(new event_1.DomEmitter(this.domNode, 'auxclick')).event, e => this.toMouseEvent(e), this.disposables), e => e.browserEvent.button === 1, this.disposables); }
        get onMouseDown() { return event_2.Event.map(this.disposables.add(new event_1.DomEmitter(this.domNode, 'mousedown')).event, e => this.toMouseEvent(e), this.disposables); }
        get onMouseOver() { return event_2.Event.map(this.disposables.add(new event_1.DomEmitter(this.domNode, 'mouseover')).event, e => this.toMouseEvent(e), this.disposables); }
        get onMouseOut() { return event_2.Event.map(this.disposables.add(new event_1.DomEmitter(this.domNode, 'mouseout')).event, e => this.toMouseEvent(e), this.disposables); }
        get onContextMenu() { return event_2.Event.any(event_2.Event.map(this.disposables.add(new event_1.DomEmitter(this.domNode, 'contextmenu')).event, e => this.toMouseEvent(e), this.disposables), event_2.Event.map(this.disposables.add(new event_1.DomEmitter(this.domNode, touch_1.EventType.Contextmenu)).event, e => this.toGestureEvent(e), this.disposables)); }
        get onTouchStart() { return event_2.Event.map(this.disposables.add(new event_1.DomEmitter(this.domNode, 'touchstart')).event, e => this.toTouchEvent(e), this.disposables); }
        get onTap() { return event_2.Event.map(this.disposables.add(new event_1.DomEmitter(this.rowsContainer, touch_1.EventType.Tap)).event, e => this.toGestureEvent(e), this.disposables); }
        toMouseEvent(browserEvent) {
            const index = this.getItemIndexFromEventTarget(browserEvent.target || null);
            const item = typeof index === 'undefined' ? undefined : this.items[index];
            const element = item && item.element;
            return { browserEvent, index, element };
        }
        toTouchEvent(browserEvent) {
            const index = this.getItemIndexFromEventTarget(browserEvent.target || null);
            const item = typeof index === 'undefined' ? undefined : this.items[index];
            const element = item && item.element;
            return { browserEvent, index, element };
        }
        toGestureEvent(browserEvent) {
            const index = this.getItemIndexFromEventTarget(browserEvent.initialTarget || null);
            const item = typeof index === 'undefined' ? undefined : this.items[index];
            const element = item && item.element;
            return { browserEvent, index, element };
        }
        toDragEvent(browserEvent) {
            const index = this.getItemIndexFromEventTarget(browserEvent.target || null);
            const item = typeof index === 'undefined' ? undefined : this.items[index];
            const element = item && item.element;
            const sector = this.getTargetSector(browserEvent, index);
            return { browserEvent, index, element, sector };
        }
        onScroll(e) {
            try {
                const previousRenderRange = this.getRenderRange(this.lastRenderTop, this.lastRenderHeight);
                this.render(previousRenderRange, e.scrollTop, e.height, e.scrollLeft, e.scrollWidth);
                if (this.supportDynamicHeights) {
                    this._rerender(e.scrollTop, e.height, e.inSmoothScrolling);
                }
            }
            catch (err) {
                console.error('Got bad scroll event:', e);
                throw err;
            }
        }
        onTouchChange(event) {
            event.preventDefault();
            event.stopPropagation();
            this.scrollTop -= event.translationY;
        }
        // DND
        onDragStart(element, uri, event) {
            if (!event.dataTransfer) {
                return;
            }
            const elements = this.dnd.getDragElements(element);
            event.dataTransfer.effectAllowed = 'copyMove';
            event.dataTransfer.setData(dnd_1.DataTransfers.TEXT, uri);
            if (event.dataTransfer.setDragImage) {
                let label;
                if (this.dnd.getDragLabel) {
                    label = this.dnd.getDragLabel(elements, event);
                }
                if (typeof label === 'undefined') {
                    label = String(elements.length);
                }
                const dragImage = (0, dom_1.$)('.monaco-drag-image');
                dragImage.textContent = label;
                const getDragImageContainer = (e) => {
                    while (e && !e.classList.contains('monaco-workbench')) {
                        e = e.parentElement;
                    }
                    return e || this.domNode.ownerDocument;
                };
                const container = getDragImageContainer(this.domNode);
                container.appendChild(dragImage);
                event.dataTransfer.setDragImage(dragImage, -10, -10);
                setTimeout(() => dragImage.remove(), 0);
            }
            this.domNode.classList.add('dragging');
            this.currentDragData = new ElementsDragAndDropData(elements);
            StaticDND.CurrentDragAndDropData = new ExternalElementsDragAndDropData(elements);
            this.dnd.onDragStart?.(this.currentDragData, event);
        }
        onDragOver(event) {
            event.browserEvent.preventDefault(); // needed so that the drop event fires (https://stackoverflow.com/questions/21339924/drop-event-not-firing-in-chrome)
            this.onDragLeaveTimeout.dispose();
            if (StaticDND.CurrentDragAndDropData && StaticDND.CurrentDragAndDropData.getData() === 'vscode-ui') {
                return false;
            }
            this.setupDragAndDropScrollTopAnimation(event.browserEvent);
            if (!event.browserEvent.dataTransfer) {
                return false;
            }
            // Drag over from outside
            if (!this.currentDragData) {
                if (StaticDND.CurrentDragAndDropData) {
                    // Drag over from another list
                    this.currentDragData = StaticDND.CurrentDragAndDropData;
                }
                else {
                    // Drag over from the desktop
                    if (!event.browserEvent.dataTransfer.types) {
                        return false;
                    }
                    this.currentDragData = new NativeDragAndDropData();
                }
            }
            const result = this.dnd.onDragOver(this.currentDragData, event.element, event.index, event.sector, event.browserEvent);
            this.canDrop = typeof result === 'boolean' ? result : result.accept;
            if (!this.canDrop) {
                this.currentDragFeedback = undefined;
                this.currentDragFeedbackDisposable.dispose();
                return false;
            }
            event.browserEvent.dataTransfer.dropEffect = (typeof result !== 'boolean' && result.effect?.type === 0 /* ListDragOverEffectType.Copy */) ? 'copy' : 'move';
            let feedback;
            if (typeof result !== 'boolean' && result.feedback) {
                feedback = result.feedback;
            }
            else {
                if (typeof event.index === 'undefined') {
                    feedback = [-1];
                }
                else {
                    feedback = [event.index];
                }
            }
            // sanitize feedback list
            feedback = (0, arrays_1.distinct)(feedback).filter(i => i >= -1 && i < this.length).sort((a, b) => a - b);
            feedback = feedback[0] === -1 ? [-1] : feedback;
            let dragOverEffectPosition = typeof result !== 'boolean' && result.effect && result.effect.position ? result.effect.position : "drop-target" /* ListDragOverEffectPosition.Over */;
            if (equalsDragFeedback(this.currentDragFeedback, feedback) && this.currentDragFeedbackPosition === dragOverEffectPosition) {
                return true;
            }
            this.currentDragFeedback = feedback;
            this.currentDragFeedbackPosition = dragOverEffectPosition;
            this.currentDragFeedbackDisposable.dispose();
            if (feedback[0] === -1) { // entire list feedback
                this.domNode.classList.add(dragOverEffectPosition);
                this.rowsContainer.classList.add(dragOverEffectPosition);
                this.currentDragFeedbackDisposable = (0, lifecycle_1.toDisposable)(() => {
                    this.domNode.classList.remove(dragOverEffectPosition);
                    this.rowsContainer.classList.remove(dragOverEffectPosition);
                });
            }
            else {
                if (feedback.length > 1 && dragOverEffectPosition !== "drop-target" /* ListDragOverEffectPosition.Over */) {
                    throw new Error('Can\'t use multiple feedbacks with position different than \'over\'');
                }
                // Make sure there is no flicker when moving between two items
                // Always use the before feedback if possible
                if (dragOverEffectPosition === "drop-target-after" /* ListDragOverEffectPosition.After */) {
                    if (feedback[0] < this.length - 1) {
                        feedback[0] += 1;
                        dragOverEffectPosition = "drop-target-before" /* ListDragOverEffectPosition.Before */;
                    }
                }
                for (const index of feedback) {
                    const item = this.items[index];
                    item.dropTarget = true;
                    item.row?.domNode.classList.add(dragOverEffectPosition);
                }
                this.currentDragFeedbackDisposable = (0, lifecycle_1.toDisposable)(() => {
                    for (const index of feedback) {
                        const item = this.items[index];
                        item.dropTarget = false;
                        item.row?.domNode.classList.remove(dragOverEffectPosition);
                    }
                });
            }
            return true;
        }
        onDragLeave(event) {
            this.onDragLeaveTimeout.dispose();
            this.onDragLeaveTimeout = (0, async_1.disposableTimeout)(() => this.clearDragOverFeedback(), 100, this.disposables);
            if (this.currentDragData) {
                this.dnd.onDragLeave?.(this.currentDragData, event.element, event.index, event.browserEvent);
            }
        }
        onDrop(event) {
            if (!this.canDrop) {
                return;
            }
            const dragData = this.currentDragData;
            this.teardownDragAndDropScrollTopAnimation();
            this.clearDragOverFeedback();
            this.domNode.classList.remove('dragging');
            this.currentDragData = undefined;
            StaticDND.CurrentDragAndDropData = undefined;
            if (!dragData || !event.browserEvent.dataTransfer) {
                return;
            }
            event.browserEvent.preventDefault();
            dragData.update(event.browserEvent.dataTransfer);
            this.dnd.drop(dragData, event.element, event.index, event.sector, event.browserEvent);
        }
        onDragEnd(event) {
            this.canDrop = false;
            this.teardownDragAndDropScrollTopAnimation();
            this.clearDragOverFeedback();
            this.domNode.classList.remove('dragging');
            this.currentDragData = undefined;
            StaticDND.CurrentDragAndDropData = undefined;
            this.dnd.onDragEnd?.(event);
        }
        clearDragOverFeedback() {
            this.currentDragFeedback = undefined;
            this.currentDragFeedbackPosition = undefined;
            this.currentDragFeedbackDisposable.dispose();
            this.currentDragFeedbackDisposable = lifecycle_1.Disposable.None;
        }
        // DND scroll top animation
        setupDragAndDropScrollTopAnimation(event) {
            if (!this.dragOverAnimationDisposable) {
                const viewTop = (0, dom_1.getTopLeftOffset)(this.domNode).top;
                this.dragOverAnimationDisposable = (0, dom_1.animate)((0, dom_1.getWindow)(this.domNode), this.animateDragAndDropScrollTop.bind(this, viewTop));
            }
            this.dragOverAnimationStopDisposable.dispose();
            this.dragOverAnimationStopDisposable = (0, async_1.disposableTimeout)(() => {
                if (this.dragOverAnimationDisposable) {
                    this.dragOverAnimationDisposable.dispose();
                    this.dragOverAnimationDisposable = undefined;
                }
            }, 1000, this.disposables);
            this.dragOverMouseY = event.pageY;
        }
        animateDragAndDropScrollTop(viewTop) {
            if (this.dragOverMouseY === undefined) {
                return;
            }
            const diff = this.dragOverMouseY - viewTop;
            const upperLimit = this.renderHeight - 35;
            if (diff < 35) {
                this.scrollTop += Math.max(-14, Math.floor(0.3 * (diff - 35)));
            }
            else if (diff > upperLimit) {
                this.scrollTop += Math.min(14, Math.floor(0.3 * (diff - upperLimit)));
            }
        }
        teardownDragAndDropScrollTopAnimation() {
            this.dragOverAnimationStopDisposable.dispose();
            if (this.dragOverAnimationDisposable) {
                this.dragOverAnimationDisposable.dispose();
                this.dragOverAnimationDisposable = undefined;
            }
        }
        // Util
        getTargetSector(browserEvent, targetIndex) {
            if (targetIndex === undefined) {
                return undefined;
            }
            const relativePosition = browserEvent.offsetY / this.items[targetIndex].size;
            const sector = Math.floor(relativePosition / 0.25);
            return (0, numbers_1.clamp)(sector, 0, 3);
        }
        getItemIndexFromEventTarget(target) {
            const scrollableElement = this.scrollableElement.getDomNode();
            let element = target;
            while (((0, dom_1.isHTMLElement)(element) || (0, dom_1.isSVGElement)(element)) && element !== this.rowsContainer && scrollableElement.contains(element)) {
                const rawIndex = element.getAttribute('data-index');
                if (rawIndex) {
                    const index = Number(rawIndex);
                    if (!isNaN(index)) {
                        return index;
                    }
                }
                element = element.parentElement;
            }
            return undefined;
        }
        getRenderRange(renderTop, renderHeight) {
            return {
                start: this.rangeMap.indexAt(renderTop),
                end: this.rangeMap.indexAfter(renderTop + renderHeight - 1)
            };
        }
        /**
         * Given a stable rendered state, checks every rendered element whether it needs
         * to be probed for dynamic height. Adjusts scroll height and top if necessary.
         */
        _rerender(renderTop, renderHeight, inSmoothScrolling) {
            const previousRenderRange = this.getRenderRange(renderTop, renderHeight);
            // Let's remember the second element's position, this helps in scrolling up
            // and preserving a linear upwards scroll movement
            let anchorElementIndex;
            let anchorElementTopDelta;
            if (renderTop === this.elementTop(previousRenderRange.start)) {
                anchorElementIndex = previousRenderRange.start;
                anchorElementTopDelta = 0;
            }
            else if (previousRenderRange.end - previousRenderRange.start > 1) {
                anchorElementIndex = previousRenderRange.start + 1;
                anchorElementTopDelta = this.elementTop(anchorElementIndex) - renderTop;
            }
            let heightDiff = 0;
            while (true) {
                const renderRange = this.getRenderRange(renderTop, renderHeight);
                let didChange = false;
                for (let i = renderRange.start; i < renderRange.end; i++) {
                    const diff = this.probeDynamicHeight(i);
                    if (diff !== 0) {
                        this.rangeMap.splice(i, 1, [this.items[i]]);
                    }
                    heightDiff += diff;
                    didChange = didChange || diff !== 0;
                }
                if (!didChange) {
                    if (heightDiff !== 0) {
                        this.eventuallyUpdateScrollDimensions();
                    }
                    const unrenderRanges = range_1.Range.relativeComplement(previousRenderRange, renderRange);
                    for (const range of unrenderRanges) {
                        for (let i = range.start; i < range.end; i++) {
                            if (this.items[i].row) {
                                this.removeItemFromDOM(i);
                            }
                        }
                    }
                    const renderRanges = range_1.Range.relativeComplement(renderRange, previousRenderRange).reverse();
                    for (const range of renderRanges) {
                        for (let i = range.end - 1; i >= range.start; i--) {
                            this.insertItemInDOM(i);
                        }
                    }
                    for (let i = renderRange.start; i < renderRange.end; i++) {
                        if (this.items[i].row) {
                            this.updateItemInDOM(this.items[i], i);
                        }
                    }
                    if (typeof anchorElementIndex === 'number') {
                        // To compute a destination scroll top, we need to take into account the current smooth scrolling
                        // animation, and then reuse it with a new target (to avoid prolonging the scroll)
                        // See https://github.com/microsoft/vscode/issues/104144
                        // See https://github.com/microsoft/vscode/pull/104284
                        // See https://github.com/microsoft/vscode/issues/107704
                        const deltaScrollTop = this.scrollable.getFutureScrollPosition().scrollTop - renderTop;
                        const newScrollTop = this.elementTop(anchorElementIndex) - anchorElementTopDelta + deltaScrollTop;
                        this.setScrollTop(newScrollTop, inSmoothScrolling);
                    }
                    this._onDidChangeContentHeight.fire(this.contentHeight);
                    return;
                }
            }
        }
        probeDynamicHeight(index) {
            const item = this.items[index];
            if (!!this.virtualDelegate.getDynamicHeight) {
                const newSize = this.virtualDelegate.getDynamicHeight(item.element);
                if (newSize !== null) {
                    const size = item.size;
                    item.size = newSize;
                    item.lastDynamicHeightWidth = this.renderWidth;
                    return newSize - size;
                }
            }
            if (!item.hasDynamicHeight || item.lastDynamicHeightWidth === this.renderWidth) {
                return 0;
            }
            if (!!this.virtualDelegate.hasDynamicHeight && !this.virtualDelegate.hasDynamicHeight(item.element)) {
                return 0;
            }
            const size = item.size;
            if (item.row) {
                item.row.domNode.style.height = '';
                item.size = item.row.domNode.offsetHeight;
                if (item.size === 0 && !(0, dom_1.isAncestor)(item.row.domNode, (0, dom_1.getWindow)(item.row.domNode).document.body)) {
                    console.warn('Measuring item node that is not in DOM! Add ListView to the DOM before measuring row height!', new Error().stack);
                }
                item.lastDynamicHeightWidth = this.renderWidth;
                return item.size - size;
            }
            const { row } = this.cache.alloc(item.templateId);
            row.domNode.style.height = '';
            this.rowsContainer.appendChild(row.domNode);
            const renderer = this.renderers.get(item.templateId);
            if (!renderer) {
                throw new errors_1.BugIndicatingError('Missing renderer for templateId: ' + item.templateId);
            }
            renderer.renderElement(item.element, index, row.templateData, undefined);
            item.size = row.domNode.offsetHeight;
            renderer.disposeElement?.(item.element, index, row.templateData, undefined);
            this.virtualDelegate.setDynamicHeight?.(item.element, item.size);
            item.lastDynamicHeightWidth = this.renderWidth;
            row.domNode.remove();
            this.cache.release(row);
            return item.size - size;
        }
        getElementDomId(index) {
            return `${this.domId}_${index}`;
        }
        // Dispose
        dispose() {
            for (const item of this.items) {
                item.dragStartDisposable.dispose();
                item.checkedDisposable.dispose();
                if (item.row) {
                    const renderer = this.renderers.get(item.row.templateId);
                    if (renderer) {
                        renderer.disposeElement?.(item.element, -1, item.row.templateData, undefined);
                        renderer.disposeTemplate(item.row.templateData);
                    }
                }
            }
            this.items = [];
            this.domNode?.remove();
            this.dragOverAnimationDisposable?.dispose();
            this.disposables.dispose();
        }
    }
    exports.ListView = ListView;
    __decorate([
        decorators_1.memoize
    ], ListView.prototype, "onMouseClick", null);
    __decorate([
        decorators_1.memoize
    ], ListView.prototype, "onMouseDblClick", null);
    __decorate([
        decorators_1.memoize
    ], ListView.prototype, "onMouseMiddleClick", null);
    __decorate([
        decorators_1.memoize
    ], ListView.prototype, "onMouseDown", null);
    __decorate([
        decorators_1.memoize
    ], ListView.prototype, "onMouseOver", null);
    __decorate([
        decorators_1.memoize
    ], ListView.prototype, "onMouseOut", null);
    __decorate([
        decorators_1.memoize
    ], ListView.prototype, "onContextMenu", null);
    __decorate([
        decorators_1.memoize
    ], ListView.prototype, "onTouchStart", null);
    __decorate([
        decorators_1.memoize
    ], ListView.prototype, "onTap", null);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/






define(__m[115/*vs/base/browser/ui/list/listWidget*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,93/*vs/base/browser/event*/,47/*vs/base/browser/keyboardEvent*/,69/*vs/base/browser/touch*/,46/*vs/base/browser/ui/aria/aria*/,443/*vs/base/browser/ui/list/splice*/,13/*vs/base/common/arrays*/,14/*vs/base/common/async*/,33/*vs/base/common/color*/,126/*vs/base/common/decorators*/,6/*vs/base/common/event*/,82/*vs/base/common/filters*/,2/*vs/base/common/lifecycle*/,141/*vs/base/common/numbers*/,16/*vs/base/common/platform*/,19/*vs/base/common/types*/,442/*vs/base/browser/ui/list/list*/,257/*vs/base/browser/ui/list/listView*/,77/*vs/base/browser/mouseEvent*/,21/*vs/base/common/observable*/,305/*vs/css!vs/base/browser/ui/list/list*/]), function (require, exports, dom_1, event_1, keyboardEvent_1, touch_1, aria_1, splice_1, arrays_1, async_1, color_1, decorators_1, event_2, filters_1, lifecycle_1, numbers_1, platform, types_1, list_1, listView_1, mouseEvent_1, observable_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.List = exports.unthemedListStyles = exports.DefaultStyleController = exports.MouseController = exports.DefaultKeyboardNavigationDelegate = exports.TypeNavigationMode = void 0;
    exports.isInputElement = isInputElement;
    exports.isMonacoEditor = isMonacoEditor;
    exports.isMonacoCustomToggle = isMonacoCustomToggle;
    exports.isActionItem = isActionItem;
    exports.isStickyScrollElement = isStickyScrollElement;
    exports.isStickyScrollContainer = isStickyScrollContainer;
    exports.isButton = isButton;
    exports.isSelectionSingleChangeEvent = isSelectionSingleChangeEvent;
    exports.isSelectionRangeChangeEvent = isSelectionRangeChangeEvent;
    class TraitRenderer {
        constructor(trait) {
            this.trait = trait;
            this.renderedElements = [];
        }
        get templateId() {
            return `template:${this.trait.name}`;
        }
        renderTemplate(container) {
            return container;
        }
        renderElement(element, index, templateData) {
            const renderedElementIndex = this.renderedElements.findIndex(el => el.templateData === templateData);
            if (renderedElementIndex >= 0) {
                const rendered = this.renderedElements[renderedElementIndex];
                this.trait.unrender(templateData);
                rendered.index = index;
            }
            else {
                const rendered = { index, templateData };
                this.renderedElements.push(rendered);
            }
            this.trait.renderIndex(index, templateData);
        }
        splice(start, deleteCount, insertCount) {
            const rendered = [];
            for (const renderedElement of this.renderedElements) {
                if (renderedElement.index < start) {
                    rendered.push(renderedElement);
                }
                else if (renderedElement.index >= start + deleteCount) {
                    rendered.push({
                        index: renderedElement.index + insertCount - deleteCount,
                        templateData: renderedElement.templateData
                    });
                }
            }
            this.renderedElements = rendered;
        }
        renderIndexes(indexes) {
            for (const { index, templateData } of this.renderedElements) {
                if (indexes.indexOf(index) > -1) {
                    this.trait.renderIndex(index, templateData);
                }
            }
        }
        disposeTemplate(templateData) {
            const index = this.renderedElements.findIndex(el => el.templateData === templateData);
            if (index < 0) {
                return;
            }
            this.renderedElements.splice(index, 1);
        }
    }
    class Trait {
        get name() { return this._trait; }
        get renderer() {
            return new TraitRenderer(this);
        }
        constructor(_trait) {
            this._trait = _trait;
            this.indexes = [];
            this.sortedIndexes = [];
            this._onChange = new event_2.Emitter();
            this.onChange = this._onChange.event;
        }
        splice(start, deleteCount, elements) {
            const diff = elements.length - deleteCount;
            const end = start + deleteCount;
            const sortedIndexes = [];
            let i = 0;
            while (i < this.sortedIndexes.length && this.sortedIndexes[i] < start) {
                sortedIndexes.push(this.sortedIndexes[i++]);
            }
            for (let j = 0; j < elements.length; j++) {
                if (elements[j]) {
                    sortedIndexes.push(j + start);
                }
            }
            while (i < this.sortedIndexes.length && this.sortedIndexes[i] >= end) {
                sortedIndexes.push(this.sortedIndexes[i++] + diff);
            }
            this.renderer.splice(start, deleteCount, elements.length);
            this._set(sortedIndexes, sortedIndexes);
        }
        renderIndex(index, container) {
            container.classList.toggle(this._trait, this.contains(index));
        }
        unrender(container) {
            container.classList.remove(this._trait);
        }
        /**
         * Sets the indexes which should have this trait.
         *
         * @param indexes Indexes which should have this trait.
         * @return The old indexes which had this trait.
         */
        set(indexes, browserEvent) {
            return this._set(indexes, [...indexes].sort(numericSort), browserEvent);
        }
        _set(indexes, sortedIndexes, browserEvent) {
            const result = this.indexes;
            const sortedResult = this.sortedIndexes;
            this.indexes = indexes;
            this.sortedIndexes = sortedIndexes;
            const toRender = disjunction(sortedResult, indexes);
            this.renderer.renderIndexes(toRender);
            this._onChange.fire({ indexes, browserEvent });
            return result;
        }
        get() {
            return this.indexes;
        }
        contains(index) {
            return (0, arrays_1.binarySearch)(this.sortedIndexes, index, numericSort) >= 0;
        }
        dispose() {
            (0, lifecycle_1.dispose)(this._onChange);
        }
    }
    __decorate([
        decorators_1.memoize
    ], Trait.prototype, "renderer", null);
    class SelectionTrait extends Trait {
        constructor(setAriaSelected) {
            super('selected');
            this.setAriaSelected = setAriaSelected;
        }
        renderIndex(index, container) {
            super.renderIndex(index, container);
            if (this.setAriaSelected) {
                if (this.contains(index)) {
                    container.setAttribute('aria-selected', 'true');
                }
                else {
                    container.setAttribute('aria-selected', 'false');
                }
            }
        }
    }
    /**
     * The TraitSpliceable is used as a util class to be able
     * to preserve traits across splice calls, given an identity
     * provider.
     */
    class TraitSpliceable {
        constructor(trait, view, identityProvider) {
            this.trait = trait;
            this.view = view;
            this.identityProvider = identityProvider;
        }
        splice(start, deleteCount, elements) {
            if (!this.identityProvider) {
                return this.trait.splice(start, deleteCount, new Array(elements.length).fill(false));
            }
            const pastElementsWithTrait = this.trait.get().map(i => this.identityProvider.getId(this.view.element(i)).toString());
            if (pastElementsWithTrait.length === 0) {
                return this.trait.splice(start, deleteCount, new Array(elements.length).fill(false));
            }
            const pastElementsWithTraitSet = new Set(pastElementsWithTrait);
            const elementsWithTrait = elements.map(e => pastElementsWithTraitSet.has(this.identityProvider.getId(e).toString()));
            this.trait.splice(start, deleteCount, elementsWithTrait);
        }
    }
    function isInputElement(e) {
        return e.tagName === 'INPUT' || e.tagName === 'TEXTAREA';
    }
    function isListElementDescendantOfClass(e, className) {
        if (e.classList.contains(className)) {
            return true;
        }
        if (e.classList.contains('monaco-list')) {
            return false;
        }
        if (!e.parentElement) {
            return false;
        }
        return isListElementDescendantOfClass(e.parentElement, className);
    }
    function isMonacoEditor(e) {
        return isListElementDescendantOfClass(e, 'monaco-editor');
    }
    function isMonacoCustomToggle(e) {
        return isListElementDescendantOfClass(e, 'monaco-custom-toggle');
    }
    function isActionItem(e) {
        return isListElementDescendantOfClass(e, 'action-item');
    }
    function isStickyScrollElement(e) {
        return isListElementDescendantOfClass(e, 'monaco-tree-sticky-row');
    }
    function isStickyScrollContainer(e) {
        return e.classList.contains('monaco-tree-sticky-container');
    }
    function isButton(e) {
        if ((e.tagName === 'A' && e.classList.contains('monaco-button')) ||
            (e.tagName === 'DIV' && e.classList.contains('monaco-button-dropdown'))) {
            return true;
        }
        if (e.classList.contains('monaco-list')) {
            return false;
        }
        if (!e.parentElement) {
            return false;
        }
        return isButton(e.parentElement);
    }
    class KeyboardController {
        get onKeyDown() {
            return event_2.Event.chain(this.disposables.add(new event_1.DomEmitter(this.view.domNode, 'keydown')).event, $ => $.filter(e => !isInputElement(e.target))
                .map(e => new keyboardEvent_1.StandardKeyboardEvent(e)));
        }
        constructor(list, view, options) {
            this.list = list;
            this.view = view;
            this.disposables = new lifecycle_1.DisposableStore();
            this.multipleSelectionDisposables = new lifecycle_1.DisposableStore();
            this.multipleSelectionSupport = options.multipleSelectionSupport;
            this.disposables.add(this.onKeyDown(e => {
                switch (e.keyCode) {
                    case 3 /* KeyCode.Enter */:
                        return this.onEnter(e);
                    case 16 /* KeyCode.UpArrow */:
                        return this.onUpArrow(e);
                    case 18 /* KeyCode.DownArrow */:
                        return this.onDownArrow(e);
                    case 11 /* KeyCode.PageUp */:
                        return this.onPageUpArrow(e);
                    case 12 /* KeyCode.PageDown */:
                        return this.onPageDownArrow(e);
                    case 9 /* KeyCode.Escape */:
                        return this.onEscape(e);
                    case 31 /* KeyCode.KeyA */:
                        if (this.multipleSelectionSupport && (platform.isMacintosh ? e.metaKey : e.ctrlKey)) {
                            this.onCtrlA(e);
                        }
                }
            }));
        }
        updateOptions(optionsUpdate) {
            if (optionsUpdate.multipleSelectionSupport !== undefined) {
                this.multipleSelectionSupport = optionsUpdate.multipleSelectionSupport;
            }
        }
        onEnter(e) {
            e.preventDefault();
            e.stopPropagation();
            this.list.setSelection(this.list.getFocus(), e.browserEvent);
        }
        onUpArrow(e) {
            e.preventDefault();
            e.stopPropagation();
            this.list.focusPrevious(1, false, e.browserEvent);
            const el = this.list.getFocus()[0];
            this.list.setAnchor(el);
            this.list.reveal(el);
            this.view.domNode.focus();
        }
        onDownArrow(e) {
            e.preventDefault();
            e.stopPropagation();
            this.list.focusNext(1, false, e.browserEvent);
            const el = this.list.getFocus()[0];
            this.list.setAnchor(el);
            this.list.reveal(el);
            this.view.domNode.focus();
        }
        onPageUpArrow(e) {
            e.preventDefault();
            e.stopPropagation();
            this.list.focusPreviousPage(e.browserEvent);
            const el = this.list.getFocus()[0];
            this.list.setAnchor(el);
            this.list.reveal(el);
            this.view.domNode.focus();
        }
        onPageDownArrow(e) {
            e.preventDefault();
            e.stopPropagation();
            this.list.focusNextPage(e.browserEvent);
            const el = this.list.getFocus()[0];
            this.list.setAnchor(el);
            this.list.reveal(el);
            this.view.domNode.focus();
        }
        onCtrlA(e) {
            e.preventDefault();
            e.stopPropagation();
            this.list.setSelection((0, arrays_1.range)(this.list.length), e.browserEvent);
            this.list.setAnchor(undefined);
            this.view.domNode.focus();
        }
        onEscape(e) {
            if (this.list.getSelection().length) {
                e.preventDefault();
                e.stopPropagation();
                this.list.setSelection([], e.browserEvent);
                this.list.setAnchor(undefined);
                this.view.domNode.focus();
            }
        }
        dispose() {
            this.disposables.dispose();
            this.multipleSelectionDisposables.dispose();
        }
    }
    __decorate([
        decorators_1.memoize
    ], KeyboardController.prototype, "onKeyDown", null);
    var TypeNavigationMode;
    (function (TypeNavigationMode) {
        TypeNavigationMode[TypeNavigationMode["Automatic"] = 0] = "Automatic";
        TypeNavigationMode[TypeNavigationMode["Trigger"] = 1] = "Trigger";
    })(TypeNavigationMode || (exports.TypeNavigationMode = TypeNavigationMode = {}));
    var TypeNavigationControllerState;
    (function (TypeNavigationControllerState) {
        TypeNavigationControllerState[TypeNavigationControllerState["Idle"] = 0] = "Idle";
        TypeNavigationControllerState[TypeNavigationControllerState["Typing"] = 1] = "Typing";
    })(TypeNavigationControllerState || (TypeNavigationControllerState = {}));
    exports.DefaultKeyboardNavigationDelegate = new class {
        mightProducePrintableCharacter(event) {
            if (event.ctrlKey || event.metaKey || event.altKey) {
                return false;
            }
            return (event.keyCode >= 31 /* KeyCode.KeyA */ && event.keyCode <= 56 /* KeyCode.KeyZ */)
                || (event.keyCode >= 21 /* KeyCode.Digit0 */ && event.keyCode <= 30 /* KeyCode.Digit9 */)
                || (event.keyCode >= 98 /* KeyCode.Numpad0 */ && event.keyCode <= 107 /* KeyCode.Numpad9 */)
                || (event.keyCode >= 85 /* KeyCode.Semicolon */ && event.keyCode <= 95 /* KeyCode.Quote */);
        }
    };
    class TypeNavigationController {
        constructor(list, view, keyboardNavigationLabelProvider, keyboardNavigationEventFilter, delegate) {
            this.list = list;
            this.view = view;
            this.keyboardNavigationLabelProvider = keyboardNavigationLabelProvider;
            this.keyboardNavigationEventFilter = keyboardNavigationEventFilter;
            this.delegate = delegate;
            this.enabled = false;
            this.state = TypeNavigationControllerState.Idle;
            this.mode = TypeNavigationMode.Automatic;
            this.triggered = false;
            this.previouslyFocused = -1;
            this.enabledDisposables = new lifecycle_1.DisposableStore();
            this.disposables = new lifecycle_1.DisposableStore();
            this.updateOptions(list.options);
        }
        updateOptions(options) {
            if (options.typeNavigationEnabled ?? true) {
                this.enable();
            }
            else {
                this.disable();
            }
            this.mode = options.typeNavigationMode ?? TypeNavigationMode.Automatic;
        }
        enable() {
            if (this.enabled) {
                return;
            }
            let typing = false;
            const onChar = event_2.Event.chain(this.enabledDisposables.add(new event_1.DomEmitter(this.view.domNode, 'keydown')).event, $ => $.filter(e => !isInputElement(e.target))
                .filter(() => this.mode === TypeNavigationMode.Automatic || this.triggered)
                .map(event => new keyboardEvent_1.StandardKeyboardEvent(event))
                .filter(e => typing || this.keyboardNavigationEventFilter(e))
                .filter(e => this.delegate.mightProducePrintableCharacter(e))
                .forEach(e => dom_1.EventHelper.stop(e, true))
                .map(event => event.browserEvent.key));
            const onClear = event_2.Event.debounce(onChar, () => null, 800, undefined, undefined, undefined, this.enabledDisposables);
            const onInput = event_2.Event.reduce(event_2.Event.any(onChar, onClear), (r, i) => i === null ? null : ((r || '') + i), undefined, this.enabledDisposables);
            onInput(this.onInput, this, this.enabledDisposables);
            onClear(this.onClear, this, this.enabledDisposables);
            onChar(() => typing = true, undefined, this.enabledDisposables);
            onClear(() => typing = false, undefined, this.enabledDisposables);
            this.enabled = true;
            this.triggered = false;
        }
        disable() {
            if (!this.enabled) {
                return;
            }
            this.enabledDisposables.clear();
            this.enabled = false;
            this.triggered = false;
        }
        onClear() {
            const focus = this.list.getFocus();
            if (focus.length > 0 && focus[0] === this.previouslyFocused) {
                // List: re-announce element on typing end since typed keys will interrupt aria label of focused element
                // Do not announce if there was a focus change at the end to prevent duplication https://github.com/microsoft/vscode/issues/95961
                const ariaLabel = this.list.options.accessibilityProvider?.getAriaLabel(this.list.element(focus[0]));
                if (typeof ariaLabel === 'string') {
                    (0, aria_1.alert)(ariaLabel);
                }
                else if (ariaLabel) {
                    (0, aria_1.alert)(ariaLabel.get());
                }
            }
            this.previouslyFocused = -1;
        }
        onInput(word) {
            if (!word) {
                this.state = TypeNavigationControllerState.Idle;
                this.triggered = false;
                return;
            }
            const focus = this.list.getFocus();
            const start = focus.length > 0 ? focus[0] : 0;
            const delta = this.state === TypeNavigationControllerState.Idle ? 1 : 0;
            this.state = TypeNavigationControllerState.Typing;
            for (let i = 0; i < this.list.length; i++) {
                const index = (start + i + delta) % this.list.length;
                const label = this.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(this.view.element(index));
                const labelStr = label && label.toString();
                if (this.list.options.typeNavigationEnabled) {
                    if (typeof labelStr !== 'undefined') {
                        // If prefix is found, focus and return early
                        if ((0, filters_1.matchesPrefix)(word, labelStr)) {
                            this.previouslyFocused = start;
                            this.list.setFocus([index]);
                            this.list.reveal(index);
                            return;
                        }
                        const fuzzy = (0, filters_1.matchesFuzzy2)(word, labelStr);
                        if (fuzzy) {
                            const fuzzyScore = fuzzy[0].end - fuzzy[0].start;
                            // ensures that when fuzzy matching, doesn't clash with prefix matching (1 input vs 1+ should be prefix and fuzzy respecitvely). Also makes sure that exact matches are prioritized.
                            if (fuzzyScore > 1 && fuzzy.length === 1) {
                                this.previouslyFocused = start;
                                this.list.setFocus([index]);
                                this.list.reveal(index);
                                return;
                            }
                        }
                    }
                }
                else if (typeof labelStr === 'undefined' || (0, filters_1.matchesPrefix)(word, labelStr)) {
                    this.previouslyFocused = start;
                    this.list.setFocus([index]);
                    this.list.reveal(index);
                    return;
                }
            }
        }
        dispose() {
            this.disable();
            this.enabledDisposables.dispose();
            this.disposables.dispose();
        }
    }
    class DOMFocusController {
        constructor(list, view) {
            this.list = list;
            this.view = view;
            this.disposables = new lifecycle_1.DisposableStore();
            const onKeyDown = event_2.Event.chain(this.disposables.add(new event_1.DomEmitter(view.domNode, 'keydown')).event, $ => $
                .filter(e => !isInputElement(e.target))
                .map(e => new keyboardEvent_1.StandardKeyboardEvent(e)));
            const onTab = event_2.Event.chain(onKeyDown, $ => $.filter(e => e.keyCode === 2 /* KeyCode.Tab */ && !e.ctrlKey && !e.metaKey && !e.shiftKey && !e.altKey));
            onTab(this.onTab, this, this.disposables);
        }
        onTab(e) {
            if (e.target !== this.view.domNode) {
                return;
            }
            const focus = this.list.getFocus();
            if (focus.length === 0) {
                return;
            }
            const focusedDomElement = this.view.domElement(focus[0]);
            if (!focusedDomElement) {
                return;
            }
            const tabIndexElement = focusedDomElement.querySelector('[tabIndex]');
            if (!tabIndexElement || !((0, dom_1.isHTMLElement)(tabIndexElement)) || tabIndexElement.tabIndex === -1) {
                return;
            }
            const style = (0, dom_1.getWindow)(tabIndexElement).getComputedStyle(tabIndexElement);
            if (style.visibility === 'hidden' || style.display === 'none') {
                return;
            }
            e.preventDefault();
            e.stopPropagation();
            tabIndexElement.focus();
        }
        dispose() {
            this.disposables.dispose();
        }
    }
    function isSelectionSingleChangeEvent(event) {
        return platform.isMacintosh ? event.browserEvent.metaKey : event.browserEvent.ctrlKey;
    }
    function isSelectionRangeChangeEvent(event) {
        return event.browserEvent.shiftKey;
    }
    function isMouseRightClick(event) {
        return (0, dom_1.isMouseEvent)(event) && event.button === 2;
    }
    const DefaultMultipleSelectionController = {
        isSelectionSingleChangeEvent,
        isSelectionRangeChangeEvent
    };
    class MouseController {
        constructor(list) {
            this.list = list;
            this.disposables = new lifecycle_1.DisposableStore();
            this._onPointer = new event_2.Emitter();
            this.onPointer = this._onPointer.event;
            if (list.options.multipleSelectionSupport !== false) {
                this.multipleSelectionController = this.list.options.multipleSelectionController || DefaultMultipleSelectionController;
            }
            this.mouseSupport = typeof list.options.mouseSupport === 'undefined' || !!list.options.mouseSupport;
            if (this.mouseSupport) {
                list.onMouseDown(this.onMouseDown, this, this.disposables);
                list.onContextMenu(this.onContextMenu, this, this.disposables);
                list.onMouseDblClick(this.onDoubleClick, this, this.disposables);
                list.onTouchStart(this.onMouseDown, this, this.disposables);
                this.disposables.add(touch_1.Gesture.addTarget(list.getHTMLElement()));
            }
            event_2.Event.any(list.onMouseClick, list.onMouseMiddleClick, list.onTap)(this.onViewPointer, this, this.disposables);
        }
        updateOptions(optionsUpdate) {
            if (optionsUpdate.multipleSelectionSupport !== undefined) {
                this.multipleSelectionController = undefined;
                if (optionsUpdate.multipleSelectionSupport) {
                    this.multipleSelectionController = this.list.options.multipleSelectionController || DefaultMultipleSelectionController;
                }
            }
        }
        isSelectionSingleChangeEvent(event) {
            if (!this.multipleSelectionController) {
                return false;
            }
            return this.multipleSelectionController.isSelectionSingleChangeEvent(event);
        }
        isSelectionRangeChangeEvent(event) {
            if (!this.multipleSelectionController) {
                return false;
            }
            return this.multipleSelectionController.isSelectionRangeChangeEvent(event);
        }
        isSelectionChangeEvent(event) {
            return this.isSelectionSingleChangeEvent(event) || this.isSelectionRangeChangeEvent(event);
        }
        onMouseDown(e) {
            if (isMonacoEditor(e.browserEvent.target)) {
                return;
            }
            if ((0, dom_1.getActiveElement)() !== e.browserEvent.target) {
                this.list.domFocus();
            }
        }
        onContextMenu(e) {
            if (isInputElement(e.browserEvent.target) || isMonacoEditor(e.browserEvent.target)) {
                return;
            }
            const focus = typeof e.index === 'undefined' ? [] : [e.index];
            this.list.setFocus(focus, e.browserEvent);
        }
        onViewPointer(e) {
            if (!this.mouseSupport) {
                return;
            }
            if (isInputElement(e.browserEvent.target) || isMonacoEditor(e.browserEvent.target)) {
                return;
            }
            if (e.browserEvent.isHandledByList) {
                return;
            }
            e.browserEvent.isHandledByList = true;
            const focus = e.index;
            if (typeof focus === 'undefined') {
                this.list.setFocus([], e.browserEvent);
                this.list.setSelection([], e.browserEvent);
                this.list.setAnchor(undefined);
                return;
            }
            if (this.isSelectionChangeEvent(e)) {
                return this.changeSelection(e);
            }
            this.list.setFocus([focus], e.browserEvent);
            this.list.setAnchor(focus);
            if (!isMouseRightClick(e.browserEvent)) {
                this.list.setSelection([focus], e.browserEvent);
            }
            this._onPointer.fire(e);
        }
        onDoubleClick(e) {
            if (isInputElement(e.browserEvent.target) || isMonacoEditor(e.browserEvent.target)) {
                return;
            }
            if (this.isSelectionChangeEvent(e)) {
                return;
            }
            if (e.browserEvent.isHandledByList) {
                return;
            }
            e.browserEvent.isHandledByList = true;
            const focus = this.list.getFocus();
            this.list.setSelection(focus, e.browserEvent);
        }
        changeSelection(e) {
            const focus = e.index;
            let anchor = this.list.getAnchor();
            if (this.isSelectionRangeChangeEvent(e)) {
                if (typeof anchor === 'undefined') {
                    const currentFocus = this.list.getFocus()[0];
                    anchor = currentFocus ?? focus;
                    this.list.setAnchor(anchor);
                }
                const min = Math.min(anchor, focus);
                const max = Math.max(anchor, focus);
                const rangeSelection = (0, arrays_1.range)(min, max + 1);
                const selection = this.list.getSelection();
                const contiguousRange = getContiguousRangeContaining(disjunction(selection, [anchor]), anchor);
                if (contiguousRange.length === 0) {
                    return;
                }
                const newSelection = disjunction(rangeSelection, relativeComplement(selection, contiguousRange));
                this.list.setSelection(newSelection, e.browserEvent);
                this.list.setFocus([focus], e.browserEvent);
            }
            else if (this.isSelectionSingleChangeEvent(e)) {
                const selection = this.list.getSelection();
                const newSelection = selection.filter(i => i !== focus);
                this.list.setFocus([focus]);
                this.list.setAnchor(focus);
                if (selection.length === newSelection.length) {
                    this.list.setSelection([...newSelection, focus], e.browserEvent);
                }
                else {
                    this.list.setSelection(newSelection, e.browserEvent);
                }
            }
        }
        dispose() {
            this.disposables.dispose();
        }
    }
    exports.MouseController = MouseController;
    class DefaultStyleController {
        constructor(styleElement, selectorSuffix) {
            this.styleElement = styleElement;
            this.selectorSuffix = selectorSuffix;
        }
        style(styles) {
            const suffix = this.selectorSuffix && `.${this.selectorSuffix}`;
            const content = [];
            if (styles.listBackground) {
                content.push(`.monaco-list${suffix} .monaco-list-rows { background: ${styles.listBackground}; }`);
            }
            if (styles.listFocusBackground) {
                content.push(`.monaco-list${suffix}:focus .monaco-list-row.focused { background-color: ${styles.listFocusBackground}; }`);
                content.push(`.monaco-list${suffix}:focus .monaco-list-row.focused:hover { background-color: ${styles.listFocusBackground}; }`); // overwrite :hover style in this case!
            }
            if (styles.listFocusForeground) {
                content.push(`.monaco-list${suffix}:focus .monaco-list-row.focused { color: ${styles.listFocusForeground}; }`);
            }
            if (styles.listActiveSelectionBackground) {
                content.push(`.monaco-list${suffix}:focus .monaco-list-row.selected { background-color: ${styles.listActiveSelectionBackground}; }`);
                content.push(`.monaco-list${suffix}:focus .monaco-list-row.selected:hover { background-color: ${styles.listActiveSelectionBackground}; }`); // overwrite :hover style in this case!
            }
            if (styles.listActiveSelectionForeground) {
                content.push(`.monaco-list${suffix}:focus .monaco-list-row.selected { color: ${styles.listActiveSelectionForeground}; }`);
            }
            if (styles.listActiveSelectionIconForeground) {
                content.push(`.monaco-list${suffix}:focus .monaco-list-row.selected .codicon { color: ${styles.listActiveSelectionIconForeground}; }`);
            }
            if (styles.listFocusAndSelectionBackground) {
                content.push(`
				.monaco-drag-image,
				.monaco-list${suffix}:focus .monaco-list-row.selected.focused { background-color: ${styles.listFocusAndSelectionBackground}; }
			`);
            }
            if (styles.listFocusAndSelectionForeground) {
                content.push(`
				.monaco-drag-image,
				.monaco-list${suffix}:focus .monaco-list-row.selected.focused { color: ${styles.listFocusAndSelectionForeground}; }
			`);
            }
            if (styles.listInactiveFocusForeground) {
                content.push(`.monaco-list${suffix} .monaco-list-row.focused { color:  ${styles.listInactiveFocusForeground}; }`);
                content.push(`.monaco-list${suffix} .monaco-list-row.focused:hover { color:  ${styles.listInactiveFocusForeground}; }`); // overwrite :hover style in this case!
            }
            if (styles.listInactiveSelectionIconForeground) {
                content.push(`.monaco-list${suffix} .monaco-list-row.focused .codicon { color:  ${styles.listInactiveSelectionIconForeground}; }`);
            }
            if (styles.listInactiveFocusBackground) {
                content.push(`.monaco-list${suffix} .monaco-list-row.focused { background-color:  ${styles.listInactiveFocusBackground}; }`);
                content.push(`.monaco-list${suffix} .monaco-list-row.focused:hover { background-color:  ${styles.listInactiveFocusBackground}; }`); // overwrite :hover style in this case!
            }
            if (styles.listInactiveSelectionBackground) {
                content.push(`.monaco-list${suffix} .monaco-list-row.selected { background-color:  ${styles.listInactiveSelectionBackground}; }`);
                content.push(`.monaco-list${suffix} .monaco-list-row.selected:hover { background-color:  ${styles.listInactiveSelectionBackground}; }`); // overwrite :hover style in this case!
            }
            if (styles.listInactiveSelectionForeground) {
                content.push(`.monaco-list${suffix} .monaco-list-row.selected { color: ${styles.listInactiveSelectionForeground}; }`);
            }
            if (styles.listHoverBackground) {
                content.push(`.monaco-list${suffix}:not(.drop-target):not(.dragging) .monaco-list-row:hover:not(.selected):not(.focused) { background-color: ${styles.listHoverBackground}; }`);
            }
            if (styles.listHoverForeground) {
                content.push(`.monaco-list${suffix}:not(.drop-target):not(.dragging) .monaco-list-row:hover:not(.selected):not(.focused) { color:  ${styles.listHoverForeground}; }`);
            }
            /**
             * Outlines
             */
            const focusAndSelectionOutline = (0, dom_1.asCssValueWithDefault)(styles.listFocusAndSelectionOutline, (0, dom_1.asCssValueWithDefault)(styles.listSelectionOutline, styles.listFocusOutline ?? ''));
            if (focusAndSelectionOutline) { // default: listFocusOutline
                content.push(`.monaco-list${suffix}:focus .monaco-list-row.focused.selected { outline: 1px solid ${focusAndSelectionOutline}; outline-offset: -1px;}`);
            }
            if (styles.listFocusOutline) { // default: set
                content.push(`
				.monaco-drag-image,
				.monaco-list${suffix}:focus .monaco-list-row.focused { outline: 1px solid ${styles.listFocusOutline}; outline-offset: -1px; }
				.monaco-workbench.context-menu-visible .monaco-list${suffix}.last-focused .monaco-list-row.focused { outline: 1px solid ${styles.listFocusOutline}; outline-offset: -1px; }
			`);
            }
            const inactiveFocusAndSelectionOutline = (0, dom_1.asCssValueWithDefault)(styles.listSelectionOutline, styles.listInactiveFocusOutline ?? '');
            if (inactiveFocusAndSelectionOutline) {
                content.push(`.monaco-list${suffix} .monaco-list-row.focused.selected { outline: 1px dotted ${inactiveFocusAndSelectionOutline}; outline-offset: -1px; }`);
            }
            if (styles.listSelectionOutline) { // default: activeContrastBorder
                content.push(`.monaco-list${suffix} .monaco-list-row.selected { outline: 1px dotted ${styles.listSelectionOutline}; outline-offset: -1px; }`);
            }
            if (styles.listInactiveFocusOutline) { // default: null
                content.push(`.monaco-list${suffix} .monaco-list-row.focused { outline: 1px dotted ${styles.listInactiveFocusOutline}; outline-offset: -1px; }`);
            }
            if (styles.listHoverOutline) { // default: activeContrastBorder
                content.push(`.monaco-list${suffix} .monaco-list-row:hover { outline: 1px dashed ${styles.listHoverOutline}; outline-offset: -1px; }`);
            }
            if (styles.listDropOverBackground) {
                content.push(`
				.monaco-list${suffix}.drop-target,
				.monaco-list${suffix} .monaco-list-rows.drop-target,
				.monaco-list${suffix} .monaco-list-row.drop-target { background-color: ${styles.listDropOverBackground} !important; color: inherit !important; }
			`);
            }
            if (styles.listDropBetweenBackground) {
                content.push(`
			.monaco-list${suffix} .monaco-list-rows.drop-target-before .monaco-list-row:first-child::before,
			.monaco-list${suffix} .monaco-list-row.drop-target-before::before {
				content: ""; position: absolute; top: 0px; left: 0px; width: 100%; height: 1px;
				background-color: ${styles.listDropBetweenBackground};
			}`);
                content.push(`
			.monaco-list${suffix} .monaco-list-rows.drop-target-after .monaco-list-row:last-child::after,
			.monaco-list${suffix} .monaco-list-row.drop-target-after::after {
				content: ""; position: absolute; bottom: 0px; left: 0px; width: 100%; height: 1px;
				background-color: ${styles.listDropBetweenBackground};
			}`);
            }
            if (styles.tableColumnsBorder) {
                content.push(`
				.monaco-table > .monaco-split-view2,
				.monaco-table > .monaco-split-view2 .monaco-sash.vertical::before,
				.monaco-workbench:not(.reduce-motion) .monaco-table:hover > .monaco-split-view2,
				.monaco-workbench:not(.reduce-motion) .monaco-table:hover > .monaco-split-view2 .monaco-sash.vertical::before {
					border-color: ${styles.tableColumnsBorder};
				}

				.monaco-workbench:not(.reduce-motion) .monaco-table > .monaco-split-view2,
				.monaco-workbench:not(.reduce-motion) .monaco-table > .monaco-split-view2 .monaco-sash.vertical::before {
					border-color: transparent;
				}
			`);
            }
            if (styles.tableOddRowsBackgroundColor) {
                content.push(`
				.monaco-table .monaco-list-row[data-parity=odd]:not(.focused):not(.selected):not(:hover) .monaco-table-tr,
				.monaco-table .monaco-list:not(:focus) .monaco-list-row[data-parity=odd].focused:not(.selected):not(:hover) .monaco-table-tr,
				.monaco-table .monaco-list:not(.focused) .monaco-list-row[data-parity=odd].focused:not(.selected):not(:hover) .monaco-table-tr {
					background-color: ${styles.tableOddRowsBackgroundColor};
				}
			`);
            }
            this.styleElement.textContent = content.join('\n');
        }
    }
    exports.DefaultStyleController = DefaultStyleController;
    exports.unthemedListStyles = {
        listFocusBackground: '#7FB0D0',
        listActiveSelectionBackground: '#0E639C',
        listActiveSelectionForeground: '#FFFFFF',
        listActiveSelectionIconForeground: '#FFFFFF',
        listFocusAndSelectionOutline: '#90C2F9',
        listFocusAndSelectionBackground: '#094771',
        listFocusAndSelectionForeground: '#FFFFFF',
        listInactiveSelectionBackground: '#3F3F46',
        listInactiveSelectionIconForeground: '#FFFFFF',
        listHoverBackground: '#2A2D2E',
        listDropOverBackground: '#383B3D',
        listDropBetweenBackground: '#EEEEEE',
        treeIndentGuidesStroke: '#a9a9a9',
        treeInactiveIndentGuidesStroke: color_1.Color.fromHex('#a9a9a9').transparent(0.4).toString(),
        tableColumnsBorder: color_1.Color.fromHex('#cccccc').transparent(0.2).toString(),
        tableOddRowsBackgroundColor: color_1.Color.fromHex('#cccccc').transparent(0.04).toString(),
        listBackground: undefined,
        listFocusForeground: undefined,
        listInactiveSelectionForeground: undefined,
        listInactiveFocusForeground: undefined,
        listInactiveFocusBackground: undefined,
        listHoverForeground: undefined,
        listFocusOutline: undefined,
        listInactiveFocusOutline: undefined,
        listSelectionOutline: undefined,
        listHoverOutline: undefined,
        treeStickyScrollBackground: undefined,
        treeStickyScrollBorder: undefined,
        treeStickyScrollShadow: undefined
    };
    const DefaultOptions = {
        keyboardSupport: true,
        mouseSupport: true,
        multipleSelectionSupport: true,
        dnd: {
            getDragURI() { return null; },
            onDragStart() { },
            onDragOver() { return false; },
            drop() { },
            dispose() { }
        }
    };
    // TODO@Joao: move these utils into a SortedArray class
    function getContiguousRangeContaining(range, value) {
        const index = range.indexOf(value);
        if (index === -1) {
            return [];
        }
        const result = [];
        let i = index - 1;
        while (i >= 0 && range[i] === value - (index - i)) {
            result.push(range[i--]);
        }
        result.reverse();
        i = index;
        while (i < range.length && range[i] === value + (i - index)) {
            result.push(range[i++]);
        }
        return result;
    }
    /**
     * Given two sorted collections of numbers, returns the intersection
     * between them (OR).
     */
    function disjunction(one, other) {
        const result = [];
        let i = 0, j = 0;
        while (i < one.length || j < other.length) {
            if (i >= one.length) {
                result.push(other[j++]);
            }
            else if (j >= other.length) {
                result.push(one[i++]);
            }
            else if (one[i] === other[j]) {
                result.push(one[i]);
                i++;
                j++;
                continue;
            }
            else if (one[i] < other[j]) {
                result.push(one[i++]);
            }
            else {
                result.push(other[j++]);
            }
        }
        return result;
    }
    /**
     * Given two sorted collections of numbers, returns the relative
     * complement between them (XOR).
     */
    function relativeComplement(one, other) {
        const result = [];
        let i = 0, j = 0;
        while (i < one.length || j < other.length) {
            if (i >= one.length) {
                result.push(other[j++]);
            }
            else if (j >= other.length) {
                result.push(one[i++]);
            }
            else if (one[i] === other[j]) {
                i++;
                j++;
                continue;
            }
            else if (one[i] < other[j]) {
                result.push(one[i++]);
            }
            else {
                j++;
            }
        }
        return result;
    }
    const numericSort = (a, b) => a - b;
    class PipelineRenderer {
        constructor(_templateId, renderers) {
            this._templateId = _templateId;
            this.renderers = renderers;
        }
        get templateId() {
            return this._templateId;
        }
        renderTemplate(container) {
            return this.renderers.map(r => r.renderTemplate(container));
        }
        renderElement(element, index, templateData, height) {
            let i = 0;
            for (const renderer of this.renderers) {
                renderer.renderElement(element, index, templateData[i++], height);
            }
        }
        disposeElement(element, index, templateData, height) {
            let i = 0;
            for (const renderer of this.renderers) {
                renderer.disposeElement?.(element, index, templateData[i], height);
                i += 1;
            }
        }
        disposeTemplate(templateData) {
            let i = 0;
            for (const renderer of this.renderers) {
                renderer.disposeTemplate(templateData[i++]);
            }
        }
    }
    class AccessibiltyRenderer {
        constructor(accessibilityProvider) {
            this.accessibilityProvider = accessibilityProvider;
            this.templateId = 'a18n';
        }
        renderTemplate(container) {
            return { container, disposables: new lifecycle_1.DisposableStore() };
        }
        renderElement(element, index, data) {
            const ariaLabel = this.accessibilityProvider.getAriaLabel(element);
            const observable = (ariaLabel && typeof ariaLabel !== 'string') ? ariaLabel : (0, observable_1.constObservable)(ariaLabel);
            data.disposables.add((0, observable_1.autorun)(reader => {
                this.setAriaLabel(reader.readObservable(observable), data.container);
            }));
            const ariaLevel = this.accessibilityProvider.getAriaLevel && this.accessibilityProvider.getAriaLevel(element);
            if (typeof ariaLevel === 'number') {
                data.container.setAttribute('aria-level', `${ariaLevel}`);
            }
            else {
                data.container.removeAttribute('aria-level');
            }
        }
        setAriaLabel(ariaLabel, element) {
            if (ariaLabel) {
                element.setAttribute('aria-label', ariaLabel);
            }
            else {
                element.removeAttribute('aria-label');
            }
        }
        disposeElement(element, index, templateData, height) {
            templateData.disposables.clear();
        }
        disposeTemplate(templateData) {
            templateData.disposables.dispose();
        }
    }
    class ListViewDragAndDrop {
        constructor(list, dnd) {
            this.list = list;
            this.dnd = dnd;
        }
        getDragElements(element) {
            const selection = this.list.getSelectedElements();
            const elements = selection.indexOf(element) > -1 ? selection : [element];
            return elements;
        }
        getDragURI(element) {
            return this.dnd.getDragURI(element);
        }
        getDragLabel(elements, originalEvent) {
            if (this.dnd.getDragLabel) {
                return this.dnd.getDragLabel(elements, originalEvent);
            }
            return undefined;
        }
        onDragStart(data, originalEvent) {
            this.dnd.onDragStart?.(data, originalEvent);
        }
        onDragOver(data, targetElement, targetIndex, targetSector, originalEvent) {
            return this.dnd.onDragOver(data, targetElement, targetIndex, targetSector, originalEvent);
        }
        onDragLeave(data, targetElement, targetIndex, originalEvent) {
            this.dnd.onDragLeave?.(data, targetElement, targetIndex, originalEvent);
        }
        onDragEnd(originalEvent) {
            this.dnd.onDragEnd?.(originalEvent);
        }
        drop(data, targetElement, targetIndex, targetSector, originalEvent) {
            this.dnd.drop(data, targetElement, targetIndex, targetSector, originalEvent);
        }
        dispose() {
            this.dnd.dispose();
        }
    }
    /**
     * The {@link List} is a virtual scrolling widget, built on top of the {@link ListView}
     * widget.
     *
     * Features:
     * - Customizable keyboard and mouse support
     * - Element traits: focus, selection, achor
     * - Accessibility support
     * - Touch support
     * - Performant template-based rendering
     * - Horizontal scrolling
     * - Variable element height support
     * - Dynamic element height support
     * - Drag-and-drop support
     */
    class List {
        get onDidChangeFocus() {
            return event_2.Event.map(this.eventBufferer.wrapEvent(this.focus.onChange), e => this.toListEvent(e), this.disposables);
        }
        get onDidChangeSelection() {
            return event_2.Event.map(this.eventBufferer.wrapEvent(this.selection.onChange), e => this.toListEvent(e), this.disposables);
        }
        get domId() { return this.view.domId; }
        get onDidScroll() { return this.view.onDidScroll; }
        get onMouseClick() { return this.view.onMouseClick; }
        get onMouseDblClick() { return this.view.onMouseDblClick; }
        get onMouseMiddleClick() { return this.view.onMouseMiddleClick; }
        get onPointer() { return this.mouseController.onPointer; }
        get onMouseDown() { return this.view.onMouseDown; }
        get onMouseOver() { return this.view.onMouseOver; }
        get onMouseOut() { return this.view.onMouseOut; }
        get onTouchStart() { return this.view.onTouchStart; }
        get onTap() { return this.view.onTap; }
        /**
         * Possible context menu trigger events:
         * - ContextMenu key
         * - Shift F10
         * - Ctrl Option Shift M (macOS with VoiceOver)
         * - Mouse right click
         */
        get onContextMenu() {
            let didJustPressContextMenuKey = false;
            const fromKeyDown = event_2.Event.chain(this.disposables.add(new event_1.DomEmitter(this.view.domNode, 'keydown')).event, $ => $.map(e => new keyboardEvent_1.StandardKeyboardEvent(e))
                .filter(e => didJustPressContextMenuKey = e.keyCode === 58 /* KeyCode.ContextMenu */ || (e.shiftKey && e.keyCode === 68 /* KeyCode.F10 */))
                .map(e => dom_1.EventHelper.stop(e, true))
                .filter(() => false));
            const fromKeyUp = event_2.Event.chain(this.disposables.add(new event_1.DomEmitter(this.view.domNode, 'keyup')).event, $ => $.forEach(() => didJustPressContextMenuKey = false)
                .map(e => new keyboardEvent_1.StandardKeyboardEvent(e))
                .filter(e => e.keyCode === 58 /* KeyCode.ContextMenu */ || (e.shiftKey && e.keyCode === 68 /* KeyCode.F10 */))
                .map(e => dom_1.EventHelper.stop(e, true))
                .map(({ browserEvent }) => {
                const focus = this.getFocus();
                const index = focus.length ? focus[0] : undefined;
                const element = typeof index !== 'undefined' ? this.view.element(index) : undefined;
                const anchor = typeof index !== 'undefined' ? this.view.domElement(index) : this.view.domNode;
                return { index, element, anchor, browserEvent };
            }));
            const fromMouse = event_2.Event.chain(this.view.onContextMenu, $ => $.filter(_ => !didJustPressContextMenuKey)
                .map(({ element, index, browserEvent }) => ({ element, index, anchor: new mouseEvent_1.StandardMouseEvent((0, dom_1.getWindow)(this.view.domNode), browserEvent), browserEvent })));
            return event_2.Event.any(fromKeyDown, fromKeyUp, fromMouse);
        }
        get onKeyDown() { return this.disposables.add(new event_1.DomEmitter(this.view.domNode, 'keydown')).event; }
        get onDidFocus() { return event_2.Event.signal(this.disposables.add(new event_1.DomEmitter(this.view.domNode, 'focus', true)).event); }
        get onDidBlur() { return event_2.Event.signal(this.disposables.add(new event_1.DomEmitter(this.view.domNode, 'blur', true)).event); }
        constructor(user, container, virtualDelegate, renderers, _options = DefaultOptions) {
            this.user = user;
            this._options = _options;
            this.focus = new Trait('focused');
            this.anchor = new Trait('anchor');
            this.eventBufferer = new event_2.EventBufferer();
            this._ariaLabel = '';
            this.disposables = new lifecycle_1.DisposableStore();
            this._onDidDispose = new event_2.Emitter();
            this.onDidDispose = this._onDidDispose.event;
            const role = this._options.accessibilityProvider && this._options.accessibilityProvider.getWidgetRole ? this._options.accessibilityProvider?.getWidgetRole() : 'list';
            this.selection = new SelectionTrait(role !== 'listbox');
            const baseRenderers = [this.focus.renderer, this.selection.renderer];
            this.accessibilityProvider = _options.accessibilityProvider;
            if (this.accessibilityProvider) {
                baseRenderers.push(new AccessibiltyRenderer(this.accessibilityProvider));
                this.accessibilityProvider.onDidChangeActiveDescendant?.(this.onDidChangeActiveDescendant, this, this.disposables);
            }
            renderers = renderers.map(r => new PipelineRenderer(r.templateId, [...baseRenderers, r]));
            const viewOptions = {
                ..._options,
                dnd: _options.dnd && new ListViewDragAndDrop(this, _options.dnd)
            };
            this.view = this.createListView(container, virtualDelegate, renderers, viewOptions);
            this.view.domNode.setAttribute('role', role);
            if (_options.styleController) {
                this.styleController = _options.styleController(this.view.domId);
            }
            else {
                const styleElement = (0, dom_1.createStyleSheet)(this.view.domNode);
                this.styleController = new DefaultStyleController(styleElement, this.view.domId);
            }
            this.spliceable = new splice_1.CombinedSpliceable([
                new TraitSpliceable(this.focus, this.view, _options.identityProvider),
                new TraitSpliceable(this.selection, this.view, _options.identityProvider),
                new TraitSpliceable(this.anchor, this.view, _options.identityProvider),
                this.view
            ]);
            this.disposables.add(this.focus);
            this.disposables.add(this.selection);
            this.disposables.add(this.anchor);
            this.disposables.add(this.view);
            this.disposables.add(this._onDidDispose);
            this.disposables.add(new DOMFocusController(this, this.view));
            if (typeof _options.keyboardSupport !== 'boolean' || _options.keyboardSupport) {
                this.keyboardController = new KeyboardController(this, this.view, _options);
                this.disposables.add(this.keyboardController);
            }
            if (_options.keyboardNavigationLabelProvider) {
                const delegate = _options.keyboardNavigationDelegate || exports.DefaultKeyboardNavigationDelegate;
                this.typeNavigationController = new TypeNavigationController(this, this.view, _options.keyboardNavigationLabelProvider, _options.keyboardNavigationEventFilter ?? (() => true), delegate);
                this.disposables.add(this.typeNavigationController);
            }
            this.mouseController = this.createMouseController(_options);
            this.disposables.add(this.mouseController);
            this.onDidChangeFocus(this._onFocusChange, this, this.disposables);
            this.onDidChangeSelection(this._onSelectionChange, this, this.disposables);
            if (this.accessibilityProvider) {
                this.ariaLabel = this.accessibilityProvider.getWidgetAriaLabel();
            }
            if (this._options.multipleSelectionSupport !== false) {
                this.view.domNode.setAttribute('aria-multiselectable', 'true');
            }
        }
        createListView(container, virtualDelegate, renderers, viewOptions) {
            return new listView_1.ListView(container, virtualDelegate, renderers, viewOptions);
        }
        createMouseController(options) {
            return new MouseController(this);
        }
        updateOptions(optionsUpdate = {}) {
            this._options = { ...this._options, ...optionsUpdate };
            this.typeNavigationController?.updateOptions(this._options);
            if (this._options.multipleSelectionController !== undefined) {
                if (this._options.multipleSelectionSupport) {
                    this.view.domNode.setAttribute('aria-multiselectable', 'true');
                }
                else {
                    this.view.domNode.removeAttribute('aria-multiselectable');
                }
            }
            this.mouseController.updateOptions(optionsUpdate);
            this.keyboardController?.updateOptions(optionsUpdate);
            this.view.updateOptions(optionsUpdate);
        }
        get options() {
            return this._options;
        }
        splice(start, deleteCount, elements = []) {
            if (start < 0 || start > this.view.length) {
                throw new list_1.ListError(this.user, `Invalid start index: ${start}`);
            }
            if (deleteCount < 0) {
                throw new list_1.ListError(this.user, `Invalid delete count: ${deleteCount}`);
            }
            if (deleteCount === 0 && elements.length === 0) {
                return;
            }
            this.eventBufferer.bufferEvents(() => this.spliceable.splice(start, deleteCount, elements));
        }
        rerender() {
            this.view.rerender();
        }
        element(index) {
            return this.view.element(index);
        }
        indexOf(element) {
            return this.view.indexOf(element);
        }
        indexAt(position) {
            return this.view.indexAt(position);
        }
        get length() {
            return this.view.length;
        }
        get contentHeight() {
            return this.view.contentHeight;
        }
        get onDidChangeContentHeight() {
            return this.view.onDidChangeContentHeight;
        }
        get scrollTop() {
            return this.view.getScrollTop();
        }
        set scrollTop(scrollTop) {
            this.view.setScrollTop(scrollTop);
        }
        get scrollHeight() {
            return this.view.scrollHeight;
        }
        get renderHeight() {
            return this.view.renderHeight;
        }
        get firstVisibleIndex() {
            return this.view.firstVisibleIndex;
        }
        get ariaLabel() {
            return this._ariaLabel;
        }
        set ariaLabel(value) {
            this._ariaLabel = value;
            this.view.domNode.setAttribute('aria-label', value);
        }
        domFocus() {
            this.view.domNode.focus({ preventScroll: true });
        }
        layout(height, width) {
            this.view.layout(height, width);
        }
        setSelection(indexes, browserEvent) {
            for (const index of indexes) {
                if (index < 0 || index >= this.length) {
                    throw new list_1.ListError(this.user, `Invalid index ${index}`);
                }
            }
            this.selection.set(indexes, browserEvent);
        }
        getSelection() {
            return this.selection.get();
        }
        getSelectedElements() {
            return this.getSelection().map(i => this.view.element(i));
        }
        setAnchor(index) {
            if (typeof index === 'undefined') {
                this.anchor.set([]);
                return;
            }
            if (index < 0 || index >= this.length) {
                throw new list_1.ListError(this.user, `Invalid index ${index}`);
            }
            this.anchor.set([index]);
        }
        getAnchor() {
            return (0, arrays_1.firstOrDefault)(this.anchor.get(), undefined);
        }
        getAnchorElement() {
            const anchor = this.getAnchor();
            return typeof anchor === 'undefined' ? undefined : this.element(anchor);
        }
        setFocus(indexes, browserEvent) {
            for (const index of indexes) {
                if (index < 0 || index >= this.length) {
                    throw new list_1.ListError(this.user, `Invalid index ${index}`);
                }
            }
            this.focus.set(indexes, browserEvent);
        }
        focusNext(n = 1, loop = false, browserEvent, filter) {
            if (this.length === 0) {
                return;
            }
            const focus = this.focus.get();
            const index = this.findNextIndex(focus.length > 0 ? focus[0] + n : 0, loop, filter);
            if (index > -1) {
                this.setFocus([index], browserEvent);
            }
        }
        focusPrevious(n = 1, loop = false, browserEvent, filter) {
            if (this.length === 0) {
                return;
            }
            const focus = this.focus.get();
            const index = this.findPreviousIndex(focus.length > 0 ? focus[0] - n : 0, loop, filter);
            if (index > -1) {
                this.setFocus([index], browserEvent);
            }
        }
        async focusNextPage(browserEvent, filter) {
            let lastPageIndex = this.view.indexAt(this.view.getScrollTop() + this.view.renderHeight);
            lastPageIndex = lastPageIndex === 0 ? 0 : lastPageIndex - 1;
            const currentlyFocusedElementIndex = this.getFocus()[0];
            if (currentlyFocusedElementIndex !== lastPageIndex && (currentlyFocusedElementIndex === undefined || lastPageIndex > currentlyFocusedElementIndex)) {
                const lastGoodPageIndex = this.findPreviousIndex(lastPageIndex, false, filter);
                if (lastGoodPageIndex > -1 && currentlyFocusedElementIndex !== lastGoodPageIndex) {
                    this.setFocus([lastGoodPageIndex], browserEvent);
                }
                else {
                    this.setFocus([lastPageIndex], browserEvent);
                }
            }
            else {
                const previousScrollTop = this.view.getScrollTop();
                let nextpageScrollTop = previousScrollTop + this.view.renderHeight;
                if (lastPageIndex > currentlyFocusedElementIndex) {
                    // scroll last page element to the top only if the last page element is below the focused element
                    nextpageScrollTop -= this.view.elementHeight(lastPageIndex);
                }
                this.view.setScrollTop(nextpageScrollTop);
                if (this.view.getScrollTop() !== previousScrollTop) {
                    this.setFocus([]);
                    // Let the scroll event listener run
                    await (0, async_1.timeout)(0);
                    await this.focusNextPage(browserEvent, filter);
                }
            }
        }
        async focusPreviousPage(browserEvent, filter, getPaddingTop = () => 0) {
            let firstPageIndex;
            const paddingTop = getPaddingTop();
            const scrollTop = this.view.getScrollTop() + paddingTop;
            if (scrollTop === 0) {
                firstPageIndex = this.view.indexAt(scrollTop);
            }
            else {
                firstPageIndex = this.view.indexAfter(scrollTop - 1);
            }
            const currentlyFocusedElementIndex = this.getFocus()[0];
            if (currentlyFocusedElementIndex !== firstPageIndex && (currentlyFocusedElementIndex === undefined || currentlyFocusedElementIndex >= firstPageIndex)) {
                const firstGoodPageIndex = this.findNextIndex(firstPageIndex, false, filter);
                if (firstGoodPageIndex > -1 && currentlyFocusedElementIndex !== firstGoodPageIndex) {
                    this.setFocus([firstGoodPageIndex], browserEvent);
                }
                else {
                    this.setFocus([firstPageIndex], browserEvent);
                }
            }
            else {
                const previousScrollTop = scrollTop;
                this.view.setScrollTop(scrollTop - this.view.renderHeight - paddingTop);
                if (this.view.getScrollTop() + getPaddingTop() !== previousScrollTop) {
                    this.setFocus([]);
                    // Let the scroll event listener run
                    await (0, async_1.timeout)(0);
                    await this.focusPreviousPage(browserEvent, filter, getPaddingTop);
                }
            }
        }
        focusLast(browserEvent, filter) {
            if (this.length === 0) {
                return;
            }
            const index = this.findPreviousIndex(this.length - 1, false, filter);
            if (index > -1) {
                this.setFocus([index], browserEvent);
            }
        }
        focusFirst(browserEvent, filter) {
            this.focusNth(0, browserEvent, filter);
        }
        focusNth(n, browserEvent, filter) {
            if (this.length === 0) {
                return;
            }
            const index = this.findNextIndex(n, false, filter);
            if (index > -1) {
                this.setFocus([index], browserEvent);
            }
        }
        findNextIndex(index, loop = false, filter) {
            for (let i = 0; i < this.length; i++) {
                if (index >= this.length && !loop) {
                    return -1;
                }
                index = index % this.length;
                if (!filter || filter(this.element(index))) {
                    return index;
                }
                index++;
            }
            return -1;
        }
        findPreviousIndex(index, loop = false, filter) {
            for (let i = 0; i < this.length; i++) {
                if (index < 0 && !loop) {
                    return -1;
                }
                index = (this.length + (index % this.length)) % this.length;
                if (!filter || filter(this.element(index))) {
                    return index;
                }
                index--;
            }
            return -1;
        }
        getFocus() {
            return this.focus.get();
        }
        getFocusedElements() {
            return this.getFocus().map(i => this.view.element(i));
        }
        reveal(index, relativeTop, paddingTop = 0) {
            if (index < 0 || index >= this.length) {
                throw new list_1.ListError(this.user, `Invalid index ${index}`);
            }
            const scrollTop = this.view.getScrollTop();
            const elementTop = this.view.elementTop(index);
            const elementHeight = this.view.elementHeight(index);
            if ((0, types_1.isNumber)(relativeTop)) {
                // y = mx + b
                const m = elementHeight - this.view.renderHeight + paddingTop;
                this.view.setScrollTop(m * (0, numbers_1.clamp)(relativeTop, 0, 1) + elementTop - paddingTop);
            }
            else {
                const viewItemBottom = elementTop + elementHeight;
                const scrollBottom = scrollTop + this.view.renderHeight;
                if (elementTop < scrollTop + paddingTop && viewItemBottom >= scrollBottom) {
                    // The element is already overflowing the viewport, no-op
                }
                else if (elementTop < scrollTop + paddingTop || (viewItemBottom >= scrollBottom && elementHeight >= this.view.renderHeight)) {
                    this.view.setScrollTop(elementTop - paddingTop);
                }
                else if (viewItemBottom >= scrollBottom) {
                    this.view.setScrollTop(viewItemBottom - this.view.renderHeight);
                }
            }
        }
        /**
         * Returns the relative position of an element rendered in the list.
         * Returns `null` if the element isn't *entirely* in the visible viewport.
         */
        getRelativeTop(index, paddingTop = 0) {
            if (index < 0 || index >= this.length) {
                throw new list_1.ListError(this.user, `Invalid index ${index}`);
            }
            const scrollTop = this.view.getScrollTop();
            const elementTop = this.view.elementTop(index);
            const elementHeight = this.view.elementHeight(index);
            if (elementTop < scrollTop + paddingTop || elementTop + elementHeight > scrollTop + this.view.renderHeight) {
                return null;
            }
            // y = mx + b
            const m = elementHeight - this.view.renderHeight + paddingTop;
            return Math.abs((scrollTop + paddingTop - elementTop) / m);
        }
        getHTMLElement() {
            return this.view.domNode;
        }
        getScrollableElement() {
            return this.view.scrollableElementDomNode;
        }
        getElementID(index) {
            return this.view.getElementDomId(index);
        }
        getElementTop(index) {
            return this.view.elementTop(index);
        }
        style(styles) {
            this.styleController.style(styles);
        }
        toListEvent({ indexes, browserEvent }) {
            return { indexes, elements: indexes.map(i => this.view.element(i)), browserEvent };
        }
        _onFocusChange() {
            const focus = this.focus.get();
            this.view.domNode.classList.toggle('element-focused', focus.length > 0);
            this.onDidChangeActiveDescendant();
        }
        onDidChangeActiveDescendant() {
            const focus = this.focus.get();
            if (focus.length > 0) {
                let id;
                if (this.accessibilityProvider?.getActiveDescendantId) {
                    id = this.accessibilityProvider.getActiveDescendantId(this.view.element(focus[0]));
                }
                this.view.domNode.setAttribute('aria-activedescendant', id || this.view.getElementDomId(focus[0]));
            }
            else {
                this.view.domNode.removeAttribute('aria-activedescendant');
            }
        }
        _onSelectionChange() {
            const selection = this.selection.get();
            this.view.domNode.classList.toggle('selection-none', selection.length === 0);
            this.view.domNode.classList.toggle('selection-single', selection.length === 1);
            this.view.domNode.classList.toggle('selection-multiple', selection.length > 1);
        }
        dispose() {
            this._onDidDispose.fire();
            this.disposables.dispose();
            this._onDidDispose.dispose();
        }
    }
    exports.List = List;
    __decorate([
        decorators_1.memoize
    ], List.prototype, "onDidChangeFocus", null);
    __decorate([
        decorators_1.memoize
    ], List.prototype, "onDidChangeSelection", null);
    __decorate([
        decorators_1.memoize
    ], List.prototype, "onContextMenu", null);
    __decorate([
        decorators_1.memoize
    ], List.prototype, "onKeyDown", null);
    __decorate([
        decorators_1.memoize
    ], List.prototype, "onDidFocus", null);
    __decorate([
        decorators_1.memoize
    ], List.prototype, "onDidBlur", null);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[637/*vs/base/browser/ui/list/listPaging*/], __M([1/*require*/,0/*exports*/,13/*vs/base/common/arrays*/,18/*vs/base/common/cancellation*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,115/*vs/base/browser/ui/list/listWidget*/,305/*vs/css!vs/base/browser/ui/list/list*/]), function (require, exports, arrays_1, cancellation_1, event_1, lifecycle_1, listWidget_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.PagedList = void 0;
    class PagedRenderer {
        get templateId() { return this.renderer.templateId; }
        constructor(renderer, modelProvider) {
            this.renderer = renderer;
            this.modelProvider = modelProvider;
        }
        renderTemplate(container) {
            const data = this.renderer.renderTemplate(container);
            return { data, disposable: lifecycle_1.Disposable.None };
        }
        renderElement(index, _, data, height) {
            data.disposable?.dispose();
            if (!data.data) {
                return;
            }
            const model = this.modelProvider();
            if (model.isResolved(index)) {
                return this.renderer.renderElement(model.get(index), index, data.data, height);
            }
            const cts = new cancellation_1.CancellationTokenSource();
            const promise = model.resolve(index, cts.token);
            data.disposable = { dispose: () => cts.cancel() };
            this.renderer.renderPlaceholder(index, data.data);
            promise.then(entry => this.renderer.renderElement(entry, index, data.data, height));
        }
        disposeTemplate(data) {
            if (data.disposable) {
                data.disposable.dispose();
                data.disposable = undefined;
            }
            if (data.data) {
                this.renderer.disposeTemplate(data.data);
                data.data = undefined;
            }
        }
    }
    class PagedAccessibilityProvider {
        constructor(modelProvider, accessibilityProvider) {
            this.modelProvider = modelProvider;
            this.accessibilityProvider = accessibilityProvider;
        }
        getWidgetAriaLabel() {
            return this.accessibilityProvider.getWidgetAriaLabel();
        }
        getAriaLabel(index) {
            const model = this.modelProvider();
            if (!model.isResolved(index)) {
                return null;
            }
            return this.accessibilityProvider.getAriaLabel(model.get(index));
        }
    }
    function fromPagedListOptions(modelProvider, options) {
        return {
            ...options,
            accessibilityProvider: options.accessibilityProvider && new PagedAccessibilityProvider(modelProvider, options.accessibilityProvider)
        };
    }
    class PagedList {
        constructor(user, container, virtualDelegate, renderers, options = {}) {
            const modelProvider = () => this.model;
            const pagedRenderers = renderers.map(r => new PagedRenderer(r, modelProvider));
            this.list = new listWidget_1.List(user, container, virtualDelegate, pagedRenderers, fromPagedListOptions(modelProvider, options));
        }
        updateOptions(options) {
            this.list.updateOptions(options);
        }
        getHTMLElement() {
            return this.list.getHTMLElement();
        }
        get onDidFocus() {
            return this.list.onDidFocus;
        }
        get widget() {
            return this.list;
        }
        get onDidDispose() {
            return this.list.onDidDispose;
        }
        get onMouseDblClick() {
            return event_1.Event.map(this.list.onMouseDblClick, ({ element, index, browserEvent }) => ({ element: element === undefined ? undefined : this._model.get(element), index, browserEvent }));
        }
        get onPointer() {
            return event_1.Event.map(this.list.onPointer, ({ element, index, browserEvent }) => ({ element: element === undefined ? undefined : this._model.get(element), index, browserEvent }));
        }
        get onDidChangeSelection() {
            return event_1.Event.map(this.list.onDidChangeSelection, ({ elements, indexes, browserEvent }) => ({ elements: elements.map(e => this._model.get(e)), indexes, browserEvent }));
        }
        get model() {
            return this._model;
        }
        set model(model) {
            this._model = model;
            this.list.splice(0, this.list.length, (0, arrays_1.range)(model.length));
        }
        getFocus() {
            return this.list.getFocus();
        }
        getSelection() {
            return this.list.getSelection();
        }
        getSelectedElements() {
            return this.getSelection().map(i => this.model.get(i));
        }
        style(styles) {
            this.list.style(styles);
        }
        dispose() {
            this.list.dispose();
        }
    }
    exports.PagedList = PagedList;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[357/*vs/base/browser/ui/splitview/splitview*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,93/*vs/base/browser/event*/,173/*vs/base/browser/ui/sash/sash*/,86/*vs/base/browser/ui/scrollbar/scrollableElement*/,13/*vs/base/common/arrays*/,33/*vs/base/common/color*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,141/*vs/base/common/numbers*/,163/*vs/base/common/scrollable*/,19/*vs/base/common/types*/,474/*vs/css!vs/base/browser/ui/splitview/splitview*/]), function (require, exports, dom_1, event_1, sash_1, scrollableElement_1, arrays_1, color_1, event_2, lifecycle_1, numbers_1, scrollable_1, types) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SplitView = exports.Sizing = void 0;
    const defaultStyles = {
        separatorBorder: color_1.Color.transparent
    };
    class ViewItem {
        set size(size) {
            this._size = size;
        }
        get size() {
            return this._size;
        }
        get visible() {
            return typeof this._cachedVisibleSize === 'undefined';
        }
        setVisible(visible, size) {
            if (visible === this.visible) {
                return;
            }
            if (visible) {
                this.size = (0, numbers_1.clamp)(this._cachedVisibleSize, this.viewMinimumSize, this.viewMaximumSize);
                this._cachedVisibleSize = undefined;
            }
            else {
                this._cachedVisibleSize = typeof size === 'number' ? size : this.size;
                this.size = 0;
            }
            this.container.classList.toggle('visible', visible);
            try {
                this.view.setVisible?.(visible);
            }
            catch (e) {
                console.error('Splitview: Failed to set visible view');
                console.error(e);
            }
        }
        get minimumSize() { return this.visible ? this.view.minimumSize : 0; }
        get viewMinimumSize() { return this.view.minimumSize; }
        get maximumSize() { return this.visible ? this.view.maximumSize : 0; }
        get viewMaximumSize() { return this.view.maximumSize; }
        get priority() { return this.view.priority; }
        get proportionalLayout() { return this.view.proportionalLayout ?? true; }
        get snap() { return !!this.view.snap; }
        set enabled(enabled) {
            this.container.style.pointerEvents = enabled ? '' : 'none';
        }
        constructor(container, view, size, disposable) {
            this.container = container;
            this.view = view;
            this.disposable = disposable;
            this._cachedVisibleSize = undefined;
            if (typeof size === 'number') {
                this._size = size;
                this._cachedVisibleSize = undefined;
                container.classList.add('visible');
            }
            else {
                this._size = 0;
                this._cachedVisibleSize = size.cachedVisibleSize;
            }
        }
        layout(offset, layoutContext) {
            this.layoutContainer(offset);
            try {
                this.view.layout(this.size, offset, layoutContext);
            }
            catch (e) {
                console.error('Splitview: Failed to layout view');
                console.error(e);
            }
        }
        dispose() {
            this.disposable.dispose();
        }
    }
    class VerticalViewItem extends ViewItem {
        layoutContainer(offset) {
            this.container.style.top = `${offset}px`;
            this.container.style.height = `${this.size}px`;
        }
    }
    class HorizontalViewItem extends ViewItem {
        layoutContainer(offset) {
            this.container.style.left = `${offset}px`;
            this.container.style.width = `${this.size}px`;
        }
    }
    var State;
    (function (State) {
        State[State["Idle"] = 0] = "Idle";
        State[State["Busy"] = 1] = "Busy";
    })(State || (State = {}));
    var Sizing;
    (function (Sizing) {
        /**
         * When adding or removing views, distribute the delta space among
         * all other views.
         */
        Sizing.Distribute = { type: 'distribute' };
        /**
         * When adding or removing views, split the delta space with another
         * specific view, indexed by the provided `index`.
         */
        function Split(index) { return { type: 'split', index }; }
        Sizing.Split = Split;
        /**
         * When adding a view, use DistributeSizing when all pre-existing views are
         * distributed evenly, otherwise use SplitSizing.
         */
        function Auto(index) { return { type: 'auto', index }; }
        Sizing.Auto = Auto;
        /**
         * When adding or removing views, assume the view is invisible.
         */
        function Invisible(cachedVisibleSize) { return { type: 'invisible', cachedVisibleSize }; }
        Sizing.Invisible = Invisible;
    })(Sizing || (exports.Sizing = Sizing = {}));
    /**
     * The {@link SplitView} is the UI component which implements a one dimensional
     * flex-like layout algorithm for a collection of {@link IView} instances, which
     * are essentially HTMLElement instances with the following size constraints:
     *
     * - {@link IView.minimumSize}
     * - {@link IView.maximumSize}
     * - {@link IView.priority}
     * - {@link IView.snap}
     *
     * In case the SplitView doesn't have enough size to fit all views, it will overflow
     * its content with a scrollbar.
     *
     * In between each pair of views there will be a {@link Sash} allowing the user
     * to resize the views, making sure the constraints are respected.
     *
     * An optional {@link TLayoutContext layout context type} may be used in order to
     * pass along layout contextual data from the {@link SplitView.layout} method down
     * to each view's {@link IView.layout} calls.
     *
     * Features:
     * - Flex-like layout algorithm
     * - Snap support
     * - Orthogonal sash support, for corner sashes
     * - View hide/show support
     * - View swap/move support
     * - Alt key modifier behavior, macOS style
     */
    class SplitView extends lifecycle_1.Disposable {
        get orthogonalStartSash() { return this._orthogonalStartSash; }
        get orthogonalEndSash() { return this._orthogonalEndSash; }
        get startSnappingEnabled() { return this._startSnappingEnabled; }
        get endSnappingEnabled() { return this._endSnappingEnabled; }
        /**
         * A reference to a sash, perpendicular to all sashes in this {@link SplitView},
         * located at the left- or top-most side of the SplitView.
         * Corner sashes will be created automatically at the intersections.
         */
        set orthogonalStartSash(sash) {
            for (const sashItem of this.sashItems) {
                sashItem.sash.orthogonalStartSash = sash;
            }
            this._orthogonalStartSash = sash;
        }
        /**
         * A reference to a sash, perpendicular to all sashes in this {@link SplitView},
         * located at the right- or bottom-most side of the SplitView.
         * Corner sashes will be created automatically at the intersections.
         */
        set orthogonalEndSash(sash) {
            for (const sashItem of this.sashItems) {
                sashItem.sash.orthogonalEndSash = sash;
            }
            this._orthogonalEndSash = sash;
        }
        /**
         * Enable/disable snapping at the beginning of this {@link SplitView}.
         */
        set startSnappingEnabled(startSnappingEnabled) {
            if (this._startSnappingEnabled === startSnappingEnabled) {
                return;
            }
            this._startSnappingEnabled = startSnappingEnabled;
            this.updateSashEnablement();
        }
        /**
         * Enable/disable snapping at the end of this {@link SplitView}.
         */
        set endSnappingEnabled(endSnappingEnabled) {
            if (this._endSnappingEnabled === endSnappingEnabled) {
                return;
            }
            this._endSnappingEnabled = endSnappingEnabled;
            this.updateSashEnablement();
        }
        /**
         * Create a new {@link SplitView} instance.
         */
        constructor(container, options = {}) {
            super();
            this.size = 0;
            this._contentSize = 0;
            this.proportions = undefined;
            this.viewItems = [];
            this.sashItems = []; // used in tests
            this.state = State.Idle;
            this._onDidSashChange = this._register(new event_2.Emitter());
            this._onDidSashReset = this._register(new event_2.Emitter());
            this._startSnappingEnabled = true;
            this._endSnappingEnabled = true;
            /**
             * Fires whenever the user resizes a {@link Sash sash}.
             */
            this.onDidSashChange = this._onDidSashChange.event;
            /**
             * Fires whenever the user double clicks a {@link Sash sash}.
             */
            this.onDidSashReset = this._onDidSashReset.event;
            this.orientation = options.orientation ?? 0 /* Orientation.VERTICAL */;
            this.inverseAltBehavior = options.inverseAltBehavior ?? false;
            this.proportionalLayout = options.proportionalLayout ?? true;
            this.getSashOrthogonalSize = options.getSashOrthogonalSize;
            this.el = document.createElement('div');
            this.el.classList.add('monaco-split-view2');
            this.el.classList.add(this.orientation === 0 /* Orientation.VERTICAL */ ? 'vertical' : 'horizontal');
            container.appendChild(this.el);
            this.sashContainer = (0, dom_1.append)(this.el, (0, dom_1.$)('.sash-container'));
            this.viewContainer = (0, dom_1.$)('.split-view-container');
            this.scrollable = this._register(new scrollable_1.Scrollable({
                forceIntegerValues: true,
                smoothScrollDuration: 125,
                scheduleAtNextAnimationFrame: callback => (0, dom_1.scheduleAtNextAnimationFrame)((0, dom_1.getWindow)(this.el), callback),
            }));
            this.scrollableElement = this._register(new scrollableElement_1.SmoothScrollableElement(this.viewContainer, {
                vertical: this.orientation === 0 /* Orientation.VERTICAL */ ? (options.scrollbarVisibility ?? 1 /* ScrollbarVisibility.Auto */) : 2 /* ScrollbarVisibility.Hidden */,
                horizontal: this.orientation === 1 /* Orientation.HORIZONTAL */ ? (options.scrollbarVisibility ?? 1 /* ScrollbarVisibility.Auto */) : 2 /* ScrollbarVisibility.Hidden */
            }, this.scrollable));
            // https://github.com/microsoft/vscode/issues/157737
            const onDidScrollViewContainer = this._register(new event_1.DomEmitter(this.viewContainer, 'scroll')).event;
            this._register(onDidScrollViewContainer(_ => {
                const position = this.scrollableElement.getScrollPosition();
                const scrollLeft = Math.abs(this.viewContainer.scrollLeft - position.scrollLeft) <= 1 ? undefined : this.viewContainer.scrollLeft;
                const scrollTop = Math.abs(this.viewContainer.scrollTop - position.scrollTop) <= 1 ? undefined : this.viewContainer.scrollTop;
                if (scrollLeft !== undefined || scrollTop !== undefined) {
                    this.scrollableElement.setScrollPosition({ scrollLeft, scrollTop });
                }
            }));
            this.onDidScroll = this.scrollableElement.onScroll;
            this._register(this.onDidScroll(e => {
                if (e.scrollTopChanged) {
                    this.viewContainer.scrollTop = e.scrollTop;
                }
                if (e.scrollLeftChanged) {
                    this.viewContainer.scrollLeft = e.scrollLeft;
                }
            }));
            (0, dom_1.append)(this.el, this.scrollableElement.getDomNode());
            this.style(options.styles || defaultStyles);
            // We have an existing set of view, add them now
            if (options.descriptor) {
                this.size = options.descriptor.size;
                options.descriptor.views.forEach((viewDescriptor, index) => {
                    const sizing = types.isUndefined(viewDescriptor.visible) || viewDescriptor.visible ? viewDescriptor.size : { type: 'invisible', cachedVisibleSize: viewDescriptor.size };
                    const view = viewDescriptor.view;
                    this.doAddView(view, sizing, index, true);
                });
                // Initialize content size and proportions for first layout
                this._contentSize = this.viewItems.reduce((r, i) => r + i.size, 0);
                this.saveProportions();
            }
        }
        style(styles) {
            if (styles.separatorBorder.isTransparent()) {
                this.el.classList.remove('separator-border');
                this.el.style.removeProperty('--separator-border');
            }
            else {
                this.el.classList.add('separator-border');
                this.el.style.setProperty('--separator-border', styles.separatorBorder.toString());
            }
        }
        /**
         * Add a {@link IView view} to this {@link SplitView}.
         *
         * @param view The view to add.
         * @param size Either a fixed size, or a dynamic {@link Sizing} strategy.
         * @param index The index to insert the view on.
         * @param skipLayout Whether layout should be skipped.
         */
        addView(view, size, index = this.viewItems.length, skipLayout) {
            this.doAddView(view, size, index, skipLayout);
        }
        /**
         * Layout the {@link SplitView}.
         *
         * @param size The entire size of the {@link SplitView}.
         * @param layoutContext An optional layout context to pass along to {@link IView views}.
         */
        layout(size, layoutContext) {
            const previousSize = Math.max(this.size, this._contentSize);
            this.size = size;
            this.layoutContext = layoutContext;
            if (!this.proportions) {
                const indexes = (0, arrays_1.range)(this.viewItems.length);
                const lowPriorityIndexes = indexes.filter(i => this.viewItems[i].priority === 1 /* LayoutPriority.Low */);
                const highPriorityIndexes = indexes.filter(i => this.viewItems[i].priority === 2 /* LayoutPriority.High */);
                this.resize(this.viewItems.length - 1, size - previousSize, undefined, lowPriorityIndexes, highPriorityIndexes);
            }
            else {
                let total = 0;
                for (let i = 0; i < this.viewItems.length; i++) {
                    const item = this.viewItems[i];
                    const proportion = this.proportions[i];
                    if (typeof proportion === 'number') {
                        total += proportion;
                    }
                    else {
                        size -= item.size;
                    }
                }
                for (let i = 0; i < this.viewItems.length; i++) {
                    const item = this.viewItems[i];
                    const proportion = this.proportions[i];
                    if (typeof proportion === 'number' && total > 0) {
                        item.size = (0, numbers_1.clamp)(Math.round(proportion * size / total), item.minimumSize, item.maximumSize);
                    }
                }
            }
            this.distributeEmptySpace();
            this.layoutViews();
        }
        saveProportions() {
            if (this.proportionalLayout && this._contentSize > 0) {
                this.proportions = this.viewItems.map(v => v.proportionalLayout && v.visible ? v.size / this._contentSize : undefined);
            }
        }
        onSashStart({ sash, start, alt }) {
            for (const item of this.viewItems) {
                item.enabled = false;
            }
            const index = this.sashItems.findIndex(item => item.sash === sash);
            // This way, we can press Alt while we resize a sash, macOS style!
            const disposable = (0, lifecycle_1.combinedDisposable)((0, dom_1.addDisposableListener)(this.el.ownerDocument.body, 'keydown', e => resetSashDragState(this.sashDragState.current, e.altKey)), (0, dom_1.addDisposableListener)(this.el.ownerDocument.body, 'keyup', () => resetSashDragState(this.sashDragState.current, false)));
            const resetSashDragState = (start, alt) => {
                const sizes = this.viewItems.map(i => i.size);
                let minDelta = Number.NEGATIVE_INFINITY;
                let maxDelta = Number.POSITIVE_INFINITY;
                if (this.inverseAltBehavior) {
                    alt = !alt;
                }
                if (alt) {
                    // When we're using the last sash with Alt, we're resizing
                    // the view to the left/up, instead of right/down as usual
                    // Thus, we must do the inverse of the usual
                    const isLastSash = index === this.sashItems.length - 1;
                    if (isLastSash) {
                        const viewItem = this.viewItems[index];
                        minDelta = (viewItem.minimumSize - viewItem.size) / 2;
                        maxDelta = (viewItem.maximumSize - viewItem.size) / 2;
                    }
                    else {
                        const viewItem = this.viewItems[index + 1];
                        minDelta = (viewItem.size - viewItem.maximumSize) / 2;
                        maxDelta = (viewItem.size - viewItem.minimumSize) / 2;
                    }
                }
                let snapBefore;
                let snapAfter;
                if (!alt) {
                    const upIndexes = (0, arrays_1.range)(index, -1);
                    const downIndexes = (0, arrays_1.range)(index + 1, this.viewItems.length);
                    const minDeltaUp = upIndexes.reduce((r, i) => r + (this.viewItems[i].minimumSize - sizes[i]), 0);
                    const maxDeltaUp = upIndexes.reduce((r, i) => r + (this.viewItems[i].viewMaximumSize - sizes[i]), 0);
                    const maxDeltaDown = downIndexes.length === 0 ? Number.POSITIVE_INFINITY : downIndexes.reduce((r, i) => r + (sizes[i] - this.viewItems[i].minimumSize), 0);
                    const minDeltaDown = downIndexes.length === 0 ? Number.NEGATIVE_INFINITY : downIndexes.reduce((r, i) => r + (sizes[i] - this.viewItems[i].viewMaximumSize), 0);
                    const minDelta = Math.max(minDeltaUp, minDeltaDown);
                    const maxDelta = Math.min(maxDeltaDown, maxDeltaUp);
                    const snapBeforeIndex = this.findFirstSnapIndex(upIndexes);
                    const snapAfterIndex = this.findFirstSnapIndex(downIndexes);
                    if (typeof snapBeforeIndex === 'number') {
                        const viewItem = this.viewItems[snapBeforeIndex];
                        const halfSize = Math.floor(viewItem.viewMinimumSize / 2);
                        snapBefore = {
                            index: snapBeforeIndex,
                            limitDelta: viewItem.visible ? minDelta - halfSize : minDelta + halfSize,
                            size: viewItem.size
                        };
                    }
                    if (typeof snapAfterIndex === 'number') {
                        const viewItem = this.viewItems[snapAfterIndex];
                        const halfSize = Math.floor(viewItem.viewMinimumSize / 2);
                        snapAfter = {
                            index: snapAfterIndex,
                            limitDelta: viewItem.visible ? maxDelta + halfSize : maxDelta - halfSize,
                            size: viewItem.size
                        };
                    }
                }
                this.sashDragState = { start, current: start, index, sizes, minDelta, maxDelta, alt, snapBefore, snapAfter, disposable };
            };
            resetSashDragState(start, alt);
        }
        onSashChange({ current }) {
            const { index, start, sizes, alt, minDelta, maxDelta, snapBefore, snapAfter } = this.sashDragState;
            this.sashDragState.current = current;
            const delta = current - start;
            const newDelta = this.resize(index, delta, sizes, undefined, undefined, minDelta, maxDelta, snapBefore, snapAfter);
            if (alt) {
                const isLastSash = index === this.sashItems.length - 1;
                const newSizes = this.viewItems.map(i => i.size);
                const viewItemIndex = isLastSash ? index : index + 1;
                const viewItem = this.viewItems[viewItemIndex];
                const newMinDelta = viewItem.size - viewItem.maximumSize;
                const newMaxDelta = viewItem.size - viewItem.minimumSize;
                const resizeIndex = isLastSash ? index - 1 : index + 1;
                this.resize(resizeIndex, -newDelta, newSizes, undefined, undefined, newMinDelta, newMaxDelta);
            }
            this.distributeEmptySpace();
            this.layoutViews();
        }
        onSashEnd(index) {
            this._onDidSashChange.fire(index);
            this.sashDragState.disposable.dispose();
            this.saveProportions();
            for (const item of this.viewItems) {
                item.enabled = true;
            }
        }
        onViewChange(item, size) {
            const index = this.viewItems.indexOf(item);
            if (index < 0 || index >= this.viewItems.length) {
                return;
            }
            size = typeof size === 'number' ? size : item.size;
            size = (0, numbers_1.clamp)(size, item.minimumSize, item.maximumSize);
            if (this.inverseAltBehavior && index > 0) {
                // In this case, we want the view to grow or shrink both sides equally
                // so we just resize the "left" side by half and let `resize` do the clamping magic
                this.resize(index - 1, Math.floor((item.size - size) / 2));
                this.distributeEmptySpace();
                this.layoutViews();
            }
            else {
                item.size = size;
                this.relayout([index], undefined);
            }
        }
        /**
         * Resize a {@link IView view} within the {@link SplitView}.
         *
         * @param index The {@link IView view} index.
         * @param size The {@link IView view} size.
         */
        resizeView(index, size) {
            if (index < 0 || index >= this.viewItems.length) {
                return;
            }
            if (this.state !== State.Idle) {
                throw new Error('Cant modify splitview');
            }
            this.state = State.Busy;
            try {
                const indexes = (0, arrays_1.range)(this.viewItems.length).filter(i => i !== index);
                const lowPriorityIndexes = [...indexes.filter(i => this.viewItems[i].priority === 1 /* LayoutPriority.Low */), index];
                const highPriorityIndexes = indexes.filter(i => this.viewItems[i].priority === 2 /* LayoutPriority.High */);
                const item = this.viewItems[index];
                size = Math.round(size);
                size = (0, numbers_1.clamp)(size, item.minimumSize, Math.min(item.maximumSize, this.size));
                item.size = size;
                this.relayout(lowPriorityIndexes, highPriorityIndexes);
            }
            finally {
                this.state = State.Idle;
            }
        }
        /**
         * Distribute the entire {@link SplitView} size among all {@link IView views}.
         */
        distributeViewSizes() {
            const flexibleViewItems = [];
            let flexibleSize = 0;
            for (const item of this.viewItems) {
                if (item.maximumSize - item.minimumSize > 0) {
                    flexibleViewItems.push(item);
                    flexibleSize += item.size;
                }
            }
            const size = Math.floor(flexibleSize / flexibleViewItems.length);
            for (const item of flexibleViewItems) {
                item.size = (0, numbers_1.clamp)(size, item.minimumSize, item.maximumSize);
            }
            const indexes = (0, arrays_1.range)(this.viewItems.length);
            const lowPriorityIndexes = indexes.filter(i => this.viewItems[i].priority === 1 /* LayoutPriority.Low */);
            const highPriorityIndexes = indexes.filter(i => this.viewItems[i].priority === 2 /* LayoutPriority.High */);
            this.relayout(lowPriorityIndexes, highPriorityIndexes);
        }
        /**
         * Returns the size of a {@link IView view}.
         */
        getViewSize(index) {
            if (index < 0 || index >= this.viewItems.length) {
                return -1;
            }
            return this.viewItems[index].size;
        }
        doAddView(view, size, index = this.viewItems.length, skipLayout) {
            if (this.state !== State.Idle) {
                throw new Error('Cant modify splitview');
            }
            this.state = State.Busy;
            try {
                // Add view
                const container = (0, dom_1.$)('.split-view-view');
                if (index === this.viewItems.length) {
                    this.viewContainer.appendChild(container);
                }
                else {
                    this.viewContainer.insertBefore(container, this.viewContainer.children.item(index));
                }
                const onChangeDisposable = view.onDidChange(size => this.onViewChange(item, size));
                const containerDisposable = (0, lifecycle_1.toDisposable)(() => container.remove());
                const disposable = (0, lifecycle_1.combinedDisposable)(onChangeDisposable, containerDisposable);
                let viewSize;
                if (typeof size === 'number') {
                    viewSize = size;
                }
                else {
                    if (size.type === 'auto') {
                        if (this.areViewsDistributed()) {
                            size = { type: 'distribute' };
                        }
                        else {
                            size = { type: 'split', index: size.index };
                        }
                    }
                    if (size.type === 'split') {
                        viewSize = this.getViewSize(size.index) / 2;
                    }
                    else if (size.type === 'invisible') {
                        viewSize = { cachedVisibleSize: size.cachedVisibleSize };
                    }
                    else {
                        viewSize = view.minimumSize;
                    }
                }
                const item = this.orientation === 0 /* Orientation.VERTICAL */
                    ? new VerticalViewItem(container, view, viewSize, disposable)
                    : new HorizontalViewItem(container, view, viewSize, disposable);
                this.viewItems.splice(index, 0, item);
                // Add sash
                if (this.viewItems.length > 1) {
                    const opts = { orthogonalStartSash: this.orthogonalStartSash, orthogonalEndSash: this.orthogonalEndSash };
                    const sash = this.orientation === 0 /* Orientation.VERTICAL */
                        ? new sash_1.Sash(this.sashContainer, { getHorizontalSashTop: s => this.getSashPosition(s), getHorizontalSashWidth: this.getSashOrthogonalSize }, { ...opts, orientation: 1 /* Orientation.HORIZONTAL */ })
                        : new sash_1.Sash(this.sashContainer, { getVerticalSashLeft: s => this.getSashPosition(s), getVerticalSashHeight: this.getSashOrthogonalSize }, { ...opts, orientation: 0 /* Orientation.VERTICAL */ });
                    const sashEventMapper = this.orientation === 0 /* Orientation.VERTICAL */
                        ? (e) => ({ sash, start: e.startY, current: e.currentY, alt: e.altKey })
                        : (e) => ({ sash, start: e.startX, current: e.currentX, alt: e.altKey });
                    const onStart = event_2.Event.map(sash.onDidStart, sashEventMapper);
                    const onStartDisposable = onStart(this.onSashStart, this);
                    const onChange = event_2.Event.map(sash.onDidChange, sashEventMapper);
                    const onChangeDisposable = onChange(this.onSashChange, this);
                    const onEnd = event_2.Event.map(sash.onDidEnd, () => this.sashItems.findIndex(item => item.sash === sash));
                    const onEndDisposable = onEnd(this.onSashEnd, this);
                    const onDidResetDisposable = sash.onDidReset(() => {
                        const index = this.sashItems.findIndex(item => item.sash === sash);
                        const upIndexes = (0, arrays_1.range)(index, -1);
                        const downIndexes = (0, arrays_1.range)(index + 1, this.viewItems.length);
                        const snapBeforeIndex = this.findFirstSnapIndex(upIndexes);
                        const snapAfterIndex = this.findFirstSnapIndex(downIndexes);
                        if (typeof snapBeforeIndex === 'number' && !this.viewItems[snapBeforeIndex].visible) {
                            return;
                        }
                        if (typeof snapAfterIndex === 'number' && !this.viewItems[snapAfterIndex].visible) {
                            return;
                        }
                        this._onDidSashReset.fire(index);
                    });
                    const disposable = (0, lifecycle_1.combinedDisposable)(onStartDisposable, onChangeDisposable, onEndDisposable, onDidResetDisposable, sash);
                    const sashItem = { sash, disposable };
                    this.sashItems.splice(index - 1, 0, sashItem);
                }
                container.appendChild(view.element);
                let highPriorityIndexes;
                if (typeof size !== 'number' && size.type === 'split') {
                    highPriorityIndexes = [size.index];
                }
                if (!skipLayout) {
                    this.relayout([index], highPriorityIndexes);
                }
                if (!skipLayout && typeof size !== 'number' && size.type === 'distribute') {
                    this.distributeViewSizes();
                }
            }
            finally {
                this.state = State.Idle;
            }
        }
        relayout(lowPriorityIndexes, highPriorityIndexes) {
            const contentSize = this.viewItems.reduce((r, i) => r + i.size, 0);
            this.resize(this.viewItems.length - 1, this.size - contentSize, undefined, lowPriorityIndexes, highPriorityIndexes);
            this.distributeEmptySpace();
            this.layoutViews();
            this.saveProportions();
        }
        resize(index, delta, sizes = this.viewItems.map(i => i.size), lowPriorityIndexes, highPriorityIndexes, overloadMinDelta = Number.NEGATIVE_INFINITY, overloadMaxDelta = Number.POSITIVE_INFINITY, snapBefore, snapAfter) {
            if (index < 0 || index >= this.viewItems.length) {
                return 0;
            }
            const upIndexes = (0, arrays_1.range)(index, -1);
            const downIndexes = (0, arrays_1.range)(index + 1, this.viewItems.length);
            if (highPriorityIndexes) {
                for (const index of highPriorityIndexes) {
                    (0, arrays_1.pushToStart)(upIndexes, index);
                    (0, arrays_1.pushToStart)(downIndexes, index);
                }
            }
            if (lowPriorityIndexes) {
                for (const index of lowPriorityIndexes) {
                    (0, arrays_1.pushToEnd)(upIndexes, index);
                    (0, arrays_1.pushToEnd)(downIndexes, index);
                }
            }
            const upItems = upIndexes.map(i => this.viewItems[i]);
            const upSizes = upIndexes.map(i => sizes[i]);
            const downItems = downIndexes.map(i => this.viewItems[i]);
            const downSizes = downIndexes.map(i => sizes[i]);
            const minDeltaUp = upIndexes.reduce((r, i) => r + (this.viewItems[i].minimumSize - sizes[i]), 0);
            const maxDeltaUp = upIndexes.reduce((r, i) => r + (this.viewItems[i].maximumSize - sizes[i]), 0);
            const maxDeltaDown = downIndexes.length === 0 ? Number.POSITIVE_INFINITY : downIndexes.reduce((r, i) => r + (sizes[i] - this.viewItems[i].minimumSize), 0);
            const minDeltaDown = downIndexes.length === 0 ? Number.NEGATIVE_INFINITY : downIndexes.reduce((r, i) => r + (sizes[i] - this.viewItems[i].maximumSize), 0);
            const minDelta = Math.max(minDeltaUp, minDeltaDown, overloadMinDelta);
            const maxDelta = Math.min(maxDeltaDown, maxDeltaUp, overloadMaxDelta);
            let snapped = false;
            if (snapBefore) {
                const snapView = this.viewItems[snapBefore.index];
                const visible = delta >= snapBefore.limitDelta;
                snapped = visible !== snapView.visible;
                snapView.setVisible(visible, snapBefore.size);
            }
            if (!snapped && snapAfter) {
                const snapView = this.viewItems[snapAfter.index];
                const visible = delta < snapAfter.limitDelta;
                snapped = visible !== snapView.visible;
                snapView.setVisible(visible, snapAfter.size);
            }
            if (snapped) {
                return this.resize(index, delta, sizes, lowPriorityIndexes, highPriorityIndexes, overloadMinDelta, overloadMaxDelta);
            }
            delta = (0, numbers_1.clamp)(delta, minDelta, maxDelta);
            for (let i = 0, deltaUp = delta; i < upItems.length; i++) {
                const item = upItems[i];
                const size = (0, numbers_1.clamp)(upSizes[i] + deltaUp, item.minimumSize, item.maximumSize);
                const viewDelta = size - upSizes[i];
                deltaUp -= viewDelta;
                item.size = size;
            }
            for (let i = 0, deltaDown = delta; i < downItems.length; i++) {
                const item = downItems[i];
                const size = (0, numbers_1.clamp)(downSizes[i] - deltaDown, item.minimumSize, item.maximumSize);
                const viewDelta = size - downSizes[i];
                deltaDown += viewDelta;
                item.size = size;
            }
            return delta;
        }
        distributeEmptySpace(lowPriorityIndex) {
            const contentSize = this.viewItems.reduce((r, i) => r + i.size, 0);
            let emptyDelta = this.size - contentSize;
            const indexes = (0, arrays_1.range)(this.viewItems.length - 1, -1);
            const lowPriorityIndexes = indexes.filter(i => this.viewItems[i].priority === 1 /* LayoutPriority.Low */);
            const highPriorityIndexes = indexes.filter(i => this.viewItems[i].priority === 2 /* LayoutPriority.High */);
            for (const index of highPriorityIndexes) {
                (0, arrays_1.pushToStart)(indexes, index);
            }
            for (const index of lowPriorityIndexes) {
                (0, arrays_1.pushToEnd)(indexes, index);
            }
            if (typeof lowPriorityIndex === 'number') {
                (0, arrays_1.pushToEnd)(indexes, lowPriorityIndex);
            }
            for (let i = 0; emptyDelta !== 0 && i < indexes.length; i++) {
                const item = this.viewItems[indexes[i]];
                const size = (0, numbers_1.clamp)(item.size + emptyDelta, item.minimumSize, item.maximumSize);
                const viewDelta = size - item.size;
                emptyDelta -= viewDelta;
                item.size = size;
            }
        }
        layoutViews() {
            // Save new content size
            this._contentSize = this.viewItems.reduce((r, i) => r + i.size, 0);
            // Layout views
            let offset = 0;
            for (const viewItem of this.viewItems) {
                viewItem.layout(offset, this.layoutContext);
                offset += viewItem.size;
            }
            // Layout sashes
            this.sashItems.forEach(item => item.sash.layout());
            this.updateSashEnablement();
            this.updateScrollableElement();
        }
        updateScrollableElement() {
            if (this.orientation === 0 /* Orientation.VERTICAL */) {
                this.scrollableElement.setScrollDimensions({
                    height: this.size,
                    scrollHeight: this._contentSize
                });
            }
            else {
                this.scrollableElement.setScrollDimensions({
                    width: this.size,
                    scrollWidth: this._contentSize
                });
            }
        }
        updateSashEnablement() {
            let previous = false;
            const collapsesDown = this.viewItems.map(i => previous = (i.size - i.minimumSize > 0) || previous);
            previous = false;
            const expandsDown = this.viewItems.map(i => previous = (i.maximumSize - i.size > 0) || previous);
            const reverseViews = [...this.viewItems].reverse();
            previous = false;
            const collapsesUp = reverseViews.map(i => previous = (i.size - i.minimumSize > 0) || previous).reverse();
            previous = false;
            const expandsUp = reverseViews.map(i => previous = (i.maximumSize - i.size > 0) || previous).reverse();
            let position = 0;
            for (let index = 0; index < this.sashItems.length; index++) {
                const { sash } = this.sashItems[index];
                const viewItem = this.viewItems[index];
                position += viewItem.size;
                const min = !(collapsesDown[index] && expandsUp[index + 1]);
                const max = !(expandsDown[index] && collapsesUp[index + 1]);
                if (min && max) {
                    const upIndexes = (0, arrays_1.range)(index, -1);
                    const downIndexes = (0, arrays_1.range)(index + 1, this.viewItems.length);
                    const snapBeforeIndex = this.findFirstSnapIndex(upIndexes);
                    const snapAfterIndex = this.findFirstSnapIndex(downIndexes);
                    const snappedBefore = typeof snapBeforeIndex === 'number' && !this.viewItems[snapBeforeIndex].visible;
                    const snappedAfter = typeof snapAfterIndex === 'number' && !this.viewItems[snapAfterIndex].visible;
                    if (snappedBefore && collapsesUp[index] && (position > 0 || this.startSnappingEnabled)) {
                        sash.state = 1 /* SashState.AtMinimum */;
                    }
                    else if (snappedAfter && collapsesDown[index] && (position < this._contentSize || this.endSnappingEnabled)) {
                        sash.state = 2 /* SashState.AtMaximum */;
                    }
                    else {
                        sash.state = 0 /* SashState.Disabled */;
                    }
                }
                else if (min && !max) {
                    sash.state = 1 /* SashState.AtMinimum */;
                }
                else if (!min && max) {
                    sash.state = 2 /* SashState.AtMaximum */;
                }
                else {
                    sash.state = 3 /* SashState.Enabled */;
                }
            }
        }
        getSashPosition(sash) {
            let position = 0;
            for (let i = 0; i < this.sashItems.length; i++) {
                position += this.viewItems[i].size;
                if (this.sashItems[i].sash === sash) {
                    return position;
                }
            }
            return 0;
        }
        findFirstSnapIndex(indexes) {
            // visible views first
            for (const index of indexes) {
                const viewItem = this.viewItems[index];
                if (!viewItem.visible) {
                    continue;
                }
                if (viewItem.snap) {
                    return index;
                }
            }
            // then, hidden views
            for (const index of indexes) {
                const viewItem = this.viewItems[index];
                if (viewItem.visible && viewItem.maximumSize - viewItem.minimumSize > 0) {
                    return undefined;
                }
                if (!viewItem.visible && viewItem.snap) {
                    return index;
                }
            }
            return undefined;
        }
        areViewsDistributed() {
            let min = undefined, max = undefined;
            for (const view of this.viewItems) {
                min = min === undefined ? view.size : Math.min(min, view.size);
                max = max === undefined ? view.size : Math.max(max, view.size);
                if (max - min > 2) {
                    return false;
                }
            }
            return true;
        }
        dispose() {
            this.sashDragState?.disposable.dispose();
            (0, lifecycle_1.dispose)(this.viewItems);
            this.viewItems = [];
            this.sashItems.forEach(i => i.disposable.dispose());
            this.sashItems = [];
            super.dispose();
        }
    }
    exports.SplitView = SplitView;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[638/*vs/base/browser/ui/table/tableWidget*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,81/*vs/base/browser/ui/hover/hoverDelegate2*/,44/*vs/base/browser/ui/hover/hoverDelegateFactory*/,115/*vs/base/browser/ui/list/listWidget*/,357/*vs/base/browser/ui/splitview/splitview*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,475/*vs/css!vs/base/browser/ui/table/table*/]), function (require, exports, dom_1, hoverDelegate2_1, hoverDelegateFactory_1, listWidget_1, splitview_1, event_1, lifecycle_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Table = void 0;
    class TableListRenderer {
        static { this.TemplateId = 'row'; }
        constructor(columns, renderers, getColumnSize) {
            this.columns = columns;
            this.getColumnSize = getColumnSize;
            this.templateId = TableListRenderer.TemplateId;
            this.renderedTemplates = new Set();
            const rendererMap = new Map(renderers.map(r => [r.templateId, r]));
            this.renderers = [];
            for (const column of columns) {
                const renderer = rendererMap.get(column.templateId);
                if (!renderer) {
                    throw new Error(`Table cell renderer for template id ${column.templateId} not found.`);
                }
                this.renderers.push(renderer);
            }
        }
        renderTemplate(container) {
            const rowContainer = (0, dom_1.append)(container, (0, dom_1.$)('.monaco-table-tr'));
            const cellContainers = [];
            const cellTemplateData = [];
            for (let i = 0; i < this.columns.length; i++) {
                const renderer = this.renderers[i];
                const cellContainer = (0, dom_1.append)(rowContainer, (0, dom_1.$)('.monaco-table-td', { 'data-col-index': i }));
                cellContainer.style.width = `${this.getColumnSize(i)}px`;
                cellContainers.push(cellContainer);
                cellTemplateData.push(renderer.renderTemplate(cellContainer));
            }
            const result = { container, cellContainers, cellTemplateData };
            this.renderedTemplates.add(result);
            return result;
        }
        renderElement(element, index, templateData, height) {
            for (let i = 0; i < this.columns.length; i++) {
                const column = this.columns[i];
                const cell = column.project(element);
                const renderer = this.renderers[i];
                renderer.renderElement(cell, index, templateData.cellTemplateData[i], height);
            }
        }
        disposeElement(element, index, templateData, height) {
            for (let i = 0; i < this.columns.length; i++) {
                const renderer = this.renderers[i];
                if (renderer.disposeElement) {
                    const column = this.columns[i];
                    const cell = column.project(element);
                    renderer.disposeElement(cell, index, templateData.cellTemplateData[i], height);
                }
            }
        }
        disposeTemplate(templateData) {
            for (let i = 0; i < this.columns.length; i++) {
                const renderer = this.renderers[i];
                renderer.disposeTemplate(templateData.cellTemplateData[i]);
            }
            (0, dom_1.clearNode)(templateData.container);
            this.renderedTemplates.delete(templateData);
        }
        layoutColumn(index, size) {
            for (const { cellContainers } of this.renderedTemplates) {
                cellContainers[index].style.width = `${size}px`;
            }
        }
    }
    function asListVirtualDelegate(delegate) {
        return {
            getHeight(row) { return delegate.getHeight(row); },
            getTemplateId() { return TableListRenderer.TemplateId; },
        };
    }
    class ColumnHeader extends lifecycle_1.Disposable {
        get minimumSize() { return this.column.minimumWidth ?? 120; }
        get maximumSize() { return this.column.maximumWidth ?? Number.POSITIVE_INFINITY; }
        get onDidChange() { return this.column.onDidChangeWidthConstraints ?? event_1.Event.None; }
        constructor(column, index) {
            super();
            this.column = column;
            this.index = index;
            this._onDidLayout = new event_1.Emitter();
            this.onDidLayout = this._onDidLayout.event;
            this.element = (0, dom_1.$)('.monaco-table-th', { 'data-col-index': index }, column.label);
            if (column.tooltip) {
                this._register((0, hoverDelegate2_1.getBaseLayerHoverDelegate)().setupManagedHover((0, hoverDelegateFactory_1.getDefaultHoverDelegate)('mouse'), this.element, column.tooltip));
            }
        }
        layout(size) {
            this._onDidLayout.fire([this.index, size]);
        }
    }
    class Table {
        static { this.InstanceCount = 0; }
        get onDidChangeFocus() { return this.list.onDidChangeFocus; }
        get onDidChangeSelection() { return this.list.onDidChangeSelection; }
        get onDidScroll() { return this.list.onDidScroll; }
        get onMouseDblClick() { return this.list.onMouseDblClick; }
        get onPointer() { return this.list.onPointer; }
        get onDidFocus() { return this.list.onDidFocus; }
        get scrollTop() { return this.list.scrollTop; }
        set scrollTop(scrollTop) { this.list.scrollTop = scrollTop; }
        get scrollHeight() { return this.list.scrollHeight; }
        get renderHeight() { return this.list.renderHeight; }
        get onDidDispose() { return this.list.onDidDispose; }
        constructor(user, container, virtualDelegate, columns, renderers, _options) {
            this.virtualDelegate = virtualDelegate;
            this.columns = columns;
            this.domId = `table_id_${++Table.InstanceCount}`;
            this.disposables = new lifecycle_1.DisposableStore();
            this.cachedWidth = 0;
            this.cachedHeight = 0;
            this.domNode = (0, dom_1.append)(container, (0, dom_1.$)(`.monaco-table.${this.domId}`));
            const headers = columns.map((c, i) => this.disposables.add(new ColumnHeader(c, i)));
            const descriptor = {
                size: headers.reduce((a, b) => a + b.column.weight, 0),
                views: headers.map(view => ({ size: view.column.weight, view }))
            };
            this.splitview = this.disposables.add(new splitview_1.SplitView(this.domNode, {
                orientation: 1 /* Orientation.HORIZONTAL */,
                scrollbarVisibility: 2 /* ScrollbarVisibility.Hidden */,
                getSashOrthogonalSize: () => this.cachedHeight,
                descriptor
            }));
            this.splitview.el.style.height = `${virtualDelegate.headerRowHeight}px`;
            this.splitview.el.style.lineHeight = `${virtualDelegate.headerRowHeight}px`;
            const renderer = new TableListRenderer(columns, renderers, i => this.splitview.getViewSize(i));
            this.list = this.disposables.add(new listWidget_1.List(user, this.domNode, asListVirtualDelegate(virtualDelegate), [renderer], _options));
            event_1.Event.any(...headers.map(h => h.onDidLayout))(([index, size]) => renderer.layoutColumn(index, size), null, this.disposables);
            this.splitview.onDidSashReset(index => {
                const totalWeight = columns.reduce((r, c) => r + c.weight, 0);
                const size = columns[index].weight / totalWeight * this.cachedWidth;
                this.splitview.resizeView(index, size);
            }, null, this.disposables);
            this.styleElement = (0, dom_1.createStyleSheet)(this.domNode);
            this.style(listWidget_1.unthemedListStyles);
        }
        updateOptions(options) {
            this.list.updateOptions(options);
        }
        splice(start, deleteCount, elements = []) {
            this.list.splice(start, deleteCount, elements);
        }
        getHTMLElement() {
            return this.domNode;
        }
        style(styles) {
            const content = [];
            content.push(`.monaco-table.${this.domId} > .monaco-split-view2 .monaco-sash.vertical::before {
			top: ${this.virtualDelegate.headerRowHeight + 1}px;
			height: calc(100% - ${this.virtualDelegate.headerRowHeight}px);
		}`);
            this.styleElement.textContent = content.join('\n');
            this.list.style(styles);
        }
        getSelectedElements() {
            return this.list.getSelectedElements();
        }
        getSelection() {
            return this.list.getSelection();
        }
        getFocus() {
            return this.list.getFocus();
        }
        dispose() {
            this.disposables.dispose();
        }
    }
    exports.Table = Table;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[175/*vs/base/browser/ui/toggle/toggle*/], __M([1/*require*/,0/*exports*/,85/*vs/base/browser/ui/widget*/,30/*vs/base/common/themables*/,6/*vs/base/common/event*/,44/*vs/base/browser/ui/hover/hoverDelegateFactory*/,81/*vs/base/browser/ui/hover/hoverDelegate2*/,476/*vs/css!vs/base/browser/ui/toggle/toggle*/]), function (require, exports, widget_1, themables_1, event_1, hoverDelegateFactory_1, hoverDelegate2_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Toggle = exports.unthemedToggleStyles = void 0;
    exports.unthemedToggleStyles = {
        inputActiveOptionBorder: '#007ACC00',
        inputActiveOptionForeground: '#FFFFFF',
        inputActiveOptionBackground: '#0E639C50'
    };
    class Toggle extends widget_1.Widget {
        constructor(opts) {
            super();
            this._onChange = this._register(new event_1.Emitter());
            this.onChange = this._onChange.event;
            this._onKeyDown = this._register(new event_1.Emitter());
            this.onKeyDown = this._onKeyDown.event;
            this._opts = opts;
            this._checked = this._opts.isChecked;
            const classes = ['monaco-custom-toggle'];
            if (this._opts.icon) {
                this._icon = this._opts.icon;
                classes.push(...themables_1.ThemeIcon.asClassNameArray(this._icon));
            }
            if (this._opts.actionClassName) {
                classes.push(...this._opts.actionClassName.split(' '));
            }
            if (this._checked) {
                classes.push('checked');
            }
            this.domNode = document.createElement('div');
            this._hover = this._register((0, hoverDelegate2_1.getBaseLayerHoverDelegate)().setupManagedHover(opts.hoverDelegate ?? (0, hoverDelegateFactory_1.getDefaultHoverDelegate)('mouse'), this.domNode, this._opts.title));
            this.domNode.classList.add(...classes);
            if (!this._opts.notFocusable) {
                this.domNode.tabIndex = 0;
            }
            this.domNode.setAttribute('role', 'checkbox');
            this.domNode.setAttribute('aria-checked', String(this._checked));
            this.domNode.setAttribute('aria-label', this._opts.title);
            this.applyStyles();
            this.onclick(this.domNode, (ev) => {
                if (this.enabled) {
                    this.checked = !this._checked;
                    this._onChange.fire(false);
                    ev.preventDefault();
                }
            });
            this._register(this.ignoreGesture(this.domNode));
            this.onkeydown(this.domNode, (keyboardEvent) => {
                if (keyboardEvent.keyCode === 10 /* KeyCode.Space */ || keyboardEvent.keyCode === 3 /* KeyCode.Enter */) {
                    this.checked = !this._checked;
                    this._onChange.fire(true);
                    keyboardEvent.preventDefault();
                    keyboardEvent.stopPropagation();
                    return;
                }
                this._onKeyDown.fire(keyboardEvent);
            });
        }
        get enabled() {
            return this.domNode.getAttribute('aria-disabled') !== 'true';
        }
        focus() {
            this.domNode.focus();
        }
        get checked() {
            return this._checked;
        }
        set checked(newIsChecked) {
            this._checked = newIsChecked;
            this.domNode.setAttribute('aria-checked', String(this._checked));
            this.domNode.classList.toggle('checked', this._checked);
            this.applyStyles();
        }
        width() {
            return 2 /*margin left*/ + 2 /*border*/ + 2 /*padding*/ + 16 /* icon width */;
        }
        applyStyles() {
            if (this.domNode) {
                this.domNode.style.borderColor = (this._checked && this._opts.inputActiveOptionBorder) || '';
                this.domNode.style.color = (this._checked && this._opts.inputActiveOptionForeground) || 'inherit';
                this.domNode.style.backgroundColor = (this._checked && this._opts.inputActiveOptionBackground) || '';
            }
        }
        enable() {
            this.domNode.setAttribute('aria-disabled', String(false));
        }
        disable() {
            this.domNode.setAttribute('aria-disabled', String(true));
        }
    }
    exports.Toggle = Toggle;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[358/*vs/base/browser/ui/findinput/findInputToggles*/], __M([1/*require*/,0/*exports*/,44/*vs/base/browser/ui/hover/hoverDelegateFactory*/,175/*vs/base/browser/ui/toggle/toggle*/,26/*vs/base/common/codicons*/,3/*vs/nls*/]), function (require, exports, hoverDelegateFactory_1, toggle_1, codicons_1, nls) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.RegexToggle = exports.WholeWordsToggle = exports.CaseSensitiveToggle = void 0;
    const NLS_CASE_SENSITIVE_TOGGLE_LABEL = nls.localize(2, "Match Case");
    const NLS_WHOLE_WORD_TOGGLE_LABEL = nls.localize(3, "Match Whole Word");
    const NLS_REGEX_TOGGLE_LABEL = nls.localize(4, "Use Regular Expression");
    class CaseSensitiveToggle extends toggle_1.Toggle {
        constructor(opts) {
            super({
                icon: codicons_1.Codicon.caseSensitive,
                title: NLS_CASE_SENSITIVE_TOGGLE_LABEL + opts.appendTitle,
                isChecked: opts.isChecked,
                hoverDelegate: opts.hoverDelegate ?? (0, hoverDelegateFactory_1.getDefaultHoverDelegate)('element'),
                inputActiveOptionBorder: opts.inputActiveOptionBorder,
                inputActiveOptionForeground: opts.inputActiveOptionForeground,
                inputActiveOptionBackground: opts.inputActiveOptionBackground
            });
        }
    }
    exports.CaseSensitiveToggle = CaseSensitiveToggle;
    class WholeWordsToggle extends toggle_1.Toggle {
        constructor(opts) {
            super({
                icon: codicons_1.Codicon.wholeWord,
                title: NLS_WHOLE_WORD_TOGGLE_LABEL + opts.appendTitle,
                isChecked: opts.isChecked,
                hoverDelegate: opts.hoverDelegate ?? (0, hoverDelegateFactory_1.getDefaultHoverDelegate)('element'),
                inputActiveOptionBorder: opts.inputActiveOptionBorder,
                inputActiveOptionForeground: opts.inputActiveOptionForeground,
                inputActiveOptionBackground: opts.inputActiveOptionBackground
            });
        }
    }
    exports.WholeWordsToggle = WholeWordsToggle;
    class RegexToggle extends toggle_1.Toggle {
        constructor(opts) {
            super({
                icon: codicons_1.Codicon.regex,
                title: NLS_REGEX_TOGGLE_LABEL + opts.appendTitle,
                isChecked: opts.isChecked,
                hoverDelegate: opts.hoverDelegate ?? (0, hoverDelegateFactory_1.getDefaultHoverDelegate)('element'),
                inputActiveOptionBorder: opts.inputActiveOptionBorder,
                inputActiveOptionForeground: opts.inputActiveOptionForeground,
                inputActiveOptionBackground: opts.inputActiveOptionBackground
            });
        }
    }
    exports.RegexToggle = RegexToggle;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[48/*vs/base/common/resources*/], __M([1/*require*/,0/*exports*/,251/*vs/base/common/extpath*/,42/*vs/base/common/network*/,99/*vs/base/common/path*/,16/*vs/base/common/platform*/,11/*vs/base/common/strings*/,22/*vs/base/common/uri*/]), function (require, exports, extpath, network_1, paths, platform_1, strings_1, uri_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DataUri = exports.addTrailingPathSeparator = exports.removeTrailingPathSeparator = exports.hasTrailingPathSeparator = exports.isEqualAuthority = exports.isAbsolutePath = exports.resolvePath = exports.relativePath = exports.normalizePath = exports.joinPath = exports.dirname = exports.extname = exports.basename = exports.basenameOrAuthority = exports.getComparisonKey = exports.isEqualOrParent = exports.isEqual = exports.extUriIgnorePathCase = exports.extUriBiasedIgnorePathCase = exports.extUri = exports.ExtUri = void 0;
    exports.originalFSPath = originalFSPath;
    function originalFSPath(uri) {
        return (0, uri_1.uriToFsPath)(uri, true);
    }
    class ExtUri {
        constructor(_ignorePathCasing) {
            this._ignorePathCasing = _ignorePathCasing;
        }
        compare(uri1, uri2, ignoreFragment = false) {
            if (uri1 === uri2) {
                return 0;
            }
            return (0, strings_1.compare)(this.getComparisonKey(uri1, ignoreFragment), this.getComparisonKey(uri2, ignoreFragment));
        }
        isEqual(uri1, uri2, ignoreFragment = false) {
            if (uri1 === uri2) {
                return true;
            }
            if (!uri1 || !uri2) {
                return false;
            }
            return this.getComparisonKey(uri1, ignoreFragment) === this.getComparisonKey(uri2, ignoreFragment);
        }
        getComparisonKey(uri, ignoreFragment = false) {
            return uri.with({
                path: this._ignorePathCasing(uri) ? uri.path.toLowerCase() : undefined,
                fragment: ignoreFragment ? null : undefined
            }).toString();
        }
        isEqualOrParent(base, parentCandidate, ignoreFragment = false) {
            if (base.scheme === parentCandidate.scheme) {
                if (base.scheme === network_1.Schemas.file) {
                    return extpath.isEqualOrParent(originalFSPath(base), originalFSPath(parentCandidate), this._ignorePathCasing(base)) && base.query === parentCandidate.query && (ignoreFragment || base.fragment === parentCandidate.fragment);
                }
                if ((0, exports.isEqualAuthority)(base.authority, parentCandidate.authority)) {
                    return extpath.isEqualOrParent(base.path, parentCandidate.path, this._ignorePathCasing(base), '/') && base.query === parentCandidate.query && (ignoreFragment || base.fragment === parentCandidate.fragment);
                }
            }
            return false;
        }
        // --- path math
        joinPath(resource, ...pathFragment) {
            return uri_1.URI.joinPath(resource, ...pathFragment);
        }
        basenameOrAuthority(resource) {
            return (0, exports.basename)(resource) || resource.authority;
        }
        basename(resource) {
            return paths.posix.basename(resource.path);
        }
        extname(resource) {
            return paths.posix.extname(resource.path);
        }
        dirname(resource) {
            if (resource.path.length === 0) {
                return resource;
            }
            let dirname;
            if (resource.scheme === network_1.Schemas.file) {
                dirname = uri_1.URI.file(paths.dirname(originalFSPath(resource))).path;
            }
            else {
                dirname = paths.posix.dirname(resource.path);
                if (resource.authority && dirname.length && dirname.charCodeAt(0) !== 47 /* CharCode.Slash */) {
                    console.error(`dirname("${resource.toString})) resulted in a relative path`);
                    dirname = '/'; // If a URI contains an authority component, then the path component must either be empty or begin with a CharCode.Slash ("/") character
                }
            }
            return resource.with({
                path: dirname
            });
        }
        normalizePath(resource) {
            if (!resource.path.length) {
                return resource;
            }
            let normalizedPath;
            if (resource.scheme === network_1.Schemas.file) {
                normalizedPath = uri_1.URI.file(paths.normalize(originalFSPath(resource))).path;
            }
            else {
                normalizedPath = paths.posix.normalize(resource.path);
            }
            return resource.with({
                path: normalizedPath
            });
        }
        relativePath(from, to) {
            if (from.scheme !== to.scheme || !(0, exports.isEqualAuthority)(from.authority, to.authority)) {
                return undefined;
            }
            if (from.scheme === network_1.Schemas.file) {
                const relativePath = paths.relative(originalFSPath(from), originalFSPath(to));
                return platform_1.isWindows ? extpath.toSlashes(relativePath) : relativePath;
            }
            let fromPath = from.path || '/';
            const toPath = to.path || '/';
            if (this._ignorePathCasing(from)) {
                // make casing of fromPath match toPath
                let i = 0;
                for (const len = Math.min(fromPath.length, toPath.length); i < len; i++) {
                    if (fromPath.charCodeAt(i) !== toPath.charCodeAt(i)) {
                        if (fromPath.charAt(i).toLowerCase() !== toPath.charAt(i).toLowerCase()) {
                            break;
                        }
                    }
                }
                fromPath = toPath.substr(0, i) + fromPath.substr(i);
            }
            return paths.posix.relative(fromPath, toPath);
        }
        resolvePath(base, path) {
            if (base.scheme === network_1.Schemas.file) {
                const newURI = uri_1.URI.file(paths.resolve(originalFSPath(base), path));
                return base.with({
                    authority: newURI.authority,
                    path: newURI.path
                });
            }
            path = extpath.toPosixPath(path); // we allow path to be a windows path
            return base.with({
                path: paths.posix.resolve(base.path, path)
            });
        }
        // --- misc
        isAbsolutePath(resource) {
            return !!resource.path && resource.path[0] === '/';
        }
        isEqualAuthority(a1, a2) {
            return a1 === a2 || (a1 !== undefined && a2 !== undefined && (0, strings_1.equalsIgnoreCase)(a1, a2));
        }
        hasTrailingPathSeparator(resource, sep = paths.sep) {
            if (resource.scheme === network_1.Schemas.file) {
                const fsp = originalFSPath(resource);
                return fsp.length > extpath.getRoot(fsp).length && fsp[fsp.length - 1] === sep;
            }
            else {
                const p = resource.path;
                return (p.length > 1 && p.charCodeAt(p.length - 1) === 47 /* CharCode.Slash */) && !(/^[a-zA-Z]:(\/$|\\$)/.test(resource.fsPath)); // ignore the slash at offset 0
            }
        }
        removeTrailingPathSeparator(resource, sep = paths.sep) {
            // Make sure that the path isn't a drive letter. A trailing separator there is not removable.
            if ((0, exports.hasTrailingPathSeparator)(resource, sep)) {
                return resource.with({ path: resource.path.substr(0, resource.path.length - 1) });
            }
            return resource;
        }
        addTrailingPathSeparator(resource, sep = paths.sep) {
            let isRootSep = false;
            if (resource.scheme === network_1.Schemas.file) {
                const fsp = originalFSPath(resource);
                isRootSep = ((fsp !== undefined) && (fsp.length === extpath.getRoot(fsp).length) && (fsp[fsp.length - 1] === sep));
            }
            else {
                sep = '/';
                const p = resource.path;
                isRootSep = p.length === 1 && p.charCodeAt(p.length - 1) === 47 /* CharCode.Slash */;
            }
            if (!isRootSep && !(0, exports.hasTrailingPathSeparator)(resource, sep)) {
                return resource.with({ path: resource.path + '/' });
            }
            return resource;
        }
    }
    exports.ExtUri = ExtUri;
    /**
     * Unbiased utility that takes uris "as they are". This means it can be interchanged with
     * uri#toString() usages. The following is true
     * ```
     * assertEqual(aUri.toString() === bUri.toString(), exturi.isEqual(aUri, bUri))
     * ```
     */
    exports.extUri = new ExtUri(() => false);
    /**
     * BIASED utility that _mostly_ ignored the case of urs paths. ONLY use this util if you
     * understand what you are doing.
     *
     * This utility is INCOMPATIBLE with `uri.toString()`-usages and both CANNOT be used interchanged.
     *
     * When dealing with uris from files or documents, `extUri` (the unbiased friend)is sufficient
     * because those uris come from a "trustworthy source". When creating unknown uris it's always
     * better to use `IUriIdentityService` which exposes an `IExtUri`-instance which knows when path
     * casing matters.
     */
    exports.extUriBiasedIgnorePathCase = new ExtUri(uri => {
        // A file scheme resource is in the same platform as code, so ignore case for non linux platforms
        // Resource can be from another platform. Lowering the case as an hack. Should come from File system provider
        return uri.scheme === network_1.Schemas.file ? !platform_1.isLinux : true;
    });
    /**
     * BIASED utility that always ignores the casing of uris paths. ONLY use this util if you
     * understand what you are doing.
     *
     * This utility is INCOMPATIBLE with `uri.toString()`-usages and both CANNOT be used interchanged.
     *
     * When dealing with uris from files or documents, `extUri` (the unbiased friend)is sufficient
     * because those uris come from a "trustworthy source". When creating unknown uris it's always
     * better to use `IUriIdentityService` which exposes an `IExtUri`-instance which knows when path
     * casing matters.
     */
    exports.extUriIgnorePathCase = new ExtUri(_ => true);
    exports.isEqual = exports.extUri.isEqual.bind(exports.extUri);
    exports.isEqualOrParent = exports.extUri.isEqualOrParent.bind(exports.extUri);
    exports.getComparisonKey = exports.extUri.getComparisonKey.bind(exports.extUri);
    exports.basenameOrAuthority = exports.extUri.basenameOrAuthority.bind(exports.extUri);
    exports.basename = exports.extUri.basename.bind(exports.extUri);
    exports.extname = exports.extUri.extname.bind(exports.extUri);
    exports.dirname = exports.extUri.dirname.bind(exports.extUri);
    exports.joinPath = exports.extUri.joinPath.bind(exports.extUri);
    exports.normalizePath = exports.extUri.normalizePath.bind(exports.extUri);
    exports.relativePath = exports.extUri.relativePath.bind(exports.extUri);
    exports.resolvePath = exports.extUri.resolvePath.bind(exports.extUri);
    exports.isAbsolutePath = exports.extUri.isAbsolutePath.bind(exports.extUri);
    exports.isEqualAuthority = exports.extUri.isEqualAuthority.bind(exports.extUri);
    exports.hasTrailingPathSeparator = exports.extUri.hasTrailingPathSeparator.bind(exports.extUri);
    exports.removeTrailingPathSeparator = exports.extUri.removeTrailingPathSeparator.bind(exports.extUri);
    exports.addTrailingPathSeparator = exports.extUri.addTrailingPathSeparator.bind(exports.extUri);
    /**
     * Data URI related helpers.
     */
    var DataUri;
    (function (DataUri) {
        DataUri.META_DATA_LABEL = 'label';
        DataUri.META_DATA_DESCRIPTION = 'description';
        DataUri.META_DATA_SIZE = 'size';
        DataUri.META_DATA_MIME = 'mime';
        function parseMetaData(dataUri) {
            const metadata = new Map();
            // Given a URI of:  data:image/png;size:2313;label:SomeLabel;description:SomeDescription;base64,77+9UE5...
            // the metadata is: size:2313;label:SomeLabel;description:SomeDescription
            const meta = dataUri.path.substring(dataUri.path.indexOf(';') + 1, dataUri.path.lastIndexOf(';'));
            meta.split(';').forEach(property => {
                const [key, value] = property.split(':');
                if (key && value) {
                    metadata.set(key, value);
                }
            });
            // Given a URI of:  data:image/png;size:2313;label:SomeLabel;description:SomeDescription;base64,77+9UE5...
            // the mime is: image/png
            const mime = dataUri.path.substring(0, dataUri.path.indexOf(';'));
            if (mime) {
                metadata.set(DataUri.META_DATA_MIME, mime);
            }
            return metadata;
        }
        DataUri.parseMetaData = parseMetaData;
    })(DataUri || (exports.DataUri = DataUri = {}));
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[57/*vs/base/common/htmlContent*/], __M([1/*require*/,0/*exports*/,8/*vs/base/common/errors*/,142/*vs/base/common/iconLabels*/,48/*vs/base/common/resources*/,11/*vs/base/common/strings*/,22/*vs/base/common/uri*/]), function (require, exports, errors_1, iconLabels_1, resources_1, strings_1, uri_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MarkdownString = void 0;
    exports.isEmptyMarkdownString = isEmptyMarkdownString;
    exports.isMarkdownString = isMarkdownString;
    exports.markdownStringEqual = markdownStringEqual;
    exports.escapeMarkdownSyntaxTokens = escapeMarkdownSyntaxTokens;
    exports.appendEscapedMarkdownCodeBlockFence = appendEscapedMarkdownCodeBlockFence;
    exports.escapeDoubleQuotes = escapeDoubleQuotes;
    exports.removeMarkdownEscapes = removeMarkdownEscapes;
    exports.parseHrefAndDimensions = parseHrefAndDimensions;
    class MarkdownString {
        constructor(value = '', isTrustedOrOptions = false) {
            this.value = value;
            if (typeof this.value !== 'string') {
                throw (0, errors_1.illegalArgument)('value');
            }
            if (typeof isTrustedOrOptions === 'boolean') {
                this.isTrusted = isTrustedOrOptions;
                this.supportThemeIcons = false;
                this.supportHtml = false;
            }
            else {
                this.isTrusted = isTrustedOrOptions.isTrusted ?? undefined;
                this.supportThemeIcons = isTrustedOrOptions.supportThemeIcons ?? false;
                this.supportHtml = isTrustedOrOptions.supportHtml ?? false;
            }
        }
        appendText(value, newlineStyle = 0 /* MarkdownStringTextNewlineStyle.Paragraph */) {
            this.value += escapeMarkdownSyntaxTokens(this.supportThemeIcons ? (0, iconLabels_1.escapeIcons)(value) : value) // CodeQL [SM02383] The Markdown is fully sanitized after being rendered.
                .replace(/([ \t]+)/g, (_match, g1) => '&nbsp;'.repeat(g1.length)) // CodeQL [SM02383] The Markdown is fully sanitized after being rendered.
                .replace(/\>/gm, '\\>') // CodeQL [SM02383] The Markdown is fully sanitized after being rendered.
                .replace(/\n/g, newlineStyle === 1 /* MarkdownStringTextNewlineStyle.Break */ ? '\\\n' : '\n\n'); // CodeQL [SM02383] The Markdown is fully sanitized after being rendered.
            return this;
        }
        appendMarkdown(value) {
            this.value += value;
            return this;
        }
        appendCodeblock(langId, code) {
            this.value += `\n${appendEscapedMarkdownCodeBlockFence(code, langId)}\n`;
            return this;
        }
        appendLink(target, label, title) {
            this.value += '[';
            this.value += this._escape(label, ']');
            this.value += '](';
            this.value += this._escape(String(target), ')');
            if (title) {
                this.value += ` "${this._escape(this._escape(title, '"'), ')')}"`;
            }
            this.value += ')';
            return this;
        }
        _escape(value, ch) {
            const r = new RegExp((0, strings_1.escapeRegExpCharacters)(ch), 'g');
            return value.replace(r, (match, offset) => {
                if (value.charAt(offset - 1) !== '\\') {
                    return `\\${match}`;
                }
                else {
                    return match;
                }
            });
        }
    }
    exports.MarkdownString = MarkdownString;
    function isEmptyMarkdownString(oneOrMany) {
        if (isMarkdownString(oneOrMany)) {
            return !oneOrMany.value;
        }
        else if (Array.isArray(oneOrMany)) {
            return oneOrMany.every(isEmptyMarkdownString);
        }
        else {
            return true;
        }
    }
    function isMarkdownString(thing) {
        if (thing instanceof MarkdownString) {
            return true;
        }
        else if (thing && typeof thing === 'object') {
            return typeof thing.value === 'string'
                && (typeof thing.isTrusted === 'boolean' || typeof thing.isTrusted === 'object' || thing.isTrusted === undefined)
                && (typeof thing.supportThemeIcons === 'boolean' || thing.supportThemeIcons === undefined);
        }
        return false;
    }
    function markdownStringEqual(a, b) {
        if (a === b) {
            return true;
        }
        else if (!a || !b) {
            return false;
        }
        else {
            return a.value === b.value
                && a.isTrusted === b.isTrusted
                && a.supportThemeIcons === b.supportThemeIcons
                && a.supportHtml === b.supportHtml
                && (a.baseUri === b.baseUri || !!a.baseUri && !!b.baseUri && (0, resources_1.isEqual)(uri_1.URI.from(a.baseUri), uri_1.URI.from(b.baseUri)));
        }
    }
    function escapeMarkdownSyntaxTokens(text) {
        // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash
        return text.replace(/[\\`*_{}[\]()#+\-!~]/g, '\\$&'); // CodeQL [SM02383] Backslash is escaped in the character class
    }
    /**
     * @see https://github.com/microsoft/vscode/issues/193746
     */
    function appendEscapedMarkdownCodeBlockFence(code, langId) {
        const longestFenceLength = code.match(/^`+/gm)?.reduce((a, b) => (a.length > b.length ? a : b)).length ??
            0;
        const desiredFenceLength = longestFenceLength >= 3 ? longestFenceLength + 1 : 3;
        // the markdown result
        return [
            `${'`'.repeat(desiredFenceLength)}${langId}`,
            code,
            `${'`'.repeat(desiredFenceLength)}`,
        ].join('\n');
    }
    function escapeDoubleQuotes(input) {
        return input.replace(/"/g, '&quot;');
    }
    function removeMarkdownEscapes(text) {
        if (!text) {
            return text;
        }
        return text.replace(/\\([\\`*_{}[\]()#+\-.!~])/g, '$1');
    }
    function parseHrefAndDimensions(href) {
        const dimensions = [];
        const splitted = href.split('|').map(s => s.trim());
        href = splitted[0];
        const parameters = splitted[1];
        if (parameters) {
            const heightFromParams = /height=(\d+)/.exec(parameters);
            const widthFromParams = /width=(\d+)/.exec(parameters);
            const height = heightFromParams ? heightFromParams[1] : '';
            const width = widthFromParams ? widthFromParams[1] : '';
            const widthIsFinite = isFinite(parseInt(width));
            const heightIsFinite = isFinite(parseInt(height));
            if (widthIsFinite) {
                dimensions.push(`width="${width}"`);
            }
            if (heightIsFinite) {
                dimensions.push(`height="${height}"`);
            }
        }
        return { href, dimensions };
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[207/*vs/base/browser/markdownRenderer*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,351/*vs/base/browser/dompurify/dompurify*/,93/*vs/base/browser/event*/,352/*vs/base/browser/formattedTextRenderer*/,47/*vs/base/browser/keyboardEvent*/,77/*vs/base/browser/mouseEvent*/,114/*vs/base/browser/ui/iconLabel/iconLabels*/,8/*vs/base/common/errors*/,6/*vs/base/common/event*/,57/*vs/base/common/htmlContent*/,142/*vs/base/common/iconLabels*/,187/*vs/base/common/idGenerator*/,98/*vs/base/common/lazy*/,2/*vs/base/common/lifecycle*/,447/*vs/base/common/marked/marked*/,252/*vs/base/common/marshalling*/,42/*vs/base/common/network*/,60/*vs/base/common/objects*/,48/*vs/base/common/resources*/,11/*vs/base/common/strings*/,22/*vs/base/common/uri*/]), function (require, exports, DOM, dompurify, event_1, formattedTextRenderer_1, keyboardEvent_1, mouseEvent_1, iconLabels_1, errors_1, event_2, htmlContent_1, iconLabels_2, idGenerator_1, lazy_1, lifecycle_1, marked, marshalling_1, network_1, objects_1, resources_1, strings_1, uri_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.allowedMarkdownAttr = void 0;
    exports.renderMarkdown = renderMarkdown;
    exports.renderStringAsPlaintext = renderStringAsPlaintext;
    exports.renderMarkdownAsPlaintext = renderMarkdownAsPlaintext;
    exports.fillInIncompleteTokens = fillInIncompleteTokens;
    const defaultMarkedRenderers = Object.freeze({
        image: ({ href, title, text }) => {
            let dimensions = [];
            let attributes = [];
            if (href) {
                ({ href, dimensions } = (0, htmlContent_1.parseHrefAndDimensions)(href));
                attributes.push(`src="${(0, htmlContent_1.escapeDoubleQuotes)(href)}"`);
            }
            if (text) {
                attributes.push(`alt="${(0, htmlContent_1.escapeDoubleQuotes)(text)}"`);
            }
            if (title) {
                attributes.push(`title="${(0, htmlContent_1.escapeDoubleQuotes)(title)}"`);
            }
            if (dimensions.length) {
                attributes = attributes.concat(dimensions);
            }
            return '<img ' + attributes.join(' ') + '>';
        },
        paragraph({ tokens }) {
            return `<p>${this.parser.parseInline(tokens)}</p>`;
        },
        link({ href, title, tokens }) {
            let text = this.parser.parseInline(tokens);
            if (typeof href !== 'string') {
                return '';
            }
            // Remove markdown escapes. Workaround for https://github.com/chjj/marked/issues/829
            if (href === text) { // raw link case
                text = (0, htmlContent_1.removeMarkdownEscapes)(text);
            }
            title = typeof title === 'string' ? (0, htmlContent_1.escapeDoubleQuotes)((0, htmlContent_1.removeMarkdownEscapes)(title)) : '';
            href = (0, htmlContent_1.removeMarkdownEscapes)(href);
            // HTML Encode href
            href = href.replace(/&/g, '&amp;')
                .replace(/</g, '&lt;')
                .replace(/>/g, '&gt;')
                .replace(/"/g, '&quot;')
                .replace(/'/g, '&#39;');
            return `<a href="${href}" title="${title || href}" draggable="false">${text}</a>`;
        },
    });
    /**
     * Low-level way create a html element from a markdown string.
     *
     * **Note** that for most cases you should be using [`MarkdownRenderer`](./src/vs/editor/contrib/markdownRenderer/browser/markdownRenderer.ts)
     * which comes with support for pretty code block rendering and which uses the default way of handling links.
     */
    function renderMarkdown(markdown, options = {}, markedOptions = {}) {
        const disposables = new lifecycle_1.DisposableStore();
        let isDisposed = false;
        const element = (0, formattedTextRenderer_1.createElement)(options);
        const _uriMassage = function (part) {
            let data;
            try {
                data = (0, marshalling_1.parse)(decodeURIComponent(part));
            }
            catch (e) {
                // ignore
            }
            if (!data) {
                return part;
            }
            data = (0, objects_1.cloneAndChange)(data, value => {
                if (markdown.uris && markdown.uris[value]) {
                    return uri_1.URI.revive(markdown.uris[value]);
                }
                else {
                    return undefined;
                }
            });
            return encodeURIComponent(JSON.stringify(data));
        };
        const _href = function (href, isDomUri) {
            const data = markdown.uris && markdown.uris[href];
            let uri = uri_1.URI.revive(data);
            if (isDomUri) {
                if (href.startsWith(network_1.Schemas.data + ':')) {
                    return href;
                }
                if (!uri) {
                    uri = uri_1.URI.parse(href);
                }
                // this URI will end up as "src"-attribute of a dom node
                // and because of that special rewriting needs to be done
                // so that the URI uses a protocol that's understood by
                // browsers (like http or https)
                return network_1.FileAccess.uriToBrowserUri(uri).toString(true);
            }
            if (!uri) {
                return href;
            }
            if (uri_1.URI.parse(href).toString() === uri.toString()) {
                return href; // no transformation performed
            }
            if (uri.query) {
                uri = uri.with({ query: _uriMassage(uri.query) });
            }
            return uri.toString();
        };
        const renderer = new marked.Renderer();
        renderer.image = defaultMarkedRenderers.image;
        renderer.link = defaultMarkedRenderers.link;
        renderer.paragraph = defaultMarkedRenderers.paragraph;
        // Will collect [id, renderedElement] tuples
        const codeBlocks = [];
        const syncCodeBlocks = [];
        if (options.codeBlockRendererSync) {
            renderer.code = ({ text, lang }) => {
                const id = idGenerator_1.defaultGenerator.nextId();
                const value = options.codeBlockRendererSync(postProcessCodeBlockLanguageId(lang), text);
                syncCodeBlocks.push([id, value]);
                return `<div class="code" data-code="${id}">${(0, strings_1.escape)(text)}</div>`;
            };
        }
        else if (options.codeBlockRenderer) {
            renderer.code = ({ text, lang }) => {
                const id = idGenerator_1.defaultGenerator.nextId();
                const value = options.codeBlockRenderer(postProcessCodeBlockLanguageId(lang), text);
                codeBlocks.push(value.then(element => [id, element]));
                return `<div class="code" data-code="${id}">${(0, strings_1.escape)(text)}</div>`;
            };
        }
        if (options.actionHandler) {
            const _activateLink = function (event) {
                let target = event.target;
                if (target.tagName !== 'A') {
                    target = target.parentElement;
                    if (!target || target.tagName !== 'A') {
                        return;
                    }
                }
                try {
                    let href = target.dataset['href'];
                    if (href) {
                        if (markdown.baseUri) {
                            href = resolveWithBaseUri(uri_1.URI.from(markdown.baseUri), href);
                        }
                        options.actionHandler.callback(href, event);
                    }
                }
                catch (err) {
                    (0, errors_1.onUnexpectedError)(err);
                }
                finally {
                    event.preventDefault();
                }
            };
            const onClick = options.actionHandler.disposables.add(new event_1.DomEmitter(element, 'click'));
            const onAuxClick = options.actionHandler.disposables.add(new event_1.DomEmitter(element, 'auxclick'));
            options.actionHandler.disposables.add(event_2.Event.any(onClick.event, onAuxClick.event)(e => {
                const mouseEvent = new mouseEvent_1.StandardMouseEvent(DOM.getWindow(element), e);
                if (!mouseEvent.leftButton && !mouseEvent.middleButton) {
                    return;
                }
                _activateLink(mouseEvent);
            }));
            options.actionHandler.disposables.add(DOM.addDisposableListener(element, 'keydown', (e) => {
                const keyboardEvent = new keyboardEvent_1.StandardKeyboardEvent(e);
                if (!keyboardEvent.equals(10 /* KeyCode.Space */) && !keyboardEvent.equals(3 /* KeyCode.Enter */)) {
                    return;
                }
                _activateLink(keyboardEvent);
            }));
        }
        if (!markdown.supportHtml) {
            // Note: we always pass the output through dompurify after this so that we don't rely on
            // marked for real sanitization.
            renderer.html = ({ text }) => {
                if (options.sanitizerOptions?.replaceWithPlaintext) {
                    return (0, strings_1.escape)(text);
                }
                const match = markdown.isTrusted ? text.match(/^(<span[^>]+>)|(<\/\s*span>)$/) : undefined;
                return match ? text : '';
            };
        }
        markedOptions.renderer = renderer;
        // values that are too long will freeze the UI
        let value = markdown.value ?? '';
        if (value.length > 100_000) {
            value = `${value.substr(0, 100_000)}…`;
        }
        // escape theme icons
        if (markdown.supportThemeIcons) {
            value = (0, iconLabels_2.markdownEscapeEscapedIcons)(value);
        }
        let renderedMarkdown;
        if (options.fillInIncompleteTokens) {
            // The defaults are applied by parse but not lexer()/parser(), and they need to be present
            const opts = {
                ...marked.defaults,
                ...markedOptions
            };
            const tokens = marked.lexer(value, opts);
            const newTokens = fillInIncompleteTokens(tokens);
            renderedMarkdown = marked.parser(newTokens, opts);
        }
        else {
            renderedMarkdown = marked.parse(value, { ...markedOptions, async: false });
        }
        // Rewrite theme icons
        if (markdown.supportThemeIcons) {
            const elements = (0, iconLabels_1.renderLabelWithIcons)(renderedMarkdown);
            renderedMarkdown = elements.map(e => typeof e === 'string' ? e : e.outerHTML).join('');
        }
        const htmlParser = new DOMParser();
        const markdownHtmlDoc = htmlParser.parseFromString(sanitizeRenderedMarkdown({ isTrusted: markdown.isTrusted, ...options.sanitizerOptions }, renderedMarkdown), 'text/html');
        markdownHtmlDoc.body.querySelectorAll('img, audio, video, source')
            .forEach(img => {
            const src = img.getAttribute('src'); // Get the raw 'src' attribute value as text, not the resolved 'src'
            if (src) {
                let href = src;
                try {
                    if (markdown.baseUri) { // absolute or relative local path, or file: uri
                        href = resolveWithBaseUri(uri_1.URI.from(markdown.baseUri), href);
                    }
                }
                catch (err) { }
                img.setAttribute('src', _href(href, true));
                if (options.remoteImageIsAllowed) {
                    const uri = uri_1.URI.parse(href);
                    if (uri.scheme !== network_1.Schemas.file && uri.scheme !== network_1.Schemas.data && !options.remoteImageIsAllowed(uri)) {
                        img.replaceWith(DOM.$('', undefined, img.outerHTML));
                    }
                }
            }
        });
        markdownHtmlDoc.body.querySelectorAll('a')
            .forEach(a => {
            const href = a.getAttribute('href'); // Get the raw 'href' attribute value as text, not the resolved 'href'
            a.setAttribute('href', ''); // Clear out href. We use the `data-href` for handling clicks instead
            if (!href
                || /^data:|javascript:/i.test(href)
                || (/^command:/i.test(href) && !markdown.isTrusted)
                || /^command:(\/\/\/)?_workbench\.downloadResource/i.test(href)) {
                // drop the link
                a.replaceWith(...a.childNodes);
            }
            else {
                let resolvedHref = _href(href, false);
                if (markdown.baseUri) {
                    resolvedHref = resolveWithBaseUri(uri_1.URI.from(markdown.baseUri), href);
                }
                a.dataset.href = resolvedHref;
            }
        });
        element.innerHTML = sanitizeRenderedMarkdown({ isTrusted: markdown.isTrusted, ...options.sanitizerOptions }, markdownHtmlDoc.body.innerHTML);
        if (codeBlocks.length > 0) {
            Promise.all(codeBlocks).then((tuples) => {
                if (isDisposed) {
                    return;
                }
                const renderedElements = new Map(tuples);
                const placeholderElements = element.querySelectorAll(`div[data-code]`);
                for (const placeholderElement of placeholderElements) {
                    const renderedElement = renderedElements.get(placeholderElement.dataset['code'] ?? '');
                    if (renderedElement) {
                        DOM.reset(placeholderElement, renderedElement);
                    }
                }
                options.asyncRenderCallback?.();
            });
        }
        else if (syncCodeBlocks.length > 0) {
            const renderedElements = new Map(syncCodeBlocks);
            const placeholderElements = element.querySelectorAll(`div[data-code]`);
            for (const placeholderElement of placeholderElements) {
                const renderedElement = renderedElements.get(placeholderElement.dataset['code'] ?? '');
                if (renderedElement) {
                    DOM.reset(placeholderElement, renderedElement);
                }
            }
        }
        // signal size changes for image tags
        if (options.asyncRenderCallback) {
            for (const img of element.getElementsByTagName('img')) {
                const listener = disposables.add(DOM.addDisposableListener(img, 'load', () => {
                    listener.dispose();
                    options.asyncRenderCallback();
                }));
            }
        }
        return {
            element,
            dispose: () => {
                isDisposed = true;
                disposables.dispose();
            }
        };
    }
    function postProcessCodeBlockLanguageId(lang) {
        if (!lang) {
            return '';
        }
        const parts = lang.split(/[\s+|:|,|\{|\?]/, 1);
        if (parts.length) {
            return parts[0];
        }
        return lang;
    }
    function resolveWithBaseUri(baseUri, href) {
        const hasScheme = /^\w[\w\d+.-]*:/.test(href);
        if (hasScheme) {
            return href;
        }
        if (baseUri.path.endsWith('/')) {
            return (0, resources_1.resolvePath)(baseUri, href).toString();
        }
        else {
            return (0, resources_1.resolvePath)((0, resources_1.dirname)(baseUri), href).toString();
        }
    }
    const selfClosingTags = ['area', 'base', 'br', 'col', 'command', 'embed', 'hr', 'img', 'input', 'keygen', 'link', 'meta', 'param', 'source', 'track', 'wbr'];
    function sanitizeRenderedMarkdown(options, renderedMarkdown) {
        const { config, allowedSchemes } = getSanitizerOptions(options);
        const store = new lifecycle_1.DisposableStore();
        store.add(addDompurifyHook('uponSanitizeAttribute', (element, e) => {
            if (e.attrName === 'style' || e.attrName === 'class') {
                if (element.tagName === 'SPAN') {
                    if (e.attrName === 'style') {
                        e.keepAttr = /^(color\:(#[0-9a-fA-F]+|var\(--vscode(-[a-zA-Z]+)+\));)?(background-color\:(#[0-9a-fA-F]+|var\(--vscode(-[a-zA-Z]+)+\));)?(border-radius:[0-9]+px;)?$/.test(e.attrValue);
                        return;
                    }
                    else if (e.attrName === 'class') {
                        e.keepAttr = /^codicon codicon-[a-z\-]+( codicon-modifier-[a-z\-]+)?$/.test(e.attrValue);
                        return;
                    }
                }
                e.keepAttr = false;
                return;
            }
            else if (element.tagName === 'INPUT' && element.attributes.getNamedItem('type')?.value === 'checkbox') {
                if ((e.attrName === 'type' && e.attrValue === 'checkbox') || e.attrName === 'disabled' || e.attrName === 'checked') {
                    e.keepAttr = true;
                    return;
                }
                e.keepAttr = false;
            }
        }));
        store.add(addDompurifyHook('uponSanitizeElement', (element, e) => {
            if (e.tagName === 'input') {
                if (element.attributes.getNamedItem('type')?.value === 'checkbox') {
                    element.setAttribute('disabled', '');
                }
                else if (!options.replaceWithPlaintext) {
                    element.remove();
                }
            }
            if (options.replaceWithPlaintext && !e.allowedTags[e.tagName] && e.tagName !== 'body') {
                if (element.parentElement) {
                    let startTagText;
                    let endTagText;
                    if (e.tagName === '#comment') {
                        startTagText = `<!--${element.textContent}-->`;
                    }
                    else {
                        const isSelfClosing = selfClosingTags.includes(e.tagName);
                        const attrString = element.attributes.length ?
                            ' ' + Array.from(element.attributes)
                                .map(attr => `${attr.name}="${attr.value}"`)
                                .join(' ')
                            : '';
                        startTagText = `<${e.tagName}${attrString}>`;
                        if (!isSelfClosing) {
                            endTagText = `</${e.tagName}>`;
                        }
                    }
                    const fragment = document.createDocumentFragment();
                    const textNode = element.parentElement.ownerDocument.createTextNode(startTagText);
                    fragment.appendChild(textNode);
                    const endTagTextNode = endTagText ? element.parentElement.ownerDocument.createTextNode(endTagText) : undefined;
                    while (element.firstChild) {
                        fragment.appendChild(element.firstChild);
                    }
                    if (endTagTextNode) {
                        fragment.appendChild(endTagTextNode);
                    }
                    element.parentElement.replaceChild(fragment, element);
                }
            }
        }));
        store.add(DOM.hookDomPurifyHrefAndSrcSanitizer(allowedSchemes));
        try {
            return dompurify.sanitize(renderedMarkdown, { ...config, RETURN_TRUSTED_TYPE: true });
        }
        finally {
            store.dispose();
        }
    }
    exports.allowedMarkdownAttr = [
        'align',
        'autoplay',
        'alt',
        'checked',
        'class',
        'colspan',
        'controls',
        'data-code',
        'data-href',
        'disabled',
        'draggable',
        'height',
        'href',
        'loop',
        'muted',
        'playsinline',
        'poster',
        'rowspan',
        'src',
        'style',
        'target',
        'title',
        'type',
        'width',
        'start',
    ];
    function getSanitizerOptions(options) {
        const allowedSchemes = [
            network_1.Schemas.http,
            network_1.Schemas.https,
            network_1.Schemas.mailto,
            network_1.Schemas.data,
            network_1.Schemas.file,
            network_1.Schemas.vscodeFileResource,
            network_1.Schemas.vscodeRemote,
            network_1.Schemas.vscodeRemoteResource,
        ];
        if (options.isTrusted) {
            allowedSchemes.push(network_1.Schemas.command);
        }
        return {
            config: {
                // allowedTags should included everything that markdown renders to.
                // Since we have our own sanitize function for marked, it's possible we missed some tag so let dompurify make sure.
                // HTML tags that can result from markdown are from reading https://spec.commonmark.org/0.29/
                // HTML table tags that can result from markdown are from https://github.github.com/gfm/#tables-extension-
                ALLOWED_TAGS: options.allowedTags ?? [...DOM.basicMarkupHtmlTags],
                ALLOWED_ATTR: exports.allowedMarkdownAttr,
                ALLOW_UNKNOWN_PROTOCOLS: true,
            },
            allowedSchemes
        };
    }
    /**
     * Strips all markdown from `string`, if it's an IMarkdownString. For example
     * `# Header` would be output as `Header`. If it's not, the string is returned.
     */
    function renderStringAsPlaintext(string) {
        return typeof string === 'string' ? string : renderMarkdownAsPlaintext(string);
    }
    /**
     * Strips all markdown from `markdown`. For example `# Header` would be output as `Header`.
     * provide @param withCodeBlocks to retain code blocks
     */
    function renderMarkdownAsPlaintext(markdown, withCodeBlocks) {
        // values that are too long will freeze the UI
        let value = markdown.value ?? '';
        if (value.length > 100_000) {
            value = `${value.substr(0, 100_000)}…`;
        }
        const html = marked.parse(value, { async: false, renderer: withCodeBlocks ? plainTextWithCodeBlocksRenderer.value : plainTextRenderer.value }).replace(/&(#\d+|[a-zA-Z]+);/g, m => unescapeInfo.get(m) ?? m);
        return sanitizeRenderedMarkdown({ isTrusted: false }, html).toString();
    }
    const unescapeInfo = new Map([
        ['&quot;', '"'],
        ['&nbsp;', ' '],
        ['&amp;', '&'],
        ['&#39;', '\''],
        ['&lt;', '<'],
        ['&gt;', '>'],
    ]);
    function createRenderer() {
        const renderer = new marked.Renderer();
        renderer.code = ({ text }) => {
            return text;
        };
        renderer.blockquote = ({ text }) => {
            return text + '\n';
        };
        renderer.html = (_) => {
            return '';
        };
        renderer.heading = function ({ tokens }) {
            return this.parser.parseInline(tokens) + '\n';
        };
        renderer.hr = () => {
            return '';
        };
        renderer.list = function ({ items }) {
            return items.map(x => this.listitem(x)).join('\n') + '\n';
        };
        renderer.listitem = ({ text }) => {
            return text + '\n';
        };
        renderer.paragraph = function ({ tokens }) {
            return this.parser.parseInline(tokens) + '\n';
        };
        renderer.table = function ({ header, rows }) {
            return header.map(cell => this.tablecell(cell)).join(' ') + '\n' + rows.map(cells => cells.map(cell => this.tablecell(cell)).join(' ')).join('\n') + '\n';
        };
        renderer.tablerow = ({ text }) => {
            return text;
        };
        renderer.tablecell = function ({ tokens }) {
            return this.parser.parseInline(tokens);
        };
        renderer.strong = ({ text }) => {
            return text;
        };
        renderer.em = ({ text }) => {
            return text;
        };
        renderer.codespan = ({ text }) => {
            return text;
        };
        renderer.br = (_) => {
            return '\n';
        };
        renderer.del = ({ text }) => {
            return text;
        };
        renderer.image = (_) => {
            return '';
        };
        renderer.text = ({ text }) => {
            return text;
        };
        renderer.link = ({ text }) => {
            return text;
        };
        return renderer;
    }
    const plainTextRenderer = new lazy_1.Lazy((withCodeBlocks) => createRenderer());
    const plainTextWithCodeBlocksRenderer = new lazy_1.Lazy(() => {
        const renderer = createRenderer();
        renderer.code = ({ text }) => {
            return `\n\`\`\`\n${text}\n\`\`\`\n`;
        };
        return renderer;
    });
    function mergeRawTokenText(tokens) {
        let mergedTokenText = '';
        tokens.forEach(token => {
            mergedTokenText += token.raw;
        });
        return mergedTokenText;
    }
    function completeSingleLinePattern(token) {
        if (!token.tokens) {
            return undefined;
        }
        for (let i = token.tokens.length - 1; i >= 0; i--) {
            const subtoken = token.tokens[i];
            if (subtoken.type === 'text') {
                const lines = subtoken.raw.split('\n');
                const lastLine = lines[lines.length - 1];
                if (lastLine.includes('`')) {
                    return completeCodespan(token);
                }
                else if (lastLine.includes('**')) {
                    return completeDoublestar(token);
                }
                else if (lastLine.match(/\*\w/)) {
                    return completeStar(token);
                }
                else if (lastLine.match(/(^|\s)__\w/)) {
                    return completeDoubleUnderscore(token);
                }
                else if (lastLine.match(/(^|\s)_\w/)) {
                    return completeUnderscore(token);
                }
                else if (
                // Text with start of link target
                hasLinkTextAndStartOfLinkTarget(lastLine) ||
                    // This token doesn't have the link text, eg if it contains other markdown constructs that are in other subtokens.
                    // But some preceding token does have an unbalanced [ at least
                    hasStartOfLinkTargetAndNoLinkText(lastLine) && token.tokens.slice(0, i).some(t => t.type === 'text' && t.raw.match(/\[[^\]]*$/))) {
                    const nextTwoSubTokens = token.tokens.slice(i + 1);
                    // A markdown link can look like
                    // [link text](https://microsoft.com "more text")
                    // Where "more text" is a title for the link or an argument to a vscode command link
                    if (
                    // If the link was parsed as a link, then look for a link token and a text token with a quote
                    nextTwoSubTokens[0]?.type === 'link' && nextTwoSubTokens[1]?.type === 'text' && nextTwoSubTokens[1].raw.match(/^ *"[^"]*$/) ||
                        // And if the link was not parsed as a link (eg command link), just look for a single quote in this token
                        lastLine.match(/^[^"]* +"[^"]*$/)) {
                        return completeLinkTargetArg(token);
                    }
                    return completeLinkTarget(token);
                }
                // Contains the start of link text, and no following tokens contain the link target
                else if (lastLine.match(/(^|\s)\[\w*/)) {
                    return completeLinkText(token);
                }
            }
        }
        return undefined;
    }
    function hasLinkTextAndStartOfLinkTarget(str) {
        return !!str.match(/(^|\s)\[.*\]\(\w*/);
    }
    function hasStartOfLinkTargetAndNoLinkText(str) {
        return !!str.match(/^[^\[]*\]\([^\)]*$/);
    }
    function completeListItemPattern(list) {
        // Patch up this one list item
        const lastListItem = list.items[list.items.length - 1];
        const lastListSubToken = lastListItem.tokens ? lastListItem.tokens[lastListItem.tokens.length - 1] : undefined;
        /*
        Example list token structures:
    
        list
            list_item
                text
                    text
                    codespan
                    link
            list_item
                text
                code // Complete indented codeblock
            list_item
                text
                space
                text
                    text // Incomplete indented codeblock
            list_item
                text
                list // Nested list
                    list_item
                        text
                            text
    
        Contrast with paragraph:
        paragraph
            text
            codespan
        */
        let newToken;
        if (lastListSubToken?.type === 'text' && !('inRawBlock' in lastListItem)) { // Why does Tag have a type of 'text'
            newToken = completeSingleLinePattern(lastListSubToken);
        }
        if (!newToken || newToken.type !== 'paragraph') { // 'text' item inside the list item turns into paragraph
            // Nothing to fix, or not a pattern we were expecting
            return;
        }
        const previousListItemsText = mergeRawTokenText(list.items.slice(0, -1));
        // Grabbing the `- ` or `1. ` or `* ` off the list item because I can't find a better way to do this
        const lastListItemLead = lastListItem.raw.match(/^(\s*(-|\d+\.|\*) +)/)?.[0];
        if (!lastListItemLead) {
            // Is badly formatted
            return;
        }
        const newListItemText = lastListItemLead +
            mergeRawTokenText(lastListItem.tokens.slice(0, -1)) +
            newToken.raw;
        const newList = marked.lexer(previousListItemsText + newListItemText)[0];
        if (newList.type !== 'list') {
            // Something went wrong
            return;
        }
        return newList;
    }
    const maxIncompleteTokensFixRounds = 3;
    function fillInIncompleteTokens(tokens) {
        for (let i = 0; i < maxIncompleteTokensFixRounds; i++) {
            const newTokens = fillInIncompleteTokensOnce(tokens);
            if (newTokens) {
                tokens = newTokens;
            }
            else {
                break;
            }
        }
        return tokens;
    }
    function fillInIncompleteTokensOnce(tokens) {
        let i;
        let newTokens;
        for (i = 0; i < tokens.length; i++) {
            const token = tokens[i];
            if (token.type === 'paragraph' && token.raw.match(/(\n|^)\|/)) {
                newTokens = completeTable(tokens.slice(i));
                break;
            }
            if (i === tokens.length - 1 && token.type === 'list') {
                const newListToken = completeListItemPattern(token);
                if (newListToken) {
                    newTokens = [newListToken];
                    break;
                }
            }
            if (i === tokens.length - 1 && token.type === 'paragraph') {
                // Only operates on a single token, because any newline that follows this should break these patterns
                const newToken = completeSingleLinePattern(token);
                if (newToken) {
                    newTokens = [newToken];
                    break;
                }
            }
        }
        if (newTokens) {
            const newTokensList = [
                ...tokens.slice(0, i),
                ...newTokens
            ];
            newTokensList.links = tokens.links;
            return newTokensList;
        }
        return null;
    }
    function completeCodespan(token) {
        return completeWithString(token, '`');
    }
    function completeStar(tokens) {
        return completeWithString(tokens, '*');
    }
    function completeUnderscore(tokens) {
        return completeWithString(tokens, '_');
    }
    function completeLinkTarget(tokens) {
        return completeWithString(tokens, ')');
    }
    function completeLinkTargetArg(tokens) {
        return completeWithString(tokens, '")');
    }
    function completeLinkText(tokens) {
        return completeWithString(tokens, '](https://microsoft.com)');
    }
    function completeDoublestar(tokens) {
        return completeWithString(tokens, '**');
    }
    function completeDoubleUnderscore(tokens) {
        return completeWithString(tokens, '__');
    }
    function completeWithString(tokens, closingString) {
        const mergedRawText = mergeRawTokenText(Array.isArray(tokens) ? tokens : [tokens]);
        // If it was completed correctly, this should be a single token.
        // Expecting either a Paragraph or a List
        return marked.lexer(mergedRawText + closingString)[0];
    }
    function completeTable(tokens) {
        const mergedRawText = mergeRawTokenText(tokens);
        const lines = mergedRawText.split('\n');
        let numCols; // The number of line1 col headers
        let hasSeparatorRow = false;
        for (let i = 0; i < lines.length; i++) {
            const line = lines[i].trim();
            if (typeof numCols === 'undefined' && line.match(/^\s*\|/)) {
                const line1Matches = line.match(/(\|[^\|]+)(?=\||$)/g);
                if (line1Matches) {
                    numCols = line1Matches.length;
                }
            }
            else if (typeof numCols === 'number') {
                if (line.match(/^\s*\|/)) {
                    if (i !== lines.length - 1) {
                        // We got the line1 header row, and the line2 separator row, but there are more lines, and it wasn't parsed as a table!
                        // That's strange and means that the table is probably malformed in the source, so I won't try to patch it up.
                        return undefined;
                    }
                    // Got a line2 separator row- partial or complete, doesn't matter, we'll replace it with a correct one
                    hasSeparatorRow = true;
                }
                else {
                    // The line after the header row isn't a valid separator row, so the table is malformed, don't fix it up
                    return undefined;
                }
            }
        }
        if (typeof numCols === 'number' && numCols > 0) {
            const prefixText = hasSeparatorRow ? lines.slice(0, -1).join('\n') : mergedRawText;
            const line1EndsInPipe = !!prefixText.match(/\|\s*$/);
            const newRawText = prefixText + (line1EndsInPipe ? '' : '|') + `\n|${' --- |'.repeat(numCols)}`;
            return marked.lexer(newRawText);
        }
        return undefined;
    }
    function addDompurifyHook(hook, cb) {
        dompurify.addHook(hook, cb);
        return (0, lifecycle_1.toDisposable)(() => dompurify.removeHook(hook));
    }
});

define(__m[258/*vs/base/browser/ui/button/button*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,351/*vs/base/browser/dompurify/dompurify*/,47/*vs/base/browser/keyboardEvent*/,207/*vs/base/browser/markdownRenderer*/,69/*vs/base/browser/touch*/,44/*vs/base/browser/ui/hover/hoverDelegateFactory*/,114/*vs/base/browser/ui/iconLabel/iconLabels*/,33/*vs/base/common/color*/,6/*vs/base/common/event*/,57/*vs/base/common/htmlContent*/,2/*vs/base/common/lifecycle*/,30/*vs/base/common/themables*/,81/*vs/base/browser/ui/hover/hoverDelegate2*/,459/*vs/css!vs/base/browser/ui/button/button*/]), function (require, exports, dom_1, dompurify_1, keyboardEvent_1, markdownRenderer_1, touch_1, hoverDelegateFactory_1, iconLabels_1, color_1, event_1, htmlContent_1, lifecycle_1, themables_1, hoverDelegate2_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Button = exports.unthemedButtonStyles = void 0;
    exports.unthemedButtonStyles = {
        buttonBackground: '#0E639C',
        buttonHoverBackground: '#006BB3',
        buttonSeparator: color_1.Color.white.toString(),
        buttonForeground: color_1.Color.white.toString(),
        buttonBorder: undefined,
        buttonSecondaryBackground: undefined,
        buttonSecondaryForeground: undefined,
        buttonSecondaryHoverBackground: undefined
    };
    class Button extends lifecycle_1.Disposable {
        get onDidClick() { return this._onDidClick.event; }
        constructor(container, options) {
            super();
            this._label = '';
            this._onDidClick = this._register(new event_1.Emitter());
            this._onDidEscape = this._register(new event_1.Emitter());
            this.options = options;
            this._element = document.createElement('a');
            this._element.classList.add('monaco-button');
            this._element.tabIndex = 0;
            this._element.setAttribute('role', 'button');
            this._element.classList.toggle('secondary', !!options.secondary);
            const background = options.secondary ? options.buttonSecondaryBackground : options.buttonBackground;
            const foreground = options.secondary ? options.buttonSecondaryForeground : options.buttonForeground;
            this._element.style.color = foreground || '';
            this._element.style.backgroundColor = background || '';
            if (options.supportShortLabel) {
                this._labelShortElement = document.createElement('div');
                this._labelShortElement.classList.add('monaco-button-label-short');
                this._element.appendChild(this._labelShortElement);
                this._labelElement = document.createElement('div');
                this._labelElement.classList.add('monaco-button-label');
                this._element.appendChild(this._labelElement);
                this._element.classList.add('monaco-text-button-with-short-label');
            }
            if (typeof options.title === 'string') {
                this.setTitle(options.title);
            }
            if (typeof options.ariaLabel === 'string') {
                this._element.setAttribute('aria-label', options.ariaLabel);
            }
            container.appendChild(this._element);
            this._register(touch_1.Gesture.addTarget(this._element));
            [dom_1.EventType.CLICK, touch_1.EventType.Tap].forEach(eventType => {
                this._register((0, dom_1.addDisposableListener)(this._element, eventType, e => {
                    if (!this.enabled) {
                        dom_1.EventHelper.stop(e);
                        return;
                    }
                    this._onDidClick.fire(e);
                }));
            });
            this._register((0, dom_1.addDisposableListener)(this._element, dom_1.EventType.KEY_DOWN, e => {
                const event = new keyboardEvent_1.StandardKeyboardEvent(e);
                let eventHandled = false;
                if (this.enabled && (event.equals(3 /* KeyCode.Enter */) || event.equals(10 /* KeyCode.Space */))) {
                    this._onDidClick.fire(e);
                    eventHandled = true;
                }
                else if (event.equals(9 /* KeyCode.Escape */)) {
                    this._onDidEscape.fire(e);
                    this._element.blur();
                    eventHandled = true;
                }
                if (eventHandled) {
                    dom_1.EventHelper.stop(event, true);
                }
            }));
            this._register((0, dom_1.addDisposableListener)(this._element, dom_1.EventType.MOUSE_OVER, e => {
                if (!this._element.classList.contains('disabled')) {
                    this.updateBackground(true);
                }
            }));
            this._register((0, dom_1.addDisposableListener)(this._element, dom_1.EventType.MOUSE_OUT, e => {
                this.updateBackground(false); // restore standard styles
            }));
            // Also set hover background when button is focused for feedback
            this.focusTracker = this._register((0, dom_1.trackFocus)(this._element));
            this._register(this.focusTracker.onDidFocus(() => { if (this.enabled) {
                this.updateBackground(true);
            } }));
            this._register(this.focusTracker.onDidBlur(() => { if (this.enabled) {
                this.updateBackground(false);
            } }));
        }
        dispose() {
            super.dispose();
            this._element.remove();
        }
        getContentElements(content) {
            const elements = [];
            for (let segment of (0, iconLabels_1.renderLabelWithIcons)(content)) {
                if (typeof (segment) === 'string') {
                    segment = segment.trim();
                    // Ignore empty segment
                    if (segment === '') {
                        continue;
                    }
                    // Convert string segments to <span> nodes
                    const node = document.createElement('span');
                    node.textContent = segment;
                    elements.push(node);
                }
                else {
                    elements.push(segment);
                }
            }
            return elements;
        }
        updateBackground(hover) {
            let background;
            if (this.options.secondary) {
                background = hover ? this.options.buttonSecondaryHoverBackground : this.options.buttonSecondaryBackground;
            }
            else {
                background = hover ? this.options.buttonHoverBackground : this.options.buttonBackground;
            }
            if (background) {
                this._element.style.backgroundColor = background;
            }
        }
        get element() {
            return this._element;
        }
        set label(value) {
            if (this._label === value) {
                return;
            }
            if ((0, htmlContent_1.isMarkdownString)(this._label) && (0, htmlContent_1.isMarkdownString)(value) && (0, htmlContent_1.markdownStringEqual)(this._label, value)) {
                return;
            }
            this._element.classList.add('monaco-text-button');
            const labelElement = this.options.supportShortLabel ? this._labelElement : this._element;
            if ((0, htmlContent_1.isMarkdownString)(value)) {
                const rendered = (0, markdownRenderer_1.renderMarkdown)(value, { inline: true });
                rendered.dispose();
                // Don't include outer `<p>`
                const root = rendered.element.querySelector('p')?.innerHTML;
                if (root) {
                    // Only allow a very limited set of inline html tags
                    const sanitized = (0, dompurify_1.sanitize)(root, { ADD_TAGS: ['b', 'i', 'u', 'code', 'span'], ALLOWED_ATTR: ['class'], RETURN_TRUSTED_TYPE: true });
                    labelElement.innerHTML = sanitized;
                }
                else {
                    (0, dom_1.reset)(labelElement);
                }
            }
            else {
                if (this.options.supportIcons) {
                    (0, dom_1.reset)(labelElement, ...this.getContentElements(value));
                }
                else {
                    labelElement.textContent = value;
                }
            }
            let title = '';
            if (typeof this.options.title === 'string') {
                title = this.options.title;
            }
            else if (this.options.title) {
                title = (0, markdownRenderer_1.renderStringAsPlaintext)(value);
            }
            this.setTitle(title);
            if (typeof this.options.ariaLabel === 'string') {
                this._element.setAttribute('aria-label', this.options.ariaLabel);
            }
            else if (this.options.ariaLabel) {
                this._element.setAttribute('aria-label', title);
            }
            this._label = value;
        }
        get label() {
            return this._label;
        }
        set icon(icon) {
            this._element.classList.add(...themables_1.ThemeIcon.asClassNameArray(icon));
        }
        set enabled(value) {
            if (value) {
                this._element.classList.remove('disabled');
                this._element.setAttribute('aria-disabled', String(false));
                this._element.tabIndex = 0;
            }
            else {
                this._element.classList.add('disabled');
                this._element.setAttribute('aria-disabled', String(true));
            }
        }
        get enabled() {
            return !this._element.classList.contains('disabled');
        }
        setTitle(title) {
            if (!this._hover && title !== '') {
                this._hover = this._register((0, hoverDelegate2_1.getBaseLayerHoverDelegate)().setupManagedHover(this.options.hoverDelegate ?? (0, hoverDelegateFactory_1.getDefaultHoverDelegate)('mouse'), this._element, title));
            }
            else if (this._hover) {
                this._hover.update(title);
            }
        }
    }
    exports.Button = Button;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[639/*vs/base/browser/ui/selectBox/selectBoxCustom*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,93/*vs/base/browser/event*/,47/*vs/base/browser/keyboardEvent*/,207/*vs/base/browser/markdownRenderer*/,81/*vs/base/browser/ui/hover/hoverDelegate2*/,44/*vs/base/browser/ui/hover/hoverDelegateFactory*/,115/*vs/base/browser/ui/list/listWidget*/,13/*vs/base/common/arrays*/,6/*vs/base/common/event*/,72/*vs/base/common/keyCodes*/,2/*vs/base/common/lifecycle*/,16/*vs/base/common/platform*/,3/*vs/nls*/,473/*vs/css!vs/base/browser/ui/selectBox/selectBoxCustom*/]), function (require, exports, dom, event_1, keyboardEvent_1, markdownRenderer_1, hoverDelegate2_1, hoverDelegateFactory_1, listWidget_1, arrays, event_2, keyCodes_1, lifecycle_1, platform_1, nls_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SelectBoxList = void 0;
    const $ = dom.$;
    const SELECT_OPTION_ENTRY_TEMPLATE_ID = 'selectOption.entry.template';
    class SelectListRenderer {
        get templateId() { return SELECT_OPTION_ENTRY_TEMPLATE_ID; }
        renderTemplate(container) {
            const data = Object.create(null);
            data.root = container;
            data.text = dom.append(container, $('.option-text'));
            data.detail = dom.append(container, $('.option-detail'));
            data.decoratorRight = dom.append(container, $('.option-decorator-right'));
            return data;
        }
        renderElement(element, index, templateData) {
            const data = templateData;
            const text = element.text;
            const detail = element.detail;
            const decoratorRight = element.decoratorRight;
            const isDisabled = element.isDisabled;
            data.text.textContent = text;
            data.detail.textContent = !!detail ? detail : '';
            data.decoratorRight.innerText = !!decoratorRight ? decoratorRight : '';
            // pseudo-select disabled option
            if (isDisabled) {
                data.root.classList.add('option-disabled');
            }
            else {
                // Make sure we do class removal from prior template rendering
                data.root.classList.remove('option-disabled');
            }
        }
        disposeTemplate(_templateData) {
            // noop
        }
    }
    class SelectBoxList extends lifecycle_1.Disposable {
        static { this.DEFAULT_DROPDOWN_MINIMUM_BOTTOM_MARGIN = 32; }
        static { this.DEFAULT_DROPDOWN_MINIMUM_TOP_MARGIN = 2; }
        static { this.DEFAULT_MINIMUM_VISIBLE_OPTIONS = 3; }
        constructor(options, selected, contextViewProvider, styles, selectBoxOptions) {
            super();
            this.options = [];
            this._currentSelection = 0;
            this._hasDetails = false;
            this._skipLayout = false;
            this._sticky = false; // for dev purposes only
            this._isVisible = false;
            this.styles = styles;
            this.selectBoxOptions = selectBoxOptions || Object.create(null);
            if (typeof this.selectBoxOptions.minBottomMargin !== 'number') {
                this.selectBoxOptions.minBottomMargin = SelectBoxList.DEFAULT_DROPDOWN_MINIMUM_BOTTOM_MARGIN;
            }
            else if (this.selectBoxOptions.minBottomMargin < 0) {
                this.selectBoxOptions.minBottomMargin = 0;
            }
            this.selectElement = document.createElement('select');
            // Use custom CSS vars for padding calculation
            this.selectElement.className = 'monaco-select-box monaco-select-box-dropdown-padding';
            if (typeof this.selectBoxOptions.ariaLabel === 'string') {
                this.selectElement.setAttribute('aria-label', this.selectBoxOptions.ariaLabel);
            }
            if (typeof this.selectBoxOptions.ariaDescription === 'string') {
                this.selectElement.setAttribute('aria-description', this.selectBoxOptions.ariaDescription);
            }
            this._onDidSelect = new event_2.Emitter();
            this._register(this._onDidSelect);
            this.registerListeners();
            this.constructSelectDropDown(contextViewProvider);
            this.selected = selected || 0;
            if (options) {
                this.setOptions(options, selected);
            }
            this.initStyleSheet();
        }
        setTitle(title) {
            if (!this._hover && title) {
                this._hover = this._register((0, hoverDelegate2_1.getBaseLayerHoverDelegate)().setupManagedHover((0, hoverDelegateFactory_1.getDefaultHoverDelegate)('mouse'), this.selectElement, title));
            }
            else if (this._hover) {
                this._hover.update(title);
            }
        }
        // IDelegate - List renderer
        getHeight() {
            return 22;
        }
        getTemplateId() {
            return SELECT_OPTION_ENTRY_TEMPLATE_ID;
        }
        constructSelectDropDown(contextViewProvider) {
            // SetUp ContextView container to hold select Dropdown
            this.contextViewProvider = contextViewProvider;
            this.selectDropDownContainer = dom.$('.monaco-select-box-dropdown-container');
            // Use custom CSS vars for padding calculation (shared with parent select)
            this.selectDropDownContainer.classList.add('monaco-select-box-dropdown-padding');
            // Setup container for select option details
            this.selectionDetailsPane = dom.append(this.selectDropDownContainer, $('.select-box-details-pane'));
            // Create span flex box item/div we can measure and control
            const widthControlOuterDiv = dom.append(this.selectDropDownContainer, $('.select-box-dropdown-container-width-control'));
            const widthControlInnerDiv = dom.append(widthControlOuterDiv, $('.width-control-div'));
            this.widthControlElement = document.createElement('span');
            this.widthControlElement.className = 'option-text-width-control';
            dom.append(widthControlInnerDiv, this.widthControlElement);
            // Always default to below position
            this._dropDownPosition = 0 /* AnchorPosition.BELOW */;
            // Inline stylesheet for themes
            this.styleElement = dom.createStyleSheet(this.selectDropDownContainer);
            // Prevent dragging of dropdown #114329
            this.selectDropDownContainer.setAttribute('draggable', 'true');
            this._register(dom.addDisposableListener(this.selectDropDownContainer, dom.EventType.DRAG_START, (e) => {
                dom.EventHelper.stop(e, true);
            }));
        }
        registerListeners() {
            // Parent native select keyboard listeners
            this._register(dom.addStandardDisposableListener(this.selectElement, 'change', (e) => {
                this.selected = e.target.selectedIndex;
                this._onDidSelect.fire({
                    index: e.target.selectedIndex,
                    selected: e.target.value
                });
                if (!!this.options[this.selected] && !!this.options[this.selected].text) {
                    this.setTitle(this.options[this.selected].text);
                }
            }));
            // Have to implement both keyboard and mouse controllers to handle disabled options
            // Intercept mouse events to override normal select actions on parents
            this._register(dom.addDisposableListener(this.selectElement, dom.EventType.CLICK, (e) => {
                dom.EventHelper.stop(e);
                if (this._isVisible) {
                    this.hideSelectDropDown(true);
                }
                else {
                    this.showSelectDropDown();
                }
            }));
            this._register(dom.addDisposableListener(this.selectElement, dom.EventType.MOUSE_DOWN, (e) => {
                dom.EventHelper.stop(e);
            }));
            // Intercept touch events
            // The following implementation is slightly different from the mouse event handlers above.
            // Use the following helper variable, otherwise the list flickers.
            let listIsVisibleOnTouchStart;
            this._register(dom.addDisposableListener(this.selectElement, 'touchstart', (e) => {
                listIsVisibleOnTouchStart = this._isVisible;
            }));
            this._register(dom.addDisposableListener(this.selectElement, 'touchend', (e) => {
                dom.EventHelper.stop(e);
                if (listIsVisibleOnTouchStart) {
                    this.hideSelectDropDown(true);
                }
                else {
                    this.showSelectDropDown();
                }
            }));
            // Intercept keyboard handling
            this._register(dom.addDisposableListener(this.selectElement, dom.EventType.KEY_DOWN, (e) => {
                const event = new keyboardEvent_1.StandardKeyboardEvent(e);
                let showDropDown = false;
                // Create and drop down select list on keyboard select
                if (platform_1.isMacintosh) {
                    if (event.keyCode === 18 /* KeyCode.DownArrow */ || event.keyCode === 16 /* KeyCode.UpArrow */ || event.keyCode === 10 /* KeyCode.Space */ || event.keyCode === 3 /* KeyCode.Enter */) {
                        showDropDown = true;
                    }
                }
                else {
                    if (event.keyCode === 18 /* KeyCode.DownArrow */ && event.altKey || event.keyCode === 16 /* KeyCode.UpArrow */ && event.altKey || event.keyCode === 10 /* KeyCode.Space */ || event.keyCode === 3 /* KeyCode.Enter */) {
                        showDropDown = true;
                    }
                }
                if (showDropDown) {
                    this.showSelectDropDown();
                    dom.EventHelper.stop(e, true);
                }
            }));
        }
        get onDidSelect() {
            return this._onDidSelect.event;
        }
        setOptions(options, selected) {
            if (!arrays.equals(this.options, options)) {
                this.options = options;
                this.selectElement.options.length = 0;
                this._hasDetails = false;
                this._cachedMaxDetailsHeight = undefined;
                this.options.forEach((option, index) => {
                    this.selectElement.add(this.createOption(option.text, index, option.isDisabled));
                    if (typeof option.description === 'string') {
                        this._hasDetails = true;
                    }
                });
            }
            if (selected !== undefined) {
                this.select(selected);
                // Set current = selected since this is not necessarily a user exit
                this._currentSelection = this.selected;
            }
        }
        setOptionsList() {
            // Mirror options in drop-down
            // Populate select list for non-native select mode
            this.selectList?.splice(0, this.selectList.length, this.options);
        }
        select(index) {
            if (index >= 0 && index < this.options.length) {
                this.selected = index;
            }
            else if (index > this.options.length - 1) {
                // Adjust index to end of list
                // This could make client out of sync with the select
                this.select(this.options.length - 1);
            }
            else if (this.selected < 0) {
                this.selected = 0;
            }
            this.selectElement.selectedIndex = this.selected;
            if (!!this.options[this.selected] && !!this.options[this.selected].text) {
                this.setTitle(this.options[this.selected].text);
            }
        }
        focus() {
            if (this.selectElement) {
                this.selectElement.tabIndex = 0;
                this.selectElement.focus();
            }
        }
        blur() {
            if (this.selectElement) {
                this.selectElement.tabIndex = -1;
                this.selectElement.blur();
            }
        }
        setFocusable(focusable) {
            this.selectElement.tabIndex = focusable ? 0 : -1;
        }
        render(container) {
            this.container = container;
            container.classList.add('select-container');
            container.appendChild(this.selectElement);
            this.styleSelectElement();
        }
        initStyleSheet() {
            const content = [];
            // Style non-native select mode
            if (this.styles.listFocusBackground) {
                content.push(`.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row.focused { background-color: ${this.styles.listFocusBackground} !important; }`);
            }
            if (this.styles.listFocusForeground) {
                content.push(`.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row.focused { color: ${this.styles.listFocusForeground} !important; }`);
            }
            if (this.styles.decoratorRightForeground) {
                content.push(`.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row:not(.focused) .option-decorator-right { color: ${this.styles.decoratorRightForeground}; }`);
            }
            if (this.styles.selectBackground && this.styles.selectBorder && this.styles.selectBorder !== this.styles.selectBackground) {
                content.push(`.monaco-select-box-dropdown-container { border: 1px solid ${this.styles.selectBorder} } `);
                content.push(`.monaco-select-box-dropdown-container > .select-box-details-pane.border-top { border-top: 1px solid ${this.styles.selectBorder} } `);
                content.push(`.monaco-select-box-dropdown-container > .select-box-details-pane.border-bottom { border-bottom: 1px solid ${this.styles.selectBorder} } `);
            }
            else if (this.styles.selectListBorder) {
                content.push(`.monaco-select-box-dropdown-container > .select-box-details-pane.border-top { border-top: 1px solid ${this.styles.selectListBorder} } `);
                content.push(`.monaco-select-box-dropdown-container > .select-box-details-pane.border-bottom { border-bottom: 1px solid ${this.styles.selectListBorder} } `);
            }
            // Hover foreground - ignore for disabled options
            if (this.styles.listHoverForeground) {
                content.push(`.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row:not(.option-disabled):not(.focused):hover { color: ${this.styles.listHoverForeground} !important; }`);
            }
            // Hover background - ignore for disabled options
            if (this.styles.listHoverBackground) {
                content.push(`.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row:not(.option-disabled):not(.focused):hover { background-color: ${this.styles.listHoverBackground} !important; }`);
            }
            // Match quick input outline styles - ignore for disabled options
            if (this.styles.listFocusOutline) {
                content.push(`.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row.focused { outline: 1.6px dotted ${this.styles.listFocusOutline} !important; outline-offset: -1.6px !important; }`);
            }
            if (this.styles.listHoverOutline) {
                content.push(`.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row:not(.option-disabled):not(.focused):hover { outline: 1.6px dashed ${this.styles.listHoverOutline} !important; outline-offset: -1.6px !important; }`);
            }
            // Clear list styles on focus and on hover for disabled options
            content.push(`.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row.option-disabled.focused { background-color: transparent !important; color: inherit !important; outline: none !important; }`);
            content.push(`.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row.option-disabled:hover { background-color: transparent !important; color: inherit !important; outline: none !important; }`);
            this.styleElement.textContent = content.join('\n');
        }
        styleSelectElement() {
            const background = this.styles.selectBackground ?? '';
            const foreground = this.styles.selectForeground ?? '';
            const border = this.styles.selectBorder ?? '';
            this.selectElement.style.backgroundColor = background;
            this.selectElement.style.color = foreground;
            this.selectElement.style.borderColor = border;
        }
        styleList() {
            const background = this.styles.selectBackground ?? '';
            const listBackground = dom.asCssValueWithDefault(this.styles.selectListBackground, background);
            this.selectDropDownListContainer.style.backgroundColor = listBackground;
            this.selectionDetailsPane.style.backgroundColor = listBackground;
            const optionsBorder = this.styles.focusBorder ?? '';
            this.selectDropDownContainer.style.outlineColor = optionsBorder;
            this.selectDropDownContainer.style.outlineOffset = '-1px';
            this.selectList.style(this.styles);
        }
        createOption(value, index, disabled) {
            const option = document.createElement('option');
            option.value = value;
            option.text = value;
            option.disabled = !!disabled;
            return option;
        }
        // ContextView dropdown methods
        showSelectDropDown() {
            this.selectionDetailsPane.innerText = '';
            if (!this.contextViewProvider || this._isVisible) {
                return;
            }
            // Lazily create and populate list only at open, moved from constructor
            this.createSelectList(this.selectDropDownContainer);
            this.setOptionsList();
            // This allows us to flip the position based on measurement
            // Set drop-down position above/below from required height and margins
            // If pre-layout cannot fit at least one option do not show drop-down
            this.contextViewProvider.showContextView({
                getAnchor: () => this.selectElement,
                render: (container) => this.renderSelectDropDown(container, true),
                layout: () => {
                    this.layoutSelectDropDown();
                },
                onHide: () => {
                    this.selectDropDownContainer.classList.remove('visible');
                    this.selectElement.classList.remove('synthetic-focus');
                },
                anchorPosition: this._dropDownPosition
            }, this.selectBoxOptions.optionsAsChildren ? this.container : undefined);
            // Hide so we can relay out
            this._isVisible = true;
            this.hideSelectDropDown(false);
            this.contextViewProvider.showContextView({
                getAnchor: () => this.selectElement,
                render: (container) => this.renderSelectDropDown(container),
                layout: () => this.layoutSelectDropDown(),
                onHide: () => {
                    this.selectDropDownContainer.classList.remove('visible');
                    this.selectElement.classList.remove('synthetic-focus');
                },
                anchorPosition: this._dropDownPosition
            }, this.selectBoxOptions.optionsAsChildren ? this.container : undefined);
            // Track initial selection the case user escape, blur
            this._currentSelection = this.selected;
            this._isVisible = true;
            this.selectElement.setAttribute('aria-expanded', 'true');
        }
        hideSelectDropDown(focusSelect) {
            if (!this.contextViewProvider || !this._isVisible) {
                return;
            }
            this._isVisible = false;
            this.selectElement.setAttribute('aria-expanded', 'false');
            if (focusSelect) {
                this.selectElement.focus();
            }
            this.contextViewProvider.hideContextView();
        }
        renderSelectDropDown(container, preLayoutPosition) {
            container.appendChild(this.selectDropDownContainer);
            // Pre-Layout allows us to change position
            this.layoutSelectDropDown(preLayoutPosition);
            return {
                dispose: () => {
                    // contextView will dispose itself if moving from one View to another
                    this.selectDropDownContainer.remove(); // remove to take out the CSS rules we add
                }
            };
        }
        // Iterate over detailed descriptions, find max height
        measureMaxDetailsHeight() {
            let maxDetailsPaneHeight = 0;
            this.options.forEach((_option, index) => {
                this.updateDetail(index);
                if (this.selectionDetailsPane.offsetHeight > maxDetailsPaneHeight) {
                    maxDetailsPaneHeight = this.selectionDetailsPane.offsetHeight;
                }
            });
            return maxDetailsPaneHeight;
        }
        layoutSelectDropDown(preLayoutPosition) {
            // Avoid recursion from layout called in onListFocus
            if (this._skipLayout) {
                return false;
            }
            // Layout ContextView drop down select list and container
            // Have to manage our vertical overflow, sizing, position below or above
            // Position has to be determined and set prior to contextView instantiation
            if (this.selectList) {
                // Make visible to enable measurements
                this.selectDropDownContainer.classList.add('visible');
                const window = dom.getWindow(this.selectElement);
                const selectPosition = dom.getDomNodePagePosition(this.selectElement);
                const styles = dom.getWindow(this.selectElement).getComputedStyle(this.selectElement);
                const verticalPadding = parseFloat(styles.getPropertyValue('--dropdown-padding-top')) + parseFloat(styles.getPropertyValue('--dropdown-padding-bottom'));
                const maxSelectDropDownHeightBelow = (window.innerHeight - selectPosition.top - selectPosition.height - (this.selectBoxOptions.minBottomMargin || 0));
                const maxSelectDropDownHeightAbove = (selectPosition.top - SelectBoxList.DEFAULT_DROPDOWN_MINIMUM_TOP_MARGIN);
                // Determine optimal width - min(longest option), opt(parent select, excluding margins), max(ContextView controlled)
                const selectWidth = this.selectElement.offsetWidth;
                const selectMinWidth = this.setWidthControlElement(this.widthControlElement);
                const selectOptimalWidth = Math.max(selectMinWidth, Math.round(selectWidth)).toString() + 'px';
                this.selectDropDownContainer.style.width = selectOptimalWidth;
                // Get initial list height and determine space above and below
                this.selectList.getHTMLElement().style.height = '';
                this.selectList.layout();
                let listHeight = this.selectList.contentHeight;
                if (this._hasDetails && this._cachedMaxDetailsHeight === undefined) {
                    this._cachedMaxDetailsHeight = this.measureMaxDetailsHeight();
                }
                const maxDetailsPaneHeight = this._hasDetails ? this._cachedMaxDetailsHeight : 0;
                const minRequiredDropDownHeight = listHeight + verticalPadding + maxDetailsPaneHeight;
                const maxVisibleOptionsBelow = ((Math.floor((maxSelectDropDownHeightBelow - verticalPadding - maxDetailsPaneHeight) / this.getHeight())));
                const maxVisibleOptionsAbove = ((Math.floor((maxSelectDropDownHeightAbove - verticalPadding - maxDetailsPaneHeight) / this.getHeight())));
                // If we are only doing pre-layout check/adjust position only
                // Calculate vertical space available, flip up if insufficient
                // Use reflected padding on parent select, ContextView style
                // properties not available before DOM attachment
                if (preLayoutPosition) {
                    // Check if select moved out of viewport , do not open
                    // If at least one option cannot be shown, don't open the drop-down or hide/remove if open
                    if ((selectPosition.top + selectPosition.height) > (window.innerHeight - 22)
                        || selectPosition.top < SelectBoxList.DEFAULT_DROPDOWN_MINIMUM_TOP_MARGIN
                        || ((maxVisibleOptionsBelow < 1) && (maxVisibleOptionsAbove < 1))) {
                        // Indicate we cannot open
                        return false;
                    }
                    // Determine if we have to flip up
                    // Always show complete list items - never more than Max available vertical height
                    if (maxVisibleOptionsBelow < SelectBoxList.DEFAULT_MINIMUM_VISIBLE_OPTIONS
                        && maxVisibleOptionsAbove > maxVisibleOptionsBelow
                        && this.options.length > maxVisibleOptionsBelow) {
                        this._dropDownPosition = 1 /* AnchorPosition.ABOVE */;
                        this.selectDropDownListContainer.remove();
                        this.selectionDetailsPane.remove();
                        this.selectDropDownContainer.appendChild(this.selectionDetailsPane);
                        this.selectDropDownContainer.appendChild(this.selectDropDownListContainer);
                        this.selectionDetailsPane.classList.remove('border-top');
                        this.selectionDetailsPane.classList.add('border-bottom');
                    }
                    else {
                        this._dropDownPosition = 0 /* AnchorPosition.BELOW */;
                        this.selectDropDownListContainer.remove();
                        this.selectionDetailsPane.remove();
                        this.selectDropDownContainer.appendChild(this.selectDropDownListContainer);
                        this.selectDropDownContainer.appendChild(this.selectionDetailsPane);
                        this.selectionDetailsPane.classList.remove('border-bottom');
                        this.selectionDetailsPane.classList.add('border-top');
                    }
                    // Do full layout on showSelectDropDown only
                    return true;
                }
                // Check if select out of viewport or cutting into status bar
                if ((selectPosition.top + selectPosition.height) > (window.innerHeight - 22)
                    || selectPosition.top < SelectBoxList.DEFAULT_DROPDOWN_MINIMUM_TOP_MARGIN
                    || (this._dropDownPosition === 0 /* AnchorPosition.BELOW */ && maxVisibleOptionsBelow < 1)
                    || (this._dropDownPosition === 1 /* AnchorPosition.ABOVE */ && maxVisibleOptionsAbove < 1)) {
                    // Cannot properly layout, close and hide
                    this.hideSelectDropDown(true);
                    return false;
                }
                // SetUp list dimensions and layout - account for container padding
                // Use position to check above or below available space
                if (this._dropDownPosition === 0 /* AnchorPosition.BELOW */) {
                    if (this._isVisible && maxVisibleOptionsBelow + maxVisibleOptionsAbove < 1) {
                        // If drop-down is visible, must be doing a DOM re-layout, hide since we don't fit
                        // Hide drop-down, hide contextview, focus on parent select
                        this.hideSelectDropDown(true);
                        return false;
                    }
                    // Adjust list height to max from select bottom to margin (default/minBottomMargin)
                    if (minRequiredDropDownHeight > maxSelectDropDownHeightBelow) {
                        listHeight = (maxVisibleOptionsBelow * this.getHeight());
                    }
                }
                else {
                    if (minRequiredDropDownHeight > maxSelectDropDownHeightAbove) {
                        listHeight = (maxVisibleOptionsAbove * this.getHeight());
                    }
                }
                // Set adjusted list height and relayout
                this.selectList.layout(listHeight);
                this.selectList.domFocus();
                // Finally set focus on selected item
                if (this.selectList.length > 0) {
                    this.selectList.setFocus([this.selected || 0]);
                    this.selectList.reveal(this.selectList.getFocus()[0] || 0);
                }
                if (this._hasDetails) {
                    // Leave the selectDropDownContainer to size itself according to children (list + details) - #57447
                    this.selectList.getHTMLElement().style.height = (listHeight + verticalPadding) + 'px';
                    this.selectDropDownContainer.style.height = '';
                }
                else {
                    this.selectDropDownContainer.style.height = (listHeight + verticalPadding) + 'px';
                }
                this.updateDetail(this.selected);
                this.selectDropDownContainer.style.width = selectOptimalWidth;
                // Maintain focus outline on parent select as well as list container - tabindex for focus
                this.selectDropDownListContainer.setAttribute('tabindex', '0');
                this.selectElement.classList.add('synthetic-focus');
                this.selectDropDownContainer.classList.add('synthetic-focus');
                return true;
            }
            else {
                return false;
            }
        }
        setWidthControlElement(container) {
            let elementWidth = 0;
            if (container) {
                let longest = 0;
                let longestLength = 0;
                this.options.forEach((option, index) => {
                    const detailLength = !!option.detail ? option.detail.length : 0;
                    const rightDecoratorLength = !!option.decoratorRight ? option.decoratorRight.length : 0;
                    const len = option.text.length + detailLength + rightDecoratorLength;
                    if (len > longestLength) {
                        longest = index;
                        longestLength = len;
                    }
                });
                container.textContent = this.options[longest].text + (!!this.options[longest].decoratorRight ? (this.options[longest].decoratorRight + ' ') : '');
                elementWidth = dom.getTotalWidth(container);
            }
            return elementWidth;
        }
        createSelectList(parent) {
            // If we have already constructive list on open, skip
            if (this.selectList) {
                return;
            }
            // SetUp container for list
            this.selectDropDownListContainer = dom.append(parent, $('.select-box-dropdown-list-container'));
            this.listRenderer = new SelectListRenderer();
            this.selectList = this._register(new listWidget_1.List('SelectBoxCustom', this.selectDropDownListContainer, this, [this.listRenderer], {
                useShadows: false,
                verticalScrollMode: 3 /* ScrollbarVisibility.Visible */,
                keyboardSupport: false,
                mouseSupport: false,
                accessibilityProvider: {
                    getAriaLabel: element => {
                        let label = element.text;
                        if (element.detail) {
                            label += `. ${element.detail}`;
                        }
                        if (element.decoratorRight) {
                            label += `. ${element.decoratorRight}`;
                        }
                        if (element.description) {
                            label += `. ${element.description}`;
                        }
                        return label;
                    },
                    getWidgetAriaLabel: () => (0, nls_1.localize)(16, "Select Box"),
                    getRole: () => platform_1.isMacintosh ? '' : 'option',
                    getWidgetRole: () => 'listbox'
                }
            }));
            if (this.selectBoxOptions.ariaLabel) {
                this.selectList.ariaLabel = this.selectBoxOptions.ariaLabel;
            }
            // SetUp list keyboard controller - control navigation, disabled items, focus
            const onKeyDown = this._register(new event_1.DomEmitter(this.selectDropDownListContainer, 'keydown'));
            const onSelectDropDownKeyDown = event_2.Event.chain(onKeyDown.event, $ => $.filter(() => this.selectList.length > 0)
                .map(e => new keyboardEvent_1.StandardKeyboardEvent(e)));
            this._register(event_2.Event.chain(onSelectDropDownKeyDown, $ => $.filter(e => e.keyCode === 3 /* KeyCode.Enter */))(this.onEnter, this));
            this._register(event_2.Event.chain(onSelectDropDownKeyDown, $ => $.filter(e => e.keyCode === 2 /* KeyCode.Tab */))(this.onEnter, this)); // Tab should behave the same as enter, #79339
            this._register(event_2.Event.chain(onSelectDropDownKeyDown, $ => $.filter(e => e.keyCode === 9 /* KeyCode.Escape */))(this.onEscape, this));
            this._register(event_2.Event.chain(onSelectDropDownKeyDown, $ => $.filter(e => e.keyCode === 16 /* KeyCode.UpArrow */))(this.onUpArrow, this));
            this._register(event_2.Event.chain(onSelectDropDownKeyDown, $ => $.filter(e => e.keyCode === 18 /* KeyCode.DownArrow */))(this.onDownArrow, this));
            this._register(event_2.Event.chain(onSelectDropDownKeyDown, $ => $.filter(e => e.keyCode === 12 /* KeyCode.PageDown */))(this.onPageDown, this));
            this._register(event_2.Event.chain(onSelectDropDownKeyDown, $ => $.filter(e => e.keyCode === 11 /* KeyCode.PageUp */))(this.onPageUp, this));
            this._register(event_2.Event.chain(onSelectDropDownKeyDown, $ => $.filter(e => e.keyCode === 14 /* KeyCode.Home */))(this.onHome, this));
            this._register(event_2.Event.chain(onSelectDropDownKeyDown, $ => $.filter(e => e.keyCode === 13 /* KeyCode.End */))(this.onEnd, this));
            this._register(event_2.Event.chain(onSelectDropDownKeyDown, $ => $.filter(e => (e.keyCode >= 21 /* KeyCode.Digit0 */ && e.keyCode <= 56 /* KeyCode.KeyZ */) || (e.keyCode >= 85 /* KeyCode.Semicolon */ && e.keyCode <= 113 /* KeyCode.NumpadDivide */)))(this.onCharacter, this));
            // SetUp list mouse controller - control navigation, disabled items, focus
            this._register(dom.addDisposableListener(this.selectList.getHTMLElement(), dom.EventType.POINTER_UP, e => this.onPointerUp(e)));
            this._register(this.selectList.onMouseOver(e => typeof e.index !== 'undefined' && this.selectList.setFocus([e.index])));
            this._register(this.selectList.onDidChangeFocus(e => this.onListFocus(e)));
            this._register(dom.addDisposableListener(this.selectDropDownContainer, dom.EventType.FOCUS_OUT, e => {
                if (!this._isVisible || dom.isAncestor(e.relatedTarget, this.selectDropDownContainer)) {
                    return;
                }
                this.onListBlur();
            }));
            this.selectList.getHTMLElement().setAttribute('aria-label', this.selectBoxOptions.ariaLabel || '');
            this.selectList.getHTMLElement().setAttribute('aria-expanded', 'true');
            this.styleList();
        }
        // List methods
        // List mouse controller - active exit, select option, fire onDidSelect if change, return focus to parent select
        // Also takes in touchend events
        onPointerUp(e) {
            if (!this.selectList.length) {
                return;
            }
            dom.EventHelper.stop(e);
            const target = e.target;
            if (!target) {
                return;
            }
            // Check our mouse event is on an option (not scrollbar)
            if (target.classList.contains('slider')) {
                return;
            }
            const listRowElement = target.closest('.monaco-list-row');
            if (!listRowElement) {
                return;
            }
            const index = Number(listRowElement.getAttribute('data-index'));
            const disabled = listRowElement.classList.contains('option-disabled');
            // Ignore mouse selection of disabled options
            if (index >= 0 && index < this.options.length && !disabled) {
                this.selected = index;
                this.select(this.selected);
                this.selectList.setFocus([this.selected]);
                this.selectList.reveal(this.selectList.getFocus()[0]);
                // Only fire if selection change
                if (this.selected !== this._currentSelection) {
                    // Set current = selected
                    this._currentSelection = this.selected;
                    this._onDidSelect.fire({
                        index: this.selectElement.selectedIndex,
                        selected: this.options[this.selected].text
                    });
                    if (!!this.options[this.selected] && !!this.options[this.selected].text) {
                        this.setTitle(this.options[this.selected].text);
                    }
                }
                this.hideSelectDropDown(true);
            }
        }
        // List Exit - passive - implicit no selection change, hide drop-down
        onListBlur() {
            if (this._sticky) {
                return;
            }
            if (this.selected !== this._currentSelection) {
                // Reset selected to current if no change
                this.select(this._currentSelection);
            }
            this.hideSelectDropDown(false);
        }
        renderDescriptionMarkdown(text, actionHandler) {
            const cleanRenderedMarkdown = (element) => {
                for (let i = 0; i < element.childNodes.length; i++) {
                    const child = element.childNodes.item(i);
                    const tagName = child.tagName && child.tagName.toLowerCase();
                    if (tagName === 'img') {
                        child.remove();
                    }
                    else {
                        cleanRenderedMarkdown(child);
                    }
                }
            };
            const rendered = (0, markdownRenderer_1.renderMarkdown)({ value: text, supportThemeIcons: true }, { actionHandler });
            rendered.element.classList.add('select-box-description-markdown');
            cleanRenderedMarkdown(rendered.element);
            return rendered.element;
        }
        // List Focus Change - passive - update details pane with newly focused element's data
        onListFocus(e) {
            // Skip during initial layout
            if (!this._isVisible || !this._hasDetails) {
                return;
            }
            this.updateDetail(e.indexes[0]);
        }
        updateDetail(selectedIndex) {
            this.selectionDetailsPane.innerText = '';
            const option = this.options[selectedIndex];
            const description = option?.description ?? '';
            const descriptionIsMarkdown = option?.descriptionIsMarkdown ?? false;
            if (description) {
                if (descriptionIsMarkdown) {
                    const actionHandler = option.descriptionMarkdownActionHandler;
                    this.selectionDetailsPane.appendChild(this.renderDescriptionMarkdown(description, actionHandler));
                }
                else {
                    this.selectionDetailsPane.innerText = description;
                }
                this.selectionDetailsPane.style.display = 'block';
            }
            else {
                this.selectionDetailsPane.style.display = 'none';
            }
            // Avoid recursion
            this._skipLayout = true;
            this.contextViewProvider.layout();
            this._skipLayout = false;
        }
        // List keyboard controller
        // List exit - active - hide ContextView dropdown, reset selection, return focus to parent select
        onEscape(e) {
            dom.EventHelper.stop(e);
            // Reset selection to value when opened
            this.select(this._currentSelection);
            this.hideSelectDropDown(true);
        }
        // List exit - active - hide ContextView dropdown, return focus to parent select, fire onDidSelect if change
        onEnter(e) {
            dom.EventHelper.stop(e);
            // Only fire if selection change
            if (this.selected !== this._currentSelection) {
                this._currentSelection = this.selected;
                this._onDidSelect.fire({
                    index: this.selectElement.selectedIndex,
                    selected: this.options[this.selected].text
                });
                if (!!this.options[this.selected] && !!this.options[this.selected].text) {
                    this.setTitle(this.options[this.selected].text);
                }
            }
            this.hideSelectDropDown(true);
        }
        // List navigation - have to handle a disabled option (jump over)
        onDownArrow(e) {
            if (this.selected < this.options.length - 1) {
                dom.EventHelper.stop(e, true);
                // Skip disabled options
                const nextOptionDisabled = this.options[this.selected + 1].isDisabled;
                if (nextOptionDisabled && this.options.length > this.selected + 2) {
                    this.selected += 2;
                }
                else if (nextOptionDisabled) {
                    return;
                }
                else {
                    this.selected++;
                }
                // Set focus/selection - only fire event when closing drop-down or on blur
                this.select(this.selected);
                this.selectList.setFocus([this.selected]);
                this.selectList.reveal(this.selectList.getFocus()[0]);
            }
        }
        onUpArrow(e) {
            if (this.selected > 0) {
                dom.EventHelper.stop(e, true);
                // Skip disabled options
                const previousOptionDisabled = this.options[this.selected - 1].isDisabled;
                if (previousOptionDisabled && this.selected > 1) {
                    this.selected -= 2;
                }
                else {
                    this.selected--;
                }
                // Set focus/selection - only fire event when closing drop-down or on blur
                this.select(this.selected);
                this.selectList.setFocus([this.selected]);
                this.selectList.reveal(this.selectList.getFocus()[0]);
            }
        }
        onPageUp(e) {
            dom.EventHelper.stop(e);
            this.selectList.focusPreviousPage();
            // Allow scrolling to settle
            setTimeout(() => {
                this.selected = this.selectList.getFocus()[0];
                // Shift selection down if we land on a disabled option
                if (this.options[this.selected].isDisabled && this.selected < this.options.length - 1) {
                    this.selected++;
                    this.selectList.setFocus([this.selected]);
                }
                this.selectList.reveal(this.selected);
                this.select(this.selected);
            }, 1);
        }
        onPageDown(e) {
            dom.EventHelper.stop(e);
            this.selectList.focusNextPage();
            // Allow scrolling to settle
            setTimeout(() => {
                this.selected = this.selectList.getFocus()[0];
                // Shift selection up if we land on a disabled option
                if (this.options[this.selected].isDisabled && this.selected > 0) {
                    this.selected--;
                    this.selectList.setFocus([this.selected]);
                }
                this.selectList.reveal(this.selected);
                this.select(this.selected);
            }, 1);
        }
        onHome(e) {
            dom.EventHelper.stop(e);
            if (this.options.length < 2) {
                return;
            }
            this.selected = 0;
            if (this.options[this.selected].isDisabled && this.selected > 1) {
                this.selected++;
            }
            this.selectList.setFocus([this.selected]);
            this.selectList.reveal(this.selected);
            this.select(this.selected);
        }
        onEnd(e) {
            dom.EventHelper.stop(e);
            if (this.options.length < 2) {
                return;
            }
            this.selected = this.options.length - 1;
            if (this.options[this.selected].isDisabled && this.selected > 1) {
                this.selected--;
            }
            this.selectList.setFocus([this.selected]);
            this.selectList.reveal(this.selected);
            this.select(this.selected);
        }
        // Mimic option first character navigation of native select
        onCharacter(e) {
            const ch = keyCodes_1.KeyCodeUtils.toString(e.keyCode);
            let optionIndex = -1;
            for (let i = 0; i < this.options.length - 1; i++) {
                optionIndex = (i + this.selected + 1) % this.options.length;
                if (this.options[optionIndex].text.charAt(0).toUpperCase() === ch && !this.options[optionIndex].isDisabled) {
                    this.select(optionIndex);
                    this.selectList.setFocus([optionIndex]);
                    this.selectList.reveal(this.selectList.getFocus()[0]);
                    dom.EventHelper.stop(e);
                    break;
                }
            }
        }
        dispose() {
            this.hideSelectDropDown(false);
            super.dispose();
        }
    }
    exports.SelectBoxList = SelectBoxList;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[640/*vs/base/browser/ui/selectBox/selectBox*/], __M([1/*require*/,0/*exports*/,639/*vs/base/browser/ui/selectBox/selectBoxCustom*/,634/*vs/base/browser/ui/selectBox/selectBoxNative*/,85/*vs/base/browser/ui/widget*/,16/*vs/base/common/platform*/,472/*vs/css!vs/base/browser/ui/selectBox/selectBox*/]), function (require, exports, selectBoxCustom_1, selectBoxNative_1, widget_1, platform_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SelectBox = void 0;
    class SelectBox extends widget_1.Widget {
        constructor(options, selected, contextViewProvider, styles, selectBoxOptions) {
            super();
            // Default to native SelectBox for OSX unless overridden
            if (platform_1.isMacintosh && !selectBoxOptions?.useCustomDrawn) {
                this.selectBoxDelegate = new selectBoxNative_1.SelectBoxNative(options, selected, styles, selectBoxOptions);
            }
            else {
                this.selectBoxDelegate = new selectBoxCustom_1.SelectBoxList(options, selected, contextViewProvider, styles, selectBoxOptions);
            }
            this._register(this.selectBoxDelegate);
        }
        // Public SelectBox Methods - routed through delegate interface
        get onDidSelect() {
            return this.selectBoxDelegate.onDidSelect;
        }
        setOptions(options, selected) {
            this.selectBoxDelegate.setOptions(options, selected);
        }
        select(index) {
            this.selectBoxDelegate.select(index);
        }
        focus() {
            this.selectBoxDelegate.focus();
        }
        blur() {
            this.selectBoxDelegate.blur();
        }
        setFocusable(focusable) {
            this.selectBoxDelegate.setFocusable(focusable);
        }
        render(container) {
            this.selectBoxDelegate.render(container);
        }
    }
    exports.SelectBox = SelectBox;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[151/*vs/base/browser/ui/actionbar/actionViewItems*/], __M([1/*require*/,0/*exports*/,64/*vs/base/browser/browser*/,224/*vs/base/browser/dnd*/,5/*vs/base/browser/dom*/,69/*vs/base/browser/touch*/,44/*vs/base/browser/ui/hover/hoverDelegateFactory*/,640/*vs/base/browser/ui/selectBox/selectBox*/,41/*vs/base/common/actions*/,2/*vs/base/common/lifecycle*/,16/*vs/base/common/platform*/,19/*vs/base/common/types*/,3/*vs/nls*/,81/*vs/base/browser/ui/hover/hoverDelegate2*/,302/*vs/css!vs/base/browser/ui/actionbar/actionbar*/]), function (require, exports, browser_1, dnd_1, dom_1, touch_1, hoverDelegateFactory_1, selectBox_1, actions_1, lifecycle_1, platform, types, nls, hoverDelegate2_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SelectActionViewItem = exports.ActionViewItem = exports.BaseActionViewItem = void 0;
    class BaseActionViewItem extends lifecycle_1.Disposable {
        get action() {
            return this._action;
        }
        constructor(context, action, options = {}) {
            super();
            this.options = options;
            this._context = context || this;
            this._action = action;
            if (action instanceof actions_1.Action) {
                this._register(action.onDidChange(event => {
                    if (!this.element) {
                        // we have not been rendered yet, so there
                        // is no point in updating the UI
                        return;
                    }
                    this.handleActionChangeEvent(event);
                }));
            }
        }
        handleActionChangeEvent(event) {
            if (event.enabled !== undefined) {
                this.updateEnabled();
            }
            if (event.checked !== undefined) {
                this.updateChecked();
            }
            if (event.class !== undefined) {
                this.updateClass();
            }
            if (event.label !== undefined) {
                this.updateLabel();
                this.updateTooltip();
            }
            if (event.tooltip !== undefined) {
                this.updateTooltip();
            }
        }
        get actionRunner() {
            if (!this._actionRunner) {
                this._actionRunner = this._register(new actions_1.ActionRunner());
            }
            return this._actionRunner;
        }
        set actionRunner(actionRunner) {
            this._actionRunner = actionRunner;
        }
        isEnabled() {
            return this._action.enabled;
        }
        setActionContext(newContext) {
            this._context = newContext;
        }
        render(container) {
            const element = this.element = container;
            this._register(touch_1.Gesture.addTarget(container));
            const enableDragging = this.options && this.options.draggable;
            if (enableDragging) {
                container.draggable = true;
                if (browser_1.isFirefox) {
                    // Firefox: requires to set a text data transfer to get going
                    this._register((0, dom_1.addDisposableListener)(container, dom_1.EventType.DRAG_START, e => e.dataTransfer?.setData(dnd_1.DataTransfers.TEXT, this._action.label)));
                }
            }
            this._register((0, dom_1.addDisposableListener)(element, touch_1.EventType.Tap, e => this.onClick(e, true))); // Preserve focus on tap #125470
            this._register((0, dom_1.addDisposableListener)(element, dom_1.EventType.MOUSE_DOWN, e => {
                if (!enableDragging) {
                    dom_1.EventHelper.stop(e, true); // do not run when dragging is on because that would disable it
                }
                if (this._action.enabled && e.button === 0) {
                    element.classList.add('active');
                }
            }));
            if (platform.isMacintosh) {
                // macOS: allow to trigger the button when holding Ctrl+key and pressing the
                // main mouse button. This is for scenarios where e.g. some interaction forces
                // the Ctrl+key to be pressed and hold but the user still wants to interact
                // with the actions (for example quick access in quick navigation mode).
                this._register((0, dom_1.addDisposableListener)(element, dom_1.EventType.CONTEXT_MENU, e => {
                    if (e.button === 0 && e.ctrlKey === true) {
                        this.onClick(e);
                    }
                }));
            }
            this._register((0, dom_1.addDisposableListener)(element, dom_1.EventType.CLICK, e => {
                dom_1.EventHelper.stop(e, true);
                // menus do not use the click event
                if (!(this.options && this.options.isMenu)) {
                    this.onClick(e);
                }
            }));
            this._register((0, dom_1.addDisposableListener)(element, dom_1.EventType.DBLCLICK, e => {
                dom_1.EventHelper.stop(e, true);
            }));
            [dom_1.EventType.MOUSE_UP, dom_1.EventType.MOUSE_OUT].forEach(event => {
                this._register((0, dom_1.addDisposableListener)(element, event, e => {
                    dom_1.EventHelper.stop(e);
                    element.classList.remove('active');
                }));
            });
        }
        onClick(event, preserveFocus = false) {
            dom_1.EventHelper.stop(event, true);
            const context = types.isUndefinedOrNull(this._context) ? this.options?.useEventAsContext ? event : { preserveFocus } : this._context;
            this.actionRunner.run(this._action, context);
        }
        // Only set the tabIndex on the element once it is about to get focused
        // That way this element wont be a tab stop when it is not needed #106441
        focus() {
            if (this.element) {
                this.element.tabIndex = 0;
                this.element.focus();
                this.element.classList.add('focused');
            }
        }
        blur() {
            if (this.element) {
                this.element.blur();
                this.element.tabIndex = -1;
                this.element.classList.remove('focused');
            }
        }
        setFocusable(focusable) {
            if (this.element) {
                this.element.tabIndex = focusable ? 0 : -1;
            }
        }
        get trapsArrowNavigation() {
            return false;
        }
        updateEnabled() {
            // implement in subclass
        }
        updateLabel() {
            // implement in subclass
        }
        getClass() {
            return this.action.class;
        }
        getTooltip() {
            return this.action.tooltip;
        }
        updateTooltip() {
            if (!this.element) {
                return;
            }
            const title = this.getTooltip() ?? '';
            this.updateAriaLabel();
            if (this.options.hoverDelegate?.showNativeHover) {
                /* While custom hover is not inside custom hover */
                this.element.title = title;
            }
            else {
                if (!this.customHover && title !== '') {
                    const hoverDelegate = this.options.hoverDelegate ?? (0, hoverDelegateFactory_1.getDefaultHoverDelegate)('element');
                    this.customHover = this._store.add((0, hoverDelegate2_1.getBaseLayerHoverDelegate)().setupManagedHover(hoverDelegate, this.element, title));
                }
                else if (this.customHover) {
                    this.customHover.update(title);
                }
            }
        }
        updateAriaLabel() {
            if (this.element) {
                const title = this.getTooltip() ?? '';
                this.element.setAttribute('aria-label', title);
            }
        }
        updateClass() {
            // implement in subclass
        }
        updateChecked() {
            // implement in subclass
        }
        dispose() {
            if (this.element) {
                this.element.remove();
                this.element = undefined;
            }
            this._context = undefined;
            super.dispose();
        }
    }
    exports.BaseActionViewItem = BaseActionViewItem;
    class ActionViewItem extends BaseActionViewItem {
        constructor(context, action, options) {
            super(context, action, options);
            this.options = options;
            this.options.icon = options.icon !== undefined ? options.icon : false;
            this.options.label = options.label !== undefined ? options.label : true;
            this.cssClass = '';
        }
        render(container) {
            super.render(container);
            types.assertType(this.element);
            const label = document.createElement('a');
            label.classList.add('action-label');
            label.setAttribute('role', this.getDefaultAriaRole());
            this.label = label;
            this.element.appendChild(label);
            if (this.options.label && this.options.keybinding) {
                const kbLabel = document.createElement('span');
                kbLabel.classList.add('keybinding');
                kbLabel.textContent = this.options.keybinding;
                this.element.appendChild(kbLabel);
            }
            this.updateClass();
            this.updateLabel();
            this.updateTooltip();
            this.updateEnabled();
            this.updateChecked();
        }
        getDefaultAriaRole() {
            if (this._action.id === actions_1.Separator.ID) {
                return 'presentation'; // A separator is a presentation item
            }
            else {
                if (this.options.isMenu) {
                    return 'menuitem';
                }
                else if (this.options.isTabList) {
                    return 'tab';
                }
                else {
                    return 'button';
                }
            }
        }
        // Only set the tabIndex on the element once it is about to get focused
        // That way this element wont be a tab stop when it is not needed #106441
        focus() {
            if (this.label) {
                this.label.tabIndex = 0;
                this.label.focus();
            }
        }
        blur() {
            if (this.label) {
                this.label.tabIndex = -1;
            }
        }
        setFocusable(focusable) {
            if (this.label) {
                this.label.tabIndex = focusable ? 0 : -1;
            }
        }
        updateLabel() {
            if (this.options.label && this.label) {
                this.label.textContent = this.action.label;
            }
        }
        getTooltip() {
            let title = null;
            if (this.action.tooltip) {
                title = this.action.tooltip;
            }
            else if (!this.options.label && this.action.label && this.options.icon) {
                title = this.action.label;
                if (this.options.keybinding) {
                    title = nls.localize(0, "{0} ({1})", title, this.options.keybinding);
                }
            }
            return title ?? undefined;
        }
        updateClass() {
            if (this.cssClass && this.label) {
                this.label.classList.remove(...this.cssClass.split(' '));
            }
            if (this.options.icon) {
                this.cssClass = this.getClass();
                if (this.label) {
                    this.label.classList.add('codicon');
                    if (this.cssClass) {
                        this.label.classList.add(...this.cssClass.split(' '));
                    }
                }
                this.updateEnabled();
            }
            else {
                this.label?.classList.remove('codicon');
            }
        }
        updateEnabled() {
            if (this.action.enabled) {
                if (this.label) {
                    this.label.removeAttribute('aria-disabled');
                    this.label.classList.remove('disabled');
                }
                this.element?.classList.remove('disabled');
            }
            else {
                if (this.label) {
                    this.label.setAttribute('aria-disabled', 'true');
                    this.label.classList.add('disabled');
                }
                this.element?.classList.add('disabled');
            }
        }
        updateAriaLabel() {
            if (this.label) {
                const title = this.getTooltip() ?? '';
                this.label.setAttribute('aria-label', title);
            }
        }
        updateChecked() {
            if (this.label) {
                if (this.action.checked !== undefined) {
                    this.label.classList.toggle('checked', this.action.checked);
                    if (this.options.isTabList) {
                        this.label.setAttribute('aria-selected', this.action.checked ? 'true' : 'false');
                    }
                    else {
                        this.label.setAttribute('aria-checked', this.action.checked ? 'true' : 'false');
                        this.label.setAttribute('role', 'checkbox');
                    }
                }
                else {
                    this.label.classList.remove('checked');
                    this.label.removeAttribute(this.options.isTabList ? 'aria-selected' : 'aria-checked');
                    this.label.setAttribute('role', this.getDefaultAriaRole());
                }
            }
        }
    }
    exports.ActionViewItem = ActionViewItem;
    class SelectActionViewItem extends BaseActionViewItem {
        constructor(ctx, action, options, selected, contextViewProvider, styles, selectBoxOptions) {
            super(ctx, action);
            this.selectBox = new selectBox_1.SelectBox(options, selected, contextViewProvider, styles, selectBoxOptions);
            this.selectBox.setFocusable(false);
            this._register(this.selectBox);
            this.registerListeners();
        }
        select(index) {
            this.selectBox.select(index);
        }
        registerListeners() {
            this._register(this.selectBox.onDidSelect(e => this.runAction(e.selected, e.index)));
        }
        runAction(option, index) {
            this.actionRunner.run(this._action, this.getActionContext(option, index));
        }
        getActionContext(option, index) {
            return option;
        }
        setFocusable(focusable) {
            this.selectBox.setFocusable(focusable);
        }
        focus() {
            this.selectBox?.focus();
        }
        blur() {
            this.selectBox?.blur();
        }
        render(container) {
            this.selectBox.render(container);
        }
    }
    exports.SelectActionViewItem = SelectActionViewItem;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[87/*vs/base/browser/ui/actionbar/actionbar*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,47/*vs/base/browser/keyboardEvent*/,151/*vs/base/browser/ui/actionbar/actionViewItems*/,44/*vs/base/browser/ui/hover/hoverDelegateFactory*/,41/*vs/base/common/actions*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,19/*vs/base/common/types*/,302/*vs/css!vs/base/browser/ui/actionbar/actionbar*/]), function (require, exports, DOM, keyboardEvent_1, actionViewItems_1, hoverDelegateFactory_1, actions_1, event_1, lifecycle_1, types) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ActionBar = void 0;
    class ActionBar extends lifecycle_1.Disposable {
        constructor(container, options = {}) {
            super();
            this._actionRunnerDisposables = this._register(new lifecycle_1.DisposableStore());
            this.viewItemDisposables = this._register(new lifecycle_1.DisposableMap());
            // Trigger Key Tracking
            this.triggerKeyDown = false;
            this.focusable = true;
            this._onDidBlur = this._register(new event_1.Emitter());
            this.onDidBlur = this._onDidBlur.event;
            this._onDidCancel = this._register(new event_1.Emitter({ onWillAddFirstListener: () => this.cancelHasListener = true }));
            this.onDidCancel = this._onDidCancel.event;
            this.cancelHasListener = false;
            this._onDidRun = this._register(new event_1.Emitter());
            this.onDidRun = this._onDidRun.event;
            this._onWillRun = this._register(new event_1.Emitter());
            this.onWillRun = this._onWillRun.event;
            this.options = options;
            this._context = options.context ?? null;
            this._orientation = this.options.orientation ?? 0 /* ActionsOrientation.HORIZONTAL */;
            this._triggerKeys = {
                keyDown: this.options.triggerKeys?.keyDown ?? false,
                keys: this.options.triggerKeys?.keys ?? [3 /* KeyCode.Enter */, 10 /* KeyCode.Space */]
            };
            this._hoverDelegate = options.hoverDelegate ?? this._register((0, hoverDelegateFactory_1.createInstantHoverDelegate)());
            if (this.options.actionRunner) {
                this._actionRunner = this.options.actionRunner;
            }
            else {
                this._actionRunner = new actions_1.ActionRunner();
                this._actionRunnerDisposables.add(this._actionRunner);
            }
            this._actionRunnerDisposables.add(this._actionRunner.onDidRun(e => this._onDidRun.fire(e)));
            this._actionRunnerDisposables.add(this._actionRunner.onWillRun(e => this._onWillRun.fire(e)));
            this.viewItems = [];
            this.focusedItem = undefined;
            this.domNode = document.createElement('div');
            this.domNode.className = 'monaco-action-bar';
            let previousKeys;
            let nextKeys;
            switch (this._orientation) {
                case 0 /* ActionsOrientation.HORIZONTAL */:
                    previousKeys = [15 /* KeyCode.LeftArrow */];
                    nextKeys = [17 /* KeyCode.RightArrow */];
                    break;
                case 1 /* ActionsOrientation.VERTICAL */:
                    previousKeys = [16 /* KeyCode.UpArrow */];
                    nextKeys = [18 /* KeyCode.DownArrow */];
                    this.domNode.className += ' vertical';
                    break;
            }
            this._register(DOM.addDisposableListener(this.domNode, DOM.EventType.KEY_DOWN, e => {
                const event = new keyboardEvent_1.StandardKeyboardEvent(e);
                let eventHandled = true;
                const focusedItem = typeof this.focusedItem === 'number' ? this.viewItems[this.focusedItem] : undefined;
                if (previousKeys && (event.equals(previousKeys[0]) || event.equals(previousKeys[1]))) {
                    eventHandled = this.focusPrevious();
                }
                else if (nextKeys && (event.equals(nextKeys[0]) || event.equals(nextKeys[1]))) {
                    eventHandled = this.focusNext();
                }
                else if (event.equals(9 /* KeyCode.Escape */) && this.cancelHasListener) {
                    this._onDidCancel.fire();
                }
                else if (event.equals(14 /* KeyCode.Home */)) {
                    eventHandled = this.focusFirst();
                }
                else if (event.equals(13 /* KeyCode.End */)) {
                    eventHandled = this.focusLast();
                }
                else if (event.equals(2 /* KeyCode.Tab */) && focusedItem instanceof actionViewItems_1.BaseActionViewItem && focusedItem.trapsArrowNavigation) {
                    // Tab, so forcibly focus next #219199
                    eventHandled = this.focusNext(undefined, true);
                }
                else if (this.isTriggerKeyEvent(event)) {
                    // Staying out of the else branch even if not triggered
                    if (this._triggerKeys.keyDown) {
                        this.doTrigger(event);
                    }
                    else {
                        this.triggerKeyDown = true;
                    }
                }
                else {
                    eventHandled = false;
                }
                if (eventHandled) {
                    event.preventDefault();
                    event.stopPropagation();
                }
            }));
            this._register(DOM.addDisposableListener(this.domNode, DOM.EventType.KEY_UP, e => {
                const event = new keyboardEvent_1.StandardKeyboardEvent(e);
                // Run action on Enter/Space
                if (this.isTriggerKeyEvent(event)) {
                    if (!this._triggerKeys.keyDown && this.triggerKeyDown) {
                        this.triggerKeyDown = false;
                        this.doTrigger(event);
                    }
                    event.preventDefault();
                    event.stopPropagation();
                }
                // Recompute focused item
                else if (event.equals(2 /* KeyCode.Tab */) || event.equals(1024 /* KeyMod.Shift */ | 2 /* KeyCode.Tab */) || event.equals(16 /* KeyCode.UpArrow */) || event.equals(18 /* KeyCode.DownArrow */) || event.equals(15 /* KeyCode.LeftArrow */) || event.equals(17 /* KeyCode.RightArrow */)) {
                    this.updateFocusedItem();
                }
            }));
            this.focusTracker = this._register(DOM.trackFocus(this.domNode));
            this._register(this.focusTracker.onDidBlur(() => {
                if (DOM.getActiveElement() === this.domNode || !DOM.isAncestor(DOM.getActiveElement(), this.domNode)) {
                    this._onDidBlur.fire();
                    this.previouslyFocusedItem = this.focusedItem;
                    this.focusedItem = undefined;
                    this.triggerKeyDown = false;
                }
            }));
            this._register(this.focusTracker.onDidFocus(() => this.updateFocusedItem()));
            this.actionsList = document.createElement('ul');
            this.actionsList.className = 'actions-container';
            if (this.options.highlightToggledItems) {
                this.actionsList.classList.add('highlight-toggled');
            }
            this.actionsList.setAttribute('role', this.options.ariaRole || 'toolbar');
            if (this.options.ariaLabel) {
                this.actionsList.setAttribute('aria-label', this.options.ariaLabel);
            }
            this.domNode.appendChild(this.actionsList);
            container.appendChild(this.domNode);
        }
        refreshRole() {
            if (this.length() >= 1) {
                this.actionsList.setAttribute('role', this.options.ariaRole || 'toolbar');
            }
            else {
                this.actionsList.setAttribute('role', 'presentation');
            }
        }
        // Some action bars should not be focusable at times
        // When an action bar is not focusable make sure to make all the elements inside it not focusable
        // When an action bar is focusable again, make sure the first item can be focused
        setFocusable(focusable) {
            this.focusable = focusable;
            if (this.focusable) {
                const firstEnabled = this.viewItems.find(vi => vi instanceof actionViewItems_1.BaseActionViewItem && vi.isEnabled());
                if (firstEnabled instanceof actionViewItems_1.BaseActionViewItem) {
                    firstEnabled.setFocusable(true);
                }
            }
            else {
                this.viewItems.forEach(vi => {
                    if (vi instanceof actionViewItems_1.BaseActionViewItem) {
                        vi.setFocusable(false);
                    }
                });
            }
        }
        isTriggerKeyEvent(event) {
            let ret = false;
            this._triggerKeys.keys.forEach(keyCode => {
                ret = ret || event.equals(keyCode);
            });
            return ret;
        }
        updateFocusedItem() {
            for (let i = 0; i < this.actionsList.children.length; i++) {
                const elem = this.actionsList.children[i];
                if (DOM.isAncestor(DOM.getActiveElement(), elem)) {
                    this.focusedItem = i;
                    this.viewItems[this.focusedItem]?.showHover?.();
                    break;
                }
            }
        }
        get context() {
            return this._context;
        }
        set context(context) {
            this._context = context;
            this.viewItems.forEach(i => i.setActionContext(context));
        }
        get actionRunner() {
            return this._actionRunner;
        }
        set actionRunner(actionRunner) {
            this._actionRunner = actionRunner;
            // when setting a new `IActionRunner` make sure to dispose old listeners and
            // start to forward events from the new listener
            this._actionRunnerDisposables.clear();
            this._actionRunnerDisposables.add(this._actionRunner.onDidRun(e => this._onDidRun.fire(e)));
            this._actionRunnerDisposables.add(this._actionRunner.onWillRun(e => this._onWillRun.fire(e)));
            this.viewItems.forEach(item => item.actionRunner = actionRunner);
        }
        getContainer() {
            return this.domNode;
        }
        getAction(indexOrElement) {
            // by index
            if (typeof indexOrElement === 'number') {
                return this.viewItems[indexOrElement]?.action;
            }
            // by element
            if (DOM.isHTMLElement(indexOrElement)) {
                while (indexOrElement.parentElement !== this.actionsList) {
                    if (!indexOrElement.parentElement) {
                        return undefined;
                    }
                    indexOrElement = indexOrElement.parentElement;
                }
                for (let i = 0; i < this.actionsList.childNodes.length; i++) {
                    if (this.actionsList.childNodes[i] === indexOrElement) {
                        return this.viewItems[i].action;
                    }
                }
            }
            return undefined;
        }
        push(arg, options = {}) {
            const actions = Array.isArray(arg) ? arg : [arg];
            let index = types.isNumber(options.index) ? options.index : null;
            actions.forEach((action) => {
                const actionViewItemElement = document.createElement('li');
                actionViewItemElement.className = 'action-item';
                actionViewItemElement.setAttribute('role', 'presentation');
                let item;
                const viewItemOptions = { hoverDelegate: this._hoverDelegate, ...options, isTabList: this.options.ariaRole === 'tablist' };
                if (this.options.actionViewItemProvider) {
                    item = this.options.actionViewItemProvider(action, viewItemOptions);
                }
                if (!item) {
                    item = new actionViewItems_1.ActionViewItem(this.context, action, viewItemOptions);
                }
                // Prevent native context menu on actions
                if (!this.options.allowContextMenu) {
                    this.viewItemDisposables.set(item, DOM.addDisposableListener(actionViewItemElement, DOM.EventType.CONTEXT_MENU, (e) => {
                        DOM.EventHelper.stop(e, true);
                    }));
                }
                item.actionRunner = this._actionRunner;
                item.setActionContext(this.context);
                item.render(actionViewItemElement);
                if (this.focusable && item instanceof actionViewItems_1.BaseActionViewItem && this.viewItems.length === 0) {
                    // We need to allow for the first enabled item to be focused on using tab navigation #106441
                    item.setFocusable(true);
                }
                if (index === null || index < 0 || index >= this.actionsList.children.length) {
                    this.actionsList.appendChild(actionViewItemElement);
                    this.viewItems.push(item);
                }
                else {
                    this.actionsList.insertBefore(actionViewItemElement, this.actionsList.children[index]);
                    this.viewItems.splice(index, 0, item);
                    index++;
                }
            });
            if (typeof this.focusedItem === 'number') {
                // After a clear actions might be re-added to simply toggle some actions. We should preserve focus #97128
                this.focus(this.focusedItem);
            }
            this.refreshRole();
        }
        clear() {
            if (this.isEmpty()) {
                return;
            }
            this.viewItems = (0, lifecycle_1.dispose)(this.viewItems);
            this.viewItemDisposables.clearAndDisposeAll();
            DOM.clearNode(this.actionsList);
            this.refreshRole();
        }
        length() {
            return this.viewItems.length;
        }
        isEmpty() {
            return this.viewItems.length === 0;
        }
        focus(arg) {
            let selectFirst = false;
            let index = undefined;
            if (arg === undefined) {
                selectFirst = true;
            }
            else if (typeof arg === 'number') {
                index = arg;
            }
            else if (typeof arg === 'boolean') {
                selectFirst = arg;
            }
            if (selectFirst && typeof this.focusedItem === 'undefined') {
                const firstEnabled = this.viewItems.findIndex(item => item.isEnabled());
                // Focus the first enabled item
                this.focusedItem = firstEnabled === -1 ? undefined : firstEnabled;
                this.updateFocus(undefined, undefined, true);
            }
            else {
                if (index !== undefined) {
                    this.focusedItem = index;
                }
                this.updateFocus(undefined, undefined, true);
            }
        }
        focusFirst() {
            this.focusedItem = this.length() - 1;
            return this.focusNext(true);
        }
        focusLast() {
            this.focusedItem = 0;
            return this.focusPrevious(true);
        }
        focusNext(forceLoop, forceFocus) {
            if (typeof this.focusedItem === 'undefined') {
                this.focusedItem = this.viewItems.length - 1;
            }
            else if (this.viewItems.length <= 1) {
                return false;
            }
            const startIndex = this.focusedItem;
            let item;
            do {
                if (!forceLoop && this.options.preventLoopNavigation && this.focusedItem + 1 >= this.viewItems.length) {
                    this.focusedItem = startIndex;
                    return false;
                }
                this.focusedItem = (this.focusedItem + 1) % this.viewItems.length;
                item = this.viewItems[this.focusedItem];
            } while (this.focusedItem !== startIndex && ((this.options.focusOnlyEnabledItems && !item.isEnabled()) || item.action.id === actions_1.Separator.ID));
            this.updateFocus(undefined, undefined, forceFocus);
            return true;
        }
        focusPrevious(forceLoop) {
            if (typeof this.focusedItem === 'undefined') {
                this.focusedItem = 0;
            }
            else if (this.viewItems.length <= 1) {
                return false;
            }
            const startIndex = this.focusedItem;
            let item;
            do {
                this.focusedItem = this.focusedItem - 1;
                if (this.focusedItem < 0) {
                    if (!forceLoop && this.options.preventLoopNavigation) {
                        this.focusedItem = startIndex;
                        return false;
                    }
                    this.focusedItem = this.viewItems.length - 1;
                }
                item = this.viewItems[this.focusedItem];
            } while (this.focusedItem !== startIndex && ((this.options.focusOnlyEnabledItems && !item.isEnabled()) || item.action.id === actions_1.Separator.ID));
            this.updateFocus(true);
            return true;
        }
        updateFocus(fromRight, preventScroll, forceFocus = false) {
            if (typeof this.focusedItem === 'undefined') {
                this.actionsList.focus({ preventScroll });
            }
            if (this.previouslyFocusedItem !== undefined && this.previouslyFocusedItem !== this.focusedItem) {
                this.viewItems[this.previouslyFocusedItem]?.blur();
            }
            const actionViewItem = this.focusedItem !== undefined ? this.viewItems[this.focusedItem] : undefined;
            if (actionViewItem) {
                let focusItem = true;
                if (!types.isFunction(actionViewItem.focus)) {
                    focusItem = false;
                }
                if (this.options.focusOnlyEnabledItems && types.isFunction(actionViewItem.isEnabled) && !actionViewItem.isEnabled()) {
                    focusItem = false;
                }
                if (actionViewItem.action.id === actions_1.Separator.ID) {
                    focusItem = false;
                }
                if (!focusItem) {
                    this.actionsList.focus({ preventScroll });
                    this.previouslyFocusedItem = undefined;
                }
                else if (forceFocus || this.previouslyFocusedItem !== this.focusedItem) {
                    actionViewItem.focus(fromRight);
                    this.previouslyFocusedItem = this.focusedItem;
                }
                if (focusItem) {
                    actionViewItem.showHover?.();
                }
            }
        }
        doTrigger(event) {
            if (typeof this.focusedItem === 'undefined') {
                return; //nothing to focus
            }
            // trigger action
            const actionViewItem = this.viewItems[this.focusedItem];
            if (actionViewItem instanceof actionViewItems_1.BaseActionViewItem) {
                const context = (actionViewItem._context === null || actionViewItem._context === undefined) ? event : actionViewItem._context;
                this.run(actionViewItem._action, context);
            }
        }
        async run(action, context) {
            await this._actionRunner.run(action, context);
        }
        dispose() {
            this._context = undefined;
            this.viewItems = (0, lifecycle_1.dispose)(this.viewItems);
            this.getContainer().remove();
            super.dispose();
        }
    }
    exports.ActionBar = ActionBar;
});

define(__m[359/*vs/base/browser/ui/dropdown/dropdownActionViewItem*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,151/*vs/base/browser/ui/actionbar/actionViewItems*/,631/*vs/base/browser/ui/dropdown/dropdown*/,6/*vs/base/common/event*/,44/*vs/base/browser/ui/hover/hoverDelegateFactory*/,81/*vs/base/browser/ui/hover/hoverDelegate2*/,303/*vs/css!vs/base/browser/ui/dropdown/dropdown*/]), function (require, exports, dom_1, actionViewItems_1, dropdown_1, event_1, hoverDelegateFactory_1, hoverDelegate2_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DropdownMenuActionViewItem = void 0;
    class DropdownMenuActionViewItem extends actionViewItems_1.BaseActionViewItem {
        constructor(action, menuActionsOrProvider, contextMenuProvider, options = Object.create(null)) {
            super(null, action, options);
            this.actionItem = null;
            this._onDidChangeVisibility = this._register(new event_1.Emitter());
            this.onDidChangeVisibility = this._onDidChangeVisibility.event;
            this.menuActionsOrProvider = menuActionsOrProvider;
            this.contextMenuProvider = contextMenuProvider;
            this.options = options;
            if (this.options.actionRunner) {
                this.actionRunner = this.options.actionRunner;
            }
        }
        render(container) {
            this.actionItem = container;
            const labelRenderer = (el) => {
                this.element = (0, dom_1.append)(el, (0, dom_1.$)('a.action-label'));
                let classNames = [];
                if (typeof this.options.classNames === 'string') {
                    classNames = this.options.classNames.split(/\s+/g).filter(s => !!s);
                }
                else if (this.options.classNames) {
                    classNames = this.options.classNames;
                }
                // todo@aeschli: remove codicon, should come through `this.options.classNames`
                if (!classNames.find(c => c === 'icon')) {
                    classNames.push('codicon');
                }
                this.element.classList.add(...classNames);
                this.element.setAttribute('role', 'button');
                this.element.setAttribute('aria-haspopup', 'true');
                this.element.setAttribute('aria-expanded', 'false');
                if (this._action.label) {
                    this._register((0, hoverDelegate2_1.getBaseLayerHoverDelegate)().setupManagedHover(this.options.hoverDelegate ?? (0, hoverDelegateFactory_1.getDefaultHoverDelegate)('mouse'), this.element, this._action.label));
                }
                this.element.ariaLabel = this._action.label || '';
                return null;
            };
            const isActionsArray = Array.isArray(this.menuActionsOrProvider);
            const options = {
                contextMenuProvider: this.contextMenuProvider,
                labelRenderer: labelRenderer,
                menuAsChild: this.options.menuAsChild,
                actions: isActionsArray ? this.menuActionsOrProvider : undefined,
                actionProvider: isActionsArray ? undefined : this.menuActionsOrProvider,
                skipTelemetry: this.options.skipTelemetry
            };
            this.dropdownMenu = this._register(new dropdown_1.DropdownMenu(container, options));
            this._register(this.dropdownMenu.onDidChangeVisibility(visible => {
                this.element?.setAttribute('aria-expanded', `${visible}`);
                this._onDidChangeVisibility.fire(visible);
            }));
            this.dropdownMenu.menuOptions = {
                actionViewItemProvider: this.options.actionViewItemProvider,
                actionRunner: this.actionRunner,
                getKeyBinding: this.options.keybindingProvider,
                context: this._context
            };
            if (this.options.anchorAlignmentProvider) {
                const that = this;
                this.dropdownMenu.menuOptions = {
                    ...this.dropdownMenu.menuOptions,
                    get anchorAlignment() {
                        return that.options.anchorAlignmentProvider();
                    }
                };
            }
            this.updateTooltip();
            this.updateEnabled();
        }
        getTooltip() {
            let title = null;
            if (this.action.tooltip) {
                title = this.action.tooltip;
            }
            else if (this.action.label) {
                title = this.action.label;
            }
            return title ?? undefined;
        }
        setActionContext(newContext) {
            super.setActionContext(newContext);
            if (this.dropdownMenu) {
                if (this.dropdownMenu.menuOptions) {
                    this.dropdownMenu.menuOptions.context = newContext;
                }
                else {
                    this.dropdownMenu.menuOptions = { context: newContext };
                }
            }
        }
        show() {
            this.dropdownMenu?.show();
        }
        updateEnabled() {
            const disabled = !this.action.enabled;
            this.actionItem?.classList.toggle('disabled', disabled);
            this.element?.classList.toggle('disabled', disabled);
        }
    }
    exports.DropdownMenuActionViewItem = DropdownMenuActionViewItem;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[259/*vs/base/browser/ui/inputbox/inputBox*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,93/*vs/base/browser/event*/,352/*vs/base/browser/formattedTextRenderer*/,87/*vs/base/browser/ui/actionbar/actionbar*/,46/*vs/base/browser/ui/aria/aria*/,81/*vs/base/browser/ui/hover/hoverDelegate2*/,44/*vs/base/browser/ui/hover/hoverDelegateFactory*/,86/*vs/base/browser/ui/scrollbar/scrollableElement*/,85/*vs/base/browser/ui/widget*/,6/*vs/base/common/event*/,450/*vs/base/common/history*/,60/*vs/base/common/objects*/,3/*vs/nls*/,466/*vs/css!vs/base/browser/ui/inputbox/inputBox*/]), function (require, exports, dom, event_1, formattedTextRenderer_1, actionbar_1, aria, hoverDelegate2_1, hoverDelegateFactory_1, scrollableElement_1, widget_1, event_2, history_1, objects_1, nls) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.HistoryInputBox = exports.InputBox = exports.unthemedInboxStyles = void 0;
    const $ = dom.$;
    exports.unthemedInboxStyles = {
        inputBackground: '#3C3C3C',
        inputForeground: '#CCCCCC',
        inputValidationInfoBorder: '#55AAFF',
        inputValidationInfoBackground: '#063B49',
        inputValidationWarningBorder: '#B89500',
        inputValidationWarningBackground: '#352A05',
        inputValidationErrorBorder: '#BE1100',
        inputValidationErrorBackground: '#5A1D1D',
        inputBorder: undefined,
        inputValidationErrorForeground: undefined,
        inputValidationInfoForeground: undefined,
        inputValidationWarningForeground: undefined
    };
    class InputBox extends widget_1.Widget {
        constructor(container, contextViewProvider, options) {
            super();
            this.state = 'idle';
            this.maxHeight = Number.POSITIVE_INFINITY;
            this._onDidChange = this._register(new event_2.Emitter());
            this.onDidChange = this._onDidChange.event;
            this._onDidHeightChange = this._register(new event_2.Emitter());
            this.onDidHeightChange = this._onDidHeightChange.event;
            this.contextViewProvider = contextViewProvider;
            this.options = options;
            this.message = null;
            this.placeholder = this.options.placeholder || '';
            this.tooltip = this.options.tooltip ?? (this.placeholder || '');
            this.ariaLabel = this.options.ariaLabel || '';
            if (this.options.validationOptions) {
                this.validation = this.options.validationOptions.validation;
            }
            this.element = dom.append(container, $('.monaco-inputbox.idle'));
            const tagName = this.options.flexibleHeight ? 'textarea' : 'input';
            const wrapper = dom.append(this.element, $('.ibwrapper'));
            this.input = dom.append(wrapper, $(tagName + '.input.empty'));
            this.input.setAttribute('autocorrect', 'off');
            this.input.setAttribute('autocapitalize', 'off');
            this.input.setAttribute('spellcheck', 'false');
            this.onfocus(this.input, () => this.element.classList.add('synthetic-focus'));
            this.onblur(this.input, () => this.element.classList.remove('synthetic-focus'));
            if (this.options.flexibleHeight) {
                this.maxHeight = typeof this.options.flexibleMaxHeight === 'number' ? this.options.flexibleMaxHeight : Number.POSITIVE_INFINITY;
                this.mirror = dom.append(wrapper, $('div.mirror'));
                this.mirror.innerText = '\u00a0';
                this.scrollableElement = new scrollableElement_1.ScrollableElement(this.element, { vertical: 1 /* ScrollbarVisibility.Auto */ });
                if (this.options.flexibleWidth) {
                    this.input.setAttribute('wrap', 'off');
                    this.mirror.style.whiteSpace = 'pre';
                    this.mirror.style.wordWrap = 'initial';
                }
                dom.append(container, this.scrollableElement.getDomNode());
                this._register(this.scrollableElement);
                // from ScrollableElement to DOM
                this._register(this.scrollableElement.onScroll(e => this.input.scrollTop = e.scrollTop));
                const onSelectionChange = this._register(new event_1.DomEmitter(container.ownerDocument, 'selectionchange'));
                const onAnchoredSelectionChange = event_2.Event.filter(onSelectionChange.event, () => {
                    const selection = container.ownerDocument.getSelection();
                    return selection?.anchorNode === wrapper;
                });
                // from DOM to ScrollableElement
                this._register(onAnchoredSelectionChange(this.updateScrollDimensions, this));
                this._register(this.onDidHeightChange(this.updateScrollDimensions, this));
            }
            else {
                this.input.type = this.options.type || 'text';
                this.input.setAttribute('wrap', 'off');
            }
            if (this.ariaLabel) {
                this.input.setAttribute('aria-label', this.ariaLabel);
            }
            if (this.placeholder && !this.options.showPlaceholderOnFocus) {
                this.setPlaceHolder(this.placeholder);
            }
            if (this.tooltip) {
                this.setTooltip(this.tooltip);
            }
            this.oninput(this.input, () => this.onValueChange());
            this.onblur(this.input, () => this.onBlur());
            this.onfocus(this.input, () => this.onFocus());
            this._register(this.ignoreGesture(this.input));
            setTimeout(() => this.updateMirror(), 0);
            // Support actions
            if (this.options.actions) {
                this.actionbar = this._register(new actionbar_1.ActionBar(this.element));
                this.actionbar.push(this.options.actions, { icon: true, label: false });
            }
            this.applyStyles();
        }
        onBlur() {
            this._hideMessage();
            if (this.options.showPlaceholderOnFocus) {
                this.input.setAttribute('placeholder', '');
            }
        }
        onFocus() {
            this._showMessage();
            if (this.options.showPlaceholderOnFocus) {
                this.input.setAttribute('placeholder', this.placeholder || '');
            }
        }
        setPlaceHolder(placeHolder) {
            this.placeholder = placeHolder;
            this.input.setAttribute('placeholder', placeHolder);
        }
        setTooltip(tooltip) {
            this.tooltip = tooltip;
            if (!this.hover) {
                this.hover = this._register((0, hoverDelegate2_1.getBaseLayerHoverDelegate)().setupManagedHover((0, hoverDelegateFactory_1.getDefaultHoverDelegate)('mouse'), this.input, tooltip));
            }
            else {
                this.hover.update(tooltip);
            }
        }
        get inputElement() {
            return this.input;
        }
        get value() {
            return this.input.value;
        }
        set value(newValue) {
            if (this.input.value !== newValue) {
                this.input.value = newValue;
                this.onValueChange();
            }
        }
        get height() {
            return typeof this.cachedHeight === 'number' ? this.cachedHeight : dom.getTotalHeight(this.element);
        }
        focus() {
            this.input.focus();
        }
        blur() {
            this.input.blur();
        }
        hasFocus() {
            return dom.isActiveElement(this.input);
        }
        select(range = null) {
            this.input.select();
            if (range) {
                this.input.setSelectionRange(range.start, range.end);
                if (range.end === this.input.value.length) {
                    this.input.scrollLeft = this.input.scrollWidth;
                }
            }
        }
        isSelectionAtEnd() {
            return this.input.selectionEnd === this.input.value.length && this.input.selectionStart === this.input.selectionEnd;
        }
        getSelection() {
            const selectionStart = this.input.selectionStart;
            if (selectionStart === null) {
                return null;
            }
            const selectionEnd = this.input.selectionEnd ?? selectionStart;
            return {
                start: selectionStart,
                end: selectionEnd,
            };
        }
        enable() {
            this.input.removeAttribute('disabled');
        }
        disable() {
            this.blur();
            this.input.disabled = true;
            this._hideMessage();
        }
        set paddingRight(paddingRight) {
            // Set width to avoid hint text overlapping buttons
            this.input.style.width = `calc(100% - ${paddingRight}px)`;
            if (this.mirror) {
                this.mirror.style.paddingRight = paddingRight + 'px';
            }
        }
        updateScrollDimensions() {
            if (typeof this.cachedContentHeight !== 'number' || typeof this.cachedHeight !== 'number' || !this.scrollableElement) {
                return;
            }
            const scrollHeight = this.cachedContentHeight;
            const height = this.cachedHeight;
            const scrollTop = this.input.scrollTop;
            this.scrollableElement.setScrollDimensions({ scrollHeight, height });
            this.scrollableElement.setScrollPosition({ scrollTop });
        }
        showMessage(message, force) {
            if (this.state === 'open' && (0, objects_1.equals)(this.message, message)) {
                // Already showing
                return;
            }
            this.message = message;
            this.element.classList.remove('idle');
            this.element.classList.remove('info');
            this.element.classList.remove('warning');
            this.element.classList.remove('error');
            this.element.classList.add(this.classForType(message.type));
            const styles = this.stylesForType(this.message.type);
            this.element.style.border = `1px solid ${dom.asCssValueWithDefault(styles.border, 'transparent')}`;
            if (this.message.content && (this.hasFocus() || force)) {
                this._showMessage();
            }
        }
        hideMessage() {
            this.message = null;
            this.element.classList.remove('info');
            this.element.classList.remove('warning');
            this.element.classList.remove('error');
            this.element.classList.add('idle');
            this._hideMessage();
            this.applyStyles();
        }
        validate() {
            let errorMsg = null;
            if (this.validation) {
                errorMsg = this.validation(this.value);
                if (errorMsg) {
                    this.inputElement.setAttribute('aria-invalid', 'true');
                    this.showMessage(errorMsg);
                }
                else if (this.inputElement.hasAttribute('aria-invalid')) {
                    this.inputElement.removeAttribute('aria-invalid');
                    this.hideMessage();
                }
            }
            return errorMsg?.type;
        }
        stylesForType(type) {
            const styles = this.options.inputBoxStyles;
            switch (type) {
                case 1 /* MessageType.INFO */: return { border: styles.inputValidationInfoBorder, background: styles.inputValidationInfoBackground, foreground: styles.inputValidationInfoForeground };
                case 2 /* MessageType.WARNING */: return { border: styles.inputValidationWarningBorder, background: styles.inputValidationWarningBackground, foreground: styles.inputValidationWarningForeground };
                default: return { border: styles.inputValidationErrorBorder, background: styles.inputValidationErrorBackground, foreground: styles.inputValidationErrorForeground };
            }
        }
        classForType(type) {
            switch (type) {
                case 1 /* MessageType.INFO */: return 'info';
                case 2 /* MessageType.WARNING */: return 'warning';
                default: return 'error';
            }
        }
        _showMessage() {
            if (!this.contextViewProvider || !this.message) {
                return;
            }
            let div;
            const layout = () => div.style.width = dom.getTotalWidth(this.element) + 'px';
            this.contextViewProvider.showContextView({
                getAnchor: () => this.element,
                anchorAlignment: 1 /* AnchorAlignment.RIGHT */,
                render: (container) => {
                    if (!this.message) {
                        return null;
                    }
                    div = dom.append(container, $('.monaco-inputbox-container'));
                    layout();
                    const renderOptions = {
                        inline: true,
                        className: 'monaco-inputbox-message'
                    };
                    const spanElement = (this.message.formatContent
                        ? (0, formattedTextRenderer_1.renderFormattedText)(this.message.content, renderOptions)
                        : (0, formattedTextRenderer_1.renderText)(this.message.content, renderOptions));
                    spanElement.classList.add(this.classForType(this.message.type));
                    const styles = this.stylesForType(this.message.type);
                    spanElement.style.backgroundColor = styles.background ?? '';
                    spanElement.style.color = styles.foreground ?? '';
                    spanElement.style.border = styles.border ? `1px solid ${styles.border}` : '';
                    dom.append(div, spanElement);
                    return null;
                },
                onHide: () => {
                    this.state = 'closed';
                },
                layout: layout
            });
            // ARIA Support
            let alertText;
            if (this.message.type === 3 /* MessageType.ERROR */) {
                alertText = nls.localize(9, "Error: {0}", this.message.content);
            }
            else if (this.message.type === 2 /* MessageType.WARNING */) {
                alertText = nls.localize(10, "Warning: {0}", this.message.content);
            }
            else {
                alertText = nls.localize(11, "Info: {0}", this.message.content);
            }
            aria.alert(alertText);
            this.state = 'open';
        }
        _hideMessage() {
            if (!this.contextViewProvider) {
                return;
            }
            if (this.state === 'open') {
                this.contextViewProvider.hideContextView();
            }
            this.state = 'idle';
        }
        onValueChange() {
            this._onDidChange.fire(this.value);
            this.validate();
            this.updateMirror();
            this.input.classList.toggle('empty', !this.value);
            if (this.state === 'open' && this.contextViewProvider) {
                this.contextViewProvider.layout();
            }
        }
        updateMirror() {
            if (!this.mirror) {
                return;
            }
            const value = this.value;
            const lastCharCode = value.charCodeAt(value.length - 1);
            const suffix = lastCharCode === 10 ? ' ' : '';
            const mirrorTextContent = (value + suffix)
                .replace(/\u000c/g, ''); // Don't measure with the form feed character, which messes up sizing
            if (mirrorTextContent) {
                this.mirror.textContent = value + suffix;
            }
            else {
                this.mirror.innerText = '\u00a0';
            }
            this.layout();
        }
        applyStyles() {
            const styles = this.options.inputBoxStyles;
            const background = styles.inputBackground ?? '';
            const foreground = styles.inputForeground ?? '';
            const border = styles.inputBorder ?? '';
            this.element.style.backgroundColor = background;
            this.element.style.color = foreground;
            this.input.style.backgroundColor = 'inherit';
            this.input.style.color = foreground;
            // there's always a border, even if the color is not set.
            this.element.style.border = `1px solid ${dom.asCssValueWithDefault(border, 'transparent')}`;
        }
        layout() {
            if (!this.mirror) {
                return;
            }
            const previousHeight = this.cachedContentHeight;
            this.cachedContentHeight = dom.getTotalHeight(this.mirror);
            if (previousHeight !== this.cachedContentHeight) {
                this.cachedHeight = Math.min(this.cachedContentHeight, this.maxHeight);
                this.input.style.height = this.cachedHeight + 'px';
                this._onDidHeightChange.fire(this.cachedContentHeight);
            }
        }
        insertAtCursor(text) {
            const inputElement = this.inputElement;
            const start = inputElement.selectionStart;
            const end = inputElement.selectionEnd;
            const content = inputElement.value;
            if (start !== null && end !== null) {
                this.value = content.substr(0, start) + text + content.substr(end);
                inputElement.setSelectionRange(start + 1, start + 1);
                this.layout();
            }
        }
        dispose() {
            this._hideMessage();
            this.message = null;
            this.actionbar?.dispose();
            super.dispose();
        }
    }
    exports.InputBox = InputBox;
    class HistoryInputBox extends InputBox {
        constructor(container, contextViewProvider, options) {
            const NLS_PLACEHOLDER_HISTORY_HINT_SUFFIX_NO_PARENS = nls.localize(12, ' or {0} for history', `\u21C5`);



            const NLS_PLACEHOLDER_HISTORY_HINT_SUFFIX_IN_PARENS = nls.localize(13, ' ({0} for history)', `\u21C5`);



            super(container, contextViewProvider, options);
            this._onDidFocus = this._register(new event_2.Emitter());
            this.onDidFocus = this._onDidFocus.event;
            this._onDidBlur = this._register(new event_2.Emitter());
            this.onDidBlur = this._onDidBlur.event;
            this.history = new history_1.HistoryNavigator(options.history, 100);
            // Function to append the history suffix to the placeholder if necessary
            const addSuffix = () => {
                if (options.showHistoryHint && options.showHistoryHint() && !this.placeholder.endsWith(NLS_PLACEHOLDER_HISTORY_HINT_SUFFIX_NO_PARENS) && !this.placeholder.endsWith(NLS_PLACEHOLDER_HISTORY_HINT_SUFFIX_IN_PARENS) && this.history.getHistory().length) {
                    const suffix = this.placeholder.endsWith(')') ? NLS_PLACEHOLDER_HISTORY_HINT_SUFFIX_NO_PARENS : NLS_PLACEHOLDER_HISTORY_HINT_SUFFIX_IN_PARENS;
                    const suffixedPlaceholder = this.placeholder + suffix;
                    if (options.showPlaceholderOnFocus && !dom.isActiveElement(this.input)) {
                        this.placeholder = suffixedPlaceholder;
                    }
                    else {
                        this.setPlaceHolder(suffixedPlaceholder);
                    }
                }
            };
            // Spot the change to the textarea class attribute which occurs when it changes between non-empty and empty,
            // and add the history suffix to the placeholder if not yet present
            this.observer = new MutationObserver((mutationList, observer) => {
                mutationList.forEach((mutation) => {
                    if (!mutation.target.textContent) {
                        addSuffix();
                    }
                });
            });
            this.observer.observe(this.input, { attributeFilter: ['class'] });
            this.onfocus(this.input, () => addSuffix());
            this.onblur(this.input, () => {
                const resetPlaceholder = (historyHint) => {
                    if (!this.placeholder.endsWith(historyHint)) {
                        return false;
                    }
                    else {
                        const revertedPlaceholder = this.placeholder.slice(0, this.placeholder.length - historyHint.length);
                        if (options.showPlaceholderOnFocus) {
                            this.placeholder = revertedPlaceholder;
                        }
                        else {
                            this.setPlaceHolder(revertedPlaceholder);
                        }
                        return true;
                    }
                };
                if (!resetPlaceholder(NLS_PLACEHOLDER_HISTORY_HINT_SUFFIX_IN_PARENS)) {
                    resetPlaceholder(NLS_PLACEHOLDER_HISTORY_HINT_SUFFIX_NO_PARENS);
                }
            });
        }
        dispose() {
            super.dispose();
            if (this.observer) {
                this.observer.disconnect();
                this.observer = undefined;
            }
        }
        addToHistory(always) {
            if (this.value && (always || this.value !== this.getCurrentValue())) {
                this.history.add(this.value);
            }
        }
        isAtLastInHistory() {
            return this.history.isLast();
        }
        isNowhereInHistory() {
            return this.history.isNowhere();
        }
        showNextValue() {
            if (!this.history.has(this.value)) {
                this.addToHistory();
            }
            let next = this.getNextValue();
            if (next) {
                next = next === this.value ? this.getNextValue() : next;
            }
            this.value = next ?? '';
            aria.status(this.value ? this.value : nls.localize(14, "Cleared Input"));
        }
        showPreviousValue() {
            if (!this.history.has(this.value)) {
                this.addToHistory();
            }
            let previous = this.getPreviousValue();
            if (previous) {
                previous = previous === this.value ? this.getPreviousValue() : previous;
            }
            if (previous) {
                this.value = previous;
                aria.status(this.value);
            }
        }
        setPlaceHolder(placeHolder) {
            super.setPlaceHolder(placeHolder);
            this.setTooltip(placeHolder);
        }
        onBlur() {
            super.onBlur();
            this._onDidBlur.fire();
        }
        onFocus() {
            super.onFocus();
            this._onDidFocus.fire();
        }
        getCurrentValue() {
            let currentValue = this.history.current();
            if (!currentValue) {
                currentValue = this.history.last();
                this.history.next();
            }
            return currentValue;
        }
        getPreviousValue() {
            return this.history.previous() || this.history.first();
        }
        getNextValue() {
            return this.history.next();
        }
    }
    exports.HistoryInputBox = HistoryInputBox;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[260/*vs/base/browser/ui/findinput/findInput*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,358/*vs/base/browser/ui/findinput/findInputToggles*/,259/*vs/base/browser/ui/inputbox/inputBox*/,85/*vs/base/browser/ui/widget*/,6/*vs/base/common/event*/,3/*vs/nls*/,2/*vs/base/common/lifecycle*/,44/*vs/base/browser/ui/hover/hoverDelegateFactory*/,304/*vs/css!vs/base/browser/ui/findinput/findInput*/]), function (require, exports, dom, findInputToggles_1, inputBox_1, widget_1, event_1, nls, lifecycle_1, hoverDelegateFactory_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.FindInput = void 0;
    const NLS_DEFAULT_LABEL = nls.localize(1, "input");
    class FindInput extends widget_1.Widget {
        constructor(parent, contextViewProvider, options) {
            super();
            this.fixFocusOnOptionClickEnabled = true;
            this.imeSessionInProgress = false;
            this.additionalTogglesDisposables = this._register(new lifecycle_1.MutableDisposable());
            this.additionalToggles = [];
            this._onDidOptionChange = this._register(new event_1.Emitter());
            this.onDidOptionChange = this._onDidOptionChange.event;
            this._onKeyDown = this._register(new event_1.Emitter());
            this.onKeyDown = this._onKeyDown.event;
            this._onMouseDown = this._register(new event_1.Emitter());
            this.onMouseDown = this._onMouseDown.event;
            this._onInput = this._register(new event_1.Emitter());
            this._onKeyUp = this._register(new event_1.Emitter());
            this._onCaseSensitiveKeyDown = this._register(new event_1.Emitter());
            this.onCaseSensitiveKeyDown = this._onCaseSensitiveKeyDown.event;
            this._onRegexKeyDown = this._register(new event_1.Emitter());
            this.onRegexKeyDown = this._onRegexKeyDown.event;
            this._lastHighlightFindOptions = 0;
            this.placeholder = options.placeholder || '';
            this.validation = options.validation;
            this.label = options.label || NLS_DEFAULT_LABEL;
            this.showCommonFindToggles = !!options.showCommonFindToggles;
            const appendCaseSensitiveLabel = options.appendCaseSensitiveLabel || '';
            const appendWholeWordsLabel = options.appendWholeWordsLabel || '';
            const appendRegexLabel = options.appendRegexLabel || '';
            const history = options.history || [];
            const flexibleHeight = !!options.flexibleHeight;
            const flexibleWidth = !!options.flexibleWidth;
            const flexibleMaxHeight = options.flexibleMaxHeight;
            this.domNode = document.createElement('div');
            this.domNode.classList.add('monaco-findInput');
            this.inputBox = this._register(new inputBox_1.HistoryInputBox(this.domNode, contextViewProvider, {
                placeholder: this.placeholder || '',
                ariaLabel: this.label || '',
                validationOptions: {
                    validation: this.validation
                },
                history,
                showHistoryHint: options.showHistoryHint,
                flexibleHeight,
                flexibleWidth,
                flexibleMaxHeight,
                inputBoxStyles: options.inputBoxStyles,
            }));
            const hoverDelegate = this._register((0, hoverDelegateFactory_1.createInstantHoverDelegate)());
            if (this.showCommonFindToggles) {
                this.regex = this._register(new findInputToggles_1.RegexToggle({
                    appendTitle: appendRegexLabel,
                    isChecked: false,
                    hoverDelegate,
                    ...options.toggleStyles
                }));
                this._register(this.regex.onChange(viaKeyboard => {
                    this._onDidOptionChange.fire(viaKeyboard);
                    if (!viaKeyboard && this.fixFocusOnOptionClickEnabled) {
                        this.inputBox.focus();
                    }
                    this.validate();
                }));
                this._register(this.regex.onKeyDown(e => {
                    this._onRegexKeyDown.fire(e);
                }));
                this.wholeWords = this._register(new findInputToggles_1.WholeWordsToggle({
                    appendTitle: appendWholeWordsLabel,
                    isChecked: false,
                    hoverDelegate,
                    ...options.toggleStyles
                }));
                this._register(this.wholeWords.onChange(viaKeyboard => {
                    this._onDidOptionChange.fire(viaKeyboard);
                    if (!viaKeyboard && this.fixFocusOnOptionClickEnabled) {
                        this.inputBox.focus();
                    }
                    this.validate();
                }));
                this.caseSensitive = this._register(new findInputToggles_1.CaseSensitiveToggle({
                    appendTitle: appendCaseSensitiveLabel,
                    isChecked: false,
                    hoverDelegate,
                    ...options.toggleStyles
                }));
                this._register(this.caseSensitive.onChange(viaKeyboard => {
                    this._onDidOptionChange.fire(viaKeyboard);
                    if (!viaKeyboard && this.fixFocusOnOptionClickEnabled) {
                        this.inputBox.focus();
                    }
                    this.validate();
                }));
                this._register(this.caseSensitive.onKeyDown(e => {
                    this._onCaseSensitiveKeyDown.fire(e);
                }));
                // Arrow-Key support to navigate between options
                const indexes = [this.caseSensitive.domNode, this.wholeWords.domNode, this.regex.domNode];
                this.onkeydown(this.domNode, (event) => {
                    if (event.equals(15 /* KeyCode.LeftArrow */) || event.equals(17 /* KeyCode.RightArrow */) || event.equals(9 /* KeyCode.Escape */)) {
                        const index = indexes.indexOf(this.domNode.ownerDocument.activeElement);
                        if (index >= 0) {
                            let newIndex = -1;
                            if (event.equals(17 /* KeyCode.RightArrow */)) {
                                newIndex = (index + 1) % indexes.length;
                            }
                            else if (event.equals(15 /* KeyCode.LeftArrow */)) {
                                if (index === 0) {
                                    newIndex = indexes.length - 1;
                                }
                                else {
                                    newIndex = index - 1;
                                }
                            }
                            if (event.equals(9 /* KeyCode.Escape */)) {
                                indexes[index].blur();
                                this.inputBox.focus();
                            }
                            else if (newIndex >= 0) {
                                indexes[newIndex].focus();
                            }
                            dom.EventHelper.stop(event, true);
                        }
                    }
                });
            }
            this.controls = document.createElement('div');
            this.controls.className = 'controls';
            this.controls.style.display = this.showCommonFindToggles ? '' : 'none';
            if (this.caseSensitive) {
                this.controls.append(this.caseSensitive.domNode);
            }
            if (this.wholeWords) {
                this.controls.appendChild(this.wholeWords.domNode);
            }
            if (this.regex) {
                this.controls.appendChild(this.regex.domNode);
            }
            this.setAdditionalToggles(options?.additionalToggles);
            if (this.controls) {
                this.domNode.appendChild(this.controls);
            }
            parent?.appendChild(this.domNode);
            this._register(dom.addDisposableListener(this.inputBox.inputElement, 'compositionstart', (e) => {
                this.imeSessionInProgress = true;
            }));
            this._register(dom.addDisposableListener(this.inputBox.inputElement, 'compositionend', (e) => {
                this.imeSessionInProgress = false;
                this._onInput.fire();
            }));
            this.onkeydown(this.inputBox.inputElement, (e) => this._onKeyDown.fire(e));
            this.onkeyup(this.inputBox.inputElement, (e) => this._onKeyUp.fire(e));
            this.oninput(this.inputBox.inputElement, (e) => this._onInput.fire());
            this.onmousedown(this.inputBox.inputElement, (e) => this._onMouseDown.fire(e));
        }
        get onDidChange() {
            return this.inputBox.onDidChange;
        }
        layout(style) {
            this.inputBox.layout();
            this.updateInputBoxPadding(style.collapsedFindWidget);
        }
        enable() {
            this.domNode.classList.remove('disabled');
            this.inputBox.enable();
            this.regex?.enable();
            this.wholeWords?.enable();
            this.caseSensitive?.enable();
            for (const toggle of this.additionalToggles) {
                toggle.enable();
            }
        }
        disable() {
            this.domNode.classList.add('disabled');
            this.inputBox.disable();
            this.regex?.disable();
            this.wholeWords?.disable();
            this.caseSensitive?.disable();
            for (const toggle of this.additionalToggles) {
                toggle.disable();
            }
        }
        setFocusInputOnOptionClick(value) {
            this.fixFocusOnOptionClickEnabled = value;
        }
        setEnabled(enabled) {
            if (enabled) {
                this.enable();
            }
            else {
                this.disable();
            }
        }
        setAdditionalToggles(toggles) {
            for (const currentToggle of this.additionalToggles) {
                currentToggle.domNode.remove();
            }
            this.additionalToggles = [];
            this.additionalTogglesDisposables.value = new lifecycle_1.DisposableStore();
            for (const toggle of toggles ?? []) {
                this.additionalTogglesDisposables.value.add(toggle);
                this.controls.appendChild(toggle.domNode);
                this.additionalTogglesDisposables.value.add(toggle.onChange(viaKeyboard => {
                    this._onDidOptionChange.fire(viaKeyboard);
                    if (!viaKeyboard && this.fixFocusOnOptionClickEnabled) {
                        this.inputBox.focus();
                    }
                }));
                this.additionalToggles.push(toggle);
            }
            if (this.additionalToggles.length > 0) {
                this.controls.style.display = '';
            }
            this.updateInputBoxPadding();
        }
        updateInputBoxPadding(controlsHidden = false) {
            if (controlsHidden) {
                this.inputBox.paddingRight = 0;
            }
            else {
                this.inputBox.paddingRight =
                    ((this.caseSensitive?.width() ?? 0) + (this.wholeWords?.width() ?? 0) + (this.regex?.width() ?? 0))
                        + this.additionalToggles.reduce((r, t) => r + t.width(), 0);
            }
        }
        getValue() {
            return this.inputBox.value;
        }
        setValue(value) {
            if (this.inputBox.value !== value) {
                this.inputBox.value = value;
            }
        }
        select() {
            this.inputBox.select();
        }
        focus() {
            this.inputBox.focus();
        }
        getCaseSensitive() {
            return this.caseSensitive?.checked ?? false;
        }
        setCaseSensitive(value) {
            if (this.caseSensitive) {
                this.caseSensitive.checked = value;
            }
        }
        getWholeWords() {
            return this.wholeWords?.checked ?? false;
        }
        setWholeWords(value) {
            if (this.wholeWords) {
                this.wholeWords.checked = value;
            }
        }
        getRegex() {
            return this.regex?.checked ?? false;
        }
        setRegex(value) {
            if (this.regex) {
                this.regex.checked = value;
                this.validate();
            }
        }
        focusOnCaseSensitive() {
            this.caseSensitive?.focus();
        }
        highlightFindOptions() {
            this.domNode.classList.remove('highlight-' + (this._lastHighlightFindOptions));
            this._lastHighlightFindOptions = 1 - this._lastHighlightFindOptions;
            this.domNode.classList.add('highlight-' + (this._lastHighlightFindOptions));
        }
        validate() {
            this.inputBox.validate();
        }
        showMessage(message) {
            this.inputBox.showMessage(message);
        }
        clearMessage() {
            this.inputBox.hideMessage();
        }
    }
    exports.FindInput = FindInput;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[641/*vs/base/browser/ui/findinput/replaceInput*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,175/*vs/base/browser/ui/toggle/toggle*/,259/*vs/base/browser/ui/inputbox/inputBox*/,85/*vs/base/browser/ui/widget*/,26/*vs/base/common/codicons*/,6/*vs/base/common/event*/,3/*vs/nls*/,44/*vs/base/browser/ui/hover/hoverDelegateFactory*/,304/*vs/css!vs/base/browser/ui/findinput/findInput*/]), function (require, exports, dom, toggle_1, inputBox_1, widget_1, codicons_1, event_1, nls, hoverDelegateFactory_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ReplaceInput = void 0;
    const NLS_DEFAULT_LABEL = nls.localize(5, "input");
    const NLS_PRESERVE_CASE_LABEL = nls.localize(6, "Preserve Case");
    class PreserveCaseToggle extends toggle_1.Toggle {
        constructor(opts) {
            super({
                // TODO: does this need its own icon?
                icon: codicons_1.Codicon.preserveCase,
                title: NLS_PRESERVE_CASE_LABEL + opts.appendTitle,
                isChecked: opts.isChecked,
                hoverDelegate: opts.hoverDelegate ?? (0, hoverDelegateFactory_1.getDefaultHoverDelegate)('element'),
                inputActiveOptionBorder: opts.inputActiveOptionBorder,
                inputActiveOptionForeground: opts.inputActiveOptionForeground,
                inputActiveOptionBackground: opts.inputActiveOptionBackground,
            });
        }
    }
    class ReplaceInput extends widget_1.Widget {
        constructor(parent, contextViewProvider, _showOptionButtons, options) {
            super();
            this._showOptionButtons = _showOptionButtons;
            this.fixFocusOnOptionClickEnabled = true;
            this.cachedOptionsWidth = 0;
            this._onDidOptionChange = this._register(new event_1.Emitter());
            this.onDidOptionChange = this._onDidOptionChange.event;
            this._onKeyDown = this._register(new event_1.Emitter());
            this.onKeyDown = this._onKeyDown.event;
            this._onMouseDown = this._register(new event_1.Emitter());
            this._onInput = this._register(new event_1.Emitter());
            this._onKeyUp = this._register(new event_1.Emitter());
            this._onPreserveCaseKeyDown = this._register(new event_1.Emitter());
            this.onPreserveCaseKeyDown = this._onPreserveCaseKeyDown.event;
            this.contextViewProvider = contextViewProvider;
            this.placeholder = options.placeholder || '';
            this.validation = options.validation;
            this.label = options.label || NLS_DEFAULT_LABEL;
            const appendPreserveCaseLabel = options.appendPreserveCaseLabel || '';
            const history = options.history || [];
            const flexibleHeight = !!options.flexibleHeight;
            const flexibleWidth = !!options.flexibleWidth;
            const flexibleMaxHeight = options.flexibleMaxHeight;
            this.domNode = document.createElement('div');
            this.domNode.classList.add('monaco-findInput');
            this.inputBox = this._register(new inputBox_1.HistoryInputBox(this.domNode, this.contextViewProvider, {
                ariaLabel: this.label || '',
                placeholder: this.placeholder || '',
                validationOptions: {
                    validation: this.validation
                },
                history,
                showHistoryHint: options.showHistoryHint,
                flexibleHeight,
                flexibleWidth,
                flexibleMaxHeight,
                inputBoxStyles: options.inputBoxStyles
            }));
            this.preserveCase = this._register(new PreserveCaseToggle({
                appendTitle: appendPreserveCaseLabel,
                isChecked: false,
                ...options.toggleStyles
            }));
            this._register(this.preserveCase.onChange(viaKeyboard => {
                this._onDidOptionChange.fire(viaKeyboard);
                if (!viaKeyboard && this.fixFocusOnOptionClickEnabled) {
                    this.inputBox.focus();
                }
                this.validate();
            }));
            this._register(this.preserveCase.onKeyDown(e => {
                this._onPreserveCaseKeyDown.fire(e);
            }));
            if (this._showOptionButtons) {
                this.cachedOptionsWidth = this.preserveCase.width();
            }
            else {
                this.cachedOptionsWidth = 0;
            }
            // Arrow-Key support to navigate between options
            const indexes = [this.preserveCase.domNode];
            this.onkeydown(this.domNode, (event) => {
                if (event.equals(15 /* KeyCode.LeftArrow */) || event.equals(17 /* KeyCode.RightArrow */) || event.equals(9 /* KeyCode.Escape */)) {
                    const index = indexes.indexOf(this.domNode.ownerDocument.activeElement);
                    if (index >= 0) {
                        let newIndex = -1;
                        if (event.equals(17 /* KeyCode.RightArrow */)) {
                            newIndex = (index + 1) % indexes.length;
                        }
                        else if (event.equals(15 /* KeyCode.LeftArrow */)) {
                            if (index === 0) {
                                newIndex = indexes.length - 1;
                            }
                            else {
                                newIndex = index - 1;
                            }
                        }
                        if (event.equals(9 /* KeyCode.Escape */)) {
                            indexes[index].blur();
                            this.inputBox.focus();
                        }
                        else if (newIndex >= 0) {
                            indexes[newIndex].focus();
                        }
                        dom.EventHelper.stop(event, true);
                    }
                }
            });
            const controls = document.createElement('div');
            controls.className = 'controls';
            controls.style.display = this._showOptionButtons ? 'block' : 'none';
            controls.appendChild(this.preserveCase.domNode);
            this.domNode.appendChild(controls);
            parent?.appendChild(this.domNode);
            this.onkeydown(this.inputBox.inputElement, (e) => this._onKeyDown.fire(e));
            this.onkeyup(this.inputBox.inputElement, (e) => this._onKeyUp.fire(e));
            this.oninput(this.inputBox.inputElement, (e) => this._onInput.fire());
            this.onmousedown(this.inputBox.inputElement, (e) => this._onMouseDown.fire(e));
        }
        enable() {
            this.domNode.classList.remove('disabled');
            this.inputBox.enable();
            this.preserveCase.enable();
        }
        disable() {
            this.domNode.classList.add('disabled');
            this.inputBox.disable();
            this.preserveCase.disable();
        }
        setEnabled(enabled) {
            if (enabled) {
                this.enable();
            }
            else {
                this.disable();
            }
        }
        select() {
            this.inputBox.select();
        }
        focus() {
            this.inputBox.focus();
        }
        getPreserveCase() {
            return this.preserveCase.checked;
        }
        setPreserveCase(value) {
            this.preserveCase.checked = value;
        }
        focusOnPreserve() {
            this.preserveCase.focus();
        }
        validate() {
            this.inputBox?.validate();
        }
        set width(newWidth) {
            this.inputBox.paddingRight = this.cachedOptionsWidth;
            this.domNode.style.width = newWidth + 'px';
        }
        dispose() {
            super.dispose();
        }
    }
    exports.ReplaceInput = ReplaceInput;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[642/*vs/base/browser/ui/menu/menu*/], __M([1/*require*/,0/*exports*/,64/*vs/base/browser/browser*/,69/*vs/base/browser/touch*/,5/*vs/base/browser/dom*/,47/*vs/base/browser/keyboardEvent*/,77/*vs/base/browser/mouseEvent*/,87/*vs/base/browser/ui/actionbar/actionbar*/,151/*vs/base/browser/ui/actionbar/actionViewItems*/,353/*vs/base/browser/ui/contextview/contextview*/,86/*vs/base/browser/ui/scrollbar/scrollableElement*/,41/*vs/base/common/actions*/,14/*vs/base/common/async*/,26/*vs/base/common/codicons*/,191/*vs/base/common/codiconsUtil*/,30/*vs/base/common/themables*/,142/*vs/base/common/iconLabels*/,2/*vs/base/common/lifecycle*/,16/*vs/base/common/platform*/,11/*vs/base/common/strings*/]), function (require, exports, browser_1, touch_1, dom_1, keyboardEvent_1, mouseEvent_1, actionbar_1, actionViewItems_1, contextview_1, scrollableElement_1, actions_1, async_1, codicons_1, codiconsUtil_1, themables_1, iconLabels_1, lifecycle_1, platform_1, strings) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Menu = exports.VerticalDirection = exports.HorizontalDirection = exports.MENU_ESCAPED_MNEMONIC_REGEX = exports.MENU_MNEMONIC_REGEX = void 0;
    exports.cleanMnemonic = cleanMnemonic;
    exports.formatRule = formatRule;
    exports.MENU_MNEMONIC_REGEX = /\(&([^\s&])\)|(^|[^&])&([^\s&])/;
    exports.MENU_ESCAPED_MNEMONIC_REGEX = /(&amp;)?(&amp;)([^\s&])/g;
    var HorizontalDirection;
    (function (HorizontalDirection) {
        HorizontalDirection[HorizontalDirection["Right"] = 0] = "Right";
        HorizontalDirection[HorizontalDirection["Left"] = 1] = "Left";
    })(HorizontalDirection || (exports.HorizontalDirection = HorizontalDirection = {}));
    var VerticalDirection;
    (function (VerticalDirection) {
        VerticalDirection[VerticalDirection["Above"] = 0] = "Above";
        VerticalDirection[VerticalDirection["Below"] = 1] = "Below";
    })(VerticalDirection || (exports.VerticalDirection = VerticalDirection = {}));
    class Menu extends actionbar_1.ActionBar {
        constructor(container, actions, options, menuStyles) {
            container.classList.add('monaco-menu-container');
            container.setAttribute('role', 'presentation');
            const menuElement = document.createElement('div');
            menuElement.classList.add('monaco-menu');
            menuElement.setAttribute('role', 'presentation');
            super(menuElement, {
                orientation: 1 /* ActionsOrientation.VERTICAL */,
                actionViewItemProvider: action => this.doGetActionViewItem(action, options, parentData),
                context: options.context,
                actionRunner: options.actionRunner,
                ariaLabel: options.ariaLabel,
                ariaRole: 'menu',
                focusOnlyEnabledItems: true,
                triggerKeys: { keys: [3 /* KeyCode.Enter */, ...(platform_1.isMacintosh || platform_1.isLinux ? [10 /* KeyCode.Space */] : [])], keyDown: true }
            });
            this.menuStyles = menuStyles;
            this.menuElement = menuElement;
            this.actionsList.tabIndex = 0;
            this.initializeOrUpdateStyleSheet(container, menuStyles);
            this._register(touch_1.Gesture.addTarget(menuElement));
            this._register((0, dom_1.addDisposableListener)(menuElement, dom_1.EventType.KEY_DOWN, (e) => {
                const event = new keyboardEvent_1.StandardKeyboardEvent(e);
                // Stop tab navigation of menus
                if (event.equals(2 /* KeyCode.Tab */)) {
                    e.preventDefault();
                }
            }));
            if (options.enableMnemonics) {
                this._register((0, dom_1.addDisposableListener)(menuElement, dom_1.EventType.KEY_DOWN, (e) => {
                    const key = e.key.toLocaleLowerCase();
                    if (this.mnemonics.has(key)) {
                        dom_1.EventHelper.stop(e, true);
                        const actions = this.mnemonics.get(key);
                        if (actions.length === 1) {
                            if (actions[0] instanceof SubmenuMenuActionViewItem && actions[0].container) {
                                this.focusItemByElement(actions[0].container);
                            }
                            actions[0].onClick(e);
                        }
                        if (actions.length > 1) {
                            const action = actions.shift();
                            if (action && action.container) {
                                this.focusItemByElement(action.container);
                                actions.push(action);
                            }
                            this.mnemonics.set(key, actions);
                        }
                    }
                }));
            }
            if (platform_1.isLinux) {
                this._register((0, dom_1.addDisposableListener)(menuElement, dom_1.EventType.KEY_DOWN, e => {
                    const event = new keyboardEvent_1.StandardKeyboardEvent(e);
                    if (event.equals(14 /* KeyCode.Home */) || event.equals(11 /* KeyCode.PageUp */)) {
                        this.focusedItem = this.viewItems.length - 1;
                        this.focusNext();
                        dom_1.EventHelper.stop(e, true);
                    }
                    else if (event.equals(13 /* KeyCode.End */) || event.equals(12 /* KeyCode.PageDown */)) {
                        this.focusedItem = 0;
                        this.focusPrevious();
                        dom_1.EventHelper.stop(e, true);
                    }
                }));
            }
            this._register((0, dom_1.addDisposableListener)(this.domNode, dom_1.EventType.MOUSE_OUT, e => {
                const relatedTarget = e.relatedTarget;
                if (!(0, dom_1.isAncestor)(relatedTarget, this.domNode)) {
                    this.focusedItem = undefined;
                    this.updateFocus();
                    e.stopPropagation();
                }
            }));
            this._register((0, dom_1.addDisposableListener)(this.actionsList, dom_1.EventType.MOUSE_OVER, e => {
                let target = e.target;
                if (!target || !(0, dom_1.isAncestor)(target, this.actionsList) || target === this.actionsList) {
                    return;
                }
                while (target.parentElement !== this.actionsList && target.parentElement !== null) {
                    target = target.parentElement;
                }
                if (target.classList.contains('action-item')) {
                    const lastFocusedItem = this.focusedItem;
                    this.setFocusedItem(target);
                    if (lastFocusedItem !== this.focusedItem) {
                        this.updateFocus();
                    }
                }
            }));
            // Support touch on actions list to focus items (needed for submenus)
            this._register(touch_1.Gesture.addTarget(this.actionsList));
            this._register((0, dom_1.addDisposableListener)(this.actionsList, touch_1.EventType.Tap, e => {
                let target = e.initialTarget;
                if (!target || !(0, dom_1.isAncestor)(target, this.actionsList) || target === this.actionsList) {
                    return;
                }
                while (target.parentElement !== this.actionsList && target.parentElement !== null) {
                    target = target.parentElement;
                }
                if (target.classList.contains('action-item')) {
                    const lastFocusedItem = this.focusedItem;
                    this.setFocusedItem(target);
                    if (lastFocusedItem !== this.focusedItem) {
                        this.updateFocus();
                    }
                }
            }));
            const parentData = {
                parent: this
            };
            this.mnemonics = new Map();
            // Scroll Logic
            this.scrollableElement = this._register(new scrollableElement_1.DomScrollableElement(menuElement, {
                alwaysConsumeMouseWheel: true,
                horizontal: 2 /* ScrollbarVisibility.Hidden */,
                vertical: 3 /* ScrollbarVisibility.Visible */,
                verticalScrollbarSize: 7,
                handleMouseWheel: true,
                useShadows: true
            }));
            const scrollElement = this.scrollableElement.getDomNode();
            scrollElement.style.position = '';
            this.styleScrollElement(scrollElement, menuStyles);
            // Support scroll on menu drag
            this._register((0, dom_1.addDisposableListener)(menuElement, touch_1.EventType.Change, e => {
                dom_1.EventHelper.stop(e, true);
                const scrollTop = this.scrollableElement.getScrollPosition().scrollTop;
                this.scrollableElement.setScrollPosition({ scrollTop: scrollTop - e.translationY });
            }));
            this._register((0, dom_1.addDisposableListener)(scrollElement, dom_1.EventType.MOUSE_UP, e => {
                // Absorb clicks in menu dead space https://github.com/microsoft/vscode/issues/63575
                // We do this on the scroll element so the scroll bar doesn't dismiss the menu either
                e.preventDefault();
            }));
            const window = (0, dom_1.getWindow)(container);
            menuElement.style.maxHeight = `${Math.max(10, window.innerHeight - container.getBoundingClientRect().top - 35)}px`;
            actions = actions.filter((a, idx) => {
                if (options.submenuIds?.has(a.id)) {
                    console.warn(`Found submenu cycle: ${a.id}`);
                    return false;
                }
                // Filter out consecutive or useless separators
                if (a instanceof actions_1.Separator) {
                    if (idx === actions.length - 1 || idx === 0) {
                        return false;
                    }
                    const prevAction = actions[idx - 1];
                    if (prevAction instanceof actions_1.Separator) {
                        return false;
                    }
                }
                return true;
            });
            this.push(actions, { icon: true, label: true, isMenu: true });
            container.appendChild(this.scrollableElement.getDomNode());
            this.scrollableElement.scanDomNode();
            this.viewItems.filter(item => !(item instanceof MenuSeparatorActionViewItem)).forEach((item, index, array) => {
                item.updatePositionInSet(index + 1, array.length);
            });
        }
        initializeOrUpdateStyleSheet(container, style) {
            if (!this.styleSheet) {
                if ((0, dom_1.isInShadowDOM)(container)) {
                    this.styleSheet = (0, dom_1.createStyleSheet)(container);
                }
                else {
                    if (!Menu.globalStyleSheet) {
                        Menu.globalStyleSheet = (0, dom_1.createStyleSheet)();
                    }
                    this.styleSheet = Menu.globalStyleSheet;
                }
            }
            this.styleSheet.textContent = getMenuWidgetCSS(style, (0, dom_1.isInShadowDOM)(container));
        }
        styleScrollElement(scrollElement, style) {
            const fgColor = style.foregroundColor ?? '';
            const bgColor = style.backgroundColor ?? '';
            const border = style.borderColor ? `1px solid ${style.borderColor}` : '';
            const borderRadius = '5px';
            const shadow = style.shadowColor ? `0 2px 8px ${style.shadowColor}` : '';
            scrollElement.style.outline = border;
            scrollElement.style.borderRadius = borderRadius;
            scrollElement.style.color = fgColor;
            scrollElement.style.backgroundColor = bgColor;
            scrollElement.style.boxShadow = shadow;
        }
        getContainer() {
            return this.scrollableElement.getDomNode();
        }
        get onScroll() {
            return this.scrollableElement.onScroll;
        }
        focusItemByElement(element) {
            const lastFocusedItem = this.focusedItem;
            this.setFocusedItem(element);
            if (lastFocusedItem !== this.focusedItem) {
                this.updateFocus();
            }
        }
        setFocusedItem(element) {
            for (let i = 0; i < this.actionsList.children.length; i++) {
                const elem = this.actionsList.children[i];
                if (element === elem) {
                    this.focusedItem = i;
                    break;
                }
            }
        }
        updateFocus(fromRight) {
            super.updateFocus(fromRight, true, true);
            if (typeof this.focusedItem !== 'undefined') {
                // Workaround for #80047 caused by an issue in chromium
                // https://bugs.chromium.org/p/chromium/issues/detail?id=414283
                // When that's fixed, just call this.scrollableElement.scanDomNode()
                this.scrollableElement.setScrollPosition({
                    scrollTop: Math.round(this.menuElement.scrollTop)
                });
            }
        }
        doGetActionViewItem(action, options, parentData) {
            if (action instanceof actions_1.Separator) {
                return new MenuSeparatorActionViewItem(options.context, action, { icon: true }, this.menuStyles);
            }
            else if (action instanceof actions_1.SubmenuAction) {
                const menuActionViewItem = new SubmenuMenuActionViewItem(action, action.actions, parentData, { ...options, submenuIds: new Set([...(options.submenuIds || []), action.id]) }, this.menuStyles);
                if (options.enableMnemonics) {
                    const mnemonic = menuActionViewItem.getMnemonic();
                    if (mnemonic && menuActionViewItem.isEnabled()) {
                        let actionViewItems = [];
                        if (this.mnemonics.has(mnemonic)) {
                            actionViewItems = this.mnemonics.get(mnemonic);
                        }
                        actionViewItems.push(menuActionViewItem);
                        this.mnemonics.set(mnemonic, actionViewItems);
                    }
                }
                return menuActionViewItem;
            }
            else {
                const menuItemOptions = { enableMnemonics: options.enableMnemonics, useEventAsContext: options.useEventAsContext };
                if (options.getKeyBinding) {
                    const keybinding = options.getKeyBinding(action);
                    if (keybinding) {
                        const keybindingLabel = keybinding.getLabel();
                        if (keybindingLabel) {
                            menuItemOptions.keybinding = keybindingLabel;
                        }
                    }
                }
                const menuActionViewItem = new BaseMenuActionViewItem(options.context, action, menuItemOptions, this.menuStyles);
                if (options.enableMnemonics) {
                    const mnemonic = menuActionViewItem.getMnemonic();
                    if (mnemonic && menuActionViewItem.isEnabled()) {
                        let actionViewItems = [];
                        if (this.mnemonics.has(mnemonic)) {
                            actionViewItems = this.mnemonics.get(mnemonic);
                        }
                        actionViewItems.push(menuActionViewItem);
                        this.mnemonics.set(mnemonic, actionViewItems);
                    }
                }
                return menuActionViewItem;
            }
        }
    }
    exports.Menu = Menu;
    class BaseMenuActionViewItem extends actionViewItems_1.BaseActionViewItem {
        constructor(ctx, action, options, menuStyle) {
            options.isMenu = true;
            super(action, action, options);
            this.menuStyle = menuStyle;
            this.options = options;
            this.options.icon = options.icon !== undefined ? options.icon : false;
            this.options.label = options.label !== undefined ? options.label : true;
            this.cssClass = '';
            // Set mnemonic
            if (this.options.label && options.enableMnemonics) {
                const label = this.action.label;
                if (label) {
                    const matches = exports.MENU_MNEMONIC_REGEX.exec(label);
                    if (matches) {
                        this.mnemonic = (!!matches[1] ? matches[1] : matches[3]).toLocaleLowerCase();
                    }
                }
            }
            // Add mouse up listener later to avoid accidental clicks
            this.runOnceToEnableMouseUp = new async_1.RunOnceScheduler(() => {
                if (!this.element) {
                    return;
                }
                this._register((0, dom_1.addDisposableListener)(this.element, dom_1.EventType.MOUSE_UP, e => {
                    // removed default prevention as it conflicts
                    // with BaseActionViewItem #101537
                    // add back if issues arise and link new issue
                    dom_1.EventHelper.stop(e, true);
                    // See https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Interact_with_the_clipboard
                    // > Writing to the clipboard
                    // > You can use the "cut" and "copy" commands without any special
                    // permission if you are using them in a short-lived event handler
                    // for a user action (for example, a click handler).
                    // => to get the Copy and Paste context menu actions working on Firefox,
                    // there should be no timeout here
                    if (browser_1.isFirefox) {
                        const mouseEvent = new mouseEvent_1.StandardMouseEvent((0, dom_1.getWindow)(this.element), e);
                        // Allowing right click to trigger the event causes the issue described below,
                        // but since the solution below does not work in FF, we must disable right click
                        if (mouseEvent.rightButton) {
                            return;
                        }
                        this.onClick(e);
                    }
                    // In all other cases, set timeout to allow context menu cancellation to trigger
                    // otherwise the action will destroy the menu and a second context menu
                    // will still trigger for right click.
                    else {
                        setTimeout(() => {
                            this.onClick(e);
                        }, 0);
                    }
                }));
                this._register((0, dom_1.addDisposableListener)(this.element, dom_1.EventType.CONTEXT_MENU, e => {
                    dom_1.EventHelper.stop(e, true);
                }));
            }, 100);
            this._register(this.runOnceToEnableMouseUp);
        }
        render(container) {
            super.render(container);
            if (!this.element) {
                return;
            }
            this.container = container;
            this.item = (0, dom_1.append)(this.element, (0, dom_1.$)('a.action-menu-item'));
            if (this._action.id === actions_1.Separator.ID) {
                // A separator is a presentation item
                this.item.setAttribute('role', 'presentation');
            }
            else {
                this.item.setAttribute('role', 'menuitem');
                if (this.mnemonic) {
                    this.item.setAttribute('aria-keyshortcuts', `${this.mnemonic}`);
                }
            }
            this.check = (0, dom_1.append)(this.item, (0, dom_1.$)('span.menu-item-check' + themables_1.ThemeIcon.asCSSSelector(codicons_1.Codicon.menuSelection)));
            this.check.setAttribute('role', 'none');
            this.label = (0, dom_1.append)(this.item, (0, dom_1.$)('span.action-label'));
            if (this.options.label && this.options.keybinding) {
                (0, dom_1.append)(this.item, (0, dom_1.$)('span.keybinding')).textContent = this.options.keybinding;
            }
            // Adds mouse up listener to actually run the action
            this.runOnceToEnableMouseUp.schedule();
            this.updateClass();
            this.updateLabel();
            this.updateTooltip();
            this.updateEnabled();
            this.updateChecked();
            this.applyStyle();
        }
        blur() {
            super.blur();
            this.applyStyle();
        }
        focus() {
            super.focus();
            this.item?.focus();
            this.applyStyle();
        }
        updatePositionInSet(pos, setSize) {
            if (this.item) {
                this.item.setAttribute('aria-posinset', `${pos}`);
                this.item.setAttribute('aria-setsize', `${setSize}`);
            }
        }
        updateLabel() {
            if (!this.label) {
                return;
            }
            if (this.options.label) {
                (0, dom_1.clearNode)(this.label);
                let label = (0, iconLabels_1.stripIcons)(this.action.label);
                if (label) {
                    const cleanLabel = cleanMnemonic(label);
                    if (!this.options.enableMnemonics) {
                        label = cleanLabel;
                    }
                    this.label.setAttribute('aria-label', cleanLabel.replace(/&&/g, '&'));
                    const matches = exports.MENU_MNEMONIC_REGEX.exec(label);
                    if (matches) {
                        label = strings.escape(label);
                        // This is global, reset it
                        exports.MENU_ESCAPED_MNEMONIC_REGEX.lastIndex = 0;
                        let escMatch = exports.MENU_ESCAPED_MNEMONIC_REGEX.exec(label);
                        // We can't use negative lookbehind so if we match our negative and skip
                        while (escMatch && escMatch[1]) {
                            escMatch = exports.MENU_ESCAPED_MNEMONIC_REGEX.exec(label);
                        }
                        const replaceDoubleEscapes = (str) => str.replace(/&amp;&amp;/g, '&amp;');
                        if (escMatch) {
                            this.label.append(strings.ltrim(replaceDoubleEscapes(label.substr(0, escMatch.index)), ' '), (0, dom_1.$)('u', { 'aria-hidden': 'true' }, escMatch[3]), strings.rtrim(replaceDoubleEscapes(label.substr(escMatch.index + escMatch[0].length)), ' '));
                        }
                        else {
                            this.label.innerText = replaceDoubleEscapes(label).trim();
                        }
                        this.item?.setAttribute('aria-keyshortcuts', (!!matches[1] ? matches[1] : matches[3]).toLocaleLowerCase());
                    }
                    else {
                        this.label.innerText = label.replace(/&&/g, '&').trim();
                    }
                }
            }
        }
        updateTooltip() {
            // menus should function like native menus and they do not have tooltips
        }
        updateClass() {
            if (this.cssClass && this.item) {
                this.item.classList.remove(...this.cssClass.split(' '));
            }
            if (this.options.icon && this.label) {
                this.cssClass = this.action.class || '';
                this.label.classList.add('icon');
                if (this.cssClass) {
                    this.label.classList.add(...this.cssClass.split(' '));
                }
                this.updateEnabled();
            }
            else if (this.label) {
                this.label.classList.remove('icon');
            }
        }
        updateEnabled() {
            if (this.action.enabled) {
                if (this.element) {
                    this.element.classList.remove('disabled');
                    this.element.removeAttribute('aria-disabled');
                }
                if (this.item) {
                    this.item.classList.remove('disabled');
                    this.item.removeAttribute('aria-disabled');
                    this.item.tabIndex = 0;
                }
            }
            else {
                if (this.element) {
                    this.element.classList.add('disabled');
                    this.element.setAttribute('aria-disabled', 'true');
                }
                if (this.item) {
                    this.item.classList.add('disabled');
                    this.item.setAttribute('aria-disabled', 'true');
                }
            }
        }
        updateChecked() {
            if (!this.item) {
                return;
            }
            const checked = this.action.checked;
            this.item.classList.toggle('checked', !!checked);
            if (checked !== undefined) {
                this.item.setAttribute('role', 'menuitemcheckbox');
                this.item.setAttribute('aria-checked', checked ? 'true' : 'false');
            }
            else {
                this.item.setAttribute('role', 'menuitem');
                this.item.setAttribute('aria-checked', '');
            }
        }
        getMnemonic() {
            return this.mnemonic;
        }
        applyStyle() {
            const isSelected = this.element && this.element.classList.contains('focused');
            const fgColor = isSelected && this.menuStyle.selectionForegroundColor ? this.menuStyle.selectionForegroundColor : this.menuStyle.foregroundColor;
            const bgColor = isSelected && this.menuStyle.selectionBackgroundColor ? this.menuStyle.selectionBackgroundColor : undefined;
            const outline = isSelected && this.menuStyle.selectionBorderColor ? `1px solid ${this.menuStyle.selectionBorderColor}` : '';
            const outlineOffset = isSelected && this.menuStyle.selectionBorderColor ? `-1px` : '';
            if (this.item) {
                this.item.style.color = fgColor ?? '';
                this.item.style.backgroundColor = bgColor ?? '';
                this.item.style.outline = outline;
                this.item.style.outlineOffset = outlineOffset;
            }
            if (this.check) {
                this.check.style.color = fgColor ?? '';
            }
        }
    }
    class SubmenuMenuActionViewItem extends BaseMenuActionViewItem {
        constructor(action, submenuActions, parentData, submenuOptions, menuStyles) {
            super(action, action, submenuOptions, menuStyles);
            this.submenuActions = submenuActions;
            this.parentData = parentData;
            this.submenuOptions = submenuOptions;
            this.mysubmenu = null;
            this.submenuDisposables = this._register(new lifecycle_1.DisposableStore());
            this.mouseOver = false;
            this.expandDirection = submenuOptions && submenuOptions.expandDirection !== undefined ? submenuOptions.expandDirection : { horizontal: HorizontalDirection.Right, vertical: VerticalDirection.Below };
            this.showScheduler = new async_1.RunOnceScheduler(() => {
                if (this.mouseOver) {
                    this.cleanupExistingSubmenu(false);
                    this.createSubmenu(false);
                }
            }, 250);
            this.hideScheduler = new async_1.RunOnceScheduler(() => {
                if (this.element && (!(0, dom_1.isAncestor)((0, dom_1.getActiveElement)(), this.element) && this.parentData.submenu === this.mysubmenu)) {
                    this.parentData.parent.focus(false);
                    this.cleanupExistingSubmenu(true);
                }
            }, 750);
        }
        render(container) {
            super.render(container);
            if (!this.element) {
                return;
            }
            if (this.item) {
                this.item.classList.add('monaco-submenu-item');
                this.item.tabIndex = 0;
                this.item.setAttribute('aria-haspopup', 'true');
                this.updateAriaExpanded('false');
                this.submenuIndicator = (0, dom_1.append)(this.item, (0, dom_1.$)('span.submenu-indicator' + themables_1.ThemeIcon.asCSSSelector(codicons_1.Codicon.menuSubmenu)));
                this.submenuIndicator.setAttribute('aria-hidden', 'true');
            }
            this._register((0, dom_1.addDisposableListener)(this.element, dom_1.EventType.KEY_UP, e => {
                const event = new keyboardEvent_1.StandardKeyboardEvent(e);
                if (event.equals(17 /* KeyCode.RightArrow */) || event.equals(3 /* KeyCode.Enter */)) {
                    dom_1.EventHelper.stop(e, true);
                    this.createSubmenu(true);
                }
            }));
            this._register((0, dom_1.addDisposableListener)(this.element, dom_1.EventType.KEY_DOWN, e => {
                const event = new keyboardEvent_1.StandardKeyboardEvent(e);
                if ((0, dom_1.getActiveElement)() === this.item) {
                    if (event.equals(17 /* KeyCode.RightArrow */) || event.equals(3 /* KeyCode.Enter */)) {
                        dom_1.EventHelper.stop(e, true);
                    }
                }
            }));
            this._register((0, dom_1.addDisposableListener)(this.element, dom_1.EventType.MOUSE_OVER, e => {
                if (!this.mouseOver) {
                    this.mouseOver = true;
                    this.showScheduler.schedule();
                }
            }));
            this._register((0, dom_1.addDisposableListener)(this.element, dom_1.EventType.MOUSE_LEAVE, e => {
                this.mouseOver = false;
            }));
            this._register((0, dom_1.addDisposableListener)(this.element, dom_1.EventType.FOCUS_OUT, e => {
                if (this.element && !(0, dom_1.isAncestor)((0, dom_1.getActiveElement)(), this.element)) {
                    this.hideScheduler.schedule();
                }
            }));
            this._register(this.parentData.parent.onScroll(() => {
                if (this.parentData.submenu === this.mysubmenu) {
                    this.parentData.parent.focus(false);
                    this.cleanupExistingSubmenu(true);
                }
            }));
        }
        updateEnabled() {
            // override on submenu entry
            // native menus do not observe enablement on sumbenus
            // we mimic that behavior
        }
        onClick(e) {
            // stop clicking from trying to run an action
            dom_1.EventHelper.stop(e, true);
            this.cleanupExistingSubmenu(false);
            this.createSubmenu(true);
        }
        cleanupExistingSubmenu(force) {
            if (this.parentData.submenu && (force || (this.parentData.submenu !== this.mysubmenu))) {
                // disposal may throw if the submenu has already been removed
                try {
                    this.parentData.submenu.dispose();
                }
                catch { }
                this.parentData.submenu = undefined;
                this.updateAriaExpanded('false');
                if (this.submenuContainer) {
                    this.submenuDisposables.clear();
                    this.submenuContainer = undefined;
                }
            }
        }
        calculateSubmenuMenuLayout(windowDimensions, submenu, entry, expandDirection) {
            const ret = { top: 0, left: 0 };
            // Start with horizontal
            ret.left = (0, contextview_1.layout)(windowDimensions.width, submenu.width, { position: expandDirection.horizontal === HorizontalDirection.Right ? 0 /* LayoutAnchorPosition.Before */ : 1 /* LayoutAnchorPosition.After */, offset: entry.left, size: entry.width });
            // We don't have enough room to layout the menu fully, so we are overlapping the menu
            if (ret.left >= entry.left && ret.left < entry.left + entry.width) {
                if (entry.left + 10 + submenu.width <= windowDimensions.width) {
                    ret.left = entry.left + 10;
                }
                entry.top += 10;
                entry.height = 0;
            }
            // Now that we have a horizontal position, try layout vertically
            ret.top = (0, contextview_1.layout)(windowDimensions.height, submenu.height, { position: 0 /* LayoutAnchorPosition.Before */, offset: entry.top, size: 0 });
            // We didn't have enough room below, but we did above, so we shift down to align the menu
            if (ret.top + submenu.height === entry.top && ret.top + entry.height + submenu.height <= windowDimensions.height) {
                ret.top += entry.height;
            }
            return ret;
        }
        createSubmenu(selectFirstItem = true) {
            if (!this.element) {
                return;
            }
            if (!this.parentData.submenu) {
                this.updateAriaExpanded('true');
                this.submenuContainer = (0, dom_1.append)(this.element, (0, dom_1.$)('div.monaco-submenu'));
                this.submenuContainer.classList.add('menubar-menu-items-holder', 'context-view');
                // Set the top value of the menu container before construction
                // This allows the menu constructor to calculate the proper max height
                const computedStyles = (0, dom_1.getWindow)(this.parentData.parent.domNode).getComputedStyle(this.parentData.parent.domNode);
                const paddingTop = parseFloat(computedStyles.paddingTop || '0') || 0;
                // this.submenuContainer.style.top = `${this.element.offsetTop - this.parentData.parent.scrollOffset - paddingTop}px`;
                this.submenuContainer.style.zIndex = '1';
                this.submenuContainer.style.position = 'fixed';
                this.submenuContainer.style.top = '0';
                this.submenuContainer.style.left = '0';
                this.parentData.submenu = new Menu(this.submenuContainer, this.submenuActions.length ? this.submenuActions : [new actions_1.EmptySubmenuAction()], this.submenuOptions, this.menuStyle);
                // layout submenu
                const entryBox = this.element.getBoundingClientRect();
                const entryBoxUpdated = {
                    top: entryBox.top - paddingTop,
                    left: entryBox.left,
                    height: entryBox.height + 2 * paddingTop,
                    width: entryBox.width
                };
                const viewBox = this.submenuContainer.getBoundingClientRect();
                const window = (0, dom_1.getWindow)(this.element);
                const { top, left } = this.calculateSubmenuMenuLayout(new dom_1.Dimension(window.innerWidth, window.innerHeight), dom_1.Dimension.lift(viewBox), entryBoxUpdated, this.expandDirection);
                // subtract offsets caused by transform parent
                this.submenuContainer.style.left = `${left - viewBox.left}px`;
                this.submenuContainer.style.top = `${top - viewBox.top}px`;
                this.submenuDisposables.add((0, dom_1.addDisposableListener)(this.submenuContainer, dom_1.EventType.KEY_UP, e => {
                    const event = new keyboardEvent_1.StandardKeyboardEvent(e);
                    if (event.equals(15 /* KeyCode.LeftArrow */)) {
                        dom_1.EventHelper.stop(e, true);
                        this.parentData.parent.focus();
                        this.cleanupExistingSubmenu(true);
                    }
                }));
                this.submenuDisposables.add((0, dom_1.addDisposableListener)(this.submenuContainer, dom_1.EventType.KEY_DOWN, e => {
                    const event = new keyboardEvent_1.StandardKeyboardEvent(e);
                    if (event.equals(15 /* KeyCode.LeftArrow */)) {
                        dom_1.EventHelper.stop(e, true);
                    }
                }));
                this.submenuDisposables.add(this.parentData.submenu.onDidCancel(() => {
                    this.parentData.parent.focus();
                    this.cleanupExistingSubmenu(true);
                }));
                this.parentData.submenu.focus(selectFirstItem);
                this.mysubmenu = this.parentData.submenu;
            }
            else {
                this.parentData.submenu.focus(false);
            }
        }
        updateAriaExpanded(value) {
            if (this.item) {
                this.item?.setAttribute('aria-expanded', value);
            }
        }
        applyStyle() {
            super.applyStyle();
            const isSelected = this.element && this.element.classList.contains('focused');
            const fgColor = isSelected && this.menuStyle.selectionForegroundColor ? this.menuStyle.selectionForegroundColor : this.menuStyle.foregroundColor;
            if (this.submenuIndicator) {
                this.submenuIndicator.style.color = fgColor ?? '';
            }
        }
        dispose() {
            super.dispose();
            this.hideScheduler.dispose();
            if (this.mysubmenu) {
                this.mysubmenu.dispose();
                this.mysubmenu = null;
            }
            if (this.submenuContainer) {
                this.submenuContainer = undefined;
            }
        }
    }
    class MenuSeparatorActionViewItem extends actionViewItems_1.ActionViewItem {
        constructor(context, action, options, menuStyles) {
            super(context, action, options);
            this.menuStyles = menuStyles;
        }
        render(container) {
            super.render(container);
            if (this.label) {
                this.label.style.borderBottomColor = this.menuStyles.separatorColor ? `${this.menuStyles.separatorColor}` : '';
            }
        }
    }
    function cleanMnemonic(label) {
        const regex = exports.MENU_MNEMONIC_REGEX;
        const matches = regex.exec(label);
        if (!matches) {
            return label;
        }
        const mnemonicInText = !matches[1];
        return label.replace(regex, mnemonicInText ? '$2$3' : '').trim();
    }
    function formatRule(c) {
        const fontCharacter = (0, codiconsUtil_1.getCodiconFontCharacters)()[c.id];
        return `.codicon-${c.id}:before { content: '\\${fontCharacter.toString(16)}'; }`;
    }
    function getMenuWidgetCSS(style, isForShadowDom) {
        let result = /* css */ `
.monaco-menu {
	font-size: 13px;
	border-radius: 5px;
	min-width: 160px;
}

${formatRule(codicons_1.Codicon.menuSelection)}
${formatRule(codicons_1.Codicon.menuSubmenu)}

.monaco-menu .monaco-action-bar {
	text-align: right;
	overflow: hidden;
	white-space: nowrap;
}

.monaco-menu .monaco-action-bar .actions-container {
	display: flex;
	margin: 0 auto;
	padding: 0;
	width: 100%;
	justify-content: flex-end;
}

.monaco-menu .monaco-action-bar.vertical .actions-container {
	display: inline-block;
}

.monaco-menu .monaco-action-bar.reverse .actions-container {
	flex-direction: row-reverse;
}

.monaco-menu .monaco-action-bar .action-item {
	cursor: pointer;
	display: inline-block;
	transition: transform 50ms ease;
	position: relative;  /* DO NOT REMOVE - this is the key to preventing the ghosting icon bug in Chrome 42 */
}

.monaco-menu .monaco-action-bar .action-item.disabled {
	cursor: default;
}

.monaco-menu .monaco-action-bar .action-item .icon,
.monaco-menu .monaco-action-bar .action-item .codicon {
	display: inline-block;
}

.monaco-menu .monaco-action-bar .action-item .codicon {
	display: flex;
	align-items: center;
}

.monaco-menu .monaco-action-bar .action-label {
	font-size: 11px;
	margin-right: 4px;
}

.monaco-menu .monaco-action-bar .action-item.disabled .action-label,
.monaco-menu .monaco-action-bar .action-item.disabled .action-label:hover {
	color: var(--vscode-disabledForeground);
}

/* Vertical actions */

.monaco-menu .monaco-action-bar.vertical {
	text-align: left;
}

.monaco-menu .monaco-action-bar.vertical .action-item {
	display: block;
}

.monaco-menu .monaco-action-bar.vertical .action-label.separator {
	display: block;
	border-bottom: 1px solid var(--vscode-menu-separatorBackground);
	padding-top: 1px;
	padding: 30px;
}

.monaco-menu .secondary-actions .monaco-action-bar .action-label {
	margin-left: 6px;
}

/* Action Items */
.monaco-menu .monaco-action-bar .action-item.select-container {
	overflow: hidden; /* somehow the dropdown overflows its container, we prevent it here to not push */
	flex: 1;
	max-width: 170px;
	min-width: 60px;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-right: 10px;
}

.monaco-menu .monaco-action-bar.vertical {
	margin-left: 0;
	overflow: visible;
}

.monaco-menu .monaco-action-bar.vertical .actions-container {
	display: block;
}

.monaco-menu .monaco-action-bar.vertical .action-item {
	padding: 0;
	transform: none;
	display: flex;
}

.monaco-menu .monaco-action-bar.vertical .action-item.active {
	transform: none;
}

.monaco-menu .monaco-action-bar.vertical .action-menu-item {
	flex: 1 1 auto;
	display: flex;
	height: 2em;
	align-items: center;
	position: relative;
	margin: 0 4px;
	border-radius: 4px;
}

.monaco-menu .monaco-action-bar.vertical .action-menu-item:hover .keybinding,
.monaco-menu .monaco-action-bar.vertical .action-menu-item:focus .keybinding {
	opacity: unset;
}

.monaco-menu .monaco-action-bar.vertical .action-label {
	flex: 1 1 auto;
	text-decoration: none;
	padding: 0 1em;
	background: none;
	font-size: 12px;
	line-height: 1;
}

.monaco-menu .monaco-action-bar.vertical .keybinding,
.monaco-menu .monaco-action-bar.vertical .submenu-indicator {
	display: inline-block;
	flex: 2 1 auto;
	padding: 0 1em;
	text-align: right;
	font-size: 12px;
	line-height: 1;
}

.monaco-menu .monaco-action-bar.vertical .submenu-indicator {
	height: 100%;
}

.monaco-menu .monaco-action-bar.vertical .submenu-indicator.codicon {
	font-size: 16px !important;
	display: flex;
	align-items: center;
}

.monaco-menu .monaco-action-bar.vertical .submenu-indicator.codicon::before {
	margin-left: auto;
	margin-right: -20px;
}

.monaco-menu .monaco-action-bar.vertical .action-item.disabled .keybinding,
.monaco-menu .monaco-action-bar.vertical .action-item.disabled .submenu-indicator {
	opacity: 0.4;
}

.monaco-menu .monaco-action-bar.vertical .action-label:not(.separator) {
	display: inline-block;
	box-sizing: border-box;
	margin: 0;
}

.monaco-menu .monaco-action-bar.vertical .action-item {
	position: static;
	overflow: visible;
}

.monaco-menu .monaco-action-bar.vertical .action-item .monaco-submenu {
	position: absolute;
}

.monaco-menu .monaco-action-bar.vertical .action-label.separator {
	width: 100%;
	height: 0px !important;
	opacity: 1;
}

.monaco-menu .monaco-action-bar.vertical .action-label.separator.text {
	padding: 0.7em 1em 0.1em 1em;
	font-weight: bold;
	opacity: 1;
}

.monaco-menu .monaco-action-bar.vertical .action-label:hover {
	color: inherit;
}

.monaco-menu .monaco-action-bar.vertical .menu-item-check {
	position: absolute;
	visibility: hidden;
	width: 1em;
	height: 100%;
}

.monaco-menu .monaco-action-bar.vertical .action-menu-item.checked .menu-item-check {
	visibility: visible;
	display: flex;
	align-items: center;
	justify-content: center;
}

/* Context Menu */

.context-view.monaco-menu-container {
	outline: 0;
	border: none;
	animation: fadeIn 0.083s linear;
	-webkit-app-region: no-drag;
}

.context-view.monaco-menu-container :focus,
.context-view.monaco-menu-container .monaco-action-bar.vertical:focus,
.context-view.monaco-menu-container .monaco-action-bar.vertical :focus {
	outline: 0;
}

.hc-black .context-view.monaco-menu-container,
.hc-light .context-view.monaco-menu-container,
:host-context(.hc-black) .context-view.monaco-menu-container,
:host-context(.hc-light) .context-view.monaco-menu-container {
	box-shadow: none;
}

.hc-black .monaco-menu .monaco-action-bar.vertical .action-item.focused,
.hc-light .monaco-menu .monaco-action-bar.vertical .action-item.focused,
:host-context(.hc-black) .monaco-menu .monaco-action-bar.vertical .action-item.focused,
:host-context(.hc-light) .monaco-menu .monaco-action-bar.vertical .action-item.focused {
	background: none;
}

/* Vertical Action Bar Styles */

.monaco-menu .monaco-action-bar.vertical {
	padding: 4px 0;
}

.monaco-menu .monaco-action-bar.vertical .action-menu-item {
	height: 2em;
}

.monaco-menu .monaco-action-bar.vertical .action-label:not(.separator),
.monaco-menu .monaco-action-bar.vertical .keybinding {
	font-size: inherit;
	padding: 0 2em;
	max-height: 100%;
}

.monaco-menu .monaco-action-bar.vertical .menu-item-check {
	font-size: inherit;
	width: 2em;
}

.monaco-menu .monaco-action-bar.vertical .action-label.separator {
	font-size: inherit;
	margin: 5px 0 !important;
	padding: 0;
	border-radius: 0;
}

.linux .monaco-menu .monaco-action-bar.vertical .action-label.separator,
:host-context(.linux) .monaco-menu .monaco-action-bar.vertical .action-label.separator {
	margin-left: 0;
	margin-right: 0;
}

.monaco-menu .monaco-action-bar.vertical .submenu-indicator {
	font-size: 60%;
	padding: 0 1.8em;
}

.linux .monaco-menu .monaco-action-bar.vertical .submenu-indicator,
:host-context(.linux) .monaco-menu .monaco-action-bar.vertical .submenu-indicator {
	height: 100%;
	mask-size: 10px 10px;
	-webkit-mask-size: 10px 10px;
}

.monaco-menu .action-item {
	cursor: default;
}`;
        if (isForShadowDom) {
            // Only define scrollbar styles when used inside shadow dom,
            // otherwise leave their styling to the global workbench styling.
            result += `
			/* Arrows */
			.monaco-scrollable-element > .scrollbar > .scra {
				cursor: pointer;
				font-size: 11px !important;
			}

			.monaco-scrollable-element > .visible {
				opacity: 1;

				/* Background rule added for IE9 - to allow clicks on dom node */
				background:rgba(0,0,0,0);

				transition: opacity 100ms linear;
			}
			.monaco-scrollable-element > .invisible {
				opacity: 0;
				pointer-events: none;
			}
			.monaco-scrollable-element > .invisible.fade {
				transition: opacity 800ms linear;
			}

			/* Scrollable Content Inset Shadow */
			.monaco-scrollable-element > .shadow {
				position: absolute;
				display: none;
			}
			.monaco-scrollable-element > .shadow.top {
				display: block;
				top: 0;
				left: 3px;
				height: 3px;
				width: 100%;
			}
			.monaco-scrollable-element > .shadow.left {
				display: block;
				top: 3px;
				left: 0;
				height: 100%;
				width: 3px;
			}
			.monaco-scrollable-element > .shadow.top-left-corner {
				display: block;
				top: 0;
				left: 0;
				height: 3px;
				width: 3px;
			}
		`;
            // Scrollbars
            const scrollbarShadowColor = style.scrollbarShadow;
            if (scrollbarShadowColor) {
                result += `
				.monaco-scrollable-element > .shadow.top {
					box-shadow: ${scrollbarShadowColor} 0 6px 6px -6px inset;
				}

				.monaco-scrollable-element > .shadow.left {
					box-shadow: ${scrollbarShadowColor} 6px 0 6px -6px inset;
				}

				.monaco-scrollable-element > .shadow.top.left {
					box-shadow: ${scrollbarShadowColor} 6px 6px 6px -6px inset;
				}
			`;
            }
            const scrollbarSliderBackgroundColor = style.scrollbarSliderBackground;
            if (scrollbarSliderBackgroundColor) {
                result += `
				.monaco-scrollable-element > .scrollbar > .slider {
					background: ${scrollbarSliderBackgroundColor};
				}
			`;
            }
            const scrollbarSliderHoverBackgroundColor = style.scrollbarSliderHoverBackground;
            if (scrollbarSliderHoverBackgroundColor) {
                result += `
				.monaco-scrollable-element > .scrollbar > .slider:hover {
					background: ${scrollbarSliderHoverBackgroundColor};
				}
			`;
            }
            const scrollbarSliderActiveBackgroundColor = style.scrollbarSliderActiveBackground;
            if (scrollbarSliderActiveBackgroundColor) {
                result += `
				.monaco-scrollable-element > .scrollbar > .slider.active {
					background: ${scrollbarSliderActiveBackgroundColor};
				}
			`;
            }
        }
        return result;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[643/*vs/base/browser/ui/toolbar/toolbar*/], __M([1/*require*/,0/*exports*/,87/*vs/base/browser/ui/actionbar/actionbar*/,359/*vs/base/browser/ui/dropdown/dropdownActionViewItem*/,41/*vs/base/common/actions*/,26/*vs/base/common/codicons*/,30/*vs/base/common/themables*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,3/*vs/nls*/,44/*vs/base/browser/ui/hover/hoverDelegateFactory*/,477/*vs/css!vs/base/browser/ui/toolbar/toolbar*/]), function (require, exports, actionbar_1, dropdownActionViewItem_1, actions_1, codicons_1, themables_1, event_1, lifecycle_1, nls, hoverDelegateFactory_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ToggleMenuAction = exports.ToolBar = void 0;
    /**
     * A widget that combines an action bar for primary actions and a dropdown for secondary actions.
     */
    class ToolBar extends lifecycle_1.Disposable {
        constructor(container, contextMenuProvider, options = { orientation: 0 /* ActionsOrientation.HORIZONTAL */ }) {
            super();
            this.submenuActionViewItems = [];
            this.hasSecondaryActions = false;
            this._onDidChangeDropdownVisibility = this._register(new event_1.EventMultiplexer());
            this.onDidChangeDropdownVisibility = this._onDidChangeDropdownVisibility.event;
            this.disposables = this._register(new lifecycle_1.DisposableStore());
            options.hoverDelegate = options.hoverDelegate ?? this._register((0, hoverDelegateFactory_1.createInstantHoverDelegate)());
            this.options = options;
            this.toggleMenuAction = this._register(new ToggleMenuAction(() => this.toggleMenuActionViewItem?.show(), options.toggleMenuTitle));
            this.element = document.createElement('div');
            this.element.className = 'monaco-toolbar';
            container.appendChild(this.element);
            this.actionBar = this._register(new actionbar_1.ActionBar(this.element, {
                orientation: options.orientation,
                ariaLabel: options.ariaLabel,
                actionRunner: options.actionRunner,
                allowContextMenu: options.allowContextMenu,
                highlightToggledItems: options.highlightToggledItems,
                hoverDelegate: options.hoverDelegate,
                actionViewItemProvider: (action, viewItemOptions) => {
                    if (action.id === ToggleMenuAction.ID) {
                        this.toggleMenuActionViewItem = new dropdownActionViewItem_1.DropdownMenuActionViewItem(action, action.menuActions, contextMenuProvider, {
                            actionViewItemProvider: this.options.actionViewItemProvider,
                            actionRunner: this.actionRunner,
                            keybindingProvider: this.options.getKeyBinding,
                            classNames: themables_1.ThemeIcon.asClassNameArray(options.moreIcon ?? codicons_1.Codicon.toolBarMore),
                            anchorAlignmentProvider: this.options.anchorAlignmentProvider,
                            menuAsChild: !!this.options.renderDropdownAsChildElement,
                            skipTelemetry: this.options.skipTelemetry,
                            isMenu: true,
                            hoverDelegate: this.options.hoverDelegate
                        });
                        this.toggleMenuActionViewItem.setActionContext(this.actionBar.context);
                        this.disposables.add(this._onDidChangeDropdownVisibility.add(this.toggleMenuActionViewItem.onDidChangeVisibility));
                        return this.toggleMenuActionViewItem;
                    }
                    if (options.actionViewItemProvider) {
                        const result = options.actionViewItemProvider(action, viewItemOptions);
                        if (result) {
                            return result;
                        }
                    }
                    if (action instanceof actions_1.SubmenuAction) {
                        const result = new dropdownActionViewItem_1.DropdownMenuActionViewItem(action, action.actions, contextMenuProvider, {
                            actionViewItemProvider: this.options.actionViewItemProvider,
                            actionRunner: this.actionRunner,
                            keybindingProvider: this.options.getKeyBinding,
                            classNames: action.class,
                            anchorAlignmentProvider: this.options.anchorAlignmentProvider,
                            menuAsChild: !!this.options.renderDropdownAsChildElement,
                            skipTelemetry: this.options.skipTelemetry,
                            hoverDelegate: this.options.hoverDelegate
                        });
                        result.setActionContext(this.actionBar.context);
                        this.submenuActionViewItems.push(result);
                        this.disposables.add(this._onDidChangeDropdownVisibility.add(result.onDidChangeVisibility));
                        return result;
                    }
                    return undefined;
                }
            }));
        }
        set actionRunner(actionRunner) {
            this.actionBar.actionRunner = actionRunner;
        }
        get actionRunner() {
            return this.actionBar.actionRunner;
        }
        getElement() {
            return this.element;
        }
        getItemAction(indexOrElement) {
            return this.actionBar.getAction(indexOrElement);
        }
        setActions(primaryActions, secondaryActions) {
            this.clear();
            const primaryActionsToSet = primaryActions ? primaryActions.slice(0) : [];
            // Inject additional action to open secondary actions if present
            this.hasSecondaryActions = !!(secondaryActions && secondaryActions.length > 0);
            if (this.hasSecondaryActions && secondaryActions) {
                this.toggleMenuAction.menuActions = secondaryActions.slice(0);
                primaryActionsToSet.push(this.toggleMenuAction);
            }
            primaryActionsToSet.forEach(action => {
                this.actionBar.push(action, { icon: this.options.icon ?? true, label: this.options.label ?? false, keybinding: this.getKeybindingLabel(action) });
            });
        }
        getKeybindingLabel(action) {
            const key = this.options.getKeyBinding?.(action);
            return key?.getLabel() ?? undefined;
        }
        clear() {
            this.submenuActionViewItems = [];
            this.disposables.clear();
            this.actionBar.clear();
        }
        dispose() {
            this.clear();
            this.disposables.dispose();
            super.dispose();
        }
    }
    exports.ToolBar = ToolBar;
    class ToggleMenuAction extends actions_1.Action {
        static { this.ID = 'toolbar.toggle.more'; }
        constructor(toggleDropdownMenu, title) {
            title = title || nls.localize(17, "More Actions...");
            super(ToggleMenuAction.ID, title, undefined, true);
            this._menuActions = [];
            this.toggleDropdownMenu = toggleDropdownMenu;
        }
        async run() {
            this.toggleDropdownMenu();
        }
        get menuActions() {
            return this._menuActions;
        }
        set menuActions(actions) {
            this._menuActions = actions;
        }
    }
    exports.ToggleMenuAction = ToggleMenuAction;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[176/*vs/base/browser/ui/tree/abstractTree*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,93/*vs/base/browser/event*/,47/*vs/base/browser/keyboardEvent*/,87/*vs/base/browser/ui/actionbar/actionbar*/,260/*vs/base/browser/ui/findinput/findInput*/,259/*vs/base/browser/ui/inputbox/inputBox*/,257/*vs/base/browser/ui/list/listView*/,115/*vs/base/browser/ui/list/listWidget*/,175/*vs/base/browser/ui/toggle/toggle*/,249/*vs/base/browser/ui/tree/indexTreeModel*/,159/*vs/base/browser/ui/tree/tree*/,41/*vs/base/common/actions*/,13/*vs/base/common/arrays*/,14/*vs/base/common/async*/,26/*vs/base/common/codicons*/,30/*vs/base/common/themables*/,45/*vs/base/common/map*/,6/*vs/base/common/event*/,82/*vs/base/common/filters*/,2/*vs/base/common/lifecycle*/,141/*vs/base/common/numbers*/,19/*vs/base/common/types*/,3/*vs/nls*/,44/*vs/base/browser/ui/hover/hoverDelegateFactory*/,21/*vs/base/common/observable*/,46/*vs/base/browser/ui/aria/aria*/,478/*vs/css!vs/base/browser/ui/tree/media/tree*/]), function (require, exports, dom_1, event_1, keyboardEvent_1, actionbar_1, findInput_1, inputBox_1, listView_1, listWidget_1, toggle_1, indexTreeModel_1, tree_1, actions_1, arrays_1, async_1, codicons_1, themables_1, map_1, event_2, filters_1, lifecycle_1, numbers_1, types_1, nls_1, hoverDelegateFactory_1, observable_1, aria_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AbstractTree = exports.TreeFindMatchType = exports.TreeFindMode = exports.FuzzyToggle = exports.ModeToggle = exports.TreeRenderer = exports.RenderIndentGuides = exports.ComposedTreeDelegate = void 0;
    class TreeElementsDragAndDropData extends listView_1.ElementsDragAndDropData {
        constructor(data) {
            super(data.elements.map(node => node.element));
            this.data = data;
        }
    }
    function asTreeDragAndDropData(data) {
        if (data instanceof listView_1.ElementsDragAndDropData) {
            return new TreeElementsDragAndDropData(data);
        }
        return data;
    }
    class TreeNodeListDragAndDrop {
        constructor(modelProvider, dnd) {
            this.modelProvider = modelProvider;
            this.dnd = dnd;
            this.autoExpandDisposable = lifecycle_1.Disposable.None;
            this.disposables = new lifecycle_1.DisposableStore();
        }
        getDragURI(node) {
            return this.dnd.getDragURI(node.element);
        }
        getDragLabel(nodes, originalEvent) {
            if (this.dnd.getDragLabel) {
                return this.dnd.getDragLabel(nodes.map(node => node.element), originalEvent);
            }
            return undefined;
        }
        onDragStart(data, originalEvent) {
            this.dnd.onDragStart?.(asTreeDragAndDropData(data), originalEvent);
        }
        onDragOver(data, targetNode, targetIndex, targetSector, originalEvent, raw = true) {
            const result = this.dnd.onDragOver(asTreeDragAndDropData(data), targetNode && targetNode.element, targetIndex, targetSector, originalEvent);
            const didChangeAutoExpandNode = this.autoExpandNode !== targetNode;
            if (didChangeAutoExpandNode) {
                this.autoExpandDisposable.dispose();
                this.autoExpandNode = targetNode;
            }
            if (typeof targetNode === 'undefined') {
                return result;
            }
            if (didChangeAutoExpandNode && typeof result !== 'boolean' && result.autoExpand) {
                this.autoExpandDisposable = (0, async_1.disposableTimeout)(() => {
                    const model = this.modelProvider();
                    const ref = model.getNodeLocation(targetNode);
                    if (model.isCollapsed(ref)) {
                        model.setCollapsed(ref, false);
                    }
                    this.autoExpandNode = undefined;
                }, 500, this.disposables);
            }
            if (typeof result === 'boolean' || !result.accept || typeof result.bubble === 'undefined' || result.feedback) {
                if (!raw) {
                    const accept = typeof result === 'boolean' ? result : result.accept;
                    const effect = typeof result === 'boolean' ? undefined : result.effect;
                    return { accept, effect, feedback: [targetIndex] };
                }
                return result;
            }
            if (result.bubble === 1 /* TreeDragOverBubble.Up */) {
                const model = this.modelProvider();
                const ref = model.getNodeLocation(targetNode);
                const parentRef = model.getParentNodeLocation(ref);
                const parentNode = model.getNode(parentRef);
                const parentIndex = parentRef && model.getListIndex(parentRef);
                return this.onDragOver(data, parentNode, parentIndex, targetSector, originalEvent, false);
            }
            const model = this.modelProvider();
            const ref = model.getNodeLocation(targetNode);
            const start = model.getListIndex(ref);
            const length = model.getListRenderCount(ref);
            return { ...result, feedback: (0, arrays_1.range)(start, start + length) };
        }
        drop(data, targetNode, targetIndex, targetSector, originalEvent) {
            this.autoExpandDisposable.dispose();
            this.autoExpandNode = undefined;
            this.dnd.drop(asTreeDragAndDropData(data), targetNode && targetNode.element, targetIndex, targetSector, originalEvent);
        }
        onDragEnd(originalEvent) {
            this.dnd.onDragEnd?.(originalEvent);
        }
        dispose() {
            this.disposables.dispose();
            this.dnd.dispose();
        }
    }
    function asListOptions(modelProvider, options) {
        return options && {
            ...options,
            identityProvider: options.identityProvider && {
                getId(el) {
                    return options.identityProvider.getId(el.element);
                }
            },
            dnd: options.dnd && new TreeNodeListDragAndDrop(modelProvider, options.dnd),
            multipleSelectionController: options.multipleSelectionController && {
                isSelectionSingleChangeEvent(e) {
                    return options.multipleSelectionController.isSelectionSingleChangeEvent({ ...e, element: e.element });
                },
                isSelectionRangeChangeEvent(e) {
                    return options.multipleSelectionController.isSelectionRangeChangeEvent({ ...e, element: e.element });
                }
            },
            accessibilityProvider: options.accessibilityProvider && {
                ...options.accessibilityProvider,
                getSetSize(node) {
                    const model = modelProvider();
                    const ref = model.getNodeLocation(node);
                    const parentRef = model.getParentNodeLocation(ref);
                    const parentNode = model.getNode(parentRef);
                    return parentNode.visibleChildrenCount;
                },
                getPosInSet(node) {
                    return node.visibleChildIndex + 1;
                },
                isChecked: options.accessibilityProvider && options.accessibilityProvider.isChecked ? (node) => {
                    return options.accessibilityProvider.isChecked(node.element);
                } : undefined,
                getRole: options.accessibilityProvider && options.accessibilityProvider.getRole ? (node) => {
                    return options.accessibilityProvider.getRole(node.element);
                } : () => 'treeitem',
                getAriaLabel(e) {
                    return options.accessibilityProvider.getAriaLabel(e.element);
                },
                getWidgetAriaLabel() {
                    return options.accessibilityProvider.getWidgetAriaLabel();
                },
                getWidgetRole: options.accessibilityProvider && options.accessibilityProvider.getWidgetRole ? () => options.accessibilityProvider.getWidgetRole() : () => 'tree',
                getAriaLevel: options.accessibilityProvider && options.accessibilityProvider.getAriaLevel ? (node) => options.accessibilityProvider.getAriaLevel(node.element) : (node) => {
                    return node.depth;
                },
                getActiveDescendantId: options.accessibilityProvider.getActiveDescendantId && (node => {
                    return options.accessibilityProvider.getActiveDescendantId(node.element);
                })
            },
            keyboardNavigationLabelProvider: options.keyboardNavigationLabelProvider && {
                ...options.keyboardNavigationLabelProvider,
                getKeyboardNavigationLabel(node) {
                    return options.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(node.element);
                }
            }
        };
    }
    class ComposedTreeDelegate {
        constructor(delegate) {
            this.delegate = delegate;
        }
        getHeight(element) {
            return this.delegate.getHeight(element.element);
        }
        getTemplateId(element) {
            return this.delegate.getTemplateId(element.element);
        }
        hasDynamicHeight(element) {
            return !!this.delegate.hasDynamicHeight && this.delegate.hasDynamicHeight(element.element);
        }
        setDynamicHeight(element, height) {
            this.delegate.setDynamicHeight?.(element.element, height);
        }
    }
    exports.ComposedTreeDelegate = ComposedTreeDelegate;
    var RenderIndentGuides;
    (function (RenderIndentGuides) {
        RenderIndentGuides["None"] = "none";
        RenderIndentGuides["OnHover"] = "onHover";
        RenderIndentGuides["Always"] = "always";
    })(RenderIndentGuides || (exports.RenderIndentGuides = RenderIndentGuides = {}));
    class EventCollection {
        get elements() {
            return this._elements;
        }
        constructor(onDidChange, _elements = []) {
            this._elements = _elements;
            this.disposables = new lifecycle_1.DisposableStore();
            this.onDidChange = event_2.Event.forEach(onDidChange, elements => this._elements = elements, this.disposables);
        }
        dispose() {
            this.disposables.dispose();
        }
    }
    class TreeRenderer {
        static { this.DefaultIndent = 8; }
        constructor(renderer, modelProvider, onDidChangeCollapseState, activeNodes, renderedIndentGuides, options = {}) {
            this.renderer = renderer;
            this.modelProvider = modelProvider;
            this.activeNodes = activeNodes;
            this.renderedIndentGuides = renderedIndentGuides;
            this.renderedElements = new Map();
            this.renderedNodes = new Map();
            this.indent = TreeRenderer.DefaultIndent;
            this.hideTwistiesOfChildlessElements = false;
            this.shouldRenderIndentGuides = false;
            this.activeIndentNodes = new Set();
            this.indentGuidesDisposable = lifecycle_1.Disposable.None;
            this.disposables = new lifecycle_1.DisposableStore();
            this.templateId = renderer.templateId;
            this.updateOptions(options);
            event_2.Event.map(onDidChangeCollapseState, e => e.node)(this.onDidChangeNodeTwistieState, this, this.disposables);
            renderer.onDidChangeTwistieState?.(this.onDidChangeTwistieState, this, this.disposables);
        }
        updateOptions(options = {}) {
            if (typeof options.indent !== 'undefined') {
                const indent = (0, numbers_1.clamp)(options.indent, 0, 40);
                if (indent !== this.indent) {
                    this.indent = indent;
                    for (const [node, templateData] of this.renderedNodes) {
                        this.renderTreeElement(node, templateData);
                    }
                }
            }
            if (typeof options.renderIndentGuides !== 'undefined') {
                const shouldRenderIndentGuides = options.renderIndentGuides !== RenderIndentGuides.None;
                if (shouldRenderIndentGuides !== this.shouldRenderIndentGuides) {
                    this.shouldRenderIndentGuides = shouldRenderIndentGuides;
                    for (const [node, templateData] of this.renderedNodes) {
                        this._renderIndentGuides(node, templateData);
                    }
                    this.indentGuidesDisposable.dispose();
                    if (shouldRenderIndentGuides) {
                        const disposables = new lifecycle_1.DisposableStore();
                        this.activeNodes.onDidChange(this._onDidChangeActiveNodes, this, disposables);
                        this.indentGuidesDisposable = disposables;
                        this._onDidChangeActiveNodes(this.activeNodes.elements);
                    }
                }
            }
            if (typeof options.hideTwistiesOfChildlessElements !== 'undefined') {
                this.hideTwistiesOfChildlessElements = options.hideTwistiesOfChildlessElements;
            }
        }
        renderTemplate(container) {
            const el = (0, dom_1.append)(container, (0, dom_1.$)('.monaco-tl-row'));
            const indent = (0, dom_1.append)(el, (0, dom_1.$)('.monaco-tl-indent'));
            const twistie = (0, dom_1.append)(el, (0, dom_1.$)('.monaco-tl-twistie'));
            const contents = (0, dom_1.append)(el, (0, dom_1.$)('.monaco-tl-contents'));
            const templateData = this.renderer.renderTemplate(contents);
            return { container, indent, twistie, indentGuidesDisposable: lifecycle_1.Disposable.None, templateData };
        }
        renderElement(node, index, templateData, height) {
            this.renderedNodes.set(node, templateData);
            this.renderedElements.set(node.element, node);
            this.renderTreeElement(node, templateData);
            this.renderer.renderElement(node, index, templateData.templateData, height);
        }
        disposeElement(node, index, templateData, height) {
            templateData.indentGuidesDisposable.dispose();
            this.renderer.disposeElement?.(node, index, templateData.templateData, height);
            if (typeof height === 'number') {
                this.renderedNodes.delete(node);
                this.renderedElements.delete(node.element);
            }
        }
        disposeTemplate(templateData) {
            this.renderer.disposeTemplate(templateData.templateData);
        }
        onDidChangeTwistieState(element) {
            const node = this.renderedElements.get(element);
            if (!node) {
                return;
            }
            this.onDidChangeNodeTwistieState(node);
        }
        onDidChangeNodeTwistieState(node) {
            const templateData = this.renderedNodes.get(node);
            if (!templateData) {
                return;
            }
            this._onDidChangeActiveNodes(this.activeNodes.elements);
            this.renderTreeElement(node, templateData);
        }
        renderTreeElement(node, templateData) {
            const indent = TreeRenderer.DefaultIndent + (node.depth - 1) * this.indent;
            templateData.twistie.style.paddingLeft = `${indent}px`;
            templateData.indent.style.width = `${indent + this.indent - 16}px`;
            if (node.collapsible) {
                templateData.container.setAttribute('aria-expanded', String(!node.collapsed));
            }
            else {
                templateData.container.removeAttribute('aria-expanded');
            }
            templateData.twistie.classList.remove(...themables_1.ThemeIcon.asClassNameArray(codicons_1.Codicon.treeItemExpanded));
            let twistieRendered = false;
            if (this.renderer.renderTwistie) {
                twistieRendered = this.renderer.renderTwistie(node.element, templateData.twistie);
            }
            if (node.collapsible && (!this.hideTwistiesOfChildlessElements || node.visibleChildrenCount > 0)) {
                if (!twistieRendered) {
                    templateData.twistie.classList.add(...themables_1.ThemeIcon.asClassNameArray(codicons_1.Codicon.treeItemExpanded));
                }
                templateData.twistie.classList.add('collapsible');
                templateData.twistie.classList.toggle('collapsed', node.collapsed);
            }
            else {
                templateData.twistie.classList.remove('collapsible', 'collapsed');
            }
            this._renderIndentGuides(node, templateData);
        }
        _renderIndentGuides(node, templateData) {
            (0, dom_1.clearNode)(templateData.indent);
            templateData.indentGuidesDisposable.dispose();
            if (!this.shouldRenderIndentGuides) {
                return;
            }
            const disposableStore = new lifecycle_1.DisposableStore();
            const model = this.modelProvider();
            while (true) {
                const ref = model.getNodeLocation(node);
                const parentRef = model.getParentNodeLocation(ref);
                if (!parentRef) {
                    break;
                }
                const parent = model.getNode(parentRef);
                const guide = (0, dom_1.$)('.indent-guide', { style: `width: ${this.indent}px` });
                if (this.activeIndentNodes.has(parent)) {
                    guide.classList.add('active');
                }
                if (templateData.indent.childElementCount === 0) {
                    templateData.indent.appendChild(guide);
                }
                else {
                    templateData.indent.insertBefore(guide, templateData.indent.firstElementChild);
                }
                this.renderedIndentGuides.add(parent, guide);
                disposableStore.add((0, lifecycle_1.toDisposable)(() => this.renderedIndentGuides.delete(parent, guide)));
                node = parent;
            }
            templateData.indentGuidesDisposable = disposableStore;
        }
        _onDidChangeActiveNodes(nodes) {
            if (!this.shouldRenderIndentGuides) {
                return;
            }
            const set = new Set();
            const model = this.modelProvider();
            nodes.forEach(node => {
                const ref = model.getNodeLocation(node);
                try {
                    const parentRef = model.getParentNodeLocation(ref);
                    if (node.collapsible && node.children.length > 0 && !node.collapsed) {
                        set.add(node);
                    }
                    else if (parentRef) {
                        set.add(model.getNode(parentRef));
                    }
                }
                catch {
                    // noop
                }
            });
            this.activeIndentNodes.forEach(node => {
                if (!set.has(node)) {
                    this.renderedIndentGuides.forEach(node, line => line.classList.remove('active'));
                }
            });
            set.forEach(node => {
                if (!this.activeIndentNodes.has(node)) {
                    this.renderedIndentGuides.forEach(node, line => line.classList.add('active'));
                }
            });
            this.activeIndentNodes = set;
        }
        dispose() {
            this.renderedNodes.clear();
            this.renderedElements.clear();
            this.indentGuidesDisposable.dispose();
            (0, lifecycle_1.dispose)(this.disposables);
        }
    }
    exports.TreeRenderer = TreeRenderer;
    class FindFilter {
        get totalCount() { return this._totalCount; }
        get matchCount() { return this._matchCount; }
        constructor(tree, keyboardNavigationLabelProvider, _filter) {
            this.tree = tree;
            this.keyboardNavigationLabelProvider = keyboardNavigationLabelProvider;
            this._filter = _filter;
            this._totalCount = 0;
            this._matchCount = 0;
            this._pattern = '';
            this._lowercasePattern = '';
            this.disposables = new lifecycle_1.DisposableStore();
            tree.onWillRefilter(this.reset, this, this.disposables);
        }
        filter(element, parentVisibility) {
            let visibility = 1 /* TreeVisibility.Visible */;
            if (this._filter) {
                const result = this._filter.filter(element, parentVisibility);
                if (typeof result === 'boolean') {
                    visibility = result ? 1 /* TreeVisibility.Visible */ : 0 /* TreeVisibility.Hidden */;
                }
                else if ((0, indexTreeModel_1.isFilterResult)(result)) {
                    visibility = (0, indexTreeModel_1.getVisibleState)(result.visibility);
                }
                else {
                    visibility = result;
                }
                if (visibility === 0 /* TreeVisibility.Hidden */) {
                    return false;
                }
            }
            this._totalCount++;
            if (!this._pattern) {
                this._matchCount++;
                return { data: filters_1.FuzzyScore.Default, visibility };
            }
            const label = this.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(element);
            const labels = Array.isArray(label) ? label : [label];
            for (const l of labels) {
                const labelStr = l && l.toString();
                if (typeof labelStr === 'undefined') {
                    return { data: filters_1.FuzzyScore.Default, visibility };
                }
                let score;
                if (this.tree.findMatchType === TreeFindMatchType.Contiguous) {
                    const index = labelStr.toLowerCase().indexOf(this._lowercasePattern);
                    if (index > -1) {
                        score = [Number.MAX_SAFE_INTEGER, 0];
                        for (let i = this._lowercasePattern.length; i > 0; i--) {
                            score.push(index + i - 1);
                        }
                    }
                }
                else {
                    score = (0, filters_1.fuzzyScore)(this._pattern, this._lowercasePattern, 0, labelStr, labelStr.toLowerCase(), 0, { firstMatchCanBeWeak: true, boostFullMatch: true });
                }
                if (score) {
                    this._matchCount++;
                    return labels.length === 1 ?
                        { data: score, visibility } :
                        { data: { label: labelStr, score: score }, visibility };
                }
            }
            if (this.tree.findMode === TreeFindMode.Filter) {
                if (typeof this.tree.options.defaultFindVisibility === 'number') {
                    return this.tree.options.defaultFindVisibility;
                }
                else if (this.tree.options.defaultFindVisibility) {
                    return this.tree.options.defaultFindVisibility(element);
                }
                else {
                    return 2 /* TreeVisibility.Recurse */;
                }
            }
            else {
                return { data: filters_1.FuzzyScore.Default, visibility };
            }
        }
        reset() {
            this._totalCount = 0;
            this._matchCount = 0;
        }
        dispose() {
            (0, lifecycle_1.dispose)(this.disposables);
        }
    }
    class ModeToggle extends toggle_1.Toggle {
        constructor(opts) {
            super({
                icon: codicons_1.Codicon.listFilter,
                title: (0, nls_1.localize)(18, "Filter"),
                isChecked: opts.isChecked ?? false,
                hoverDelegate: opts.hoverDelegate ?? (0, hoverDelegateFactory_1.getDefaultHoverDelegate)('element'),
                inputActiveOptionBorder: opts.inputActiveOptionBorder,
                inputActiveOptionForeground: opts.inputActiveOptionForeground,
                inputActiveOptionBackground: opts.inputActiveOptionBackground
            });
        }
    }
    exports.ModeToggle = ModeToggle;
    class FuzzyToggle extends toggle_1.Toggle {
        constructor(opts) {
            super({
                icon: codicons_1.Codicon.searchFuzzy,
                title: (0, nls_1.localize)(19, "Fuzzy Match"),
                isChecked: opts.isChecked ?? false,
                hoverDelegate: opts.hoverDelegate ?? (0, hoverDelegateFactory_1.getDefaultHoverDelegate)('element'),
                inputActiveOptionBorder: opts.inputActiveOptionBorder,
                inputActiveOptionForeground: opts.inputActiveOptionForeground,
                inputActiveOptionBackground: opts.inputActiveOptionBackground
            });
        }
    }
    exports.FuzzyToggle = FuzzyToggle;
    const unthemedFindWidgetStyles = {
        inputBoxStyles: inputBox_1.unthemedInboxStyles,
        toggleStyles: toggle_1.unthemedToggleStyles,
        listFilterWidgetBackground: undefined,
        listFilterWidgetNoMatchesOutline: undefined,
        listFilterWidgetOutline: undefined,
        listFilterWidgetShadow: undefined
    };
    var TreeFindMode;
    (function (TreeFindMode) {
        TreeFindMode[TreeFindMode["Highlight"] = 0] = "Highlight";
        TreeFindMode[TreeFindMode["Filter"] = 1] = "Filter";
    })(TreeFindMode || (exports.TreeFindMode = TreeFindMode = {}));
    var TreeFindMatchType;
    (function (TreeFindMatchType) {
        TreeFindMatchType[TreeFindMatchType["Fuzzy"] = 0] = "Fuzzy";
        TreeFindMatchType[TreeFindMatchType["Contiguous"] = 1] = "Contiguous";
    })(TreeFindMatchType || (exports.TreeFindMatchType = TreeFindMatchType = {}));
    class FindWidget extends lifecycle_1.Disposable {
        set mode(mode) {
            this.modeToggle.checked = mode === TreeFindMode.Filter;
            this.findInput.inputBox.setPlaceHolder(mode === TreeFindMode.Filter ? (0, nls_1.localize)(20, "Type to filter") : (0, nls_1.localize)(21, "Type to search"));
        }
        set matchType(matchType) {
            this.matchTypeToggle.checked = matchType === TreeFindMatchType.Fuzzy;
        }
        constructor(container, tree, contextViewProvider, mode, matchType, options) {
            super();
            this.tree = tree;
            this.elements = (0, dom_1.h)('.monaco-tree-type-filter', [
                (0, dom_1.h)('.monaco-tree-type-filter-grab.codicon.codicon-debug-gripper@grab', { tabIndex: 0 }),
                (0, dom_1.h)('.monaco-tree-type-filter-input@findInput'),
                (0, dom_1.h)('.monaco-tree-type-filter-actionbar@actionbar'),
            ]);
            this.width = 0;
            this.right = 0;
            this.top = 0;
            this._onDidDisable = new event_2.Emitter();
            container.appendChild(this.elements.root);
            this._register((0, lifecycle_1.toDisposable)(() => this.elements.root.remove()));
            const styles = options?.styles ?? unthemedFindWidgetStyles;
            if (styles.listFilterWidgetBackground) {
                this.elements.root.style.backgroundColor = styles.listFilterWidgetBackground;
            }
            if (styles.listFilterWidgetShadow) {
                this.elements.root.style.boxShadow = `0 0 8px 2px ${styles.listFilterWidgetShadow}`;
            }
            const toggleHoverDelegate = this._register((0, hoverDelegateFactory_1.createInstantHoverDelegate)());
            this.modeToggle = this._register(new ModeToggle({ ...styles.toggleStyles, isChecked: mode === TreeFindMode.Filter, hoverDelegate: toggleHoverDelegate }));
            this.matchTypeToggle = this._register(new FuzzyToggle({ ...styles.toggleStyles, isChecked: matchType === TreeFindMatchType.Fuzzy, hoverDelegate: toggleHoverDelegate }));
            this.onDidChangeMode = event_2.Event.map(this.modeToggle.onChange, () => this.modeToggle.checked ? TreeFindMode.Filter : TreeFindMode.Highlight, this._store);
            this.onDidChangeMatchType = event_2.Event.map(this.matchTypeToggle.onChange, () => this.matchTypeToggle.checked ? TreeFindMatchType.Fuzzy : TreeFindMatchType.Contiguous, this._store);
            this.findInput = this._register(new findInput_1.FindInput(this.elements.findInput, contextViewProvider, {
                label: (0, nls_1.localize)(22, "Type to search"),
                additionalToggles: [this.modeToggle, this.matchTypeToggle],
                showCommonFindToggles: false,
                inputBoxStyles: styles.inputBoxStyles,
                toggleStyles: styles.toggleStyles,
                history: options?.history
            }));
            this.actionbar = this._register(new actionbar_1.ActionBar(this.elements.actionbar));
            this.mode = mode;
            const emitter = this._register(new event_1.DomEmitter(this.findInput.inputBox.inputElement, 'keydown'));
            const onKeyDown = event_2.Event.chain(emitter.event, $ => $.map(e => new keyboardEvent_1.StandardKeyboardEvent(e)));
            this._register(onKeyDown((e) => {
                // Using equals() so we reserve modified keys for future use
                if (e.equals(3 /* KeyCode.Enter */)) {
                    // This is the only keyboard way to return to the tree from a history item that isn't the last one
                    e.preventDefault();
                    e.stopPropagation();
                    this.findInput.inputBox.addToHistory();
                    this.tree.domFocus();
                    return;
                }
                if (e.equals(18 /* KeyCode.DownArrow */)) {
                    e.preventDefault();
                    e.stopPropagation();
                    if (this.findInput.inputBox.isAtLastInHistory() || this.findInput.inputBox.isNowhereInHistory()) {
                        // Retain original pre-history DownArrow behavior
                        this.findInput.inputBox.addToHistory();
                        this.tree.domFocus();
                    }
                    else {
                        // Downward through history
                        this.findInput.inputBox.showNextValue();
                    }
                    return;
                }
                if (e.equals(16 /* KeyCode.UpArrow */)) {
                    e.preventDefault();
                    e.stopPropagation();
                    // Upward through history
                    this.findInput.inputBox.showPreviousValue();
                    return;
                }
            }));
            const closeAction = this._register(new actions_1.Action('close', (0, nls_1.localize)(23, "Close"), 'codicon codicon-close', true, () => this.dispose()));
            this.actionbar.push(closeAction, { icon: true, label: false });
            const onGrabMouseDown = this._register(new event_1.DomEmitter(this.elements.grab, 'mousedown'));
            this._register(onGrabMouseDown.event(e => {
                const disposables = new lifecycle_1.DisposableStore();
                const onWindowMouseMove = disposables.add(new event_1.DomEmitter((0, dom_1.getWindow)(e), 'mousemove'));
                const onWindowMouseUp = disposables.add(new event_1.DomEmitter((0, dom_1.getWindow)(e), 'mouseup'));
                const startRight = this.right;
                const startX = e.pageX;
                const startTop = this.top;
                const startY = e.pageY;
                this.elements.grab.classList.add('grabbing');
                const transition = this.elements.root.style.transition;
                this.elements.root.style.transition = 'unset';
                const update = (e) => {
                    const deltaX = e.pageX - startX;
                    this.right = startRight - deltaX;
                    const deltaY = e.pageY - startY;
                    this.top = startTop + deltaY;
                    this.layout();
                };
                disposables.add(onWindowMouseMove.event(update));
                disposables.add(onWindowMouseUp.event(e => {
                    update(e);
                    this.elements.grab.classList.remove('grabbing');
                    this.elements.root.style.transition = transition;
                    disposables.dispose();
                }));
            }));
            const onGrabKeyDown = event_2.Event.chain(this._register(new event_1.DomEmitter(this.elements.grab, 'keydown')).event, $ => $.map(e => new keyboardEvent_1.StandardKeyboardEvent(e)));
            this._register(onGrabKeyDown((e) => {
                let right;
                let top;
                if (e.keyCode === 15 /* KeyCode.LeftArrow */) {
                    right = Number.POSITIVE_INFINITY;
                }
                else if (e.keyCode === 17 /* KeyCode.RightArrow */) {
                    right = 0;
                }
                else if (e.keyCode === 10 /* KeyCode.Space */) {
                    right = this.right === 0 ? Number.POSITIVE_INFINITY : 0;
                }
                if (e.keyCode === 16 /* KeyCode.UpArrow */) {
                    top = 0;
                }
                else if (e.keyCode === 18 /* KeyCode.DownArrow */) {
                    top = Number.POSITIVE_INFINITY;
                }
                if (right !== undefined) {
                    e.preventDefault();
                    e.stopPropagation();
                    this.right = right;
                    this.layout();
                }
                if (top !== undefined) {
                    e.preventDefault();
                    e.stopPropagation();
                    this.top = top;
                    const transition = this.elements.root.style.transition;
                    this.elements.root.style.transition = 'unset';
                    this.layout();
                    setTimeout(() => {
                        this.elements.root.style.transition = transition;
                    }, 0);
                }
            }));
            this.onDidChangeValue = this.findInput.onDidChange;
        }
        layout(width = this.width) {
            this.width = width;
            this.right = (0, numbers_1.clamp)(this.right, 0, Math.max(0, width - 212));
            this.elements.root.style.right = `${this.right}px`;
            this.top = (0, numbers_1.clamp)(this.top, 0, 24);
            this.elements.root.style.top = `${this.top}px`;
        }
        showMessage(message) {
            this.findInput.showMessage(message);
        }
        clearMessage() {
            this.findInput.clearMessage();
        }
        async dispose() {
            this._onDidDisable.fire();
            this.elements.root.classList.add('disabled');
            await (0, async_1.timeout)(300);
            super.dispose();
        }
    }
    class FindController {
        get pattern() { return this._pattern; }
        get mode() { return this._mode; }
        set mode(mode) {
            if (mode === this._mode) {
                return;
            }
            this._mode = mode;
            if (this.widget) {
                this.widget.mode = this._mode;
            }
            this.tree.refilter();
            this.render();
            this._onDidChangeMode.fire(mode);
        }
        get matchType() { return this._matchType; }
        set matchType(matchType) {
            if (matchType === this._matchType) {
                return;
            }
            this._matchType = matchType;
            if (this.widget) {
                this.widget.matchType = this._matchType;
            }
            this.tree.refilter();
            this.render();
            this._onDidChangeMatchType.fire(matchType);
        }
        constructor(tree, model, view, filter, contextViewProvider, options = {}) {
            this.tree = tree;
            this.view = view;
            this.filter = filter;
            this.contextViewProvider = contextViewProvider;
            this.options = options;
            this._pattern = '';
            this.width = 0;
            this._onDidChangeMode = new event_2.Emitter();
            this.onDidChangeMode = this._onDidChangeMode.event;
            this._onDidChangeMatchType = new event_2.Emitter();
            this.onDidChangeMatchType = this._onDidChangeMatchType.event;
            this._onDidChangePattern = new event_2.Emitter();
            this._onDidChangeOpenState = new event_2.Emitter();
            this.onDidChangeOpenState = this._onDidChangeOpenState.event;
            this.enabledDisposables = new lifecycle_1.DisposableStore();
            this.disposables = new lifecycle_1.DisposableStore();
            this._mode = tree.options.defaultFindMode ?? TreeFindMode.Highlight;
            this._matchType = tree.options.defaultFindMatchType ?? TreeFindMatchType.Fuzzy;
            model.onDidSplice(this.onDidSpliceModel, this, this.disposables);
        }
        updateOptions(optionsUpdate = {}) {
            if (optionsUpdate.defaultFindMode !== undefined) {
                this.mode = optionsUpdate.defaultFindMode;
            }
            if (optionsUpdate.defaultFindMatchType !== undefined) {
                this.matchType = optionsUpdate.defaultFindMatchType;
            }
        }
        onDidSpliceModel() {
            if (!this.widget || this.pattern.length === 0) {
                return;
            }
            this.tree.refilter();
            this.render();
        }
        render() {
            const noMatches = this.filter.totalCount > 0 && this.filter.matchCount === 0;
            if (this.pattern && noMatches) {
                (0, aria_1.alert)((0, nls_1.localize)(24, "No results"));
                if (this.tree.options.showNotFoundMessage ?? true) {
                    this.widget?.showMessage({ type: 2 /* MessageType.WARNING */, content: (0, nls_1.localize)(25, "No elements found.") });
                }
                else {
                    this.widget?.showMessage({ type: 2 /* MessageType.WARNING */ });
                }
            }
            else {
                this.widget?.clearMessage();
                if (this.pattern) {
                    (0, aria_1.alert)((0, nls_1.localize)(26, "{0} results", this.filter.matchCount));
                }
            }
        }
        shouldAllowFocus(node) {
            if (!this.widget || !this.pattern) {
                return true;
            }
            if (this.filter.totalCount > 0 && this.filter.matchCount <= 1) {
                return true;
            }
            return !filters_1.FuzzyScore.isDefault(node.filterData);
        }
        layout(width) {
            this.width = width;
            this.widget?.layout(width);
        }
        dispose() {
            this._history = undefined;
            this._onDidChangePattern.dispose();
            this.enabledDisposables.dispose();
            this.disposables.dispose();
        }
    }
    function stickyScrollNodeStateEquals(node1, node2) {
        return node1.position === node2.position && stickyScrollNodeEquals(node1, node2);
    }
    function stickyScrollNodeEquals(node1, node2) {
        return node1.node.element === node2.node.element &&
            node1.startIndex === node2.startIndex &&
            node1.height === node2.height &&
            node1.endIndex === node2.endIndex;
    }
    class StickyScrollState {
        constructor(stickyNodes = []) {
            this.stickyNodes = stickyNodes;
        }
        get count() { return this.stickyNodes.length; }
        equal(state) {
            return (0, arrays_1.equals)(this.stickyNodes, state.stickyNodes, stickyScrollNodeStateEquals);
        }
        lastNodePartiallyVisible() {
            if (this.count === 0) {
                return false;
            }
            const lastStickyNode = this.stickyNodes[this.count - 1];
            if (this.count === 1) {
                return lastStickyNode.position !== 0;
            }
            const secondLastStickyNode = this.stickyNodes[this.count - 2];
            return secondLastStickyNode.position + secondLastStickyNode.height !== lastStickyNode.position;
        }
        animationStateChanged(previousState) {
            if (!(0, arrays_1.equals)(this.stickyNodes, previousState.stickyNodes, stickyScrollNodeEquals)) {
                return false;
            }
            if (this.count === 0) {
                return false;
            }
            const lastStickyNode = this.stickyNodes[this.count - 1];
            const previousLastStickyNode = previousState.stickyNodes[previousState.count - 1];
            return lastStickyNode.position !== previousLastStickyNode.position;
        }
    }
    class DefaultStickyScrollDelegate {
        constrainStickyScrollNodes(stickyNodes, stickyScrollMaxItemCount, maxWidgetHeight) {
            for (let i = 0; i < stickyNodes.length; i++) {
                const stickyNode = stickyNodes[i];
                const stickyNodeBottom = stickyNode.position + stickyNode.height;
                if (stickyNodeBottom > maxWidgetHeight || i >= stickyScrollMaxItemCount) {
                    return stickyNodes.slice(0, i);
                }
            }
            return stickyNodes;
        }
    }
    class StickyScrollController extends lifecycle_1.Disposable {
        constructor(tree, model, view, renderers, treeDelegate, options = {}) {
            super();
            this.tree = tree;
            this.model = model;
            this.view = view;
            this.treeDelegate = treeDelegate;
            this.maxWidgetViewRatio = 0.4;
            const stickyScrollOptions = this.validateStickySettings(options);
            this.stickyScrollMaxItemCount = stickyScrollOptions.stickyScrollMaxItemCount;
            this.stickyScrollDelegate = options.stickyScrollDelegate ?? new DefaultStickyScrollDelegate();
            this._widget = this._register(new StickyScrollWidget(view.getScrollableElement(), view, tree, renderers, treeDelegate, options.accessibilityProvider));
            this.onDidChangeHasFocus = this._widget.onDidChangeHasFocus;
            this.onContextMenu = this._widget.onContextMenu;
            this._register(view.onDidScroll(() => this.update()));
            this._register(view.onDidChangeContentHeight(() => this.update()));
            this._register(tree.onDidChangeCollapseState(() => this.update()));
            this.update();
        }
        get height() {
            return this._widget.height;
        }
        getNodeAtHeight(height) {
            let index;
            if (height === 0) {
                index = this.view.firstVisibleIndex;
            }
            else {
                index = this.view.indexAt(height + this.view.scrollTop);
            }
            if (index < 0 || index >= this.view.length) {
                return undefined;
            }
            return this.view.element(index);
        }
        update() {
            const firstVisibleNode = this.getNodeAtHeight(0);
            // Don't render anything if there are no elements
            if (!firstVisibleNode || this.tree.scrollTop === 0) {
                this._widget.setState(undefined);
                return;
            }
            const stickyState = this.findStickyState(firstVisibleNode);
            this._widget.setState(stickyState);
        }
        findStickyState(firstVisibleNode) {
            const stickyNodes = [];
            let firstVisibleNodeUnderWidget = firstVisibleNode;
            let stickyNodesHeight = 0;
            let nextStickyNode = this.getNextStickyNode(firstVisibleNodeUnderWidget, undefined, stickyNodesHeight);
            while (nextStickyNode) {
                stickyNodes.push(nextStickyNode);
                stickyNodesHeight += nextStickyNode.height;
                if (stickyNodes.length <= this.stickyScrollMaxItemCount) {
                    firstVisibleNodeUnderWidget = this.getNextVisibleNode(nextStickyNode);
                    if (!firstVisibleNodeUnderWidget) {
                        break;
                    }
                }
                nextStickyNode = this.getNextStickyNode(firstVisibleNodeUnderWidget, nextStickyNode.node, stickyNodesHeight);
            }
            const contrainedStickyNodes = this.constrainStickyNodes(stickyNodes);
            return contrainedStickyNodes.length ? new StickyScrollState(contrainedStickyNodes) : undefined;
        }
        getNextVisibleNode(previousStickyNode) {
            return this.getNodeAtHeight(previousStickyNode.position + previousStickyNode.height);
        }
        getNextStickyNode(firstVisibleNodeUnderWidget, previousStickyNode, stickyNodesHeight) {
            const nextStickyNode = this.getAncestorUnderPrevious(firstVisibleNodeUnderWidget, previousStickyNode);
            if (!nextStickyNode) {
                return undefined;
            }
            if (nextStickyNode === firstVisibleNodeUnderWidget) {
                if (!this.nodeIsUncollapsedParent(firstVisibleNodeUnderWidget)) {
                    return undefined;
                }
                if (this.nodeTopAlignsWithStickyNodesBottom(firstVisibleNodeUnderWidget, stickyNodesHeight)) {
                    return undefined;
                }
            }
            return this.createStickyScrollNode(nextStickyNode, stickyNodesHeight);
        }
        nodeTopAlignsWithStickyNodesBottom(node, stickyNodesHeight) {
            const nodeIndex = this.getNodeIndex(node);
            const elementTop = this.view.getElementTop(nodeIndex);
            const stickyPosition = stickyNodesHeight;
            return this.view.scrollTop === elementTop - stickyPosition;
        }
        createStickyScrollNode(node, currentStickyNodesHeight) {
            const height = this.treeDelegate.getHeight(node);
            const { startIndex, endIndex } = this.getNodeRange(node);
            const position = this.calculateStickyNodePosition(endIndex, currentStickyNodesHeight, height);
            return { node, position, height, startIndex, endIndex };
        }
        getAncestorUnderPrevious(node, previousAncestor = undefined) {
            let currentAncestor = node;
            let parentOfcurrentAncestor = this.getParentNode(currentAncestor);
            while (parentOfcurrentAncestor) {
                if (parentOfcurrentAncestor === previousAncestor) {
                    return currentAncestor;
                }
                currentAncestor = parentOfcurrentAncestor;
                parentOfcurrentAncestor = this.getParentNode(currentAncestor);
            }
            if (previousAncestor === undefined) {
                return currentAncestor;
            }
            return undefined;
        }
        calculateStickyNodePosition(lastDescendantIndex, stickyRowPositionTop, stickyNodeHeight) {
            let lastChildRelativeTop = this.view.getRelativeTop(lastDescendantIndex);
            // If the last descendant is only partially visible at the top of the view, getRelativeTop() returns null
            // In that case, utilize the next node's relative top to calculate the sticky node's position
            if (lastChildRelativeTop === null && this.view.firstVisibleIndex === lastDescendantIndex && lastDescendantIndex + 1 < this.view.length) {
                const nodeHeight = this.treeDelegate.getHeight(this.view.element(lastDescendantIndex));
                const nextNodeRelativeTop = this.view.getRelativeTop(lastDescendantIndex + 1);
                lastChildRelativeTop = nextNodeRelativeTop ? nextNodeRelativeTop - nodeHeight / this.view.renderHeight : null;
            }
            if (lastChildRelativeTop === null) {
                return stickyRowPositionTop;
            }
            const lastChildNode = this.view.element(lastDescendantIndex);
            const lastChildHeight = this.treeDelegate.getHeight(lastChildNode);
            const topOfLastChild = lastChildRelativeTop * this.view.renderHeight;
            const bottomOfLastChild = topOfLastChild + lastChildHeight;
            if (stickyRowPositionTop + stickyNodeHeight > bottomOfLastChild && stickyRowPositionTop <= bottomOfLastChild) {
                return bottomOfLastChild - stickyNodeHeight;
            }
            return stickyRowPositionTop;
        }
        constrainStickyNodes(stickyNodes) {
            if (stickyNodes.length === 0) {
                return [];
            }
            // Check if sticky nodes need to be constrained
            const maximumStickyWidgetHeight = this.view.renderHeight * this.maxWidgetViewRatio;
            const lastStickyNode = stickyNodes[stickyNodes.length - 1];
            if (stickyNodes.length <= this.stickyScrollMaxItemCount && lastStickyNode.position + lastStickyNode.height <= maximumStickyWidgetHeight) {
                return stickyNodes;
            }
            // constrain sticky nodes
            const constrainedStickyNodes = this.stickyScrollDelegate.constrainStickyScrollNodes(stickyNodes, this.stickyScrollMaxItemCount, maximumStickyWidgetHeight);
            if (!constrainedStickyNodes.length) {
                return [];
            }
            // Validate constraints
            const lastConstrainedStickyNode = constrainedStickyNodes[constrainedStickyNodes.length - 1];
            if (constrainedStickyNodes.length > this.stickyScrollMaxItemCount || lastConstrainedStickyNode.position + lastConstrainedStickyNode.height > maximumStickyWidgetHeight) {
                throw new Error('stickyScrollDelegate violates constraints');
            }
            return constrainedStickyNodes;
        }
        getParentNode(node) {
            const nodeLocation = this.model.getNodeLocation(node);
            const parentLocation = this.model.getParentNodeLocation(nodeLocation);
            return parentLocation ? this.model.getNode(parentLocation) : undefined;
        }
        nodeIsUncollapsedParent(node) {
            const nodeLocation = this.model.getNodeLocation(node);
            return this.model.getListRenderCount(nodeLocation) > 1;
        }
        getNodeIndex(node) {
            const nodeLocation = this.model.getNodeLocation(node);
            const nodeIndex = this.model.getListIndex(nodeLocation);
            return nodeIndex;
        }
        getNodeRange(node) {
            const nodeLocation = this.model.getNodeLocation(node);
            const startIndex = this.model.getListIndex(nodeLocation);
            if (startIndex < 0) {
                throw new Error('Node not found in tree');
            }
            const renderCount = this.model.getListRenderCount(nodeLocation);
            const endIndex = startIndex + renderCount - 1;
            return { startIndex, endIndex };
        }
        nodePositionTopBelowWidget(node) {
            const ancestors = [];
            let currentAncestor = this.getParentNode(node);
            while (currentAncestor) {
                ancestors.push(currentAncestor);
                currentAncestor = this.getParentNode(currentAncestor);
            }
            let widgetHeight = 0;
            for (let i = 0; i < ancestors.length && i < this.stickyScrollMaxItemCount; i++) {
                widgetHeight += this.treeDelegate.getHeight(ancestors[i]);
            }
            return widgetHeight;
        }
        domFocus() {
            this._widget.domFocus();
        }
        // Whether sticky scroll was the last focused part in the tree or not
        focusedLast() {
            return this._widget.focusedLast();
        }
        updateOptions(optionsUpdate = {}) {
            if (!optionsUpdate.stickyScrollMaxItemCount) {
                return;
            }
            const validatedOptions = this.validateStickySettings(optionsUpdate);
            if (this.stickyScrollMaxItemCount !== validatedOptions.stickyScrollMaxItemCount) {
                this.stickyScrollMaxItemCount = validatedOptions.stickyScrollMaxItemCount;
                this.update();
            }
        }
        validateStickySettings(options) {
            let stickyScrollMaxItemCount = 7;
            if (typeof options.stickyScrollMaxItemCount === 'number') {
                stickyScrollMaxItemCount = Math.max(options.stickyScrollMaxItemCount, 1);
            }
            return { stickyScrollMaxItemCount };
        }
    }
    class StickyScrollWidget {
        constructor(container, view, tree, treeRenderers, treeDelegate, accessibilityProvider) {
            this.view = view;
            this.tree = tree;
            this.treeRenderers = treeRenderers;
            this.treeDelegate = treeDelegate;
            this.accessibilityProvider = accessibilityProvider;
            this._previousElements = [];
            this._previousStateDisposables = new lifecycle_1.DisposableStore();
            this._rootDomNode = (0, dom_1.$)('.monaco-tree-sticky-container.empty');
            container.appendChild(this._rootDomNode);
            const shadow = (0, dom_1.$)('.monaco-tree-sticky-container-shadow');
            this._rootDomNode.appendChild(shadow);
            this.stickyScrollFocus = new StickyScrollFocus(this._rootDomNode, view);
            this.onDidChangeHasFocus = this.stickyScrollFocus.onDidChangeHasFocus;
            this.onContextMenu = this.stickyScrollFocus.onContextMenu;
        }
        get height() {
            if (!this._previousState) {
                return 0;
            }
            const lastElement = this._previousState.stickyNodes[this._previousState.count - 1];
            return lastElement.position + lastElement.height;
        }
        setState(state) {
            const wasVisible = !!this._previousState && this._previousState.count > 0;
            const isVisible = !!state && state.count > 0;
            // If state has not changed, do nothing
            if ((!wasVisible && !isVisible) || (wasVisible && isVisible && this._previousState.equal(state))) {
                return;
            }
            // Update visibility of the widget if changed
            if (wasVisible !== isVisible) {
                this.setVisible(isVisible);
            }
            if (!isVisible) {
                this._previousState = undefined;
                this._previousElements = [];
                this._previousStateDisposables.clear();
                return;
            }
            const lastStickyNode = state.stickyNodes[state.count - 1];
            // If the new state is only a change in the last node's position, update the position of the last element
            if (this._previousState && state.animationStateChanged(this._previousState)) {
                this._previousElements[this._previousState.count - 1].style.top = `${lastStickyNode.position}px`;
            }
            // create new dom elements
            else {
                this._previousStateDisposables.clear();
                const elements = Array(state.count);
                for (let stickyIndex = state.count - 1; stickyIndex >= 0; stickyIndex--) {
                    const stickyNode = state.stickyNodes[stickyIndex];
                    const { element, disposable } = this.createElement(stickyNode, stickyIndex, state.count);
                    elements[stickyIndex] = element;
                    this._rootDomNode.appendChild(element);
                    this._previousStateDisposables.add(disposable);
                }
                this.stickyScrollFocus.updateElements(elements, state);
                this._previousElements = elements;
            }
            this._previousState = state;
            // Set the height of the widget to the bottom of the last sticky node
            this._rootDomNode.style.height = `${lastStickyNode.position + lastStickyNode.height}px`;
        }
        createElement(stickyNode, stickyIndex, stickyNodesTotal) {
            const nodeIndex = stickyNode.startIndex;
            // Sticky element container
            const stickyElement = document.createElement('div');
            stickyElement.style.top = `${stickyNode.position}px`;
            if (this.tree.options.setRowHeight !== false) {
                stickyElement.style.height = `${stickyNode.height}px`;
            }
            if (this.tree.options.setRowLineHeight !== false) {
                stickyElement.style.lineHeight = `${stickyNode.height}px`;
            }
            stickyElement.classList.add('monaco-tree-sticky-row');
            stickyElement.classList.add('monaco-list-row');
            stickyElement.setAttribute('data-index', `${nodeIndex}`);
            stickyElement.setAttribute('data-parity', nodeIndex % 2 === 0 ? 'even' : 'odd');
            stickyElement.setAttribute('id', this.view.getElementID(nodeIndex));
            const accessibilityDisposable = this.setAccessibilityAttributes(stickyElement, stickyNode.node.element, stickyIndex, stickyNodesTotal);
            // Get the renderer for the node
            const nodeTemplateId = this.treeDelegate.getTemplateId(stickyNode.node);
            const renderer = this.treeRenderers.find((renderer) => renderer.templateId === nodeTemplateId);
            if (!renderer) {
                throw new Error(`No renderer found for template id ${nodeTemplateId}`);
            }
            // To make sure we do not influence the original node, we create a copy of the node
            // We need to check if it is already a unique instance of the node by the delegate
            let nodeCopy = stickyNode.node;
            if (nodeCopy === this.tree.getNode(this.tree.getNodeLocation(stickyNode.node))) {
                nodeCopy = new Proxy(stickyNode.node, {});
            }
            // Render the element
            const templateData = renderer.renderTemplate(stickyElement);
            renderer.renderElement(nodeCopy, stickyNode.startIndex, templateData, stickyNode.height);
            // Remove the element from the DOM when state is disposed
            const disposable = (0, lifecycle_1.toDisposable)(() => {
                accessibilityDisposable.dispose();
                renderer.disposeElement(nodeCopy, stickyNode.startIndex, templateData, stickyNode.height);
                renderer.disposeTemplate(templateData);
                stickyElement.remove();
            });
            return { element: stickyElement, disposable };
        }
        setAccessibilityAttributes(container, element, stickyIndex, stickyNodesTotal) {
            if (!this.accessibilityProvider) {
                return lifecycle_1.Disposable.None;
            }
            if (this.accessibilityProvider.getSetSize) {
                container.setAttribute('aria-setsize', String(this.accessibilityProvider.getSetSize(element, stickyIndex, stickyNodesTotal)));
            }
            if (this.accessibilityProvider.getPosInSet) {
                container.setAttribute('aria-posinset', String(this.accessibilityProvider.getPosInSet(element, stickyIndex)));
            }
            if (this.accessibilityProvider.getRole) {
                container.setAttribute('role', this.accessibilityProvider.getRole(element) ?? 'treeitem');
            }
            const ariaLabel = this.accessibilityProvider.getAriaLabel(element);
            const observable = (ariaLabel && typeof ariaLabel !== 'string') ? ariaLabel : (0, observable_1.constObservable)(ariaLabel);
            const result = (0, observable_1.autorun)(reader => {
                const value = reader.readObservable(observable);
                if (value) {
                    container.setAttribute('aria-label', value);
                }
                else {
                    container.removeAttribute('aria-label');
                }
            });
            if (typeof ariaLabel === 'string') {
            }
            else if (ariaLabel) {
                container.setAttribute('aria-label', ariaLabel.get());
            }
            const ariaLevel = this.accessibilityProvider.getAriaLevel && this.accessibilityProvider.getAriaLevel(element);
            if (typeof ariaLevel === 'number') {
                container.setAttribute('aria-level', `${ariaLevel}`);
            }
            // Sticky Scroll elements can not be selected
            container.setAttribute('aria-selected', String(false));
            return result;
        }
        setVisible(visible) {
            this._rootDomNode.classList.toggle('empty', !visible);
            if (!visible) {
                this.stickyScrollFocus.updateElements([], undefined);
            }
        }
        domFocus() {
            this.stickyScrollFocus.domFocus();
        }
        focusedLast() {
            return this.stickyScrollFocus.focusedLast();
        }
        dispose() {
            this.stickyScrollFocus.dispose();
            this._previousStateDisposables.dispose();
            this._rootDomNode.remove();
        }
    }
    class StickyScrollFocus extends lifecycle_1.Disposable {
        get domHasFocus() { return this._domHasFocus; }
        set domHasFocus(hasFocus) {
            if (hasFocus !== this._domHasFocus) {
                this._onDidChangeHasFocus.fire(hasFocus);
                this._domHasFocus = hasFocus;
            }
        }
        constructor(container, view) {
            super();
            this.container = container;
            this.view = view;
            this.focusedIndex = -1;
            this.elements = [];
            this._onDidChangeHasFocus = new event_2.Emitter();
            this.onDidChangeHasFocus = this._onDidChangeHasFocus.event;
            this._onContextMenu = new event_2.Emitter();
            this.onContextMenu = this._onContextMenu.event;
            this._domHasFocus = false;
            this._register((0, dom_1.addDisposableListener)(this.container, 'focus', () => this.onFocus()));
            this._register((0, dom_1.addDisposableListener)(this.container, 'blur', () => this.onBlur()));
            this._register(this.view.onDidFocus(() => this.toggleStickyScrollFocused(false)));
            this._register(this.view.onKeyDown((e) => this.onKeyDown(e)));
            this._register(this.view.onMouseDown((e) => this.onMouseDown(e)));
            this._register(this.view.onContextMenu((e) => this.handleContextMenu(e)));
        }
        handleContextMenu(e) {
            const target = e.browserEvent.target;
            if (!(0, listWidget_1.isStickyScrollContainer)(target) && !(0, listWidget_1.isStickyScrollElement)(target)) {
                if (this.focusedLast()) {
                    this.view.domFocus();
                }
                return;
            }
            // The list handles the context menu triggered by a mouse event
            // In that case only set the focus of the element clicked and leave the rest to the list to handle
            if (!(0, dom_1.isKeyboardEvent)(e.browserEvent)) {
                if (!this.state) {
                    throw new Error('Context menu should not be triggered when state is undefined');
                }
                const stickyIndex = this.state.stickyNodes.findIndex(stickyNode => stickyNode.node.element === e.element?.element);
                if (stickyIndex === -1) {
                    throw new Error('Context menu should not be triggered when element is not in sticky scroll widget');
                }
                this.container.focus();
                this.setFocus(stickyIndex);
                return;
            }
            if (!this.state || this.focusedIndex < 0) {
                throw new Error('Context menu key should not be triggered when focus is not in sticky scroll widget');
            }
            const stickyNode = this.state.stickyNodes[this.focusedIndex];
            const element = stickyNode.node.element;
            const anchor = this.elements[this.focusedIndex];
            this._onContextMenu.fire({ element, anchor, browserEvent: e.browserEvent, isStickyScroll: true });
        }
        onKeyDown(e) {
            // Sticky Scroll Navigation
            if (this.domHasFocus && this.state) {
                // Move up
                if (e.key === 'ArrowUp') {
                    this.setFocusedElement(Math.max(0, this.focusedIndex - 1));
                    e.preventDefault();
                    e.stopPropagation();
                }
                // Move down, if last sticky node is focused, move focus into first child of last sticky node
                else if (e.key === 'ArrowDown' || e.key === 'ArrowRight') {
                    if (this.focusedIndex >= this.state.count - 1) {
                        const nodeIndexToFocus = this.state.stickyNodes[this.state.count - 1].startIndex + 1;
                        this.view.domFocus();
                        this.view.setFocus([nodeIndexToFocus]);
                        this.scrollNodeUnderWidget(nodeIndexToFocus, this.state);
                    }
                    else {
                        this.setFocusedElement(this.focusedIndex + 1);
                    }
                    e.preventDefault();
                    e.stopPropagation();
                }
            }
        }
        onMouseDown(e) {
            const target = e.browserEvent.target;
            if (!(0, listWidget_1.isStickyScrollContainer)(target) && !(0, listWidget_1.isStickyScrollElement)(target)) {
                return;
            }
            e.browserEvent.preventDefault();
            e.browserEvent.stopPropagation();
        }
        updateElements(elements, state) {
            if (state && state.count === 0) {
                throw new Error('Sticky scroll state must be undefined when there are no sticky nodes');
            }
            if (state && state.count !== elements.length) {
                throw new Error('Sticky scroll focus received illigel state');
            }
            const previousIndex = this.focusedIndex;
            this.removeFocus();
            this.elements = elements;
            this.state = state;
            if (state) {
                const newFocusedIndex = (0, numbers_1.clamp)(previousIndex, 0, state.count - 1);
                this.setFocus(newFocusedIndex);
            }
            else {
                if (this.domHasFocus) {
                    this.view.domFocus();
                }
            }
            // must come last as it calls blur()
            this.container.tabIndex = state ? 0 : -1;
        }
        setFocusedElement(stickyIndex) {
            // doesn't imply that the widget has (or will have) focus
            const state = this.state;
            if (!state) {
                throw new Error('Cannot set focus when state is undefined');
            }
            this.setFocus(stickyIndex);
            if (stickyIndex < state.count - 1) {
                return;
            }
            // If the last sticky node is not fully visible, scroll it into view
            if (state.lastNodePartiallyVisible()) {
                const lastStickyNode = state.stickyNodes[stickyIndex];
                this.scrollNodeUnderWidget(lastStickyNode.endIndex + 1, state);
            }
        }
        scrollNodeUnderWidget(nodeIndex, state) {
            const lastStickyNode = state.stickyNodes[state.count - 1];
            const secondLastStickyNode = state.count > 1 ? state.stickyNodes[state.count - 2] : undefined;
            const elementScrollTop = this.view.getElementTop(nodeIndex);
            const elementTargetViewTop = secondLastStickyNode ? secondLastStickyNode.position + secondLastStickyNode.height + lastStickyNode.height : lastStickyNode.height;
            this.view.scrollTop = elementScrollTop - elementTargetViewTop;
        }
        domFocus() {
            if (!this.state) {
                throw new Error('Cannot focus when state is undefined');
            }
            this.container.focus();
        }
        focusedLast() {
            if (!this.state) {
                return false;
            }
            return this.view.getHTMLElement().classList.contains('sticky-scroll-focused');
        }
        removeFocus() {
            if (this.focusedIndex === -1) {
                return;
            }
            this.toggleElementFocus(this.elements[this.focusedIndex], false);
            this.focusedIndex = -1;
        }
        setFocus(newFocusIndex) {
            if (0 > newFocusIndex) {
                throw new Error('addFocus() can not remove focus');
            }
            if (!this.state && newFocusIndex >= 0) {
                throw new Error('Cannot set focus index when state is undefined');
            }
            if (this.state && newFocusIndex >= this.state.count) {
                throw new Error('Cannot set focus index to an index that does not exist');
            }
            const oldIndex = this.focusedIndex;
            if (oldIndex >= 0) {
                this.toggleElementFocus(this.elements[oldIndex], false);
            }
            if (newFocusIndex >= 0) {
                this.toggleElementFocus(this.elements[newFocusIndex], true);
            }
            this.focusedIndex = newFocusIndex;
        }
        toggleElementFocus(element, focused) {
            this.toggleElementActiveFocus(element, focused && this.domHasFocus);
            this.toggleElementPassiveFocus(element, focused);
        }
        toggleCurrentElementActiveFocus(focused) {
            if (this.focusedIndex === -1) {
                return;
            }
            this.toggleElementActiveFocus(this.elements[this.focusedIndex], focused);
        }
        toggleElementActiveFocus(element, focused) {
            // active focus is set when sticky scroll has focus
            element.classList.toggle('focused', focused);
        }
        toggleElementPassiveFocus(element, focused) {
            // passive focus allows to show focus when sticky scroll does not have focus
            // for example when the context menu has focus
            element.classList.toggle('passive-focused', focused);
        }
        toggleStickyScrollFocused(focused) {
            // Weather the last focus in the view was sticky scroll and not the list
            // Is only removed when the focus is back in the tree an no longer in sticky scroll
            this.view.getHTMLElement().classList.toggle('sticky-scroll-focused', focused);
        }
        onFocus() {
            if (!this.state || this.elements.length === 0) {
                throw new Error('Cannot focus when state is undefined or elements are empty');
            }
            this.domHasFocus = true;
            this.toggleStickyScrollFocused(true);
            this.toggleCurrentElementActiveFocus(true);
            if (this.focusedIndex === -1) {
                this.setFocus(0);
            }
        }
        onBlur() {
            this.domHasFocus = false;
            this.toggleCurrentElementActiveFocus(false);
        }
        dispose() {
            this.toggleStickyScrollFocused(false);
            this._onDidChangeHasFocus.fire(false);
            super.dispose();
        }
    }
    function asTreeMouseEvent(event) {
        let target = tree_1.TreeMouseEventTarget.Unknown;
        if ((0, dom_1.hasParentWithClass)(event.browserEvent.target, 'monaco-tl-twistie', 'monaco-tl-row')) {
            target = tree_1.TreeMouseEventTarget.Twistie;
        }
        else if ((0, dom_1.hasParentWithClass)(event.browserEvent.target, 'monaco-tl-contents', 'monaco-tl-row')) {
            target = tree_1.TreeMouseEventTarget.Element;
        }
        else if ((0, dom_1.hasParentWithClass)(event.browserEvent.target, 'monaco-tree-type-filter', 'monaco-list')) {
            target = tree_1.TreeMouseEventTarget.Filter;
        }
        return {
            browserEvent: event.browserEvent,
            element: event.element ? event.element.element : null,
            target
        };
    }
    function asTreeContextMenuEvent(event) {
        const isStickyScroll = (0, listWidget_1.isStickyScrollContainer)(event.browserEvent.target);
        return {
            element: event.element ? event.element.element : null,
            browserEvent: event.browserEvent,
            anchor: event.anchor,
            isStickyScroll
        };
    }
    function dfs(node, fn) {
        fn(node);
        node.children.forEach(child => dfs(child, fn));
    }
    /**
     * The trait concept needs to exist at the tree level, because collapsed
     * tree nodes will not be known by the list.
     */
    class Trait {
        get nodeSet() {
            if (!this._nodeSet) {
                this._nodeSet = this.createNodeSet();
            }
            return this._nodeSet;
        }
        constructor(getFirstViewElementWithTrait, identityProvider) {
            this.getFirstViewElementWithTrait = getFirstViewElementWithTrait;
            this.identityProvider = identityProvider;
            this.nodes = [];
            this._onDidChange = new event_2.Emitter();
            this.onDidChange = this._onDidChange.event;
        }
        set(nodes, browserEvent) {
            if (!browserEvent?.__forceEvent && (0, arrays_1.equals)(this.nodes, nodes)) {
                return;
            }
            this._set(nodes, false, browserEvent);
        }
        _set(nodes, silent, browserEvent) {
            this.nodes = [...nodes];
            this.elements = undefined;
            this._nodeSet = undefined;
            if (!silent) {
                const that = this;
                this._onDidChange.fire({ get elements() { return that.get(); }, browserEvent });
            }
        }
        get() {
            if (!this.elements) {
                this.elements = this.nodes.map(node => node.element);
            }
            return [...this.elements];
        }
        getNodes() {
            return this.nodes;
        }
        has(node) {
            return this.nodeSet.has(node);
        }
        onDidModelSplice({ insertedNodes, deletedNodes }) {
            if (!this.identityProvider) {
                const set = this.createNodeSet();
                const visit = (node) => set.delete(node);
                deletedNodes.forEach(node => dfs(node, visit));
                this.set([...set.values()]);
                return;
            }
            const deletedNodesIdSet = new Set();
            const deletedNodesVisitor = (node) => deletedNodesIdSet.add(this.identityProvider.getId(node.element).toString());
            deletedNodes.forEach(node => dfs(node, deletedNodesVisitor));
            const insertedNodesMap = new Map();
            const insertedNodesVisitor = (node) => insertedNodesMap.set(this.identityProvider.getId(node.element).toString(), node);
            insertedNodes.forEach(node => dfs(node, insertedNodesVisitor));
            const nodes = [];
            for (const node of this.nodes) {
                const id = this.identityProvider.getId(node.element).toString();
                const wasDeleted = deletedNodesIdSet.has(id);
                if (!wasDeleted) {
                    nodes.push(node);
                }
                else {
                    const insertedNode = insertedNodesMap.get(id);
                    if (insertedNode && insertedNode.visible) {
                        nodes.push(insertedNode);
                    }
                }
            }
            if (this.nodes.length > 0 && nodes.length === 0) {
                const node = this.getFirstViewElementWithTrait();
                if (node) {
                    nodes.push(node);
                }
            }
            this._set(nodes, true);
        }
        createNodeSet() {
            const set = new Set();
            for (const node of this.nodes) {
                set.add(node);
            }
            return set;
        }
    }
    class TreeNodeListMouseController extends listWidget_1.MouseController {
        constructor(list, tree, stickyScrollProvider) {
            super(list);
            this.tree = tree;
            this.stickyScrollProvider = stickyScrollProvider;
        }
        onViewPointer(e) {
            if ((0, listWidget_1.isButton)(e.browserEvent.target) ||
                (0, listWidget_1.isInputElement)(e.browserEvent.target) ||
                (0, listWidget_1.isMonacoEditor)(e.browserEvent.target)) {
                return;
            }
            if (e.browserEvent.isHandledByList) {
                return;
            }
            const node = e.element;
            if (!node) {
                return super.onViewPointer(e);
            }
            if (this.isSelectionRangeChangeEvent(e) || this.isSelectionSingleChangeEvent(e)) {
                return super.onViewPointer(e);
            }
            const target = e.browserEvent.target;
            const onTwistie = target.classList.contains('monaco-tl-twistie')
                || (target.classList.contains('monaco-icon-label') && target.classList.contains('folder-icon') && e.browserEvent.offsetX < 16);
            const isStickyElement = (0, listWidget_1.isStickyScrollElement)(e.browserEvent.target);
            let expandOnlyOnTwistieClick = false;
            if (isStickyElement) {
                expandOnlyOnTwistieClick = true;
            }
            else if (typeof this.tree.expandOnlyOnTwistieClick === 'function') {
                expandOnlyOnTwistieClick = this.tree.expandOnlyOnTwistieClick(node.element);
            }
            else {
                expandOnlyOnTwistieClick = !!this.tree.expandOnlyOnTwistieClick;
            }
            if (!isStickyElement) {
                if (expandOnlyOnTwistieClick && !onTwistie && e.browserEvent.detail !== 2) {
                    return super.onViewPointer(e);
                }
                if (!this.tree.expandOnDoubleClick && e.browserEvent.detail === 2) {
                    return super.onViewPointer(e);
                }
            }
            else {
                this.handleStickyScrollMouseEvent(e, node);
            }
            if (node.collapsible && (!isStickyElement || onTwistie)) {
                const location = this.tree.getNodeLocation(node);
                const recursive = e.browserEvent.altKey;
                this.tree.setFocus([location]);
                this.tree.toggleCollapsed(location, recursive);
                if (onTwistie) {
                    // Do not set this before calling a handler on the super class, because it will reject it as handled
                    e.browserEvent.isHandledByList = true;
                    return;
                }
            }
            if (!isStickyElement) {
                super.onViewPointer(e);
            }
        }
        handleStickyScrollMouseEvent(e, node) {
            if ((0, listWidget_1.isMonacoCustomToggle)(e.browserEvent.target) || (0, listWidget_1.isActionItem)(e.browserEvent.target)) {
                return;
            }
            const stickyScrollController = this.stickyScrollProvider();
            if (!stickyScrollController) {
                throw new Error('Sticky scroll controller not found');
            }
            const nodeIndex = this.list.indexOf(node);
            const elementScrollTop = this.list.getElementTop(nodeIndex);
            const elementTargetViewTop = stickyScrollController.nodePositionTopBelowWidget(node);
            this.tree.scrollTop = elementScrollTop - elementTargetViewTop;
            this.list.domFocus();
            this.list.setFocus([nodeIndex]);
            this.list.setSelection([nodeIndex]);
        }
        onDoubleClick(e) {
            const onTwistie = e.browserEvent.target.classList.contains('monaco-tl-twistie');
            if (onTwistie || !this.tree.expandOnDoubleClick) {
                return;
            }
            if (e.browserEvent.isHandledByList) {
                return;
            }
            super.onDoubleClick(e);
        }
        // to make sure dom focus is not stolen (for example with context menu)
        onMouseDown(e) {
            const target = e.browserEvent.target;
            if (!(0, listWidget_1.isStickyScrollContainer)(target) && !(0, listWidget_1.isStickyScrollElement)(target)) {
                super.onMouseDown(e);
                return;
            }
        }
        onContextMenu(e) {
            const target = e.browserEvent.target;
            if (!(0, listWidget_1.isStickyScrollContainer)(target) && !(0, listWidget_1.isStickyScrollElement)(target)) {
                super.onContextMenu(e);
                return;
            }
        }
    }
    /**
     * We use this List subclass to restore selection and focus as nodes
     * get rendered in the list, possibly due to a node expand() call.
     */
    class TreeNodeList extends listWidget_1.List {
        constructor(user, container, virtualDelegate, renderers, focusTrait, selectionTrait, anchorTrait, options) {
            super(user, container, virtualDelegate, renderers, options);
            this.focusTrait = focusTrait;
            this.selectionTrait = selectionTrait;
            this.anchorTrait = anchorTrait;
        }
        createMouseController(options) {
            return new TreeNodeListMouseController(this, options.tree, options.stickyScrollProvider);
        }
        splice(start, deleteCount, elements = []) {
            super.splice(start, deleteCount, elements);
            if (elements.length === 0) {
                return;
            }
            const additionalFocus = [];
            const additionalSelection = [];
            let anchor;
            elements.forEach((node, index) => {
                if (this.focusTrait.has(node)) {
                    additionalFocus.push(start + index);
                }
                if (this.selectionTrait.has(node)) {
                    additionalSelection.push(start + index);
                }
                if (this.anchorTrait.has(node)) {
                    anchor = start + index;
                }
            });
            if (additionalFocus.length > 0) {
                super.setFocus((0, arrays_1.distinct)([...super.getFocus(), ...additionalFocus]));
            }
            if (additionalSelection.length > 0) {
                super.setSelection((0, arrays_1.distinct)([...super.getSelection(), ...additionalSelection]));
            }
            if (typeof anchor === 'number') {
                super.setAnchor(anchor);
            }
        }
        setFocus(indexes, browserEvent, fromAPI = false) {
            super.setFocus(indexes, browserEvent);
            if (!fromAPI) {
                this.focusTrait.set(indexes.map(i => this.element(i)), browserEvent);
            }
        }
        setSelection(indexes, browserEvent, fromAPI = false) {
            super.setSelection(indexes, browserEvent);
            if (!fromAPI) {
                this.selectionTrait.set(indexes.map(i => this.element(i)), browserEvent);
            }
        }
        setAnchor(index, fromAPI = false) {
            super.setAnchor(index);
            if (!fromAPI) {
                if (typeof index === 'undefined') {
                    this.anchorTrait.set([]);
                }
                else {
                    this.anchorTrait.set([this.element(index)]);
                }
            }
        }
    }
    class AbstractTree {
        get onDidScroll() { return this.view.onDidScroll; }
        get onDidChangeFocus() { return this.eventBufferer.wrapEvent(this.focus.onDidChange); }
        get onDidChangeSelection() { return this.eventBufferer.wrapEvent(this.selection.onDidChange); }
        get onMouseDblClick() { return event_2.Event.filter(event_2.Event.map(this.view.onMouseDblClick, asTreeMouseEvent), e => e.target !== tree_1.TreeMouseEventTarget.Filter); }
        get onMouseOver() { return event_2.Event.map(this.view.onMouseOver, asTreeMouseEvent); }
        get onMouseOut() { return event_2.Event.map(this.view.onMouseOut, asTreeMouseEvent); }
        get onContextMenu() { return event_2.Event.any(event_2.Event.filter(event_2.Event.map(this.view.onContextMenu, asTreeContextMenuEvent), e => !e.isStickyScroll), this.stickyScrollController?.onContextMenu ?? event_2.Event.None); }
        get onPointer() { return event_2.Event.map(this.view.onPointer, asTreeMouseEvent); }
        get onKeyDown() { return this.view.onKeyDown; }
        get onDidFocus() { return this.view.onDidFocus; }
        get onDidChangeModel() { return event_2.Event.signal(this.model.onDidSplice); }
        get onDidChangeCollapseState() { return this.model.onDidChangeCollapseState; }
        get findMode() { return this.findController?.mode ?? TreeFindMode.Highlight; }
        set findMode(findMode) { if (this.findController) {
            this.findController.mode = findMode;
        } }
        get findMatchType() { return this.findController?.matchType ?? TreeFindMatchType.Fuzzy; }
        set findMatchType(findFuzzy) { if (this.findController) {
            this.findController.matchType = findFuzzy;
        } }
        get expandOnDoubleClick() { return typeof this._options.expandOnDoubleClick === 'undefined' ? true : this._options.expandOnDoubleClick; }
        get expandOnlyOnTwistieClick() { return typeof this._options.expandOnlyOnTwistieClick === 'undefined' ? true : this._options.expandOnlyOnTwistieClick; }
        get onDidDispose() { return this.view.onDidDispose; }
        constructor(_user, container, delegate, renderers, _options = {}) {
            this._user = _user;
            this._options = _options;
            this.eventBufferer = new event_2.EventBufferer();
            this.onDidChangeFindOpenState = event_2.Event.None;
            this.onDidChangeStickyScrollFocused = event_2.Event.None;
            this.disposables = new lifecycle_1.DisposableStore();
            this._onWillRefilter = new event_2.Emitter();
            this.onWillRefilter = this._onWillRefilter.event;
            this._onDidUpdateOptions = new event_2.Emitter();
            this.treeDelegate = new ComposedTreeDelegate(delegate);
            const onDidChangeCollapseStateRelay = new event_2.Relay();
            const onDidChangeActiveNodes = new event_2.Relay();
            const activeNodes = this.disposables.add(new EventCollection(onDidChangeActiveNodes.event));
            const renderedIndentGuides = new map_1.SetMap();
            this.renderers = renderers.map(r => new TreeRenderer(r, () => this.model, onDidChangeCollapseStateRelay.event, activeNodes, renderedIndentGuides, _options));
            for (const r of this.renderers) {
                this.disposables.add(r);
            }
            let filter;
            if (_options.keyboardNavigationLabelProvider) {
                filter = new FindFilter(this, _options.keyboardNavigationLabelProvider, _options.filter);
                _options = { ..._options, filter: filter }; // TODO need typescript help here
                this.disposables.add(filter);
            }
            this.focus = new Trait(() => this.view.getFocusedElements()[0], _options.identityProvider);
            this.selection = new Trait(() => this.view.getSelectedElements()[0], _options.identityProvider);
            this.anchor = new Trait(() => this.view.getAnchorElement(), _options.identityProvider);
            this.view = new TreeNodeList(_user, container, this.treeDelegate, this.renderers, this.focus, this.selection, this.anchor, { ...asListOptions(() => this.model, _options), tree: this, stickyScrollProvider: () => this.stickyScrollController });
            this.model = this.createModel(_user, this.view, _options);
            onDidChangeCollapseStateRelay.input = this.model.onDidChangeCollapseState;
            const onDidModelSplice = event_2.Event.forEach(this.model.onDidSplice, e => {
                this.eventBufferer.bufferEvents(() => {
                    this.focus.onDidModelSplice(e);
                    this.selection.onDidModelSplice(e);
                });
            }, this.disposables);
            // Make sure the `forEach` always runs
            onDidModelSplice(() => null, null, this.disposables);
            // Active nodes can change when the model changes or when focus or selection change.
            // We debounce it with 0 delay since these events may fire in the same stack and we only
            // want to run this once. It also doesn't matter if it runs on the next tick since it's only
            // a nice to have UI feature.
            const activeNodesEmitter = this.disposables.add(new event_2.Emitter());
            const activeNodesDebounce = this.disposables.add(new async_1.Delayer(0));
            this.disposables.add(event_2.Event.any(onDidModelSplice, this.focus.onDidChange, this.selection.onDidChange)(() => {
                activeNodesDebounce.trigger(() => {
                    const set = new Set();
                    for (const node of this.focus.getNodes()) {
                        set.add(node);
                    }
                    for (const node of this.selection.getNodes()) {
                        set.add(node);
                    }
                    activeNodesEmitter.fire([...set.values()]);
                });
            }));
            onDidChangeActiveNodes.input = activeNodesEmitter.event;
            if (_options.keyboardSupport !== false) {
                const onKeyDown = event_2.Event.chain(this.view.onKeyDown, $ => $.filter(e => !(0, listWidget_1.isInputElement)(e.target))
                    .map(e => new keyboardEvent_1.StandardKeyboardEvent(e)));
                event_2.Event.chain(onKeyDown, $ => $.filter(e => e.keyCode === 15 /* KeyCode.LeftArrow */))(this.onLeftArrow, this, this.disposables);
                event_2.Event.chain(onKeyDown, $ => $.filter(e => e.keyCode === 17 /* KeyCode.RightArrow */))(this.onRightArrow, this, this.disposables);
                event_2.Event.chain(onKeyDown, $ => $.filter(e => e.keyCode === 10 /* KeyCode.Space */))(this.onSpace, this, this.disposables);
            }
            if ((_options.findWidgetEnabled ?? true) && _options.keyboardNavigationLabelProvider && _options.contextViewProvider) {
                const opts = this.options.findWidgetStyles ? { styles: this.options.findWidgetStyles } : undefined;
                this.findController = new FindController(this, this.model, this.view, filter, _options.contextViewProvider, opts);
                this.focusNavigationFilter = node => this.findController.shouldAllowFocus(node);
                this.onDidChangeFindOpenState = this.findController.onDidChangeOpenState;
                this.disposables.add(this.findController);
                this.onDidChangeFindMode = this.findController.onDidChangeMode;
                this.onDidChangeFindMatchType = this.findController.onDidChangeMatchType;
            }
            else {
                this.onDidChangeFindMode = event_2.Event.None;
                this.onDidChangeFindMatchType = event_2.Event.None;
            }
            if (_options.enableStickyScroll) {
                this.stickyScrollController = new StickyScrollController(this, this.model, this.view, this.renderers, this.treeDelegate, _options);
                this.onDidChangeStickyScrollFocused = this.stickyScrollController.onDidChangeHasFocus;
            }
            this.styleElement = (0, dom_1.createStyleSheet)(this.view.getHTMLElement());
            this.getHTMLElement().classList.toggle('always', this._options.renderIndentGuides === RenderIndentGuides.Always);
        }
        updateOptions(optionsUpdate = {}) {
            this._options = { ...this._options, ...optionsUpdate };
            for (const renderer of this.renderers) {
                renderer.updateOptions(optionsUpdate);
            }
            this.view.updateOptions(this._options);
            this.findController?.updateOptions(optionsUpdate);
            this.updateStickyScroll(optionsUpdate);
            this._onDidUpdateOptions.fire(this._options);
            this.getHTMLElement().classList.toggle('always', this._options.renderIndentGuides === RenderIndentGuides.Always);
        }
        get options() {
            return this._options;
        }
        updateStickyScroll(optionsUpdate) {
            if (!this.stickyScrollController && this._options.enableStickyScroll) {
                this.stickyScrollController = new StickyScrollController(this, this.model, this.view, this.renderers, this.treeDelegate, this._options);
                this.onDidChangeStickyScrollFocused = this.stickyScrollController.onDidChangeHasFocus;
            }
            else if (this.stickyScrollController && !this._options.enableStickyScroll) {
                this.onDidChangeStickyScrollFocused = event_2.Event.None;
                this.stickyScrollController.dispose();
                this.stickyScrollController = undefined;
            }
            this.stickyScrollController?.updateOptions(optionsUpdate);
        }
        // Widget
        getHTMLElement() {
            return this.view.getHTMLElement();
        }
        get scrollTop() {
            return this.view.scrollTop;
        }
        set scrollTop(scrollTop) {
            this.view.scrollTop = scrollTop;
        }
        get scrollHeight() {
            return this.view.scrollHeight;
        }
        get renderHeight() {
            return this.view.renderHeight;
        }
        get ariaLabel() {
            return this.view.ariaLabel;
        }
        set ariaLabel(value) {
            this.view.ariaLabel = value;
        }
        domFocus() {
            if (this.stickyScrollController?.focusedLast()) {
                this.stickyScrollController.domFocus();
            }
            else {
                this.view.domFocus();
            }
        }
        layout(height, width) {
            this.view.layout(height, width);
            if ((0, types_1.isNumber)(width)) {
                this.findController?.layout(width);
            }
        }
        style(styles) {
            const suffix = `.${this.view.domId}`;
            const content = [];
            if (styles.treeIndentGuidesStroke) {
                content.push(`.monaco-list${suffix}:hover .monaco-tl-indent > .indent-guide, .monaco-list${suffix}.always .monaco-tl-indent > .indent-guide  { border-color: ${styles.treeInactiveIndentGuidesStroke}; }`);
                content.push(`.monaco-list${suffix} .monaco-tl-indent > .indent-guide.active { border-color: ${styles.treeIndentGuidesStroke}; }`);
            }
            // Sticky Scroll Background
            const stickyScrollBackground = styles.treeStickyScrollBackground ?? styles.listBackground;
            if (stickyScrollBackground) {
                content.push(`.monaco-list${suffix} .monaco-scrollable-element .monaco-tree-sticky-container { background-color: ${stickyScrollBackground}; }`);
                content.push(`.monaco-list${suffix} .monaco-scrollable-element .monaco-tree-sticky-container .monaco-tree-sticky-row { background-color: ${stickyScrollBackground}; }`);
            }
            // Sticky Scroll Border
            if (styles.treeStickyScrollBorder) {
                content.push(`.monaco-list${suffix} .monaco-scrollable-element .monaco-tree-sticky-container { border-bottom: 1px solid ${styles.treeStickyScrollBorder}; }`);
            }
            // Sticky Scroll Shadow
            if (styles.treeStickyScrollShadow) {
                content.push(`.monaco-list${suffix} .monaco-scrollable-element .monaco-tree-sticky-container .monaco-tree-sticky-container-shadow { box-shadow: ${styles.treeStickyScrollShadow} 0 6px 6px -6px inset; height: 3px; }`);
            }
            // Sticky Scroll Focus
            if (styles.listFocusForeground) {
                content.push(`.monaco-list${suffix}.sticky-scroll-focused .monaco-scrollable-element .monaco-tree-sticky-container:focus .monaco-list-row.focused { color: ${styles.listFocusForeground}; }`);
                content.push(`.monaco-list${suffix}:not(.sticky-scroll-focused) .monaco-scrollable-element .monaco-tree-sticky-container .monaco-list-row.focused { color: inherit; }`);
            }
            // Sticky Scroll Focus Outlines
            const focusAndSelectionOutline = (0, dom_1.asCssValueWithDefault)(styles.listFocusAndSelectionOutline, (0, dom_1.asCssValueWithDefault)(styles.listSelectionOutline, styles.listFocusOutline ?? ''));
            if (focusAndSelectionOutline) { // default: listFocusOutline
                content.push(`.monaco-list${suffix}.sticky-scroll-focused .monaco-scrollable-element .monaco-tree-sticky-container:focus .monaco-list-row.focused.selected { outline: 1px solid ${focusAndSelectionOutline}; outline-offset: -1px;}`);
                content.push(`.monaco-list${suffix}:not(.sticky-scroll-focused) .monaco-scrollable-element .monaco-tree-sticky-container .monaco-list-row.focused.selected { outline: inherit;}`);
            }
            if (styles.listFocusOutline) { // default: set
                content.push(`.monaco-list${suffix}.sticky-scroll-focused .monaco-scrollable-element .monaco-tree-sticky-container:focus .monaco-list-row.focused { outline: 1px solid ${styles.listFocusOutline}; outline-offset: -1px; }`);
                content.push(`.monaco-list${suffix}:not(.sticky-scroll-focused) .monaco-scrollable-element .monaco-tree-sticky-container .monaco-list-row.focused { outline: inherit; }`);
                content.push(`.monaco-workbench.context-menu-visible .monaco-list${suffix}.last-focused.sticky-scroll-focused .monaco-scrollable-element .monaco-tree-sticky-container .monaco-list-row.passive-focused { outline: 1px solid ${styles.listFocusOutline}; outline-offset: -1px; }`);
                content.push(`.monaco-workbench.context-menu-visible .monaco-list${suffix}.last-focused.sticky-scroll-focused .monaco-list-rows .monaco-list-row.focused { outline: inherit; }`);
                content.push(`.monaco-workbench.context-menu-visible .monaco-list${suffix}.last-focused:not(.sticky-scroll-focused) .monaco-tree-sticky-container .monaco-list-rows .monaco-list-row.focused { outline: inherit; }`);
            }
            this.styleElement.textContent = content.join('\n');
            this.view.style(styles);
        }
        // Tree navigation
        getParentElement(location) {
            const parentRef = this.model.getParentNodeLocation(location);
            const parentNode = this.model.getNode(parentRef);
            return parentNode.element;
        }
        getFirstElementChild(location) {
            return this.model.getFirstElementChild(location);
        }
        // Tree
        getNode(location) {
            return this.model.getNode(location);
        }
        getNodeLocation(node) {
            return this.model.getNodeLocation(node);
        }
        collapse(location, recursive = false) {
            return this.model.setCollapsed(location, true, recursive);
        }
        expand(location, recursive = false) {
            return this.model.setCollapsed(location, false, recursive);
        }
        toggleCollapsed(location, recursive = false) {
            return this.model.setCollapsed(location, undefined, recursive);
        }
        isCollapsible(location) {
            return this.model.isCollapsible(location);
        }
        setCollapsible(location, collapsible) {
            return this.model.setCollapsible(location, collapsible);
        }
        isCollapsed(location) {
            return this.model.isCollapsed(location);
        }
        refilter() {
            this._onWillRefilter.fire(undefined);
            this.model.refilter();
        }
        setSelection(elements, browserEvent) {
            this.eventBufferer.bufferEvents(() => {
                const nodes = elements.map(e => this.model.getNode(e));
                this.selection.set(nodes, browserEvent);
                const indexes = elements.map(e => this.model.getListIndex(e)).filter(i => i > -1);
                this.view.setSelection(indexes, browserEvent, true);
            });
        }
        getSelection() {
            return this.selection.get();
        }
        setFocus(elements, browserEvent) {
            this.eventBufferer.bufferEvents(() => {
                const nodes = elements.map(e => this.model.getNode(e));
                this.focus.set(nodes, browserEvent);
                const indexes = elements.map(e => this.model.getListIndex(e)).filter(i => i > -1);
                this.view.setFocus(indexes, browserEvent, true);
            });
        }
        focusNext(n = 1, loop = false, browserEvent, filter = ((0, dom_1.isKeyboardEvent)(browserEvent) && browserEvent.altKey) ? undefined : this.focusNavigationFilter) {
            this.view.focusNext(n, loop, browserEvent, filter);
        }
        focusPrevious(n = 1, loop = false, browserEvent, filter = ((0, dom_1.isKeyboardEvent)(browserEvent) && browserEvent.altKey) ? undefined : this.focusNavigationFilter) {
            this.view.focusPrevious(n, loop, browserEvent, filter);
        }
        focusNextPage(browserEvent, filter = ((0, dom_1.isKeyboardEvent)(browserEvent) && browserEvent.altKey) ? undefined : this.focusNavigationFilter) {
            return this.view.focusNextPage(browserEvent, filter);
        }
        focusPreviousPage(browserEvent, filter = ((0, dom_1.isKeyboardEvent)(browserEvent) && browserEvent.altKey) ? undefined : this.focusNavigationFilter) {
            return this.view.focusPreviousPage(browserEvent, filter, () => this.stickyScrollController?.height ?? 0);
        }
        focusLast(browserEvent, filter = ((0, dom_1.isKeyboardEvent)(browserEvent) && browserEvent.altKey) ? undefined : this.focusNavigationFilter) {
            this.view.focusLast(browserEvent, filter);
        }
        focusFirst(browserEvent, filter = ((0, dom_1.isKeyboardEvent)(browserEvent) && browserEvent.altKey) ? undefined : this.focusNavigationFilter) {
            this.view.focusFirst(browserEvent, filter);
        }
        getFocus() {
            return this.focus.get();
        }
        reveal(location, relativeTop) {
            this.model.expandTo(location);
            const index = this.model.getListIndex(location);
            if (index === -1) {
                return;
            }
            if (!this.stickyScrollController) {
                this.view.reveal(index, relativeTop);
            }
            else {
                const paddingTop = this.stickyScrollController.nodePositionTopBelowWidget(this.getNode(location));
                this.view.reveal(index, relativeTop, paddingTop);
            }
        }
        // List
        onLeftArrow(e) {
            e.preventDefault();
            e.stopPropagation();
            const nodes = this.view.getFocusedElements();
            if (nodes.length === 0) {
                return;
            }
            const node = nodes[0];
            const location = this.model.getNodeLocation(node);
            const didChange = this.model.setCollapsed(location, true);
            if (!didChange) {
                const parentLocation = this.model.getParentNodeLocation(location);
                if (!parentLocation) {
                    return;
                }
                const parentListIndex = this.model.getListIndex(parentLocation);
                this.view.reveal(parentListIndex);
                this.view.setFocus([parentListIndex]);
            }
        }
        onRightArrow(e) {
            e.preventDefault();
            e.stopPropagation();
            const nodes = this.view.getFocusedElements();
            if (nodes.length === 0) {
                return;
            }
            const node = nodes[0];
            const location = this.model.getNodeLocation(node);
            const didChange = this.model.setCollapsed(location, false);
            if (!didChange) {
                if (!node.children.some(child => child.visible)) {
                    return;
                }
                const [focusedIndex] = this.view.getFocus();
                const firstChildIndex = focusedIndex + 1;
                this.view.reveal(firstChildIndex);
                this.view.setFocus([firstChildIndex]);
            }
        }
        onSpace(e) {
            e.preventDefault();
            e.stopPropagation();
            const nodes = this.view.getFocusedElements();
            if (nodes.length === 0) {
                return;
            }
            const node = nodes[0];
            const location = this.model.getNodeLocation(node);
            const recursive = e.browserEvent.altKey;
            this.model.setCollapsed(location, undefined, recursive);
        }
        dispose() {
            (0, lifecycle_1.dispose)(this.disposables);
            this.stickyScrollController?.dispose();
            this.view.dispose();
        }
    }
    exports.AbstractTree = AbstractTree;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[644/*vs/base/browser/ui/tree/dataTree*/], __M([1/*require*/,0/*exports*/,176/*vs/base/browser/ui/tree/abstractTree*/,250/*vs/base/browser/ui/tree/objectTreeModel*/]), function (require, exports, abstractTree_1, objectTreeModel_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DataTree = void 0;
    class DataTree extends abstractTree_1.AbstractTree {
        constructor(user, container, delegate, renderers, dataSource, options = {}) {
            super(user, container, delegate, renderers, options);
            this.user = user;
            this.dataSource = dataSource;
            this.identityProvider = options.identityProvider;
        }
        createModel(user, view, options) {
            return new objectTreeModel_1.ObjectTreeModel(user, view, options);
        }
    }
    exports.DataTree = DataTree;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/






define(__m[360/*vs/base/browser/ui/tree/objectTree*/], __M([1/*require*/,0/*exports*/,176/*vs/base/browser/ui/tree/abstractTree*/,627/*vs/base/browser/ui/tree/compressedObjectTreeModel*/,250/*vs/base/browser/ui/tree/objectTreeModel*/,126/*vs/base/common/decorators*/,53/*vs/base/common/iterator*/]), function (require, exports, abstractTree_1, compressedObjectTreeModel_1, objectTreeModel_1, decorators_1, iterator_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CompressibleObjectTree = exports.ObjectTree = void 0;
    class ObjectTree extends abstractTree_1.AbstractTree {
        get onDidChangeCollapseState() { return this.model.onDidChangeCollapseState; }
        constructor(user, container, delegate, renderers, options = {}) {
            super(user, container, delegate, renderers, options);
            this.user = user;
        }
        setChildren(element, children = iterator_1.Iterable.empty(), options) {
            this.model.setChildren(element, children, options);
        }
        rerender(element) {
            if (element === undefined) {
                this.view.rerender();
                return;
            }
            this.model.rerender(element);
        }
        hasElement(element) {
            return this.model.has(element);
        }
        createModel(user, view, options) {
            return new objectTreeModel_1.ObjectTreeModel(user, view, options);
        }
    }
    exports.ObjectTree = ObjectTree;
    class CompressibleRenderer {
        get compressedTreeNodeProvider() {
            return this._compressedTreeNodeProvider();
        }
        constructor(_compressedTreeNodeProvider, stickyScrollDelegate, renderer) {
            this._compressedTreeNodeProvider = _compressedTreeNodeProvider;
            this.stickyScrollDelegate = stickyScrollDelegate;
            this.renderer = renderer;
            this.templateId = renderer.templateId;
            if (renderer.onDidChangeTwistieState) {
                this.onDidChangeTwistieState = renderer.onDidChangeTwistieState;
            }
        }
        renderTemplate(container) {
            const data = this.renderer.renderTemplate(container);
            return { compressedTreeNode: undefined, data };
        }
        renderElement(node, index, templateData, height) {
            let compressedTreeNode = this.stickyScrollDelegate.getCompressedNode(node);
            if (!compressedTreeNode) {
                compressedTreeNode = this.compressedTreeNodeProvider.getCompressedTreeNode(node.element);
            }
            if (compressedTreeNode.element.elements.length === 1) {
                templateData.compressedTreeNode = undefined;
                this.renderer.renderElement(node, index, templateData.data, height);
            }
            else {
                templateData.compressedTreeNode = compressedTreeNode;
                this.renderer.renderCompressedElements(compressedTreeNode, index, templateData.data, height);
            }
        }
        disposeElement(node, index, templateData, height) {
            if (templateData.compressedTreeNode) {
                this.renderer.disposeCompressedElements?.(templateData.compressedTreeNode, index, templateData.data, height);
            }
            else {
                this.renderer.disposeElement?.(node, index, templateData.data, height);
            }
        }
        disposeTemplate(templateData) {
            this.renderer.disposeTemplate(templateData.data);
        }
        renderTwistie(element, twistieElement) {
            if (this.renderer.renderTwistie) {
                return this.renderer.renderTwistie(element, twistieElement);
            }
            return false;
        }
    }
    __decorate([
        decorators_1.memoize
    ], CompressibleRenderer.prototype, "compressedTreeNodeProvider", null);
    class CompressibleStickyScrollDelegate {
        constructor(modelProvider) {
            this.modelProvider = modelProvider;
            this.compressedStickyNodes = new Map();
        }
        getCompressedNode(node) {
            return this.compressedStickyNodes.get(node);
        }
        constrainStickyScrollNodes(stickyNodes, stickyScrollMaxItemCount, maxWidgetHeight) {
            this.compressedStickyNodes.clear();
            if (stickyNodes.length === 0) {
                return [];
            }
            for (let i = 0; i < stickyNodes.length; i++) {
                const stickyNode = stickyNodes[i];
                const stickyNodeBottom = stickyNode.position + stickyNode.height;
                const followingReachesMaxHeight = i + 1 < stickyNodes.length && stickyNodeBottom + stickyNodes[i + 1].height > maxWidgetHeight;
                if (followingReachesMaxHeight || i >= stickyScrollMaxItemCount - 1 && stickyScrollMaxItemCount < stickyNodes.length) {
                    const uncompressedStickyNodes = stickyNodes.slice(0, i);
                    const overflowingStickyNodes = stickyNodes.slice(i);
                    const compressedStickyNode = this.compressStickyNodes(overflowingStickyNodes);
                    return [...uncompressedStickyNodes, compressedStickyNode];
                }
            }
            return stickyNodes;
        }
        compressStickyNodes(stickyNodes) {
            if (stickyNodes.length === 0) {
                throw new Error('Can\'t compress empty sticky nodes');
            }
            const compressionModel = this.modelProvider();
            if (!compressionModel.isCompressionEnabled()) {
                return stickyNodes[0];
            }
            // Collect all elements to be compressed
            const elements = [];
            for (let i = 0; i < stickyNodes.length; i++) {
                const stickyNode = stickyNodes[i];
                const compressedNode = compressionModel.getCompressedTreeNode(stickyNode.node.element);
                if (compressedNode.element) {
                    // if an element is incompressible, it can't be compressed with it's parent element
                    if (i !== 0 && compressedNode.element.incompressible) {
                        break;
                    }
                    elements.push(...compressedNode.element.elements);
                }
            }
            if (elements.length < 2) {
                return stickyNodes[0];
            }
            // Compress the elements
            const lastStickyNode = stickyNodes[stickyNodes.length - 1];
            const compressedElement = { elements, incompressible: false };
            const compressedNode = { ...lastStickyNode.node, children: [], element: compressedElement };
            const stickyTreeNode = new Proxy(stickyNodes[0].node, {});
            const compressedStickyNode = {
                node: stickyTreeNode,
                startIndex: stickyNodes[0].startIndex,
                endIndex: lastStickyNode.endIndex,
                position: stickyNodes[0].position,
                height: stickyNodes[0].height,
            };
            this.compressedStickyNodes.set(stickyTreeNode, compressedNode);
            return compressedStickyNode;
        }
    }
    function asObjectTreeOptions(compressedTreeNodeProvider, options) {
        return options && {
            ...options,
            keyboardNavigationLabelProvider: options.keyboardNavigationLabelProvider && {
                getKeyboardNavigationLabel(e) {
                    let compressedTreeNode;
                    try {
                        compressedTreeNode = compressedTreeNodeProvider().getCompressedTreeNode(e);
                    }
                    catch {
                        return options.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(e);
                    }
                    if (compressedTreeNode.element.elements.length === 1) {
                        return options.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(e);
                    }
                    else {
                        return options.keyboardNavigationLabelProvider.getCompressedNodeKeyboardNavigationLabel(compressedTreeNode.element.elements);
                    }
                }
            }
        };
    }
    class CompressibleObjectTree extends ObjectTree {
        constructor(user, container, delegate, renderers, options = {}) {
            const compressedTreeNodeProvider = () => this;
            const stickyScrollDelegate = new CompressibleStickyScrollDelegate(() => this.model);
            const compressibleRenderers = renderers.map(r => new CompressibleRenderer(compressedTreeNodeProvider, stickyScrollDelegate, r));
            super(user, container, delegate, compressibleRenderers, { ...asObjectTreeOptions(compressedTreeNodeProvider, options), stickyScrollDelegate });
        }
        setChildren(element, children = iterator_1.Iterable.empty(), options) {
            this.model.setChildren(element, children, options);
        }
        createModel(user, view, options) {
            return new compressedObjectTreeModel_1.CompressibleObjectTreeModel(user, view, options);
        }
        updateOptions(optionsUpdate = {}) {
            super.updateOptions(optionsUpdate);
            if (typeof optionsUpdate.compressionEnabled !== 'undefined') {
                this.model.setCompressionEnabled(optionsUpdate.compressionEnabled);
            }
        }
        getCompressedTreeNode(element = null) {
            return this.model.getCompressedTreeNode(element);
        }
    }
    exports.CompressibleObjectTree = CompressibleObjectTree;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[645/*vs/base/browser/ui/tree/asyncDataTree*/], __M([1/*require*/,0/*exports*/,257/*vs/base/browser/ui/list/listView*/,176/*vs/base/browser/ui/tree/abstractTree*/,249/*vs/base/browser/ui/tree/indexTreeModel*/,360/*vs/base/browser/ui/tree/objectTree*/,159/*vs/base/browser/ui/tree/tree*/,14/*vs/base/common/async*/,26/*vs/base/common/codicons*/,30/*vs/base/common/themables*/,8/*vs/base/common/errors*/,6/*vs/base/common/event*/,53/*vs/base/common/iterator*/,2/*vs/base/common/lifecycle*/,19/*vs/base/common/types*/]), function (require, exports, listView_1, abstractTree_1, indexTreeModel_1, objectTree_1, tree_1, async_1, codicons_1, themables_1, errors_1, event_1, iterator_1, lifecycle_1, types_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CompressibleAsyncDataTree = exports.AsyncDataTree = void 0;
    function createAsyncDataTreeNode(props) {
        return {
            ...props,
            children: [],
            refreshPromise: undefined,
            stale: true,
            slow: false,
            forceExpanded: false
        };
    }
    function isAncestor(ancestor, descendant) {
        if (!descendant.parent) {
            return false;
        }
        else if (descendant.parent === ancestor) {
            return true;
        }
        else {
            return isAncestor(ancestor, descendant.parent);
        }
    }
    function intersects(node, other) {
        return node === other || isAncestor(node, other) || isAncestor(other, node);
    }
    class AsyncDataTreeNodeWrapper {
        get element() { return this.node.element.element; }
        get children() { return this.node.children.map(node => new AsyncDataTreeNodeWrapper(node)); }
        get depth() { return this.node.depth; }
        get visibleChildrenCount() { return this.node.visibleChildrenCount; }
        get visibleChildIndex() { return this.node.visibleChildIndex; }
        get collapsible() { return this.node.collapsible; }
        get collapsed() { return this.node.collapsed; }
        get visible() { return this.node.visible; }
        get filterData() { return this.node.filterData; }
        constructor(node) {
            this.node = node;
        }
    }
    class AsyncDataTreeRenderer {
        constructor(renderer, nodeMapper, onDidChangeTwistieState) {
            this.renderer = renderer;
            this.nodeMapper = nodeMapper;
            this.onDidChangeTwistieState = onDidChangeTwistieState;
            this.renderedNodes = new Map();
            this.templateId = renderer.templateId;
        }
        renderTemplate(container) {
            const templateData = this.renderer.renderTemplate(container);
            return { templateData };
        }
        renderElement(node, index, templateData, height) {
            this.renderer.renderElement(this.nodeMapper.map(node), index, templateData.templateData, height);
        }
        renderTwistie(element, twistieElement) {
            if (element.slow) {
                twistieElement.classList.add(...themables_1.ThemeIcon.asClassNameArray(codicons_1.Codicon.treeItemLoading));
                return true;
            }
            else {
                twistieElement.classList.remove(...themables_1.ThemeIcon.asClassNameArray(codicons_1.Codicon.treeItemLoading));
                return false;
            }
        }
        disposeElement(node, index, templateData, height) {
            this.renderer.disposeElement?.(this.nodeMapper.map(node), index, templateData.templateData, height);
        }
        disposeTemplate(templateData) {
            this.renderer.disposeTemplate(templateData.templateData);
        }
        dispose() {
            this.renderedNodes.clear();
        }
    }
    function asTreeEvent(e) {
        return {
            browserEvent: e.browserEvent,
            elements: e.elements.map(e => e.element)
        };
    }
    function asTreeMouseEvent(e) {
        return {
            browserEvent: e.browserEvent,
            element: e.element && e.element.element,
            target: e.target
        };
    }
    class AsyncDataTreeElementsDragAndDropData extends listView_1.ElementsDragAndDropData {
        constructor(data) {
            super(data.elements.map(node => node.element));
            this.data = data;
        }
    }
    function asAsyncDataTreeDragAndDropData(data) {
        if (data instanceof listView_1.ElementsDragAndDropData) {
            return new AsyncDataTreeElementsDragAndDropData(data);
        }
        return data;
    }
    class AsyncDataTreeNodeListDragAndDrop {
        constructor(dnd) {
            this.dnd = dnd;
        }
        getDragURI(node) {
            return this.dnd.getDragURI(node.element);
        }
        getDragLabel(nodes, originalEvent) {
            if (this.dnd.getDragLabel) {
                return this.dnd.getDragLabel(nodes.map(node => node.element), originalEvent);
            }
            return undefined;
        }
        onDragStart(data, originalEvent) {
            this.dnd.onDragStart?.(asAsyncDataTreeDragAndDropData(data), originalEvent);
        }
        onDragOver(data, targetNode, targetIndex, targetSector, originalEvent, raw = true) {
            return this.dnd.onDragOver(asAsyncDataTreeDragAndDropData(data), targetNode && targetNode.element, targetIndex, targetSector, originalEvent);
        }
        drop(data, targetNode, targetIndex, targetSector, originalEvent) {
            this.dnd.drop(asAsyncDataTreeDragAndDropData(data), targetNode && targetNode.element, targetIndex, targetSector, originalEvent);
        }
        onDragEnd(originalEvent) {
            this.dnd.onDragEnd?.(originalEvent);
        }
        dispose() {
            this.dnd.dispose();
        }
    }
    function asObjectTreeOptions(options) {
        return options && {
            ...options,
            collapseByDefault: true,
            identityProvider: options.identityProvider && {
                getId(el) {
                    return options.identityProvider.getId(el.element);
                }
            },
            dnd: options.dnd && new AsyncDataTreeNodeListDragAndDrop(options.dnd),
            multipleSelectionController: options.multipleSelectionController && {
                isSelectionSingleChangeEvent(e) {
                    return options.multipleSelectionController.isSelectionSingleChangeEvent({ ...e, element: e.element });
                },
                isSelectionRangeChangeEvent(e) {
                    return options.multipleSelectionController.isSelectionRangeChangeEvent({ ...e, element: e.element });
                }
            },
            accessibilityProvider: options.accessibilityProvider && {
                ...options.accessibilityProvider,
                getPosInSet: undefined,
                getSetSize: undefined,
                getRole: options.accessibilityProvider.getRole ? (el) => {
                    return options.accessibilityProvider.getRole(el.element);
                } : () => 'treeitem',
                isChecked: options.accessibilityProvider.isChecked ? (e) => {
                    return !!(options.accessibilityProvider?.isChecked(e.element));
                } : undefined,
                getAriaLabel(e) {
                    return options.accessibilityProvider.getAriaLabel(e.element);
                },
                getWidgetAriaLabel() {
                    return options.accessibilityProvider.getWidgetAriaLabel();
                },
                getWidgetRole: options.accessibilityProvider.getWidgetRole ? () => options.accessibilityProvider.getWidgetRole() : () => 'tree',
                getAriaLevel: options.accessibilityProvider.getAriaLevel && (node => {
                    return options.accessibilityProvider.getAriaLevel(node.element);
                }),
                getActiveDescendantId: options.accessibilityProvider.getActiveDescendantId && (node => {
                    return options.accessibilityProvider.getActiveDescendantId(node.element);
                })
            },
            filter: options.filter && {
                filter(e, parentVisibility) {
                    return options.filter.filter(e.element, parentVisibility);
                }
            },
            keyboardNavigationLabelProvider: options.keyboardNavigationLabelProvider && {
                ...options.keyboardNavigationLabelProvider,
                getKeyboardNavigationLabel(e) {
                    return options.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(e.element);
                }
            },
            sorter: undefined,
            expandOnlyOnTwistieClick: typeof options.expandOnlyOnTwistieClick === 'undefined' ? undefined : (typeof options.expandOnlyOnTwistieClick !== 'function' ? options.expandOnlyOnTwistieClick : (e => options.expandOnlyOnTwistieClick(e.element))),
            defaultFindVisibility: e => {
                if (e.hasChildren && e.stale) {
                    return 1 /* TreeVisibility.Visible */;
                }
                else if (typeof options.defaultFindVisibility === 'number') {
                    return options.defaultFindVisibility;
                }
                else if (typeof options.defaultFindVisibility === 'undefined') {
                    return 2 /* TreeVisibility.Recurse */;
                }
                else {
                    return options.defaultFindVisibility(e.element);
                }
            }
        };
    }
    function dfs(node, fn) {
        fn(node);
        node.children.forEach(child => dfs(child, fn));
    }
    class AsyncDataTree {
        get onDidScroll() { return this.tree.onDidScroll; }
        get onDidChangeFocus() { return event_1.Event.map(this.tree.onDidChangeFocus, asTreeEvent); }
        get onDidChangeSelection() { return event_1.Event.map(this.tree.onDidChangeSelection, asTreeEvent); }
        get onMouseDblClick() { return event_1.Event.map(this.tree.onMouseDblClick, asTreeMouseEvent); }
        get onPointer() { return event_1.Event.map(this.tree.onPointer, asTreeMouseEvent); }
        get onDidFocus() { return this.tree.onDidFocus; }
        /**
         * To be used internally only!
         * @deprecated
         */
        get onDidChangeModel() { return this.tree.onDidChangeModel; }
        get onDidChangeCollapseState() { return this.tree.onDidChangeCollapseState; }
        get onDidChangeFindOpenState() { return this.tree.onDidChangeFindOpenState; }
        get onDidChangeStickyScrollFocused() { return this.tree.onDidChangeStickyScrollFocused; }
        get onDidDispose() { return this.tree.onDidDispose; }
        constructor(user, container, delegate, renderers, dataSource, options = {}) {
            this.user = user;
            this.dataSource = dataSource;
            this.nodes = new Map();
            this.subTreeRefreshPromises = new Map();
            this.refreshPromises = new Map();
            this._onDidRender = new event_1.Emitter();
            this._onDidChangeNodeSlowState = new event_1.Emitter();
            this.nodeMapper = new tree_1.WeakMapper(node => new AsyncDataTreeNodeWrapper(node));
            this.disposables = new lifecycle_1.DisposableStore();
            this.identityProvider = options.identityProvider;
            this.autoExpandSingleChildren = typeof options.autoExpandSingleChildren === 'undefined' ? false : options.autoExpandSingleChildren;
            this.sorter = options.sorter;
            this.getDefaultCollapseState = e => options.collapseByDefault ? (options.collapseByDefault(e) ? tree_1.ObjectTreeElementCollapseState.PreserveOrCollapsed : tree_1.ObjectTreeElementCollapseState.PreserveOrExpanded) : undefined;
            this.tree = this.createTree(user, container, delegate, renderers, options);
            this.onDidChangeFindMode = this.tree.onDidChangeFindMode;
            this.onDidChangeFindMatchType = this.tree.onDidChangeFindMatchType;
            this.root = createAsyncDataTreeNode({
                element: undefined,
                parent: null,
                hasChildren: true,
                defaultCollapseState: undefined
            });
            if (this.identityProvider) {
                this.root = {
                    ...this.root,
                    id: null
                };
            }
            this.nodes.set(null, this.root);
            this.tree.onDidChangeCollapseState(this._onDidChangeCollapseState, this, this.disposables);
        }
        createTree(user, container, delegate, renderers, options) {
            const objectTreeDelegate = new abstractTree_1.ComposedTreeDelegate(delegate);
            const objectTreeRenderers = renderers.map(r => new AsyncDataTreeRenderer(r, this.nodeMapper, this._onDidChangeNodeSlowState.event));
            const objectTreeOptions = asObjectTreeOptions(options) || {};
            return new objectTree_1.ObjectTree(user, container, objectTreeDelegate, objectTreeRenderers, objectTreeOptions);
        }
        updateOptions(options = {}) {
            this.tree.updateOptions(options);
        }
        // Widget
        getHTMLElement() {
            return this.tree.getHTMLElement();
        }
        get scrollTop() {
            return this.tree.scrollTop;
        }
        set scrollTop(scrollTop) {
            this.tree.scrollTop = scrollTop;
        }
        get scrollHeight() {
            return this.tree.scrollHeight;
        }
        get renderHeight() {
            return this.tree.renderHeight;
        }
        domFocus() {
            this.tree.domFocus();
        }
        layout(height, width) {
            this.tree.layout(height, width);
        }
        style(styles) {
            this.tree.style(styles);
        }
        // Model
        getInput() {
            return this.root.element;
        }
        async setInput(input, viewState) {
            this.refreshPromises.forEach(promise => promise.cancel());
            this.refreshPromises.clear();
            this.root.element = input;
            const viewStateContext = viewState && { viewState, focus: [], selection: [] };
            await this._updateChildren(input, true, false, viewStateContext);
            if (viewStateContext) {
                this.tree.setFocus(viewStateContext.focus);
                this.tree.setSelection(viewStateContext.selection);
            }
            if (viewState && typeof viewState.scrollTop === 'number') {
                this.scrollTop = viewState.scrollTop;
            }
        }
        async _updateChildren(element = this.root.element, recursive = true, rerender = false, viewStateContext, options) {
            if (typeof this.root.element === 'undefined') {
                throw new tree_1.TreeError(this.user, 'Tree input not set');
            }
            if (this.root.refreshPromise) {
                await this.root.refreshPromise;
                await event_1.Event.toPromise(this._onDidRender.event);
            }
            const node = this.getDataNode(element);
            await this.refreshAndRenderNode(node, recursive, viewStateContext, options);
            if (rerender) {
                try {
                    this.tree.rerender(node);
                }
                catch {
                    // missing nodes are fine, this could've resulted from
                    // parallel refresh calls, removing `node` altogether
                }
            }
        }
        // View
        rerender(element) {
            if (element === undefined || element === this.root.element) {
                this.tree.rerender();
                return;
            }
            const node = this.getDataNode(element);
            this.tree.rerender(node);
        }
        // Tree
        getNode(element = this.root.element) {
            const dataNode = this.getDataNode(element);
            const node = this.tree.getNode(dataNode === this.root ? null : dataNode);
            return this.nodeMapper.map(node);
        }
        collapse(element, recursive = false) {
            const node = this.getDataNode(element);
            return this.tree.collapse(node === this.root ? null : node, recursive);
        }
        async expand(element, recursive = false) {
            if (typeof this.root.element === 'undefined') {
                throw new tree_1.TreeError(this.user, 'Tree input not set');
            }
            if (this.root.refreshPromise) {
                await this.root.refreshPromise;
                await event_1.Event.toPromise(this._onDidRender.event);
            }
            const node = this.getDataNode(element);
            if (this.tree.hasElement(node) && !this.tree.isCollapsible(node)) {
                return false;
            }
            if (node.refreshPromise) {
                await this.root.refreshPromise;
                await event_1.Event.toPromise(this._onDidRender.event);
            }
            if (node !== this.root && !node.refreshPromise && !this.tree.isCollapsed(node)) {
                return false;
            }
            const result = this.tree.expand(node === this.root ? null : node, recursive);
            if (node.refreshPromise) {
                await this.root.refreshPromise;
                await event_1.Event.toPromise(this._onDidRender.event);
            }
            return result;
        }
        setSelection(elements, browserEvent) {
            const nodes = elements.map(e => this.getDataNode(e));
            this.tree.setSelection(nodes, browserEvent);
        }
        getSelection() {
            const nodes = this.tree.getSelection();
            return nodes.map(n => n.element);
        }
        setFocus(elements, browserEvent) {
            const nodes = elements.map(e => this.getDataNode(e));
            this.tree.setFocus(nodes, browserEvent);
        }
        getFocus() {
            const nodes = this.tree.getFocus();
            return nodes.map(n => n.element);
        }
        reveal(element, relativeTop) {
            this.tree.reveal(this.getDataNode(element), relativeTop);
        }
        // Tree navigation
        getParentElement(element) {
            const node = this.tree.getParentElement(this.getDataNode(element));
            return (node && node.element);
        }
        getFirstElementChild(element = this.root.element) {
            const dataNode = this.getDataNode(element);
            const node = this.tree.getFirstElementChild(dataNode === this.root ? null : dataNode);
            return (node && node.element);
        }
        // Implementation
        getDataNode(element) {
            const node = this.nodes.get((element === this.root.element ? null : element));
            if (!node) {
                throw new tree_1.TreeError(this.user, `Data tree node not found: ${element}`);
            }
            return node;
        }
        async refreshAndRenderNode(node, recursive, viewStateContext, options) {
            await this.refreshNode(node, recursive, viewStateContext);
            if (this.disposables.isDisposed) {
                return; // tree disposed during refresh (#199264)
            }
            this.render(node, viewStateContext, options);
        }
        async refreshNode(node, recursive, viewStateContext) {
            let result;
            this.subTreeRefreshPromises.forEach((refreshPromise, refreshNode) => {
                if (!result && intersects(refreshNode, node)) {
                    result = refreshPromise.then(() => this.refreshNode(node, recursive, viewStateContext));
                }
            });
            if (result) {
                return result;
            }
            if (node !== this.root) {
                const treeNode = this.tree.getNode(node);
                if (treeNode.collapsed) {
                    node.hasChildren = !!this.dataSource.hasChildren(node.element);
                    node.stale = true;
                    this.setChildren(node, [], recursive, viewStateContext);
                    return;
                }
            }
            return this.doRefreshSubTree(node, recursive, viewStateContext);
        }
        async doRefreshSubTree(node, recursive, viewStateContext) {
            let done;
            node.refreshPromise = new Promise(c => done = c);
            this.subTreeRefreshPromises.set(node, node.refreshPromise);
            node.refreshPromise.finally(() => {
                node.refreshPromise = undefined;
                this.subTreeRefreshPromises.delete(node);
            });
            try {
                const childrenToRefresh = await this.doRefreshNode(node, recursive, viewStateContext);
                node.stale = false;
                await async_1.Promises.settled(childrenToRefresh.map(child => this.doRefreshSubTree(child, recursive, viewStateContext)));
            }
            finally {
                done();
            }
        }
        async doRefreshNode(node, recursive, viewStateContext) {
            node.hasChildren = !!this.dataSource.hasChildren(node.element);
            let childrenPromise;
            if (!node.hasChildren) {
                childrenPromise = Promise.resolve(iterator_1.Iterable.empty());
            }
            else {
                const children = this.doGetChildren(node);
                if ((0, types_1.isIterable)(children)) {
                    childrenPromise = Promise.resolve(children);
                }
                else {
                    const slowTimeout = (0, async_1.timeout)(800);
                    slowTimeout.then(() => {
                        node.slow = true;
                        this._onDidChangeNodeSlowState.fire(node);
                    }, _ => null);
                    childrenPromise = children.finally(() => slowTimeout.cancel());
                }
            }
            try {
                const children = await childrenPromise;
                return this.setChildren(node, children, recursive, viewStateContext);
            }
            catch (err) {
                if (node !== this.root && this.tree.hasElement(node)) {
                    this.tree.collapse(node);
                }
                if ((0, errors_1.isCancellationError)(err)) {
                    return [];
                }
                throw err;
            }
            finally {
                if (node.slow) {
                    node.slow = false;
                    this._onDidChangeNodeSlowState.fire(node);
                }
            }
        }
        doGetChildren(node) {
            let result = this.refreshPromises.get(node);
            if (result) {
                return result;
            }
            const children = this.dataSource.getChildren(node.element);
            if ((0, types_1.isIterable)(children)) {
                return this.processChildren(children);
            }
            else {
                result = (0, async_1.createCancelablePromise)(async () => this.processChildren(await children));
                this.refreshPromises.set(node, result);
                return result.finally(() => { this.refreshPromises.delete(node); });
            }
        }
        _onDidChangeCollapseState({ node, deep }) {
            if (node.element === null) {
                return;
            }
            if (!node.collapsed && node.element.stale) {
                if (deep) {
                    this.collapse(node.element.element);
                }
                else {
                    this.refreshAndRenderNode(node.element, false)
                        .catch(errors_1.onUnexpectedError);
                }
            }
        }
        setChildren(node, childrenElementsIterable, recursive, viewStateContext) {
            const childrenElements = [...childrenElementsIterable];
            // perf: if the node was and still is a leaf, avoid all this hassle
            if (node.children.length === 0 && childrenElements.length === 0) {
                return [];
            }
            const nodesToForget = new Map();
            const childrenTreeNodesById = new Map();
            for (const child of node.children) {
                nodesToForget.set(child.element, child);
                if (this.identityProvider) {
                    childrenTreeNodesById.set(child.id, { node: child, collapsed: this.tree.hasElement(child) && this.tree.isCollapsed(child) });
                }
            }
            const childrenToRefresh = [];
            const children = childrenElements.map(element => {
                const hasChildren = !!this.dataSource.hasChildren(element);
                if (!this.identityProvider) {
                    const asyncDataTreeNode = createAsyncDataTreeNode({ element, parent: node, hasChildren, defaultCollapseState: this.getDefaultCollapseState(element) });
                    if (hasChildren && asyncDataTreeNode.defaultCollapseState === tree_1.ObjectTreeElementCollapseState.PreserveOrExpanded) {
                        childrenToRefresh.push(asyncDataTreeNode);
                    }
                    return asyncDataTreeNode;
                }
                const id = this.identityProvider.getId(element).toString();
                const result = childrenTreeNodesById.get(id);
                if (result) {
                    const asyncDataTreeNode = result.node;
                    nodesToForget.delete(asyncDataTreeNode.element);
                    this.nodes.delete(asyncDataTreeNode.element);
                    this.nodes.set(element, asyncDataTreeNode);
                    asyncDataTreeNode.element = element;
                    asyncDataTreeNode.hasChildren = hasChildren;
                    if (recursive) {
                        if (result.collapsed) {
                            asyncDataTreeNode.children.forEach(node => dfs(node, node => this.nodes.delete(node.element)));
                            asyncDataTreeNode.children.splice(0, asyncDataTreeNode.children.length);
                            asyncDataTreeNode.stale = true;
                        }
                        else {
                            childrenToRefresh.push(asyncDataTreeNode);
                        }
                    }
                    else if (hasChildren && !result.collapsed) {
                        childrenToRefresh.push(asyncDataTreeNode);
                    }
                    return asyncDataTreeNode;
                }
                const childAsyncDataTreeNode = createAsyncDataTreeNode({ element, parent: node, id, hasChildren, defaultCollapseState: this.getDefaultCollapseState(element) });
                if (viewStateContext && viewStateContext.viewState.focus && viewStateContext.viewState.focus.indexOf(id) > -1) {
                    viewStateContext.focus.push(childAsyncDataTreeNode);
                }
                if (viewStateContext && viewStateContext.viewState.selection && viewStateContext.viewState.selection.indexOf(id) > -1) {
                    viewStateContext.selection.push(childAsyncDataTreeNode);
                }
                if (viewStateContext && viewStateContext.viewState.expanded && viewStateContext.viewState.expanded.indexOf(id) > -1) {
                    childrenToRefresh.push(childAsyncDataTreeNode);
                }
                else if (hasChildren && childAsyncDataTreeNode.defaultCollapseState === tree_1.ObjectTreeElementCollapseState.PreserveOrExpanded) {
                    childrenToRefresh.push(childAsyncDataTreeNode);
                }
                return childAsyncDataTreeNode;
            });
            for (const node of nodesToForget.values()) {
                dfs(node, node => this.nodes.delete(node.element));
            }
            for (const child of children) {
                this.nodes.set(child.element, child);
            }
            node.children.splice(0, node.children.length, ...children);
            // TODO@joao this doesn't take filter into account
            if (node !== this.root && this.autoExpandSingleChildren && children.length === 1 && childrenToRefresh.length === 0) {
                children[0].forceExpanded = true;
                childrenToRefresh.push(children[0]);
            }
            return childrenToRefresh;
        }
        render(node, viewStateContext, options) {
            const children = node.children.map(node => this.asTreeElement(node, viewStateContext));
            const objectTreeOptions = options && {
                ...options,
                diffIdentityProvider: options.diffIdentityProvider && {
                    getId(node) {
                        return options.diffIdentityProvider.getId(node.element);
                    }
                }
            };
            this.tree.setChildren(node === this.root ? null : node, children, objectTreeOptions);
            if (node !== this.root) {
                this.tree.setCollapsible(node, node.hasChildren);
            }
            this._onDidRender.fire();
        }
        asTreeElement(node, viewStateContext) {
            if (node.stale) {
                return {
                    element: node,
                    collapsible: node.hasChildren,
                    collapsed: true
                };
            }
            let collapsed;
            if (viewStateContext && viewStateContext.viewState.expanded && node.id && viewStateContext.viewState.expanded.indexOf(node.id) > -1) {
                collapsed = false;
            }
            else if (node.forceExpanded) {
                collapsed = false;
                node.forceExpanded = false;
            }
            else {
                collapsed = node.defaultCollapseState;
            }
            return {
                element: node,
                children: node.hasChildren ? iterator_1.Iterable.map(node.children, child => this.asTreeElement(child, viewStateContext)) : [],
                collapsible: node.hasChildren,
                collapsed
            };
        }
        processChildren(children) {
            if (this.sorter) {
                children = [...children].sort(this.sorter.compare.bind(this.sorter));
            }
            return children;
        }
        dispose() {
            this.disposables.dispose();
            this.tree.dispose();
        }
    }
    exports.AsyncDataTree = AsyncDataTree;
    class CompressibleAsyncDataTreeNodeWrapper {
        get element() {
            return {
                elements: this.node.element.elements.map(e => e.element),
                incompressible: this.node.element.incompressible
            };
        }
        get children() { return this.node.children.map(node => new CompressibleAsyncDataTreeNodeWrapper(node)); }
        get depth() { return this.node.depth; }
        get visibleChildrenCount() { return this.node.visibleChildrenCount; }
        get visibleChildIndex() { return this.node.visibleChildIndex; }
        get collapsible() { return this.node.collapsible; }
        get collapsed() { return this.node.collapsed; }
        get visible() { return this.node.visible; }
        get filterData() { return this.node.filterData; }
        constructor(node) {
            this.node = node;
        }
    }
    class CompressibleAsyncDataTreeRenderer {
        constructor(renderer, nodeMapper, compressibleNodeMapperProvider, onDidChangeTwistieState) {
            this.renderer = renderer;
            this.nodeMapper = nodeMapper;
            this.compressibleNodeMapperProvider = compressibleNodeMapperProvider;
            this.onDidChangeTwistieState = onDidChangeTwistieState;
            this.renderedNodes = new Map();
            this.disposables = [];
            this.templateId = renderer.templateId;
        }
        renderTemplate(container) {
            const templateData = this.renderer.renderTemplate(container);
            return { templateData };
        }
        renderElement(node, index, templateData, height) {
            this.renderer.renderElement(this.nodeMapper.map(node), index, templateData.templateData, height);
        }
        renderCompressedElements(node, index, templateData, height) {
            this.renderer.renderCompressedElements(this.compressibleNodeMapperProvider().map(node), index, templateData.templateData, height);
        }
        renderTwistie(element, twistieElement) {
            if (element.slow) {
                twistieElement.classList.add(...themables_1.ThemeIcon.asClassNameArray(codicons_1.Codicon.treeItemLoading));
                return true;
            }
            else {
                twistieElement.classList.remove(...themables_1.ThemeIcon.asClassNameArray(codicons_1.Codicon.treeItemLoading));
                return false;
            }
        }
        disposeElement(node, index, templateData, height) {
            this.renderer.disposeElement?.(this.nodeMapper.map(node), index, templateData.templateData, height);
        }
        disposeCompressedElements(node, index, templateData, height) {
            this.renderer.disposeCompressedElements?.(this.compressibleNodeMapperProvider().map(node), index, templateData.templateData, height);
        }
        disposeTemplate(templateData) {
            this.renderer.disposeTemplate(templateData.templateData);
        }
        dispose() {
            this.renderedNodes.clear();
            this.disposables = (0, lifecycle_1.dispose)(this.disposables);
        }
    }
    function asCompressibleObjectTreeOptions(options) {
        const objectTreeOptions = options && asObjectTreeOptions(options);
        return objectTreeOptions && {
            ...objectTreeOptions,
            keyboardNavigationLabelProvider: objectTreeOptions.keyboardNavigationLabelProvider && {
                ...objectTreeOptions.keyboardNavigationLabelProvider,
                getCompressedNodeKeyboardNavigationLabel(els) {
                    return options.keyboardNavigationLabelProvider.getCompressedNodeKeyboardNavigationLabel(els.map(e => e.element));
                }
            }
        };
    }
    class CompressibleAsyncDataTree extends AsyncDataTree {
        constructor(user, container, virtualDelegate, compressionDelegate, renderers, dataSource, options = {}) {
            super(user, container, virtualDelegate, renderers, dataSource, options);
            this.compressionDelegate = compressionDelegate;
            this.compressibleNodeMapper = new tree_1.WeakMapper(node => new CompressibleAsyncDataTreeNodeWrapper(node));
            this.filter = options.filter;
        }
        createTree(user, container, delegate, renderers, options) {
            const objectTreeDelegate = new abstractTree_1.ComposedTreeDelegate(delegate);
            const objectTreeRenderers = renderers.map(r => new CompressibleAsyncDataTreeRenderer(r, this.nodeMapper, () => this.compressibleNodeMapper, this._onDidChangeNodeSlowState.event));
            const objectTreeOptions = asCompressibleObjectTreeOptions(options) || {};
            return new objectTree_1.CompressibleObjectTree(user, container, objectTreeDelegate, objectTreeRenderers, objectTreeOptions);
        }
        asTreeElement(node, viewStateContext) {
            return {
                incompressible: this.compressionDelegate.isIncompressible(node.element),
                ...super.asTreeElement(node, viewStateContext)
            };
        }
        updateOptions(options = {}) {
            this.tree.updateOptions(options);
        }
        render(node, viewStateContext, options) {
            if (!this.identityProvider) {
                return super.render(node, viewStateContext);
            }
            // Preserve traits across compressions. Hacky but does the trick.
            // This is hard to fix properly since it requires rewriting the traits
            // across trees and lists. Let's just keep it this way for now.
            const getId = (element) => this.identityProvider.getId(element).toString();
            const getUncompressedIds = (nodes) => {
                const result = new Set();
                for (const node of nodes) {
                    const compressedNode = this.tree.getCompressedTreeNode(node === this.root ? null : node);
                    if (!compressedNode.element) {
                        continue;
                    }
                    for (const node of compressedNode.element.elements) {
                        result.add(getId(node.element));
                    }
                }
                return result;
            };
            const oldSelection = getUncompressedIds(this.tree.getSelection());
            const oldFocus = getUncompressedIds(this.tree.getFocus());
            super.render(node, viewStateContext, options);
            const selection = this.getSelection();
            let didChangeSelection = false;
            const focus = this.getFocus();
            let didChangeFocus = false;
            const visit = (node) => {
                const compressedNode = node.element;
                if (compressedNode) {
                    for (let i = 0; i < compressedNode.elements.length; i++) {
                        const id = getId(compressedNode.elements[i].element);
                        const element = compressedNode.elements[compressedNode.elements.length - 1].element;
                        // github.com/microsoft/vscode/issues/85938
                        if (oldSelection.has(id) && selection.indexOf(element) === -1) {
                            selection.push(element);
                            didChangeSelection = true;
                        }
                        if (oldFocus.has(id) && focus.indexOf(element) === -1) {
                            focus.push(element);
                            didChangeFocus = true;
                        }
                    }
                }
                node.children.forEach(visit);
            };
            visit(this.tree.getCompressedTreeNode(node === this.root ? null : node));
            if (didChangeSelection) {
                this.setSelection(selection);
            }
            if (didChangeFocus) {
                this.setFocus(focus);
            }
        }
        // For compressed async data trees, `TreeVisibility.Recurse` doesn't currently work
        // and we have to filter everything beforehand
        // Related to #85193 and #85835
        processChildren(children) {
            if (this.filter) {
                children = iterator_1.Iterable.filter(children, e => {
                    const result = this.filter.filter(e, 1 /* TreeVisibility.Visible */);
                    const visibility = getVisibility(result);
                    if (visibility === 2 /* TreeVisibility.Recurse */) {
                        throw new Error('Recursive tree visibility not supported in async data compressed trees');
                    }
                    return visibility === 1 /* TreeVisibility.Visible */;
                });
            }
            return super.processChildren(children);
        }
    }
    exports.CompressibleAsyncDataTree = CompressibleAsyncDataTree;
    function getVisibility(filterResult) {
        if (typeof filterResult === 'boolean') {
            return filterResult ? 1 /* TreeVisibility.Visible */ : 0 /* TreeVisibility.Hidden */;
        }
        else if ((0, indexTreeModel_1.isFilterResult)(filterResult)) {
            return (0, indexTreeModel_1.getVisibleState)(filterResult.visibility);
        }
        else {
            return (0, indexTreeModel_1.getVisibleState)(filterResult);
        }
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[361/*vs/base/common/worker/simpleWorker*/], __M([1/*require*/,0/*exports*/,8/*vs/base/common/errors*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,42/*vs/base/common/network*/,16/*vs/base/common/platform*/,11/*vs/base/common/strings*/]), function (require, exports, errors_1, event_1, lifecycle_1, network_1, platform_1, strings) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SimpleWorkerServer = exports.SimpleWorkerClient = void 0;
    exports.logOnceWebWorkerWarning = logOnceWebWorkerWarning;
    exports.create = create;
    // ESM-comment-begin
    const isESM = false;
    // ESM-comment-end
    // ESM-uncomment-begin
    // const isESM = true;
    // ESM-uncomment-end
    const DEFAULT_CHANNEL = 'default';
    const INITIALIZE = '$initialize';
    let webWorkerWarningLogged = false;
    function logOnceWebWorkerWarning(err) {
        if (!platform_1.isWeb) {
            // running tests
            return;
        }
        if (!webWorkerWarningLogged) {
            webWorkerWarningLogged = true;
            console.warn('Could not create web worker(s). Falling back to loading web worker code in main thread, which might cause UI freezes. Please see https://github.com/microsoft/monaco-editor#faq');
        }
        console.warn(err.message);
    }
    class RequestMessage {
        constructor(vsWorker, req, channel, method, args) {
            this.vsWorker = vsWorker;
            this.req = req;
            this.channel = channel;
            this.method = method;
            this.args = args;
            this.type = 0 /* MessageType.Request */;
        }
    }
    class ReplyMessage {
        constructor(vsWorker, seq, res, err) {
            this.vsWorker = vsWorker;
            this.seq = seq;
            this.res = res;
            this.err = err;
            this.type = 1 /* MessageType.Reply */;
        }
    }
    class SubscribeEventMessage {
        constructor(vsWorker, req, channel, eventName, arg) {
            this.vsWorker = vsWorker;
            this.req = req;
            this.channel = channel;
            this.eventName = eventName;
            this.arg = arg;
            this.type = 2 /* MessageType.SubscribeEvent */;
        }
    }
    class EventMessage {
        constructor(vsWorker, req, event) {
            this.vsWorker = vsWorker;
            this.req = req;
            this.event = event;
            this.type = 3 /* MessageType.Event */;
        }
    }
    class UnsubscribeEventMessage {
        constructor(vsWorker, req) {
            this.vsWorker = vsWorker;
            this.req = req;
            this.type = 4 /* MessageType.UnsubscribeEvent */;
        }
    }
    class SimpleWorkerProtocol {
        constructor(handler) {
            this._workerId = -1;
            this._handler = handler;
            this._lastSentReq = 0;
            this._pendingReplies = Object.create(null);
            this._pendingEmitters = new Map();
            this._pendingEvents = new Map();
        }
        setWorkerId(workerId) {
            this._workerId = workerId;
        }
        sendMessage(channel, method, args) {
            const req = String(++this._lastSentReq);
            return new Promise((resolve, reject) => {
                this._pendingReplies[req] = {
                    resolve: resolve,
                    reject: reject
                };
                this._send(new RequestMessage(this._workerId, req, channel, method, args));
            });
        }
        listen(channel, eventName, arg) {
            let req = null;
            const emitter = new event_1.Emitter({
                onWillAddFirstListener: () => {
                    req = String(++this._lastSentReq);
                    this._pendingEmitters.set(req, emitter);
                    this._send(new SubscribeEventMessage(this._workerId, req, channel, eventName, arg));
                },
                onDidRemoveLastListener: () => {
                    this._pendingEmitters.delete(req);
                    this._send(new UnsubscribeEventMessage(this._workerId, req));
                    req = null;
                }
            });
            return emitter.event;
        }
        handleMessage(message) {
            if (!message || !message.vsWorker) {
                return;
            }
            if (this._workerId !== -1 && message.vsWorker !== this._workerId) {
                return;
            }
            this._handleMessage(message);
        }
        createProxyToRemoteChannel(channel, sendMessageBarrier) {
            const handler = {
                get: (target, name) => {
                    if (typeof name === 'string' && !target[name]) {
                        if (propertyIsDynamicEvent(name)) { // onDynamic...
                            target[name] = (arg) => {
                                return this.listen(channel, name, arg);
                            };
                        }
                        else if (propertyIsEvent(name)) { // on...
                            target[name] = this.listen(channel, name, undefined);
                        }
                        else if (name.charCodeAt(0) === 36 /* CharCode.DollarSign */) { // $...
                            target[name] = async (...myArgs) => {
                                await sendMessageBarrier?.();
                                return this.sendMessage(channel, name, myArgs);
                            };
                        }
                    }
                    return target[name];
                }
            };
            return new Proxy(Object.create(null), handler);
        }
        _handleMessage(msg) {
            switch (msg.type) {
                case 1 /* MessageType.Reply */:
                    return this._handleReplyMessage(msg);
                case 0 /* MessageType.Request */:
                    return this._handleRequestMessage(msg);
                case 2 /* MessageType.SubscribeEvent */:
                    return this._handleSubscribeEventMessage(msg);
                case 3 /* MessageType.Event */:
                    return this._handleEventMessage(msg);
                case 4 /* MessageType.UnsubscribeEvent */:
                    return this._handleUnsubscribeEventMessage(msg);
            }
        }
        _handleReplyMessage(replyMessage) {
            if (!this._pendingReplies[replyMessage.seq]) {
                console.warn('Got reply to unknown seq');
                return;
            }
            const reply = this._pendingReplies[replyMessage.seq];
            delete this._pendingReplies[replyMessage.seq];
            if (replyMessage.err) {
                let err = replyMessage.err;
                if (replyMessage.err.$isError) {
                    err = new Error();
                    err.name = replyMessage.err.name;
                    err.message = replyMessage.err.message;
                    err.stack = replyMessage.err.stack;
                }
                reply.reject(err);
                return;
            }
            reply.resolve(replyMessage.res);
        }
        _handleRequestMessage(requestMessage) {
            const req = requestMessage.req;
            const result = this._handler.handleMessage(requestMessage.channel, requestMessage.method, requestMessage.args);
            result.then((r) => {
                this._send(new ReplyMessage(this._workerId, req, r, undefined));
            }, (e) => {
                if (e.detail instanceof Error) {
                    // Loading errors have a detail property that points to the actual error
                    e.detail = (0, errors_1.transformErrorForSerialization)(e.detail);
                }
                this._send(new ReplyMessage(this._workerId, req, undefined, (0, errors_1.transformErrorForSerialization)(e)));
            });
        }
        _handleSubscribeEventMessage(msg) {
            const req = msg.req;
            const disposable = this._handler.handleEvent(msg.channel, msg.eventName, msg.arg)((event) => {
                this._send(new EventMessage(this._workerId, req, event));
            });
            this._pendingEvents.set(req, disposable);
        }
        _handleEventMessage(msg) {
            if (!this._pendingEmitters.has(msg.req)) {
                console.warn('Got event for unknown req');
                return;
            }
            this._pendingEmitters.get(msg.req).fire(msg.event);
        }
        _handleUnsubscribeEventMessage(msg) {
            if (!this._pendingEvents.has(msg.req)) {
                console.warn('Got unsubscribe for unknown req');
                return;
            }
            this._pendingEvents.get(msg.req).dispose();
            this._pendingEvents.delete(msg.req);
        }
        _send(msg) {
            const transfer = [];
            if (msg.type === 0 /* MessageType.Request */) {
                for (let i = 0; i < msg.args.length; i++) {
                    if (msg.args[i] instanceof ArrayBuffer) {
                        transfer.push(msg.args[i]);
                    }
                }
            }
            else if (msg.type === 1 /* MessageType.Reply */) {
                if (msg.res instanceof ArrayBuffer) {
                    transfer.push(msg.res);
                }
            }
            this._handler.sendMessage(msg, transfer);
        }
    }
    /**
     * Main thread side
     */
    class SimpleWorkerClient extends lifecycle_1.Disposable {
        constructor(workerFactory, workerDescriptor) {
            super();
            this._localChannels = new Map();
            this._worker = this._register(workerFactory.create({
                amdModuleId: 'vs/base/common/worker/simpleWorker',
                esmModuleLocation: workerDescriptor.esmModuleLocation,
                label: workerDescriptor.label
            }, (msg) => {
                this._protocol.handleMessage(msg);
            }, (err) => {
                // in Firefox, web workers fail lazily :(
                // we will reject the proxy
                (0, errors_1.onUnexpectedError)(err);
            }));
            this._protocol = new SimpleWorkerProtocol({
                sendMessage: (msg, transfer) => {
                    this._worker.postMessage(msg, transfer);
                },
                handleMessage: (channel, method, args) => {
                    return this._handleMessage(channel, method, args);
                },
                handleEvent: (channel, eventName, arg) => {
                    return this._handleEvent(channel, eventName, arg);
                }
            });
            this._protocol.setWorkerId(this._worker.getId());
            // Gather loader configuration
            let loaderConfiguration = null;
            const globalRequire = globalThis.require;
            if (typeof globalRequire !== 'undefined' && typeof globalRequire.getConfig === 'function') {
                // Get the configuration from the Monaco AMD Loader
                loaderConfiguration = globalRequire.getConfig();
            }
            else if (typeof globalThis.requirejs !== 'undefined') {
                // Get the configuration from requirejs
                loaderConfiguration = globalThis.requirejs.s.contexts._.config;
            }
            // Send initialize message
            this._onModuleLoaded = this._protocol.sendMessage(DEFAULT_CHANNEL, INITIALIZE, [
                this._worker.getId(),
                JSON.parse(JSON.stringify(loaderConfiguration)),
                workerDescriptor.amdModuleId,
            ]);
            this.proxy = this._protocol.createProxyToRemoteChannel(DEFAULT_CHANNEL, async () => { await this._onModuleLoaded; });
            this._onModuleLoaded.catch((e) => {
                this._onError('Worker failed to load ' + workerDescriptor.amdModuleId, e);
            });
        }
        _handleMessage(channelName, method, args) {
            const channel = this._localChannels.get(channelName);
            if (!channel) {
                return Promise.reject(new Error(`Missing channel ${channelName} on main thread`));
            }
            if (typeof channel[method] !== 'function') {
                return Promise.reject(new Error(`Missing method ${method} on main thread channel ${channelName}`));
            }
            try {
                return Promise.resolve(channel[method].apply(channel, args));
            }
            catch (e) {
                return Promise.reject(e);
            }
        }
        _handleEvent(channelName, eventName, arg) {
            const channel = this._localChannels.get(channelName);
            if (!channel) {
                throw new Error(`Missing channel ${channelName} on main thread`);
            }
            if (propertyIsDynamicEvent(eventName)) {
                const event = channel[eventName].call(channel, arg);
                if (typeof event !== 'function') {
                    throw new Error(`Missing dynamic event ${eventName} on main thread channel ${channelName}.`);
                }
                return event;
            }
            if (propertyIsEvent(eventName)) {
                const event = channel[eventName];
                if (typeof event !== 'function') {
                    throw new Error(`Missing event ${eventName} on main thread channel ${channelName}.`);
                }
                return event;
            }
            throw new Error(`Malformed event name ${eventName}`);
        }
        setChannel(channel, handler) {
            this._localChannels.set(channel, handler);
        }
        _onError(message, error) {
            console.error(message);
            console.info(error);
        }
    }
    exports.SimpleWorkerClient = SimpleWorkerClient;
    function propertyIsEvent(name) {
        // Assume a property is an event if it has a form of "onSomething"
        return name[0] === 'o' && name[1] === 'n' && strings.isUpperAsciiLetter(name.charCodeAt(2));
    }
    function propertyIsDynamicEvent(name) {
        // Assume a property is a dynamic event (a method that returns an event) if it has a form of "onDynamicSomething"
        return /^onDynamic/.test(name) && strings.isUpperAsciiLetter(name.charCodeAt(9));
    }
    /**
     * Worker side
     */
    class SimpleWorkerServer {
        constructor(postMessage, requestHandlerFactory) {
            this._localChannels = new Map();
            this._remoteChannels = new Map();
            this._requestHandlerFactory = requestHandlerFactory;
            this._requestHandler = null;
            this._protocol = new SimpleWorkerProtocol({
                sendMessage: (msg, transfer) => {
                    postMessage(msg, transfer);
                },
                handleMessage: (channel, method, args) => this._handleMessage(channel, method, args),
                handleEvent: (channel, eventName, arg) => this._handleEvent(channel, eventName, arg)
            });
        }
        onmessage(msg) {
            this._protocol.handleMessage(msg);
        }
        _handleMessage(channel, method, args) {
            if (channel === DEFAULT_CHANNEL && method === INITIALIZE) {
                return this.initialize(args[0], args[1], args[2]);
            }
            const requestHandler = (channel === DEFAULT_CHANNEL ? this._requestHandler : this._localChannels.get(channel));
            if (!requestHandler) {
                return Promise.reject(new Error(`Missing channel ${channel} on worker thread`));
            }
            if (typeof requestHandler[method] !== 'function') {
                return Promise.reject(new Error(`Missing method ${method} on worker thread channel ${channel}`));
            }
            try {
                return Promise.resolve(requestHandler[method].apply(requestHandler, args));
            }
            catch (e) {
                return Promise.reject(e);
            }
        }
        _handleEvent(channel, eventName, arg) {
            const requestHandler = (channel === DEFAULT_CHANNEL ? this._requestHandler : this._localChannels.get(channel));
            if (!requestHandler) {
                throw new Error(`Missing channel ${channel} on worker thread`);
            }
            if (propertyIsDynamicEvent(eventName)) {
                const event = requestHandler[eventName].call(requestHandler, arg);
                if (typeof event !== 'function') {
                    throw new Error(`Missing dynamic event ${eventName} on request handler.`);
                }
                return event;
            }
            if (propertyIsEvent(eventName)) {
                const event = requestHandler[eventName];
                if (typeof event !== 'function') {
                    throw new Error(`Missing event ${eventName} on request handler.`);
                }
                return event;
            }
            throw new Error(`Malformed event name ${eventName}`);
        }
        getChannel(channel) {
            if (!this._remoteChannels.has(channel)) {
                const inst = this._protocol.createProxyToRemoteChannel(channel);
                this._remoteChannels.set(channel, inst);
            }
            return this._remoteChannels.get(channel);
        }
        async initialize(workerId, loaderConfig, moduleId) {
            this._protocol.setWorkerId(workerId);
            if (this._requestHandlerFactory) {
                // static request handler
                this._requestHandler = this._requestHandlerFactory(this);
                return;
            }
            if (loaderConfig) {
                // Remove 'baseUrl', handling it is beyond scope for now
                if (typeof loaderConfig.baseUrl !== 'undefined') {
                    delete loaderConfig['baseUrl'];
                }
                if (typeof loaderConfig.paths !== 'undefined') {
                    if (typeof loaderConfig.paths.vs !== 'undefined') {
                        delete loaderConfig.paths['vs'];
                    }
                }
                if (typeof loaderConfig.trustedTypesPolicy !== 'undefined') {
                    // don't use, it has been destroyed during serialize
                    delete loaderConfig['trustedTypesPolicy'];
                }
                // Since this is in a web worker, enable catching errors
                loaderConfig.catchError = true;
                globalThis.require.config(loaderConfig);
            }
            if (isESM) {
                const url = network_1.FileAccess.asBrowserUri(`${moduleId}.js`).toString(true);
                return new Promise((resolve_1, reject_1) => { require([`${url}`], resolve_1, reject_1); }).then((module) => {
                    this._requestHandler = module.create(this);
                    if (!this._requestHandler) {
                        throw new Error(`No RequestHandler!`);
                    }
                });
            }
            return new Promise((resolve, reject) => {
                // Use the global require to be sure to get the global config
                // ESM-comment-begin
                const req = (globalThis.require || require);
                // ESM-comment-end
                // ESM-uncomment-begin
                // const req = globalThis.require;
                // ESM-uncomment-end
                req([moduleId], (module) => {
                    this._requestHandler = module.create(this);
                    if (!this._requestHandler) {
                        reject(new Error(`No RequestHandler!`));
                        return;
                    }
                    resolve();
                }, reject);
            });
        }
    }
    exports.SimpleWorkerServer = SimpleWorkerServer;
    /**
     * Defines the worker entry point. Must be exported and named `create`.
     * @skipMangle
     */
    function create(postMessage) {
        return new SimpleWorkerServer(postMessage, null);
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[646/*vs/base/browser/defaultWorkerFactory*/], __M([1/*require*/,0/*exports*/,103/*vs/base/browser/trustedTypes*/,8/*vs/base/common/errors*/,42/*vs/base/common/network*/,361/*vs/base/common/worker/simpleWorker*/,2/*vs/base/common/lifecycle*/,13/*vs/base/common/arrays*/,3/*vs/nls*/]), function (require, exports, trustedTypes_1, errors_1, network_1, simpleWorker_1, lifecycle_1, arrays_1, nls_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.WorkerDescriptor = void 0;
    exports.createWebWorker = createWebWorker;
    // ESM-comment-begin
    const isESM = false;
    // ESM-comment-end
    // ESM-uncomment-begin
    // const isESM = true;
    // ESM-uncomment-end
    // Reuse the trusted types policy defined from worker bootstrap
    // when available.
    // Refs https://github.com/microsoft/vscode/issues/222193
    let ttPolicy;
    if (typeof self === 'object' && self.constructor && self.constructor.name === 'DedicatedWorkerGlobalScope' && globalThis.workerttPolicy !== undefined) {
        ttPolicy = globalThis.workerttPolicy;
    }
    else {
        ttPolicy = (0, trustedTypes_1.createTrustedTypesPolicy)('defaultWorkerFactory', { createScriptURL: value => value });
    }
    function getWorker(esmWorkerLocation, label) {
        const monacoEnvironment = globalThis.MonacoEnvironment;
        if (monacoEnvironment) {
            if (typeof monacoEnvironment.getWorker === 'function') {
                return monacoEnvironment.getWorker('workerMain.js', label);
            }
            if (typeof monacoEnvironment.getWorkerUrl === 'function') {
                const workerUrl = monacoEnvironment.getWorkerUrl('workerMain.js', label);
                return new Worker(ttPolicy ? ttPolicy.createScriptURL(workerUrl) : workerUrl, { name: label, type: isESM ? 'module' : undefined });
            }
        }
        // ESM-comment-begin
        if (typeof require === 'function') {
            const workerMainLocation = require.toUrl('vs/base/worker/workerMain.js'); // explicitly using require.toUrl(), see https://github.com/microsoft/vscode/issues/107440#issuecomment-698982321
            const factoryModuleId = 'vs/base/worker/defaultWorkerFactory.js';
            const workerBaseUrl = require.toUrl(factoryModuleId).slice(0, -factoryModuleId.length); // explicitly using require.toUrl(), see https://github.com/microsoft/vscode/issues/107440#issuecomment-698982321
            const workerUrl = getWorkerBootstrapUrl(label, workerMainLocation, workerBaseUrl);
            return new Worker(ttPolicy ? ttPolicy.createScriptURL(workerUrl) : workerUrl, { name: label, type: isESM ? 'module' : undefined });
        }
        // ESM-comment-end
        if (esmWorkerLocation) {
            const workerUrl = getWorkerBootstrapUrl(label, esmWorkerLocation.toString(true));
            const worker = new Worker(ttPolicy ? ttPolicy.createScriptURL(workerUrl) : workerUrl, { name: label, type: isESM ? 'module' : undefined });
            if (isESM) {
                return whenESMWorkerReady(worker);
            }
            else {
                return worker;
            }
        }
        throw new Error(`You must define a function MonacoEnvironment.getWorkerUrl or MonacoEnvironment.getWorker`);
    }
    function getWorkerBootstrapUrl(label, workerScriptUrl, workerBaseUrl) {
        const workerScriptUrlIsAbsolute = /^((http:)|(https:)|(file:)|(vscode-file:))/.test(workerScriptUrl);
        if (workerScriptUrlIsAbsolute && workerScriptUrl.substring(0, globalThis.origin.length) !== globalThis.origin) {
            // this is the cross-origin case
            // i.e. the webpage is running at a different origin than where the scripts are loaded from
        }
        else {
            const start = workerScriptUrl.lastIndexOf('?');
            const end = workerScriptUrl.lastIndexOf('#', start);
            const params = start > 0
                ? new URLSearchParams(workerScriptUrl.substring(start + 1, ~end ? end : undefined))
                : new URLSearchParams();
            network_1.COI.addSearchParam(params, true, true);
            const search = params.toString();
            if (!search) {
                workerScriptUrl = `${workerScriptUrl}#${label}`;
            }
            else {
                workerScriptUrl = `${workerScriptUrl}?${params.toString()}#${label}`;
            }
        }
        if (!isESM && !workerScriptUrlIsAbsolute) {
            // we have to convert relative script URLs to the origin because importScripts
            // does not work unless the script URL is absolute
            workerScriptUrl = new URL(workerScriptUrl, globalThis.origin).toString();
        }
        const blob = new Blob([(0, arrays_1.coalesce)([
                `/*${label}*/`,
                workerBaseUrl ? `globalThis.MonacoEnvironment = { baseUrl: '${workerBaseUrl}' };` : undefined,
                `globalThis._VSCODE_NLS_MESSAGES = ${JSON.stringify((0, nls_1.getNLSMessages)())};`,
                `globalThis._VSCODE_NLS_LANGUAGE = ${JSON.stringify((0, nls_1.getNLSLanguage)())};`,
                `globalThis._VSCODE_FILE_ROOT = '${globalThis._VSCODE_FILE_ROOT}';`,
                `const ttPolicy = globalThis.trustedTypes?.createPolicy('defaultWorkerFactory', { createScriptURL: value => value });`,
                `globalThis.workerttPolicy = ttPolicy;`,
                isESM ? `await import(ttPolicy?.createScriptURL('${workerScriptUrl}') ?? '${workerScriptUrl}');` : `importScripts(ttPolicy?.createScriptURL('${workerScriptUrl}') ?? '${workerScriptUrl}');`,
                isESM ? `globalThis.postMessage({ type: 'vscode-worker-ready' });` : undefined, // in ESM signal we are ready after the async import
                `/*${label}*/`
            ]).join('')], { type: 'application/javascript' });
        return URL.createObjectURL(blob);
    }
    function whenESMWorkerReady(worker) {
        return new Promise((resolve, reject) => {
            worker.onmessage = function (e) {
                if (e.data.type === 'vscode-worker-ready') {
                    worker.onmessage = null;
                    resolve(worker);
                }
            };
            worker.onerror = reject;
        });
    }
    function isPromiseLike(obj) {
        if (typeof obj.then === 'function') {
            return true;
        }
        return false;
    }
    /**
     * A worker that uses HTML5 web workers so that is has
     * its own global scope and its own thread.
     */
    class WebWorker extends lifecycle_1.Disposable {
        constructor(esmWorkerLocation, amdModuleId, id, label, onMessageCallback, onErrorCallback) {
            super();
            this.id = id;
            this.label = label;
            const workerOrPromise = getWorker(esmWorkerLocation, label);
            if (isPromiseLike(workerOrPromise)) {
                this.worker = workerOrPromise;
            }
            else {
                this.worker = Promise.resolve(workerOrPromise);
            }
            this.postMessage(amdModuleId, []);
            this.worker.then((w) => {
                w.onmessage = function (ev) {
                    onMessageCallback(ev.data);
                };
                w.onmessageerror = onErrorCallback;
                if (typeof w.addEventListener === 'function') {
                    w.addEventListener('error', onErrorCallback);
                }
            });
            this._register((0, lifecycle_1.toDisposable)(() => {
                this.worker?.then(w => {
                    w.onmessage = null;
                    w.onmessageerror = null;
                    w.removeEventListener('error', onErrorCallback);
                    w.terminate();
                });
                this.worker = null;
            }));
        }
        getId() {
            return this.id;
        }
        postMessage(message, transfer) {
            this.worker?.then(w => {
                try {
                    w.postMessage(message, transfer);
                }
                catch (err) {
                    (0, errors_1.onUnexpectedError)(err);
                    (0, errors_1.onUnexpectedError)(new Error(`FAILED to post message to '${this.label}'-worker`, { cause: err }));
                }
            });
        }
    }
    class WorkerDescriptor {
        constructor(amdModuleId, label) {
            this.amdModuleId = amdModuleId;
            this.label = label;
            this.esmModuleLocation = (isESM ? network_1.FileAccess.asBrowserUri(`${amdModuleId}.esm.js`) : undefined);
        }
    }
    exports.WorkerDescriptor = WorkerDescriptor;
    class DefaultWorkerFactory {
        static { this.LAST_WORKER_ID = 0; }
        constructor() {
            this._webWorkerFailedBeforeError = false;
        }
        create(desc, onMessageCallback, onErrorCallback) {
            const workerId = (++DefaultWorkerFactory.LAST_WORKER_ID);
            if (this._webWorkerFailedBeforeError) {
                throw this._webWorkerFailedBeforeError;
            }
            return new WebWorker(desc.esmModuleLocation, desc.amdModuleId, workerId, desc.label || 'anonymous' + workerId, onMessageCallback, (err) => {
                (0, simpleWorker_1.logOnceWebWorkerWarning)(err);
                this._webWorkerFailedBeforeError = err;
                onErrorCallback(err);
            });
        }
    }
    function createWebWorker(arg0, arg1) {
        const workerDescriptor = (typeof arg0 === 'string' ? new WorkerDescriptor(arg0, arg1) : arg0);
        return new simpleWorker_1.SimpleWorkerClient(new DefaultWorkerFactory(), workerDescriptor);
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[647/*vs/base/parts/storage/common/storage*/], __M([1/*require*/,0/*exports*/,14/*vs/base/common/async*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,252/*vs/base/common/marshalling*/,19/*vs/base/common/types*/]), function (require, exports, async_1, event_1, lifecycle_1, marshalling_1, types_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.InMemoryStorageDatabase = exports.Storage = exports.StorageState = exports.StorageHint = void 0;
    var StorageHint;
    (function (StorageHint) {
        // A hint to the storage that the storage
        // does not exist on disk yet. This allows
        // the storage library to improve startup
        // time by not checking the storage for data.
        StorageHint[StorageHint["STORAGE_DOES_NOT_EXIST"] = 0] = "STORAGE_DOES_NOT_EXIST";
        // A hint to the storage that the storage
        // is backed by an in-memory storage.
        StorageHint[StorageHint["STORAGE_IN_MEMORY"] = 1] = "STORAGE_IN_MEMORY";
    })(StorageHint || (exports.StorageHint = StorageHint = {}));
    var StorageState;
    (function (StorageState) {
        StorageState[StorageState["None"] = 0] = "None";
        StorageState[StorageState["Initialized"] = 1] = "Initialized";
        StorageState[StorageState["Closed"] = 2] = "Closed";
    })(StorageState || (exports.StorageState = StorageState = {}));
    class Storage extends lifecycle_1.Disposable {
        static { this.DEFAULT_FLUSH_DELAY = 100; }
        constructor(database, options = Object.create(null)) {
            super();
            this.database = database;
            this.options = options;
            this._onDidChangeStorage = this._register(new event_1.PauseableEmitter());
            this.onDidChangeStorage = this._onDidChangeStorage.event;
            this.state = StorageState.None;
            this.cache = new Map();
            this.flushDelayer = this._register(new async_1.ThrottledDelayer(Storage.DEFAULT_FLUSH_DELAY));
            this.pendingDeletes = new Set();
            this.pendingInserts = new Map();
            this.whenFlushedCallbacks = [];
            this.registerListeners();
        }
        registerListeners() {
            this._register(this.database.onDidChangeItemsExternal(e => this.onDidChangeItemsExternal(e)));
        }
        onDidChangeItemsExternal(e) {
            this._onDidChangeStorage.pause();
            try {
                // items that change external require us to update our
                // caches with the values. we just accept the value and
                // emit an event if there is a change.
                e.changed?.forEach((value, key) => this.acceptExternal(key, value));
                e.deleted?.forEach(key => this.acceptExternal(key, undefined));
            }
            finally {
                this._onDidChangeStorage.resume();
            }
        }
        acceptExternal(key, value) {
            if (this.state === StorageState.Closed) {
                return; // Return early if we are already closed
            }
            let changed = false;
            // Item got removed, check for deletion
            if ((0, types_1.isUndefinedOrNull)(value)) {
                changed = this.cache.delete(key);
            }
            // Item got updated, check for change
            else {
                const currentValue = this.cache.get(key);
                if (currentValue !== value) {
                    this.cache.set(key, value);
                    changed = true;
                }
            }
            // Signal to outside listeners
            if (changed) {
                this._onDidChangeStorage.fire({ key, external: true });
            }
        }
        get(key, fallbackValue) {
            const value = this.cache.get(key);
            if ((0, types_1.isUndefinedOrNull)(value)) {
                return fallbackValue;
            }
            return value;
        }
        getBoolean(key, fallbackValue) {
            const value = this.get(key);
            if ((0, types_1.isUndefinedOrNull)(value)) {
                return fallbackValue;
            }
            return value === 'true';
        }
        getNumber(key, fallbackValue) {
            const value = this.get(key);
            if ((0, types_1.isUndefinedOrNull)(value)) {
                return fallbackValue;
            }
            return parseInt(value, 10);
        }
        async set(key, value, external = false) {
            if (this.state === StorageState.Closed) {
                return; // Return early if we are already closed
            }
            // We remove the key for undefined/null values
            if ((0, types_1.isUndefinedOrNull)(value)) {
                return this.delete(key, external);
            }
            // Otherwise, convert to String and store
            const valueStr = (0, types_1.isObject)(value) || Array.isArray(value) ? (0, marshalling_1.stringify)(value) : String(value);
            // Return early if value already set
            const currentValue = this.cache.get(key);
            if (currentValue === valueStr) {
                return;
            }
            // Update in cache and pending
            this.cache.set(key, valueStr);
            this.pendingInserts.set(key, valueStr);
            this.pendingDeletes.delete(key);
            // Event
            this._onDidChangeStorage.fire({ key, external });
            // Accumulate work by scheduling after timeout
            return this.doFlush();
        }
        async delete(key, external = false) {
            if (this.state === StorageState.Closed) {
                return; // Return early if we are already closed
            }
            // Remove from cache and add to pending
            const wasDeleted = this.cache.delete(key);
            if (!wasDeleted) {
                return; // Return early if value already deleted
            }
            if (!this.pendingDeletes.has(key)) {
                this.pendingDeletes.add(key);
            }
            this.pendingInserts.delete(key);
            // Event
            this._onDidChangeStorage.fire({ key, external });
            // Accumulate work by scheduling after timeout
            return this.doFlush();
        }
        get hasPending() {
            return this.pendingInserts.size > 0 || this.pendingDeletes.size > 0;
        }
        async flushPending() {
            if (!this.hasPending) {
                return; // return early if nothing to do
            }
            // Get pending data
            const updateRequest = { insert: this.pendingInserts, delete: this.pendingDeletes };
            // Reset pending data for next run
            this.pendingDeletes = new Set();
            this.pendingInserts = new Map();
            // Update in storage and release any
            // waiters we have once done
            return this.database.updateItems(updateRequest).finally(() => {
                if (!this.hasPending) {
                    while (this.whenFlushedCallbacks.length) {
                        this.whenFlushedCallbacks.pop()?.();
                    }
                }
            });
        }
        async doFlush(delay) {
            if (this.options.hint === StorageHint.STORAGE_IN_MEMORY) {
                return this.flushPending(); // return early if in-memory
            }
            return this.flushDelayer.trigger(() => this.flushPending(), delay);
        }
    }
    exports.Storage = Storage;
    class InMemoryStorageDatabase {
        constructor() {
            this.onDidChangeItemsExternal = event_1.Event.None;
            this.items = new Map();
        }
        async updateItems(request) {
            request.insert?.forEach((value, key) => this.items.set(key, value));
            request.delete?.forEach(key => this.items.delete(key));
        }
    }
    exports.InMemoryStorageDatabase = InMemoryStorageDatabase;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[362/*vs/editor/browser/config/elementSizeObserver*/], __M([1/*require*/,0/*exports*/,2/*vs/base/common/lifecycle*/,6/*vs/base/common/event*/,5/*vs/base/browser/dom*/]), function (require, exports, lifecycle_1, event_1, dom_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ElementSizeObserver = void 0;
    class ElementSizeObserver extends lifecycle_1.Disposable {
        constructor(referenceDomElement, dimension) {
            super();
            this._onDidChange = this._register(new event_1.Emitter());
            this.onDidChange = this._onDidChange.event;
            this._referenceDomElement = referenceDomElement;
            this._width = -1;
            this._height = -1;
            this._resizeObserver = null;
            this.measureReferenceDomElement(false, dimension);
        }
        dispose() {
            this.stopObserving();
            super.dispose();
        }
        getWidth() {
            return this._width;
        }
        getHeight() {
            return this._height;
        }
        startObserving() {
            if (!this._resizeObserver && this._referenceDomElement) {
                // We want to react to the resize observer only once per animation frame
                // The first time the resize observer fires, we will react to it immediately.
                // Otherwise we will postpone to the next animation frame.
                // We'll use `observeContentRect` to store the content rect we received.
                let observedDimenstion = null;
                const observeNow = () => {
                    if (observedDimenstion) {
                        this.observe({ width: observedDimenstion.width, height: observedDimenstion.height });
                    }
                    else {
                        this.observe();
                    }
                };
                let shouldObserve = false;
                let alreadyObservedThisAnimationFrame = false;
                const update = () => {
                    if (shouldObserve && !alreadyObservedThisAnimationFrame) {
                        try {
                            shouldObserve = false;
                            alreadyObservedThisAnimationFrame = true;
                            observeNow();
                        }
                        finally {
                            (0, dom_1.scheduleAtNextAnimationFrame)((0, dom_1.getWindow)(this._referenceDomElement), () => {
                                alreadyObservedThisAnimationFrame = false;
                                update();
                            });
                        }
                    }
                };
                this._resizeObserver = new ResizeObserver((entries) => {
                    if (entries && entries[0] && entries[0].contentRect) {
                        observedDimenstion = { width: entries[0].contentRect.width, height: entries[0].contentRect.height };
                    }
                    else {
                        observedDimenstion = null;
                    }
                    shouldObserve = true;
                    update();
                });
                this._resizeObserver.observe(this._referenceDomElement);
            }
        }
        stopObserving() {
            if (this._resizeObserver) {
                this._resizeObserver.disconnect();
                this._resizeObserver = null;
            }
        }
        observe(dimension) {
            this.measureReferenceDomElement(true, dimension);
        }
        measureReferenceDomElement(emitEvent, dimension) {
            let observedWidth = 0;
            let observedHeight = 0;
            if (dimension) {
                observedWidth = dimension.width;
                observedHeight = dimension.height;
            }
            else if (this._referenceDomElement) {
                observedWidth = this._referenceDomElement.clientWidth;
                observedHeight = this._referenceDomElement.clientHeight;
            }
            observedWidth = Math.max(5, observedWidth);
            observedHeight = Math.max(5, observedHeight);
            if (this._width !== observedWidth || this._height !== observedHeight) {
                this._width = observedWidth;
                this._height = observedHeight;
                if (emitEvent) {
                    this._onDidChange.fire();
                }
            }
        }
    }
    exports.ElementSizeObserver = ElementSizeObserver;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[648/*vs/editor/browser/services/hoverService/updatableHoverWidget*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,18/*vs/base/common/cancellation*/,57/*vs/base/common/htmlContent*/,19/*vs/base/common/types*/,3/*vs/nls*/]), function (require, exports, dom_1, cancellation_1, htmlContent_1, types_1, nls_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ManagedHoverWidget = void 0;
    class ManagedHoverWidget {
        constructor(hoverDelegate, target, fadeInAnimation) {
            this.hoverDelegate = hoverDelegate;
            this.target = target;
            this.fadeInAnimation = fadeInAnimation;
        }
        async update(content, focus, options) {
            if (this._cancellationTokenSource) {
                // there's an computation ongoing, cancel it
                this._cancellationTokenSource.dispose(true);
                this._cancellationTokenSource = undefined;
            }
            if (this.isDisposed) {
                return;
            }
            let resolvedContent;
            if (content === undefined || (0, types_1.isString)(content) || (0, dom_1.isHTMLElement)(content)) {
                resolvedContent = content;
            }
            else if (!(0, types_1.isFunction)(content.markdown)) {
                resolvedContent = content.markdown ?? content.markdownNotSupportedFallback;
            }
            else {
                // compute the content, potentially long-running
                // show 'Loading' if no hover is up yet
                if (!this._hoverWidget) {
                    this.show((0, nls_1.localize)(69, "Loading..."), focus, options);
                }
                // compute the content
                this._cancellationTokenSource = new cancellation_1.CancellationTokenSource();
                const token = this._cancellationTokenSource.token;
                resolvedContent = await content.markdown(token);
                if (resolvedContent === undefined) {
                    resolvedContent = content.markdownNotSupportedFallback;
                }
                if (this.isDisposed || token.isCancellationRequested) {
                    // either the widget has been closed in the meantime
                    // or there has been a new call to `update`
                    return;
                }
            }
            this.show(resolvedContent, focus, options);
        }
        show(content, focus, options) {
            const oldHoverWidget = this._hoverWidget;
            if (this.hasContent(content)) {
                const hoverOptions = {
                    content,
                    target: this.target,
                    actions: options?.actions,
                    linkHandler: options?.linkHandler,
                    trapFocus: options?.trapFocus,
                    appearance: {
                        showPointer: this.hoverDelegate.placement === 'element',
                        skipFadeInAnimation: !this.fadeInAnimation || !!oldHoverWidget, // do not fade in if the hover is already showing
                        showHoverHint: options?.appearance?.showHoverHint,
                    },
                    position: {
                        hoverPosition: 2 /* HoverPosition.BELOW */,
                    },
                };
                this._hoverWidget = this.hoverDelegate.showHover(hoverOptions, focus);
            }
            oldHoverWidget?.dispose();
        }
        hasContent(content) {
            if (!content) {
                return false;
            }
            if ((0, htmlContent_1.isMarkdownString)(content)) {
                return !!content.value;
            }
            return true;
        }
        get isDisposed() {
            return this._hoverWidget?.isDisposed;
        }
        dispose() {
            this._hoverWidget?.dispose();
            this._cancellationTokenSource?.dispose(true);
            this._cancellationTokenSource = undefined;
        }
    }
    exports.ManagedHoverWidget = ManagedHoverWidget;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[649/*vs/editor/browser/viewParts/contentWidgets/contentWidgets*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,39/*vs/base/browser/fastDomNode*/,56/*vs/editor/browser/view/viewPart*/]), function (require, exports, dom, fastDomNode_1, viewPart_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ViewContentWidgets = void 0;
    class ViewContentWidgets extends viewPart_1.ViewPart {
        constructor(context, viewDomNode) {
            super(context);
            this._viewDomNode = viewDomNode;
            this._widgets = {};
            this.domNode = (0, fastDomNode_1.createFastDomNode)(document.createElement('div'));
            viewPart_1.PartFingerprints.write(this.domNode, 1 /* PartFingerprint.ContentWidgets */);
            this.domNode.setClassName('contentWidgets');
            this.domNode.setPosition('absolute');
            this.domNode.setTop(0);
            this.overflowingContentWidgetsDomNode = (0, fastDomNode_1.createFastDomNode)(document.createElement('div'));
            viewPart_1.PartFingerprints.write(this.overflowingContentWidgetsDomNode, 2 /* PartFingerprint.OverflowingContentWidgets */);
            this.overflowingContentWidgetsDomNode.setClassName('overflowingContentWidgets');
        }
        dispose() {
            super.dispose();
            this._widgets = {};
        }
        // --- begin event handlers
        onConfigurationChanged(e) {
            const keys = Object.keys(this._widgets);
            for (const widgetId of keys) {
                this._widgets[widgetId].onConfigurationChanged(e);
            }
            return true;
        }
        onDecorationsChanged(e) {
            // true for inline decorations that can end up relayouting text
            return true;
        }
        onFlushed(e) {
            return true;
        }
        onLineMappingChanged(e) {
            this._updateAnchorsViewPositions();
            return true;
        }
        onLinesChanged(e) {
            this._updateAnchorsViewPositions();
            return true;
        }
        onLinesDeleted(e) {
            this._updateAnchorsViewPositions();
            return true;
        }
        onLinesInserted(e) {
            this._updateAnchorsViewPositions();
            return true;
        }
        onScrollChanged(e) {
            return true;
        }
        onZonesChanged(e) {
            return true;
        }
        // ---- end view event handlers
        _updateAnchorsViewPositions() {
            const keys = Object.keys(this._widgets);
            for (const widgetId of keys) {
                this._widgets[widgetId].updateAnchorViewPosition();
            }
        }
        addWidget(_widget) {
            const myWidget = new Widget(this._context, this._viewDomNode, _widget);
            this._widgets[myWidget.id] = myWidget;
            if (myWidget.allowEditorOverflow) {
                this.overflowingContentWidgetsDomNode.appendChild(myWidget.domNode);
            }
            else {
                this.domNode.appendChild(myWidget.domNode);
            }
            this.setShouldRender();
        }
        setWidgetPosition(widget, primaryAnchor, secondaryAnchor, preference, affinity) {
            const myWidget = this._widgets[widget.getId()];
            myWidget.setPosition(primaryAnchor, secondaryAnchor, preference, affinity);
            this.setShouldRender();
        }
        removeWidget(widget) {
            const widgetId = widget.getId();
            if (this._widgets.hasOwnProperty(widgetId)) {
                const myWidget = this._widgets[widgetId];
                delete this._widgets[widgetId];
                const domNode = myWidget.domNode.domNode;
                domNode.remove();
                domNode.removeAttribute('monaco-visible-content-widget');
                this.setShouldRender();
            }
        }
        shouldSuppressMouseDownOnWidget(widgetId) {
            if (this._widgets.hasOwnProperty(widgetId)) {
                return this._widgets[widgetId].suppressMouseDown;
            }
            return false;
        }
        onBeforeRender(viewportData) {
            const keys = Object.keys(this._widgets);
            for (const widgetId of keys) {
                this._widgets[widgetId].onBeforeRender(viewportData);
            }
        }
        prepareRender(ctx) {
            const keys = Object.keys(this._widgets);
            for (const widgetId of keys) {
                this._widgets[widgetId].prepareRender(ctx);
            }
        }
        render(ctx) {
            const keys = Object.keys(this._widgets);
            for (const widgetId of keys) {
                this._widgets[widgetId].render(ctx);
            }
        }
    }
    exports.ViewContentWidgets = ViewContentWidgets;
    class Widget {
        constructor(context, viewDomNode, actual) {
            this._primaryAnchor = new PositionPair(null, null);
            this._secondaryAnchor = new PositionPair(null, null);
            this._context = context;
            this._viewDomNode = viewDomNode;
            this._actual = actual;
            this.domNode = (0, fastDomNode_1.createFastDomNode)(this._actual.getDomNode());
            this.id = this._actual.getId();
            this.allowEditorOverflow = this._actual.allowEditorOverflow || false;
            this.suppressMouseDown = this._actual.suppressMouseDown || false;
            const options = this._context.configuration.options;
            const layoutInfo = options.get(146 /* EditorOption.layoutInfo */);
            this._fixedOverflowWidgets = options.get(42 /* EditorOption.fixedOverflowWidgets */);
            this._contentWidth = layoutInfo.contentWidth;
            this._contentLeft = layoutInfo.contentLeft;
            this._lineHeight = options.get(67 /* EditorOption.lineHeight */);
            this._affinity = null;
            this._preference = [];
            this._cachedDomNodeOffsetWidth = -1;
            this._cachedDomNodeOffsetHeight = -1;
            this._maxWidth = this._getMaxWidth();
            this._isVisible = false;
            this._renderData = null;
            this.domNode.setPosition((this._fixedOverflowWidgets && this.allowEditorOverflow) ? 'fixed' : 'absolute');
            this.domNode.setDisplay('none');
            this.domNode.setVisibility('hidden');
            this.domNode.setAttribute('widgetId', this.id);
            this.domNode.setMaxWidth(this._maxWidth);
        }
        onConfigurationChanged(e) {
            const options = this._context.configuration.options;
            this._lineHeight = options.get(67 /* EditorOption.lineHeight */);
            if (e.hasChanged(146 /* EditorOption.layoutInfo */)) {
                const layoutInfo = options.get(146 /* EditorOption.layoutInfo */);
                this._contentLeft = layoutInfo.contentLeft;
                this._contentWidth = layoutInfo.contentWidth;
                this._maxWidth = this._getMaxWidth();
            }
        }
        updateAnchorViewPosition() {
            this._setPosition(this._affinity, this._primaryAnchor.modelPosition, this._secondaryAnchor.modelPosition);
        }
        _setPosition(affinity, primaryAnchor, secondaryAnchor) {
            this._affinity = affinity;
            this._primaryAnchor = getValidPositionPair(primaryAnchor, this._context.viewModel, this._affinity);
            this._secondaryAnchor = getValidPositionPair(secondaryAnchor, this._context.viewModel, this._affinity);
            function getValidPositionPair(position, viewModel, affinity) {
                if (!position) {
                    return new PositionPair(null, null);
                }
                // Do not trust that widgets give a valid position
                const validModelPosition = viewModel.model.validatePosition(position);
                if (viewModel.coordinatesConverter.modelPositionIsVisible(validModelPosition)) {
                    const viewPosition = viewModel.coordinatesConverter.convertModelPositionToViewPosition(validModelPosition, affinity ?? undefined);
                    return new PositionPair(position, viewPosition);
                }
                return new PositionPair(position, null);
            }
        }
        _getMaxWidth() {
            const elDocument = this.domNode.domNode.ownerDocument;
            const elWindow = elDocument.defaultView;
            return (this.allowEditorOverflow
                ? elWindow?.innerWidth || elDocument.documentElement.offsetWidth || elDocument.body.offsetWidth
                : this._contentWidth);
        }
        setPosition(primaryAnchor, secondaryAnchor, preference, affinity) {
            this._setPosition(affinity, primaryAnchor, secondaryAnchor);
            this._preference = preference;
            if (this._primaryAnchor.viewPosition && this._preference && this._preference.length > 0) {
                // this content widget would like to be visible if possible
                // we change it from `display:none` to `display:block` even if it
                // might be outside the viewport such that we can measure its size
                // in `prepareRender`
                this.domNode.setDisplay('block');
            }
            else {
                this.domNode.setDisplay('none');
            }
            this._cachedDomNodeOffsetWidth = -1;
            this._cachedDomNodeOffsetHeight = -1;
        }
        _layoutBoxInViewport(anchor, width, height, ctx) {
            // Our visible box is split horizontally by the current line => 2 boxes
            // a) the box above the line
            const aboveLineTop = anchor.top;
            const heightAvailableAboveLine = aboveLineTop;
            // b) the box under the line
            const underLineTop = anchor.top + anchor.height;
            const heightAvailableUnderLine = ctx.viewportHeight - underLineTop;
            const aboveTop = aboveLineTop - height;
            const fitsAbove = (heightAvailableAboveLine >= height);
            const belowTop = underLineTop;
            const fitsBelow = (heightAvailableUnderLine >= height);
            // And its left
            let left = anchor.left;
            if (left + width > ctx.scrollLeft + ctx.viewportWidth) {
                left = ctx.scrollLeft + ctx.viewportWidth - width;
            }
            if (left < ctx.scrollLeft) {
                left = ctx.scrollLeft;
            }
            return { fitsAbove, aboveTop, fitsBelow, belowTop, left };
        }
        _layoutHorizontalSegmentInPage(windowSize, domNodePosition, left, width) {
            // Leave some clearance to the left/right
            const LEFT_PADDING = 15;
            const RIGHT_PADDING = 15;
            // Initially, the limits are defined as the dom node limits
            const MIN_LIMIT = Math.max(LEFT_PADDING, domNodePosition.left - width);
            const MAX_LIMIT = Math.min(domNodePosition.left + domNodePosition.width + width, windowSize.width - RIGHT_PADDING);
            const elDocument = this._viewDomNode.domNode.ownerDocument;
            const elWindow = elDocument.defaultView;
            let absoluteLeft = domNodePosition.left + left - (elWindow?.scrollX ?? 0);
            if (absoluteLeft + width > MAX_LIMIT) {
                const delta = absoluteLeft - (MAX_LIMIT - width);
                absoluteLeft -= delta;
                left -= delta;
            }
            if (absoluteLeft < MIN_LIMIT) {
                const delta = absoluteLeft - MIN_LIMIT;
                absoluteLeft -= delta;
                left -= delta;
            }
            return [left, absoluteLeft];
        }
        _layoutBoxInPage(anchor, width, height, ctx) {
            const aboveTop = anchor.top - height;
            const belowTop = anchor.top + anchor.height;
            const domNodePosition = dom.getDomNodePagePosition(this._viewDomNode.domNode);
            const elDocument = this._viewDomNode.domNode.ownerDocument;
            const elWindow = elDocument.defaultView;
            const absoluteAboveTop = domNodePosition.top + aboveTop - (elWindow?.scrollY ?? 0);
            const absoluteBelowTop = domNodePosition.top + belowTop - (elWindow?.scrollY ?? 0);
            const windowSize = dom.getClientArea(elDocument.body);
            const [left, absoluteAboveLeft] = this._layoutHorizontalSegmentInPage(windowSize, domNodePosition, anchor.left - ctx.scrollLeft + this._contentLeft, width);
            // Leave some clearance to the top/bottom
            const TOP_PADDING = 22;
            const BOTTOM_PADDING = 22;
            const fitsAbove = (absoluteAboveTop >= TOP_PADDING);
            const fitsBelow = (absoluteBelowTop + height <= windowSize.height - BOTTOM_PADDING);
            if (this._fixedOverflowWidgets) {
                return {
                    fitsAbove,
                    aboveTop: Math.max(absoluteAboveTop, TOP_PADDING),
                    fitsBelow,
                    belowTop: absoluteBelowTop,
                    left: absoluteAboveLeft
                };
            }
            return { fitsAbove, aboveTop, fitsBelow, belowTop, left };
        }
        _prepareRenderWidgetAtExactPositionOverflowing(topLeft) {
            return new Coordinate(topLeft.top, topLeft.left + this._contentLeft);
        }
        /**
         * Compute the coordinates above and below the primary and secondary anchors.
         * The content widget *must* touch the primary anchor.
         * The content widget should touch if possible the secondary anchor.
         */
        _getAnchorsCoordinates(ctx) {
            const primary = getCoordinates(this._primaryAnchor.viewPosition, this._affinity, this._lineHeight);
            const secondaryViewPosition = (this._secondaryAnchor.viewPosition?.lineNumber === this._primaryAnchor.viewPosition?.lineNumber ? this._secondaryAnchor.viewPosition : null);
            const secondary = getCoordinates(secondaryViewPosition, this._affinity, this._lineHeight);
            return { primary, secondary };
            function getCoordinates(position, affinity, lineHeight) {
                if (!position) {
                    return null;
                }
                const horizontalPosition = ctx.visibleRangeForPosition(position);
                if (!horizontalPosition) {
                    return null;
                }
                // Left-align widgets that should appear :before content
                const left = (position.column === 1 && affinity === 3 /* PositionAffinity.LeftOfInjectedText */ ? 0 : horizontalPosition.left);
                const top = ctx.getVerticalOffsetForLineNumber(position.lineNumber) - ctx.scrollTop;
                return new AnchorCoordinate(top, left, lineHeight);
            }
        }
        _reduceAnchorCoordinates(primary, secondary, width) {
            if (!secondary) {
                return primary;
            }
            const fontInfo = this._context.configuration.options.get(50 /* EditorOption.fontInfo */);
            let left = secondary.left;
            if (left < primary.left) {
                left = Math.max(left, primary.left - width + fontInfo.typicalFullwidthCharacterWidth);
            }
            else {
                left = Math.min(left, primary.left + width - fontInfo.typicalFullwidthCharacterWidth);
            }
            return new AnchorCoordinate(primary.top, left, primary.height);
        }
        _prepareRenderWidget(ctx) {
            if (!this._preference || this._preference.length === 0) {
                return null;
            }
            const { primary, secondary } = this._getAnchorsCoordinates(ctx);
            if (!primary) {
                return {
                    kind: 'offViewport',
                    preserveFocus: this.domNode.domNode.contains(this.domNode.domNode.ownerDocument.activeElement)
                };
                // return null;
            }
            if (this._cachedDomNodeOffsetWidth === -1 || this._cachedDomNodeOffsetHeight === -1) {
                let preferredDimensions = null;
                if (typeof this._actual.beforeRender === 'function') {
                    preferredDimensions = safeInvoke(this._actual.beforeRender, this._actual);
                }
                if (preferredDimensions) {
                    this._cachedDomNodeOffsetWidth = preferredDimensions.width;
                    this._cachedDomNodeOffsetHeight = preferredDimensions.height;
                }
                else {
                    const domNode = this.domNode.domNode;
                    const clientRect = domNode.getBoundingClientRect();
                    this._cachedDomNodeOffsetWidth = Math.round(clientRect.width);
                    this._cachedDomNodeOffsetHeight = Math.round(clientRect.height);
                }
            }
            const anchor = this._reduceAnchorCoordinates(primary, secondary, this._cachedDomNodeOffsetWidth);
            let placement;
            if (this.allowEditorOverflow) {
                placement = this._layoutBoxInPage(anchor, this._cachedDomNodeOffsetWidth, this._cachedDomNodeOffsetHeight, ctx);
            }
            else {
                placement = this._layoutBoxInViewport(anchor, this._cachedDomNodeOffsetWidth, this._cachedDomNodeOffsetHeight, ctx);
            }
            // Do two passes, first for perfect fit, second picks first option
            for (let pass = 1; pass <= 2; pass++) {
                for (const pref of this._preference) {
                    // placement
                    if (pref === 1 /* ContentWidgetPositionPreference.ABOVE */) {
                        if (!placement) {
                            // Widget outside of viewport
                            return null;
                        }
                        if (pass === 2 || placement.fitsAbove) {
                            return {
                                kind: 'inViewport',
                                coordinate: new Coordinate(placement.aboveTop, placement.left),
                                position: 1 /* ContentWidgetPositionPreference.ABOVE */
                            };
                        }
                    }
                    else if (pref === 2 /* ContentWidgetPositionPreference.BELOW */) {
                        if (!placement) {
                            // Widget outside of viewport
                            return null;
                        }
                        if (pass === 2 || placement.fitsBelow) {
                            return {
                                kind: 'inViewport',
                                coordinate: new Coordinate(placement.belowTop, placement.left),
                                position: 2 /* ContentWidgetPositionPreference.BELOW */
                            };
                        }
                    }
                    else {
                        if (this.allowEditorOverflow) {
                            return {
                                kind: 'inViewport',
                                coordinate: this._prepareRenderWidgetAtExactPositionOverflowing(new Coordinate(anchor.top, anchor.left)),
                                position: 0 /* ContentWidgetPositionPreference.EXACT */
                            };
                        }
                        else {
                            return {
                                kind: 'inViewport',
                                coordinate: new Coordinate(anchor.top, anchor.left),
                                position: 0 /* ContentWidgetPositionPreference.EXACT */
                            };
                        }
                    }
                }
            }
            return null;
        }
        /**
         * On this first pass, we ensure that the content widget (if it is in the viewport) has the max width set correctly.
         */
        onBeforeRender(viewportData) {
            if (!this._primaryAnchor.viewPosition || !this._preference) {
                return;
            }
            if (this._primaryAnchor.viewPosition.lineNumber < viewportData.startLineNumber || this._primaryAnchor.viewPosition.lineNumber > viewportData.endLineNumber) {
                // Outside of viewport
                return;
            }
            this.domNode.setMaxWidth(this._maxWidth);
        }
        prepareRender(ctx) {
            this._renderData = this._prepareRenderWidget(ctx);
        }
        render(ctx) {
            if (!this._renderData || this._renderData.kind === 'offViewport') {
                // This widget should be invisible
                if (this._isVisible) {
                    this.domNode.removeAttribute('monaco-visible-content-widget');
                    this._isVisible = false;
                    if (this._renderData?.kind === 'offViewport' && this._renderData.preserveFocus) {
                        // widget wants to be shown, but it is outside of the viewport and it
                        // has focus which we need to preserve
                        this.domNode.setTop(-1000);
                    }
                    else {
                        this.domNode.setVisibility('hidden');
                    }
                }
                if (typeof this._actual.afterRender === 'function') {
                    safeInvoke(this._actual.afterRender, this._actual, null);
                }
                return;
            }
            // This widget should be visible
            if (this.allowEditorOverflow) {
                this.domNode.setTop(this._renderData.coordinate.top);
                this.domNode.setLeft(this._renderData.coordinate.left);
            }
            else {
                this.domNode.setTop(this._renderData.coordinate.top + ctx.scrollTop - ctx.bigNumbersDelta);
                this.domNode.setLeft(this._renderData.coordinate.left);
            }
            if (!this._isVisible) {
                this.domNode.setVisibility('inherit');
                this.domNode.setAttribute('monaco-visible-content-widget', 'true');
                this._isVisible = true;
            }
            if (typeof this._actual.afterRender === 'function') {
                safeInvoke(this._actual.afterRender, this._actual, this._renderData.position);
            }
        }
    }
    class PositionPair {
        constructor(modelPosition, viewPosition) {
            this.modelPosition = modelPosition;
            this.viewPosition = viewPosition;
        }
    }
    class Coordinate {
        constructor(top, left) {
            this.top = top;
            this.left = left;
            this._coordinateBrand = undefined;
        }
    }
    class AnchorCoordinate {
        constructor(top, left, height) {
            this.top = top;
            this.left = left;
            this.height = height;
            this._anchorCoordinateBrand = undefined;
        }
    }
    function safeInvoke(fn, thisArg, ...args) {
        try {
            return fn.call(thisArg, ...args);
        }
        catch {
            // ignore
            return null;
        }
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[650/*vs/editor/browser/viewParts/overlayWidgets/overlayWidgets*/], __M([1/*require*/,0/*exports*/,39/*vs/base/browser/fastDomNode*/,56/*vs/editor/browser/view/viewPart*/,5/*vs/base/browser/dom*/,492/*vs/css!vs/editor/browser/viewParts/overlayWidgets/overlayWidgets*/]), function (require, exports, fastDomNode_1, viewPart_1, dom) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ViewOverlayWidgets = void 0;
    class ViewOverlayWidgets extends viewPart_1.ViewPart {
        constructor(context, viewDomNode) {
            super(context);
            this._viewDomNode = viewDomNode;
            const options = this._context.configuration.options;
            const layoutInfo = options.get(146 /* EditorOption.layoutInfo */);
            this._widgets = {};
            this._verticalScrollbarWidth = layoutInfo.verticalScrollbarWidth;
            this._minimapWidth = layoutInfo.minimap.minimapWidth;
            this._horizontalScrollbarHeight = layoutInfo.horizontalScrollbarHeight;
            this._editorHeight = layoutInfo.height;
            this._editorWidth = layoutInfo.width;
            this._viewDomNodeRect = { top: 0, left: 0, width: 0, height: 0 };
            this._domNode = (0, fastDomNode_1.createFastDomNode)(document.createElement('div'));
            viewPart_1.PartFingerprints.write(this._domNode, 4 /* PartFingerprint.OverlayWidgets */);
            this._domNode.setClassName('overlayWidgets');
            this.overflowingOverlayWidgetsDomNode = (0, fastDomNode_1.createFastDomNode)(document.createElement('div'));
            viewPart_1.PartFingerprints.write(this.overflowingOverlayWidgetsDomNode, 5 /* PartFingerprint.OverflowingOverlayWidgets */);
            this.overflowingOverlayWidgetsDomNode.setClassName('overflowingOverlayWidgets');
        }
        dispose() {
            super.dispose();
            this._widgets = {};
        }
        getDomNode() {
            return this._domNode;
        }
        // ---- begin view event handlers
        onConfigurationChanged(e) {
            const options = this._context.configuration.options;
            const layoutInfo = options.get(146 /* EditorOption.layoutInfo */);
            this._verticalScrollbarWidth = layoutInfo.verticalScrollbarWidth;
            this._minimapWidth = layoutInfo.minimap.minimapWidth;
            this._horizontalScrollbarHeight = layoutInfo.horizontalScrollbarHeight;
            this._editorHeight = layoutInfo.height;
            this._editorWidth = layoutInfo.width;
            return true;
        }
        // ---- end view event handlers
        addWidget(widget) {
            const domNode = (0, fastDomNode_1.createFastDomNode)(widget.getDomNode());
            this._widgets[widget.getId()] = {
                widget: widget,
                preference: null,
                domNode: domNode
            };
            // This is sync because a widget wants to be in the dom
            domNode.setPosition('absolute');
            domNode.setAttribute('widgetId', widget.getId());
            if (widget.allowEditorOverflow) {
                this.overflowingOverlayWidgetsDomNode.appendChild(domNode);
            }
            else {
                this._domNode.appendChild(domNode);
            }
            this.setShouldRender();
            this._updateMaxMinWidth();
        }
        setWidgetPosition(widget, position) {
            const widgetData = this._widgets[widget.getId()];
            const preference = position ? position.preference : null;
            const stack = position?.stackOridinal;
            if (widgetData.preference === preference && widgetData.stack === stack) {
                this._updateMaxMinWidth();
                return false;
            }
            widgetData.preference = preference;
            widgetData.stack = stack;
            this.setShouldRender();
            this._updateMaxMinWidth();
            return true;
        }
        removeWidget(widget) {
            const widgetId = widget.getId();
            if (this._widgets.hasOwnProperty(widgetId)) {
                const widgetData = this._widgets[widgetId];
                const domNode = widgetData.domNode.domNode;
                delete this._widgets[widgetId];
                domNode.remove();
                this.setShouldRender();
                this._updateMaxMinWidth();
            }
        }
        _updateMaxMinWidth() {
            let maxMinWidth = 0;
            const keys = Object.keys(this._widgets);
            for (let i = 0, len = keys.length; i < len; i++) {
                const widgetId = keys[i];
                const widget = this._widgets[widgetId];
                const widgetMinWidthInPx = widget.widget.getMinContentWidthInPx?.();
                if (typeof widgetMinWidthInPx !== 'undefined') {
                    maxMinWidth = Math.max(maxMinWidth, widgetMinWidthInPx);
                }
            }
            this._context.viewLayout.setOverlayWidgetsMinWidth(maxMinWidth);
        }
        _renderWidget(widgetData, stackCoordinates) {
            const domNode = widgetData.domNode;
            if (widgetData.preference === null) {
                domNode.setTop('');
                return;
            }
            const maxRight = (2 * this._verticalScrollbarWidth) + this._minimapWidth;
            if (widgetData.preference === 0 /* OverlayWidgetPositionPreference.TOP_RIGHT_CORNER */ || widgetData.preference === 1 /* OverlayWidgetPositionPreference.BOTTOM_RIGHT_CORNER */) {
                if (widgetData.preference === 1 /* OverlayWidgetPositionPreference.BOTTOM_RIGHT_CORNER */) {
                    const widgetHeight = domNode.domNode.clientHeight;
                    domNode.setTop((this._editorHeight - widgetHeight - 2 * this._horizontalScrollbarHeight));
                }
                else {
                    domNode.setTop(0);
                }
                if (widgetData.stack !== undefined) {
                    domNode.setTop(stackCoordinates[widgetData.preference]);
                    stackCoordinates[widgetData.preference] += domNode.domNode.clientWidth;
                }
                else {
                    domNode.setRight(maxRight);
                }
            }
            else if (widgetData.preference === 2 /* OverlayWidgetPositionPreference.TOP_CENTER */) {
                domNode.domNode.style.right = '50%';
                if (widgetData.stack !== undefined) {
                    domNode.setTop(stackCoordinates[2 /* OverlayWidgetPositionPreference.TOP_CENTER */]);
                    stackCoordinates[2 /* OverlayWidgetPositionPreference.TOP_CENTER */] += domNode.domNode.clientHeight;
                }
                else {
                    domNode.setTop(0);
                }
            }
            else {
                const { top, left } = widgetData.preference;
                const fixedOverflowWidgets = this._context.configuration.options.get(42 /* EditorOption.fixedOverflowWidgets */);
                if (fixedOverflowWidgets && widgetData.widget.allowEditorOverflow) {
                    // top, left are computed relative to the editor and we need them relative to the page
                    const editorBoundingBox = this._viewDomNodeRect;
                    domNode.setTop(top + editorBoundingBox.top);
                    domNode.setLeft(left + editorBoundingBox.left);
                    domNode.setPosition('fixed');
                }
                else {
                    domNode.setTop(top);
                    domNode.setLeft(left);
                    domNode.setPosition('absolute');
                }
            }
        }
        prepareRender(ctx) {
            this._viewDomNodeRect = dom.getDomNodePagePosition(this._viewDomNode.domNode);
        }
        render(ctx) {
            this._domNode.setWidth(this._editorWidth);
            const keys = Object.keys(this._widgets);
            const stackCoordinates = Array.from({ length: 2 /* OverlayWidgetPositionPreference.TOP_CENTER */ + 1 }, () => 0);
            keys.sort((a, b) => (this._widgets[a].stack || 0) - (this._widgets[b].stack || 0));
            for (let i = 0, len = keys.length; i < len; i++) {
                const widgetId = keys[i];
                this._renderWidget(this._widgets[widgetId], stackCoordinates);
            }
        }
    }
    exports.ViewOverlayWidgets = ViewOverlayWidgets;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[651/*vs/editor/browser/widget/codeEditor/codeEditorContributions*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,8/*vs/base/common/errors*/,2/*vs/base/common/lifecycle*/]), function (require, exports, dom_1, errors_1, lifecycle_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CodeEditorContributions = void 0;
    class CodeEditorContributions extends lifecycle_1.Disposable {
        constructor() {
            super();
            this._editor = null;
            this._instantiationService = null;
            /**
             * Contains all instantiated contributions.
             */
            this._instances = this._register(new lifecycle_1.DisposableMap());
            /**
             * Contains contributions which are not yet instantiated.
             */
            this._pending = new Map();
            /**
             * Tracks which instantiation kinds are still left in `_pending`.
             */
            this._finishedInstantiation = [];
            this._finishedInstantiation[0 /* EditorContributionInstantiation.Eager */] = false;
            this._finishedInstantiation[1 /* EditorContributionInstantiation.AfterFirstRender */] = false;
            this._finishedInstantiation[2 /* EditorContributionInstantiation.BeforeFirstInteraction */] = false;
            this._finishedInstantiation[3 /* EditorContributionInstantiation.Eventually */] = false;
        }
        initialize(editor, contributions, instantiationService) {
            this._editor = editor;
            this._instantiationService = instantiationService;
            for (const desc of contributions) {
                if (this._pending.has(desc.id)) {
                    (0, errors_1.onUnexpectedError)(new Error(`Cannot have two contributions with the same id ${desc.id}`));
                    continue;
                }
                this._pending.set(desc.id, desc);
            }
            this._instantiateSome(0 /* EditorContributionInstantiation.Eager */);
            // AfterFirstRender
            // - these extensions will be instantiated at the latest 50ms after the first render.
            // - but if there is idle time, we will instantiate them sooner.
            this._register((0, dom_1.runWhenWindowIdle)((0, dom_1.getWindow)(this._editor.getDomNode()), () => {
                this._instantiateSome(1 /* EditorContributionInstantiation.AfterFirstRender */);
            }));
            // BeforeFirstInteraction
            // - these extensions will be instantiated at the latest before a mouse or a keyboard event.
            // - but if there is idle time, we will instantiate them sooner.
            this._register((0, dom_1.runWhenWindowIdle)((0, dom_1.getWindow)(this._editor.getDomNode()), () => {
                this._instantiateSome(2 /* EditorContributionInstantiation.BeforeFirstInteraction */);
            }));
            // Eventually
            // - these extensions will only be instantiated when there is idle time.
            // - since there is no guarantee that there will ever be idle time, we set a timeout of 5s here.
            this._register((0, dom_1.runWhenWindowIdle)((0, dom_1.getWindow)(this._editor.getDomNode()), () => {
                this._instantiateSome(3 /* EditorContributionInstantiation.Eventually */);
            }, 5000));
        }
        saveViewState() {
            const contributionsState = {};
            for (const [id, contribution] of this._instances) {
                if (typeof contribution.saveViewState === 'function') {
                    contributionsState[id] = contribution.saveViewState();
                }
            }
            return contributionsState;
        }
        restoreViewState(contributionsState) {
            for (const [id, contribution] of this._instances) {
                if (typeof contribution.restoreViewState === 'function') {
                    contribution.restoreViewState(contributionsState[id]);
                }
            }
        }
        get(id) {
            this._instantiateById(id);
            return this._instances.get(id) || null;
        }
        onBeforeInteractionEvent() {
            // this method is called very often by the editor!
            this._instantiateSome(2 /* EditorContributionInstantiation.BeforeFirstInteraction */);
        }
        onAfterModelAttached() {
            return (0, dom_1.runWhenWindowIdle)((0, dom_1.getWindow)(this._editor?.getDomNode()), () => {
                this._instantiateSome(1 /* EditorContributionInstantiation.AfterFirstRender */);
            }, 50);
        }
        _instantiateSome(instantiation) {
            if (this._finishedInstantiation[instantiation]) {
                // already done with this instantiation!
                return;
            }
            this._finishedInstantiation[instantiation] = true;
            const contribs = this._findPendingContributionsByInstantiation(instantiation);
            for (const contrib of contribs) {
                this._instantiateById(contrib.id);
            }
        }
        _findPendingContributionsByInstantiation(instantiation) {
            const result = [];
            for (const [, desc] of this._pending) {
                if (desc.instantiation === instantiation) {
                    result.push(desc);
                }
            }
            return result;
        }
        _instantiateById(id) {
            const desc = this._pending.get(id);
            if (!desc) {
                return;
            }
            this._pending.delete(id);
            if (!this._instantiationService || !this._editor) {
                throw new Error(`Cannot instantiate contributions before being initialized!`);
            }
            try {
                const instance = this._instantiationService.createInstance(desc.ctor, this._editor);
                this._instances.set(desc.id, instance);
                if (typeof instance.restoreViewState === 'function' && desc.instantiation !== 0 /* EditorContributionInstantiation.Eager */) {
                    console.warn(`Editor contribution '${desc.id}' should be eager instantiated because it uses saveViewState / restoreViewState.`);
                }
            }
            catch (err) {
                (0, errors_1.onUnexpectedError)(err);
            }
        }
    }
    exports.CodeEditorContributions = CodeEditorContributions;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[363/*vs/editor/browser/widget/diffEditor/components/diffEditorSash*/], __M([1/*require*/,0/*exports*/,173/*vs/base/browser/ui/sash/sash*/,2/*vs/base/common/lifecycle*/,21/*vs/base/common/observable*/,65/*vs/base/common/observableInternal/derived*/]), function (require, exports, sash_1, lifecycle_1, observable_1, derived_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DiffEditorSash = exports.SashLayout = void 0;
    class SashLayout {
        resetSash() {
            this._sashRatio.set(undefined, undefined);
        }
        constructor(_options, dimensions) {
            this._options = _options;
            this.dimensions = dimensions;
            this.sashLeft = (0, derived_1.derivedWithSetter)(this, reader => {
                const ratio = this._sashRatio.read(reader) ?? this._options.splitViewDefaultRatio.read(reader);
                return this._computeSashLeft(ratio, reader);
            }, (value, tx) => {
                const contentWidth = this.dimensions.width.get();
                this._sashRatio.set(value / contentWidth, tx);
            });
            this._sashRatio = (0, observable_1.observableValue)(this, undefined);
        }
        /** @pure */
        _computeSashLeft(desiredRatio, reader) {
            const contentWidth = this.dimensions.width.read(reader);
            const midPoint = Math.floor(this._options.splitViewDefaultRatio.read(reader) * contentWidth);
            const sashLeft = this._options.enableSplitViewResizing.read(reader) ? Math.floor(desiredRatio * contentWidth) : midPoint;
            const MINIMUM_EDITOR_WIDTH = 100;
            if (contentWidth <= MINIMUM_EDITOR_WIDTH * 2) {
                return midPoint;
            }
            if (sashLeft < MINIMUM_EDITOR_WIDTH) {
                return MINIMUM_EDITOR_WIDTH;
            }
            if (sashLeft > contentWidth - MINIMUM_EDITOR_WIDTH) {
                return contentWidth - MINIMUM_EDITOR_WIDTH;
            }
            return sashLeft;
        }
    }
    exports.SashLayout = SashLayout;
    class DiffEditorSash extends lifecycle_1.Disposable {
        constructor(_domNode, _dimensions, _enabled, _boundarySashes, sashLeft, _resetSash) {
            super();
            this._domNode = _domNode;
            this._dimensions = _dimensions;
            this._enabled = _enabled;
            this._boundarySashes = _boundarySashes;
            this.sashLeft = sashLeft;
            this._resetSash = _resetSash;
            this._sash = this._register(new sash_1.Sash(this._domNode, {
                getVerticalSashTop: (_sash) => 0,
                getVerticalSashLeft: (_sash) => this.sashLeft.get(),
                getVerticalSashHeight: (_sash) => this._dimensions.height.get(),
            }, { orientation: 0 /* Orientation.VERTICAL */ }));
            this._startSashPosition = undefined;
            this._register(this._sash.onDidStart(() => {
                this._startSashPosition = this.sashLeft.get();
            }));
            this._register(this._sash.onDidChange((e) => {
                this.sashLeft.set(this._startSashPosition + (e.currentX - e.startX), undefined);
            }));
            this._register(this._sash.onDidEnd(() => this._sash.layout()));
            this._register(this._sash.onDidReset(() => this._resetSash()));
            this._register((0, observable_1.autorun)(reader => {
                const sashes = this._boundarySashes.read(reader);
                if (sashes) {
                    this._sash.orthogonalEndSash = sashes.bottom;
                }
            }));
            this._register((0, observable_1.autorun)(reader => {
                /** @description DiffEditorSash.layoutSash */
                const enabled = this._enabled.read(reader);
                this._sash.state = enabled ? 3 /* SashState.Enabled */ : 0 /* SashState.Disabled */;
                this.sashLeft.read(reader);
                this._dimensions.height.read(reader);
                this._sash.layout();
            }));
        }
    }
    exports.DiffEditorSash = DiffEditorSash;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[652/*vs/editor/browser/widget/diffEditor/components/diffEditorViewZones/inlineDiffDeletedCodeMargin*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,41/*vs/base/common/actions*/,26/*vs/base/common/codicons*/,2/*vs/base/common/lifecycle*/,16/*vs/base/common/platform*/,30/*vs/base/common/themables*/,3/*vs/nls*/]), function (require, exports, dom_1, actions_1, codicons_1, lifecycle_1, platform_1, themables_1, nls_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.InlineDiffDeletedCodeMargin = void 0;
    class InlineDiffDeletedCodeMargin extends lifecycle_1.Disposable {
        get visibility() {
            return this._visibility;
        }
        set visibility(_visibility) {
            if (this._visibility !== _visibility) {
                this._visibility = _visibility;
                this._diffActions.style.visibility = _visibility ? 'visible' : 'hidden';
            }
        }
        constructor(_getViewZoneId, _marginDomNode, _modifiedEditor, _diff, _editor, _viewLineCounts, _originalTextModel, _contextMenuService, _clipboardService) {
            super();
            this._getViewZoneId = _getViewZoneId;
            this._marginDomNode = _marginDomNode;
            this._modifiedEditor = _modifiedEditor;
            this._diff = _diff;
            this._editor = _editor;
            this._viewLineCounts = _viewLineCounts;
            this._originalTextModel = _originalTextModel;
            this._contextMenuService = _contextMenuService;
            this._clipboardService = _clipboardService;
            this._visibility = false;
            // make sure the diff margin shows above overlay.
            this._marginDomNode.style.zIndex = '10';
            this._diffActions = document.createElement('div');
            this._diffActions.className = themables_1.ThemeIcon.asClassName(codicons_1.Codicon.lightBulb) + ' lightbulb-glyph';
            this._diffActions.style.position = 'absolute';
            const lineHeight = this._modifiedEditor.getOption(67 /* EditorOption.lineHeight */);
            this._diffActions.style.right = '0px';
            this._diffActions.style.visibility = 'hidden';
            this._diffActions.style.height = `${lineHeight}px`;
            this._diffActions.style.lineHeight = `${lineHeight}px`;
            this._marginDomNode.appendChild(this._diffActions);
            let currentLineNumberOffset = 0;
            const useShadowDOM = _modifiedEditor.getOption(128 /* EditorOption.useShadowDOM */) && !platform_1.isIOS; // Do not use shadow dom on IOS #122035
            const showContextMenu = (x, y) => {
                this._contextMenuService.showContextMenu({
                    domForShadowRoot: useShadowDOM ? _modifiedEditor.getDomNode() ?? undefined : undefined,
                    getAnchor: () => ({ x, y }),
                    getActions: () => {
                        const actions = [];
                        const isDeletion = _diff.modified.isEmpty;
                        // default action
                        actions.push(new actions_1.Action('diff.clipboard.copyDeletedContent', isDeletion
                            ? (_diff.original.length > 1
                                ? (0, nls_1.localize)(99, "Copy deleted lines")
                                : (0, nls_1.localize)(100, "Copy deleted line"))
                            : (_diff.original.length > 1
                                ? (0, nls_1.localize)(101, "Copy changed lines")
                                : (0, nls_1.localize)(102, "Copy changed line")), undefined, true, async () => {
                            const originalText = this._originalTextModel.getValueInRange(_diff.original.toExclusiveRange());
                            await this._clipboardService.writeText(originalText);
                        }));
                        if (_diff.original.length > 1) {
                            actions.push(new actions_1.Action('diff.clipboard.copyDeletedLineContent', isDeletion
                                ? (0, nls_1.localize)(103, "Copy deleted line ({0})", _diff.original.startLineNumber + currentLineNumberOffset)
                                : (0, nls_1.localize)(104, "Copy changed line ({0})", _diff.original.startLineNumber + currentLineNumberOffset), undefined, true, async () => {
                                let lineContent = this._originalTextModel.getLineContent(_diff.original.startLineNumber + currentLineNumberOffset);
                                if (lineContent === '') {
                                    // empty line -> new line
                                    const eof = this._originalTextModel.getEndOfLineSequence();
                                    lineContent = eof === 0 /* EndOfLineSequence.LF */ ? '\n' : '\r\n';
                                }
                                await this._clipboardService.writeText(lineContent);
                            }));
                        }
                        const readOnly = _modifiedEditor.getOption(92 /* EditorOption.readOnly */);
                        if (!readOnly) {
                            actions.push(new actions_1.Action('diff.inline.revertChange', (0, nls_1.localize)(105, "Revert this change"), undefined, true, async () => {
                                this._editor.revert(this._diff);
                            }));
                        }
                        return actions;
                    },
                    autoSelectFirstItem: true
                });
            };
            this._register((0, dom_1.addStandardDisposableListener)(this._diffActions, 'mousedown', e => {
                if (!e.leftButton) {
                    return;
                }
                const { top, height } = (0, dom_1.getDomNodePagePosition)(this._diffActions);
                const pad = Math.floor(lineHeight / 3);
                e.preventDefault();
                showContextMenu(e.posx, top + height + pad);
            }));
            this._register(_modifiedEditor.onMouseMove((e) => {
                if ((e.target.type === 8 /* MouseTargetType.CONTENT_VIEW_ZONE */ || e.target.type === 5 /* MouseTargetType.GUTTER_VIEW_ZONE */) && e.target.detail.viewZoneId === this._getViewZoneId()) {
                    currentLineNumberOffset = this._updateLightBulbPosition(this._marginDomNode, e.event.browserEvent.y, lineHeight);
                    this.visibility = true;
                }
                else {
                    this.visibility = false;
                }
            }));
            this._register(_modifiedEditor.onMouseDown((e) => {
                if (!e.event.leftButton) {
                    return;
                }
                if (e.target.type === 8 /* MouseTargetType.CONTENT_VIEW_ZONE */ || e.target.type === 5 /* MouseTargetType.GUTTER_VIEW_ZONE */) {
                    const viewZoneId = e.target.detail.viewZoneId;
                    if (viewZoneId === this._getViewZoneId()) {
                        e.event.preventDefault();
                        currentLineNumberOffset = this._updateLightBulbPosition(this._marginDomNode, e.event.browserEvent.y, lineHeight);
                        showContextMenu(e.event.posx, e.event.posy + lineHeight);
                    }
                }
            }));
        }
        _updateLightBulbPosition(marginDomNode, y, lineHeight) {
            const { top } = (0, dom_1.getDomNodePagePosition)(marginDomNode);
            const offset = y - top;
            const lineNumberOffset = Math.floor(offset / lineHeight);
            const newTop = lineNumberOffset * lineHeight;
            this._diffActions.style.top = `${newTop}px`;
            if (this._viewLineCounts) {
                let acc = 0;
                for (let i = 0; i < this._viewLineCounts.length; i++) {
                    acc += this._viewLineCounts[i];
                    if (lineNumberOffset < acc) {
                        return i;
                    }
                }
            }
            return lineNumberOffset;
        }
    }
    exports.InlineDiffDeletedCodeMargin = InlineDiffDeletedCodeMargin;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[653/*vs/editor/browser/widget/diffEditor/features/revertButtonsFeature*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,114/*vs/base/browser/ui/iconLabel/iconLabels*/,26/*vs/base/common/codicons*/,2/*vs/base/common/lifecycle*/,21/*vs/base/common/observable*/,55/*vs/editor/common/core/lineRange*/,4/*vs/editor/common/core/range*/,105/*vs/editor/common/diff/rangeMapping*/,40/*vs/editor/common/model*/,3/*vs/nls*/]), function (require, exports, dom_1, iconLabels_1, codicons_1, lifecycle_1, observable_1, lineRange_1, range_1, rangeMapping_1, model_1, nls_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.RevertButton = exports.RevertButtonsFeature = void 0;
    const emptyArr = [];
    class RevertButtonsFeature extends lifecycle_1.Disposable {
        constructor(_editors, _diffModel, _options, _widget) {
            super();
            this._editors = _editors;
            this._diffModel = _diffModel;
            this._options = _options;
            this._widget = _widget;
            this._selectedDiffs = (0, observable_1.derived)(this, (reader) => {
                /** @description selectedDiffs */
                const model = this._diffModel.read(reader);
                const diff = model?.diff.read(reader);
                // Return `emptyArr` because it is a constant. [] is always a new array and would trigger a change.
                if (!diff) {
                    return emptyArr;
                }
                const selections = this._editors.modifiedSelections.read(reader);
                if (selections.every(s => s.isEmpty())) {
                    return emptyArr;
                }
                const selectedLineNumbers = new lineRange_1.LineRangeSet(selections.map(s => lineRange_1.LineRange.fromRangeInclusive(s)));
                const selectedMappings = diff.mappings.filter(m => m.lineRangeMapping.innerChanges && selectedLineNumbers.intersects(m.lineRangeMapping.modified));
                const result = selectedMappings.map(mapping => ({
                    mapping,
                    rangeMappings: mapping.lineRangeMapping.innerChanges.filter(c => selections.some(s => range_1.Range.areIntersecting(c.modifiedRange, s)))
                }));
                if (result.length === 0 || result.every(r => r.rangeMappings.length === 0)) {
                    return emptyArr;
                }
                return result;
            });
            this._register((0, observable_1.autorunWithStore)((reader, store) => {
                if (!this._options.shouldRenderOldRevertArrows.read(reader)) {
                    return;
                }
                const model = this._diffModel.read(reader);
                const diff = model?.diff.read(reader);
                if (!model || !diff) {
                    return;
                }
                if (model.movedTextToCompare.read(reader)) {
                    return;
                }
                const glyphWidgetsModified = [];
                const selectedDiffs = this._selectedDiffs.read(reader);
                const selectedDiffsSet = new Set(selectedDiffs.map(d => d.mapping));
                if (selectedDiffs.length > 0) {
                    // The button to revert the selection
                    const selections = this._editors.modifiedSelections.read(reader);
                    const btn = store.add(new RevertButton(selections[selections.length - 1].positionLineNumber, this._widget, selectedDiffs.flatMap(d => d.rangeMappings), true));
                    this._editors.modified.addGlyphMarginWidget(btn);
                    glyphWidgetsModified.push(btn);
                }
                for (const m of diff.mappings) {
                    if (selectedDiffsSet.has(m)) {
                        continue;
                    }
                    if (!m.lineRangeMapping.modified.isEmpty && m.lineRangeMapping.innerChanges) {
                        const btn = store.add(new RevertButton(m.lineRangeMapping.modified.startLineNumber, this._widget, m.lineRangeMapping, false));
                        this._editors.modified.addGlyphMarginWidget(btn);
                        glyphWidgetsModified.push(btn);
                    }
                }
                store.add((0, lifecycle_1.toDisposable)(() => {
                    for (const w of glyphWidgetsModified) {
                        this._editors.modified.removeGlyphMarginWidget(w);
                    }
                }));
            }));
        }
    }
    exports.RevertButtonsFeature = RevertButtonsFeature;
    class RevertButton extends lifecycle_1.Disposable {
        static { this.counter = 0; }
        getId() { return this._id; }
        constructor(_lineNumber, _widget, _diffs, _revertSelection) {
            super();
            this._lineNumber = _lineNumber;
            this._widget = _widget;
            this._diffs = _diffs;
            this._revertSelection = _revertSelection;
            this._id = `revertButton${RevertButton.counter++}`;
            this._domNode = (0, dom_1.h)('div.revertButton', {
                title: this._revertSelection
                    ? (0, nls_1.localize)(122, 'Revert Selected Changes')
                    : (0, nls_1.localize)(123, 'Revert Change')
            }, [(0, iconLabels_1.renderIcon)(codicons_1.Codicon.arrowRight)]).root;
            this._register((0, dom_1.addDisposableListener)(this._domNode, dom_1.EventType.MOUSE_DOWN, e => {
                // don't prevent context menu from showing up
                if (e.button !== 2) {
                    e.stopPropagation();
                    e.preventDefault();
                }
            }));
            this._register((0, dom_1.addDisposableListener)(this._domNode, dom_1.EventType.MOUSE_UP, e => {
                e.stopPropagation();
                e.preventDefault();
            }));
            this._register((0, dom_1.addDisposableListener)(this._domNode, dom_1.EventType.CLICK, (e) => {
                if (this._diffs instanceof rangeMapping_1.LineRangeMapping) {
                    this._widget.revert(this._diffs);
                }
                else {
                    this._widget.revertRangeMappings(this._diffs);
                }
                e.stopPropagation();
                e.preventDefault();
            }));
        }
        /**
         * Get the dom node of the glyph widget.
         */
        getDomNode() {
            return this._domNode;
        }
        /**
         * Get the placement of the glyph widget.
         */
        getPosition() {
            return {
                lane: model_1.GlyphMarginLane.Right,
                range: {
                    startColumn: 1,
                    startLineNumber: this._lineNumber,
                    endColumn: 1,
                    endLineNumber: this._lineNumber,
                },
                zIndex: 10001,
            };
        }
    }
    exports.RevertButton = RevertButton;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[88/*vs/editor/browser/widget/diffEditor/utils*/], __M([1/*require*/,0/*exports*/,67/*vs/base/common/arraysFind*/,18/*vs/base/common/cancellation*/,2/*vs/base/common/lifecycle*/,21/*vs/base/common/observable*/,362/*vs/editor/browser/config/elementSizeObserver*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/,113/*vs/editor/common/core/textLength*/]), function (require, exports, arraysFind_1, cancellation_1, lifecycle_1, observable_1, elementSizeObserver_1, position_1, range_1, textLength_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.RefCounted = exports.DisposableCancellationTokenSource = exports.ManagedOverlayWidget = exports.PlaceholderViewZone = exports.ViewZoneOverlayWidget = exports.ObservableElementSizeObserver = void 0;
    exports.joinCombine = joinCombine;
    exports.applyObservableDecorations = applyObservableDecorations;
    exports.appendRemoveOnDispose = appendRemoveOnDispose;
    exports.prependRemoveOnDispose = prependRemoveOnDispose;
    exports.animatedObservable = animatedObservable;
    exports.applyStyle = applyStyle;
    exports.applyViewZones = applyViewZones;
    exports.translatePosition = translatePosition;
    exports.filterWithPrevious = filterWithPrevious;
    function joinCombine(arr1, arr2, keySelector, combine) {
        if (arr1.length === 0) {
            return arr2;
        }
        if (arr2.length === 0) {
            return arr1;
        }
        const result = [];
        let i = 0;
        let j = 0;
        while (i < arr1.length && j < arr2.length) {
            const val1 = arr1[i];
            const val2 = arr2[j];
            const key1 = keySelector(val1);
            const key2 = keySelector(val2);
            if (key1 < key2) {
                result.push(val1);
                i++;
            }
            else if (key1 > key2) {
                result.push(val2);
                j++;
            }
            else {
                result.push(combine(val1, val2));
                i++;
                j++;
            }
        }
        while (i < arr1.length) {
            result.push(arr1[i]);
            i++;
        }
        while (j < arr2.length) {
            result.push(arr2[j]);
            j++;
        }
        return result;
    }
    // TODO make utility
    function applyObservableDecorations(editor, decorations) {
        const d = new lifecycle_1.DisposableStore();
        const decorationsCollection = editor.createDecorationsCollection();
        d.add((0, observable_1.autorunOpts)({ debugName: () => `Apply decorations from ${decorations.debugName}` }, reader => {
            const d = decorations.read(reader);
            decorationsCollection.set(d);
        }));
        d.add({
            dispose: () => {
                decorationsCollection.clear();
            }
        });
        return d;
    }
    function appendRemoveOnDispose(parent, child) {
        parent.appendChild(child);
        return (0, lifecycle_1.toDisposable)(() => {
            child.remove();
        });
    }
    function prependRemoveOnDispose(parent, child) {
        parent.prepend(child);
        return (0, lifecycle_1.toDisposable)(() => {
            child.remove();
        });
    }
    class ObservableElementSizeObserver extends lifecycle_1.Disposable {
        get width() { return this._width; }
        get height() { return this._height; }
        get automaticLayout() { return this._automaticLayout; }
        constructor(element, dimension) {
            super();
            this._automaticLayout = false;
            this.elementSizeObserver = this._register(new elementSizeObserver_1.ElementSizeObserver(element, dimension));
            this._width = (0, observable_1.observableValue)(this, this.elementSizeObserver.getWidth());
            this._height = (0, observable_1.observableValue)(this, this.elementSizeObserver.getHeight());
            this._register(this.elementSizeObserver.onDidChange(e => (0, observable_1.transaction)(tx => {
                /** @description Set width/height from elementSizeObserver */
                this._width.set(this.elementSizeObserver.getWidth(), tx);
                this._height.set(this.elementSizeObserver.getHeight(), tx);
            })));
        }
        observe(dimension) {
            this.elementSizeObserver.observe(dimension);
        }
        setAutomaticLayout(automaticLayout) {
            this._automaticLayout = automaticLayout;
            if (automaticLayout) {
                this.elementSizeObserver.startObserving();
            }
            else {
                this.elementSizeObserver.stopObserving();
            }
        }
    }
    exports.ObservableElementSizeObserver = ObservableElementSizeObserver;
    function animatedObservable(targetWindow, base, store) {
        let targetVal = base.get();
        let startVal = targetVal;
        let curVal = targetVal;
        const result = (0, observable_1.observableValue)('animatedValue', targetVal);
        let animationStartMs = -1;
        const durationMs = 300;
        let animationFrame = undefined;
        store.add((0, observable_1.autorunHandleChanges)({
            createEmptyChangeSummary: () => ({ animate: false }),
            handleChange: (ctx, s) => {
                if (ctx.didChange(base)) {
                    s.animate = s.animate || ctx.change;
                }
                return true;
            }
        }, (reader, s) => {
            /** @description update value */
            if (animationFrame !== undefined) {
                targetWindow.cancelAnimationFrame(animationFrame);
                animationFrame = undefined;
            }
            startVal = curVal;
            targetVal = base.read(reader);
            animationStartMs = Date.now() - (s.animate ? 0 : durationMs);
            update();
        }));
        function update() {
            const passedMs = Date.now() - animationStartMs;
            curVal = Math.floor(easeOutExpo(passedMs, startVal, targetVal - startVal, durationMs));
            if (passedMs < durationMs) {
                animationFrame = targetWindow.requestAnimationFrame(update);
            }
            else {
                curVal = targetVal;
            }
            result.set(curVal, undefined);
        }
        return result;
    }
    function easeOutExpo(t, b, c, d) {
        return t === d ? b + c : c * (-Math.pow(2, -10 * t / d) + 1) + b;
    }
    class ViewZoneOverlayWidget extends lifecycle_1.Disposable {
        constructor(editor, viewZone, htmlElement) {
            super();
            this._register(new ManagedOverlayWidget(editor, htmlElement));
            this._register(applyStyle(htmlElement, {
                height: viewZone.actualHeight,
                top: viewZone.actualTop,
            }));
        }
    }
    exports.ViewZoneOverlayWidget = ViewZoneOverlayWidget;
    class PlaceholderViewZone {
        get afterLineNumber() { return this._afterLineNumber.get(); }
        constructor(_afterLineNumber, heightInPx) {
            this._afterLineNumber = _afterLineNumber;
            this.heightInPx = heightInPx;
            this.domNode = document.createElement('div');
            this._actualTop = (0, observable_1.observableValue)(this, undefined);
            this._actualHeight = (0, observable_1.observableValue)(this, undefined);
            this.actualTop = this._actualTop;
            this.actualHeight = this._actualHeight;
            this.showInHiddenAreas = true;
            this.onChange = this._afterLineNumber;
            this.onDomNodeTop = (top) => {
                this._actualTop.set(top, undefined);
            };
            this.onComputedHeight = (height) => {
                this._actualHeight.set(height, undefined);
            };
        }
    }
    exports.PlaceholderViewZone = PlaceholderViewZone;
    class ManagedOverlayWidget {
        static { this._counter = 0; }
        constructor(_editor, _domElement) {
            this._editor = _editor;
            this._domElement = _domElement;
            this._overlayWidgetId = `managedOverlayWidget-${ManagedOverlayWidget._counter++}`;
            this._overlayWidget = {
                getId: () => this._overlayWidgetId,
                getDomNode: () => this._domElement,
                getPosition: () => null
            };
            this._editor.addOverlayWidget(this._overlayWidget);
        }
        dispose() {
            this._editor.removeOverlayWidget(this._overlayWidget);
        }
    }
    exports.ManagedOverlayWidget = ManagedOverlayWidget;
    function applyStyle(domNode, style) {
        return (0, observable_1.autorun)(reader => {
            /** @description applyStyle */
            for (let [key, val] of Object.entries(style)) {
                if (val && typeof val === 'object' && 'read' in val) {
                    val = val.read(reader);
                }
                if (typeof val === 'number') {
                    val = `${val}px`;
                }
                key = key.replace(/[A-Z]/g, m => '-' + m.toLowerCase());
                domNode.style[key] = val;
            }
        });
    }
    function applyViewZones(editor, viewZones, setIsUpdating, zoneIds) {
        const store = new lifecycle_1.DisposableStore();
        const lastViewZoneIds = [];
        store.add((0, observable_1.autorunWithStore)((reader, store) => {
            /** @description applyViewZones */
            const curViewZones = viewZones.read(reader);
            const viewZonIdsPerViewZone = new Map();
            const viewZoneIdPerOnChangeObservable = new Map();
            // Add/remove view zones
            if (setIsUpdating) {
                setIsUpdating(true);
            }
            editor.changeViewZones(a => {
                for (const id of lastViewZoneIds) {
                    a.removeZone(id);
                    zoneIds?.delete(id);
                }
                lastViewZoneIds.length = 0;
                for (const z of curViewZones) {
                    const id = a.addZone(z);
                    if (z.setZoneId) {
                        z.setZoneId(id);
                    }
                    lastViewZoneIds.push(id);
                    zoneIds?.add(id);
                    viewZonIdsPerViewZone.set(z, id);
                }
            });
            if (setIsUpdating) {
                setIsUpdating(false);
            }
            // Layout zone on change
            store.add((0, observable_1.autorunHandleChanges)({
                createEmptyChangeSummary() {
                    return { zoneIds: [] };
                },
                handleChange(context, changeSummary) {
                    const id = viewZoneIdPerOnChangeObservable.get(context.changedObservable);
                    if (id !== undefined) {
                        changeSummary.zoneIds.push(id);
                    }
                    return true;
                },
            }, (reader, changeSummary) => {
                /** @description layoutZone on change */
                for (const vz of curViewZones) {
                    if (vz.onChange) {
                        viewZoneIdPerOnChangeObservable.set(vz.onChange, viewZonIdsPerViewZone.get(vz));
                        vz.onChange.read(reader);
                    }
                }
                if (setIsUpdating) {
                    setIsUpdating(true);
                }
                editor.changeViewZones(a => { for (const id of changeSummary.zoneIds) {
                    a.layoutZone(id);
                } });
                if (setIsUpdating) {
                    setIsUpdating(false);
                }
            }));
        }));
        store.add({
            dispose() {
                if (setIsUpdating) {
                    setIsUpdating(true);
                }
                editor.changeViewZones(a => { for (const id of lastViewZoneIds) {
                    a.removeZone(id);
                } });
                zoneIds?.clear();
                if (setIsUpdating) {
                    setIsUpdating(false);
                }
            }
        });
        return store;
    }
    class DisposableCancellationTokenSource extends cancellation_1.CancellationTokenSource {
        dispose() {
            super.dispose(true);
        }
    }
    exports.DisposableCancellationTokenSource = DisposableCancellationTokenSource;
    function translatePosition(posInOriginal, mappings) {
        const mapping = (0, arraysFind_1.findLast)(mappings, m => m.original.startLineNumber <= posInOriginal.lineNumber);
        if (!mapping) {
            // No changes before the position
            return range_1.Range.fromPositions(posInOriginal);
        }
        if (mapping.original.endLineNumberExclusive <= posInOriginal.lineNumber) {
            const newLineNumber = posInOriginal.lineNumber - mapping.original.endLineNumberExclusive + mapping.modified.endLineNumberExclusive;
            return range_1.Range.fromPositions(new position_1.Position(newLineNumber, posInOriginal.column));
        }
        if (!mapping.innerChanges) {
            // Only for legacy algorithm
            return range_1.Range.fromPositions(new position_1.Position(mapping.modified.startLineNumber, 1));
        }
        const innerMapping = (0, arraysFind_1.findLast)(mapping.innerChanges, m => m.originalRange.getStartPosition().isBeforeOrEqual(posInOriginal));
        if (!innerMapping) {
            const newLineNumber = posInOriginal.lineNumber - mapping.original.startLineNumber + mapping.modified.startLineNumber;
            return range_1.Range.fromPositions(new position_1.Position(newLineNumber, posInOriginal.column));
        }
        if (innerMapping.originalRange.containsPosition(posInOriginal)) {
            return innerMapping.modifiedRange;
        }
        else {
            const l = lengthBetweenPositions(innerMapping.originalRange.getEndPosition(), posInOriginal);
            return range_1.Range.fromPositions(l.addToPosition(innerMapping.modifiedRange.getEndPosition()));
        }
    }
    function lengthBetweenPositions(position1, position2) {
        if (position1.lineNumber === position2.lineNumber) {
            return new textLength_1.TextLength(0, position2.column - position1.column);
        }
        else {
            return new textLength_1.TextLength(position2.lineNumber - position1.lineNumber, position2.column - 1);
        }
    }
    function filterWithPrevious(arr, filter) {
        let prev;
        return arr.filter(cur => {
            const result = filter(cur, prev);
            prev = cur;
            return result;
        });
    }
    class RefCounted {
        static create(value, debugOwner = undefined) {
            return new BaseRefCounted(value, value, debugOwner);
        }
        static createWithDisposable(value, disposable, debugOwner = undefined) {
            const store = new lifecycle_1.DisposableStore();
            store.add(disposable);
            store.add(value);
            return new BaseRefCounted(value, store, debugOwner);
        }
    }
    exports.RefCounted = RefCounted;
    class BaseRefCounted extends RefCounted {
        constructor(object, _disposable, _debugOwner) {
            super();
            this.object = object;
            this._disposable = _disposable;
            this._debugOwner = _debugOwner;
            this._refCount = 1;
            this._isDisposed = false;
            this._owners = [];
            if (_debugOwner) {
                this._addOwner(_debugOwner);
            }
        }
        _addOwner(debugOwner) {
            if (debugOwner) {
                this._owners.push(debugOwner);
            }
        }
        createNewRef(debugOwner) {
            this._refCount++;
            if (debugOwner) {
                this._addOwner(debugOwner);
            }
            return new ClonedRefCounted(this, debugOwner);
        }
        dispose() {
            if (this._isDisposed) {
                return;
            }
            this._isDisposed = true;
            this._decreaseRefCount(this._debugOwner);
        }
        _decreaseRefCount(debugOwner) {
            this._refCount--;
            if (this._refCount === 0) {
                this._disposable.dispose();
            }
            if (debugOwner) {
                const idx = this._owners.indexOf(debugOwner);
                if (idx !== -1) {
                    this._owners.splice(idx, 1);
                }
            }
        }
    }
    class ClonedRefCounted extends RefCounted {
        constructor(_base, _debugOwner) {
            super();
            this._base = _base;
            this._debugOwner = _debugOwner;
            this._isDisposed = false;
        }
        get object() { return this._base.object; }
        createNewRef(debugOwner) {
            return this._base.createNewRef(debugOwner);
        }
        dispose() {
            if (this._isDisposed) {
                return;
            }
            this._isDisposed = true;
            this._base._decreaseRefCount(this._debugOwner);
        }
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[364/*vs/editor/browser/widget/diffEditor/features/movedBlocksLinesFeature*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,87/*vs/base/browser/ui/actionbar/actionbar*/,41/*vs/base/common/actions*/,13/*vs/base/common/arrays*/,67/*vs/base/common/arraysFind*/,26/*vs/base/common/codicons*/,2/*vs/base/common/lifecycle*/,21/*vs/base/common/observable*/,30/*vs/base/common/themables*/,88/*vs/editor/browser/widget/diffEditor/utils*/,68/*vs/editor/common/core/offsetRange*/,3/*vs/nls*/]), function (require, exports, dom_1, actionbar_1, actions_1, arrays_1, arraysFind_1, codicons_1, lifecycle_1, observable_1, themables_1, utils_1, offsetRange_1, nls_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MovedBlocksLinesFeature = void 0;
    class MovedBlocksLinesFeature extends lifecycle_1.Disposable {
        static { this.movedCodeBlockPadding = 4; }
        constructor(_rootElement, _diffModel, _originalEditorLayoutInfo, _modifiedEditorLayoutInfo, _editors) {
            super();
            this._rootElement = _rootElement;
            this._diffModel = _diffModel;
            this._originalEditorLayoutInfo = _originalEditorLayoutInfo;
            this._modifiedEditorLayoutInfo = _modifiedEditorLayoutInfo;
            this._editors = _editors;
            this._originalScrollTop = (0, observable_1.observableFromEvent)(this, this._editors.original.onDidScrollChange, () => this._editors.original.getScrollTop());
            this._modifiedScrollTop = (0, observable_1.observableFromEvent)(this, this._editors.modified.onDidScrollChange, () => this._editors.modified.getScrollTop());
            this._viewZonesChanged = (0, observable_1.observableSignalFromEvent)('onDidChangeViewZones', this._editors.modified.onDidChangeViewZones);
            this.width = (0, observable_1.observableValue)(this, 0);
            this._modifiedViewZonesChangedSignal = (0, observable_1.observableSignalFromEvent)('modified.onDidChangeViewZones', this._editors.modified.onDidChangeViewZones);
            this._originalViewZonesChangedSignal = (0, observable_1.observableSignalFromEvent)('original.onDidChangeViewZones', this._editors.original.onDidChangeViewZones);
            this._state = (0, observable_1.derivedWithStore)(this, (reader, store) => {
                /** @description state */
                this._element.replaceChildren();
                const model = this._diffModel.read(reader);
                const moves = model?.diff.read(reader)?.movedTexts;
                if (!moves || moves.length === 0) {
                    this.width.set(0, undefined);
                    return;
                }
                this._viewZonesChanged.read(reader);
                const infoOrig = this._originalEditorLayoutInfo.read(reader);
                const infoMod = this._modifiedEditorLayoutInfo.read(reader);
                if (!infoOrig || !infoMod) {
                    this.width.set(0, undefined);
                    return;
                }
                this._modifiedViewZonesChangedSignal.read(reader);
                this._originalViewZonesChangedSignal.read(reader);
                const lines = moves.map((move) => {
                    function computeLineStart(range, editor) {
                        const t1 = editor.getTopForLineNumber(range.startLineNumber, true);
                        const t2 = editor.getTopForLineNumber(range.endLineNumberExclusive, true);
                        return (t1 + t2) / 2;
                    }
                    const start = computeLineStart(move.lineRangeMapping.original, this._editors.original);
                    const startOffset = this._originalScrollTop.read(reader);
                    const end = computeLineStart(move.lineRangeMapping.modified, this._editors.modified);
                    const endOffset = this._modifiedScrollTop.read(reader);
                    const from = start - startOffset;
                    const to = end - endOffset;
                    const top = Math.min(start, end);
                    const bottom = Math.max(start, end);
                    return { range: new offsetRange_1.OffsetRange(top, bottom), from, to, fromWithoutScroll: start, toWithoutScroll: end, move };
                });
                lines.sort((0, arrays_1.tieBreakComparators)((0, arrays_1.compareBy)(l => l.fromWithoutScroll > l.toWithoutScroll, arrays_1.booleanComparator), (0, arrays_1.compareBy)(l => l.fromWithoutScroll > l.toWithoutScroll ? l.fromWithoutScroll : -l.toWithoutScroll, arrays_1.numberComparator)));
                const layout = LinesLayout.compute(lines.map(l => l.range));
                const padding = 10;
                const lineAreaLeft = infoOrig.verticalScrollbarWidth;
                const lineAreaWidth = (layout.getTrackCount() - 1) * 10 + padding * 2;
                const width = lineAreaLeft + lineAreaWidth + (infoMod.contentLeft - MovedBlocksLinesFeature.movedCodeBlockPadding);
                let idx = 0;
                for (const line of lines) {
                    const track = layout.getTrack(idx);
                    const verticalY = lineAreaLeft + padding + track * 10;
                    const arrowHeight = 15;
                    const arrowWidth = 15;
                    const right = width;
                    const rectWidth = infoMod.glyphMarginWidth + infoMod.lineNumbersWidth;
                    const rectHeight = 18;
                    const rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
                    rect.classList.add('arrow-rectangle');
                    rect.setAttribute('x', `${right - rectWidth}`);
                    rect.setAttribute('y', `${line.to - rectHeight / 2}`);
                    rect.setAttribute('width', `${rectWidth}`);
                    rect.setAttribute('height', `${rectHeight}`);
                    this._element.appendChild(rect);
                    const g = document.createElementNS('http://www.w3.org/2000/svg', 'g');
                    const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
                    path.setAttribute('d', `M ${0} ${line.from} L ${verticalY} ${line.from} L ${verticalY} ${line.to} L ${right - arrowWidth} ${line.to}`);
                    path.setAttribute('fill', 'none');
                    g.appendChild(path);
                    const arrowRight = document.createElementNS('http://www.w3.org/2000/svg', 'polygon');
                    arrowRight.classList.add('arrow');
                    store.add((0, observable_1.autorun)(reader => {
                        path.classList.toggle('currentMove', line.move === model.activeMovedText.read(reader));
                        arrowRight.classList.toggle('currentMove', line.move === model.activeMovedText.read(reader));
                    }));
                    arrowRight.setAttribute('points', `${right - arrowWidth},${line.to - arrowHeight / 2} ${right},${line.to} ${right - arrowWidth},${line.to + arrowHeight / 2}`);
                    g.appendChild(arrowRight);
                    this._element.appendChild(g);
                    /*
                    TODO@hediet
                    path.addEventListener('mouseenter', () => {
                        model.setHoveredMovedText(line.move);
                    });
                    path.addEventListener('mouseleave', () => {
                        model.setHoveredMovedText(undefined);
                    });*/
                    idx++;
                }
                this.width.set(lineAreaWidth, undefined);
            });
            this._element = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
            this._element.setAttribute('class', 'moved-blocks-lines');
            this._rootElement.appendChild(this._element);
            this._register((0, lifecycle_1.toDisposable)(() => this._element.remove()));
            this._register((0, observable_1.autorun)(reader => {
                /** @description update moved blocks lines positioning */
                const info = this._originalEditorLayoutInfo.read(reader);
                const info2 = this._modifiedEditorLayoutInfo.read(reader);
                if (!info || !info2) {
                    return;
                }
                this._element.style.left = `${info.width - info.verticalScrollbarWidth}px`;
                this._element.style.height = `${info.height}px`;
                this._element.style.width = `${info.verticalScrollbarWidth + info.contentLeft - MovedBlocksLinesFeature.movedCodeBlockPadding + this.width.read(reader)}px`;
            }));
            this._register((0, observable_1.recomputeInitiallyAndOnChange)(this._state));
            const movedBlockViewZones = (0, observable_1.derived)(reader => {
                const model = this._diffModel.read(reader);
                const d = model?.diff.read(reader);
                if (!d) {
                    return [];
                }
                return d.movedTexts.map(move => ({
                    move,
                    original: new utils_1.PlaceholderViewZone((0, observable_1.constObservable)(move.lineRangeMapping.original.startLineNumber - 1), 18),
                    modified: new utils_1.PlaceholderViewZone((0, observable_1.constObservable)(move.lineRangeMapping.modified.startLineNumber - 1), 18),
                }));
            });
            this._register((0, utils_1.applyViewZones)(this._editors.original, movedBlockViewZones.map(zones => /** @description movedBlockViewZones.original */ zones.map(z => z.original))));
            this._register((0, utils_1.applyViewZones)(this._editors.modified, movedBlockViewZones.map(zones => /** @description movedBlockViewZones.modified */ zones.map(z => z.modified))));
            this._register((0, observable_1.autorunWithStore)((reader, store) => {
                const blocks = movedBlockViewZones.read(reader);
                for (const b of blocks) {
                    store.add(new MovedBlockOverlayWidget(this._editors.original, b.original, b.move, 'original', this._diffModel.get()));
                    store.add(new MovedBlockOverlayWidget(this._editors.modified, b.modified, b.move, 'modified', this._diffModel.get()));
                }
            }));
            const originalHasFocus = (0, observable_1.observableSignalFromEvent)('original.onDidFocusEditorWidget', e => this._editors.original.onDidFocusEditorWidget(() => setTimeout(() => e(undefined), 0)));
            const modifiedHasFocus = (0, observable_1.observableSignalFromEvent)('modified.onDidFocusEditorWidget', e => this._editors.modified.onDidFocusEditorWidget(() => setTimeout(() => e(undefined), 0)));
            let lastChangedEditor = 'modified';
            this._register((0, observable_1.autorunHandleChanges)({
                createEmptyChangeSummary: () => undefined,
                handleChange: (ctx, summary) => {
                    if (ctx.didChange(originalHasFocus)) {
                        lastChangedEditor = 'original';
                    }
                    if (ctx.didChange(modifiedHasFocus)) {
                        lastChangedEditor = 'modified';
                    }
                    return true;
                }
            }, reader => {
                /** @description MovedBlocksLines.setActiveMovedTextFromCursor */
                originalHasFocus.read(reader);
                modifiedHasFocus.read(reader);
                const m = this._diffModel.read(reader);
                if (!m) {
                    return;
                }
                const diff = m.diff.read(reader);
                let movedText = undefined;
                if (diff && lastChangedEditor === 'original') {
                    const originalPos = this._editors.originalCursor.read(reader);
                    if (originalPos) {
                        movedText = diff.movedTexts.find(m => m.lineRangeMapping.original.contains(originalPos.lineNumber));
                    }
                }
                if (diff && lastChangedEditor === 'modified') {
                    const modifiedPos = this._editors.modifiedCursor.read(reader);
                    if (modifiedPos) {
                        movedText = diff.movedTexts.find(m => m.lineRangeMapping.modified.contains(modifiedPos.lineNumber));
                    }
                }
                if (movedText !== m.movedTextToCompare.get()) {
                    m.movedTextToCompare.set(undefined, undefined);
                }
                m.setActiveMovedText(movedText);
            }));
        }
    }
    exports.MovedBlocksLinesFeature = MovedBlocksLinesFeature;
    class LinesLayout {
        static compute(lines) {
            const setsPerTrack = [];
            const trackPerLineIdx = [];
            for (const line of lines) {
                let trackIdx = setsPerTrack.findIndex(set => !set.intersectsStrict(line));
                if (trackIdx === -1) {
                    const maxTrackCount = 6;
                    if (setsPerTrack.length >= maxTrackCount) {
                        trackIdx = (0, arraysFind_1.findMaxIdx)(setsPerTrack, (0, arrays_1.compareBy)(set => set.intersectWithRangeLength(line), arrays_1.numberComparator));
                    }
                    else {
                        trackIdx = setsPerTrack.length;
                        setsPerTrack.push(new offsetRange_1.OffsetRangeSet());
                    }
                }
                setsPerTrack[trackIdx].addRange(line);
                trackPerLineIdx.push(trackIdx);
            }
            return new LinesLayout(setsPerTrack.length, trackPerLineIdx);
        }
        constructor(_trackCount, trackPerLineIdx) {
            this._trackCount = _trackCount;
            this.trackPerLineIdx = trackPerLineIdx;
        }
        getTrack(lineIdx) {
            return this.trackPerLineIdx[lineIdx];
        }
        getTrackCount() {
            return this._trackCount;
        }
    }
    class MovedBlockOverlayWidget extends utils_1.ViewZoneOverlayWidget {
        constructor(_editor, _viewZone, _move, _kind, _diffModel) {
            const root = (0, dom_1.h)('div.diff-hidden-lines-widget');
            super(_editor, _viewZone, root.root);
            this._editor = _editor;
            this._move = _move;
            this._kind = _kind;
            this._diffModel = _diffModel;
            this._nodes = (0, dom_1.h)('div.diff-moved-code-block', { style: { marginRight: '4px' } }, [
                (0, dom_1.h)('div.text-content@textContent'),
                (0, dom_1.h)('div.action-bar@actionBar'),
            ]);
            root.root.appendChild(this._nodes.root);
            const editorLayout = (0, observable_1.observableFromEvent)(this._editor.onDidLayoutChange, () => this._editor.getLayoutInfo());
            this._register((0, utils_1.applyStyle)(this._nodes.root, {
                paddingRight: editorLayout.map(l => l.verticalScrollbarWidth)
            }));
            let text;
            if (_move.changes.length > 0) {
                text = this._kind === 'original' ? (0, nls_1.localize)(118, 'Code moved with changes to line {0}-{1}', this._move.lineRangeMapping.modified.startLineNumber, this._move.lineRangeMapping.modified.endLineNumberExclusive - 1) : (0, nls_1.localize)(119, 'Code moved with changes from line {0}-{1}', this._move.lineRangeMapping.original.startLineNumber, this._move.lineRangeMapping.original.endLineNumberExclusive - 1);
            }
            else {
                text = this._kind === 'original' ? (0, nls_1.localize)(120, 'Code moved to line {0}-{1}', this._move.lineRangeMapping.modified.startLineNumber, this._move.lineRangeMapping.modified.endLineNumberExclusive - 1) : (0, nls_1.localize)(121, 'Code moved from line {0}-{1}', this._move.lineRangeMapping.original.startLineNumber, this._move.lineRangeMapping.original.endLineNumberExclusive - 1);
            }
            const actionBar = this._register(new actionbar_1.ActionBar(this._nodes.actionBar, {
                highlightToggledItems: true,
            }));
            const caption = new actions_1.Action('', text, '', false);
            actionBar.push(caption, { icon: false, label: true });
            const actionCompare = new actions_1.Action('', 'Compare', themables_1.ThemeIcon.asClassName(codicons_1.Codicon.compareChanges), true, () => {
                this._editor.focus();
                this._diffModel.movedTextToCompare.set(this._diffModel.movedTextToCompare.get() === _move ? undefined : this._move, undefined);
            });
            this._register((0, observable_1.autorun)(reader => {
                const isActive = this._diffModel.movedTextToCompare.read(reader) === _move;
                actionCompare.checked = isActive;
            }));
            actionBar.push(actionCompare, { icon: false, label: true });
        }
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[654/*vs/editor/browser/widget/diffEditor/utils/editorGutter*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,2/*vs/base/common/lifecycle*/,21/*vs/base/common/observable*/,55/*vs/editor/common/core/lineRange*/,68/*vs/editor/common/core/offsetRange*/]), function (require, exports, dom_1, lifecycle_1, observable_1, lineRange_1, offsetRange_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.EditorGutter = void 0;
    class EditorGutter extends lifecycle_1.Disposable {
        constructor(_editor, _domNode, itemProvider) {
            super();
            this._editor = _editor;
            this._domNode = _domNode;
            this.itemProvider = itemProvider;
            this.scrollTop = (0, observable_1.observableFromEvent)(this, this._editor.onDidScrollChange, (e) => /** @description editor.onDidScrollChange */ this._editor.getScrollTop());
            this.isScrollTopZero = this.scrollTop.map((scrollTop) => /** @description isScrollTopZero */ scrollTop === 0);
            this.modelAttached = (0, observable_1.observableFromEvent)(this, this._editor.onDidChangeModel, (e) => /** @description editor.onDidChangeModel */ this._editor.hasModel());
            this.editorOnDidChangeViewZones = (0, observable_1.observableSignalFromEvent)('onDidChangeViewZones', this._editor.onDidChangeViewZones);
            this.editorOnDidContentSizeChange = (0, observable_1.observableSignalFromEvent)('onDidContentSizeChange', this._editor.onDidContentSizeChange);
            this.domNodeSizeChanged = (0, observable_1.observableSignal)('domNodeSizeChanged');
            this.views = new Map();
            this._domNode.className = 'gutter monaco-editor';
            const scrollDecoration = this._domNode.appendChild((0, dom_1.h)('div.scroll-decoration', { role: 'presentation', ariaHidden: 'true', style: { width: '100%' } })
                .root);
            const o = new ResizeObserver(() => {
                (0, observable_1.transaction)(tx => {
                    /** @description ResizeObserver: size changed */
                    this.domNodeSizeChanged.trigger(tx);
                });
            });
            o.observe(this._domNode);
            this._register((0, lifecycle_1.toDisposable)(() => o.disconnect()));
            this._register((0, observable_1.autorun)(reader => {
                /** @description update scroll decoration */
                scrollDecoration.className = this.isScrollTopZero.read(reader) ? '' : 'scroll-decoration';
            }));
            this._register((0, observable_1.autorun)(reader => /** @description EditorGutter.Render */ this.render(reader)));
        }
        dispose() {
            super.dispose();
            (0, dom_1.reset)(this._domNode);
        }
        render(reader) {
            if (!this.modelAttached.read(reader)) {
                return;
            }
            this.domNodeSizeChanged.read(reader);
            this.editorOnDidChangeViewZones.read(reader);
            this.editorOnDidContentSizeChange.read(reader);
            const scrollTop = this.scrollTop.read(reader);
            const visibleRanges = this._editor.getVisibleRanges();
            const unusedIds = new Set(this.views.keys());
            const viewRange = offsetRange_1.OffsetRange.ofStartAndLength(0, this._domNode.clientHeight);
            if (!viewRange.isEmpty) {
                for (const visibleRange of visibleRanges) {
                    const visibleRange2 = new lineRange_1.LineRange(visibleRange.startLineNumber, visibleRange.endLineNumber + 1);
                    const gutterItems = this.itemProvider.getIntersectingGutterItems(visibleRange2, reader);
                    (0, observable_1.transaction)(tx => {
                        /** EditorGutter.render */
                        for (const gutterItem of gutterItems) {
                            if (!gutterItem.range.intersect(visibleRange2)) {
                                continue;
                            }
                            unusedIds.delete(gutterItem.id);
                            let view = this.views.get(gutterItem.id);
                            if (!view) {
                                const viewDomNode = document.createElement('div');
                                this._domNode.appendChild(viewDomNode);
                                const gutterItemObs = (0, observable_1.observableValue)('item', gutterItem);
                                const itemView = this.itemProvider.createView(gutterItemObs, viewDomNode);
                                view = new ManagedGutterItemView(gutterItemObs, itemView, viewDomNode);
                                this.views.set(gutterItem.id, view);
                            }
                            else {
                                view.item.set(gutterItem, tx);
                            }
                            const top = gutterItem.range.startLineNumber <= this._editor.getModel().getLineCount()
                                ? this._editor.getTopForLineNumber(gutterItem.range.startLineNumber, true) - scrollTop
                                : this._editor.getBottomForLineNumber(gutterItem.range.startLineNumber - 1, false) - scrollTop;
                            const bottom = gutterItem.range.endLineNumberExclusive === 1 ?
                                Math.max(top, this._editor.getTopForLineNumber(gutterItem.range.startLineNumber, false) - scrollTop)
                                : Math.max(top, this._editor.getBottomForLineNumber(gutterItem.range.endLineNumberExclusive - 1, true) - scrollTop);
                            const height = bottom - top;
                            view.domNode.style.top = `${top}px`;
                            view.domNode.style.height = `${height}px`;
                            view.gutterItemView.layout(offsetRange_1.OffsetRange.ofStartAndLength(top, height), viewRange);
                        }
                    });
                }
            }
            for (const id of unusedIds) {
                const view = this.views.get(id);
                view.gutterItemView.dispose();
                view.domNode.remove();
                this.views.delete(id);
            }
        }
    }
    exports.EditorGutter = EditorGutter;
    class ManagedGutterItemView {
        constructor(item, gutterItemView, domNode) {
            this.item = item;
            this.gutterItemView = gutterItemView;
            this.domNode = domNode;
        }
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[365/*vs/editor/browser/widget/multiDiffEditor/utils*/], __M([1/*require*/,0/*exports*/,41/*vs/base/common/actions*/]), function (require, exports, actions_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ActionRunnerWithContext = void 0;
    class ActionRunnerWithContext extends actions_1.ActionRunner {
        constructor(_getContext) {
            super();
            this._getContext = _getContext;
        }
        runAction(action, _context) {
            const ctx = this._getContext();
            return super.runAction(action, ctx);
        }
    }
    exports.ActionRunnerWithContext = ActionRunnerWithContext;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[37/*vs/editor/common/config/editorOptions*/], __M([1/*require*/,0/*exports*/,13/*vs/base/common/arrays*/,60/*vs/base/common/objects*/,16/*vs/base/common/platform*/,197/*vs/editor/common/core/textModelDefaults*/,147/*vs/editor/common/core/wordHelper*/,3/*vs/nls*/]), function (require, exports, arrays, objects, platform, textModelDefaults_1, wordHelper_1, nls) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.EditorOptions = exports.editorOptionsRegistry = exports.EDITOR_FONT_DEFAULTS = exports.unicodeHighlightConfigKeys = exports.inUntrustedWorkspace = exports.ShowLightbulbIconMode = exports.EditorLayoutInfoComputer = exports.EditorFontVariations = exports.EditorFontLigatures = exports.TextEditorCursorStyle = exports.ApplyUpdateResult = exports.ComputeOptionsMemory = exports.ConfigurationChangedEvent = exports.MINIMAP_GUTTER_WIDTH = void 0;
    exports.boolean = boolean;
    exports.clampedInt = clampedInt;
    exports.clampedFloat = clampedFloat;
    exports.stringSet = stringSet;
    exports.filterValidationDecorations = filterValidationDecorations;
    /**
     * @internal
     * The width of the minimap gutter, in pixels.
     */
    exports.MINIMAP_GUTTER_WIDTH = 8;
    //#endregion
    /**
     * An event describing that the configuration of the editor has changed.
     */
    class ConfigurationChangedEvent {
        /**
         * @internal
         */
        constructor(values) {
            this._values = values;
        }
        hasChanged(id) {
            return this._values[id];
        }
    }
    exports.ConfigurationChangedEvent = ConfigurationChangedEvent;
    /**
     * @internal
     */
    class ComputeOptionsMemory {
        constructor() {
            this.stableMinimapLayoutInput = null;
            this.stableFitMaxMinimapScale = 0;
            this.stableFitRemainingWidth = 0;
        }
    }
    exports.ComputeOptionsMemory = ComputeOptionsMemory;
    /**
     * @internal
     */
    class BaseEditorOption {
        constructor(id, name, defaultValue, schema) {
            this.id = id;
            this.name = name;
            this.defaultValue = defaultValue;
            this.schema = schema;
        }
        applyUpdate(value, update) {
            return applyUpdate(value, update);
        }
        compute(env, options, value) {
            return value;
        }
    }
    class ApplyUpdateResult {
        constructor(newValue, didChange) {
            this.newValue = newValue;
            this.didChange = didChange;
        }
    }
    exports.ApplyUpdateResult = ApplyUpdateResult;
    function applyUpdate(value, update) {
        if (typeof value !== 'object' || typeof update !== 'object' || !value || !update) {
            return new ApplyUpdateResult(update, value !== update);
        }
        if (Array.isArray(value) || Array.isArray(update)) {
            const arrayEquals = Array.isArray(value) && Array.isArray(update) && arrays.equals(value, update);
            return new ApplyUpdateResult(update, !arrayEquals);
        }
        let didChange = false;
        for (const key in update) {
            if (update.hasOwnProperty(key)) {
                const result = applyUpdate(value[key], update[key]);
                if (result.didChange) {
                    value[key] = result.newValue;
                    didChange = true;
                }
            }
        }
        return new ApplyUpdateResult(value, didChange);
    }
    /**
     * @internal
     */
    class ComputedEditorOption {
        constructor(id) {
            this.schema = undefined;
            this.id = id;
            this.name = '_never_';
            this.defaultValue = undefined;
        }
        applyUpdate(value, update) {
            return applyUpdate(value, update);
        }
        validate(input) {
            return this.defaultValue;
        }
    }
    class SimpleEditorOption {
        constructor(id, name, defaultValue, schema) {
            this.id = id;
            this.name = name;
            this.defaultValue = defaultValue;
            this.schema = schema;
        }
        applyUpdate(value, update) {
            return applyUpdate(value, update);
        }
        validate(input) {
            if (typeof input === 'undefined') {
                return this.defaultValue;
            }
            return input;
        }
        compute(env, options, value) {
            return value;
        }
    }
    /**
     * @internal
     */
    function boolean(value, defaultValue) {
        if (typeof value === 'undefined') {
            return defaultValue;
        }
        if (value === 'false') {
            // treat the string 'false' as false
            return false;
        }
        return Boolean(value);
    }
    class EditorBooleanOption extends SimpleEditorOption {
        constructor(id, name, defaultValue, schema = undefined) {
            if (typeof schema !== 'undefined') {
                schema.type = 'boolean';
                schema.default = defaultValue;
            }
            super(id, name, defaultValue, schema);
        }
        validate(input) {
            return boolean(input, this.defaultValue);
        }
    }
    /**
     * @internal
     */
    function clampedInt(value, defaultValue, minimum, maximum) {
        if (typeof value === 'undefined') {
            return defaultValue;
        }
        let r = parseInt(value, 10);
        if (isNaN(r)) {
            return defaultValue;
        }
        r = Math.max(minimum, r);
        r = Math.min(maximum, r);
        return r | 0;
    }
    class EditorIntOption extends SimpleEditorOption {
        static clampedInt(value, defaultValue, minimum, maximum) {
            return clampedInt(value, defaultValue, minimum, maximum);
        }
        constructor(id, name, defaultValue, minimum, maximum, schema = undefined) {
            if (typeof schema !== 'undefined') {
                schema.type = 'integer';
                schema.default = defaultValue;
                schema.minimum = minimum;
                schema.maximum = maximum;
            }
            super(id, name, defaultValue, schema);
            this.minimum = minimum;
            this.maximum = maximum;
        }
        validate(input) {
            return EditorIntOption.clampedInt(input, this.defaultValue, this.minimum, this.maximum);
        }
    }
    /**
     * @internal
     */
    function clampedFloat(value, defaultValue, minimum, maximum) {
        if (typeof value === 'undefined') {
            return defaultValue;
        }
        const r = EditorFloatOption.float(value, defaultValue);
        return EditorFloatOption.clamp(r, minimum, maximum);
    }
    class EditorFloatOption extends SimpleEditorOption {
        static clamp(n, min, max) {
            if (n < min) {
                return min;
            }
            if (n > max) {
                return max;
            }
            return n;
        }
        static float(value, defaultValue) {
            if (typeof value === 'number') {
                return value;
            }
            if (typeof value === 'undefined') {
                return defaultValue;
            }
            const r = parseFloat(value);
            return (isNaN(r) ? defaultValue : r);
        }
        constructor(id, name, defaultValue, validationFn, schema) {
            if (typeof schema !== 'undefined') {
                schema.type = 'number';
                schema.default = defaultValue;
            }
            super(id, name, defaultValue, schema);
            this.validationFn = validationFn;
        }
        validate(input) {
            return this.validationFn(EditorFloatOption.float(input, this.defaultValue));
        }
    }
    class EditorStringOption extends SimpleEditorOption {
        static string(value, defaultValue) {
            if (typeof value !== 'string') {
                return defaultValue;
            }
            return value;
        }
        constructor(id, name, defaultValue, schema = undefined) {
            if (typeof schema !== 'undefined') {
                schema.type = 'string';
                schema.default = defaultValue;
            }
            super(id, name, defaultValue, schema);
        }
        validate(input) {
            return EditorStringOption.string(input, this.defaultValue);
        }
    }
    /**
     * @internal
     */
    function stringSet(value, defaultValue, allowedValues, renamedValues) {
        if (typeof value !== 'string') {
            return defaultValue;
        }
        if (renamedValues && value in renamedValues) {
            return renamedValues[value];
        }
        if (allowedValues.indexOf(value) === -1) {
            return defaultValue;
        }
        return value;
    }
    class EditorStringEnumOption extends SimpleEditorOption {
        constructor(id, name, defaultValue, allowedValues, schema = undefined) {
            if (typeof schema !== 'undefined') {
                schema.type = 'string';
                schema.enum = allowedValues;
                schema.default = defaultValue;
            }
            super(id, name, defaultValue, schema);
            this._allowedValues = allowedValues;
        }
        validate(input) {
            return stringSet(input, this.defaultValue, this._allowedValues);
        }
    }
    class EditorEnumOption extends BaseEditorOption {
        constructor(id, name, defaultValue, defaultStringValue, allowedValues, convert, schema = undefined) {
            if (typeof schema !== 'undefined') {
                schema.type = 'string';
                schema.enum = allowedValues;
                schema.default = defaultStringValue;
            }
            super(id, name, defaultValue, schema);
            this._allowedValues = allowedValues;
            this._convert = convert;
        }
        validate(input) {
            if (typeof input !== 'string') {
                return this.defaultValue;
            }
            if (this._allowedValues.indexOf(input) === -1) {
                return this.defaultValue;
            }
            return this._convert(input);
        }
    }
    //#endregion
    //#region autoIndent
    function _autoIndentFromString(autoIndent) {
        switch (autoIndent) {
            case 'none': return 0 /* EditorAutoIndentStrategy.None */;
            case 'keep': return 1 /* EditorAutoIndentStrategy.Keep */;
            case 'brackets': return 2 /* EditorAutoIndentStrategy.Brackets */;
            case 'advanced': return 3 /* EditorAutoIndentStrategy.Advanced */;
            case 'full': return 4 /* EditorAutoIndentStrategy.Full */;
        }
    }
    //#endregion
    //#region accessibilitySupport
    class EditorAccessibilitySupport extends BaseEditorOption {
        constructor() {
            super(2 /* EditorOption.accessibilitySupport */, 'accessibilitySupport', 0 /* AccessibilitySupport.Unknown */, {
                type: 'string',
                enum: ['auto', 'on', 'off'],
                enumDescriptions: [
                    nls.localize(183, "Use platform APIs to detect when a Screen Reader is attached."),
                    nls.localize(184, "Optimize for usage with a Screen Reader."),
                    nls.localize(185, "Assume a screen reader is not attached."),
                ],
                default: 'auto',
                tags: ['accessibility'],
                description: nls.localize(186, "Controls if the UI should run in a mode where it is optimized for screen readers.")
            });
        }
        validate(input) {
            switch (input) {
                case 'auto': return 0 /* AccessibilitySupport.Unknown */;
                case 'off': return 1 /* AccessibilitySupport.Disabled */;
                case 'on': return 2 /* AccessibilitySupport.Enabled */;
            }
            return this.defaultValue;
        }
        compute(env, options, value) {
            if (value === 0 /* AccessibilitySupport.Unknown */) {
                // The editor reads the `accessibilitySupport` from the environment
                return env.accessibilitySupport;
            }
            return value;
        }
    }
    class EditorComments extends BaseEditorOption {
        constructor() {
            const defaults = {
                insertSpace: true,
                ignoreEmptyLines: true,
            };
            super(23 /* EditorOption.comments */, 'comments', defaults, {
                'editor.comments.insertSpace': {
                    type: 'boolean',
                    default: defaults.insertSpace,
                    description: nls.localize(187, "Controls whether a space character is inserted when commenting.")
                },
                'editor.comments.ignoreEmptyLines': {
                    type: 'boolean',
                    default: defaults.ignoreEmptyLines,
                    description: nls.localize(188, 'Controls if empty lines should be ignored with toggle, add or remove actions for line comments.')
                },
            });
        }
        validate(_input) {
            if (!_input || typeof _input !== 'object') {
                return this.defaultValue;
            }
            const input = _input;
            return {
                insertSpace: boolean(input.insertSpace, this.defaultValue.insertSpace),
                ignoreEmptyLines: boolean(input.ignoreEmptyLines, this.defaultValue.ignoreEmptyLines),
            };
        }
    }
    function _cursorBlinkingStyleFromString(cursorBlinkingStyle) {
        switch (cursorBlinkingStyle) {
            case 'blink': return 1 /* TextEditorCursorBlinkingStyle.Blink */;
            case 'smooth': return 2 /* TextEditorCursorBlinkingStyle.Smooth */;
            case 'phase': return 3 /* TextEditorCursorBlinkingStyle.Phase */;
            case 'expand': return 4 /* TextEditorCursorBlinkingStyle.Expand */;
            case 'solid': return 5 /* TextEditorCursorBlinkingStyle.Solid */;
        }
    }
    //#endregion
    //#region cursorStyle
    /**
     * The style in which the editor's cursor should be rendered.
     */
    var TextEditorCursorStyle;
    (function (TextEditorCursorStyle) {
        /**
         * As a vertical line (sitting between two characters).
         */
        TextEditorCursorStyle[TextEditorCursorStyle["Line"] = 1] = "Line";
        /**
         * As a block (sitting on top of a character).
         */
        TextEditorCursorStyle[TextEditorCursorStyle["Block"] = 2] = "Block";
        /**
         * As a horizontal line (sitting under a character).
         */
        TextEditorCursorStyle[TextEditorCursorStyle["Underline"] = 3] = "Underline";
        /**
         * As a thin vertical line (sitting between two characters).
         */
        TextEditorCursorStyle[TextEditorCursorStyle["LineThin"] = 4] = "LineThin";
        /**
         * As an outlined block (sitting on top of a character).
         */
        TextEditorCursorStyle[TextEditorCursorStyle["BlockOutline"] = 5] = "BlockOutline";
        /**
         * As a thin horizontal line (sitting under a character).
         */
        TextEditorCursorStyle[TextEditorCursorStyle["UnderlineThin"] = 6] = "UnderlineThin";
    })(TextEditorCursorStyle || (exports.TextEditorCursorStyle = TextEditorCursorStyle = {}));
    function _cursorStyleFromString(cursorStyle) {
        switch (cursorStyle) {
            case 'line': return TextEditorCursorStyle.Line;
            case 'block': return TextEditorCursorStyle.Block;
            case 'underline': return TextEditorCursorStyle.Underline;
            case 'line-thin': return TextEditorCursorStyle.LineThin;
            case 'block-outline': return TextEditorCursorStyle.BlockOutline;
            case 'underline-thin': return TextEditorCursorStyle.UnderlineThin;
        }
    }
    //#endregion
    //#region editorClassName
    class EditorClassName extends ComputedEditorOption {
        constructor() {
            super(143 /* EditorOption.editorClassName */);
        }
        compute(env, options, _) {
            const classNames = ['monaco-editor'];
            if (options.get(39 /* EditorOption.extraEditorClassName */)) {
                classNames.push(options.get(39 /* EditorOption.extraEditorClassName */));
            }
            if (env.extraEditorClassName) {
                classNames.push(env.extraEditorClassName);
            }
            if (options.get(74 /* EditorOption.mouseStyle */) === 'default') {
                classNames.push('mouse-default');
            }
            else if (options.get(74 /* EditorOption.mouseStyle */) === 'copy') {
                classNames.push('mouse-copy');
            }
            if (options.get(112 /* EditorOption.showUnused */)) {
                classNames.push('showUnused');
            }
            if (options.get(141 /* EditorOption.showDeprecated */)) {
                classNames.push('showDeprecated');
            }
            return classNames.join(' ');
        }
    }
    //#endregion
    //#region emptySelectionClipboard
    class EditorEmptySelectionClipboard extends EditorBooleanOption {
        constructor() {
            super(37 /* EditorOption.emptySelectionClipboard */, 'emptySelectionClipboard', true, { description: nls.localize(189, "Controls whether copying without a selection copies the current line.") });
        }
        compute(env, options, value) {
            return value && env.emptySelectionClipboard;
        }
    }
    class EditorFind extends BaseEditorOption {
        constructor() {
            const defaults = {
                cursorMoveOnType: true,
                seedSearchStringFromSelection: 'always',
                autoFindInSelection: 'never',
                globalFindClipboard: false,
                addExtraSpaceOnTop: true,
                loop: true
            };
            super(41 /* EditorOption.find */, 'find', defaults, {
                'editor.find.cursorMoveOnType': {
                    type: 'boolean',
                    default: defaults.cursorMoveOnType,
                    description: nls.localize(190, "Controls whether the cursor should jump to find matches while typing.")
                },
                'editor.find.seedSearchStringFromSelection': {
                    type: 'string',
                    enum: ['never', 'always', 'selection'],
                    default: defaults.seedSearchStringFromSelection,
                    enumDescriptions: [
                        nls.localize(191, 'Never seed search string from the editor selection.'),
                        nls.localize(192, 'Always seed search string from the editor selection, including word at cursor position.'),
                        nls.localize(193, 'Only seed search string from the editor selection.')
                    ],
                    description: nls.localize(194, "Controls whether the search string in the Find Widget is seeded from the editor selection.")
                },
                'editor.find.autoFindInSelection': {
                    type: 'string',
                    enum: ['never', 'always', 'multiline'],
                    default: defaults.autoFindInSelection,
                    enumDescriptions: [
                        nls.localize(195, 'Never turn on Find in Selection automatically (default).'),
                        nls.localize(196, 'Always turn on Find in Selection automatically.'),
                        nls.localize(197, 'Turn on Find in Selection automatically when multiple lines of content are selected.')
                    ],
                    description: nls.localize(198, "Controls the condition for turning on Find in Selection automatically.")
                },
                'editor.find.globalFindClipboard': {
                    type: 'boolean',
                    default: defaults.globalFindClipboard,
                    description: nls.localize(199, "Controls whether the Find Widget should read or modify the shared find clipboard on macOS."),
                    included: platform.isMacintosh
                },
                'editor.find.addExtraSpaceOnTop': {
                    type: 'boolean',
                    default: defaults.addExtraSpaceOnTop,
                    description: nls.localize(200, "Controls whether the Find Widget should add extra lines on top of the editor. When true, you can scroll beyond the first line when the Find Widget is visible.")
                },
                'editor.find.loop': {
                    type: 'boolean',
                    default: defaults.loop,
                    description: nls.localize(201, "Controls whether the search automatically restarts from the beginning (or the end) when no further matches can be found.")
                },
            });
        }
        validate(_input) {
            if (!_input || typeof _input !== 'object') {
                return this.defaultValue;
            }
            const input = _input;
            return {
                cursorMoveOnType: boolean(input.cursorMoveOnType, this.defaultValue.cursorMoveOnType),
                seedSearchStringFromSelection: typeof _input.seedSearchStringFromSelection === 'boolean'
                    ? (_input.seedSearchStringFromSelection ? 'always' : 'never')
                    : stringSet(input.seedSearchStringFromSelection, this.defaultValue.seedSearchStringFromSelection, ['never', 'always', 'selection']),
                autoFindInSelection: typeof _input.autoFindInSelection === 'boolean'
                    ? (_input.autoFindInSelection ? 'always' : 'never')
                    : stringSet(input.autoFindInSelection, this.defaultValue.autoFindInSelection, ['never', 'always', 'multiline']),
                globalFindClipboard: boolean(input.globalFindClipboard, this.defaultValue.globalFindClipboard),
                addExtraSpaceOnTop: boolean(input.addExtraSpaceOnTop, this.defaultValue.addExtraSpaceOnTop),
                loop: boolean(input.loop, this.defaultValue.loop),
            };
        }
    }
    //#endregion
    //#region fontLigatures
    /**
     * @internal
     */
    class EditorFontLigatures extends BaseEditorOption {
        static { this.OFF = '"liga" off, "calt" off'; }
        static { this.ON = '"liga" on, "calt" on'; }
        constructor() {
            super(51 /* EditorOption.fontLigatures */, 'fontLigatures', EditorFontLigatures.OFF, {
                anyOf: [
                    {
                        type: 'boolean',
                        description: nls.localize(202, "Enables/Disables font ligatures ('calt' and 'liga' font features). Change this to a string for fine-grained control of the 'font-feature-settings' CSS property."),
                    },
                    {
                        type: 'string',
                        description: nls.localize(203, "Explicit 'font-feature-settings' CSS property. A boolean can be passed instead if one only needs to turn on/off ligatures.")
                    }
                ],
                description: nls.localize(204, "Configures font ligatures or font features. Can be either a boolean to enable/disable ligatures or a string for the value of the CSS 'font-feature-settings' property."),
                default: false
            });
        }
        validate(input) {
            if (typeof input === 'undefined') {
                return this.defaultValue;
            }
            if (typeof input === 'string') {
                if (input === 'false' || input.length === 0) {
                    return EditorFontLigatures.OFF;
                }
                if (input === 'true') {
                    return EditorFontLigatures.ON;
                }
                return input;
            }
            if (Boolean(input)) {
                return EditorFontLigatures.ON;
            }
            return EditorFontLigatures.OFF;
        }
    }
    exports.EditorFontLigatures = EditorFontLigatures;
    //#endregion
    //#region fontVariations
    /**
     * @internal
     */
    class EditorFontVariations extends BaseEditorOption {
        // Text is laid out using default settings.
        static { this.OFF = 'normal'; }
        // Translate `fontWeight` config to the `font-variation-settings` CSS property.
        static { this.TRANSLATE = 'translate'; }
        constructor() {
            super(54 /* EditorOption.fontVariations */, 'fontVariations', EditorFontVariations.OFF, {
                anyOf: [
                    {
                        type: 'boolean',
                        description: nls.localize(205, "Enables/Disables the translation from font-weight to font-variation-settings. Change this to a string for fine-grained control of the 'font-variation-settings' CSS property."),
                    },
                    {
                        type: 'string',
                        description: nls.localize(206, "Explicit 'font-variation-settings' CSS property. A boolean can be passed instead if one only needs to translate font-weight to font-variation-settings.")
                    }
                ],
                description: nls.localize(207, "Configures font variations. Can be either a boolean to enable/disable the translation from font-weight to font-variation-settings or a string for the value of the CSS 'font-variation-settings' property."),
                default: false
            });
        }
        validate(input) {
            if (typeof input === 'undefined') {
                return this.defaultValue;
            }
            if (typeof input === 'string') {
                if (input === 'false') {
                    return EditorFontVariations.OFF;
                }
                if (input === 'true') {
                    return EditorFontVariations.TRANSLATE;
                }
                return input;
            }
            if (Boolean(input)) {
                return EditorFontVariations.TRANSLATE;
            }
            return EditorFontVariations.OFF;
        }
        compute(env, options, value) {
            // The value is computed from the fontWeight if it is true.
            // So take the result from env.fontInfo
            return env.fontInfo.fontVariationSettings;
        }
    }
    exports.EditorFontVariations = EditorFontVariations;
    //#endregion
    //#region fontInfo
    class EditorFontInfo extends ComputedEditorOption {
        constructor() {
            super(50 /* EditorOption.fontInfo */);
        }
        compute(env, options, _) {
            return env.fontInfo;
        }
    }
    //#endregion
    //#region fontSize
    class EditorFontSize extends SimpleEditorOption {
        constructor() {
            super(52 /* EditorOption.fontSize */, 'fontSize', exports.EDITOR_FONT_DEFAULTS.fontSize, {
                type: 'number',
                minimum: 6,
                maximum: 100,
                default: exports.EDITOR_FONT_DEFAULTS.fontSize,
                description: nls.localize(208, "Controls the font size in pixels.")
            });
        }
        validate(input) {
            const r = EditorFloatOption.float(input, this.defaultValue);
            if (r === 0) {
                return exports.EDITOR_FONT_DEFAULTS.fontSize;
            }
            return EditorFloatOption.clamp(r, 6, 100);
        }
        compute(env, options, value) {
            // The final fontSize respects the editor zoom level.
            // So take the result from env.fontInfo
            return env.fontInfo.fontSize;
        }
    }
    //#endregion
    //#region fontWeight
    class EditorFontWeight extends BaseEditorOption {
        static { this.SUGGESTION_VALUES = ['normal', 'bold', '100', '200', '300', '400', '500', '600', '700', '800', '900']; }
        static { this.MINIMUM_VALUE = 1; }
        static { this.MAXIMUM_VALUE = 1000; }
        constructor() {
            super(53 /* EditorOption.fontWeight */, 'fontWeight', exports.EDITOR_FONT_DEFAULTS.fontWeight, {
                anyOf: [
                    {
                        type: 'number',
                        minimum: EditorFontWeight.MINIMUM_VALUE,
                        maximum: EditorFontWeight.MAXIMUM_VALUE,
                        errorMessage: nls.localize(209, "Only \"normal\" and \"bold\" keywords or numbers between 1 and 1000 are allowed.")
                    },
                    {
                        type: 'string',
                        pattern: '^(normal|bold|1000|[1-9][0-9]{0,2})$'
                    },
                    {
                        enum: EditorFontWeight.SUGGESTION_VALUES
                    }
                ],
                default: exports.EDITOR_FONT_DEFAULTS.fontWeight,
                description: nls.localize(210, "Controls the font weight. Accepts \"normal\" and \"bold\" keywords or numbers between 1 and 1000.")
            });
        }
        validate(input) {
            if (input === 'normal' || input === 'bold') {
                return input;
            }
            return String(EditorIntOption.clampedInt(input, exports.EDITOR_FONT_DEFAULTS.fontWeight, EditorFontWeight.MINIMUM_VALUE, EditorFontWeight.MAXIMUM_VALUE));
        }
    }
    class EditorGoToLocation extends BaseEditorOption {
        constructor() {
            const defaults = {
                multiple: 'peek',
                multipleDefinitions: 'peek',
                multipleTypeDefinitions: 'peek',
                multipleDeclarations: 'peek',
                multipleImplementations: 'peek',
                multipleReferences: 'peek',
                multipleTests: 'peek',
                alternativeDefinitionCommand: 'editor.action.goToReferences',
                alternativeTypeDefinitionCommand: 'editor.action.goToReferences',
                alternativeDeclarationCommand: 'editor.action.goToReferences',
                alternativeImplementationCommand: '',
                alternativeReferenceCommand: '',
                alternativeTestsCommand: '',
            };
            const jsonSubset = {
                type: 'string',
                enum: ['peek', 'gotoAndPeek', 'goto'],
                default: defaults.multiple,
                enumDescriptions: [
                    nls.localize(211, 'Show Peek view of the results (default)'),
                    nls.localize(212, 'Go to the primary result and show a Peek view'),
                    nls.localize(213, 'Go to the primary result and enable Peek-less navigation to others')
                ]
            };
            const alternativeCommandOptions = ['', 'editor.action.referenceSearch.trigger', 'editor.action.goToReferences', 'editor.action.peekImplementation', 'editor.action.goToImplementation', 'editor.action.peekTypeDefinition', 'editor.action.goToTypeDefinition', 'editor.action.peekDeclaration', 'editor.action.revealDeclaration', 'editor.action.peekDefinition', 'editor.action.revealDefinitionAside', 'editor.action.revealDefinition'];
            super(58 /* EditorOption.gotoLocation */, 'gotoLocation', defaults, {
                'editor.gotoLocation.multiple': {
                    deprecationMessage: nls.localize(214, "This setting is deprecated, please use separate settings like 'editor.editor.gotoLocation.multipleDefinitions' or 'editor.editor.gotoLocation.multipleImplementations' instead."),
                },
                'editor.gotoLocation.multipleDefinitions': {
                    description: nls.localize(215, "Controls the behavior the 'Go to Definition'-command when multiple target locations exist."),
                    ...jsonSubset,
                },
                'editor.gotoLocation.multipleTypeDefinitions': {
                    description: nls.localize(216, "Controls the behavior the 'Go to Type Definition'-command when multiple target locations exist."),
                    ...jsonSubset,
                },
                'editor.gotoLocation.multipleDeclarations': {
                    description: nls.localize(217, "Controls the behavior the 'Go to Declaration'-command when multiple target locations exist."),
                    ...jsonSubset,
                },
                'editor.gotoLocation.multipleImplementations': {
                    description: nls.localize(218, "Controls the behavior the 'Go to Implementations'-command when multiple target locations exist."),
                    ...jsonSubset,
                },
                'editor.gotoLocation.multipleReferences': {
                    description: nls.localize(219, "Controls the behavior the 'Go to References'-command when multiple target locations exist."),
                    ...jsonSubset,
                },
                'editor.gotoLocation.alternativeDefinitionCommand': {
                    type: 'string',
                    default: defaults.alternativeDefinitionCommand,
                    enum: alternativeCommandOptions,
                    description: nls.localize(220, "Alternative command id that is being executed when the result of 'Go to Definition' is the current location.")
                },
                'editor.gotoLocation.alternativeTypeDefinitionCommand': {
                    type: 'string',
                    default: defaults.alternativeTypeDefinitionCommand,
                    enum: alternativeCommandOptions,
                    description: nls.localize(221, "Alternative command id that is being executed when the result of 'Go to Type Definition' is the current location.")
                },
                'editor.gotoLocation.alternativeDeclarationCommand': {
                    type: 'string',
                    default: defaults.alternativeDeclarationCommand,
                    enum: alternativeCommandOptions,
                    description: nls.localize(222, "Alternative command id that is being executed when the result of 'Go to Declaration' is the current location.")
                },
                'editor.gotoLocation.alternativeImplementationCommand': {
                    type: 'string',
                    default: defaults.alternativeImplementationCommand,
                    enum: alternativeCommandOptions,
                    description: nls.localize(223, "Alternative command id that is being executed when the result of 'Go to Implementation' is the current location.")
                },
                'editor.gotoLocation.alternativeReferenceCommand': {
                    type: 'string',
                    default: defaults.alternativeReferenceCommand,
                    enum: alternativeCommandOptions,
                    description: nls.localize(224, "Alternative command id that is being executed when the result of 'Go to Reference' is the current location.")
                },
            });
        }
        validate(_input) {
            if (!_input || typeof _input !== 'object') {
                return this.defaultValue;
            }
            const input = _input;
            return {
                multiple: stringSet(input.multiple, this.defaultValue.multiple, ['peek', 'gotoAndPeek', 'goto']),
                multipleDefinitions: input.multipleDefinitions ?? stringSet(input.multipleDefinitions, 'peek', ['peek', 'gotoAndPeek', 'goto']),
                multipleTypeDefinitions: input.multipleTypeDefinitions ?? stringSet(input.multipleTypeDefinitions, 'peek', ['peek', 'gotoAndPeek', 'goto']),
                multipleDeclarations: input.multipleDeclarations ?? stringSet(input.multipleDeclarations, 'peek', ['peek', 'gotoAndPeek', 'goto']),
                multipleImplementations: input.multipleImplementations ?? stringSet(input.multipleImplementations, 'peek', ['peek', 'gotoAndPeek', 'goto']),
                multipleReferences: input.multipleReferences ?? stringSet(input.multipleReferences, 'peek', ['peek', 'gotoAndPeek', 'goto']),
                multipleTests: input.multipleTests ?? stringSet(input.multipleTests, 'peek', ['peek', 'gotoAndPeek', 'goto']),
                alternativeDefinitionCommand: EditorStringOption.string(input.alternativeDefinitionCommand, this.defaultValue.alternativeDefinitionCommand),
                alternativeTypeDefinitionCommand: EditorStringOption.string(input.alternativeTypeDefinitionCommand, this.defaultValue.alternativeTypeDefinitionCommand),
                alternativeDeclarationCommand: EditorStringOption.string(input.alternativeDeclarationCommand, this.defaultValue.alternativeDeclarationCommand),
                alternativeImplementationCommand: EditorStringOption.string(input.alternativeImplementationCommand, this.defaultValue.alternativeImplementationCommand),
                alternativeReferenceCommand: EditorStringOption.string(input.alternativeReferenceCommand, this.defaultValue.alternativeReferenceCommand),
                alternativeTestsCommand: EditorStringOption.string(input.alternativeTestsCommand, this.defaultValue.alternativeTestsCommand),
            };
        }
    }
    class EditorHover extends BaseEditorOption {
        constructor() {
            const defaults = {
                enabled: true,
                delay: 300,
                hidingDelay: 300,
                sticky: true,
                above: true,
            };
            super(60 /* EditorOption.hover */, 'hover', defaults, {
                'editor.hover.enabled': {
                    type: 'boolean',
                    default: defaults.enabled,
                    description: nls.localize(225, "Controls whether the hover is shown.")
                },
                'editor.hover.delay': {
                    type: 'number',
                    default: defaults.delay,
                    minimum: 0,
                    maximum: 10000,
                    description: nls.localize(226, "Controls the delay in milliseconds after which the hover is shown.")
                },
                'editor.hover.sticky': {
                    type: 'boolean',
                    default: defaults.sticky,
                    description: nls.localize(227, "Controls whether the hover should remain visible when mouse is moved over it.")
                },
                'editor.hover.hidingDelay': {
                    type: 'integer',
                    minimum: 0,
                    default: defaults.hidingDelay,
                    description: nls.localize(228, "Controls the delay in milliseconds after which the hover is hidden. Requires `editor.hover.sticky` to be enabled.")
                },
                'editor.hover.above': {
                    type: 'boolean',
                    default: defaults.above,
                    description: nls.localize(229, "Prefer showing hovers above the line, if there's space.")
                },
            });
        }
        validate(_input) {
            if (!_input || typeof _input !== 'object') {
                return this.defaultValue;
            }
            const input = _input;
            return {
                enabled: boolean(input.enabled, this.defaultValue.enabled),
                delay: EditorIntOption.clampedInt(input.delay, this.defaultValue.delay, 0, 10000),
                sticky: boolean(input.sticky, this.defaultValue.sticky),
                hidingDelay: EditorIntOption.clampedInt(input.hidingDelay, this.defaultValue.hidingDelay, 0, 600000),
                above: boolean(input.above, this.defaultValue.above),
            };
        }
    }
    /**
     * @internal
     */
    class EditorLayoutInfoComputer extends ComputedEditorOption {
        constructor() {
            super(146 /* EditorOption.layoutInfo */);
        }
        compute(env, options, _) {
            return EditorLayoutInfoComputer.computeLayout(options, {
                memory: env.memory,
                outerWidth: env.outerWidth,
                outerHeight: env.outerHeight,
                isDominatedByLongLines: env.isDominatedByLongLines,
                lineHeight: env.fontInfo.lineHeight,
                viewLineCount: env.viewLineCount,
                lineNumbersDigitCount: env.lineNumbersDigitCount,
                typicalHalfwidthCharacterWidth: env.fontInfo.typicalHalfwidthCharacterWidth,
                maxDigitWidth: env.fontInfo.maxDigitWidth,
                pixelRatio: env.pixelRatio,
                glyphMarginDecorationLaneCount: env.glyphMarginDecorationLaneCount
            });
        }
        static computeContainedMinimapLineCount(input) {
            const typicalViewportLineCount = input.height / input.lineHeight;
            const extraLinesBeforeFirstLine = Math.floor(input.paddingTop / input.lineHeight);
            let extraLinesBeyondLastLine = Math.floor(input.paddingBottom / input.lineHeight);
            if (input.scrollBeyondLastLine) {
                extraLinesBeyondLastLine = Math.max(extraLinesBeyondLastLine, typicalViewportLineCount - 1);
            }
            const desiredRatio = (extraLinesBeforeFirstLine + input.viewLineCount + extraLinesBeyondLastLine) / (input.pixelRatio * input.height);
            const minimapLineCount = Math.floor(input.viewLineCount / desiredRatio);
            return { typicalViewportLineCount, extraLinesBeforeFirstLine, extraLinesBeyondLastLine, desiredRatio, minimapLineCount };
        }
        static _computeMinimapLayout(input, memory) {
            const outerWidth = input.outerWidth;
            const outerHeight = input.outerHeight;
            const pixelRatio = input.pixelRatio;
            if (!input.minimap.enabled) {
                return {
                    renderMinimap: 0 /* RenderMinimap.None */,
                    minimapLeft: 0,
                    minimapWidth: 0,
                    minimapHeightIsEditorHeight: false,
                    minimapIsSampling: false,
                    minimapScale: 1,
                    minimapLineHeight: 1,
                    minimapCanvasInnerWidth: 0,
                    minimapCanvasInnerHeight: Math.floor(pixelRatio * outerHeight),
                    minimapCanvasOuterWidth: 0,
                    minimapCanvasOuterHeight: outerHeight,
                };
            }
            // Can use memory if only the `viewLineCount` and `remainingWidth` have changed
            const stableMinimapLayoutInput = memory.stableMinimapLayoutInput;
            const couldUseMemory = (stableMinimapLayoutInput
                // && input.outerWidth === lastMinimapLayoutInput.outerWidth !!! INTENTIONAL OMITTED
                && input.outerHeight === stableMinimapLayoutInput.outerHeight
                && input.lineHeight === stableMinimapLayoutInput.lineHeight
                && input.typicalHalfwidthCharacterWidth === stableMinimapLayoutInput.typicalHalfwidthCharacterWidth
                && input.pixelRatio === stableMinimapLayoutInput.pixelRatio
                && input.scrollBeyondLastLine === stableMinimapLayoutInput.scrollBeyondLastLine
                && input.paddingTop === stableMinimapLayoutInput.paddingTop
                && input.paddingBottom === stableMinimapLayoutInput.paddingBottom
                && input.minimap.enabled === stableMinimapLayoutInput.minimap.enabled
                && input.minimap.side === stableMinimapLayoutInput.minimap.side
                && input.minimap.size === stableMinimapLayoutInput.minimap.size
                && input.minimap.showSlider === stableMinimapLayoutInput.minimap.showSlider
                && input.minimap.renderCharacters === stableMinimapLayoutInput.minimap.renderCharacters
                && input.minimap.maxColumn === stableMinimapLayoutInput.minimap.maxColumn
                && input.minimap.scale === stableMinimapLayoutInput.minimap.scale
                && input.verticalScrollbarWidth === stableMinimapLayoutInput.verticalScrollbarWidth
                // && input.viewLineCount === lastMinimapLayoutInput.viewLineCount !!! INTENTIONAL OMITTED
                // && input.remainingWidth === lastMinimapLayoutInput.remainingWidth !!! INTENTIONAL OMITTED
                && input.isViewportWrapping === stableMinimapLayoutInput.isViewportWrapping);
            const lineHeight = input.lineHeight;
            const typicalHalfwidthCharacterWidth = input.typicalHalfwidthCharacterWidth;
            const scrollBeyondLastLine = input.scrollBeyondLastLine;
            const minimapRenderCharacters = input.minimap.renderCharacters;
            let minimapScale = (pixelRatio >= 2 ? Math.round(input.minimap.scale * 2) : input.minimap.scale);
            const minimapMaxColumn = input.minimap.maxColumn;
            const minimapSize = input.minimap.size;
            const minimapSide = input.minimap.side;
            const verticalScrollbarWidth = input.verticalScrollbarWidth;
            const viewLineCount = input.viewLineCount;
            const remainingWidth = input.remainingWidth;
            const isViewportWrapping = input.isViewportWrapping;
            const baseCharHeight = minimapRenderCharacters ? 2 : 3;
            let minimapCanvasInnerHeight = Math.floor(pixelRatio * outerHeight);
            const minimapCanvasOuterHeight = minimapCanvasInnerHeight / pixelRatio;
            let minimapHeightIsEditorHeight = false;
            let minimapIsSampling = false;
            let minimapLineHeight = baseCharHeight * minimapScale;
            let minimapCharWidth = minimapScale / pixelRatio;
            let minimapWidthMultiplier = 1;
            if (minimapSize === 'fill' || minimapSize === 'fit') {
                const { typicalViewportLineCount, extraLinesBeforeFirstLine, extraLinesBeyondLastLine, desiredRatio, minimapLineCount } = EditorLayoutInfoComputer.computeContainedMinimapLineCount({
                    viewLineCount: viewLineCount,
                    scrollBeyondLastLine: scrollBeyondLastLine,
                    paddingTop: input.paddingTop,
                    paddingBottom: input.paddingBottom,
                    height: outerHeight,
                    lineHeight: lineHeight,
                    pixelRatio: pixelRatio
                });
                // ratio is intentionally not part of the layout to avoid the layout changing all the time
                // when doing sampling
                const ratio = viewLineCount / minimapLineCount;
                if (ratio > 1) {
                    minimapHeightIsEditorHeight = true;
                    minimapIsSampling = true;
                    minimapScale = 1;
                    minimapLineHeight = 1;
                    minimapCharWidth = minimapScale / pixelRatio;
                }
                else {
                    let fitBecomesFill = false;
                    let maxMinimapScale = minimapScale + 1;
                    if (minimapSize === 'fit') {
                        const effectiveMinimapHeight = Math.ceil((extraLinesBeforeFirstLine + viewLineCount + extraLinesBeyondLastLine) * minimapLineHeight);
                        if (isViewportWrapping && couldUseMemory && remainingWidth <= memory.stableFitRemainingWidth) {
                            // There is a loop when using `fit` and viewport wrapping:
                            // - view line count impacts minimap layout
                            // - minimap layout impacts viewport width
                            // - viewport width impacts view line count
                            // To break the loop, once we go to a smaller minimap scale, we try to stick with it.
                            fitBecomesFill = true;
                            maxMinimapScale = memory.stableFitMaxMinimapScale;
                        }
                        else {
                            fitBecomesFill = (effectiveMinimapHeight > minimapCanvasInnerHeight);
                        }
                    }
                    if (minimapSize === 'fill' || fitBecomesFill) {
                        minimapHeightIsEditorHeight = true;
                        const configuredMinimapScale = minimapScale;
                        minimapLineHeight = Math.min(lineHeight * pixelRatio, Math.max(1, Math.floor(1 / desiredRatio)));
                        if (isViewportWrapping && couldUseMemory && remainingWidth <= memory.stableFitRemainingWidth) {
                            // There is a loop when using `fill` and viewport wrapping:
                            // - view line count impacts minimap layout
                            // - minimap layout impacts viewport width
                            // - viewport width impacts view line count
                            // To break the loop, once we go to a smaller minimap scale, we try to stick with it.
                            maxMinimapScale = memory.stableFitMaxMinimapScale;
                        }
                        minimapScale = Math.min(maxMinimapScale, Math.max(1, Math.floor(minimapLineHeight / baseCharHeight)));
                        if (minimapScale > configuredMinimapScale) {
                            minimapWidthMultiplier = Math.min(2, minimapScale / configuredMinimapScale);
                        }
                        minimapCharWidth = minimapScale / pixelRatio / minimapWidthMultiplier;
                        minimapCanvasInnerHeight = Math.ceil((Math.max(typicalViewportLineCount, extraLinesBeforeFirstLine + viewLineCount + extraLinesBeyondLastLine)) * minimapLineHeight);
                        if (isViewportWrapping) {
                            // remember for next time
                            memory.stableMinimapLayoutInput = input;
                            memory.stableFitRemainingWidth = remainingWidth;
                            memory.stableFitMaxMinimapScale = minimapScale;
                        }
                        else {
                            memory.stableMinimapLayoutInput = null;
                            memory.stableFitRemainingWidth = 0;
                        }
                    }
                }
            }
            // Given:
            // (leaving 2px for the cursor to have space after the last character)
            // viewportColumn = (contentWidth - verticalScrollbarWidth - 2) / typicalHalfwidthCharacterWidth
            // minimapWidth = viewportColumn * minimapCharWidth
            // contentWidth = remainingWidth - minimapWidth
            // What are good values for contentWidth and minimapWidth ?
            // minimapWidth = ((contentWidth - verticalScrollbarWidth - 2) / typicalHalfwidthCharacterWidth) * minimapCharWidth
            // typicalHalfwidthCharacterWidth * minimapWidth = (contentWidth - verticalScrollbarWidth - 2) * minimapCharWidth
            // typicalHalfwidthCharacterWidth * minimapWidth = (remainingWidth - minimapWidth - verticalScrollbarWidth - 2) * minimapCharWidth
            // (typicalHalfwidthCharacterWidth + minimapCharWidth) * minimapWidth = (remainingWidth - verticalScrollbarWidth - 2) * minimapCharWidth
            // minimapWidth = ((remainingWidth - verticalScrollbarWidth - 2) * minimapCharWidth) / (typicalHalfwidthCharacterWidth + minimapCharWidth)
            const minimapMaxWidth = Math.floor(minimapMaxColumn * minimapCharWidth);
            const minimapWidth = Math.min(minimapMaxWidth, Math.max(0, Math.floor(((remainingWidth - verticalScrollbarWidth - 2) * minimapCharWidth) / (typicalHalfwidthCharacterWidth + minimapCharWidth))) + exports.MINIMAP_GUTTER_WIDTH);
            let minimapCanvasInnerWidth = Math.floor(pixelRatio * minimapWidth);
            const minimapCanvasOuterWidth = minimapCanvasInnerWidth / pixelRatio;
            minimapCanvasInnerWidth = Math.floor(minimapCanvasInnerWidth * minimapWidthMultiplier);
            const renderMinimap = (minimapRenderCharacters ? 1 /* RenderMinimap.Text */ : 2 /* RenderMinimap.Blocks */);
            const minimapLeft = (minimapSide === 'left' ? 0 : (outerWidth - minimapWidth - verticalScrollbarWidth));
            return {
                renderMinimap,
                minimapLeft,
                minimapWidth,
                minimapHeightIsEditorHeight,
                minimapIsSampling,
                minimapScale,
                minimapLineHeight,
                minimapCanvasInnerWidth,
                minimapCanvasInnerHeight,
                minimapCanvasOuterWidth,
                minimapCanvasOuterHeight,
            };
        }
        static computeLayout(options, env) {
            const outerWidth = env.outerWidth | 0;
            const outerHeight = env.outerHeight | 0;
            const lineHeight = env.lineHeight | 0;
            const lineNumbersDigitCount = env.lineNumbersDigitCount | 0;
            const typicalHalfwidthCharacterWidth = env.typicalHalfwidthCharacterWidth;
            const maxDigitWidth = env.maxDigitWidth;
            const pixelRatio = env.pixelRatio;
            const viewLineCount = env.viewLineCount;
            const wordWrapOverride2 = options.get(138 /* EditorOption.wordWrapOverride2 */);
            const wordWrapOverride1 = (wordWrapOverride2 === 'inherit' ? options.get(137 /* EditorOption.wordWrapOverride1 */) : wordWrapOverride2);
            const wordWrap = (wordWrapOverride1 === 'inherit' ? options.get(133 /* EditorOption.wordWrap */) : wordWrapOverride1);
            const wordWrapColumn = options.get(136 /* EditorOption.wordWrapColumn */);
            const isDominatedByLongLines = env.isDominatedByLongLines;
            const showGlyphMargin = options.get(57 /* EditorOption.glyphMargin */);
            const showLineNumbers = (options.get(68 /* EditorOption.lineNumbers */).renderType !== 0 /* RenderLineNumbersType.Off */);
            const lineNumbersMinChars = options.get(69 /* EditorOption.lineNumbersMinChars */);
            const scrollBeyondLastLine = options.get(106 /* EditorOption.scrollBeyondLastLine */);
            const padding = options.get(84 /* EditorOption.padding */);
            const minimap = options.get(73 /* EditorOption.minimap */);
            const scrollbar = options.get(104 /* EditorOption.scrollbar */);
            const verticalScrollbarWidth = scrollbar.verticalScrollbarSize;
            const verticalScrollbarHasArrows = scrollbar.verticalHasArrows;
            const scrollbarArrowSize = scrollbar.arrowSize;
            const horizontalScrollbarHeight = scrollbar.horizontalScrollbarSize;
            const folding = options.get(43 /* EditorOption.folding */);
            const showFoldingDecoration = options.get(111 /* EditorOption.showFoldingControls */) !== 'never';
            let lineDecorationsWidth = options.get(66 /* EditorOption.lineDecorationsWidth */);
            if (folding && showFoldingDecoration) {
                lineDecorationsWidth += 16;
            }
            let lineNumbersWidth = 0;
            if (showLineNumbers) {
                const digitCount = Math.max(lineNumbersDigitCount, lineNumbersMinChars);
                lineNumbersWidth = Math.round(digitCount * maxDigitWidth);
            }
            let glyphMarginWidth = 0;
            if (showGlyphMargin) {
                glyphMarginWidth = lineHeight * env.glyphMarginDecorationLaneCount;
            }
            let glyphMarginLeft = 0;
            let lineNumbersLeft = glyphMarginLeft + glyphMarginWidth;
            let decorationsLeft = lineNumbersLeft + lineNumbersWidth;
            let contentLeft = decorationsLeft + lineDecorationsWidth;
            const remainingWidth = outerWidth - glyphMarginWidth - lineNumbersWidth - lineDecorationsWidth;
            let isWordWrapMinified = false;
            let isViewportWrapping = false;
            let wrappingColumn = -1;
            if (wordWrapOverride1 === 'inherit' && isDominatedByLongLines) {
                // Force viewport width wrapping if model is dominated by long lines
                isWordWrapMinified = true;
                isViewportWrapping = true;
            }
            else if (wordWrap === 'on' || wordWrap === 'bounded') {
                isViewportWrapping = true;
            }
            else if (wordWrap === 'wordWrapColumn') {
                wrappingColumn = wordWrapColumn;
            }
            const minimapLayout = EditorLayoutInfoComputer._computeMinimapLayout({
                outerWidth: outerWidth,
                outerHeight: outerHeight,
                lineHeight: lineHeight,
                typicalHalfwidthCharacterWidth: typicalHalfwidthCharacterWidth,
                pixelRatio: pixelRatio,
                scrollBeyondLastLine: scrollBeyondLastLine,
                paddingTop: padding.top,
                paddingBottom: padding.bottom,
                minimap: minimap,
                verticalScrollbarWidth: verticalScrollbarWidth,
                viewLineCount: viewLineCount,
                remainingWidth: remainingWidth,
                isViewportWrapping: isViewportWrapping,
            }, env.memory || new ComputeOptionsMemory());
            if (minimapLayout.renderMinimap !== 0 /* RenderMinimap.None */ && minimapLayout.minimapLeft === 0) {
                // the minimap is rendered to the left, so move everything to the right
                glyphMarginLeft += minimapLayout.minimapWidth;
                lineNumbersLeft += minimapLayout.minimapWidth;
                decorationsLeft += minimapLayout.minimapWidth;
                contentLeft += minimapLayout.minimapWidth;
            }
            const contentWidth = remainingWidth - minimapLayout.minimapWidth;
            // (leaving 2px for the cursor to have space after the last character)
            const viewportColumn = Math.max(1, Math.floor((contentWidth - verticalScrollbarWidth - 2) / typicalHalfwidthCharacterWidth));
            const verticalArrowSize = (verticalScrollbarHasArrows ? scrollbarArrowSize : 0);
            if (isViewportWrapping) {
                // compute the actual wrappingColumn
                wrappingColumn = Math.max(1, viewportColumn);
                if (wordWrap === 'bounded') {
                    wrappingColumn = Math.min(wrappingColumn, wordWrapColumn);
                }
            }
            return {
                width: outerWidth,
                height: outerHeight,
                glyphMarginLeft: glyphMarginLeft,
                glyphMarginWidth: glyphMarginWidth,
                glyphMarginDecorationLaneCount: env.glyphMarginDecorationLaneCount,
                lineNumbersLeft: lineNumbersLeft,
                lineNumbersWidth: lineNumbersWidth,
                decorationsLeft: decorationsLeft,
                decorationsWidth: lineDecorationsWidth,
                contentLeft: contentLeft,
                contentWidth: contentWidth,
                minimap: minimapLayout,
                viewportColumn: viewportColumn,
                isWordWrapMinified: isWordWrapMinified,
                isViewportWrapping: isViewportWrapping,
                wrappingColumn: wrappingColumn,
                verticalScrollbarWidth: verticalScrollbarWidth,
                horizontalScrollbarHeight: horizontalScrollbarHeight,
                overviewRuler: {
                    top: verticalArrowSize,
                    width: verticalScrollbarWidth,
                    height: (outerHeight - 2 * verticalArrowSize),
                    right: 0
                }
            };
        }
    }
    exports.EditorLayoutInfoComputer = EditorLayoutInfoComputer;
    //#endregion
    //#region WrappingStrategy
    class WrappingStrategy extends BaseEditorOption {
        constructor() {
            super(140 /* EditorOption.wrappingStrategy */, 'wrappingStrategy', 'simple', {
                'editor.wrappingStrategy': {
                    enumDescriptions: [
                        nls.localize(230, "Assumes that all characters are of the same width. This is a fast algorithm that works correctly for monospace fonts and certain scripts (like Latin characters) where glyphs are of equal width."),
                        nls.localize(231, "Delegates wrapping points computation to the browser. This is a slow algorithm, that might cause freezes for large files, but it works correctly in all cases.")
                    ],
                    type: 'string',
                    enum: ['simple', 'advanced'],
                    default: 'simple',
                    description: nls.localize(232, "Controls the algorithm that computes wrapping points. Note that when in accessibility mode, advanced will be used for the best experience.")
                }
            });
        }
        validate(input) {
            return stringSet(input, 'simple', ['simple', 'advanced']);
        }
        compute(env, options, value) {
            const accessibilitySupport = options.get(2 /* EditorOption.accessibilitySupport */);
            if (accessibilitySupport === 2 /* AccessibilitySupport.Enabled */) {
                // if we know for a fact that a screen reader is attached, we switch our strategy to advanced to
                // help that the editor's wrapping points match the textarea's wrapping points
                return 'advanced';
            }
            return value;
        }
    }
    //#endregion
    //#region lightbulb
    var ShowLightbulbIconMode;
    (function (ShowLightbulbIconMode) {
        ShowLightbulbIconMode["Off"] = "off";
        ShowLightbulbIconMode["OnCode"] = "onCode";
        ShowLightbulbIconMode["On"] = "on";
    })(ShowLightbulbIconMode || (exports.ShowLightbulbIconMode = ShowLightbulbIconMode = {}));
    class EditorLightbulb extends BaseEditorOption {
        constructor() {
            const defaults = { enabled: ShowLightbulbIconMode.OnCode };
            super(65 /* EditorOption.lightbulb */, 'lightbulb', defaults, {
                'editor.lightbulb.enabled': {
                    type: 'string',
                    tags: ['experimental'],
                    enum: [ShowLightbulbIconMode.Off, ShowLightbulbIconMode.OnCode, ShowLightbulbIconMode.On],
                    default: defaults.enabled,
                    enumDescriptions: [
                        nls.localize(233, 'Disable the code action menu.'),
                        nls.localize(234, 'Show the code action menu when the cursor is on lines with code.'),
                        nls.localize(235, 'Show the code action menu when the cursor is on lines with code or on empty lines.'),
                    ],
                    description: nls.localize(236, "Enables the Code Action lightbulb in the editor.")
                }
            });
        }
        validate(_input) {
            if (!_input || typeof _input !== 'object') {
                return this.defaultValue;
            }
            const input = _input;
            return {
                enabled: stringSet(input.enabled, this.defaultValue.enabled, [ShowLightbulbIconMode.Off, ShowLightbulbIconMode.OnCode, ShowLightbulbIconMode.On])
            };
        }
    }
    class EditorStickyScroll extends BaseEditorOption {
        constructor() {
            const defaults = { enabled: true, maxLineCount: 5, defaultModel: 'outlineModel', scrollWithEditor: true };
            super(116 /* EditorOption.stickyScroll */, 'stickyScroll', defaults, {
                'editor.stickyScroll.enabled': {
                    type: 'boolean',
                    default: defaults.enabled,
                    description: nls.localize(237, "Shows the nested current scopes during the scroll at the top of the editor."),
                    tags: ['experimental']
                },
                'editor.stickyScroll.maxLineCount': {
                    type: 'number',
                    default: defaults.maxLineCount,
                    minimum: 1,
                    maximum: 20,
                    description: nls.localize(238, "Defines the maximum number of sticky lines to show.")
                },
                'editor.stickyScroll.defaultModel': {
                    type: 'string',
                    enum: ['outlineModel', 'foldingProviderModel', 'indentationModel'],
                    default: defaults.defaultModel,
                    description: nls.localize(239, "Defines the model to use for determining which lines to stick. If the outline model does not exist, it will fall back on the folding provider model which falls back on the indentation model. This order is respected in all three cases.")
                },
                'editor.stickyScroll.scrollWithEditor': {
                    type: 'boolean',
                    default: defaults.scrollWithEditor,
                    description: nls.localize(240, "Enable scrolling of Sticky Scroll with the editor's horizontal scrollbar.")
                },
            });
        }
        validate(_input) {
            if (!_input || typeof _input !== 'object') {
                return this.defaultValue;
            }
            const input = _input;
            return {
                enabled: boolean(input.enabled, this.defaultValue.enabled),
                maxLineCount: EditorIntOption.clampedInt(input.maxLineCount, this.defaultValue.maxLineCount, 1, 20),
                defaultModel: stringSet(input.defaultModel, this.defaultValue.defaultModel, ['outlineModel', 'foldingProviderModel', 'indentationModel']),
                scrollWithEditor: boolean(input.scrollWithEditor, this.defaultValue.scrollWithEditor)
            };
        }
    }
    class EditorInlayHints extends BaseEditorOption {
        constructor() {
            const defaults = { enabled: 'on', fontSize: 0, fontFamily: '', padding: false };
            super(142 /* EditorOption.inlayHints */, 'inlayHints', defaults, {
                'editor.inlayHints.enabled': {
                    type: 'string',
                    default: defaults.enabled,
                    description: nls.localize(241, "Enables the inlay hints in the editor."),
                    enum: ['on', 'onUnlessPressed', 'offUnlessPressed', 'off'],
                    markdownEnumDescriptions: [
                        nls.localize(242, "Inlay hints are enabled"),
                        nls.localize(243, "Inlay hints are showing by default and hide when holding {0}", platform.isMacintosh ? `Ctrl+Option` : `Ctrl+Alt`),
                        nls.localize(244, "Inlay hints are hidden by default and show when holding {0}", platform.isMacintosh ? `Ctrl+Option` : `Ctrl+Alt`),
                        nls.localize(245, "Inlay hints are disabled"),
                    ],
                },
                'editor.inlayHints.fontSize': {
                    type: 'number',
                    default: defaults.fontSize,
                    markdownDescription: nls.localize(246, "Controls font size of inlay hints in the editor. As default the {0} is used when the configured value is less than {1} or greater than the editor font size.", '`#editor.fontSize#`', '`5`')
                },
                'editor.inlayHints.fontFamily': {
                    type: 'string',
                    default: defaults.fontFamily,
                    markdownDescription: nls.localize(247, "Controls font family of inlay hints in the editor. When set to empty, the {0} is used.", '`#editor.fontFamily#`')
                },
                'editor.inlayHints.padding': {
                    type: 'boolean',
                    default: defaults.padding,
                    description: nls.localize(248, "Enables the padding around the inlay hints in the editor.")
                }
            });
        }
        validate(_input) {
            if (!_input || typeof _input !== 'object') {
                return this.defaultValue;
            }
            const input = _input;
            if (typeof input.enabled === 'boolean') {
                input.enabled = input.enabled ? 'on' : 'off';
            }
            return {
                enabled: stringSet(input.enabled, this.defaultValue.enabled, ['on', 'off', 'offUnlessPressed', 'onUnlessPressed']),
                fontSize: EditorIntOption.clampedInt(input.fontSize, this.defaultValue.fontSize, 0, 100),
                fontFamily: EditorStringOption.string(input.fontFamily, this.defaultValue.fontFamily),
                padding: boolean(input.padding, this.defaultValue.padding)
            };
        }
    }
    //#endregion
    //#region lineDecorationsWidth
    class EditorLineDecorationsWidth extends BaseEditorOption {
        constructor() {
            super(66 /* EditorOption.lineDecorationsWidth */, 'lineDecorationsWidth', 10);
        }
        validate(input) {
            if (typeof input === 'string' && /^\d+(\.\d+)?ch$/.test(input)) {
                const multiple = parseFloat(input.substring(0, input.length - 2));
                return -multiple; // negative numbers signal a multiple
            }
            else {
                return EditorIntOption.clampedInt(input, this.defaultValue, 0, 1000);
            }
        }
        compute(env, options, value) {
            if (value < 0) {
                // negative numbers signal a multiple
                return EditorIntOption.clampedInt(-value * env.fontInfo.typicalHalfwidthCharacterWidth, this.defaultValue, 0, 1000);
            }
            else {
                return value;
            }
        }
    }
    //#endregion
    //#region lineHeight
    class EditorLineHeight extends EditorFloatOption {
        constructor() {
            super(67 /* EditorOption.lineHeight */, 'lineHeight', exports.EDITOR_FONT_DEFAULTS.lineHeight, x => EditorFloatOption.clamp(x, 0, 150), { markdownDescription: nls.localize(249, "Controls the line height. \n - Use 0 to automatically compute the line height from the font size.\n - Values between 0 and 8 will be used as a multiplier with the font size.\n - Values greater than or equal to 8 will be used as effective values.") });
        }
        compute(env, options, value) {
            // The lineHeight is computed from the fontSize if it is 0.
            // Moreover, the final lineHeight respects the editor zoom level.
            // So take the result from env.fontInfo
            return env.fontInfo.lineHeight;
        }
    }
    class EditorMinimap extends BaseEditorOption {
        constructor() {
            const defaults = {
                enabled: true,
                size: 'proportional',
                side: 'right',
                showSlider: 'mouseover',
                autohide: false,
                renderCharacters: true,
                maxColumn: 120,
                scale: 1,
                showRegionSectionHeaders: true,
                showMarkSectionHeaders: true,
                sectionHeaderFontSize: 9,
                sectionHeaderLetterSpacing: 1,
            };
            super(73 /* EditorOption.minimap */, 'minimap', defaults, {
                'editor.minimap.enabled': {
                    type: 'boolean',
                    default: defaults.enabled,
                    description: nls.localize(250, "Controls whether the minimap is shown.")
                },
                'editor.minimap.autohide': {
                    type: 'boolean',
                    default: defaults.autohide,
                    description: nls.localize(251, "Controls whether the minimap is hidden automatically.")
                },
                'editor.minimap.size': {
                    type: 'string',
                    enum: ['proportional', 'fill', 'fit'],
                    enumDescriptions: [
                        nls.localize(252, "The minimap has the same size as the editor contents (and might scroll)."),
                        nls.localize(253, "The minimap will stretch or shrink as necessary to fill the height of the editor (no scrolling)."),
                        nls.localize(254, "The minimap will shrink as necessary to never be larger than the editor (no scrolling)."),
                    ],
                    default: defaults.size,
                    description: nls.localize(255, "Controls the size of the minimap.")
                },
                'editor.minimap.side': {
                    type: 'string',
                    enum: ['left', 'right'],
                    default: defaults.side,
                    description: nls.localize(256, "Controls the side where to render the minimap.")
                },
                'editor.minimap.showSlider': {
                    type: 'string',
                    enum: ['always', 'mouseover'],
                    default: defaults.showSlider,
                    description: nls.localize(257, "Controls when the minimap slider is shown.")
                },
                'editor.minimap.scale': {
                    type: 'number',
                    default: defaults.scale,
                    minimum: 1,
                    maximum: 3,
                    enum: [1, 2, 3],
                    description: nls.localize(258, "Scale of content drawn in the minimap: 1, 2 or 3.")
                },
                'editor.minimap.renderCharacters': {
                    type: 'boolean',
                    default: defaults.renderCharacters,
                    description: nls.localize(259, "Render the actual characters on a line as opposed to color blocks.")
                },
                'editor.minimap.maxColumn': {
                    type: 'number',
                    default: defaults.maxColumn,
                    description: nls.localize(260, "Limit the width of the minimap to render at most a certain number of columns.")
                },
                'editor.minimap.showRegionSectionHeaders': {
                    type: 'boolean',
                    default: defaults.showRegionSectionHeaders,
                    description: nls.localize(261, "Controls whether named regions are shown as section headers in the minimap.")
                },
                'editor.minimap.showMarkSectionHeaders': {
                    type: 'boolean',
                    default: defaults.showMarkSectionHeaders,
                    description: nls.localize(262, "Controls whether MARK: comments are shown as section headers in the minimap.")
                },
                'editor.minimap.sectionHeaderFontSize': {
                    type: 'number',
                    default: defaults.sectionHeaderFontSize,
                    description: nls.localize(263, "Controls the font size of section headers in the minimap.")
                },
                'editor.minimap.sectionHeaderLetterSpacing': {
                    type: 'number',
                    default: defaults.sectionHeaderLetterSpacing,
                    description: nls.localize(264, "Controls the amount of space (in pixels) between characters of section header. This helps the readability of the header in small font sizes.")
                }
            });
        }
        validate(_input) {
            if (!_input || typeof _input !== 'object') {
                return this.defaultValue;
            }
            const input = _input;
            return {
                enabled: boolean(input.enabled, this.defaultValue.enabled),
                autohide: boolean(input.autohide, this.defaultValue.autohide),
                size: stringSet(input.size, this.defaultValue.size, ['proportional', 'fill', 'fit']),
                side: stringSet(input.side, this.defaultValue.side, ['right', 'left']),
                showSlider: stringSet(input.showSlider, this.defaultValue.showSlider, ['always', 'mouseover']),
                renderCharacters: boolean(input.renderCharacters, this.defaultValue.renderCharacters),
                scale: EditorIntOption.clampedInt(input.scale, 1, 1, 3),
                maxColumn: EditorIntOption.clampedInt(input.maxColumn, this.defaultValue.maxColumn, 1, 10000),
                showRegionSectionHeaders: boolean(input.showRegionSectionHeaders, this.defaultValue.showRegionSectionHeaders),
                showMarkSectionHeaders: boolean(input.showMarkSectionHeaders, this.defaultValue.showMarkSectionHeaders),
                sectionHeaderFontSize: EditorFloatOption.clamp(input.sectionHeaderFontSize ?? this.defaultValue.sectionHeaderFontSize, 4, 32),
                sectionHeaderLetterSpacing: EditorFloatOption.clamp(input.sectionHeaderLetterSpacing ?? this.defaultValue.sectionHeaderLetterSpacing, 0, 5),
            };
        }
    }
    //#endregion
    //#region multiCursorModifier
    function _multiCursorModifierFromString(multiCursorModifier) {
        if (multiCursorModifier === 'ctrlCmd') {
            return (platform.isMacintosh ? 'metaKey' : 'ctrlKey');
        }
        return 'altKey';
    }
    class EditorPadding extends BaseEditorOption {
        constructor() {
            super(84 /* EditorOption.padding */, 'padding', { top: 0, bottom: 0 }, {
                'editor.padding.top': {
                    type: 'number',
                    default: 0,
                    minimum: 0,
                    maximum: 1000,
                    description: nls.localize(265, "Controls the amount of space between the top edge of the editor and the first line.")
                },
                'editor.padding.bottom': {
                    type: 'number',
                    default: 0,
                    minimum: 0,
                    maximum: 1000,
                    description: nls.localize(266, "Controls the amount of space between the bottom edge of the editor and the last line.")
                }
            });
        }
        validate(_input) {
            if (!_input || typeof _input !== 'object') {
                return this.defaultValue;
            }
            const input = _input;
            return {
                top: EditorIntOption.clampedInt(input.top, 0, 0, 1000),
                bottom: EditorIntOption.clampedInt(input.bottom, 0, 0, 1000)
            };
        }
    }
    class EditorParameterHints extends BaseEditorOption {
        constructor() {
            const defaults = {
                enabled: true,
                cycle: true
            };
            super(86 /* EditorOption.parameterHints */, 'parameterHints', defaults, {
                'editor.parameterHints.enabled': {
                    type: 'boolean',
                    default: defaults.enabled,
                    description: nls.localize(267, "Enables a pop-up that shows parameter documentation and type information as you type.")
                },
                'editor.parameterHints.cycle': {
                    type: 'boolean',
                    default: defaults.cycle,
                    description: nls.localize(268, "Controls whether the parameter hints menu cycles or closes when reaching the end of the list.")
                },
            });
        }
        validate(_input) {
            if (!_input || typeof _input !== 'object') {
                return this.defaultValue;
            }
            const input = _input;
            return {
                enabled: boolean(input.enabled, this.defaultValue.enabled),
                cycle: boolean(input.cycle, this.defaultValue.cycle)
            };
        }
    }
    //#endregion
    //#region pixelRatio
    class EditorPixelRatio extends ComputedEditorOption {
        constructor() {
            super(144 /* EditorOption.pixelRatio */);
        }
        compute(env, options, _) {
            return env.pixelRatio;
        }
    }
    //#endregion
    //#region
    class PlaceholderOption extends BaseEditorOption {
        constructor() {
            super(88 /* EditorOption.placeholder */, 'placeholder', undefined);
        }
        validate(input) {
            if (typeof input === 'undefined') {
                return this.defaultValue;
            }
            if (typeof input === 'string') {
                return input;
            }
            return this.defaultValue;
        }
    }
    class EditorQuickSuggestions extends BaseEditorOption {
        constructor() {
            const defaults = {
                other: 'on',
                comments: 'off',
                strings: 'off'
            };
            const types = [
                { type: 'boolean' },
                {
                    type: 'string',
                    enum: ['on', 'inline', 'off'],
                    enumDescriptions: [nls.localize(269, "Quick suggestions show inside the suggest widget"), nls.localize(270, "Quick suggestions show as ghost text"), nls.localize(271, "Quick suggestions are disabled")]
                }
            ];
            super(90 /* EditorOption.quickSuggestions */, 'quickSuggestions', defaults, {
                type: 'object',
                additionalProperties: false,
                properties: {
                    strings: {
                        anyOf: types,
                        default: defaults.strings,
                        description: nls.localize(272, "Enable quick suggestions inside strings.")
                    },
                    comments: {
                        anyOf: types,
                        default: defaults.comments,
                        description: nls.localize(273, "Enable quick suggestions inside comments.")
                    },
                    other: {
                        anyOf: types,
                        default: defaults.other,
                        description: nls.localize(274, "Enable quick suggestions outside of strings and comments.")
                    },
                },
                default: defaults,
                markdownDescription: nls.localize(275, "Controls whether suggestions should automatically show up while typing. This can be controlled for typing in comments, strings, and other code. Quick suggestion can be configured to show as ghost text or with the suggest widget. Also be aware of the {0}-setting which controls if suggestions are triggered by special characters.", '`#editor.suggestOnTriggerCharacters#`')
            });
            this.defaultValue = defaults;
        }
        validate(input) {
            if (typeof input === 'boolean') {
                // boolean -> all on/off
                const value = input ? 'on' : 'off';
                return { comments: value, strings: value, other: value };
            }
            if (!input || typeof input !== 'object') {
                // invalid object
                return this.defaultValue;
            }
            const { other, comments, strings } = input;
            const allowedValues = ['on', 'inline', 'off'];
            let validatedOther;
            let validatedComments;
            let validatedStrings;
            if (typeof other === 'boolean') {
                validatedOther = other ? 'on' : 'off';
            }
            else {
                validatedOther = stringSet(other, this.defaultValue.other, allowedValues);
            }
            if (typeof comments === 'boolean') {
                validatedComments = comments ? 'on' : 'off';
            }
            else {
                validatedComments = stringSet(comments, this.defaultValue.comments, allowedValues);
            }
            if (typeof strings === 'boolean') {
                validatedStrings = strings ? 'on' : 'off';
            }
            else {
                validatedStrings = stringSet(strings, this.defaultValue.strings, allowedValues);
            }
            return {
                other: validatedOther,
                comments: validatedComments,
                strings: validatedStrings
            };
        }
    }
    class EditorRenderLineNumbersOption extends BaseEditorOption {
        constructor() {
            super(68 /* EditorOption.lineNumbers */, 'lineNumbers', { renderType: 1 /* RenderLineNumbersType.On */, renderFn: null }, {
                type: 'string',
                enum: ['off', 'on', 'relative', 'interval'],
                enumDescriptions: [
                    nls.localize(276, "Line numbers are not rendered."),
                    nls.localize(277, "Line numbers are rendered as absolute number."),
                    nls.localize(278, "Line numbers are rendered as distance in lines to cursor position."),
                    nls.localize(279, "Line numbers are rendered every 10 lines.")
                ],
                default: 'on',
                description: nls.localize(280, "Controls the display of line numbers.")
            });
        }
        validate(lineNumbers) {
            let renderType = this.defaultValue.renderType;
            let renderFn = this.defaultValue.renderFn;
            if (typeof lineNumbers !== 'undefined') {
                if (typeof lineNumbers === 'function') {
                    renderType = 4 /* RenderLineNumbersType.Custom */;
                    renderFn = lineNumbers;
                }
                else if (lineNumbers === 'interval') {
                    renderType = 3 /* RenderLineNumbersType.Interval */;
                }
                else if (lineNumbers === 'relative') {
                    renderType = 2 /* RenderLineNumbersType.Relative */;
                }
                else if (lineNumbers === 'on') {
                    renderType = 1 /* RenderLineNumbersType.On */;
                }
                else {
                    renderType = 0 /* RenderLineNumbersType.Off */;
                }
            }
            return {
                renderType,
                renderFn
            };
        }
    }
    //#endregion
    //#region renderValidationDecorations
    /**
     * @internal
     */
    function filterValidationDecorations(options) {
        const renderValidationDecorations = options.get(99 /* EditorOption.renderValidationDecorations */);
        if (renderValidationDecorations === 'editable') {
            return options.get(92 /* EditorOption.readOnly */);
        }
        return renderValidationDecorations === 'on' ? false : true;
    }
    class EditorRulers extends BaseEditorOption {
        constructor() {
            const defaults = [];
            const columnSchema = { type: 'number', description: nls.localize(281, "Number of monospace characters at which this editor ruler will render.") };
            super(103 /* EditorOption.rulers */, 'rulers', defaults, {
                type: 'array',
                items: {
                    anyOf: [
                        columnSchema,
                        {
                            type: [
                                'object'
                            ],
                            properties: {
                                column: columnSchema,
                                color: {
                                    type: 'string',
                                    description: nls.localize(282, "Color of this editor ruler."),
                                    format: 'color-hex'
                                }
                            }
                        }
                    ]
                },
                default: defaults,
                description: nls.localize(283, "Render vertical rulers after a certain number of monospace characters. Use multiple values for multiple rulers. No rulers are drawn if array is empty.")
            });
        }
        validate(input) {
            if (Array.isArray(input)) {
                const rulers = [];
                for (const _element of input) {
                    if (typeof _element === 'number') {
                        rulers.push({
                            column: EditorIntOption.clampedInt(_element, 0, 0, 10000),
                            color: null
                        });
                    }
                    else if (_element && typeof _element === 'object') {
                        const element = _element;
                        rulers.push({
                            column: EditorIntOption.clampedInt(element.column, 0, 0, 10000),
                            color: element.color
                        });
                    }
                }
                rulers.sort((a, b) => a.column - b.column);
                return rulers;
            }
            return this.defaultValue;
        }
    }
    //#endregion
    //#region readonly
    /**
     * Configuration options for readonly message
     */
    class ReadonlyMessage extends BaseEditorOption {
        constructor() {
            const defaults = undefined;
            super(93 /* EditorOption.readOnlyMessage */, 'readOnlyMessage', defaults);
        }
        validate(_input) {
            if (!_input || typeof _input !== 'object') {
                return this.defaultValue;
            }
            return _input;
        }
    }
    function _scrollbarVisibilityFromString(visibility, defaultValue) {
        if (typeof visibility !== 'string') {
            return defaultValue;
        }
        switch (visibility) {
            case 'hidden': return 2 /* ScrollbarVisibility.Hidden */;
            case 'visible': return 3 /* ScrollbarVisibility.Visible */;
            default: return 1 /* ScrollbarVisibility.Auto */;
        }
    }
    class EditorScrollbar extends BaseEditorOption {
        constructor() {
            const defaults = {
                vertical: 1 /* ScrollbarVisibility.Auto */,
                horizontal: 1 /* ScrollbarVisibility.Auto */,
                arrowSize: 11,
                useShadows: true,
                verticalHasArrows: false,
                horizontalHasArrows: false,
                horizontalScrollbarSize: 12,
                horizontalSliderSize: 12,
                verticalScrollbarSize: 14,
                verticalSliderSize: 14,
                handleMouseWheel: true,
                alwaysConsumeMouseWheel: true,
                scrollByPage: false,
                ignoreHorizontalScrollbarInContentHeight: false,
            };
            super(104 /* EditorOption.scrollbar */, 'scrollbar', defaults, {
                'editor.scrollbar.vertical': {
                    type: 'string',
                    enum: ['auto', 'visible', 'hidden'],
                    enumDescriptions: [
                        nls.localize(284, "The vertical scrollbar will be visible only when necessary."),
                        nls.localize(285, "The vertical scrollbar will always be visible."),
                        nls.localize(286, "The vertical scrollbar will always be hidden."),
                    ],
                    default: 'auto',
                    description: nls.localize(287, "Controls the visibility of the vertical scrollbar.")
                },
                'editor.scrollbar.horizontal': {
                    type: 'string',
                    enum: ['auto', 'visible', 'hidden'],
                    enumDescriptions: [
                        nls.localize(288, "The horizontal scrollbar will be visible only when necessary."),
                        nls.localize(289, "The horizontal scrollbar will always be visible."),
                        nls.localize(290, "The horizontal scrollbar will always be hidden."),
                    ],
                    default: 'auto',
                    description: nls.localize(291, "Controls the visibility of the horizontal scrollbar.")
                },
                'editor.scrollbar.verticalScrollbarSize': {
                    type: 'number',
                    default: defaults.verticalScrollbarSize,
                    description: nls.localize(292, "The width of the vertical scrollbar.")
                },
                'editor.scrollbar.horizontalScrollbarSize': {
                    type: 'number',
                    default: defaults.horizontalScrollbarSize,
                    description: nls.localize(293, "The height of the horizontal scrollbar.")
                },
                'editor.scrollbar.scrollByPage': {
                    type: 'boolean',
                    default: defaults.scrollByPage,
                    description: nls.localize(294, "Controls whether clicks scroll by page or jump to click position.")
                },
                'editor.scrollbar.ignoreHorizontalScrollbarInContentHeight': {
                    type: 'boolean',
                    default: defaults.ignoreHorizontalScrollbarInContentHeight,
                    description: nls.localize(295, "When set, the horizontal scrollbar will not increase the size of the editor's content.")
                }
            });
        }
        validate(_input) {
            if (!_input || typeof _input !== 'object') {
                return this.defaultValue;
            }
            const input = _input;
            const horizontalScrollbarSize = EditorIntOption.clampedInt(input.horizontalScrollbarSize, this.defaultValue.horizontalScrollbarSize, 0, 1000);
            const verticalScrollbarSize = EditorIntOption.clampedInt(input.verticalScrollbarSize, this.defaultValue.verticalScrollbarSize, 0, 1000);
            return {
                arrowSize: EditorIntOption.clampedInt(input.arrowSize, this.defaultValue.arrowSize, 0, 1000),
                vertical: _scrollbarVisibilityFromString(input.vertical, this.defaultValue.vertical),
                horizontal: _scrollbarVisibilityFromString(input.horizontal, this.defaultValue.horizontal),
                useShadows: boolean(input.useShadows, this.defaultValue.useShadows),
                verticalHasArrows: boolean(input.verticalHasArrows, this.defaultValue.verticalHasArrows),
                horizontalHasArrows: boolean(input.horizontalHasArrows, this.defaultValue.horizontalHasArrows),
                handleMouseWheel: boolean(input.handleMouseWheel, this.defaultValue.handleMouseWheel),
                alwaysConsumeMouseWheel: boolean(input.alwaysConsumeMouseWheel, this.defaultValue.alwaysConsumeMouseWheel),
                horizontalScrollbarSize: horizontalScrollbarSize,
                horizontalSliderSize: EditorIntOption.clampedInt(input.horizontalSliderSize, horizontalScrollbarSize, 0, 1000),
                verticalScrollbarSize: verticalScrollbarSize,
                verticalSliderSize: EditorIntOption.clampedInt(input.verticalSliderSize, verticalScrollbarSize, 0, 1000),
                scrollByPage: boolean(input.scrollByPage, this.defaultValue.scrollByPage),
                ignoreHorizontalScrollbarInContentHeight: boolean(input.ignoreHorizontalScrollbarInContentHeight, this.defaultValue.ignoreHorizontalScrollbarInContentHeight),
            };
        }
    }
    /**
     * @internal
    */
    exports.inUntrustedWorkspace = 'inUntrustedWorkspace';
    /**
     * @internal
     */
    exports.unicodeHighlightConfigKeys = {
        allowedCharacters: 'editor.unicodeHighlight.allowedCharacters',
        invisibleCharacters: 'editor.unicodeHighlight.invisibleCharacters',
        nonBasicASCII: 'editor.unicodeHighlight.nonBasicASCII',
        ambiguousCharacters: 'editor.unicodeHighlight.ambiguousCharacters',
        includeComments: 'editor.unicodeHighlight.includeComments',
        includeStrings: 'editor.unicodeHighlight.includeStrings',
        allowedLocales: 'editor.unicodeHighlight.allowedLocales',
    };
    class UnicodeHighlight extends BaseEditorOption {
        constructor() {
            const defaults = {
                nonBasicASCII: exports.inUntrustedWorkspace,
                invisibleCharacters: true,
                ambiguousCharacters: true,
                includeComments: exports.inUntrustedWorkspace,
                includeStrings: true,
                allowedCharacters: {},
                allowedLocales: { _os: true, _vscode: true },
            };
            super(126 /* EditorOption.unicodeHighlighting */, 'unicodeHighlight', defaults, {
                [exports.unicodeHighlightConfigKeys.nonBasicASCII]: {
                    restricted: true,
                    type: ['boolean', 'string'],
                    enum: [true, false, exports.inUntrustedWorkspace],
                    default: defaults.nonBasicASCII,
                    description: nls.localize(296, "Controls whether all non-basic ASCII characters are highlighted. Only characters between U+0020 and U+007E, tab, line-feed and carriage-return are considered basic ASCII.")
                },
                [exports.unicodeHighlightConfigKeys.invisibleCharacters]: {
                    restricted: true,
                    type: 'boolean',
                    default: defaults.invisibleCharacters,
                    description: nls.localize(297, "Controls whether characters that just reserve space or have no width at all are highlighted.")
                },
                [exports.unicodeHighlightConfigKeys.ambiguousCharacters]: {
                    restricted: true,
                    type: 'boolean',
                    default: defaults.ambiguousCharacters,
                    description: nls.localize(298, "Controls whether characters are highlighted that can be confused with basic ASCII characters, except those that are common in the current user locale.")
                },
                [exports.unicodeHighlightConfigKeys.includeComments]: {
                    restricted: true,
                    type: ['boolean', 'string'],
                    enum: [true, false, exports.inUntrustedWorkspace],
                    default: defaults.includeComments,
                    description: nls.localize(299, "Controls whether characters in comments should also be subject to Unicode highlighting.")
                },
                [exports.unicodeHighlightConfigKeys.includeStrings]: {
                    restricted: true,
                    type: ['boolean', 'string'],
                    enum: [true, false, exports.inUntrustedWorkspace],
                    default: defaults.includeStrings,
                    description: nls.localize(300, "Controls whether characters in strings should also be subject to Unicode highlighting.")
                },
                [exports.unicodeHighlightConfigKeys.allowedCharacters]: {
                    restricted: true,
                    type: 'object',
                    default: defaults.allowedCharacters,
                    description: nls.localize(301, "Defines allowed characters that are not being highlighted."),
                    additionalProperties: {
                        type: 'boolean'
                    }
                },
                [exports.unicodeHighlightConfigKeys.allowedLocales]: {
                    restricted: true,
                    type: 'object',
                    additionalProperties: {
                        type: 'boolean'
                    },
                    default: defaults.allowedLocales,
                    description: nls.localize(302, "Unicode characters that are common in allowed locales are not being highlighted.")
                },
            });
        }
        applyUpdate(value, update) {
            let didChange = false;
            if (update.allowedCharacters && value) {
                // Treat allowedCharacters atomically
                if (!objects.equals(value.allowedCharacters, update.allowedCharacters)) {
                    value = { ...value, allowedCharacters: update.allowedCharacters };
                    didChange = true;
                }
            }
            if (update.allowedLocales && value) {
                // Treat allowedLocales atomically
                if (!objects.equals(value.allowedLocales, update.allowedLocales)) {
                    value = { ...value, allowedLocales: update.allowedLocales };
                    didChange = true;
                }
            }
            const result = super.applyUpdate(value, update);
            if (didChange) {
                return new ApplyUpdateResult(result.newValue, true);
            }
            return result;
        }
        validate(_input) {
            if (!_input || typeof _input !== 'object') {
                return this.defaultValue;
            }
            const input = _input;
            return {
                nonBasicASCII: primitiveSet(input.nonBasicASCII, exports.inUntrustedWorkspace, [true, false, exports.inUntrustedWorkspace]),
                invisibleCharacters: boolean(input.invisibleCharacters, this.defaultValue.invisibleCharacters),
                ambiguousCharacters: boolean(input.ambiguousCharacters, this.defaultValue.ambiguousCharacters),
                includeComments: primitiveSet(input.includeComments, exports.inUntrustedWorkspace, [true, false, exports.inUntrustedWorkspace]),
                includeStrings: primitiveSet(input.includeStrings, exports.inUntrustedWorkspace, [true, false, exports.inUntrustedWorkspace]),
                allowedCharacters: this.validateBooleanMap(_input.allowedCharacters, this.defaultValue.allowedCharacters),
                allowedLocales: this.validateBooleanMap(_input.allowedLocales, this.defaultValue.allowedLocales),
            };
        }
        validateBooleanMap(map, defaultValue) {
            if ((typeof map !== 'object') || !map) {
                return defaultValue;
            }
            const result = {};
            for (const [key, value] of Object.entries(map)) {
                if (value === true) {
                    result[key] = true;
                }
            }
            return result;
        }
    }
    /**
     * Configuration options for inline suggestions
     */
    class InlineEditorSuggest extends BaseEditorOption {
        constructor() {
            const defaults = {
                enabled: true,
                mode: 'subwordSmart',
                showToolbar: 'onHover',
                suppressSuggestions: false,
                keepOnBlur: false,
                fontFamily: 'default'
            };
            super(62 /* EditorOption.inlineSuggest */, 'inlineSuggest', defaults, {
                'editor.inlineSuggest.enabled': {
                    type: 'boolean',
                    default: defaults.enabled,
                    description: nls.localize(303, "Controls whether to automatically show inline suggestions in the editor.")
                },
                'editor.inlineSuggest.showToolbar': {
                    type: 'string',
                    default: defaults.showToolbar,
                    enum: ['always', 'onHover', 'never'],
                    enumDescriptions: [
                        nls.localize(304, "Show the inline suggestion toolbar whenever an inline suggestion is shown."),
                        nls.localize(305, "Show the inline suggestion toolbar when hovering over an inline suggestion."),
                        nls.localize(306, "Never show the inline suggestion toolbar."),
                    ],
                    description: nls.localize(307, "Controls when to show the inline suggestion toolbar."),
                },
                'editor.inlineSuggest.suppressSuggestions': {
                    type: 'boolean',
                    default: defaults.suppressSuggestions,
                    description: nls.localize(308, "Controls how inline suggestions interact with the suggest widget. If enabled, the suggest widget is not shown automatically when inline suggestions are available.")
                },
                'editor.inlineSuggest.fontFamily': {
                    type: 'string',
                    default: defaults.fontFamily,
                    description: nls.localize(309, "Controls the font family of the inline suggestions.")
                },
            });
        }
        validate(_input) {
            if (!_input || typeof _input !== 'object') {
                return this.defaultValue;
            }
            const input = _input;
            return {
                enabled: boolean(input.enabled, this.defaultValue.enabled),
                mode: stringSet(input.mode, this.defaultValue.mode, ['prefix', 'subword', 'subwordSmart']),
                showToolbar: stringSet(input.showToolbar, this.defaultValue.showToolbar, ['always', 'onHover', 'never']),
                suppressSuggestions: boolean(input.suppressSuggestions, this.defaultValue.suppressSuggestions),
                keepOnBlur: boolean(input.keepOnBlur, this.defaultValue.keepOnBlur),
                fontFamily: EditorStringOption.string(input.fontFamily, this.defaultValue.fontFamily)
            };
        }
    }
    class InlineEditorEdit extends BaseEditorOption {
        constructor() {
            const defaults = {
                enabled: false,
                showToolbar: 'onHover',
                fontFamily: 'default',
                keepOnBlur: false,
            };
            super(63 /* EditorOption.inlineEdit */, 'experimentalInlineEdit', defaults, {
                'editor.experimentalInlineEdit.enabled': {
                    type: 'boolean',
                    default: defaults.enabled,
                    description: nls.localize(310, "Controls whether to show inline edits in the editor.")
                },
                'editor.experimentalInlineEdit.showToolbar': {
                    type: 'string',
                    default: defaults.showToolbar,
                    enum: ['always', 'onHover', 'never'],
                    enumDescriptions: [
                        nls.localize(311, "Show the inline edit toolbar whenever an inline suggestion is shown."),
                        nls.localize(312, "Show the inline edit toolbar when hovering over an inline suggestion."),
                        nls.localize(313, "Never show the inline edit toolbar."),
                    ],
                    description: nls.localize(314, "Controls when to show the inline edit toolbar."),
                },
                'editor.experimentalInlineEdit.fontFamily': {
                    type: 'string',
                    default: defaults.fontFamily,
                    description: nls.localize(315, "Controls the font family of the inline edit.")
                },
            });
        }
        validate(_input) {
            if (!_input || typeof _input !== 'object') {
                return this.defaultValue;
            }
            const input = _input;
            return {
                enabled: boolean(input.enabled, this.defaultValue.enabled),
                showToolbar: stringSet(input.showToolbar, this.defaultValue.showToolbar, ['always', 'onHover', 'never']),
                fontFamily: EditorStringOption.string(input.fontFamily, this.defaultValue.fontFamily),
                keepOnBlur: boolean(input.keepOnBlur, this.defaultValue.keepOnBlur),
            };
        }
    }
    /**
     * Configuration options for inline suggestions
     */
    class BracketPairColorization extends BaseEditorOption {
        constructor() {
            const defaults = {
                enabled: textModelDefaults_1.EDITOR_MODEL_DEFAULTS.bracketPairColorizationOptions.enabled,
                independentColorPoolPerBracketType: textModelDefaults_1.EDITOR_MODEL_DEFAULTS.bracketPairColorizationOptions.independentColorPoolPerBracketType,
            };
            super(15 /* EditorOption.bracketPairColorization */, 'bracketPairColorization', defaults, {
                'editor.bracketPairColorization.enabled': {
                    type: 'boolean',
                    default: defaults.enabled,
                    markdownDescription: nls.localize(316, "Controls whether bracket pair colorization is enabled or not. Use {0} to override the bracket highlight colors.", '`#workbench.colorCustomizations#`')
                },
                'editor.bracketPairColorization.independentColorPoolPerBracketType': {
                    type: 'boolean',
                    default: defaults.independentColorPoolPerBracketType,
                    description: nls.localize(317, "Controls whether each bracket type has its own independent color pool.")
                },
            });
        }
        validate(_input) {
            if (!_input || typeof _input !== 'object') {
                return this.defaultValue;
            }
            const input = _input;
            return {
                enabled: boolean(input.enabled, this.defaultValue.enabled),
                independentColorPoolPerBracketType: boolean(input.independentColorPoolPerBracketType, this.defaultValue.independentColorPoolPerBracketType),
            };
        }
    }
    /**
     * Configuration options for inline suggestions
     */
    class GuideOptions extends BaseEditorOption {
        constructor() {
            const defaults = {
                bracketPairs: false,
                bracketPairsHorizontal: 'active',
                highlightActiveBracketPair: true,
                indentation: true,
                highlightActiveIndentation: true
            };
            super(16 /* EditorOption.guides */, 'guides', defaults, {
                'editor.guides.bracketPairs': {
                    type: ['boolean', 'string'],
                    enum: [true, 'active', false],
                    enumDescriptions: [
                        nls.localize(318, "Enables bracket pair guides."),
                        nls.localize(319, "Enables bracket pair guides only for the active bracket pair."),
                        nls.localize(320, "Disables bracket pair guides."),
                    ],
                    default: defaults.bracketPairs,
                    description: nls.localize(321, "Controls whether bracket pair guides are enabled or not.")
                },
                'editor.guides.bracketPairsHorizontal': {
                    type: ['boolean', 'string'],
                    enum: [true, 'active', false],
                    enumDescriptions: [
                        nls.localize(322, "Enables horizontal guides as addition to vertical bracket pair guides."),
                        nls.localize(323, "Enables horizontal guides only for the active bracket pair."),
                        nls.localize(324, "Disables horizontal bracket pair guides."),
                    ],
                    default: defaults.bracketPairsHorizontal,
                    description: nls.localize(325, "Controls whether horizontal bracket pair guides are enabled or not.")
                },
                'editor.guides.highlightActiveBracketPair': {
                    type: 'boolean',
                    default: defaults.highlightActiveBracketPair,
                    description: nls.localize(326, "Controls whether the editor should highlight the active bracket pair.")
                },
                'editor.guides.indentation': {
                    type: 'boolean',
                    default: defaults.indentation,
                    description: nls.localize(327, "Controls whether the editor should render indent guides.")
                },
                'editor.guides.highlightActiveIndentation': {
                    type: ['boolean', 'string'],
                    enum: [true, 'always', false],
                    enumDescriptions: [
                        nls.localize(328, "Highlights the active indent guide."),
                        nls.localize(329, "Highlights the active indent guide even if bracket guides are highlighted."),
                        nls.localize(330, "Do not highlight the active indent guide."),
                    ],
                    default: defaults.highlightActiveIndentation,
                    description: nls.localize(331, "Controls whether the editor should highlight the active indent guide.")
                }
            });
        }
        validate(_input) {
            if (!_input || typeof _input !== 'object') {
                return this.defaultValue;
            }
            const input = _input;
            return {
                bracketPairs: primitiveSet(input.bracketPairs, this.defaultValue.bracketPairs, [true, false, 'active']),
                bracketPairsHorizontal: primitiveSet(input.bracketPairsHorizontal, this.defaultValue.bracketPairsHorizontal, [true, false, 'active']),
                highlightActiveBracketPair: boolean(input.highlightActiveBracketPair, this.defaultValue.highlightActiveBracketPair),
                indentation: boolean(input.indentation, this.defaultValue.indentation),
                highlightActiveIndentation: primitiveSet(input.highlightActiveIndentation, this.defaultValue.highlightActiveIndentation, [true, false, 'always']),
            };
        }
    }
    function primitiveSet(value, defaultValue, allowedValues) {
        const idx = allowedValues.indexOf(value);
        if (idx === -1) {
            return defaultValue;
        }
        return allowedValues[idx];
    }
    class EditorSuggest extends BaseEditorOption {
        constructor() {
            const defaults = {
                insertMode: 'insert',
                filterGraceful: true,
                snippetsPreventQuickSuggestions: false,
                localityBonus: false,
                shareSuggestSelections: false,
                selectionMode: 'always',
                showIcons: true,
                showStatusBar: false,
                preview: false,
                previewMode: 'subwordSmart',
                showInlineDetails: true,
                showMethods: true,
                showFunctions: true,
                showConstructors: true,
                showDeprecated: true,
                matchOnWordStartOnly: true,
                showFields: true,
                showVariables: true,
                showClasses: true,
                showStructs: true,
                showInterfaces: true,
                showModules: true,
                showProperties: true,
                showEvents: true,
                showOperators: true,
                showUnits: true,
                showValues: true,
                showConstants: true,
                showEnums: true,
                showEnumMembers: true,
                showKeywords: true,
                showWords: true,
                showColors: true,
                showFiles: true,
                showReferences: true,
                showFolders: true,
                showTypeParameters: true,
                showSnippets: true,
                showUsers: true,
                showIssues: true,
            };
            super(119 /* EditorOption.suggest */, 'suggest', defaults, {
                'editor.suggest.insertMode': {
                    type: 'string',
                    enum: ['insert', 'replace'],
                    enumDescriptions: [
                        nls.localize(332, "Insert suggestion without overwriting text right of the cursor."),
                        nls.localize(333, "Insert suggestion and overwrite text right of the cursor."),
                    ],
                    default: defaults.insertMode,
                    description: nls.localize(334, "Controls whether words are overwritten when accepting completions. Note that this depends on extensions opting into this feature.")
                },
                'editor.suggest.filterGraceful': {
                    type: 'boolean',
                    default: defaults.filterGraceful,
                    description: nls.localize(335, "Controls whether filtering and sorting suggestions accounts for small typos.")
                },
                'editor.suggest.localityBonus': {
                    type: 'boolean',
                    default: defaults.localityBonus,
                    description: nls.localize(336, "Controls whether sorting favors words that appear close to the cursor.")
                },
                'editor.suggest.shareSuggestSelections': {
                    type: 'boolean',
                    default: defaults.shareSuggestSelections,
                    markdownDescription: nls.localize(337, "Controls whether remembered suggestion selections are shared between multiple workspaces and windows (needs `#editor.suggestSelection#`).")
                },
                'editor.suggest.selectionMode': {
                    type: 'string',
                    enum: ['always', 'never', 'whenTriggerCharacter', 'whenQuickSuggestion'],
                    enumDescriptions: [
                        nls.localize(338, "Always select a suggestion when automatically triggering IntelliSense."),
                        nls.localize(339, "Never select a suggestion when automatically triggering IntelliSense."),
                        nls.localize(340, "Select a suggestion only when triggering IntelliSense from a trigger character."),
                        nls.localize(341, "Select a suggestion only when triggering IntelliSense as you type."),
                    ],
                    default: defaults.selectionMode,
                    markdownDescription: nls.localize(342, "Controls whether a suggestion is selected when the widget shows. Note that this only applies to automatically triggered suggestions ({0} and {1}) and that a suggestion is always selected when explicitly invoked, e.g via `Ctrl+Space`.", '`#editor.quickSuggestions#`', '`#editor.suggestOnTriggerCharacters#`')
                },
                'editor.suggest.snippetsPreventQuickSuggestions': {
                    type: 'boolean',
                    default: defaults.snippetsPreventQuickSuggestions,
                    description: nls.localize(343, "Controls whether an active snippet prevents quick suggestions.")
                },
                'editor.suggest.showIcons': {
                    type: 'boolean',
                    default: defaults.showIcons,
                    description: nls.localize(344, "Controls whether to show or hide icons in suggestions.")
                },
                'editor.suggest.showStatusBar': {
                    type: 'boolean',
                    default: defaults.showStatusBar,
                    description: nls.localize(345, "Controls the visibility of the status bar at the bottom of the suggest widget.")
                },
                'editor.suggest.preview': {
                    type: 'boolean',
                    default: defaults.preview,
                    description: nls.localize(346, "Controls whether to preview the suggestion outcome in the editor.")
                },
                'editor.suggest.showInlineDetails': {
                    type: 'boolean',
                    default: defaults.showInlineDetails,
                    description: nls.localize(347, "Controls whether suggest details show inline with the label or only in the details widget.")
                },
                'editor.suggest.maxVisibleSuggestions': {
                    type: 'number',
                    deprecationMessage: nls.localize(348, "This setting is deprecated. The suggest widget can now be resized."),
                },
                'editor.suggest.filteredTypes': {
                    type: 'object',
                    deprecationMessage: nls.localize(349, "This setting is deprecated, please use separate settings like 'editor.suggest.showKeywords' or 'editor.suggest.showSnippets' instead.")
                },
                'editor.suggest.showMethods': {
                    type: 'boolean',
                    default: true,
                    markdownDescription: nls.localize(350, "When enabled IntelliSense shows `method`-suggestions.")
                },
                'editor.suggest.showFunctions': {
                    type: 'boolean',
                    default: true,
                    markdownDescription: nls.localize(351, "When enabled IntelliSense shows `function`-suggestions.")
                },
                'editor.suggest.showConstructors': {
                    type: 'boolean',
                    default: true,
                    markdownDescription: nls.localize(352, "When enabled IntelliSense shows `constructor`-suggestions.")
                },
                'editor.suggest.showDeprecated': {
                    type: 'boolean',
                    default: true,
                    markdownDescription: nls.localize(353, "When enabled IntelliSense shows `deprecated`-suggestions.")
                },
                'editor.suggest.matchOnWordStartOnly': {
                    type: 'boolean',
                    default: true,
                    markdownDescription: nls.localize(354, "When enabled IntelliSense filtering requires that the first character matches on a word start. For example, `c` on `Console` or `WebContext` but _not_ on `description`. When disabled IntelliSense will show more results but still sorts them by match quality.")
                },
                'editor.suggest.showFields': {
                    type: 'boolean',
                    default: true,
                    markdownDescription: nls.localize(355, "When enabled IntelliSense shows `field`-suggestions.")
                },
                'editor.suggest.showVariables': {
                    type: 'boolean',
                    default: true,
                    markdownDescription: nls.localize(356, "When enabled IntelliSense shows `variable`-suggestions.")
                },
                'editor.suggest.showClasses': {
                    type: 'boolean',
                    default: true,
                    markdownDescription: nls.localize(357, "When enabled IntelliSense shows `class`-suggestions.")
                },
                'editor.suggest.showStructs': {
                    type: 'boolean',
                    default: true,
                    markdownDescription: nls.localize(358, "When enabled IntelliSense shows `struct`-suggestions.")
                },
                'editor.suggest.showInterfaces': {
                    type: 'boolean',
                    default: true,
                    markdownDescription: nls.localize(359, "When enabled IntelliSense shows `interface`-suggestions.")
                },
                'editor.suggest.showModules': {
                    type: 'boolean',
                    default: true,
                    markdownDescription: nls.localize(360, "When enabled IntelliSense shows `module`-suggestions.")
                },
                'editor.suggest.showProperties': {
                    type: 'boolean',
                    default: true,
                    markdownDescription: nls.localize(361, "When enabled IntelliSense shows `property`-suggestions.")
                },
                'editor.suggest.showEvents': {
                    type: 'boolean',
                    default: true,
                    markdownDescription: nls.localize(362, "When enabled IntelliSense shows `event`-suggestions.")
                },
                'editor.suggest.showOperators': {
                    type: 'boolean',
                    default: true,
                    markdownDescription: nls.localize(363, "When enabled IntelliSense shows `operator`-suggestions.")
                },
                'editor.suggest.showUnits': {
                    type: 'boolean',
                    default: true,
                    markdownDescription: nls.localize(364, "When enabled IntelliSense shows `unit`-suggestions.")
                },
                'editor.suggest.showValues': {
                    type: 'boolean',
                    default: true,
                    markdownDescription: nls.localize(365, "When enabled IntelliSense shows `value`-suggestions.")
                },
                'editor.suggest.showConstants': {
                    type: 'boolean',
                    default: true,
                    markdownDescription: nls.localize(366, "When enabled IntelliSense shows `constant`-suggestions.")
                },
                'editor.suggest.showEnums': {
                    type: 'boolean',
                    default: true,
                    markdownDescription: nls.localize(367, "When enabled IntelliSense shows `enum`-suggestions.")
                },
                'editor.suggest.showEnumMembers': {
                    type: 'boolean',
                    default: true,
                    markdownDescription: nls.localize(368, "When enabled IntelliSense shows `enumMember`-suggestions.")
                },
                'editor.suggest.showKeywords': {
                    type: 'boolean',
                    default: true,
                    markdownDescription: nls.localize(369, "When enabled IntelliSense shows `keyword`-suggestions.")
                },
                'editor.suggest.showWords': {
                    type: 'boolean',
                    default: true,
                    markdownDescription: nls.localize(370, "When enabled IntelliSense shows `text`-suggestions.")
                },
                'editor.suggest.showColors': {
                    type: 'boolean',
                    default: true,
                    markdownDescription: nls.localize(371, "When enabled IntelliSense shows `color`-suggestions.")
                },
                'editor.suggest.showFiles': {
                    type: 'boolean',
                    default: true,
                    markdownDescription: nls.localize(372, "When enabled IntelliSense shows `file`-suggestions.")
                },
                'editor.suggest.showReferences': {
                    type: 'boolean',
                    default: true,
                    markdownDescription: nls.localize(373, "When enabled IntelliSense shows `reference`-suggestions.")
                },
                'editor.suggest.showCustomcolors': {
                    type: 'boolean',
                    default: true,
                    markdownDescription: nls.localize(374, "When enabled IntelliSense shows `customcolor`-suggestions.")
                },
                'editor.suggest.showFolders': {
                    type: 'boolean',
                    default: true,
                    markdownDescription: nls.localize(375, "When enabled IntelliSense shows `folder`-suggestions.")
                },
                'editor.suggest.showTypeParameters': {
                    type: 'boolean',
                    default: true,
                    markdownDescription: nls.localize(376, "When enabled IntelliSense shows `typeParameter`-suggestions.")
                },
                'editor.suggest.showSnippets': {
                    type: 'boolean',
                    default: true,
                    markdownDescription: nls.localize(377, "When enabled IntelliSense shows `snippet`-suggestions.")
                },
                'editor.suggest.showUsers': {
                    type: 'boolean',
                    default: true,
                    markdownDescription: nls.localize(378, "When enabled IntelliSense shows `user`-suggestions.")
                },
                'editor.suggest.showIssues': {
                    type: 'boolean',
                    default: true,
                    markdownDescription: nls.localize(379, "When enabled IntelliSense shows `issues`-suggestions.")
                }
            });
        }
        validate(_input) {
            if (!_input || typeof _input !== 'object') {
                return this.defaultValue;
            }
            const input = _input;
            return {
                insertMode: stringSet(input.insertMode, this.defaultValue.insertMode, ['insert', 'replace']),
                filterGraceful: boolean(input.filterGraceful, this.defaultValue.filterGraceful),
                snippetsPreventQuickSuggestions: boolean(input.snippetsPreventQuickSuggestions, this.defaultValue.filterGraceful),
                localityBonus: boolean(input.localityBonus, this.defaultValue.localityBonus),
                shareSuggestSelections: boolean(input.shareSuggestSelections, this.defaultValue.shareSuggestSelections),
                selectionMode: stringSet(input.selectionMode, this.defaultValue.selectionMode, ['always', 'never', 'whenQuickSuggestion', 'whenTriggerCharacter']),
                showIcons: boolean(input.showIcons, this.defaultValue.showIcons),
                showStatusBar: boolean(input.showStatusBar, this.defaultValue.showStatusBar),
                preview: boolean(input.preview, this.defaultValue.preview),
                previewMode: stringSet(input.previewMode, this.defaultValue.previewMode, ['prefix', 'subword', 'subwordSmart']),
                showInlineDetails: boolean(input.showInlineDetails, this.defaultValue.showInlineDetails),
                showMethods: boolean(input.showMethods, this.defaultValue.showMethods),
                showFunctions: boolean(input.showFunctions, this.defaultValue.showFunctions),
                showConstructors: boolean(input.showConstructors, this.defaultValue.showConstructors),
                showDeprecated: boolean(input.showDeprecated, this.defaultValue.showDeprecated),
                matchOnWordStartOnly: boolean(input.matchOnWordStartOnly, this.defaultValue.matchOnWordStartOnly),
                showFields: boolean(input.showFields, this.defaultValue.showFields),
                showVariables: boolean(input.showVariables, this.defaultValue.showVariables),
                showClasses: boolean(input.showClasses, this.defaultValue.showClasses),
                showStructs: boolean(input.showStructs, this.defaultValue.showStructs),
                showInterfaces: boolean(input.showInterfaces, this.defaultValue.showInterfaces),
                showModules: boolean(input.showModules, this.defaultValue.showModules),
                showProperties: boolean(input.showProperties, this.defaultValue.showProperties),
                showEvents: boolean(input.showEvents, this.defaultValue.showEvents),
                showOperators: boolean(input.showOperators, this.defaultValue.showOperators),
                showUnits: boolean(input.showUnits, this.defaultValue.showUnits),
                showValues: boolean(input.showValues, this.defaultValue.showValues),
                showConstants: boolean(input.showConstants, this.defaultValue.showConstants),
                showEnums: boolean(input.showEnums, this.defaultValue.showEnums),
                showEnumMembers: boolean(input.showEnumMembers, this.defaultValue.showEnumMembers),
                showKeywords: boolean(input.showKeywords, this.defaultValue.showKeywords),
                showWords: boolean(input.showWords, this.defaultValue.showWords),
                showColors: boolean(input.showColors, this.defaultValue.showColors),
                showFiles: boolean(input.showFiles, this.defaultValue.showFiles),
                showReferences: boolean(input.showReferences, this.defaultValue.showReferences),
                showFolders: boolean(input.showFolders, this.defaultValue.showFolders),
                showTypeParameters: boolean(input.showTypeParameters, this.defaultValue.showTypeParameters),
                showSnippets: boolean(input.showSnippets, this.defaultValue.showSnippets),
                showUsers: boolean(input.showUsers, this.defaultValue.showUsers),
                showIssues: boolean(input.showIssues, this.defaultValue.showIssues),
            };
        }
    }
    class SmartSelect extends BaseEditorOption {
        constructor() {
            super(114 /* EditorOption.smartSelect */, 'smartSelect', {
                selectLeadingAndTrailingWhitespace: true,
                selectSubwords: true,
            }, {
                'editor.smartSelect.selectLeadingAndTrailingWhitespace': {
                    description: nls.localize(380, "Whether leading and trailing whitespace should always be selected."),
                    default: true,
                    type: 'boolean'
                },
                'editor.smartSelect.selectSubwords': {
                    description: nls.localize(381, "Whether subwords (like 'foo' in 'fooBar' or 'foo_bar') should be selected."),
                    default: true,
                    type: 'boolean'
                }
            });
        }
        validate(input) {
            if (!input || typeof input !== 'object') {
                return this.defaultValue;
            }
            return {
                selectLeadingAndTrailingWhitespace: boolean(input.selectLeadingAndTrailingWhitespace, this.defaultValue.selectLeadingAndTrailingWhitespace),
                selectSubwords: boolean(input.selectSubwords, this.defaultValue.selectSubwords),
            };
        }
    }
    //#endregion
    //#region wordSegmenterLocales
    /**
     * Locales used for segmenting lines into words when doing word related navigations or operations.
     *
     * Specify the BCP 47 language tag of the word you wish to recognize (e.g., ja, zh-CN, zh-Hant-TW, etc.).
     */
    class WordSegmenterLocales extends BaseEditorOption {
        constructor() {
            const defaults = [];
            super(131 /* EditorOption.wordSegmenterLocales */, 'wordSegmenterLocales', defaults, {
                anyOf: [
                    {
                        description: nls.localize(382, "Locales to be used for word segmentation when doing word related navigations or operations. Specify the BCP 47 language tag of the word you wish to recognize (e.g., ja, zh-CN, zh-Hant-TW, etc.)."),
                        type: 'string',
                    }, {
                        description: nls.localize(383, "Locales to be used for word segmentation when doing word related navigations or operations. Specify the BCP 47 language tag of the word you wish to recognize (e.g., ja, zh-CN, zh-Hant-TW, etc.)."),
                        type: 'array',
                        items: {
                            type: 'string'
                        }
                    }
                ]
            });
        }
        validate(input) {
            if (typeof input === 'string') {
                input = [input];
            }
            if (Array.isArray(input)) {
                const validLocales = [];
                for (const locale of input) {
                    if (typeof locale === 'string') {
                        try {
                            if (Intl.Segmenter.supportedLocalesOf(locale).length > 0) {
                                validLocales.push(locale);
                            }
                        }
                        catch {
                            // ignore invalid locales
                        }
                    }
                }
                return validLocales;
            }
            return this.defaultValue;
        }
    }
    class WrappingIndentOption extends BaseEditorOption {
        constructor() {
            super(139 /* EditorOption.wrappingIndent */, 'wrappingIndent', 1 /* WrappingIndent.Same */, {
                'editor.wrappingIndent': {
                    type: 'string',
                    enum: ['none', 'same', 'indent', 'deepIndent'],
                    enumDescriptions: [
                        nls.localize(384, "No indentation. Wrapped lines begin at column 1."),
                        nls.localize(385, "Wrapped lines get the same indentation as the parent."),
                        nls.localize(386, "Wrapped lines get +1 indentation toward the parent."),
                        nls.localize(387, "Wrapped lines get +2 indentation toward the parent."),
                    ],
                    description: nls.localize(388, "Controls the indentation of wrapped lines."),
                    default: 'same'
                }
            });
        }
        validate(input) {
            switch (input) {
                case 'none': return 0 /* WrappingIndent.None */;
                case 'same': return 1 /* WrappingIndent.Same */;
                case 'indent': return 2 /* WrappingIndent.Indent */;
                case 'deepIndent': return 3 /* WrappingIndent.DeepIndent */;
            }
            return 1 /* WrappingIndent.Same */;
        }
        compute(env, options, value) {
            const accessibilitySupport = options.get(2 /* EditorOption.accessibilitySupport */);
            if (accessibilitySupport === 2 /* AccessibilitySupport.Enabled */) {
                // if we know for a fact that a screen reader is attached, we use no indent wrapping to
                // help that the editor's wrapping points match the textarea's wrapping points
                return 0 /* WrappingIndent.None */;
            }
            return value;
        }
    }
    class EditorWrappingInfoComputer extends ComputedEditorOption {
        constructor() {
            super(147 /* EditorOption.wrappingInfo */);
        }
        compute(env, options, _) {
            const layoutInfo = options.get(146 /* EditorOption.layoutInfo */);
            return {
                isDominatedByLongLines: env.isDominatedByLongLines,
                isWordWrapMinified: layoutInfo.isWordWrapMinified,
                isViewportWrapping: layoutInfo.isViewportWrapping,
                wrappingColumn: layoutInfo.wrappingColumn,
            };
        }
    }
    class EditorDropIntoEditor extends BaseEditorOption {
        constructor() {
            const defaults = { enabled: true, showDropSelector: 'afterDrop' };
            super(36 /* EditorOption.dropIntoEditor */, 'dropIntoEditor', defaults, {
                'editor.dropIntoEditor.enabled': {
                    type: 'boolean',
                    default: defaults.enabled,
                    markdownDescription: nls.localize(389, "Controls whether you can drag and drop a file into a text editor by holding down the `Shift` key (instead of opening the file in an editor)."),
                },
                'editor.dropIntoEditor.showDropSelector': {
                    type: 'string',
                    markdownDescription: nls.localize(390, "Controls if a widget is shown when dropping files into the editor. This widget lets you control how the file is dropped."),
                    enum: [
                        'afterDrop',
                        'never'
                    ],
                    enumDescriptions: [
                        nls.localize(391, "Show the drop selector widget after a file is dropped into the editor."),
                        nls.localize(392, "Never show the drop selector widget. Instead the default drop provider is always used."),
                    ],
                    default: 'afterDrop',
                },
            });
        }
        validate(_input) {
            if (!_input || typeof _input !== 'object') {
                return this.defaultValue;
            }
            const input = _input;
            return {
                enabled: boolean(input.enabled, this.defaultValue.enabled),
                showDropSelector: stringSet(input.showDropSelector, this.defaultValue.showDropSelector, ['afterDrop', 'never']),
            };
        }
    }
    class EditorPasteAs extends BaseEditorOption {
        constructor() {
            const defaults = { enabled: true, showPasteSelector: 'afterPaste' };
            super(85 /* EditorOption.pasteAs */, 'pasteAs', defaults, {
                'editor.pasteAs.enabled': {
                    type: 'boolean',
                    default: defaults.enabled,
                    markdownDescription: nls.localize(393, "Controls whether you can paste content in different ways."),
                },
                'editor.pasteAs.showPasteSelector': {
                    type: 'string',
                    markdownDescription: nls.localize(394, "Controls if a widget is shown when pasting content in to the editor. This widget lets you control how the file is pasted."),
                    enum: [
                        'afterPaste',
                        'never'
                    ],
                    enumDescriptions: [
                        nls.localize(395, "Show the paste selector widget after content is pasted into the editor."),
                        nls.localize(396, "Never show the paste selector widget. Instead the default pasting behavior is always used."),
                    ],
                    default: 'afterPaste',
                },
            });
        }
        validate(_input) {
            if (!_input || typeof _input !== 'object') {
                return this.defaultValue;
            }
            const input = _input;
            return {
                enabled: boolean(input.enabled, this.defaultValue.enabled),
                showPasteSelector: stringSet(input.showPasteSelector, this.defaultValue.showPasteSelector, ['afterPaste', 'never']),
            };
        }
    }
    //#endregion
    const DEFAULT_WINDOWS_FONT_FAMILY = 'Consolas, \'Courier New\', monospace';
    const DEFAULT_MAC_FONT_FAMILY = 'Menlo, Monaco, \'Courier New\', monospace';
    const DEFAULT_LINUX_FONT_FAMILY = '\'Droid Sans Mono\', \'monospace\', monospace';
    /**
     * @internal
     */
    exports.EDITOR_FONT_DEFAULTS = {
        fontFamily: (platform.isMacintosh ? DEFAULT_MAC_FONT_FAMILY : (platform.isLinux ? DEFAULT_LINUX_FONT_FAMILY : DEFAULT_WINDOWS_FONT_FAMILY)),
        fontWeight: 'normal',
        fontSize: (platform.isMacintosh ? 12 : 14),
        lineHeight: 0,
        letterSpacing: 0,
    };
    /**
     * @internal
     */
    exports.editorOptionsRegistry = [];
    function register(option) {
        exports.editorOptionsRegistry[option.id] = option;
        return option;
    }
    exports.EditorOptions = {
        acceptSuggestionOnCommitCharacter: register(new EditorBooleanOption(0 /* EditorOption.acceptSuggestionOnCommitCharacter */, 'acceptSuggestionOnCommitCharacter', true, { markdownDescription: nls.localize(397, "Controls whether suggestions should be accepted on commit characters. For example, in JavaScript, the semi-colon (`;`) can be a commit character that accepts a suggestion and types that character.") })),
        acceptSuggestionOnEnter: register(new EditorStringEnumOption(1 /* EditorOption.acceptSuggestionOnEnter */, 'acceptSuggestionOnEnter', 'on', ['on', 'smart', 'off'], {
            markdownEnumDescriptions: [
                '',
                nls.localize(398, "Only accept a suggestion with `Enter` when it makes a textual change."),
                ''
            ],
            markdownDescription: nls.localize(399, "Controls whether suggestions should be accepted on `Enter`, in addition to `Tab`. Helps to avoid ambiguity between inserting new lines or accepting suggestions.")
        })),
        accessibilitySupport: register(new EditorAccessibilitySupport()),
        accessibilityPageSize: register(new EditorIntOption(3 /* EditorOption.accessibilityPageSize */, 'accessibilityPageSize', 10, 1, 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */, {
            description: nls.localize(400, "Controls the number of lines in the editor that can be read out by a screen reader at once. When we detect a screen reader we automatically set the default to be 500. Warning: this has a performance implication for numbers larger than the default."),
            tags: ['accessibility']
        })),
        ariaLabel: register(new EditorStringOption(4 /* EditorOption.ariaLabel */, 'ariaLabel', nls.localize(401, "Editor content"))),
        ariaRequired: register(new EditorBooleanOption(5 /* EditorOption.ariaRequired */, 'ariaRequired', false, undefined)),
        screenReaderAnnounceInlineSuggestion: register(new EditorBooleanOption(8 /* EditorOption.screenReaderAnnounceInlineSuggestion */, 'screenReaderAnnounceInlineSuggestion', true, {
            description: nls.localize(402, "Control whether inline suggestions are announced by a screen reader."),
            tags: ['accessibility']
        })),
        autoClosingBrackets: register(new EditorStringEnumOption(6 /* EditorOption.autoClosingBrackets */, 'autoClosingBrackets', 'languageDefined', ['always', 'languageDefined', 'beforeWhitespace', 'never'], {
            enumDescriptions: [
                '',
                nls.localize(403, "Use language configurations to determine when to autoclose brackets."),
                nls.localize(404, "Autoclose brackets only when the cursor is to the left of whitespace."),
                '',
            ],
            description: nls.localize(405, "Controls whether the editor should automatically close brackets after the user adds an opening bracket.")
        })),
        autoClosingComments: register(new EditorStringEnumOption(7 /* EditorOption.autoClosingComments */, 'autoClosingComments', 'languageDefined', ['always', 'languageDefined', 'beforeWhitespace', 'never'], {
            enumDescriptions: [
                '',
                nls.localize(406, "Use language configurations to determine when to autoclose comments."),
                nls.localize(407, "Autoclose comments only when the cursor is to the left of whitespace."),
                '',
            ],
            description: nls.localize(408, "Controls whether the editor should automatically close comments after the user adds an opening comment.")
        })),
        autoClosingDelete: register(new EditorStringEnumOption(9 /* EditorOption.autoClosingDelete */, 'autoClosingDelete', 'auto', ['always', 'auto', 'never'], {
            enumDescriptions: [
                '',
                nls.localize(409, "Remove adjacent closing quotes or brackets only if they were automatically inserted."),
                '',
            ],
            description: nls.localize(410, "Controls whether the editor should remove adjacent closing quotes or brackets when deleting.")
        })),
        autoClosingOvertype: register(new EditorStringEnumOption(10 /* EditorOption.autoClosingOvertype */, 'autoClosingOvertype', 'auto', ['always', 'auto', 'never'], {
            enumDescriptions: [
                '',
                nls.localize(411, "Type over closing quotes or brackets only if they were automatically inserted."),
                '',
            ],
            description: nls.localize(412, "Controls whether the editor should type over closing quotes or brackets.")
        })),
        autoClosingQuotes: register(new EditorStringEnumOption(11 /* EditorOption.autoClosingQuotes */, 'autoClosingQuotes', 'languageDefined', ['always', 'languageDefined', 'beforeWhitespace', 'never'], {
            enumDescriptions: [
                '',
                nls.localize(413, "Use language configurations to determine when to autoclose quotes."),
                nls.localize(414, "Autoclose quotes only when the cursor is to the left of whitespace."),
                '',
            ],
            description: nls.localize(415, "Controls whether the editor should automatically close quotes after the user adds an opening quote.")
        })),
        autoIndent: register(new EditorEnumOption(12 /* EditorOption.autoIndent */, 'autoIndent', 4 /* EditorAutoIndentStrategy.Full */, 'full', ['none', 'keep', 'brackets', 'advanced', 'full'], _autoIndentFromString, {
            enumDescriptions: [
                nls.localize(416, "The editor will not insert indentation automatically."),
                nls.localize(417, "The editor will keep the current line's indentation."),
                nls.localize(418, "The editor will keep the current line's indentation and honor language defined brackets."),
                nls.localize(419, "The editor will keep the current line's indentation, honor language defined brackets and invoke special onEnterRules defined by languages."),
                nls.localize(420, "The editor will keep the current line's indentation, honor language defined brackets, invoke special onEnterRules defined by languages, and honor indentationRules defined by languages."),
            ],
            description: nls.localize(421, "Controls whether the editor should automatically adjust the indentation when users type, paste, move or indent lines.")
        })),
        automaticLayout: register(new EditorBooleanOption(13 /* EditorOption.automaticLayout */, 'automaticLayout', false)),
        autoSurround: register(new EditorStringEnumOption(14 /* EditorOption.autoSurround */, 'autoSurround', 'languageDefined', ['languageDefined', 'quotes', 'brackets', 'never'], {
            enumDescriptions: [
                nls.localize(422, "Use language configurations to determine when to automatically surround selections."),
                nls.localize(423, "Surround with quotes but not brackets."),
                nls.localize(424, "Surround with brackets but not quotes."),
                ''
            ],
            description: nls.localize(425, "Controls whether the editor should automatically surround selections when typing quotes or brackets.")
        })),
        bracketPairColorization: register(new BracketPairColorization()),
        bracketPairGuides: register(new GuideOptions()),
        stickyTabStops: register(new EditorBooleanOption(117 /* EditorOption.stickyTabStops */, 'stickyTabStops', false, { description: nls.localize(426, "Emulate selection behavior of tab characters when using spaces for indentation. Selection will stick to tab stops.") })),
        codeLens: register(new EditorBooleanOption(17 /* EditorOption.codeLens */, 'codeLens', true, { description: nls.localize(427, "Controls whether the editor shows CodeLens.") })),
        codeLensFontFamily: register(new EditorStringOption(18 /* EditorOption.codeLensFontFamily */, 'codeLensFontFamily', '', { description: nls.localize(428, "Controls the font family for CodeLens.") })),
        codeLensFontSize: register(new EditorIntOption(19 /* EditorOption.codeLensFontSize */, 'codeLensFontSize', 0, 0, 100, {
            type: 'number',
            default: 0,
            minimum: 0,
            maximum: 100,
            markdownDescription: nls.localize(429, "Controls the font size in pixels for CodeLens. When set to 0, 90% of `#editor.fontSize#` is used.")
        })),
        colorDecorators: register(new EditorBooleanOption(20 /* EditorOption.colorDecorators */, 'colorDecorators', true, { description: nls.localize(430, "Controls whether the editor should render the inline color decorators and color picker.") })),
        colorDecoratorActivatedOn: register(new EditorStringEnumOption(149 /* EditorOption.colorDecoratorsActivatedOn */, 'colorDecoratorsActivatedOn', 'clickAndHover', ['clickAndHover', 'hover', 'click'], {
            enumDescriptions: [
                nls.localize(431, "Make the color picker appear both on click and hover of the color decorator"),
                nls.localize(432, "Make the color picker appear on hover of the color decorator"),
                nls.localize(433, "Make the color picker appear on click of the color decorator")
            ],
            description: nls.localize(434, "Controls the condition to make a color picker appear from a color decorator")
        })),
        colorDecoratorsLimit: register(new EditorIntOption(21 /* EditorOption.colorDecoratorsLimit */, 'colorDecoratorsLimit', 500, 1, 1000000, {
            markdownDescription: nls.localize(435, "Controls the max number of color decorators that can be rendered in an editor at once.")
        })),
        columnSelection: register(new EditorBooleanOption(22 /* EditorOption.columnSelection */, 'columnSelection', false, { description: nls.localize(436, "Enable that the selection with the mouse and keys is doing column selection.") })),
        comments: register(new EditorComments()),
        contextmenu: register(new EditorBooleanOption(24 /* EditorOption.contextmenu */, 'contextmenu', true)),
        copyWithSyntaxHighlighting: register(new EditorBooleanOption(25 /* EditorOption.copyWithSyntaxHighlighting */, 'copyWithSyntaxHighlighting', true, { description: nls.localize(437, "Controls whether syntax highlighting should be copied into the clipboard.") })),
        cursorBlinking: register(new EditorEnumOption(26 /* EditorOption.cursorBlinking */, 'cursorBlinking', 1 /* TextEditorCursorBlinkingStyle.Blink */, 'blink', ['blink', 'smooth', 'phase', 'expand', 'solid'], _cursorBlinkingStyleFromString, { description: nls.localize(438, "Control the cursor animation style.") })),
        cursorSmoothCaretAnimation: register(new EditorStringEnumOption(27 /* EditorOption.cursorSmoothCaretAnimation */, 'cursorSmoothCaretAnimation', 'off', ['off', 'explicit', 'on'], {
            enumDescriptions: [
                nls.localize(439, "Smooth caret animation is disabled."),
                nls.localize(440, "Smooth caret animation is enabled only when the user moves the cursor with an explicit gesture."),
                nls.localize(441, "Smooth caret animation is always enabled.")
            ],
            description: nls.localize(442, "Controls whether the smooth caret animation should be enabled.")
        })),
        cursorStyle: register(new EditorEnumOption(28 /* EditorOption.cursorStyle */, 'cursorStyle', TextEditorCursorStyle.Line, 'line', ['line', 'block', 'underline', 'line-thin', 'block-outline', 'underline-thin'], _cursorStyleFromString, { description: nls.localize(443, "Controls the cursor style.") })),
        cursorSurroundingLines: register(new EditorIntOption(29 /* EditorOption.cursorSurroundingLines */, 'cursorSurroundingLines', 0, 0, 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */, { description: nls.localize(444, "Controls the minimal number of visible leading lines (minimum 0) and trailing lines (minimum 1) surrounding the cursor. Known as 'scrollOff' or 'scrollOffset' in some other editors.") })),
        cursorSurroundingLinesStyle: register(new EditorStringEnumOption(30 /* EditorOption.cursorSurroundingLinesStyle */, 'cursorSurroundingLinesStyle', 'default', ['default', 'all'], {
            enumDescriptions: [
                nls.localize(445, "`cursorSurroundingLines` is enforced only when triggered via the keyboard or API."),
                nls.localize(446, "`cursorSurroundingLines` is enforced always.")
            ],
            markdownDescription: nls.localize(447, "Controls when `#editor.cursorSurroundingLines#` should be enforced.")
        })),
        cursorWidth: register(new EditorIntOption(31 /* EditorOption.cursorWidth */, 'cursorWidth', 0, 0, 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */, { markdownDescription: nls.localize(448, "Controls the width of the cursor when `#editor.cursorStyle#` is set to `line`.") })),
        disableLayerHinting: register(new EditorBooleanOption(32 /* EditorOption.disableLayerHinting */, 'disableLayerHinting', false)),
        disableMonospaceOptimizations: register(new EditorBooleanOption(33 /* EditorOption.disableMonospaceOptimizations */, 'disableMonospaceOptimizations', false)),
        domReadOnly: register(new EditorBooleanOption(34 /* EditorOption.domReadOnly */, 'domReadOnly', false)),
        dragAndDrop: register(new EditorBooleanOption(35 /* EditorOption.dragAndDrop */, 'dragAndDrop', true, { description: nls.localize(449, "Controls whether the editor should allow moving selections via drag and drop.") })),
        emptySelectionClipboard: register(new EditorEmptySelectionClipboard()),
        dropIntoEditor: register(new EditorDropIntoEditor()),
        stickyScroll: register(new EditorStickyScroll()),
        experimentalWhitespaceRendering: register(new EditorStringEnumOption(38 /* EditorOption.experimentalWhitespaceRendering */, 'experimentalWhitespaceRendering', 'svg', ['svg', 'font', 'off'], {
            enumDescriptions: [
                nls.localize(450, "Use a new rendering method with svgs."),
                nls.localize(451, "Use a new rendering method with font characters."),
                nls.localize(452, "Use the stable rendering method."),
            ],
            description: nls.localize(453, "Controls whether whitespace is rendered with a new, experimental method.")
        })),
        extraEditorClassName: register(new EditorStringOption(39 /* EditorOption.extraEditorClassName */, 'extraEditorClassName', '')),
        fastScrollSensitivity: register(new EditorFloatOption(40 /* EditorOption.fastScrollSensitivity */, 'fastScrollSensitivity', 5, x => (x <= 0 ? 5 : x), { markdownDescription: nls.localize(454, "Scrolling speed multiplier when pressing `Alt`.") })),
        find: register(new EditorFind()),
        fixedOverflowWidgets: register(new EditorBooleanOption(42 /* EditorOption.fixedOverflowWidgets */, 'fixedOverflowWidgets', false)),
        folding: register(new EditorBooleanOption(43 /* EditorOption.folding */, 'folding', true, { description: nls.localize(455, "Controls whether the editor has code folding enabled.") })),
        foldingStrategy: register(new EditorStringEnumOption(44 /* EditorOption.foldingStrategy */, 'foldingStrategy', 'auto', ['auto', 'indentation'], {
            enumDescriptions: [
                nls.localize(456, "Use a language-specific folding strategy if available, else the indentation-based one."),
                nls.localize(457, "Use the indentation-based folding strategy."),
            ],
            description: nls.localize(458, "Controls the strategy for computing folding ranges.")
        })),
        foldingHighlight: register(new EditorBooleanOption(45 /* EditorOption.foldingHighlight */, 'foldingHighlight', true, { description: nls.localize(459, "Controls whether the editor should highlight folded ranges.") })),
        foldingImportsByDefault: register(new EditorBooleanOption(46 /* EditorOption.foldingImportsByDefault */, 'foldingImportsByDefault', false, { description: nls.localize(460, "Controls whether the editor automatically collapses import ranges.") })),
        foldingMaximumRegions: register(new EditorIntOption(47 /* EditorOption.foldingMaximumRegions */, 'foldingMaximumRegions', 5000, 10, 65000, // limit must be less than foldingRanges MAX_FOLDING_REGIONS
        { description: nls.localize(461, "The maximum number of foldable regions. Increasing this value may result in the editor becoming less responsive when the current source has a large number of foldable regions.") })),
        unfoldOnClickAfterEndOfLine: register(new EditorBooleanOption(48 /* EditorOption.unfoldOnClickAfterEndOfLine */, 'unfoldOnClickAfterEndOfLine', false, { description: nls.localize(462, "Controls whether clicking on the empty content after a folded line will unfold the line.") })),
        fontFamily: register(new EditorStringOption(49 /* EditorOption.fontFamily */, 'fontFamily', exports.EDITOR_FONT_DEFAULTS.fontFamily, { description: nls.localize(463, "Controls the font family.") })),
        fontInfo: register(new EditorFontInfo()),
        fontLigatures2: register(new EditorFontLigatures()),
        fontSize: register(new EditorFontSize()),
        fontWeight: register(new EditorFontWeight()),
        fontVariations: register(new EditorFontVariations()),
        formatOnPaste: register(new EditorBooleanOption(55 /* EditorOption.formatOnPaste */, 'formatOnPaste', false, { description: nls.localize(464, "Controls whether the editor should automatically format the pasted content. A formatter must be available and the formatter should be able to format a range in a document.") })),
        formatOnType: register(new EditorBooleanOption(56 /* EditorOption.formatOnType */, 'formatOnType', false, { description: nls.localize(465, "Controls whether the editor should automatically format the line after typing.") })),
        glyphMargin: register(new EditorBooleanOption(57 /* EditorOption.glyphMargin */, 'glyphMargin', true, { description: nls.localize(466, "Controls whether the editor should render the vertical glyph margin. Glyph margin is mostly used for debugging.") })),
        gotoLocation: register(new EditorGoToLocation()),
        hideCursorInOverviewRuler: register(new EditorBooleanOption(59 /* EditorOption.hideCursorInOverviewRuler */, 'hideCursorInOverviewRuler', false, { description: nls.localize(467, "Controls whether the cursor should be hidden in the overview ruler.") })),
        hover: register(new EditorHover()),
        inDiffEditor: register(new EditorBooleanOption(61 /* EditorOption.inDiffEditor */, 'inDiffEditor', false)),
        letterSpacing: register(new EditorFloatOption(64 /* EditorOption.letterSpacing */, 'letterSpacing', exports.EDITOR_FONT_DEFAULTS.letterSpacing, x => EditorFloatOption.clamp(x, -5, 20), { description: nls.localize(468, "Controls the letter spacing in pixels.") })),
        lightbulb: register(new EditorLightbulb()),
        lineDecorationsWidth: register(new EditorLineDecorationsWidth()),
        lineHeight: register(new EditorLineHeight()),
        lineNumbers: register(new EditorRenderLineNumbersOption()),
        lineNumbersMinChars: register(new EditorIntOption(69 /* EditorOption.lineNumbersMinChars */, 'lineNumbersMinChars', 5, 1, 300)),
        linkedEditing: register(new EditorBooleanOption(70 /* EditorOption.linkedEditing */, 'linkedEditing', false, { description: nls.localize(469, "Controls whether the editor has linked editing enabled. Depending on the language, related symbols such as HTML tags, are updated while editing.") })),
        links: register(new EditorBooleanOption(71 /* EditorOption.links */, 'links', true, { description: nls.localize(470, "Controls whether the editor should detect links and make them clickable.") })),
        matchBrackets: register(new EditorStringEnumOption(72 /* EditorOption.matchBrackets */, 'matchBrackets', 'always', ['always', 'near', 'never'], { description: nls.localize(471, "Highlight matching brackets.") })),
        minimap: register(new EditorMinimap()),
        mouseStyle: register(new EditorStringEnumOption(74 /* EditorOption.mouseStyle */, 'mouseStyle', 'text', ['text', 'default', 'copy'])),
        mouseWheelScrollSensitivity: register(new EditorFloatOption(75 /* EditorOption.mouseWheelScrollSensitivity */, 'mouseWheelScrollSensitivity', 1, x => (x === 0 ? 1 : x), { markdownDescription: nls.localize(472, "A multiplier to be used on the `deltaX` and `deltaY` of mouse wheel scroll events.") })),
        mouseWheelZoom: register(new EditorBooleanOption(76 /* EditorOption.mouseWheelZoom */, 'mouseWheelZoom', false, {
            markdownDescription: platform.isMacintosh
                ? nls.localize(473, "Zoom the font of the editor when using mouse wheel and holding `Cmd`.")
                : nls.localize(474, "Zoom the font of the editor when using mouse wheel and holding `Ctrl`.")
        })),
        multiCursorMergeOverlapping: register(new EditorBooleanOption(77 /* EditorOption.multiCursorMergeOverlapping */, 'multiCursorMergeOverlapping', true, { description: nls.localize(475, "Merge multiple cursors when they are overlapping.") })),
        multiCursorModifier: register(new EditorEnumOption(78 /* EditorOption.multiCursorModifier */, 'multiCursorModifier', 'altKey', 'alt', ['ctrlCmd', 'alt'], _multiCursorModifierFromString, {
            markdownEnumDescriptions: [
                nls.localize(476, "Maps to `Control` on Windows and Linux and to `Command` on macOS."),
                nls.localize(477, "Maps to `Alt` on Windows and Linux and to `Option` on macOS.")
            ],
            markdownDescription: nls.localize(478, "The modifier to be used to add multiple cursors with the mouse. The Go to Definition and Open Link mouse gestures will adapt such that they do not conflict with the [multicursor modifier](https://code.visualstudio.com/docs/editor/codebasics#_multicursor-modifier).")






        })),
        multiCursorPaste: register(new EditorStringEnumOption(79 /* EditorOption.multiCursorPaste */, 'multiCursorPaste', 'spread', ['spread', 'full'], {
            markdownEnumDescriptions: [
                nls.localize(479, "Each cursor pastes a single line of the text."),
                nls.localize(480, "Each cursor pastes the full text.")
            ],
            markdownDescription: nls.localize(481, "Controls pasting when the line count of the pasted text matches the cursor count.")
        })),
        multiCursorLimit: register(new EditorIntOption(80 /* EditorOption.multiCursorLimit */, 'multiCursorLimit', 10000, 1, 100000, {
            markdownDescription: nls.localize(482, "Controls the max number of cursors that can be in an active editor at once.")
        })),
        occurrencesHighlight: register(new EditorStringEnumOption(81 /* EditorOption.occurrencesHighlight */, 'occurrencesHighlight', 'singleFile', ['off', 'singleFile', 'multiFile'], {
            markdownEnumDescriptions: [
                nls.localize(483, "Does not highlight occurrences."),
                nls.localize(484, "Highlights occurrences only in the current file."),
                nls.localize(485, "Experimental: Highlights occurrences across all valid open files.")
            ],
            markdownDescription: nls.localize(486, "Controls whether occurrences should be highlighted across open files.")
        })),
        overviewRulerBorder: register(new EditorBooleanOption(82 /* EditorOption.overviewRulerBorder */, 'overviewRulerBorder', true, { description: nls.localize(487, "Controls whether a border should be drawn around the overview ruler.") })),
        overviewRulerLanes: register(new EditorIntOption(83 /* EditorOption.overviewRulerLanes */, 'overviewRulerLanes', 3, 0, 3)),
        padding: register(new EditorPadding()),
        pasteAs: register(new EditorPasteAs()),
        parameterHints: register(new EditorParameterHints()),
        peekWidgetDefaultFocus: register(new EditorStringEnumOption(87 /* EditorOption.peekWidgetDefaultFocus */, 'peekWidgetDefaultFocus', 'tree', ['tree', 'editor'], {
            enumDescriptions: [
                nls.localize(488, "Focus the tree when opening peek"),
                nls.localize(489, "Focus the editor when opening peek")
            ],
            description: nls.localize(490, "Controls whether to focus the inline editor or the tree in the peek widget.")
        })),
        placeholder: register(new PlaceholderOption()),
        definitionLinkOpensInPeek: register(new EditorBooleanOption(89 /* EditorOption.definitionLinkOpensInPeek */, 'definitionLinkOpensInPeek', false, { description: nls.localize(491, "Controls whether the Go to Definition mouse gesture always opens the peek widget.") })),
        quickSuggestions: register(new EditorQuickSuggestions()),
        quickSuggestionsDelay: register(new EditorIntOption(91 /* EditorOption.quickSuggestionsDelay */, 'quickSuggestionsDelay', 10, 0, 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */, { description: nls.localize(492, "Controls the delay in milliseconds after which quick suggestions will show up.") })),
        readOnly: register(new EditorBooleanOption(92 /* EditorOption.readOnly */, 'readOnly', false)),
        readOnlyMessage: register(new ReadonlyMessage()),
        renameOnType: register(new EditorBooleanOption(94 /* EditorOption.renameOnType */, 'renameOnType', false, { description: nls.localize(493, "Controls whether the editor auto renames on type."), markdownDeprecationMessage: nls.localize(494, "Deprecated, use `editor.linkedEditing` instead.") })),
        renderControlCharacters: register(new EditorBooleanOption(95 /* EditorOption.renderControlCharacters */, 'renderControlCharacters', true, { description: nls.localize(495, "Controls whether the editor should render control characters."), restricted: true })),
        renderFinalNewline: register(new EditorStringEnumOption(96 /* EditorOption.renderFinalNewline */, 'renderFinalNewline', (platform.isLinux ? 'dimmed' : 'on'), ['off', 'on', 'dimmed'], { description: nls.localize(496, "Render last line number when the file ends with a newline.") })),
        renderLineHighlight: register(new EditorStringEnumOption(97 /* EditorOption.renderLineHighlight */, 'renderLineHighlight', 'line', ['none', 'gutter', 'line', 'all'], {
            enumDescriptions: [
                '',
                '',
                '',
                nls.localize(497, "Highlights both the gutter and the current line."),
            ],
            description: nls.localize(498, "Controls how the editor should render the current line highlight.")
        })),
        renderLineHighlightOnlyWhenFocus: register(new EditorBooleanOption(98 /* EditorOption.renderLineHighlightOnlyWhenFocus */, 'renderLineHighlightOnlyWhenFocus', false, { description: nls.localize(499, "Controls if the editor should render the current line highlight only when the editor is focused.") })),
        renderValidationDecorations: register(new EditorStringEnumOption(99 /* EditorOption.renderValidationDecorations */, 'renderValidationDecorations', 'editable', ['editable', 'on', 'off'])),
        renderWhitespace: register(new EditorStringEnumOption(100 /* EditorOption.renderWhitespace */, 'renderWhitespace', 'selection', ['none', 'boundary', 'selection', 'trailing', 'all'], {
            enumDescriptions: [
                '',
                nls.localize(500, "Render whitespace characters except for single spaces between words."),
                nls.localize(501, "Render whitespace characters only on selected text."),
                nls.localize(502, "Render only trailing whitespace characters."),
                ''
            ],
            description: nls.localize(503, "Controls how the editor should render whitespace characters.")
        })),
        revealHorizontalRightPadding: register(new EditorIntOption(101 /* EditorOption.revealHorizontalRightPadding */, 'revealHorizontalRightPadding', 15, 0, 1000)),
        roundedSelection: register(new EditorBooleanOption(102 /* EditorOption.roundedSelection */, 'roundedSelection', true, { description: nls.localize(504, "Controls whether selections should have rounded corners.") })),
        rulers: register(new EditorRulers()),
        scrollbar: register(new EditorScrollbar()),
        scrollBeyondLastColumn: register(new EditorIntOption(105 /* EditorOption.scrollBeyondLastColumn */, 'scrollBeyondLastColumn', 4, 0, 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */, { description: nls.localize(505, "Controls the number of extra characters beyond which the editor will scroll horizontally.") })),
        scrollBeyondLastLine: register(new EditorBooleanOption(106 /* EditorOption.scrollBeyondLastLine */, 'scrollBeyondLastLine', true, { description: nls.localize(506, "Controls whether the editor will scroll beyond the last line.") })),
        scrollPredominantAxis: register(new EditorBooleanOption(107 /* EditorOption.scrollPredominantAxis */, 'scrollPredominantAxis', true, { description: nls.localize(507, "Scroll only along the predominant axis when scrolling both vertically and horizontally at the same time. Prevents horizontal drift when scrolling vertically on a trackpad.") })),
        selectionClipboard: register(new EditorBooleanOption(108 /* EditorOption.selectionClipboard */, 'selectionClipboard', true, {
            description: nls.localize(508, "Controls whether the Linux primary clipboard should be supported."),
            included: platform.isLinux
        })),
        selectionHighlight: register(new EditorBooleanOption(109 /* EditorOption.selectionHighlight */, 'selectionHighlight', true, { description: nls.localize(509, "Controls whether the editor should highlight matches similar to the selection.") })),
        selectOnLineNumbers: register(new EditorBooleanOption(110 /* EditorOption.selectOnLineNumbers */, 'selectOnLineNumbers', true)),
        showFoldingControls: register(new EditorStringEnumOption(111 /* EditorOption.showFoldingControls */, 'showFoldingControls', 'mouseover', ['always', 'never', 'mouseover'], {
            enumDescriptions: [
                nls.localize(510, "Always show the folding controls."),
                nls.localize(511, "Never show the folding controls and reduce the gutter size."),
                nls.localize(512, "Only show the folding controls when the mouse is over the gutter."),
            ],
            description: nls.localize(513, "Controls when the folding controls on the gutter are shown.")
        })),
        showUnused: register(new EditorBooleanOption(112 /* EditorOption.showUnused */, 'showUnused', true, { description: nls.localize(514, "Controls fading out of unused code.") })),
        showDeprecated: register(new EditorBooleanOption(141 /* EditorOption.showDeprecated */, 'showDeprecated', true, { description: nls.localize(515, "Controls strikethrough deprecated variables.") })),
        inlayHints: register(new EditorInlayHints()),
        snippetSuggestions: register(new EditorStringEnumOption(113 /* EditorOption.snippetSuggestions */, 'snippetSuggestions', 'inline', ['top', 'bottom', 'inline', 'none'], {
            enumDescriptions: [
                nls.localize(516, "Show snippet suggestions on top of other suggestions."),
                nls.localize(517, "Show snippet suggestions below other suggestions."),
                nls.localize(518, "Show snippets suggestions with other suggestions."),
                nls.localize(519, "Do not show snippet suggestions."),
            ],
            description: nls.localize(520, "Controls whether snippets are shown with other suggestions and how they are sorted.")
        })),
        smartSelect: register(new SmartSelect()),
        smoothScrolling: register(new EditorBooleanOption(115 /* EditorOption.smoothScrolling */, 'smoothScrolling', false, { description: nls.localize(521, "Controls whether the editor will scroll using an animation.") })),
        stopRenderingLineAfter: register(new EditorIntOption(118 /* EditorOption.stopRenderingLineAfter */, 'stopRenderingLineAfter', 10000, -1, 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */)),
        suggest: register(new EditorSuggest()),
        inlineSuggest: register(new InlineEditorSuggest()),
        inlineEdit: register(new InlineEditorEdit()),
        inlineCompletionsAccessibilityVerbose: register(new EditorBooleanOption(150 /* EditorOption.inlineCompletionsAccessibilityVerbose */, 'inlineCompletionsAccessibilityVerbose', false, { description: nls.localize(522, "Controls whether the accessibility hint should be provided to screen reader users when an inline completion is shown.") })),
        suggestFontSize: register(new EditorIntOption(120 /* EditorOption.suggestFontSize */, 'suggestFontSize', 0, 0, 1000, { markdownDescription: nls.localize(523, "Font size for the suggest widget. When set to {0}, the value of {1} is used.", '`0`', '`#editor.fontSize#`') })),
        suggestLineHeight: register(new EditorIntOption(121 /* EditorOption.suggestLineHeight */, 'suggestLineHeight', 0, 0, 1000, { markdownDescription: nls.localize(524, "Line height for the suggest widget. When set to {0}, the value of {1} is used. The minimum value is 8.", '`0`', '`#editor.lineHeight#`') })),
        suggestOnTriggerCharacters: register(new EditorBooleanOption(122 /* EditorOption.suggestOnTriggerCharacters */, 'suggestOnTriggerCharacters', true, { description: nls.localize(525, "Controls whether suggestions should automatically show up when typing trigger characters.") })),
        suggestSelection: register(new EditorStringEnumOption(123 /* EditorOption.suggestSelection */, 'suggestSelection', 'first', ['first', 'recentlyUsed', 'recentlyUsedByPrefix'], {
            markdownEnumDescriptions: [
                nls.localize(526, "Always select the first suggestion."),
                nls.localize(527, "Select recent suggestions unless further typing selects one, e.g. `console.| -> console.log` because `log` has been completed recently."),
                nls.localize(528, "Select suggestions based on previous prefixes that have completed those suggestions, e.g. `co -> console` and `con -> const`."),
            ],
            description: nls.localize(529, "Controls how suggestions are pre-selected when showing the suggest list.")
        })),
        tabCompletion: register(new EditorStringEnumOption(124 /* EditorOption.tabCompletion */, 'tabCompletion', 'off', ['on', 'off', 'onlySnippets'], {
            enumDescriptions: [
                nls.localize(530, "Tab complete will insert the best matching suggestion when pressing tab."),
                nls.localize(531, "Disable tab completions."),
                nls.localize(532, "Tab complete snippets when their prefix match. Works best when 'quickSuggestions' aren't enabled."),
            ],
            description: nls.localize(533, "Enables tab completions.")
        })),
        tabIndex: register(new EditorIntOption(125 /* EditorOption.tabIndex */, 'tabIndex', 0, -1, 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */)),
        unicodeHighlight: register(new UnicodeHighlight()),
        unusualLineTerminators: register(new EditorStringEnumOption(127 /* EditorOption.unusualLineTerminators */, 'unusualLineTerminators', 'prompt', ['auto', 'off', 'prompt'], {
            enumDescriptions: [
                nls.localize(534, "Unusual line terminators are automatically removed."),
                nls.localize(535, "Unusual line terminators are ignored."),
                nls.localize(536, "Unusual line terminators prompt to be removed."),
            ],
            description: nls.localize(537, "Remove unusual line terminators that might cause problems.")
        })),
        useShadowDOM: register(new EditorBooleanOption(128 /* EditorOption.useShadowDOM */, 'useShadowDOM', true)),
        useTabStops: register(new EditorBooleanOption(129 /* EditorOption.useTabStops */, 'useTabStops', true, { description: nls.localize(538, "Spaces and tabs are inserted and deleted in alignment with tab stops.") })),
        wordBreak: register(new EditorStringEnumOption(130 /* EditorOption.wordBreak */, 'wordBreak', 'normal', ['normal', 'keepAll'], {
            markdownEnumDescriptions: [
                nls.localize(539, "Use the default line break rule."),
                nls.localize(540, "Word breaks should not be used for Chinese/Japanese/Korean (CJK) text. Non-CJK text behavior is the same as for normal."),
            ],
            description: nls.localize(541, "Controls the word break rules used for Chinese/Japanese/Korean (CJK) text.")
        })),
        wordSegmenterLocales: register(new WordSegmenterLocales()),
        wordSeparators: register(new EditorStringOption(132 /* EditorOption.wordSeparators */, 'wordSeparators', wordHelper_1.USUAL_WORD_SEPARATORS, { description: nls.localize(542, "Characters that will be used as word separators when doing word related navigations or operations.") })),
        wordWrap: register(new EditorStringEnumOption(133 /* EditorOption.wordWrap */, 'wordWrap', 'off', ['off', 'on', 'wordWrapColumn', 'bounded'], {
            markdownEnumDescriptions: [
                nls.localize(543, "Lines will never wrap."),
                nls.localize(544, "Lines will wrap at the viewport width."),
                nls.localize(545, "Lines will wrap at `#editor.wordWrapColumn#`."),





                nls.localize(546, "Lines will wrap at the minimum of viewport and `#editor.wordWrapColumn#`."),






            ],
            description: nls.localize(547, "Controls how lines should wrap.")






        })),
        wordWrapBreakAfterCharacters: register(new EditorStringOption(134 /* EditorOption.wordWrapBreakAfterCharacters */, 'wordWrapBreakAfterCharacters', 
        // allow-any-unicode-next-line
        ' \t})]?|/&.,;¢°′″‰℃、。。、¢,.:;?!%・・ゝゞヽヾーァィゥェォッャュョヮヵヶぁぃぅぇぉっゃゅょゎゕゖㇰㇱㇲㇳㇴㇵㇶㇷㇸㇹㇺㇻㇼㇽㇾㇿ々〻ァィゥェォャュョッー”〉》」』】〕)]}」')),
        wordWrapBreakBeforeCharacters: register(new EditorStringOption(135 /* EditorOption.wordWrapBreakBeforeCharacters */, 'wordWrapBreakBeforeCharacters', 
        // allow-any-unicode-next-line
        '([{‘“〈《「『【〔([{「£¥$£¥++')),
        wordWrapColumn: register(new EditorIntOption(136 /* EditorOption.wordWrapColumn */, 'wordWrapColumn', 80, 1, 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */, {
            markdownDescription: nls.localize(548, "Controls the wrapping column of the editor when `#editor.wordWrap#` is `wordWrapColumn` or `bounded`.")






        })),
        wordWrapOverride1: register(new EditorStringEnumOption(137 /* EditorOption.wordWrapOverride1 */, 'wordWrapOverride1', 'inherit', ['off', 'on', 'inherit'])),
        wordWrapOverride2: register(new EditorStringEnumOption(138 /* EditorOption.wordWrapOverride2 */, 'wordWrapOverride2', 'inherit', ['off', 'on', 'inherit'])),
        // Leave these at the end (because they have dependencies!)
        editorClassName: register(new EditorClassName()),
        defaultColorDecorators: register(new EditorBooleanOption(148 /* EditorOption.defaultColorDecorators */, 'defaultColorDecorators', false, { markdownDescription: nls.localize(549, "Controls whether inline color decorations should be shown using the default document color provider") })),
        pixelRatio: register(new EditorPixelRatio()),
        tabFocusMode: register(new EditorBooleanOption(145 /* EditorOption.tabFocusMode */, 'tabFocusMode', false, { markdownDescription: nls.localize(550, "Controls whether the editor receives tabs or defers them to the workbench for navigation.") })),
        layoutInfo: register(new EditorLayoutInfoComputer()),
        wrappingInfo: register(new EditorWrappingInfoComputer()),
        wrappingIndent: register(new WrappingIndentOption()),
        wrappingStrategy: register(new WrappingStrategy())
    };
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[655/*vs/editor/browser/viewParts/viewCursors/viewCursor*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,39/*vs/base/browser/fastDomNode*/,11/*vs/base/common/strings*/,74/*vs/editor/browser/config/domFontInfo*/,37/*vs/editor/common/config/editorOptions*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/,226/*vs/base/browser/ui/mouseCursor/mouseCursor*/]), function (require, exports, dom, fastDomNode_1, strings, domFontInfo_1, editorOptions_1, position_1, range_1, mouseCursor_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ViewCursor = exports.CursorPlurality = void 0;
    class ViewCursorRenderData {
        constructor(top, left, paddingLeft, width, height, textContent, textContentClassName) {
            this.top = top;
            this.left = left;
            this.paddingLeft = paddingLeft;
            this.width = width;
            this.height = height;
            this.textContent = textContent;
            this.textContentClassName = textContentClassName;
        }
    }
    var CursorPlurality;
    (function (CursorPlurality) {
        CursorPlurality[CursorPlurality["Single"] = 0] = "Single";
        CursorPlurality[CursorPlurality["MultiPrimary"] = 1] = "MultiPrimary";
        CursorPlurality[CursorPlurality["MultiSecondary"] = 2] = "MultiSecondary";
    })(CursorPlurality || (exports.CursorPlurality = CursorPlurality = {}));
    class ViewCursor {
        constructor(context, plurality) {
            this._context = context;
            const options = this._context.configuration.options;
            const fontInfo = options.get(50 /* EditorOption.fontInfo */);
            this._cursorStyle = options.get(28 /* EditorOption.cursorStyle */);
            this._lineHeight = options.get(67 /* EditorOption.lineHeight */);
            this._typicalHalfwidthCharacterWidth = fontInfo.typicalHalfwidthCharacterWidth;
            this._lineCursorWidth = Math.min(options.get(31 /* EditorOption.cursorWidth */), this._typicalHalfwidthCharacterWidth);
            this._isVisible = true;
            // Create the dom node
            this._domNode = (0, fastDomNode_1.createFastDomNode)(document.createElement('div'));
            this._domNode.setClassName(`cursor ${mouseCursor_1.MOUSE_CURSOR_TEXT_CSS_CLASS_NAME}`);
            this._domNode.setHeight(this._lineHeight);
            this._domNode.setTop(0);
            this._domNode.setLeft(0);
            (0, domFontInfo_1.applyFontInfo)(this._domNode, fontInfo);
            this._domNode.setDisplay('none');
            this._position = new position_1.Position(1, 1);
            this._pluralityClass = '';
            this.setPlurality(plurality);
            this._lastRenderedContent = '';
            this._renderData = null;
        }
        getDomNode() {
            return this._domNode;
        }
        getPosition() {
            return this._position;
        }
        setPlurality(plurality) {
            switch (plurality) {
                default:
                case CursorPlurality.Single:
                    this._pluralityClass = '';
                    break;
                case CursorPlurality.MultiPrimary:
                    this._pluralityClass = 'cursor-primary';
                    break;
                case CursorPlurality.MultiSecondary:
                    this._pluralityClass = 'cursor-secondary';
                    break;
            }
        }
        show() {
            if (!this._isVisible) {
                this._domNode.setVisibility('inherit');
                this._isVisible = true;
            }
        }
        hide() {
            if (this._isVisible) {
                this._domNode.setVisibility('hidden');
                this._isVisible = false;
            }
        }
        onConfigurationChanged(e) {
            const options = this._context.configuration.options;
            const fontInfo = options.get(50 /* EditorOption.fontInfo */);
            this._cursorStyle = options.get(28 /* EditorOption.cursorStyle */);
            this._lineHeight = options.get(67 /* EditorOption.lineHeight */);
            this._typicalHalfwidthCharacterWidth = fontInfo.typicalHalfwidthCharacterWidth;
            this._lineCursorWidth = Math.min(options.get(31 /* EditorOption.cursorWidth */), this._typicalHalfwidthCharacterWidth);
            (0, domFontInfo_1.applyFontInfo)(this._domNode, fontInfo);
            return true;
        }
        onCursorPositionChanged(position, pauseAnimation) {
            if (pauseAnimation) {
                this._domNode.domNode.style.transitionProperty = 'none';
            }
            else {
                this._domNode.domNode.style.transitionProperty = '';
            }
            this._position = position;
            return true;
        }
        /**
         * If `this._position` is inside a grapheme, returns the position where the grapheme starts.
         * Also returns the next grapheme.
         */
        _getGraphemeAwarePosition() {
            const { lineNumber, column } = this._position;
            const lineContent = this._context.viewModel.getLineContent(lineNumber);
            const [startOffset, endOffset] = strings.getCharContainingOffset(lineContent, column - 1);
            return [new position_1.Position(lineNumber, startOffset + 1), lineContent.substring(startOffset, endOffset)];
        }
        _prepareRender(ctx) {
            let textContent = '';
            let textContentClassName = '';
            const [position, nextGrapheme] = this._getGraphemeAwarePosition();
            if (this._cursorStyle === editorOptions_1.TextEditorCursorStyle.Line || this._cursorStyle === editorOptions_1.TextEditorCursorStyle.LineThin) {
                const visibleRange = ctx.visibleRangeForPosition(position);
                if (!visibleRange || visibleRange.outsideRenderedLine) {
                    // Outside viewport
                    return null;
                }
                const window = dom.getWindow(this._domNode.domNode);
                let width;
                if (this._cursorStyle === editorOptions_1.TextEditorCursorStyle.Line) {
                    width = dom.computeScreenAwareSize(window, this._lineCursorWidth > 0 ? this._lineCursorWidth : 2);
                    if (width > 2) {
                        textContent = nextGrapheme;
                        textContentClassName = this._getTokenClassName(position);
                    }
                }
                else {
                    width = dom.computeScreenAwareSize(window, 1);
                }
                let left = visibleRange.left;
                let paddingLeft = 0;
                if (width >= 2 && left >= 1) {
                    // shift the cursor a bit between the characters
                    paddingLeft = 1;
                    left -= paddingLeft;
                }
                const top = ctx.getVerticalOffsetForLineNumber(position.lineNumber) - ctx.bigNumbersDelta;
                return new ViewCursorRenderData(top, left, paddingLeft, width, this._lineHeight, textContent, textContentClassName);
            }
            const visibleRangeForCharacter = ctx.linesVisibleRangesForRange(new range_1.Range(position.lineNumber, position.column, position.lineNumber, position.column + nextGrapheme.length), false);
            if (!visibleRangeForCharacter || visibleRangeForCharacter.length === 0) {
                // Outside viewport
                return null;
            }
            const firstVisibleRangeForCharacter = visibleRangeForCharacter[0];
            if (firstVisibleRangeForCharacter.outsideRenderedLine || firstVisibleRangeForCharacter.ranges.length === 0) {
                // Outside viewport
                return null;
            }
            const range = firstVisibleRangeForCharacter.ranges[0];
            const width = (nextGrapheme === '\t'
                ? this._typicalHalfwidthCharacterWidth
                : (range.width < 1
                    ? this._typicalHalfwidthCharacterWidth
                    : range.width));
            if (this._cursorStyle === editorOptions_1.TextEditorCursorStyle.Block) {
                textContent = nextGrapheme;
                textContentClassName = this._getTokenClassName(position);
            }
            let top = ctx.getVerticalOffsetForLineNumber(position.lineNumber) - ctx.bigNumbersDelta;
            let height = this._lineHeight;
            // Underline might interfere with clicking
            if (this._cursorStyle === editorOptions_1.TextEditorCursorStyle.Underline || this._cursorStyle === editorOptions_1.TextEditorCursorStyle.UnderlineThin) {
                top += this._lineHeight - 2;
                height = 2;
            }
            return new ViewCursorRenderData(top, range.left, 0, width, height, textContent, textContentClassName);
        }
        _getTokenClassName(position) {
            const lineData = this._context.viewModel.getViewLineData(position.lineNumber);
            const tokenIndex = lineData.tokens.findTokenIndexAtOffset(position.column - 1);
            return lineData.tokens.getClassName(tokenIndex);
        }
        prepareRender(ctx) {
            this._renderData = this._prepareRender(ctx);
        }
        render(ctx) {
            if (!this._renderData) {
                this._domNode.setDisplay('none');
                return null;
            }
            if (this._lastRenderedContent !== this._renderData.textContent) {
                this._lastRenderedContent = this._renderData.textContent;
                this._domNode.domNode.textContent = this._lastRenderedContent;
            }
            this._domNode.setClassName(`cursor ${this._pluralityClass} ${mouseCursor_1.MOUSE_CURSOR_TEXT_CSS_CLASS_NAME} ${this._renderData.textContentClassName}`);
            this._domNode.setDisplay('block');
            this._domNode.setTop(this._renderData.top);
            this._domNode.setLeft(this._renderData.left);
            this._domNode.setPaddingLeft(this._renderData.paddingLeft);
            this._domNode.setWidth(this._renderData.width);
            this._domNode.setLineHeight(this._renderData.height);
            this._domNode.setHeight(this._renderData.height);
            return {
                domNode: this._domNode.domNode,
                position: this._position,
                contentLeft: this._renderData.left,
                height: this._renderData.height,
                width: 2
            };
        }
    }
    exports.ViewCursor = ViewCursor;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[261/*vs/editor/common/config/fontInfo*/], __M([1/*require*/,0/*exports*/,16/*vs/base/common/platform*/,37/*vs/editor/common/config/editorOptions*/,165/*vs/editor/common/config/editorZoom*/]), function (require, exports, platform, editorOptions_1, editorZoom_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.FontInfo = exports.SERIALIZED_FONT_INFO_VERSION = exports.BareFontInfo = void 0;
    /**
     * Determined from empirical observations.
     * @internal
     */
    const GOLDEN_LINE_HEIGHT_RATIO = platform.isMacintosh ? 1.5 : 1.35;
    /**
     * @internal
     */
    const MINIMUM_LINE_HEIGHT = 8;
    class BareFontInfo {
        /**
         * @internal
         */
        static createFromValidatedSettings(options, pixelRatio, ignoreEditorZoom) {
            const fontFamily = options.get(49 /* EditorOption.fontFamily */);
            const fontWeight = options.get(53 /* EditorOption.fontWeight */);
            const fontSize = options.get(52 /* EditorOption.fontSize */);
            const fontFeatureSettings = options.get(51 /* EditorOption.fontLigatures */);
            const fontVariationSettings = options.get(54 /* EditorOption.fontVariations */);
            const lineHeight = options.get(67 /* EditorOption.lineHeight */);
            const letterSpacing = options.get(64 /* EditorOption.letterSpacing */);
            return BareFontInfo._create(fontFamily, fontWeight, fontSize, fontFeatureSettings, fontVariationSettings, lineHeight, letterSpacing, pixelRatio, ignoreEditorZoom);
        }
        /**
         * @internal
         */
        static _create(fontFamily, fontWeight, fontSize, fontFeatureSettings, fontVariationSettings, lineHeight, letterSpacing, pixelRatio, ignoreEditorZoom) {
            if (lineHeight === 0) {
                lineHeight = GOLDEN_LINE_HEIGHT_RATIO * fontSize;
            }
            else if (lineHeight < MINIMUM_LINE_HEIGHT) {
                // Values too small to be line heights in pixels are in ems.
                lineHeight = lineHeight * fontSize;
            }
            // Enforce integer, minimum constraints
            lineHeight = Math.round(lineHeight);
            if (lineHeight < MINIMUM_LINE_HEIGHT) {
                lineHeight = MINIMUM_LINE_HEIGHT;
            }
            const editorZoomLevelMultiplier = 1 + (ignoreEditorZoom ? 0 : editorZoom_1.EditorZoom.getZoomLevel() * 0.1);
            fontSize *= editorZoomLevelMultiplier;
            lineHeight *= editorZoomLevelMultiplier;
            if (fontVariationSettings === editorOptions_1.EditorFontVariations.TRANSLATE) {
                if (fontWeight === 'normal' || fontWeight === 'bold') {
                    fontVariationSettings = editorOptions_1.EditorFontVariations.OFF;
                }
                else {
                    const fontWeightAsNumber = parseInt(fontWeight, 10);
                    fontVariationSettings = `'wght' ${fontWeightAsNumber}`;
                    fontWeight = 'normal';
                }
            }
            return new BareFontInfo({
                pixelRatio: pixelRatio,
                fontFamily: fontFamily,
                fontWeight: fontWeight,
                fontSize: fontSize,
                fontFeatureSettings: fontFeatureSettings,
                fontVariationSettings,
                lineHeight: lineHeight,
                letterSpacing: letterSpacing
            });
        }
        /**
         * @internal
         */
        constructor(opts) {
            this._bareFontInfoBrand = undefined;
            this.pixelRatio = opts.pixelRatio;
            this.fontFamily = String(opts.fontFamily);
            this.fontWeight = String(opts.fontWeight);
            this.fontSize = opts.fontSize;
            this.fontFeatureSettings = opts.fontFeatureSettings;
            this.fontVariationSettings = opts.fontVariationSettings;
            this.lineHeight = opts.lineHeight | 0;
            this.letterSpacing = opts.letterSpacing;
        }
        /**
         * @internal
         */
        getId() {
            return `${this.pixelRatio}-${this.fontFamily}-${this.fontWeight}-${this.fontSize}-${this.fontFeatureSettings}-${this.fontVariationSettings}-${this.lineHeight}-${this.letterSpacing}`;
        }
        /**
         * @internal
         */
        getMassagedFontFamily() {
            const fallbackFontFamily = editorOptions_1.EDITOR_FONT_DEFAULTS.fontFamily;
            const fontFamily = BareFontInfo._wrapInQuotes(this.fontFamily);
            if (fallbackFontFamily && this.fontFamily !== fallbackFontFamily) {
                return `${fontFamily}, ${fallbackFontFamily}`;
            }
            return fontFamily;
        }
        static _wrapInQuotes(fontFamily) {
            if (/[,"']/.test(fontFamily)) {
                // Looks like the font family might be already escaped
                return fontFamily;
            }
            if (/[+ ]/.test(fontFamily)) {
                // Wrap a font family using + or <space> with quotes
                return `"${fontFamily}"`;
            }
            return fontFamily;
        }
    }
    exports.BareFontInfo = BareFontInfo;
    // change this whenever `FontInfo` members are changed
    exports.SERIALIZED_FONT_INFO_VERSION = 2;
    class FontInfo extends BareFontInfo {
        /**
         * @internal
         */
        constructor(opts, isTrusted) {
            super(opts);
            this._editorStylingBrand = undefined;
            this.version = exports.SERIALIZED_FONT_INFO_VERSION;
            this.isTrusted = isTrusted;
            this.isMonospace = opts.isMonospace;
            this.typicalHalfwidthCharacterWidth = opts.typicalHalfwidthCharacterWidth;
            this.typicalFullwidthCharacterWidth = opts.typicalFullwidthCharacterWidth;
            this.canUseHalfwidthRightwardsArrow = opts.canUseHalfwidthRightwardsArrow;
            this.spaceWidth = opts.spaceWidth;
            this.middotWidth = opts.middotWidth;
            this.wsmiddotWidth = opts.wsmiddotWidth;
            this.maxDigitWidth = opts.maxDigitWidth;
        }
        /**
         * @internal
         */
        equals(other) {
            return (this.fontFamily === other.fontFamily
                && this.fontWeight === other.fontWeight
                && this.fontSize === other.fontSize
                && this.fontFeatureSettings === other.fontFeatureSettings
                && this.fontVariationSettings === other.fontVariationSettings
                && this.lineHeight === other.lineHeight
                && this.letterSpacing === other.letterSpacing
                && this.typicalHalfwidthCharacterWidth === other.typicalHalfwidthCharacterWidth
                && this.typicalFullwidthCharacterWidth === other.typicalFullwidthCharacterWidth
                && this.canUseHalfwidthRightwardsArrow === other.canUseHalfwidthRightwardsArrow
                && this.spaceWidth === other.spaceWidth
                && this.middotWidth === other.middotWidth
                && this.wsmiddotWidth === other.wsmiddotWidth
                && this.maxDigitWidth === other.maxDigitWidth);
        }
    }
    exports.FontInfo = FontInfo;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[366/*vs/editor/browser/config/fontMeasurements*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,253/*vs/base/browser/pixelRatio*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,545/*vs/editor/browser/config/charWidthReader*/,37/*vs/editor/common/config/editorOptions*/,261/*vs/editor/common/config/fontInfo*/]), function (require, exports, dom_1, pixelRatio_1, event_1, lifecycle_1, charWidthReader_1, editorOptions_1, fontInfo_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.FontMeasurements = exports.FontMeasurementsImpl = void 0;
    class FontMeasurementsImpl extends lifecycle_1.Disposable {
        constructor() {
            super(...arguments);
            this._cache = new Map();
            this._evictUntrustedReadingsTimeout = -1;
            this._onDidChange = this._register(new event_1.Emitter());
            this.onDidChange = this._onDidChange.event;
        }
        dispose() {
            if (this._evictUntrustedReadingsTimeout !== -1) {
                clearTimeout(this._evictUntrustedReadingsTimeout);
                this._evictUntrustedReadingsTimeout = -1;
            }
            super.dispose();
        }
        /**
         * Clear all cached font information and trigger a change event.
         */
        clearAllFontInfos() {
            this._cache.clear();
            this._onDidChange.fire();
        }
        _ensureCache(targetWindow) {
            const windowId = (0, dom_1.getWindowId)(targetWindow);
            let cache = this._cache.get(windowId);
            if (!cache) {
                cache = new FontMeasurementsCache();
                this._cache.set(windowId, cache);
            }
            return cache;
        }
        _writeToCache(targetWindow, item, value) {
            const cache = this._ensureCache(targetWindow);
            cache.put(item, value);
            if (!value.isTrusted && this._evictUntrustedReadingsTimeout === -1) {
                // Try reading again after some time
                this._evictUntrustedReadingsTimeout = targetWindow.setTimeout(() => {
                    this._evictUntrustedReadingsTimeout = -1;
                    this._evictUntrustedReadings(targetWindow);
                }, 5000);
            }
        }
        _evictUntrustedReadings(targetWindow) {
            const cache = this._ensureCache(targetWindow);
            const values = cache.getValues();
            let somethingRemoved = false;
            for (const item of values) {
                if (!item.isTrusted) {
                    somethingRemoved = true;
                    cache.remove(item);
                }
            }
            if (somethingRemoved) {
                this._onDidChange.fire();
            }
        }
        /**
         * Read font information.
         */
        readFontInfo(targetWindow, bareFontInfo) {
            const cache = this._ensureCache(targetWindow);
            if (!cache.has(bareFontInfo)) {
                let readConfig = this._actualReadFontInfo(targetWindow, bareFontInfo);
                if (readConfig.typicalHalfwidthCharacterWidth <= 2 || readConfig.typicalFullwidthCharacterWidth <= 2 || readConfig.spaceWidth <= 2 || readConfig.maxDigitWidth <= 2) {
                    // Hey, it's Bug 14341 ... we couldn't read
                    readConfig = new fontInfo_1.FontInfo({
                        pixelRatio: pixelRatio_1.PixelRatio.getInstance(targetWindow).value,
                        fontFamily: readConfig.fontFamily,
                        fontWeight: readConfig.fontWeight,
                        fontSize: readConfig.fontSize,
                        fontFeatureSettings: readConfig.fontFeatureSettings,
                        fontVariationSettings: readConfig.fontVariationSettings,
                        lineHeight: readConfig.lineHeight,
                        letterSpacing: readConfig.letterSpacing,
                        isMonospace: readConfig.isMonospace,
                        typicalHalfwidthCharacterWidth: Math.max(readConfig.typicalHalfwidthCharacterWidth, 5),
                        typicalFullwidthCharacterWidth: Math.max(readConfig.typicalFullwidthCharacterWidth, 5),
                        canUseHalfwidthRightwardsArrow: readConfig.canUseHalfwidthRightwardsArrow,
                        spaceWidth: Math.max(readConfig.spaceWidth, 5),
                        middotWidth: Math.max(readConfig.middotWidth, 5),
                        wsmiddotWidth: Math.max(readConfig.wsmiddotWidth, 5),
                        maxDigitWidth: Math.max(readConfig.maxDigitWidth, 5),
                    }, false);
                }
                this._writeToCache(targetWindow, bareFontInfo, readConfig);
            }
            return cache.get(bareFontInfo);
        }
        _createRequest(chr, type, all, monospace) {
            const result = new charWidthReader_1.CharWidthRequest(chr, type);
            all.push(result);
            monospace?.push(result);
            return result;
        }
        _actualReadFontInfo(targetWindow, bareFontInfo) {
            const all = [];
            const monospace = [];
            const typicalHalfwidthCharacter = this._createRequest('n', 0 /* CharWidthRequestType.Regular */, all, monospace);
            const typicalFullwidthCharacter = this._createRequest('\uff4d', 0 /* CharWidthRequestType.Regular */, all, null);
            const space = this._createRequest(' ', 0 /* CharWidthRequestType.Regular */, all, monospace);
            const digit0 = this._createRequest('0', 0 /* CharWidthRequestType.Regular */, all, monospace);
            const digit1 = this._createRequest('1', 0 /* CharWidthRequestType.Regular */, all, monospace);
            const digit2 = this._createRequest('2', 0 /* CharWidthRequestType.Regular */, all, monospace);
            const digit3 = this._createRequest('3', 0 /* CharWidthRequestType.Regular */, all, monospace);
            const digit4 = this._createRequest('4', 0 /* CharWidthRequestType.Regular */, all, monospace);
            const digit5 = this._createRequest('5', 0 /* CharWidthRequestType.Regular */, all, monospace);
            const digit6 = this._createRequest('6', 0 /* CharWidthRequestType.Regular */, all, monospace);
            const digit7 = this._createRequest('7', 0 /* CharWidthRequestType.Regular */, all, monospace);
            const digit8 = this._createRequest('8', 0 /* CharWidthRequestType.Regular */, all, monospace);
            const digit9 = this._createRequest('9', 0 /* CharWidthRequestType.Regular */, all, monospace);
            // monospace test: used for whitespace rendering
            const rightwardsArrow = this._createRequest('→', 0 /* CharWidthRequestType.Regular */, all, monospace);
            const halfwidthRightwardsArrow = this._createRequest('→', 0 /* CharWidthRequestType.Regular */, all, null);
            // U+00B7 - MIDDLE DOT
            const middot = this._createRequest('·', 0 /* CharWidthRequestType.Regular */, all, monospace);
            // U+2E31 - WORD SEPARATOR MIDDLE DOT
            const wsmiddotWidth = this._createRequest(String.fromCharCode(0x2E31), 0 /* CharWidthRequestType.Regular */, all, null);
            // monospace test: some characters
            const monospaceTestChars = '|/-_ilm%';
            for (let i = 0, len = monospaceTestChars.length; i < len; i++) {
                this._createRequest(monospaceTestChars.charAt(i), 0 /* CharWidthRequestType.Regular */, all, monospace);
                this._createRequest(monospaceTestChars.charAt(i), 1 /* CharWidthRequestType.Italic */, all, monospace);
                this._createRequest(monospaceTestChars.charAt(i), 2 /* CharWidthRequestType.Bold */, all, monospace);
            }
            (0, charWidthReader_1.readCharWidths)(targetWindow, bareFontInfo, all);
            const maxDigitWidth = Math.max(digit0.width, digit1.width, digit2.width, digit3.width, digit4.width, digit5.width, digit6.width, digit7.width, digit8.width, digit9.width);
            let isMonospace = (bareFontInfo.fontFeatureSettings === editorOptions_1.EditorFontLigatures.OFF);
            const referenceWidth = monospace[0].width;
            for (let i = 1, len = monospace.length; isMonospace && i < len; i++) {
                const diff = referenceWidth - monospace[i].width;
                if (diff < -0.001 || diff > 0.001) {
                    isMonospace = false;
                    break;
                }
            }
            let canUseHalfwidthRightwardsArrow = true;
            if (isMonospace && halfwidthRightwardsArrow.width !== referenceWidth) {
                // using a halfwidth rightwards arrow would break monospace...
                canUseHalfwidthRightwardsArrow = false;
            }
            if (halfwidthRightwardsArrow.width > rightwardsArrow.width) {
                // using a halfwidth rightwards arrow would paint a larger arrow than a regular rightwards arrow
                canUseHalfwidthRightwardsArrow = false;
            }
            return new fontInfo_1.FontInfo({
                pixelRatio: pixelRatio_1.PixelRatio.getInstance(targetWindow).value,
                fontFamily: bareFontInfo.fontFamily,
                fontWeight: bareFontInfo.fontWeight,
                fontSize: bareFontInfo.fontSize,
                fontFeatureSettings: bareFontInfo.fontFeatureSettings,
                fontVariationSettings: bareFontInfo.fontVariationSettings,
                lineHeight: bareFontInfo.lineHeight,
                letterSpacing: bareFontInfo.letterSpacing,
                isMonospace: isMonospace,
                typicalHalfwidthCharacterWidth: typicalHalfwidthCharacter.width,
                typicalFullwidthCharacterWidth: typicalFullwidthCharacter.width,
                canUseHalfwidthRightwardsArrow: canUseHalfwidthRightwardsArrow,
                spaceWidth: space.width,
                middotWidth: middot.width,
                wsmiddotWidth: wsmiddotWidth.width,
                maxDigitWidth: maxDigitWidth
            }, true);
        }
    }
    exports.FontMeasurementsImpl = FontMeasurementsImpl;
    class FontMeasurementsCache {
        constructor() {
            this._keys = Object.create(null);
            this._values = Object.create(null);
        }
        has(item) {
            const itemId = item.getId();
            return !!this._values[itemId];
        }
        get(item) {
            const itemId = item.getId();
            return this._values[itemId];
        }
        put(item, value) {
            const itemId = item.getId();
            this._keys[itemId] = item;
            this._values[itemId] = value;
        }
        remove(item) {
            const itemId = item.getId();
            delete this._keys[itemId];
            delete this._values[itemId];
        }
        getValues() {
            return Object.keys(this._keys).map(id => this._values[id]);
        }
    }
    exports.FontMeasurements = new FontMeasurementsImpl();
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[116/*vs/editor/common/core/stringBuilder*/], __M([1/*require*/,0/*exports*/,11/*vs/base/common/strings*/,16/*vs/base/common/platform*/,160/*vs/base/common/buffer*/]), function (require, exports, strings, platform, buffer) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.StringBuilder = void 0;
    exports.getPlatformTextDecoder = getPlatformTextDecoder;
    exports.decodeUTF16LE = decodeUTF16LE;
    let _utf16LE_TextDecoder;
    function getUTF16LE_TextDecoder() {
        if (!_utf16LE_TextDecoder) {
            _utf16LE_TextDecoder = new TextDecoder('UTF-16LE');
        }
        return _utf16LE_TextDecoder;
    }
    let _utf16BE_TextDecoder;
    function getUTF16BE_TextDecoder() {
        if (!_utf16BE_TextDecoder) {
            _utf16BE_TextDecoder = new TextDecoder('UTF-16BE');
        }
        return _utf16BE_TextDecoder;
    }
    let _platformTextDecoder;
    function getPlatformTextDecoder() {
        if (!_platformTextDecoder) {
            _platformTextDecoder = platform.isLittleEndian() ? getUTF16LE_TextDecoder() : getUTF16BE_TextDecoder();
        }
        return _platformTextDecoder;
    }
    function decodeUTF16LE(source, offset, len) {
        const view = new Uint16Array(source.buffer, offset, len);
        if (len > 0 && (view[0] === 0xFEFF || view[0] === 0xFFFE)) {
            // UTF16 sometimes starts with a BOM https://de.wikipedia.org/wiki/Byte_Order_Mark
            // It looks like TextDecoder.decode will eat up a leading BOM (0xFEFF or 0xFFFE)
            // We don't want that behavior because we know the string is UTF16LE and the BOM should be maintained
            // So we use the manual decoder
            return compatDecodeUTF16LE(source, offset, len);
        }
        return getUTF16LE_TextDecoder().decode(view);
    }
    function compatDecodeUTF16LE(source, offset, len) {
        const result = [];
        let resultLen = 0;
        for (let i = 0; i < len; i++) {
            const charCode = buffer.readUInt16LE(source, offset);
            offset += 2;
            result[resultLen++] = String.fromCharCode(charCode);
        }
        return result.join('');
    }
    class StringBuilder {
        constructor(capacity) {
            this._capacity = capacity | 0;
            this._buffer = new Uint16Array(this._capacity);
            this._completedStrings = null;
            this._bufferLength = 0;
        }
        reset() {
            this._completedStrings = null;
            this._bufferLength = 0;
        }
        build() {
            if (this._completedStrings !== null) {
                this._flushBuffer();
                return this._completedStrings.join('');
            }
            return this._buildBuffer();
        }
        _buildBuffer() {
            if (this._bufferLength === 0) {
                return '';
            }
            const view = new Uint16Array(this._buffer.buffer, 0, this._bufferLength);
            return getPlatformTextDecoder().decode(view);
        }
        _flushBuffer() {
            const bufferString = this._buildBuffer();
            this._bufferLength = 0;
            if (this._completedStrings === null) {
                this._completedStrings = [bufferString];
            }
            else {
                this._completedStrings[this._completedStrings.length] = bufferString;
            }
        }
        /**
         * Append a char code (<2^16)
         */
        appendCharCode(charCode) {
            const remainingSpace = this._capacity - this._bufferLength;
            if (remainingSpace <= 1) {
                if (remainingSpace === 0 || strings.isHighSurrogate(charCode)) {
                    this._flushBuffer();
                }
            }
            this._buffer[this._bufferLength++] = charCode;
        }
        /**
         * Append an ASCII char code (<2^8)
         */
        appendASCIICharCode(charCode) {
            if (this._bufferLength === this._capacity) {
                // buffer is full
                this._flushBuffer();
            }
            this._buffer[this._bufferLength++] = charCode;
        }
        appendString(str) {
            const strLen = str.length;
            if (this._bufferLength + strLen >= this._capacity) {
                // This string does not fit in the remaining buffer space
                this._flushBuffer();
                this._completedStrings[this._completedStrings.length] = str;
                return;
            }
            for (let i = 0; i < strLen; i++) {
                this._buffer[this._bufferLength++] = str.charCodeAt(i);
            }
        }
    }
    exports.StringBuilder = StringBuilder;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[656/*vs/editor/browser/view/domLineBreaksComputer*/], __M([1/*require*/,0/*exports*/,103/*vs/base/browser/trustedTypes*/,11/*vs/base/common/strings*/,19/*vs/base/common/types*/,74/*vs/editor/browser/config/domFontInfo*/,116/*vs/editor/common/core/stringBuilder*/,325/*vs/editor/common/modelLineProjectionData*/,132/*vs/editor/common/textModelEvents*/]), function (require, exports, trustedTypes_1, strings, types_1, domFontInfo_1, stringBuilder_1, modelLineProjectionData_1, textModelEvents_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DOMLineBreaksComputerFactory = void 0;
    const ttPolicy = (0, trustedTypes_1.createTrustedTypesPolicy)('domLineBreaksComputer', { createHTML: value => value });
    class DOMLineBreaksComputerFactory {
        static create(targetWindow) {
            return new DOMLineBreaksComputerFactory(new WeakRef(targetWindow));
        }
        constructor(targetWindow) {
            this.targetWindow = targetWindow;
        }
        createLineBreaksComputer(fontInfo, tabSize, wrappingColumn, wrappingIndent, wordBreak) {
            const requests = [];
            const injectedTexts = [];
            return {
                addRequest: (lineText, injectedText, previousLineBreakData) => {
                    requests.push(lineText);
                    injectedTexts.push(injectedText);
                },
                finalize: () => {
                    return createLineBreaks((0, types_1.assertIsDefined)(this.targetWindow.deref()), requests, fontInfo, tabSize, wrappingColumn, wrappingIndent, wordBreak, injectedTexts);
                }
            };
        }
    }
    exports.DOMLineBreaksComputerFactory = DOMLineBreaksComputerFactory;
    function createLineBreaks(targetWindow, requests, fontInfo, tabSize, firstLineBreakColumn, wrappingIndent, wordBreak, injectedTextsPerLine) {
        function createEmptyLineBreakWithPossiblyInjectedText(requestIdx) {
            const injectedTexts = injectedTextsPerLine[requestIdx];
            if (injectedTexts) {
                const lineText = textModelEvents_1.LineInjectedText.applyInjectedText(requests[requestIdx], injectedTexts);
                const injectionOptions = injectedTexts.map(t => t.options);
                const injectionOffsets = injectedTexts.map(text => text.column - 1);
                // creating a `LineBreakData` with an invalid `breakOffsetsVisibleColumn` is OK
                // because `breakOffsetsVisibleColumn` will never be used because it contains injected text
                return new modelLineProjectionData_1.ModelLineProjectionData(injectionOffsets, injectionOptions, [lineText.length], [], 0);
            }
            else {
                return null;
            }
        }
        if (firstLineBreakColumn === -1) {
            const result = [];
            for (let i = 0, len = requests.length; i < len; i++) {
                result[i] = createEmptyLineBreakWithPossiblyInjectedText(i);
            }
            return result;
        }
        const overallWidth = Math.round(firstLineBreakColumn * fontInfo.typicalHalfwidthCharacterWidth);
        const additionalIndent = (wrappingIndent === 3 /* WrappingIndent.DeepIndent */ ? 2 : wrappingIndent === 2 /* WrappingIndent.Indent */ ? 1 : 0);
        const additionalIndentSize = Math.round(tabSize * additionalIndent);
        const additionalIndentLength = Math.ceil(fontInfo.spaceWidth * additionalIndentSize);
        const containerDomNode = document.createElement('div');
        (0, domFontInfo_1.applyFontInfo)(containerDomNode, fontInfo);
        const sb = new stringBuilder_1.StringBuilder(10000);
        const firstNonWhitespaceIndices = [];
        const wrappedTextIndentLengths = [];
        const renderLineContents = [];
        const allCharOffsets = [];
        const allVisibleColumns = [];
        for (let i = 0; i < requests.length; i++) {
            const lineContent = textModelEvents_1.LineInjectedText.applyInjectedText(requests[i], injectedTextsPerLine[i]);
            let firstNonWhitespaceIndex = 0;
            let wrappedTextIndentLength = 0;
            let width = overallWidth;
            if (wrappingIndent !== 0 /* WrappingIndent.None */) {
                firstNonWhitespaceIndex = strings.firstNonWhitespaceIndex(lineContent);
                if (firstNonWhitespaceIndex === -1) {
                    // all whitespace line
                    firstNonWhitespaceIndex = 0;
                }
                else {
                    // Track existing indent
                    for (let i = 0; i < firstNonWhitespaceIndex; i++) {
                        const charWidth = (lineContent.charCodeAt(i) === 9 /* CharCode.Tab */
                            ? (tabSize - (wrappedTextIndentLength % tabSize))
                            : 1);
                        wrappedTextIndentLength += charWidth;
                    }
                    const indentWidth = Math.ceil(fontInfo.spaceWidth * wrappedTextIndentLength);
                    // Force sticking to beginning of line if no character would fit except for the indentation
                    if (indentWidth + fontInfo.typicalFullwidthCharacterWidth > overallWidth) {
                        firstNonWhitespaceIndex = 0;
                        wrappedTextIndentLength = 0;
                    }
                    else {
                        width = overallWidth - indentWidth;
                    }
                }
            }
            const renderLineContent = lineContent.substr(firstNonWhitespaceIndex);
            const tmp = renderLine(renderLineContent, wrappedTextIndentLength, tabSize, width, sb, additionalIndentLength);
            firstNonWhitespaceIndices[i] = firstNonWhitespaceIndex;
            wrappedTextIndentLengths[i] = wrappedTextIndentLength;
            renderLineContents[i] = renderLineContent;
            allCharOffsets[i] = tmp[0];
            allVisibleColumns[i] = tmp[1];
        }
        const html = sb.build();
        const trustedhtml = ttPolicy?.createHTML(html) ?? html;
        containerDomNode.innerHTML = trustedhtml;
        containerDomNode.style.position = 'absolute';
        containerDomNode.style.top = '10000';
        if (wordBreak === 'keepAll') {
            // word-break: keep-all; overflow-wrap: anywhere
            containerDomNode.style.wordBreak = 'keep-all';
            containerDomNode.style.overflowWrap = 'anywhere';
        }
        else {
            // overflow-wrap: break-word
            containerDomNode.style.wordBreak = 'inherit';
            containerDomNode.style.overflowWrap = 'break-word';
        }
        targetWindow.document.body.appendChild(containerDomNode);
        const range = document.createRange();
        const lineDomNodes = Array.prototype.slice.call(containerDomNode.children, 0);
        const result = [];
        for (let i = 0; i < requests.length; i++) {
            const lineDomNode = lineDomNodes[i];
            const breakOffsets = readLineBreaks(range, lineDomNode, renderLineContents[i], allCharOffsets[i]);
            if (breakOffsets === null) {
                result[i] = createEmptyLineBreakWithPossiblyInjectedText(i);
                continue;
            }
            const firstNonWhitespaceIndex = firstNonWhitespaceIndices[i];
            const wrappedTextIndentLength = wrappedTextIndentLengths[i] + additionalIndentSize;
            const visibleColumns = allVisibleColumns[i];
            const breakOffsetsVisibleColumn = [];
            for (let j = 0, len = breakOffsets.length; j < len; j++) {
                breakOffsetsVisibleColumn[j] = visibleColumns[breakOffsets[j]];
            }
            if (firstNonWhitespaceIndex !== 0) {
                // All break offsets are relative to the renderLineContent, make them absolute again
                for (let j = 0, len = breakOffsets.length; j < len; j++) {
                    breakOffsets[j] += firstNonWhitespaceIndex;
                }
            }
            let injectionOptions;
            let injectionOffsets;
            const curInjectedTexts = injectedTextsPerLine[i];
            if (curInjectedTexts) {
                injectionOptions = curInjectedTexts.map(t => t.options);
                injectionOffsets = curInjectedTexts.map(text => text.column - 1);
            }
            else {
                injectionOptions = null;
                injectionOffsets = null;
            }
            result[i] = new modelLineProjectionData_1.ModelLineProjectionData(injectionOffsets, injectionOptions, breakOffsets, breakOffsetsVisibleColumn, wrappedTextIndentLength);
        }
        containerDomNode.remove();
        return result;
    }
    function renderLine(lineContent, initialVisibleColumn, tabSize, width, sb, wrappingIndentLength) {
        if (wrappingIndentLength !== 0) {
            const hangingOffset = String(wrappingIndentLength);
            sb.appendString('<div style="text-indent: -');
            sb.appendString(hangingOffset);
            sb.appendString('px; padding-left: ');
            sb.appendString(hangingOffset);
            sb.appendString('px; box-sizing: border-box; width:');
        }
        else {
            sb.appendString('<div style="width:');
        }
        sb.appendString(String(width));
        sb.appendString('px;">');
        // if (containsRTL) {
        // 	sb.appendASCIIString('" dir="ltr');
        // }
        const len = lineContent.length;
        let visibleColumn = initialVisibleColumn;
        let charOffset = 0;
        const charOffsets = [];
        const visibleColumns = [];
        let nextCharCode = (0 < len ? lineContent.charCodeAt(0) : 0 /* CharCode.Null */);
        sb.appendString('<span>');
        for (let charIndex = 0; charIndex < len; charIndex++) {
            if (charIndex !== 0 && charIndex % 16384 /* Constants.SPAN_MODULO_LIMIT */ === 0) {
                sb.appendString('</span><span>');
            }
            charOffsets[charIndex] = charOffset;
            visibleColumns[charIndex] = visibleColumn;
            const charCode = nextCharCode;
            nextCharCode = (charIndex + 1 < len ? lineContent.charCodeAt(charIndex + 1) : 0 /* CharCode.Null */);
            let producedCharacters = 1;
            let charWidth = 1;
            switch (charCode) {
                case 9 /* CharCode.Tab */:
                    producedCharacters = (tabSize - (visibleColumn % tabSize));
                    charWidth = producedCharacters;
                    for (let space = 1; space <= producedCharacters; space++) {
                        if (space < producedCharacters) {
                            sb.appendCharCode(0xA0); // &nbsp;
                        }
                        else {
                            sb.appendASCIICharCode(32 /* CharCode.Space */);
                        }
                    }
                    break;
                case 32 /* CharCode.Space */:
                    if (nextCharCode === 32 /* CharCode.Space */) {
                        sb.appendCharCode(0xA0); // &nbsp;
                    }
                    else {
                        sb.appendASCIICharCode(32 /* CharCode.Space */);
                    }
                    break;
                case 60 /* CharCode.LessThan */:
                    sb.appendString('&lt;');
                    break;
                case 62 /* CharCode.GreaterThan */:
                    sb.appendString('&gt;');
                    break;
                case 38 /* CharCode.Ampersand */:
                    sb.appendString('&amp;');
                    break;
                case 0 /* CharCode.Null */:
                    sb.appendString('&#00;');
                    break;
                case 65279 /* CharCode.UTF8_BOM */:
                case 8232 /* CharCode.LINE_SEPARATOR */:
                case 8233 /* CharCode.PARAGRAPH_SEPARATOR */:
                case 133 /* CharCode.NEXT_LINE */:
                    sb.appendCharCode(0xFFFD);
                    break;
                default:
                    if (strings.isFullWidthCharacter(charCode)) {
                        charWidth++;
                    }
                    if (charCode < 32) {
                        sb.appendCharCode(9216 + charCode);
                    }
                    else {
                        sb.appendCharCode(charCode);
                    }
            }
            charOffset += producedCharacters;
            visibleColumn += charWidth;
        }
        sb.appendString('</span>');
        charOffsets[lineContent.length] = charOffset;
        visibleColumns[lineContent.length] = visibleColumn;
        sb.appendString('</div>');
        return [charOffsets, visibleColumns];
    }
    function readLineBreaks(range, lineDomNode, lineContent, charOffsets) {
        if (lineContent.length <= 1) {
            return null;
        }
        const spans = Array.prototype.slice.call(lineDomNode.children, 0);
        const breakOffsets = [];
        try {
            discoverBreaks(range, spans, charOffsets, 0, null, lineContent.length - 1, null, breakOffsets);
        }
        catch (err) {
            console.log(err);
            return null;
        }
        if (breakOffsets.length === 0) {
            return null;
        }
        breakOffsets.push(lineContent.length);
        return breakOffsets;
    }
    function discoverBreaks(range, spans, charOffsets, low, lowRects, high, highRects, result) {
        if (low === high) {
            return;
        }
        lowRects = lowRects || readClientRect(range, spans, charOffsets[low], charOffsets[low + 1]);
        highRects = highRects || readClientRect(range, spans, charOffsets[high], charOffsets[high + 1]);
        if (Math.abs(lowRects[0].top - highRects[0].top) <= 0.1) {
            // same line
            return;
        }
        // there is at least one line break between these two offsets
        if (low + 1 === high) {
            // the two characters are adjacent, so the line break must be exactly between them
            result.push(high);
            return;
        }
        const mid = low + ((high - low) / 2) | 0;
        const midRects = readClientRect(range, spans, charOffsets[mid], charOffsets[mid + 1]);
        discoverBreaks(range, spans, charOffsets, low, lowRects, mid, midRects, result);
        discoverBreaks(range, spans, charOffsets, mid, midRects, high, highRects, result);
    }
    function readClientRect(range, spans, startOffset, endOffset) {
        range.setStart(spans[(startOffset / 16384 /* Constants.SPAN_MODULO_LIMIT */) | 0].firstChild, startOffset % 16384 /* Constants.SPAN_MODULO_LIMIT */);
        range.setEnd(spans[(endOffset / 16384 /* Constants.SPAN_MODULO_LIMIT */) | 0].firstChild, endOffset % 16384 /* Constants.SPAN_MODULO_LIMIT */);
        return range.getClientRects();
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[262/*vs/editor/browser/view/viewLayer*/], __M([1/*require*/,0/*exports*/,39/*vs/base/browser/fastDomNode*/,103/*vs/base/browser/trustedTypes*/,8/*vs/base/common/errors*/,116/*vs/editor/common/core/stringBuilder*/]), function (require, exports, fastDomNode_1, trustedTypes_1, errors_1, stringBuilder_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.VisibleLinesCollection = exports.RenderedLinesCollection = void 0;
    class RenderedLinesCollection {
        constructor(_lineFactory) {
            this._lineFactory = _lineFactory;
            this._set(1, []);
        }
        flush() {
            this._set(1, []);
        }
        _set(rendLineNumberStart, lines) {
            this._lines = lines;
            this._rendLineNumberStart = rendLineNumberStart;
        }
        _get() {
            return {
                rendLineNumberStart: this._rendLineNumberStart,
                lines: this._lines
            };
        }
        /**
         * @returns Inclusive line number that is inside this collection
         */
        getStartLineNumber() {
            return this._rendLineNumberStart;
        }
        /**
         * @returns Inclusive line number that is inside this collection
         */
        getEndLineNumber() {
            return this._rendLineNumberStart + this._lines.length - 1;
        }
        getCount() {
            return this._lines.length;
        }
        getLine(lineNumber) {
            const lineIndex = lineNumber - this._rendLineNumberStart;
            if (lineIndex < 0 || lineIndex >= this._lines.length) {
                throw new errors_1.BugIndicatingError('Illegal value for lineNumber');
            }
            return this._lines[lineIndex];
        }
        /**
         * @returns Lines that were removed from this collection
         */
        onLinesDeleted(deleteFromLineNumber, deleteToLineNumber) {
            if (this.getCount() === 0) {
                // no lines
                return null;
            }
            const startLineNumber = this.getStartLineNumber();
            const endLineNumber = this.getEndLineNumber();
            if (deleteToLineNumber < startLineNumber) {
                // deleting above the viewport
                const deleteCnt = deleteToLineNumber - deleteFromLineNumber + 1;
                this._rendLineNumberStart -= deleteCnt;
                return null;
            }
            if (deleteFromLineNumber > endLineNumber) {
                // deleted below the viewport
                return null;
            }
            // Record what needs to be deleted
            let deleteStartIndex = 0;
            let deleteCount = 0;
            for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
                const lineIndex = lineNumber - this._rendLineNumberStart;
                if (deleteFromLineNumber <= lineNumber && lineNumber <= deleteToLineNumber) {
                    // this is a line to be deleted
                    if (deleteCount === 0) {
                        // this is the first line to be deleted
                        deleteStartIndex = lineIndex;
                        deleteCount = 1;
                    }
                    else {
                        deleteCount++;
                    }
                }
            }
            // Adjust this._rendLineNumberStart for lines deleted above
            if (deleteFromLineNumber < startLineNumber) {
                // Something was deleted above
                let deleteAboveCount = 0;
                if (deleteToLineNumber < startLineNumber) {
                    // the entire deleted lines are above
                    deleteAboveCount = deleteToLineNumber - deleteFromLineNumber + 1;
                }
                else {
                    deleteAboveCount = startLineNumber - deleteFromLineNumber;
                }
                this._rendLineNumberStart -= deleteAboveCount;
            }
            const deleted = this._lines.splice(deleteStartIndex, deleteCount);
            return deleted;
        }
        onLinesChanged(changeFromLineNumber, changeCount) {
            const changeToLineNumber = changeFromLineNumber + changeCount - 1;
            if (this.getCount() === 0) {
                // no lines
                return false;
            }
            const startLineNumber = this.getStartLineNumber();
            const endLineNumber = this.getEndLineNumber();
            let someoneNotified = false;
            for (let changedLineNumber = changeFromLineNumber; changedLineNumber <= changeToLineNumber; changedLineNumber++) {
                if (changedLineNumber >= startLineNumber && changedLineNumber <= endLineNumber) {
                    // Notify the line
                    this._lines[changedLineNumber - this._rendLineNumberStart].onContentChanged();
                    someoneNotified = true;
                }
            }
            return someoneNotified;
        }
        onLinesInserted(insertFromLineNumber, insertToLineNumber) {
            if (this.getCount() === 0) {
                // no lines
                return null;
            }
            const insertCnt = insertToLineNumber - insertFromLineNumber + 1;
            const startLineNumber = this.getStartLineNumber();
            const endLineNumber = this.getEndLineNumber();
            if (insertFromLineNumber <= startLineNumber) {
                // inserting above the viewport
                this._rendLineNumberStart += insertCnt;
                return null;
            }
            if (insertFromLineNumber > endLineNumber) {
                // inserting below the viewport
                return null;
            }
            if (insertCnt + insertFromLineNumber > endLineNumber) {
                // insert inside the viewport in such a way that all remaining lines are pushed outside
                const deleted = this._lines.splice(insertFromLineNumber - this._rendLineNumberStart, endLineNumber - insertFromLineNumber + 1);
                return deleted;
            }
            // insert inside the viewport, push out some lines, but not all remaining lines
            const newLines = [];
            for (let i = 0; i < insertCnt; i++) {
                newLines[i] = this._lineFactory.createLine();
            }
            const insertIndex = insertFromLineNumber - this._rendLineNumberStart;
            const beforeLines = this._lines.slice(0, insertIndex);
            const afterLines = this._lines.slice(insertIndex, this._lines.length - insertCnt);
            const deletedLines = this._lines.slice(this._lines.length - insertCnt, this._lines.length);
            this._lines = beforeLines.concat(newLines).concat(afterLines);
            return deletedLines;
        }
        onTokensChanged(ranges) {
            if (this.getCount() === 0) {
                // no lines
                return false;
            }
            const startLineNumber = this.getStartLineNumber();
            const endLineNumber = this.getEndLineNumber();
            let notifiedSomeone = false;
            for (let i = 0, len = ranges.length; i < len; i++) {
                const rng = ranges[i];
                if (rng.toLineNumber < startLineNumber || rng.fromLineNumber > endLineNumber) {
                    // range outside viewport
                    continue;
                }
                const from = Math.max(startLineNumber, rng.fromLineNumber);
                const to = Math.min(endLineNumber, rng.toLineNumber);
                for (let lineNumber = from; lineNumber <= to; lineNumber++) {
                    const lineIndex = lineNumber - this._rendLineNumberStart;
                    this._lines[lineIndex].onTokensChanged();
                    notifiedSomeone = true;
                }
            }
            return notifiedSomeone;
        }
    }
    exports.RenderedLinesCollection = RenderedLinesCollection;
    class VisibleLinesCollection {
        constructor(_lineFactory) {
            this._lineFactory = _lineFactory;
            this.domNode = this._createDomNode();
            this._linesCollection = new RenderedLinesCollection(this._lineFactory);
        }
        _createDomNode() {
            const domNode = (0, fastDomNode_1.createFastDomNode)(document.createElement('div'));
            domNode.setClassName('view-layer');
            domNode.setPosition('absolute');
            domNode.domNode.setAttribute('role', 'presentation');
            domNode.domNode.setAttribute('aria-hidden', 'true');
            return domNode;
        }
        // ---- begin view event handlers
        onConfigurationChanged(e) {
            if (e.hasChanged(146 /* EditorOption.layoutInfo */)) {
                return true;
            }
            return false;
        }
        onFlushed(e) {
            this._linesCollection.flush();
            // No need to clear the dom node because a full .innerHTML will occur in ViewLayerRenderer._render
            return true;
        }
        onLinesChanged(e) {
            return this._linesCollection.onLinesChanged(e.fromLineNumber, e.count);
        }
        onLinesDeleted(e) {
            const deleted = this._linesCollection.onLinesDeleted(e.fromLineNumber, e.toLineNumber);
            if (deleted) {
                // Remove from DOM
                for (let i = 0, len = deleted.length; i < len; i++) {
                    const lineDomNode = deleted[i].getDomNode();
                    lineDomNode?.remove();
                }
            }
            return true;
        }
        onLinesInserted(e) {
            const deleted = this._linesCollection.onLinesInserted(e.fromLineNumber, e.toLineNumber);
            if (deleted) {
                // Remove from DOM
                for (let i = 0, len = deleted.length; i < len; i++) {
                    const lineDomNode = deleted[i].getDomNode();
                    lineDomNode?.remove();
                }
            }
            return true;
        }
        onScrollChanged(e) {
            return e.scrollTopChanged;
        }
        onTokensChanged(e) {
            return this._linesCollection.onTokensChanged(e.ranges);
        }
        onZonesChanged(e) {
            return true;
        }
        // ---- end view event handlers
        getStartLineNumber() {
            return this._linesCollection.getStartLineNumber();
        }
        getEndLineNumber() {
            return this._linesCollection.getEndLineNumber();
        }
        getVisibleLine(lineNumber) {
            return this._linesCollection.getLine(lineNumber);
        }
        renderLines(viewportData) {
            const inp = this._linesCollection._get();
            const renderer = new ViewLayerRenderer(this.domNode.domNode, this._lineFactory, viewportData);
            const ctx = {
                rendLineNumberStart: inp.rendLineNumberStart,
                lines: inp.lines,
                linesLength: inp.lines.length
            };
            // Decide if this render will do a single update (single large .innerHTML) or many updates (inserting/removing dom nodes)
            const resCtx = renderer.render(ctx, viewportData.startLineNumber, viewportData.endLineNumber, viewportData.relativeVerticalOffset);
            this._linesCollection._set(resCtx.rendLineNumberStart, resCtx.lines);
        }
    }
    exports.VisibleLinesCollection = VisibleLinesCollection;
    class ViewLayerRenderer {
        static { this._ttPolicy = (0, trustedTypes_1.createTrustedTypesPolicy)('editorViewLayer', { createHTML: value => value }); }
        constructor(_domNode, _lineFactory, _viewportData) {
            this._domNode = _domNode;
            this._lineFactory = _lineFactory;
            this._viewportData = _viewportData;
        }
        render(inContext, startLineNumber, stopLineNumber, deltaTop) {
            const ctx = {
                rendLineNumberStart: inContext.rendLineNumberStart,
                lines: inContext.lines.slice(0),
                linesLength: inContext.linesLength
            };
            if ((ctx.rendLineNumberStart + ctx.linesLength - 1 < startLineNumber) || (stopLineNumber < ctx.rendLineNumberStart)) {
                // There is no overlap whatsoever
                ctx.rendLineNumberStart = startLineNumber;
                ctx.linesLength = stopLineNumber - startLineNumber + 1;
                ctx.lines = [];
                for (let x = startLineNumber; x <= stopLineNumber; x++) {
                    ctx.lines[x - startLineNumber] = this._lineFactory.createLine();
                }
                this._finishRendering(ctx, true, deltaTop);
                return ctx;
            }
            // Update lines which will remain untouched
            this._renderUntouchedLines(ctx, Math.max(startLineNumber - ctx.rendLineNumberStart, 0), Math.min(stopLineNumber - ctx.rendLineNumberStart, ctx.linesLength - 1), deltaTop, startLineNumber);
            if (ctx.rendLineNumberStart > startLineNumber) {
                // Insert lines before
                const fromLineNumber = startLineNumber;
                const toLineNumber = Math.min(stopLineNumber, ctx.rendLineNumberStart - 1);
                if (fromLineNumber <= toLineNumber) {
                    this._insertLinesBefore(ctx, fromLineNumber, toLineNumber, deltaTop, startLineNumber);
                    ctx.linesLength += toLineNumber - fromLineNumber + 1;
                }
            }
            else if (ctx.rendLineNumberStart < startLineNumber) {
                // Remove lines before
                const removeCnt = Math.min(ctx.linesLength, startLineNumber - ctx.rendLineNumberStart);
                if (removeCnt > 0) {
                    this._removeLinesBefore(ctx, removeCnt);
                    ctx.linesLength -= removeCnt;
                }
            }
            ctx.rendLineNumberStart = startLineNumber;
            if (ctx.rendLineNumberStart + ctx.linesLength - 1 < stopLineNumber) {
                // Insert lines after
                const fromLineNumber = ctx.rendLineNumberStart + ctx.linesLength;
                const toLineNumber = stopLineNumber;
                if (fromLineNumber <= toLineNumber) {
                    this._insertLinesAfter(ctx, fromLineNumber, toLineNumber, deltaTop, startLineNumber);
                    ctx.linesLength += toLineNumber - fromLineNumber + 1;
                }
            }
            else if (ctx.rendLineNumberStart + ctx.linesLength - 1 > stopLineNumber) {
                // Remove lines after
                const fromLineNumber = Math.max(0, stopLineNumber - ctx.rendLineNumberStart + 1);
                const toLineNumber = ctx.linesLength - 1;
                const removeCnt = toLineNumber - fromLineNumber + 1;
                if (removeCnt > 0) {
                    this._removeLinesAfter(ctx, removeCnt);
                    ctx.linesLength -= removeCnt;
                }
            }
            this._finishRendering(ctx, false, deltaTop);
            return ctx;
        }
        _renderUntouchedLines(ctx, startIndex, endIndex, deltaTop, deltaLN) {
            const rendLineNumberStart = ctx.rendLineNumberStart;
            const lines = ctx.lines;
            for (let i = startIndex; i <= endIndex; i++) {
                const lineNumber = rendLineNumberStart + i;
                lines[i].layoutLine(lineNumber, deltaTop[lineNumber - deltaLN], this._viewportData.lineHeight);
            }
        }
        _insertLinesBefore(ctx, fromLineNumber, toLineNumber, deltaTop, deltaLN) {
            const newLines = [];
            let newLinesLen = 0;
            for (let lineNumber = fromLineNumber; lineNumber <= toLineNumber; lineNumber++) {
                newLines[newLinesLen++] = this._lineFactory.createLine();
            }
            ctx.lines = newLines.concat(ctx.lines);
        }
        _removeLinesBefore(ctx, removeCount) {
            for (let i = 0; i < removeCount; i++) {
                const lineDomNode = ctx.lines[i].getDomNode();
                lineDomNode?.remove();
            }
            ctx.lines.splice(0, removeCount);
        }
        _insertLinesAfter(ctx, fromLineNumber, toLineNumber, deltaTop, deltaLN) {
            const newLines = [];
            let newLinesLen = 0;
            for (let lineNumber = fromLineNumber; lineNumber <= toLineNumber; lineNumber++) {
                newLines[newLinesLen++] = this._lineFactory.createLine();
            }
            ctx.lines = ctx.lines.concat(newLines);
        }
        _removeLinesAfter(ctx, removeCount) {
            const removeIndex = ctx.linesLength - removeCount;
            for (let i = 0; i < removeCount; i++) {
                const lineDomNode = ctx.lines[removeIndex + i].getDomNode();
                lineDomNode?.remove();
            }
            ctx.lines.splice(removeIndex, removeCount);
        }
        _finishRenderingNewLines(ctx, domNodeIsEmpty, newLinesHTML, wasNew) {
            if (ViewLayerRenderer._ttPolicy) {
                newLinesHTML = ViewLayerRenderer._ttPolicy.createHTML(newLinesHTML);
            }
            const lastChild = this._domNode.lastChild;
            if (domNodeIsEmpty || !lastChild) {
                this._domNode.innerHTML = newLinesHTML; // explains the ugly casts -> https://github.com/microsoft/vscode/issues/106396#issuecomment-692625393;
            }
            else {
                lastChild.insertAdjacentHTML('afterend', newLinesHTML);
            }
            let currChild = this._domNode.lastChild;
            for (let i = ctx.linesLength - 1; i >= 0; i--) {
                const line = ctx.lines[i];
                if (wasNew[i]) {
                    line.setDomNode(currChild);
                    currChild = currChild.previousSibling;
                }
            }
        }
        _finishRenderingInvalidLines(ctx, invalidLinesHTML, wasInvalid) {
            const hugeDomNode = document.createElement('div');
            if (ViewLayerRenderer._ttPolicy) {
                invalidLinesHTML = ViewLayerRenderer._ttPolicy.createHTML(invalidLinesHTML);
            }
            hugeDomNode.innerHTML = invalidLinesHTML;
            for (let i = 0; i < ctx.linesLength; i++) {
                const line = ctx.lines[i];
                if (wasInvalid[i]) {
                    const source = hugeDomNode.firstChild;
                    const lineDomNode = line.getDomNode();
                    lineDomNode.parentNode.replaceChild(source, lineDomNode);
                    line.setDomNode(source);
                }
            }
        }
        static { this._sb = new stringBuilder_1.StringBuilder(100000); }
        _finishRendering(ctx, domNodeIsEmpty, deltaTop) {
            const sb = ViewLayerRenderer._sb;
            const linesLength = ctx.linesLength;
            const lines = ctx.lines;
            const rendLineNumberStart = ctx.rendLineNumberStart;
            const wasNew = [];
            {
                sb.reset();
                let hadNewLine = false;
                for (let i = 0; i < linesLength; i++) {
                    const line = lines[i];
                    wasNew[i] = false;
                    const lineDomNode = line.getDomNode();
                    if (lineDomNode) {
                        // line is not new
                        continue;
                    }
                    const renderResult = line.renderLine(i + rendLineNumberStart, deltaTop[i], this._viewportData.lineHeight, this._viewportData, sb);
                    if (!renderResult) {
                        // line does not need rendering
                        continue;
                    }
                    wasNew[i] = true;
                    hadNewLine = true;
                }
                if (hadNewLine) {
                    this._finishRenderingNewLines(ctx, domNodeIsEmpty, sb.build(), wasNew);
                }
            }
            {
                sb.reset();
                let hadInvalidLine = false;
                const wasInvalid = [];
                for (let i = 0; i < linesLength; i++) {
                    const line = lines[i];
                    wasInvalid[i] = false;
                    if (wasNew[i]) {
                        // line was new
                        continue;
                    }
                    const renderResult = line.renderLine(i + rendLineNumberStart, deltaTop[i], this._viewportData.lineHeight, this._viewportData, sb);
                    if (!renderResult) {
                        // line does not need rendering
                        continue;
                    }
                    wasInvalid[i] = true;
                    hadInvalidLine = true;
                }
                if (hadInvalidLine) {
                    this._finishRenderingInvalidLines(ctx, sb.build(), wasInvalid);
                }
            }
        }
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[657/*vs/editor/browser/view/viewOverlays*/], __M([1/*require*/,0/*exports*/,39/*vs/base/browser/fastDomNode*/,74/*vs/editor/browser/config/domFontInfo*/,262/*vs/editor/browser/view/viewLayer*/,56/*vs/editor/browser/view/viewPart*/]), function (require, exports, fastDomNode_1, domFontInfo_1, viewLayer_1, viewPart_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MarginViewOverlays = exports.ContentViewOverlays = exports.ViewOverlayLine = exports.ViewOverlays = void 0;
    class ViewOverlays extends viewPart_1.ViewPart {
        constructor(context) {
            super(context);
            this._dynamicOverlays = [];
            this._isFocused = false;
            this._visibleLines = new viewLayer_1.VisibleLinesCollection({
                createLine: () => new ViewOverlayLine(this._dynamicOverlays)
            });
            this.domNode = this._visibleLines.domNode;
            const options = this._context.configuration.options;
            const fontInfo = options.get(50 /* EditorOption.fontInfo */);
            (0, domFontInfo_1.applyFontInfo)(this.domNode, fontInfo);
            this.domNode.setClassName('view-overlays');
        }
        shouldRender() {
            if (super.shouldRender()) {
                return true;
            }
            for (let i = 0, len = this._dynamicOverlays.length; i < len; i++) {
                const dynamicOverlay = this._dynamicOverlays[i];
                if (dynamicOverlay.shouldRender()) {
                    return true;
                }
            }
            return false;
        }
        dispose() {
            super.dispose();
            for (let i = 0, len = this._dynamicOverlays.length; i < len; i++) {
                const dynamicOverlay = this._dynamicOverlays[i];
                dynamicOverlay.dispose();
            }
            this._dynamicOverlays = [];
        }
        getDomNode() {
            return this.domNode;
        }
        addDynamicOverlay(overlay) {
            this._dynamicOverlays.push(overlay);
        }
        // ----- event handlers
        onConfigurationChanged(e) {
            this._visibleLines.onConfigurationChanged(e);
            const options = this._context.configuration.options;
            const fontInfo = options.get(50 /* EditorOption.fontInfo */);
            (0, domFontInfo_1.applyFontInfo)(this.domNode, fontInfo);
            return true;
        }
        onFlushed(e) {
            return this._visibleLines.onFlushed(e);
        }
        onFocusChanged(e) {
            this._isFocused = e.isFocused;
            return true;
        }
        onLinesChanged(e) {
            return this._visibleLines.onLinesChanged(e);
        }
        onLinesDeleted(e) {
            return this._visibleLines.onLinesDeleted(e);
        }
        onLinesInserted(e) {
            return this._visibleLines.onLinesInserted(e);
        }
        onScrollChanged(e) {
            return this._visibleLines.onScrollChanged(e) || true;
        }
        onTokensChanged(e) {
            return this._visibleLines.onTokensChanged(e);
        }
        onZonesChanged(e) {
            return this._visibleLines.onZonesChanged(e);
        }
        // ----- end event handlers
        prepareRender(ctx) {
            const toRender = this._dynamicOverlays.filter(overlay => overlay.shouldRender());
            for (let i = 0, len = toRender.length; i < len; i++) {
                const dynamicOverlay = toRender[i];
                dynamicOverlay.prepareRender(ctx);
                dynamicOverlay.onDidRender();
            }
        }
        render(ctx) {
            // Overwriting to bypass `shouldRender` flag
            this._viewOverlaysRender(ctx);
            this.domNode.toggleClassName('focused', this._isFocused);
        }
        _viewOverlaysRender(ctx) {
            this._visibleLines.renderLines(ctx.viewportData);
        }
    }
    exports.ViewOverlays = ViewOverlays;
    class ViewOverlayLine {
        constructor(dynamicOverlays) {
            this._dynamicOverlays = dynamicOverlays;
            this._domNode = null;
            this._renderedContent = null;
        }
        getDomNode() {
            if (!this._domNode) {
                return null;
            }
            return this._domNode.domNode;
        }
        setDomNode(domNode) {
            this._domNode = (0, fastDomNode_1.createFastDomNode)(domNode);
        }
        onContentChanged() {
            // Nothing
        }
        onTokensChanged() {
            // Nothing
        }
        renderLine(lineNumber, deltaTop, lineHeight, viewportData, sb) {
            let result = '';
            for (let i = 0, len = this._dynamicOverlays.length; i < len; i++) {
                const dynamicOverlay = this._dynamicOverlays[i];
                result += dynamicOverlay.render(viewportData.startLineNumber, lineNumber);
            }
            if (this._renderedContent === result) {
                // No rendering needed
                return false;
            }
            this._renderedContent = result;
            sb.appendString('<div style="top:');
            sb.appendString(String(deltaTop));
            sb.appendString('px;height:');
            sb.appendString(String(lineHeight));
            sb.appendString('px;">');
            sb.appendString(result);
            sb.appendString('</div>');
            return true;
        }
        layoutLine(lineNumber, deltaTop, lineHeight) {
            if (this._domNode) {
                this._domNode.setTop(deltaTop);
                this._domNode.setHeight(lineHeight);
            }
        }
    }
    exports.ViewOverlayLine = ViewOverlayLine;
    class ContentViewOverlays extends ViewOverlays {
        constructor(context) {
            super(context);
            const options = this._context.configuration.options;
            const layoutInfo = options.get(146 /* EditorOption.layoutInfo */);
            this._contentWidth = layoutInfo.contentWidth;
            this.domNode.setHeight(0);
        }
        // --- begin event handlers
        onConfigurationChanged(e) {
            const options = this._context.configuration.options;
            const layoutInfo = options.get(146 /* EditorOption.layoutInfo */);
            this._contentWidth = layoutInfo.contentWidth;
            return super.onConfigurationChanged(e) || true;
        }
        onScrollChanged(e) {
            return super.onScrollChanged(e) || e.scrollWidthChanged;
        }
        // --- end event handlers
        _viewOverlaysRender(ctx) {
            super._viewOverlaysRender(ctx);
            this.domNode.setWidth(Math.max(ctx.scrollWidth, this._contentWidth));
        }
    }
    exports.ContentViewOverlays = ContentViewOverlays;
    class MarginViewOverlays extends ViewOverlays {
        constructor(context) {
            super(context);
            const options = this._context.configuration.options;
            const layoutInfo = options.get(146 /* EditorOption.layoutInfo */);
            this._contentLeft = layoutInfo.contentLeft;
            this.domNode.setClassName('margin-view-overlays');
            this.domNode.setWidth(1);
            (0, domFontInfo_1.applyFontInfo)(this.domNode, options.get(50 /* EditorOption.fontInfo */));
        }
        onConfigurationChanged(e) {
            const options = this._context.configuration.options;
            (0, domFontInfo_1.applyFontInfo)(this.domNode, options.get(50 /* EditorOption.fontInfo */));
            const layoutInfo = options.get(146 /* EditorOption.layoutInfo */);
            this._contentLeft = layoutInfo.contentLeft;
            return super.onConfigurationChanged(e) || true;
        }
        onScrollChanged(e) {
            return super.onScrollChanged(e) || e.scrollHeightChanged;
        }
        _viewOverlaysRender(ctx) {
            super._viewOverlaysRender(ctx);
            const height = Math.min(ctx.scrollHeight, 1000000);
            this.domNode.setHeight(height);
            this.domNode.setWidth(this._contentLeft);
        }
    }
    exports.MarginViewOverlays = MarginViewOverlays;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[367/*vs/editor/common/core/textChange*/], __M([1/*require*/,0/*exports*/,160/*vs/base/common/buffer*/,116/*vs/editor/common/core/stringBuilder*/]), function (require, exports, buffer, stringBuilder_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.TextChange = void 0;
    exports.compressConsecutiveTextChanges = compressConsecutiveTextChanges;
    function escapeNewLine(str) {
        return (str
            .replace(/\n/g, '\\n')
            .replace(/\r/g, '\\r'));
    }
    class TextChange {
        get oldLength() {
            return this.oldText.length;
        }
        get oldEnd() {
            return this.oldPosition + this.oldText.length;
        }
        get newLength() {
            return this.newText.length;
        }
        get newEnd() {
            return this.newPosition + this.newText.length;
        }
        constructor(oldPosition, oldText, newPosition, newText) {
            this.oldPosition = oldPosition;
            this.oldText = oldText;
            this.newPosition = newPosition;
            this.newText = newText;
        }
        toString() {
            if (this.oldText.length === 0) {
                return `(insert@${this.oldPosition} "${escapeNewLine(this.newText)}")`;
            }
            if (this.newText.length === 0) {
                return `(delete@${this.oldPosition} "${escapeNewLine(this.oldText)}")`;
            }
            return `(replace@${this.oldPosition} "${escapeNewLine(this.oldText)}" with "${escapeNewLine(this.newText)}")`;
        }
        static _writeStringSize(str) {
            return (4 + 2 * str.length);
        }
        static _writeString(b, str, offset) {
            const len = str.length;
            buffer.writeUInt32BE(b, len, offset);
            offset += 4;
            for (let i = 0; i < len; i++) {
                buffer.writeUInt16LE(b, str.charCodeAt(i), offset);
                offset += 2;
            }
            return offset;
        }
        static _readString(b, offset) {
            const len = buffer.readUInt32BE(b, offset);
            offset += 4;
            return (0, stringBuilder_1.decodeUTF16LE)(b, offset, len);
        }
        writeSize() {
            return (+4 // oldPosition
                + 4 // newPosition
                + TextChange._writeStringSize(this.oldText)
                + TextChange._writeStringSize(this.newText));
        }
        write(b, offset) {
            buffer.writeUInt32BE(b, this.oldPosition, offset);
            offset += 4;
            buffer.writeUInt32BE(b, this.newPosition, offset);
            offset += 4;
            offset = TextChange._writeString(b, this.oldText, offset);
            offset = TextChange._writeString(b, this.newText, offset);
            return offset;
        }
        static read(b, offset, dest) {
            const oldPosition = buffer.readUInt32BE(b, offset);
            offset += 4;
            const newPosition = buffer.readUInt32BE(b, offset);
            offset += 4;
            const oldText = TextChange._readString(b, offset);
            offset += TextChange._writeStringSize(oldText);
            const newText = TextChange._readString(b, offset);
            offset += TextChange._writeStringSize(newText);
            dest.push(new TextChange(oldPosition, oldText, newPosition, newText));
            return offset;
        }
    }
    exports.TextChange = TextChange;
    function compressConsecutiveTextChanges(prevEdits, currEdits) {
        if (prevEdits === null || prevEdits.length === 0) {
            return currEdits;
        }
        const compressor = new TextChangeCompressor(prevEdits, currEdits);
        return compressor.compress();
    }
    class TextChangeCompressor {
        constructor(prevEdits, currEdits) {
            this._prevEdits = prevEdits;
            this._currEdits = currEdits;
            this._result = [];
            this._resultLen = 0;
            this._prevLen = this._prevEdits.length;
            this._prevDeltaOffset = 0;
            this._currLen = this._currEdits.length;
            this._currDeltaOffset = 0;
        }
        compress() {
            let prevIndex = 0;
            let currIndex = 0;
            let prevEdit = this._getPrev(prevIndex);
            let currEdit = this._getCurr(currIndex);
            while (prevIndex < this._prevLen || currIndex < this._currLen) {
                if (prevEdit === null) {
                    this._acceptCurr(currEdit);
                    currEdit = this._getCurr(++currIndex);
                    continue;
                }
                if (currEdit === null) {
                    this._acceptPrev(prevEdit);
                    prevEdit = this._getPrev(++prevIndex);
                    continue;
                }
                if (currEdit.oldEnd <= prevEdit.newPosition) {
                    this._acceptCurr(currEdit);
                    currEdit = this._getCurr(++currIndex);
                    continue;
                }
                if (prevEdit.newEnd <= currEdit.oldPosition) {
                    this._acceptPrev(prevEdit);
                    prevEdit = this._getPrev(++prevIndex);
                    continue;
                }
                if (currEdit.oldPosition < prevEdit.newPosition) {
                    const [e1, e2] = TextChangeCompressor._splitCurr(currEdit, prevEdit.newPosition - currEdit.oldPosition);
                    this._acceptCurr(e1);
                    currEdit = e2;
                    continue;
                }
                if (prevEdit.newPosition < currEdit.oldPosition) {
                    const [e1, e2] = TextChangeCompressor._splitPrev(prevEdit, currEdit.oldPosition - prevEdit.newPosition);
                    this._acceptPrev(e1);
                    prevEdit = e2;
                    continue;
                }
                // At this point, currEdit.oldPosition === prevEdit.newPosition
                let mergePrev;
                let mergeCurr;
                if (currEdit.oldEnd === prevEdit.newEnd) {
                    mergePrev = prevEdit;
                    mergeCurr = currEdit;
                    prevEdit = this._getPrev(++prevIndex);
                    currEdit = this._getCurr(++currIndex);
                }
                else if (currEdit.oldEnd < prevEdit.newEnd) {
                    const [e1, e2] = TextChangeCompressor._splitPrev(prevEdit, currEdit.oldLength);
                    mergePrev = e1;
                    mergeCurr = currEdit;
                    prevEdit = e2;
                    currEdit = this._getCurr(++currIndex);
                }
                else {
                    const [e1, e2] = TextChangeCompressor._splitCurr(currEdit, prevEdit.newLength);
                    mergePrev = prevEdit;
                    mergeCurr = e1;
                    prevEdit = this._getPrev(++prevIndex);
                    currEdit = e2;
                }
                this._result[this._resultLen++] = new TextChange(mergePrev.oldPosition, mergePrev.oldText, mergeCurr.newPosition, mergeCurr.newText);
                this._prevDeltaOffset += mergePrev.newLength - mergePrev.oldLength;
                this._currDeltaOffset += mergeCurr.newLength - mergeCurr.oldLength;
            }
            const merged = TextChangeCompressor._merge(this._result);
            const cleaned = TextChangeCompressor._removeNoOps(merged);
            return cleaned;
        }
        _acceptCurr(currEdit) {
            this._result[this._resultLen++] = TextChangeCompressor._rebaseCurr(this._prevDeltaOffset, currEdit);
            this._currDeltaOffset += currEdit.newLength - currEdit.oldLength;
        }
        _getCurr(currIndex) {
            return (currIndex < this._currLen ? this._currEdits[currIndex] : null);
        }
        _acceptPrev(prevEdit) {
            this._result[this._resultLen++] = TextChangeCompressor._rebasePrev(this._currDeltaOffset, prevEdit);
            this._prevDeltaOffset += prevEdit.newLength - prevEdit.oldLength;
        }
        _getPrev(prevIndex) {
            return (prevIndex < this._prevLen ? this._prevEdits[prevIndex] : null);
        }
        static _rebaseCurr(prevDeltaOffset, currEdit) {
            return new TextChange(currEdit.oldPosition - prevDeltaOffset, currEdit.oldText, currEdit.newPosition, currEdit.newText);
        }
        static _rebasePrev(currDeltaOffset, prevEdit) {
            return new TextChange(prevEdit.oldPosition, prevEdit.oldText, prevEdit.newPosition + currDeltaOffset, prevEdit.newText);
        }
        static _splitPrev(edit, offset) {
            const preText = edit.newText.substr(0, offset);
            const postText = edit.newText.substr(offset);
            return [
                new TextChange(edit.oldPosition, edit.oldText, edit.newPosition, preText),
                new TextChange(edit.oldEnd, '', edit.newPosition + offset, postText)
            ];
        }
        static _splitCurr(edit, offset) {
            const preText = edit.oldText.substr(0, offset);
            const postText = edit.oldText.substr(offset);
            return [
                new TextChange(edit.oldPosition, preText, edit.newPosition, edit.newText),
                new TextChange(edit.oldPosition + offset, postText, edit.newEnd, '')
            ];
        }
        static _merge(edits) {
            if (edits.length === 0) {
                return edits;
            }
            const result = [];
            let resultLen = 0;
            let prev = edits[0];
            for (let i = 1; i < edits.length; i++) {
                const curr = edits[i];
                if (prev.oldEnd === curr.oldPosition) {
                    // Merge into `prev`
                    prev = new TextChange(prev.oldPosition, prev.oldText + curr.oldText, prev.newPosition, prev.newText + curr.newText);
                }
                else {
                    result[resultLen++] = prev;
                    prev = curr;
                }
            }
            result[resultLen++] = prev;
            return result;
        }
        static _removeNoOps(edits) {
            if (edits.length === 0) {
                return edits;
            }
            const result = [];
            let resultLen = 0;
            for (let i = 0; i < edits.length; i++) {
                const edit = edits[i];
                if (edit.oldText === edit.newText) {
                    continue;
                }
                result[resultLen++] = edit;
            }
            return result;
        }
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[368/*vs/editor/common/languageSelector*/], __M([1/*require*/,0/*exports*/,350/*vs/base/common/glob*/,99/*vs/base/common/path*/]), function (require, exports, glob_1, path_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.score = score;
    function score(selector, candidateUri, candidateLanguage, candidateIsSynchronized, candidateNotebookUri, candidateNotebookType) {
        if (Array.isArray(selector)) {
            // array -> take max individual value
            let ret = 0;
            for (const filter of selector) {
                const value = score(filter, candidateUri, candidateLanguage, candidateIsSynchronized, candidateNotebookUri, candidateNotebookType);
                if (value === 10) {
                    return value; // already at the highest
                }
                if (value > ret) {
                    ret = value;
                }
            }
            return ret;
        }
        else if (typeof selector === 'string') {
            if (!candidateIsSynchronized) {
                return 0;
            }
            // short-hand notion, desugars to
            // 'fooLang' -> { language: 'fooLang'}
            // '*' -> { language: '*' }
            if (selector === '*') {
                return 5;
            }
            else if (selector === candidateLanguage) {
                return 10;
            }
            else {
                return 0;
            }
        }
        else if (selector) {
            // filter -> select accordingly, use defaults for scheme
            const { language, pattern, scheme, hasAccessToAllModels, notebookType } = selector; // TODO: microsoft/TypeScript#42768
            if (!candidateIsSynchronized && !hasAccessToAllModels) {
                return 0;
            }
            // selector targets a notebook -> use the notebook uri instead
            // of the "normal" document uri.
            if (notebookType && candidateNotebookUri) {
                candidateUri = candidateNotebookUri;
            }
            let ret = 0;
            if (scheme) {
                if (scheme === candidateUri.scheme) {
                    ret = 10;
                }
                else if (scheme === '*') {
                    ret = 5;
                }
                else {
                    return 0;
                }
            }
            if (language) {
                if (language === candidateLanguage) {
                    ret = 10;
                }
                else if (language === '*') {
                    ret = Math.max(ret, 5);
                }
                else {
                    return 0;
                }
            }
            if (notebookType) {
                if (notebookType === candidateNotebookType) {
                    ret = 10;
                }
                else if (notebookType === '*' && candidateNotebookType !== undefined) {
                    ret = Math.max(ret, 5);
                }
                else {
                    return 0;
                }
            }
            if (pattern) {
                let normalizedPattern;
                if (typeof pattern === 'string') {
                    normalizedPattern = pattern;
                }
                else {
                    // Since this pattern has a `base` property, we need
                    // to normalize this path first before passing it on
                    // because we will compare it against `Uri.fsPath`
                    // which uses platform specific separators.
                    // Refs: https://github.com/microsoft/vscode/issues/99938
                    normalizedPattern = { ...pattern, base: (0, path_1.normalize)(pattern.base) };
                }
                if (normalizedPattern === candidateUri.fsPath || (0, glob_1.match)(normalizedPattern, candidateUri.fsPath)) {
                    ret = 10;
                }
                else {
                    return 0;
                }
            }
            return ret;
        }
        else {
            return 0;
        }
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[658/*vs/editor/common/languageFeatureRegistry*/], __M([1/*require*/,0/*exports*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,40/*vs/editor/common/model*/,368/*vs/editor/common/languageSelector*/]), function (require, exports, event_1, lifecycle_1, model_1, languageSelector_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.LanguageFeatureRegistry = void 0;
    function isExclusive(selector) {
        if (typeof selector === 'string') {
            return false;
        }
        else if (Array.isArray(selector)) {
            return selector.every(isExclusive);
        }
        else {
            return !!selector.exclusive; // TODO: microsoft/TypeScript#42768
        }
    }
    class MatchCandidate {
        constructor(uri, languageId, notebookUri, notebookType, recursive) {
            this.uri = uri;
            this.languageId = languageId;
            this.notebookUri = notebookUri;
            this.notebookType = notebookType;
            this.recursive = recursive;
        }
        equals(other) {
            return this.notebookType === other.notebookType
                && this.languageId === other.languageId
                && this.uri.toString() === other.uri.toString()
                && this.notebookUri?.toString() === other.notebookUri?.toString()
                && this.recursive === other.recursive;
        }
    }
    class LanguageFeatureRegistry {
        constructor(_notebookInfoResolver) {
            this._notebookInfoResolver = _notebookInfoResolver;
            this._clock = 0;
            this._entries = [];
            this._onDidChange = new event_1.Emitter();
            this.onDidChange = this._onDidChange.event;
        }
        register(selector, provider) {
            let entry = {
                selector,
                provider,
                _score: -1,
                _time: this._clock++
            };
            this._entries.push(entry);
            this._lastCandidate = undefined;
            this._onDidChange.fire(this._entries.length);
            return (0, lifecycle_1.toDisposable)(() => {
                if (entry) {
                    const idx = this._entries.indexOf(entry);
                    if (idx >= 0) {
                        this._entries.splice(idx, 1);
                        this._lastCandidate = undefined;
                        this._onDidChange.fire(this._entries.length);
                        entry = undefined;
                    }
                }
            });
        }
        has(model) {
            return this.all(model).length > 0;
        }
        all(model) {
            if (!model) {
                return [];
            }
            this._updateScores(model, false);
            const result = [];
            // from registry
            for (const entry of this._entries) {
                if (entry._score > 0) {
                    result.push(entry.provider);
                }
            }
            return result;
        }
        ordered(model, recursive = false) {
            const result = [];
            this._orderedForEach(model, recursive, entry => result.push(entry.provider));
            return result;
        }
        orderedGroups(model) {
            const result = [];
            let lastBucket;
            let lastBucketScore;
            this._orderedForEach(model, false, entry => {
                if (lastBucket && lastBucketScore === entry._score) {
                    lastBucket.push(entry.provider);
                }
                else {
                    lastBucketScore = entry._score;
                    lastBucket = [entry.provider];
                    result.push(lastBucket);
                }
            });
            return result;
        }
        _orderedForEach(model, recursive, callback) {
            this._updateScores(model, recursive);
            for (const entry of this._entries) {
                if (entry._score > 0) {
                    callback(entry);
                }
            }
        }
        _updateScores(model, recursive) {
            const notebookInfo = this._notebookInfoResolver?.(model.uri);
            // use the uri (scheme, pattern) of the notebook info iff we have one
            // otherwise it's the model's/document's uri
            const candidate = notebookInfo
                ? new MatchCandidate(model.uri, model.getLanguageId(), notebookInfo.uri, notebookInfo.type, recursive)
                : new MatchCandidate(model.uri, model.getLanguageId(), undefined, undefined, recursive);
            if (this._lastCandidate?.equals(candidate)) {
                // nothing has changed
                return;
            }
            this._lastCandidate = candidate;
            for (const entry of this._entries) {
                entry._score = (0, languageSelector_1.score)(entry.selector, candidate.uri, candidate.languageId, (0, model_1.shouldSynchronizeModel)(model), candidate.notebookUri, candidate.notebookType);
                if (isExclusive(entry.selector) && entry._score > 0) {
                    if (recursive) {
                        entry._score = 0;
                    }
                    else {
                        // support for one exclusive selector that overwrites
                        // any other selector
                        for (const entry of this._entries) {
                            entry._score = 0;
                        }
                        entry._score = 1000;
                        break;
                    }
                }
            }
            // needs sorting
            this._entries.sort(LanguageFeatureRegistry._compareByScoreAndTime);
        }
        static _compareByScoreAndTime(a, b) {
            if (a._score < b._score) {
                return 1;
            }
            else if (a._score > b._score) {
                return -1;
            }
            // De-prioritize built-in providers
            if (isBuiltinSelector(a.selector) && !isBuiltinSelector(b.selector)) {
                return 1;
            }
            else if (!isBuiltinSelector(a.selector) && isBuiltinSelector(b.selector)) {
                return -1;
            }
            if (a._time < b._time) {
                return 1;
            }
            else if (a._time > b._time) {
                return -1;
            }
            else {
                return 0;
            }
        }
    }
    exports.LanguageFeatureRegistry = LanguageFeatureRegistry;
    function isBuiltinSelector(selector) {
        if (typeof selector === 'string') {
            return false;
        }
        if (Array.isArray(selector)) {
            return selector.some(isBuiltinSelector);
        }
        return Boolean(selector.isBuiltin);
    }
});

define(__m[27/*vs/editor/common/languages*/], __M([1/*require*/,0/*exports*/,26/*vs/base/common/codicons*/,22/*vs/base/common/uri*/,4/*vs/editor/common/core/range*/,585/*vs/editor/common/tokenizationRegistry*/,3/*vs/nls*/]), function (require, exports, codicons_1, uri_1, range_1, tokenizationRegistry_1, nls_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.InlineEditTriggerKind = exports.TreeSitterTokenizationRegistry = exports.TokenizationRegistry = exports.LazyTokenizationSupport = exports.InlayHintKind = exports.Command = exports.NewSymbolNameTriggerKind = exports.NewSymbolNameTag = exports.FoldingRangeKind = exports.TextEdit = exports.SymbolKinds = exports.symbolKindNames = exports.DocumentHighlightKind = exports.SignatureHelpTriggerKind = exports.DocumentPasteTriggerKind = exports.SelectedSuggestionInfo = exports.InlineCompletionTriggerKind = exports.CompletionItemKinds = exports.HoverVerbosityAction = exports.EncodedTokenizationResult = exports.TokenizationResult = exports.Token = void 0;
    exports.isLocationLink = isLocationLink;
    exports.getAriaLabelForSymbol = getAriaLabelForSymbol;
    class Token {
        constructor(offset, type, language) {
            this.offset = offset;
            this.type = type;
            this.language = language;
            this._tokenBrand = undefined;
        }
        toString() {
            return '(' + this.offset + ', ' + this.type + ')';
        }
    }
    exports.Token = Token;
    /**
     * @internal
     */
    class TokenizationResult {
        constructor(tokens, endState) {
            this.tokens = tokens;
            this.endState = endState;
            this._tokenizationResultBrand = undefined;
        }
    }
    exports.TokenizationResult = TokenizationResult;
    /**
     * @internal
     */
    class EncodedTokenizationResult {
        constructor(
        /**
         * The tokens in binary format. Each token occupies two array indices. For token i:
         *  - at offset 2*i => startIndex
         *  - at offset 2*i + 1 => metadata
         *
         */
        tokens, endState) {
            this.tokens = tokens;
            this.endState = endState;
            this._encodedTokenizationResultBrand = undefined;
        }
    }
    exports.EncodedTokenizationResult = EncodedTokenizationResult;
    var HoverVerbosityAction;
    (function (HoverVerbosityAction) {
        /**
         * Increase the verbosity of the hover
         */
        HoverVerbosityAction[HoverVerbosityAction["Increase"] = 0] = "Increase";
        /**
         * Decrease the verbosity of the hover
         */
        HoverVerbosityAction[HoverVerbosityAction["Decrease"] = 1] = "Decrease";
    })(HoverVerbosityAction || (exports.HoverVerbosityAction = HoverVerbosityAction = {}));
    /**
     * @internal
     */
    var CompletionItemKinds;
    (function (CompletionItemKinds) {
        const byKind = new Map();
        byKind.set(0 /* CompletionItemKind.Method */, codicons_1.Codicon.symbolMethod);
        byKind.set(1 /* CompletionItemKind.Function */, codicons_1.Codicon.symbolFunction);
        byKind.set(2 /* CompletionItemKind.Constructor */, codicons_1.Codicon.symbolConstructor);
        byKind.set(3 /* CompletionItemKind.Field */, codicons_1.Codicon.symbolField);
        byKind.set(4 /* CompletionItemKind.Variable */, codicons_1.Codicon.symbolVariable);
        byKind.set(5 /* CompletionItemKind.Class */, codicons_1.Codicon.symbolClass);
        byKind.set(6 /* CompletionItemKind.Struct */, codicons_1.Codicon.symbolStruct);
        byKind.set(7 /* CompletionItemKind.Interface */, codicons_1.Codicon.symbolInterface);
        byKind.set(8 /* CompletionItemKind.Module */, codicons_1.Codicon.symbolModule);
        byKind.set(9 /* CompletionItemKind.Property */, codicons_1.Codicon.symbolProperty);
        byKind.set(10 /* CompletionItemKind.Event */, codicons_1.Codicon.symbolEvent);
        byKind.set(11 /* CompletionItemKind.Operator */, codicons_1.Codicon.symbolOperator);
        byKind.set(12 /* CompletionItemKind.Unit */, codicons_1.Codicon.symbolUnit);
        byKind.set(13 /* CompletionItemKind.Value */, codicons_1.Codicon.symbolValue);
        byKind.set(15 /* CompletionItemKind.Enum */, codicons_1.Codicon.symbolEnum);
        byKind.set(14 /* CompletionItemKind.Constant */, codicons_1.Codicon.symbolConstant);
        byKind.set(15 /* CompletionItemKind.Enum */, codicons_1.Codicon.symbolEnum);
        byKind.set(16 /* CompletionItemKind.EnumMember */, codicons_1.Codicon.symbolEnumMember);
        byKind.set(17 /* CompletionItemKind.Keyword */, codicons_1.Codicon.symbolKeyword);
        byKind.set(27 /* CompletionItemKind.Snippet */, codicons_1.Codicon.symbolSnippet);
        byKind.set(18 /* CompletionItemKind.Text */, codicons_1.Codicon.symbolText);
        byKind.set(19 /* CompletionItemKind.Color */, codicons_1.Codicon.symbolColor);
        byKind.set(20 /* CompletionItemKind.File */, codicons_1.Codicon.symbolFile);
        byKind.set(21 /* CompletionItemKind.Reference */, codicons_1.Codicon.symbolReference);
        byKind.set(22 /* CompletionItemKind.Customcolor */, codicons_1.Codicon.symbolCustomColor);
        byKind.set(23 /* CompletionItemKind.Folder */, codicons_1.Codicon.symbolFolder);
        byKind.set(24 /* CompletionItemKind.TypeParameter */, codicons_1.Codicon.symbolTypeParameter);
        byKind.set(25 /* CompletionItemKind.User */, codicons_1.Codicon.account);
        byKind.set(26 /* CompletionItemKind.Issue */, codicons_1.Codicon.issues);
        /**
         * @internal
         */
        function toIcon(kind) {
            let codicon = byKind.get(kind);
            if (!codicon) {
                console.info('No codicon found for CompletionItemKind ' + kind);
                codicon = codicons_1.Codicon.symbolProperty;
            }
            return codicon;
        }
        CompletionItemKinds.toIcon = toIcon;
        const data = new Map();
        data.set('method', 0 /* CompletionItemKind.Method */);
        data.set('function', 1 /* CompletionItemKind.Function */);
        data.set('constructor', 2 /* CompletionItemKind.Constructor */);
        data.set('field', 3 /* CompletionItemKind.Field */);
        data.set('variable', 4 /* CompletionItemKind.Variable */);
        data.set('class', 5 /* CompletionItemKind.Class */);
        data.set('struct', 6 /* CompletionItemKind.Struct */);
        data.set('interface', 7 /* CompletionItemKind.Interface */);
        data.set('module', 8 /* CompletionItemKind.Module */);
        data.set('property', 9 /* CompletionItemKind.Property */);
        data.set('event', 10 /* CompletionItemKind.Event */);
        data.set('operator', 11 /* CompletionItemKind.Operator */);
        data.set('unit', 12 /* CompletionItemKind.Unit */);
        data.set('value', 13 /* CompletionItemKind.Value */);
        data.set('constant', 14 /* CompletionItemKind.Constant */);
        data.set('enum', 15 /* CompletionItemKind.Enum */);
        data.set('enum-member', 16 /* CompletionItemKind.EnumMember */);
        data.set('enumMember', 16 /* CompletionItemKind.EnumMember */);
        data.set('keyword', 17 /* CompletionItemKind.Keyword */);
        data.set('snippet', 27 /* CompletionItemKind.Snippet */);
        data.set('text', 18 /* CompletionItemKind.Text */);
        data.set('color', 19 /* CompletionItemKind.Color */);
        data.set('file', 20 /* CompletionItemKind.File */);
        data.set('reference', 21 /* CompletionItemKind.Reference */);
        data.set('customcolor', 22 /* CompletionItemKind.Customcolor */);
        data.set('folder', 23 /* CompletionItemKind.Folder */);
        data.set('type-parameter', 24 /* CompletionItemKind.TypeParameter */);
        data.set('typeParameter', 24 /* CompletionItemKind.TypeParameter */);
        data.set('account', 25 /* CompletionItemKind.User */);
        data.set('issue', 26 /* CompletionItemKind.Issue */);
        /**
         * @internal
         */
        function fromString(value, strict) {
            let res = data.get(value);
            if (typeof res === 'undefined' && !strict) {
                res = 9 /* CompletionItemKind.Property */;
            }
            return res;
        }
        CompletionItemKinds.fromString = fromString;
    })(CompletionItemKinds || (exports.CompletionItemKinds = CompletionItemKinds = {}));
    /**
     * How an {@link InlineCompletionsProvider inline completion provider} was triggered.
     */
    var InlineCompletionTriggerKind;
    (function (InlineCompletionTriggerKind) {
        /**
         * Completion was triggered automatically while editing.
         * It is sufficient to return a single completion item in this case.
         */
        InlineCompletionTriggerKind[InlineCompletionTriggerKind["Automatic"] = 0] = "Automatic";
        /**
         * Completion was triggered explicitly by a user gesture.
         * Return multiple completion items to enable cycling through them.
         */
        InlineCompletionTriggerKind[InlineCompletionTriggerKind["Explicit"] = 1] = "Explicit";
    })(InlineCompletionTriggerKind || (exports.InlineCompletionTriggerKind = InlineCompletionTriggerKind = {}));
    class SelectedSuggestionInfo {
        constructor(range, text, completionKind, isSnippetText) {
            this.range = range;
            this.text = text;
            this.completionKind = completionKind;
            this.isSnippetText = isSnippetText;
        }
        equals(other) {
            return range_1.Range.lift(this.range).equalsRange(other.range)
                && this.text === other.text
                && this.completionKind === other.completionKind
                && this.isSnippetText === other.isSnippetText;
        }
    }
    exports.SelectedSuggestionInfo = SelectedSuggestionInfo;
    /**
     * @internal
     */
    var DocumentPasteTriggerKind;
    (function (DocumentPasteTriggerKind) {
        DocumentPasteTriggerKind[DocumentPasteTriggerKind["Automatic"] = 0] = "Automatic";
        DocumentPasteTriggerKind[DocumentPasteTriggerKind["PasteAs"] = 1] = "PasteAs";
    })(DocumentPasteTriggerKind || (exports.DocumentPasteTriggerKind = DocumentPasteTriggerKind = {}));
    var SignatureHelpTriggerKind;
    (function (SignatureHelpTriggerKind) {
        SignatureHelpTriggerKind[SignatureHelpTriggerKind["Invoke"] = 1] = "Invoke";
        SignatureHelpTriggerKind[SignatureHelpTriggerKind["TriggerCharacter"] = 2] = "TriggerCharacter";
        SignatureHelpTriggerKind[SignatureHelpTriggerKind["ContentChange"] = 3] = "ContentChange";
    })(SignatureHelpTriggerKind || (exports.SignatureHelpTriggerKind = SignatureHelpTriggerKind = {}));
    /**
     * A document highlight kind.
     */
    var DocumentHighlightKind;
    (function (DocumentHighlightKind) {
        /**
         * A textual occurrence.
         */
        DocumentHighlightKind[DocumentHighlightKind["Text"] = 0] = "Text";
        /**
         * Read-access of a symbol, like reading a variable.
         */
        DocumentHighlightKind[DocumentHighlightKind["Read"] = 1] = "Read";
        /**
         * Write-access of a symbol, like writing to a variable.
         */
        DocumentHighlightKind[DocumentHighlightKind["Write"] = 2] = "Write";
    })(DocumentHighlightKind || (exports.DocumentHighlightKind = DocumentHighlightKind = {}));
    /**
     * @internal
     */
    function isLocationLink(thing) {
        return thing
            && uri_1.URI.isUri(thing.uri)
            && range_1.Range.isIRange(thing.range)
            && (range_1.Range.isIRange(thing.originSelectionRange) || range_1.Range.isIRange(thing.targetSelectionRange));
    }
    /**
     * @internal
     */
    exports.symbolKindNames = {
        [17 /* SymbolKind.Array */]: (0, nls_1.localize)(669, "array"),
        [16 /* SymbolKind.Boolean */]: (0, nls_1.localize)(670, "boolean"),
        [4 /* SymbolKind.Class */]: (0, nls_1.localize)(671, "class"),
        [13 /* SymbolKind.Constant */]: (0, nls_1.localize)(672, "constant"),
        [8 /* SymbolKind.Constructor */]: (0, nls_1.localize)(673, "constructor"),
        [9 /* SymbolKind.Enum */]: (0, nls_1.localize)(674, "enumeration"),
        [21 /* SymbolKind.EnumMember */]: (0, nls_1.localize)(675, "enumeration member"),
        [23 /* SymbolKind.Event */]: (0, nls_1.localize)(676, "event"),
        [7 /* SymbolKind.Field */]: (0, nls_1.localize)(677, "field"),
        [0 /* SymbolKind.File */]: (0, nls_1.localize)(678, "file"),
        [11 /* SymbolKind.Function */]: (0, nls_1.localize)(679, "function"),
        [10 /* SymbolKind.Interface */]: (0, nls_1.localize)(680, "interface"),
        [19 /* SymbolKind.Key */]: (0, nls_1.localize)(681, "key"),
        [5 /* SymbolKind.Method */]: (0, nls_1.localize)(682, "method"),
        [1 /* SymbolKind.Module */]: (0, nls_1.localize)(683, "module"),
        [2 /* SymbolKind.Namespace */]: (0, nls_1.localize)(684, "namespace"),
        [20 /* SymbolKind.Null */]: (0, nls_1.localize)(685, "null"),
        [15 /* SymbolKind.Number */]: (0, nls_1.localize)(686, "number"),
        [18 /* SymbolKind.Object */]: (0, nls_1.localize)(687, "object"),
        [24 /* SymbolKind.Operator */]: (0, nls_1.localize)(688, "operator"),
        [3 /* SymbolKind.Package */]: (0, nls_1.localize)(689, "package"),
        [6 /* SymbolKind.Property */]: (0, nls_1.localize)(690, "property"),
        [14 /* SymbolKind.String */]: (0, nls_1.localize)(691, "string"),
        [22 /* SymbolKind.Struct */]: (0, nls_1.localize)(692, "struct"),
        [25 /* SymbolKind.TypeParameter */]: (0, nls_1.localize)(693, "type parameter"),
        [12 /* SymbolKind.Variable */]: (0, nls_1.localize)(694, "variable"),
    };
    /**
     * @internal
     */
    function getAriaLabelForSymbol(symbolName, kind) {
        return (0, nls_1.localize)(695, '{0} ({1})', symbolName, exports.symbolKindNames[kind]);
    }
    /**
     * @internal
     */
    var SymbolKinds;
    (function (SymbolKinds) {
        const byKind = new Map();
        byKind.set(0 /* SymbolKind.File */, codicons_1.Codicon.symbolFile);
        byKind.set(1 /* SymbolKind.Module */, codicons_1.Codicon.symbolModule);
        byKind.set(2 /* SymbolKind.Namespace */, codicons_1.Codicon.symbolNamespace);
        byKind.set(3 /* SymbolKind.Package */, codicons_1.Codicon.symbolPackage);
        byKind.set(4 /* SymbolKind.Class */, codicons_1.Codicon.symbolClass);
        byKind.set(5 /* SymbolKind.Method */, codicons_1.Codicon.symbolMethod);
        byKind.set(6 /* SymbolKind.Property */, codicons_1.Codicon.symbolProperty);
        byKind.set(7 /* SymbolKind.Field */, codicons_1.Codicon.symbolField);
        byKind.set(8 /* SymbolKind.Constructor */, codicons_1.Codicon.symbolConstructor);
        byKind.set(9 /* SymbolKind.Enum */, codicons_1.Codicon.symbolEnum);
        byKind.set(10 /* SymbolKind.Interface */, codicons_1.Codicon.symbolInterface);
        byKind.set(11 /* SymbolKind.Function */, codicons_1.Codicon.symbolFunction);
        byKind.set(12 /* SymbolKind.Variable */, codicons_1.Codicon.symbolVariable);
        byKind.set(13 /* SymbolKind.Constant */, codicons_1.Codicon.symbolConstant);
        byKind.set(14 /* SymbolKind.String */, codicons_1.Codicon.symbolString);
        byKind.set(15 /* SymbolKind.Number */, codicons_1.Codicon.symbolNumber);
        byKind.set(16 /* SymbolKind.Boolean */, codicons_1.Codicon.symbolBoolean);
        byKind.set(17 /* SymbolKind.Array */, codicons_1.Codicon.symbolArray);
        byKind.set(18 /* SymbolKind.Object */, codicons_1.Codicon.symbolObject);
        byKind.set(19 /* SymbolKind.Key */, codicons_1.Codicon.symbolKey);
        byKind.set(20 /* SymbolKind.Null */, codicons_1.Codicon.symbolNull);
        byKind.set(21 /* SymbolKind.EnumMember */, codicons_1.Codicon.symbolEnumMember);
        byKind.set(22 /* SymbolKind.Struct */, codicons_1.Codicon.symbolStruct);
        byKind.set(23 /* SymbolKind.Event */, codicons_1.Codicon.symbolEvent);
        byKind.set(24 /* SymbolKind.Operator */, codicons_1.Codicon.symbolOperator);
        byKind.set(25 /* SymbolKind.TypeParameter */, codicons_1.Codicon.symbolTypeParameter);
        /**
         * @internal
         */
        function toIcon(kind) {
            let icon = byKind.get(kind);
            if (!icon) {
                console.info('No codicon found for SymbolKind ' + kind);
                icon = codicons_1.Codicon.symbolProperty;
            }
            return icon;
        }
        SymbolKinds.toIcon = toIcon;
    })(SymbolKinds || (exports.SymbolKinds = SymbolKinds = {}));
    /** @internal */
    class TextEdit {
    }
    exports.TextEdit = TextEdit;
    class FoldingRangeKind {
        /**
         * Kind for folding range representing a comment. The value of the kind is 'comment'.
         */
        static { this.Comment = new FoldingRangeKind('comment'); }
        /**
         * Kind for folding range representing a import. The value of the kind is 'imports'.
         */
        static { this.Imports = new FoldingRangeKind('imports'); }
        /**
         * Kind for folding range representing regions (for example marked by `#region`, `#endregion`).
         * The value of the kind is 'region'.
         */
        static { this.Region = new FoldingRangeKind('region'); }
        /**
         * Returns a {@link FoldingRangeKind} for the given value.
         *
         * @param value of the kind.
         */
        static fromValue(value) {
            switch (value) {
                case 'comment': return FoldingRangeKind.Comment;
                case 'imports': return FoldingRangeKind.Imports;
                case 'region': return FoldingRangeKind.Region;
            }
            return new FoldingRangeKind(value);
        }
        /**
         * Creates a new {@link FoldingRangeKind}.
         *
         * @param value of the kind.
         */
        constructor(value) {
            this.value = value;
        }
    }
    exports.FoldingRangeKind = FoldingRangeKind;
    var NewSymbolNameTag;
    (function (NewSymbolNameTag) {
        NewSymbolNameTag[NewSymbolNameTag["AIGenerated"] = 1] = "AIGenerated";
    })(NewSymbolNameTag || (exports.NewSymbolNameTag = NewSymbolNameTag = {}));
    var NewSymbolNameTriggerKind;
    (function (NewSymbolNameTriggerKind) {
        NewSymbolNameTriggerKind[NewSymbolNameTriggerKind["Invoke"] = 0] = "Invoke";
        NewSymbolNameTriggerKind[NewSymbolNameTriggerKind["Automatic"] = 1] = "Automatic";
    })(NewSymbolNameTriggerKind || (exports.NewSymbolNameTriggerKind = NewSymbolNameTriggerKind = {}));
    /**
     * @internal
     */
    var Command;
    (function (Command) {
        /**
         * @internal
         */
        function is(obj) {
            if (!obj || typeof obj !== 'object') {
                return false;
            }
            return typeof obj.id === 'string' &&
                typeof obj.title === 'string';
        }
        Command.is = is;
    })(Command || (exports.Command = Command = {}));
    var InlayHintKind;
    (function (InlayHintKind) {
        InlayHintKind[InlayHintKind["Type"] = 1] = "Type";
        InlayHintKind[InlayHintKind["Parameter"] = 2] = "Parameter";
    })(InlayHintKind || (exports.InlayHintKind = InlayHintKind = {}));
    /**
     * @internal
     */
    class LazyTokenizationSupport {
        constructor(createSupport) {
            this.createSupport = createSupport;
            this._tokenizationSupport = null;
        }
        dispose() {
            if (this._tokenizationSupport) {
                this._tokenizationSupport.then((support) => {
                    if (support) {
                        support.dispose();
                    }
                });
            }
        }
        get tokenizationSupport() {
            if (!this._tokenizationSupport) {
                this._tokenizationSupport = this.createSupport();
            }
            return this._tokenizationSupport;
        }
    }
    exports.LazyTokenizationSupport = LazyTokenizationSupport;
    /**
     * @internal
     */
    exports.TokenizationRegistry = new tokenizationRegistry_1.TokenizationRegistry();
    /**
     * @internal
     */
    exports.TreeSitterTokenizationRegistry = new tokenizationRegistry_1.TokenizationRegistry();
    var InlineEditTriggerKind;
    (function (InlineEditTriggerKind) {
        InlineEditTriggerKind[InlineEditTriggerKind["Invoke"] = 0] = "Invoke";
        InlineEditTriggerKind[InlineEditTriggerKind["Automatic"] = 1] = "Automatic";
    })(InlineEditTriggerKind || (exports.InlineEditTriggerKind = InlineEditTriggerKind = {}));
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[177/*vs/editor/common/languages/nullTokenize*/], __M([1/*require*/,0/*exports*/,27/*vs/editor/common/languages*/]), function (require, exports, languages_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.NullState = void 0;
    exports.nullTokenize = nullTokenize;
    exports.nullTokenizeEncoded = nullTokenizeEncoded;
    exports.NullState = new class {
        clone() {
            return this;
        }
        equals(other) {
            return (this === other);
        }
    };
    function nullTokenize(languageId, state) {
        return new languages_1.TokenizationResult([new languages_1.Token(0, '', languageId)], state);
    }
    function nullTokenizeEncoded(languageId, state) {
        const tokens = new Uint32Array(2);
        tokens[0] = 0;
        tokens[1] = ((languageId << 0 /* MetadataConsts.LANGUAGEID_OFFSET */)
            | (0 /* StandardTokenType.Other */ << 8 /* MetadataConsts.TOKEN_TYPE_OFFSET */)
            | (0 /* FontStyle.None */ << 11 /* MetadataConsts.FONT_STYLE_OFFSET */)
            | (1 /* ColorId.DefaultForeground */ << 15 /* MetadataConsts.FOREGROUND_OFFSET */)
            | (2 /* ColorId.DefaultBackground */ << 24 /* MetadataConsts.BACKGROUND_OFFSET */)) >>> 0;
        return new languages_1.EncodedTokenizationResult(tokens, state === null ? exports.NullState : state);
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[208/*vs/editor/common/languages/supports/richEditBrackets*/], __M([1/*require*/,0/*exports*/,11/*vs/base/common/strings*/,116/*vs/editor/common/core/stringBuilder*/,4/*vs/editor/common/core/range*/]), function (require, exports, strings, stringBuilder, range_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.BracketsUtils = exports.RichEditBrackets = exports.RichEditBracket = void 0;
    exports.createBracketOrRegExp = createBracketOrRegExp;
    /**
     * Represents a grouping of colliding bracket pairs.
     *
     * Most of the times this contains a single bracket pair,
     * but sometimes this contains multiple bracket pairs in cases
     * where the same string appears as a closing bracket for multiple
     * bracket pairs, or the same string appears an opening bracket for
     * multiple bracket pairs.
     *
     * e.g. of a group containing a single pair:
     *   open: ['{'], close: ['}']
     *
     * e.g. of a group containing multiple pairs:
     *   open: ['if', 'for'], close: ['end', 'end']
     */
    class RichEditBracket {
        constructor(languageId, index, open, close, forwardRegex, reversedRegex) {
            this._richEditBracketBrand = undefined;
            this.languageId = languageId;
            this.index = index;
            this.open = open;
            this.close = close;
            this.forwardRegex = forwardRegex;
            this.reversedRegex = reversedRegex;
            this._openSet = RichEditBracket._toSet(this.open);
            this._closeSet = RichEditBracket._toSet(this.close);
        }
        /**
         * Check if the provided `text` is an open bracket in this group.
         */
        isOpen(text) {
            return this._openSet.has(text);
        }
        /**
         * Check if the provided `text` is a close bracket in this group.
         */
        isClose(text) {
            return this._closeSet.has(text);
        }
        static _toSet(arr) {
            const result = new Set();
            for (const element of arr) {
                result.add(element);
            }
            return result;
        }
    }
    exports.RichEditBracket = RichEditBracket;
    /**
     * Groups together brackets that have equal open or close sequences.
     *
     * For example, if the following brackets are defined:
     *   ['IF','END']
     *   ['for','end']
     *   ['{','}']
     *
     * Then the grouped brackets would be:
     *   { open: ['if', 'for'], close: ['end', 'end'] }
     *   { open: ['{'], close: ['}'] }
     *
     */
    function groupFuzzyBrackets(brackets) {
        const N = brackets.length;
        brackets = brackets.map(b => [b[0].toLowerCase(), b[1].toLowerCase()]);
        const group = [];
        for (let i = 0; i < N; i++) {
            group[i] = i;
        }
        const areOverlapping = (a, b) => {
            const [aOpen, aClose] = a;
            const [bOpen, bClose] = b;
            return (aOpen === bOpen || aOpen === bClose || aClose === bOpen || aClose === bClose);
        };
        const mergeGroups = (g1, g2) => {
            const newG = Math.min(g1, g2);
            const oldG = Math.max(g1, g2);
            for (let i = 0; i < N; i++) {
                if (group[i] === oldG) {
                    group[i] = newG;
                }
            }
        };
        // group together brackets that have the same open or the same close sequence
        for (let i = 0; i < N; i++) {
            const a = brackets[i];
            for (let j = i + 1; j < N; j++) {
                const b = brackets[j];
                if (areOverlapping(a, b)) {
                    mergeGroups(group[i], group[j]);
                }
            }
        }
        const result = [];
        for (let g = 0; g < N; g++) {
            const currentOpen = [];
            const currentClose = [];
            for (let i = 0; i < N; i++) {
                if (group[i] === g) {
                    const [open, close] = brackets[i];
                    currentOpen.push(open);
                    currentClose.push(close);
                }
            }
            if (currentOpen.length > 0) {
                result.push({
                    open: currentOpen,
                    close: currentClose
                });
            }
        }
        return result;
    }
    class RichEditBrackets {
        constructor(languageId, _brackets) {
            this._richEditBracketsBrand = undefined;
            const brackets = groupFuzzyBrackets(_brackets);
            this.brackets = brackets.map((b, index) => {
                return new RichEditBracket(languageId, index, b.open, b.close, getRegexForBracketPair(b.open, b.close, brackets, index), getReversedRegexForBracketPair(b.open, b.close, brackets, index));
            });
            this.forwardRegex = getRegexForBrackets(this.brackets);
            this.reversedRegex = getReversedRegexForBrackets(this.brackets);
            this.textIsBracket = {};
            this.textIsOpenBracket = {};
            this.maxBracketLength = 0;
            for (const bracket of this.brackets) {
                for (const open of bracket.open) {
                    this.textIsBracket[open] = bracket;
                    this.textIsOpenBracket[open] = true;
                    this.maxBracketLength = Math.max(this.maxBracketLength, open.length);
                }
                for (const close of bracket.close) {
                    this.textIsBracket[close] = bracket;
                    this.textIsOpenBracket[close] = false;
                    this.maxBracketLength = Math.max(this.maxBracketLength, close.length);
                }
            }
        }
    }
    exports.RichEditBrackets = RichEditBrackets;
    function collectSuperstrings(str, brackets, currentIndex, dest) {
        for (let i = 0, len = brackets.length; i < len; i++) {
            if (i === currentIndex) {
                continue;
            }
            const bracket = brackets[i];
            for (const open of bracket.open) {
                if (open.indexOf(str) >= 0) {
                    dest.push(open);
                }
            }
            for (const close of bracket.close) {
                if (close.indexOf(str) >= 0) {
                    dest.push(close);
                }
            }
        }
    }
    function lengthcmp(a, b) {
        return a.length - b.length;
    }
    function unique(arr) {
        if (arr.length <= 1) {
            return arr;
        }
        const result = [];
        const seen = new Set();
        for (const element of arr) {
            if (seen.has(element)) {
                continue;
            }
            result.push(element);
            seen.add(element);
        }
        return result;
    }
    /**
     * Create a regular expression that can be used to search forward in a piece of text
     * for a group of bracket pairs. But this regex must be built in a way in which
     * it is aware of the other bracket pairs defined for the language.
     *
     * For example, if a language contains the following bracket pairs:
     *   ['begin', 'end']
     *   ['if', 'end if']
     * The two bracket pairs do not collide because no open or close brackets are equal.
     * So the function getRegexForBracketPair is called twice, once with
     * the ['begin'], ['end'] group consisting of one bracket pair, and once with
     * the ['if'], ['end if'] group consiting of the other bracket pair.
     *
     * But there could be a situation where an occurrence of 'end if' is mistaken
     * for an occurrence of 'end'.
     *
     * Therefore, for the bracket pair ['begin', 'end'], the regex will also
     * target 'end if'. The regex will be something like:
     *   /(\bend if\b)|(\bend\b)|(\bif\b)/
     *
     * The regex also searches for "superstrings" (other brackets that might be mistaken with the current bracket).
     *
     */
    function getRegexForBracketPair(open, close, brackets, currentIndex) {
        // search in all brackets for other brackets that are a superstring of these brackets
        let pieces = [];
        pieces = pieces.concat(open);
        pieces = pieces.concat(close);
        for (let i = 0, len = pieces.length; i < len; i++) {
            collectSuperstrings(pieces[i], brackets, currentIndex, pieces);
        }
        pieces = unique(pieces);
        pieces.sort(lengthcmp);
        pieces.reverse();
        return createBracketOrRegExp(pieces);
    }
    /**
     * Matching a regular expression in JS can only be done "forwards". So JS offers natively only
     * methods to find the first match of a regex in a string. But sometimes, it is useful to
     * find the last match of a regex in a string. For such a situation, a nice solution is to
     * simply reverse the string and then search for a reversed regex.
     *
     * This function also has the fine details of `getRegexForBracketPair`. For the same example
     * given above, the regex produced here would look like:
     *   /(\bfi dne\b)|(\bdne\b)|(\bfi\b)/
     */
    function getReversedRegexForBracketPair(open, close, brackets, currentIndex) {
        // search in all brackets for other brackets that are a superstring of these brackets
        let pieces = [];
        pieces = pieces.concat(open);
        pieces = pieces.concat(close);
        for (let i = 0, len = pieces.length; i < len; i++) {
            collectSuperstrings(pieces[i], brackets, currentIndex, pieces);
        }
        pieces = unique(pieces);
        pieces.sort(lengthcmp);
        pieces.reverse();
        return createBracketOrRegExp(pieces.map(toReversedString));
    }
    /**
     * Creates a regular expression that targets all bracket pairs.
     *
     * e.g. for the bracket pairs:
     *  ['{','}']
     *  ['begin,'end']
     *  ['for','end']
     * the regex would look like:
     *  /(\{)|(\})|(\bbegin\b)|(\bend\b)|(\bfor\b)/
     */
    function getRegexForBrackets(brackets) {
        let pieces = [];
        for (const bracket of brackets) {
            for (const open of bracket.open) {
                pieces.push(open);
            }
            for (const close of bracket.close) {
                pieces.push(close);
            }
        }
        pieces = unique(pieces);
        return createBracketOrRegExp(pieces);
    }
    /**
     * Matching a regular expression in JS can only be done "forwards". So JS offers natively only
     * methods to find the first match of a regex in a string. But sometimes, it is useful to
     * find the last match of a regex in a string. For such a situation, a nice solution is to
     * simply reverse the string and then search for a reversed regex.
     *
     * e.g. for the bracket pairs:
     *  ['{','}']
     *  ['begin,'end']
     *  ['for','end']
     * the regex would look like:
     *  /(\{)|(\})|(\bnigeb\b)|(\bdne\b)|(\brof\b)/
     */
    function getReversedRegexForBrackets(brackets) {
        let pieces = [];
        for (const bracket of brackets) {
            for (const open of bracket.open) {
                pieces.push(open);
            }
            for (const close of bracket.close) {
                pieces.push(close);
            }
        }
        pieces = unique(pieces);
        return createBracketOrRegExp(pieces.map(toReversedString));
    }
    function prepareBracketForRegExp(str) {
        // This bracket pair uses letters like e.g. "begin" - "end"
        const insertWordBoundaries = (/^[\w ]+$/.test(str));
        str = strings.escapeRegExpCharacters(str);
        return (insertWordBoundaries ? `\\b${str}\\b` : str);
    }
    function createBracketOrRegExp(pieces, options) {
        const regexStr = `(${pieces.map(prepareBracketForRegExp).join(')|(')})`;
        return strings.createRegExp(regexStr, true, options);
    }
    const toReversedString = (function () {
        function reverse(str) {
            // create a Uint16Array and then use a TextDecoder to create a string
            const arr = new Uint16Array(str.length);
            let offset = 0;
            for (let i = str.length - 1; i >= 0; i--) {
                arr[offset++] = str.charCodeAt(i);
            }
            return stringBuilder.getPlatformTextDecoder().decode(arr);
        }
        let lastInput = null;
        let lastOutput = null;
        return function toReversedString(str) {
            if (lastInput !== str) {
                lastInput = str;
                lastOutput = reverse(lastInput);
            }
            return lastOutput;
        };
    })();
    class BracketsUtils {
        static _findPrevBracketInText(reversedBracketRegex, lineNumber, reversedText, offset) {
            const m = reversedText.match(reversedBracketRegex);
            if (!m) {
                return null;
            }
            const matchOffset = reversedText.length - (m.index || 0);
            const matchLength = m[0].length;
            const absoluteMatchOffset = offset + matchOffset;
            return new range_1.Range(lineNumber, absoluteMatchOffset - matchLength + 1, lineNumber, absoluteMatchOffset + 1);
        }
        static findPrevBracketInRange(reversedBracketRegex, lineNumber, lineText, startOffset, endOffset) {
            // Because JS does not support backwards regex search, we search forwards in a reversed string with a reversed regex ;)
            const reversedLineText = toReversedString(lineText);
            const reversedSubstr = reversedLineText.substring(lineText.length - endOffset, lineText.length - startOffset);
            return this._findPrevBracketInText(reversedBracketRegex, lineNumber, reversedSubstr, startOffset);
        }
        static findNextBracketInText(bracketRegex, lineNumber, text, offset) {
            const m = text.match(bracketRegex);
            if (!m) {
                return null;
            }
            const matchOffset = m.index || 0;
            const matchLength = m[0].length;
            if (matchLength === 0) {
                return null;
            }
            const absoluteMatchOffset = offset + matchOffset;
            return new range_1.Range(lineNumber, absoluteMatchOffset + 1, lineNumber, absoluteMatchOffset + 1 + matchLength);
        }
        static findNextBracketInRange(bracketRegex, lineNumber, lineText, startOffset, endOffset) {
            const substr = lineText.substring(startOffset, endOffset);
            return this.findNextBracketInText(bracketRegex, lineNumber, substr, startOffset);
        }
    }
    exports.BracketsUtils = BracketsUtils;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[659/*vs/editor/common/languages/supports/electricCharacter*/], __M([1/*require*/,0/*exports*/,13/*vs/base/common/arrays*/,169/*vs/editor/common/languages/supports*/,208/*vs/editor/common/languages/supports/richEditBrackets*/]), function (require, exports, arrays_1, supports_1, richEditBrackets_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.BracketElectricCharacterSupport = void 0;
    class BracketElectricCharacterSupport {
        constructor(richEditBrackets) {
            this._richEditBrackets = richEditBrackets;
        }
        getElectricCharacters() {
            const result = [];
            if (this._richEditBrackets) {
                for (const bracket of this._richEditBrackets.brackets) {
                    for (const close of bracket.close) {
                        const lastChar = close.charAt(close.length - 1);
                        result.push(lastChar);
                    }
                }
            }
            return (0, arrays_1.distinct)(result);
        }
        onElectricCharacter(character, context, column) {
            if (!this._richEditBrackets || this._richEditBrackets.brackets.length === 0) {
                return null;
            }
            const tokenIndex = context.findTokenIndexAtOffset(column - 1);
            if ((0, supports_1.ignoreBracketsInToken)(context.getStandardTokenType(tokenIndex))) {
                return null;
            }
            const reversedBracketRegex = this._richEditBrackets.reversedRegex;
            const text = context.getLineContent().substring(0, column - 1) + character;
            const r = richEditBrackets_1.BracketsUtils.findPrevBracketInRange(reversedBracketRegex, 1, text, 0, text.length);
            if (!r) {
                return null;
            }
            const bracketText = text.substring(r.startColumn - 1, r.endColumn - 1).toLowerCase();
            const isOpen = this._richEditBrackets.textIsOpenBracket[bracketText];
            if (isOpen) {
                return null;
            }
            const textBeforeBracket = context.getActualLineContentBefore(r.startColumn - 1);
            if (!/^\s*$/.test(textBeforeBracket)) {
                // There is other text on the line before the bracket
                return null;
            }
            return {
                matchOpenBracket: bracketText
            };
        }
    }
    exports.BracketElectricCharacterSupport = BracketElectricCharacterSupport;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[660/*vs/editor/common/languages/supports/languageBracketsConfiguration*/], __M([1/*require*/,0/*exports*/,297/*vs/base/common/cache*/,208/*vs/editor/common/languages/supports/richEditBrackets*/]), function (require, exports, cache_1, richEditBrackets_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ClosingBracketKind = exports.OpeningBracketKind = exports.BracketKindBase = exports.LanguageBracketsConfiguration = void 0;
    /**
     * Captures all bracket related configurations for a single language.
     * Immutable.
    */
    class LanguageBracketsConfiguration {
        constructor(languageId, config) {
            this.languageId = languageId;
            const bracketPairs = config.brackets ? filterValidBrackets(config.brackets) : [];
            const openingBracketInfos = new cache_1.CachedFunction((bracket) => {
                const closing = new Set();
                return {
                    info: new OpeningBracketKind(this, bracket, closing),
                    closing,
                };
            });
            const closingBracketInfos = new cache_1.CachedFunction((bracket) => {
                const opening = new Set();
                const openingColorized = new Set();
                return {
                    info: new ClosingBracketKind(this, bracket, opening, openingColorized),
                    opening,
                    openingColorized,
                };
            });
            for (const [open, close] of bracketPairs) {
                const opening = openingBracketInfos.get(open);
                const closing = closingBracketInfos.get(close);
                opening.closing.add(closing.info);
                closing.opening.add(opening.info);
            }
            // Treat colorized brackets as brackets, and mark them as colorized.
            const colorizedBracketPairs = config.colorizedBracketPairs
                ? filterValidBrackets(config.colorizedBracketPairs)
                // If not configured: Take all brackets except `<` ... `>`
                // Many languages set < ... > as bracket pair, even though they also use it as comparison operator.
                // This leads to problems when colorizing this bracket, so we exclude it if not explicitly configured otherwise.
                // https://github.com/microsoft/vscode/issues/132476
                : bracketPairs.filter((p) => !(p[0] === '<' && p[1] === '>'));
            for (const [open, close] of colorizedBracketPairs) {
                const opening = openingBracketInfos.get(open);
                const closing = closingBracketInfos.get(close);
                opening.closing.add(closing.info);
                closing.openingColorized.add(opening.info);
                closing.opening.add(opening.info);
            }
            this._openingBrackets = new Map([...openingBracketInfos.cachedValues].map(([k, v]) => [k, v.info]));
            this._closingBrackets = new Map([...closingBracketInfos.cachedValues].map(([k, v]) => [k, v.info]));
        }
        /**
         * No two brackets have the same bracket text.
        */
        get openingBrackets() {
            return [...this._openingBrackets.values()];
        }
        /**
         * No two brackets have the same bracket text.
        */
        get closingBrackets() {
            return [...this._closingBrackets.values()];
        }
        getOpeningBracketInfo(bracketText) {
            return this._openingBrackets.get(bracketText);
        }
        getClosingBracketInfo(bracketText) {
            return this._closingBrackets.get(bracketText);
        }
        getBracketInfo(bracketText) {
            return this.getOpeningBracketInfo(bracketText) || this.getClosingBracketInfo(bracketText);
        }
        getBracketRegExp(options) {
            const brackets = Array.from([...this._openingBrackets.keys(), ...this._closingBrackets.keys()]);
            return (0, richEditBrackets_1.createBracketOrRegExp)(brackets, options);
        }
    }
    exports.LanguageBracketsConfiguration = LanguageBracketsConfiguration;
    function filterValidBrackets(bracketPairs) {
        return bracketPairs.filter(([open, close]) => open !== '' && close !== '');
    }
    class BracketKindBase {
        constructor(config, bracketText) {
            this.config = config;
            this.bracketText = bracketText;
        }
        get languageId() {
            return this.config.languageId;
        }
    }
    exports.BracketKindBase = BracketKindBase;
    class OpeningBracketKind extends BracketKindBase {
        constructor(config, bracketText, openedBrackets) {
            super(config, bracketText);
            this.openedBrackets = openedBrackets;
            this.isOpeningBracket = true;
        }
    }
    exports.OpeningBracketKind = OpeningBracketKind;
    class ClosingBracketKind extends BracketKindBase {
        constructor(config, bracketText, 
        /**
         * Non empty array of all opening brackets this bracket closes.
        */
        openingBrackets, openingColorizedBrackets) {
            super(config, bracketText);
            this.openingBrackets = openingBrackets;
            this.openingColorizedBrackets = openingColorizedBrackets;
            this.isOpeningBracket = false;
        }
        /**
         * Checks if this bracket closes the given other bracket.
         * If the bracket infos come from different configurations, this method will return false.
        */
        closes(other) {
            if (other['config'] !== this.config) {
                return false;
            }
            return this.openingBrackets.has(other);
        }
        closesColorized(other) {
            if (other['config'] !== this.config) {
                return false;
            }
            return this.openingColorizedBrackets.has(other);
        }
        getOpeningBrackets() {
            return [...this.openingBrackets];
        }
    }
    exports.ClosingBracketKind = ClosingBracketKind;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[369/*vs/editor/common/languages/textToHtmlTokenizer*/], __M([1/*require*/,0/*exports*/,11/*vs/base/common/strings*/,83/*vs/editor/common/tokens/lineTokens*/,27/*vs/editor/common/languages*/,177/*vs/editor/common/languages/nullTokenize*/]), function (require, exports, strings, lineTokens_1, languages_1, nullTokenize_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.tokenizeToString = tokenizeToString;
    exports.tokenizeLineToHTML = tokenizeLineToHTML;
    exports._tokenizeToString = _tokenizeToString;
    const fallback = {
        getInitialState: () => nullTokenize_1.NullState,
        tokenizeEncoded: (buffer, hasEOL, state) => (0, nullTokenize_1.nullTokenizeEncoded)(0 /* LanguageId.Null */, state)
    };
    async function tokenizeToString(languageService, text, languageId) {
        if (!languageId) {
            return _tokenizeToString(text, languageService.languageIdCodec, fallback);
        }
        const tokenizationSupport = await languages_1.TokenizationRegistry.getOrCreate(languageId);
        return _tokenizeToString(text, languageService.languageIdCodec, tokenizationSupport || fallback);
    }
    function tokenizeLineToHTML(text, viewLineTokens, colorMap, startOffset, endOffset, tabSize, useNbsp) {
        let result = `<div>`;
        let charIndex = startOffset;
        let tabsCharDelta = 0;
        let prevIsSpace = true;
        for (let tokenIndex = 0, tokenCount = viewLineTokens.getCount(); tokenIndex < tokenCount; tokenIndex++) {
            const tokenEndIndex = viewLineTokens.getEndOffset(tokenIndex);
            if (tokenEndIndex <= startOffset) {
                continue;
            }
            let partContent = '';
            for (; charIndex < tokenEndIndex && charIndex < endOffset; charIndex++) {
                const charCode = text.charCodeAt(charIndex);
                switch (charCode) {
                    case 9 /* CharCode.Tab */: {
                        let insertSpacesCount = tabSize - (charIndex + tabsCharDelta) % tabSize;
                        tabsCharDelta += insertSpacesCount - 1;
                        while (insertSpacesCount > 0) {
                            if (useNbsp && prevIsSpace) {
                                partContent += '&#160;';
                                prevIsSpace = false;
                            }
                            else {
                                partContent += ' ';
                                prevIsSpace = true;
                            }
                            insertSpacesCount--;
                        }
                        break;
                    }
                    case 60 /* CharCode.LessThan */:
                        partContent += '&lt;';
                        prevIsSpace = false;
                        break;
                    case 62 /* CharCode.GreaterThan */:
                        partContent += '&gt;';
                        prevIsSpace = false;
                        break;
                    case 38 /* CharCode.Ampersand */:
                        partContent += '&amp;';
                        prevIsSpace = false;
                        break;
                    case 0 /* CharCode.Null */:
                        partContent += '&#00;';
                        prevIsSpace = false;
                        break;
                    case 65279 /* CharCode.UTF8_BOM */:
                    case 8232 /* CharCode.LINE_SEPARATOR */:
                    case 8233 /* CharCode.PARAGRAPH_SEPARATOR */:
                    case 133 /* CharCode.NEXT_LINE */:
                        partContent += '\ufffd';
                        prevIsSpace = false;
                        break;
                    case 13 /* CharCode.CarriageReturn */:
                        // zero width space, because carriage return would introduce a line break
                        partContent += '&#8203';
                        prevIsSpace = false;
                        break;
                    case 32 /* CharCode.Space */:
                        if (useNbsp && prevIsSpace) {
                            partContent += '&#160;';
                            prevIsSpace = false;
                        }
                        else {
                            partContent += ' ';
                            prevIsSpace = true;
                        }
                        break;
                    default:
                        partContent += String.fromCharCode(charCode);
                        prevIsSpace = false;
                }
            }
            result += `<span style="${viewLineTokens.getInlineStyle(tokenIndex, colorMap)}">${partContent}</span>`;
            if (tokenEndIndex > endOffset || charIndex >= endOffset) {
                break;
            }
        }
        result += `</div>`;
        return result;
    }
    function _tokenizeToString(text, languageIdCodec, tokenizationSupport) {
        let result = `<div class="monaco-tokenized-source">`;
        const lines = strings.splitLines(text);
        let currentState = tokenizationSupport.getInitialState();
        for (let i = 0, len = lines.length; i < len; i++) {
            const line = lines[i];
            if (i > 0) {
                result += `<br/>`;
            }
            const tokenizationResult = tokenizationSupport.tokenizeEncoded(line, true, currentState);
            lineTokens_1.LineTokens.convertToEndOffset(tokenizationResult.tokens, line.length);
            const lineTokens = new lineTokens_1.LineTokens(tokenizationResult.tokens, line, languageIdCodec);
            const viewLineTokens = lineTokens.inflate();
            let startOffset = 0;
            for (let j = 0, lenJ = viewLineTokens.getCount(); j < lenJ; j++) {
                const type = viewLineTokens.getClassName(j);
                const endIndex = viewLineTokens.getEndOffset(j);
                result += `<span class="${type}">${strings.escape(line.substring(startOffset, endIndex))}</span>`;
                startOffset = endIndex;
            }
            currentState = tokenizationResult.endState;
        }
        result += `</div>`;
        return result;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[661/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsImpl*/], __M([1/*require*/,0/*exports*/,13/*vs/base/common/arrays*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,4/*vs/editor/common/core/range*/,169/*vs/editor/common/languages/supports*/,208/*vs/editor/common/languages/supports/richEditBrackets*/,584/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/bracketPairsTree*/]), function (require, exports, arrays_1, event_1, lifecycle_1, range_1, supports_1, richEditBrackets_1, bracketPairsTree_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.BracketPairsTextModelPart = void 0;
    class BracketPairsTextModelPart extends lifecycle_1.Disposable {
        get canBuildAST() {
            const maxSupportedDocumentLength = /* max lines */ 50_000 * /* average column count */ 100;
            return this.textModel.getValueLength() <= maxSupportedDocumentLength;
        }
        constructor(textModel, languageConfigurationService) {
            super();
            this.textModel = textModel;
            this.languageConfigurationService = languageConfigurationService;
            this.bracketPairsTree = this._register(new lifecycle_1.MutableDisposable());
            this.onDidChangeEmitter = new event_1.Emitter();
            this.onDidChange = this.onDidChangeEmitter.event;
            this.bracketsRequested = false;
        }
        //#region TextModel events
        handleLanguageConfigurationServiceChange(e) {
            if (!e.languageId || this.bracketPairsTree.value?.object.didLanguageChange(e.languageId)) {
                this.bracketPairsTree.clear();
                this.updateBracketPairsTree();
            }
        }
        handleDidChangeOptions(e) {
            this.bracketPairsTree.clear();
            this.updateBracketPairsTree();
        }
        handleDidChangeLanguage(e) {
            this.bracketPairsTree.clear();
            this.updateBracketPairsTree();
        }
        handleDidChangeContent(change) {
            this.bracketPairsTree.value?.object.handleContentChanged(change);
        }
        handleDidChangeBackgroundTokenizationState() {
            this.bracketPairsTree.value?.object.handleDidChangeBackgroundTokenizationState();
        }
        handleDidChangeTokens(e) {
            this.bracketPairsTree.value?.object.handleDidChangeTokens(e);
        }
        //#endregion
        updateBracketPairsTree() {
            if (this.bracketsRequested && this.canBuildAST) {
                if (!this.bracketPairsTree.value) {
                    const store = new lifecycle_1.DisposableStore();
                    this.bracketPairsTree.value = createDisposableRef(store.add(new bracketPairsTree_1.BracketPairsTree(this.textModel, (languageId) => {
                        return this.languageConfigurationService.getLanguageConfiguration(languageId);
                    })), store);
                    store.add(this.bracketPairsTree.value.object.onDidChange(e => this.onDidChangeEmitter.fire(e)));
                    this.onDidChangeEmitter.fire();
                }
            }
            else {
                if (this.bracketPairsTree.value) {
                    this.bracketPairsTree.clear();
                    // Important: Don't call fire if there was no change!
                    this.onDidChangeEmitter.fire();
                }
            }
        }
        /**
         * Returns all bracket pairs that intersect the given range.
         * The result is sorted by the start position.
        */
        getBracketPairsInRange(range) {
            this.bracketsRequested = true;
            this.updateBracketPairsTree();
            return this.bracketPairsTree.value?.object.getBracketPairsInRange(range, false) || arrays_1.CallbackIterable.empty;
        }
        getBracketPairsInRangeWithMinIndentation(range) {
            this.bracketsRequested = true;
            this.updateBracketPairsTree();
            return this.bracketPairsTree.value?.object.getBracketPairsInRange(range, true) || arrays_1.CallbackIterable.empty;
        }
        getBracketsInRange(range, onlyColorizedBrackets = false) {
            this.bracketsRequested = true;
            this.updateBracketPairsTree();
            return this.bracketPairsTree.value?.object.getBracketsInRange(range, onlyColorizedBrackets) || arrays_1.CallbackIterable.empty;
        }
        findMatchingBracketUp(_bracket, _position, maxDuration) {
            const position = this.textModel.validatePosition(_position);
            const languageId = this.textModel.getLanguageIdAtPosition(position.lineNumber, position.column);
            if (this.canBuildAST) {
                const closingBracketInfo = this.languageConfigurationService
                    .getLanguageConfiguration(languageId)
                    .bracketsNew.getClosingBracketInfo(_bracket);
                if (!closingBracketInfo) {
                    return null;
                }
                const bracketPair = this.getBracketPairsInRange(range_1.Range.fromPositions(_position, _position)).findLast((b) => closingBracketInfo.closes(b.openingBracketInfo));
                if (bracketPair) {
                    return bracketPair.openingBracketRange;
                }
                return null;
            }
            else {
                // Fallback to old bracket matching code:
                const bracket = _bracket.toLowerCase();
                const bracketsSupport = this.languageConfigurationService.getLanguageConfiguration(languageId).brackets;
                if (!bracketsSupport) {
                    return null;
                }
                const data = bracketsSupport.textIsBracket[bracket];
                if (!data) {
                    return null;
                }
                return stripBracketSearchCanceled(this._findMatchingBracketUp(data, position, createTimeBasedContinueBracketSearchPredicate(maxDuration)));
            }
        }
        matchBracket(position, maxDuration) {
            if (this.canBuildAST) {
                const bracketPair = this.getBracketPairsInRange(range_1.Range.fromPositions(position, position)).filter((item) => item.closingBracketRange !== undefined &&
                    (item.openingBracketRange.containsPosition(position) ||
                        item.closingBracketRange.containsPosition(position))).findLastMaxBy((0, arrays_1.compareBy)((item) => item.openingBracketRange.containsPosition(position)
                    ? item.openingBracketRange
                    : item.closingBracketRange, range_1.Range.compareRangesUsingStarts));
                if (bracketPair) {
                    return [bracketPair.openingBracketRange, bracketPair.closingBracketRange];
                }
                return null;
            }
            else {
                // Fallback to old bracket matching code:
                const continueSearchPredicate = createTimeBasedContinueBracketSearchPredicate(maxDuration);
                return this._matchBracket(this.textModel.validatePosition(position), continueSearchPredicate);
            }
        }
        _establishBracketSearchOffsets(position, lineTokens, modeBrackets, tokenIndex) {
            const tokenCount = lineTokens.getCount();
            const currentLanguageId = lineTokens.getLanguageId(tokenIndex);
            // limit search to not go before `maxBracketLength`
            let searchStartOffset = Math.max(0, position.column - 1 - modeBrackets.maxBracketLength);
            for (let i = tokenIndex - 1; i >= 0; i--) {
                const tokenEndOffset = lineTokens.getEndOffset(i);
                if (tokenEndOffset <= searchStartOffset) {
                    break;
                }
                if ((0, supports_1.ignoreBracketsInToken)(lineTokens.getStandardTokenType(i)) || lineTokens.getLanguageId(i) !== currentLanguageId) {
                    searchStartOffset = tokenEndOffset;
                    break;
                }
            }
            // limit search to not go after `maxBracketLength`
            let searchEndOffset = Math.min(lineTokens.getLineContent().length, position.column - 1 + modeBrackets.maxBracketLength);
            for (let i = tokenIndex + 1; i < tokenCount; i++) {
                const tokenStartOffset = lineTokens.getStartOffset(i);
                if (tokenStartOffset >= searchEndOffset) {
                    break;
                }
                if ((0, supports_1.ignoreBracketsInToken)(lineTokens.getStandardTokenType(i)) || lineTokens.getLanguageId(i) !== currentLanguageId) {
                    searchEndOffset = tokenStartOffset;
                    break;
                }
            }
            return { searchStartOffset, searchEndOffset };
        }
        _matchBracket(position, continueSearchPredicate) {
            const lineNumber = position.lineNumber;
            const lineTokens = this.textModel.tokenization.getLineTokens(lineNumber);
            const lineText = this.textModel.getLineContent(lineNumber);
            const tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
            if (tokenIndex < 0) {
                return null;
            }
            const currentModeBrackets = this.languageConfigurationService.getLanguageConfiguration(lineTokens.getLanguageId(tokenIndex)).brackets;
            // check that the token is not to be ignored
            if (currentModeBrackets && !(0, supports_1.ignoreBracketsInToken)(lineTokens.getStandardTokenType(tokenIndex))) {
                let { searchStartOffset, searchEndOffset } = this._establishBracketSearchOffsets(position, lineTokens, currentModeBrackets, tokenIndex);
                // it might be the case that [currentTokenStart -> currentTokenEnd] contains multiple brackets
                // `bestResult` will contain the most right-side result
                let bestResult = null;
                while (true) {
                    const foundBracket = richEditBrackets_1.BracketsUtils.findNextBracketInRange(currentModeBrackets.forwardRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
                    if (!foundBracket) {
                        // there are no more brackets in this text
                        break;
                    }
                    // check that we didn't hit a bracket too far away from position
                    if (foundBracket.startColumn <= position.column && position.column <= foundBracket.endColumn) {
                        const foundBracketText = lineText.substring(foundBracket.startColumn - 1, foundBracket.endColumn - 1).toLowerCase();
                        const r = this._matchFoundBracket(foundBracket, currentModeBrackets.textIsBracket[foundBracketText], currentModeBrackets.textIsOpenBracket[foundBracketText], continueSearchPredicate);
                        if (r) {
                            if (r instanceof BracketSearchCanceled) {
                                return null;
                            }
                            bestResult = r;
                        }
                    }
                    searchStartOffset = foundBracket.endColumn - 1;
                }
                if (bestResult) {
                    return bestResult;
                }
            }
            // If position is in between two tokens, try also looking in the previous token
            if (tokenIndex > 0 && lineTokens.getStartOffset(tokenIndex) === position.column - 1) {
                const prevTokenIndex = tokenIndex - 1;
                const prevModeBrackets = this.languageConfigurationService.getLanguageConfiguration(lineTokens.getLanguageId(prevTokenIndex)).brackets;
                // check that previous token is not to be ignored
                if (prevModeBrackets && !(0, supports_1.ignoreBracketsInToken)(lineTokens.getStandardTokenType(prevTokenIndex))) {
                    const { searchStartOffset, searchEndOffset } = this._establishBracketSearchOffsets(position, lineTokens, prevModeBrackets, prevTokenIndex);
                    const foundBracket = richEditBrackets_1.BracketsUtils.findPrevBracketInRange(prevModeBrackets.reversedRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
                    // check that we didn't hit a bracket too far away from position
                    if (foundBracket && foundBracket.startColumn <= position.column && position.column <= foundBracket.endColumn) {
                        const foundBracketText = lineText.substring(foundBracket.startColumn - 1, foundBracket.endColumn - 1).toLowerCase();
                        const r = this._matchFoundBracket(foundBracket, prevModeBrackets.textIsBracket[foundBracketText], prevModeBrackets.textIsOpenBracket[foundBracketText], continueSearchPredicate);
                        if (r) {
                            if (r instanceof BracketSearchCanceled) {
                                return null;
                            }
                            return r;
                        }
                    }
                }
            }
            return null;
        }
        _matchFoundBracket(foundBracket, data, isOpen, continueSearchPredicate) {
            if (!data) {
                return null;
            }
            const matched = (isOpen
                ? this._findMatchingBracketDown(data, foundBracket.getEndPosition(), continueSearchPredicate)
                : this._findMatchingBracketUp(data, foundBracket.getStartPosition(), continueSearchPredicate));
            if (!matched) {
                return null;
            }
            if (matched instanceof BracketSearchCanceled) {
                return matched;
            }
            return [foundBracket, matched];
        }
        _findMatchingBracketUp(bracket, position, continueSearchPredicate) {
            // console.log('_findMatchingBracketUp: ', 'bracket: ', JSON.stringify(bracket), 'startPosition: ', String(position));
            const languageId = bracket.languageId;
            const reversedBracketRegex = bracket.reversedRegex;
            let count = -1;
            let totalCallCount = 0;
            const searchPrevMatchingBracketInRange = (lineNumber, lineText, searchStartOffset, searchEndOffset) => {
                while (true) {
                    if (continueSearchPredicate && (++totalCallCount) % 100 === 0 && !continueSearchPredicate()) {
                        return BracketSearchCanceled.INSTANCE;
                    }
                    const r = richEditBrackets_1.BracketsUtils.findPrevBracketInRange(reversedBracketRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
                    if (!r) {
                        break;
                    }
                    const hitText = lineText.substring(r.startColumn - 1, r.endColumn - 1).toLowerCase();
                    if (bracket.isOpen(hitText)) {
                        count++;
                    }
                    else if (bracket.isClose(hitText)) {
                        count--;
                    }
                    if (count === 0) {
                        return r;
                    }
                    searchEndOffset = r.startColumn - 1;
                }
                return null;
            };
            for (let lineNumber = position.lineNumber; lineNumber >= 1; lineNumber--) {
                const lineTokens = this.textModel.tokenization.getLineTokens(lineNumber);
                const tokenCount = lineTokens.getCount();
                const lineText = this.textModel.getLineContent(lineNumber);
                let tokenIndex = tokenCount - 1;
                let searchStartOffset = lineText.length;
                let searchEndOffset = lineText.length;
                if (lineNumber === position.lineNumber) {
                    tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
                    searchStartOffset = position.column - 1;
                    searchEndOffset = position.column - 1;
                }
                let prevSearchInToken = true;
                for (; tokenIndex >= 0; tokenIndex--) {
                    const searchInToken = (lineTokens.getLanguageId(tokenIndex) === languageId && !(0, supports_1.ignoreBracketsInToken)(lineTokens.getStandardTokenType(tokenIndex)));
                    if (searchInToken) {
                        // this token should be searched
                        if (prevSearchInToken) {
                            // the previous token should be searched, simply extend searchStartOffset
                            searchStartOffset = lineTokens.getStartOffset(tokenIndex);
                        }
                        else {
                            // the previous token should not be searched
                            searchStartOffset = lineTokens.getStartOffset(tokenIndex);
                            searchEndOffset = lineTokens.getEndOffset(tokenIndex);
                        }
                    }
                    else {
                        // this token should not be searched
                        if (prevSearchInToken && searchStartOffset !== searchEndOffset) {
                            const r = searchPrevMatchingBracketInRange(lineNumber, lineText, searchStartOffset, searchEndOffset);
                            if (r) {
                                return r;
                            }
                        }
                    }
                    prevSearchInToken = searchInToken;
                }
                if (prevSearchInToken && searchStartOffset !== searchEndOffset) {
                    const r = searchPrevMatchingBracketInRange(lineNumber, lineText, searchStartOffset, searchEndOffset);
                    if (r) {
                        return r;
                    }
                }
            }
            return null;
        }
        _findMatchingBracketDown(bracket, position, continueSearchPredicate) {
            // console.log('_findMatchingBracketDown: ', 'bracket: ', JSON.stringify(bracket), 'startPosition: ', String(position));
            const languageId = bracket.languageId;
            const bracketRegex = bracket.forwardRegex;
            let count = 1;
            let totalCallCount = 0;
            const searchNextMatchingBracketInRange = (lineNumber, lineText, searchStartOffset, searchEndOffset) => {
                while (true) {
                    if (continueSearchPredicate && (++totalCallCount) % 100 === 0 && !continueSearchPredicate()) {
                        return BracketSearchCanceled.INSTANCE;
                    }
                    const r = richEditBrackets_1.BracketsUtils.findNextBracketInRange(bracketRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
                    if (!r) {
                        break;
                    }
                    const hitText = lineText.substring(r.startColumn - 1, r.endColumn - 1).toLowerCase();
                    if (bracket.isOpen(hitText)) {
                        count++;
                    }
                    else if (bracket.isClose(hitText)) {
                        count--;
                    }
                    if (count === 0) {
                        return r;
                    }
                    searchStartOffset = r.endColumn - 1;
                }
                return null;
            };
            const lineCount = this.textModel.getLineCount();
            for (let lineNumber = position.lineNumber; lineNumber <= lineCount; lineNumber++) {
                const lineTokens = this.textModel.tokenization.getLineTokens(lineNumber);
                const tokenCount = lineTokens.getCount();
                const lineText = this.textModel.getLineContent(lineNumber);
                let tokenIndex = 0;
                let searchStartOffset = 0;
                let searchEndOffset = 0;
                if (lineNumber === position.lineNumber) {
                    tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
                    searchStartOffset = position.column - 1;
                    searchEndOffset = position.column - 1;
                }
                let prevSearchInToken = true;
                for (; tokenIndex < tokenCount; tokenIndex++) {
                    const searchInToken = (lineTokens.getLanguageId(tokenIndex) === languageId && !(0, supports_1.ignoreBracketsInToken)(lineTokens.getStandardTokenType(tokenIndex)));
                    if (searchInToken) {
                        // this token should be searched
                        if (prevSearchInToken) {
                            // the previous token should be searched, simply extend searchEndOffset
                            searchEndOffset = lineTokens.getEndOffset(tokenIndex);
                        }
                        else {
                            // the previous token should not be searched
                            searchStartOffset = lineTokens.getStartOffset(tokenIndex);
                            searchEndOffset = lineTokens.getEndOffset(tokenIndex);
                        }
                    }
                    else {
                        // this token should not be searched
                        if (prevSearchInToken && searchStartOffset !== searchEndOffset) {
                            const r = searchNextMatchingBracketInRange(lineNumber, lineText, searchStartOffset, searchEndOffset);
                            if (r) {
                                return r;
                            }
                        }
                    }
                    prevSearchInToken = searchInToken;
                }
                if (prevSearchInToken && searchStartOffset !== searchEndOffset) {
                    const r = searchNextMatchingBracketInRange(lineNumber, lineText, searchStartOffset, searchEndOffset);
                    if (r) {
                        return r;
                    }
                }
            }
            return null;
        }
        findPrevBracket(_position) {
            const position = this.textModel.validatePosition(_position);
            if (this.canBuildAST) {
                this.bracketsRequested = true;
                this.updateBracketPairsTree();
                return this.bracketPairsTree.value?.object.getFirstBracketBefore(position) || null;
            }
            let languageId = null;
            let modeBrackets = null;
            let bracketConfig = null;
            for (let lineNumber = position.lineNumber; lineNumber >= 1; lineNumber--) {
                const lineTokens = this.textModel.tokenization.getLineTokens(lineNumber);
                const tokenCount = lineTokens.getCount();
                const lineText = this.textModel.getLineContent(lineNumber);
                let tokenIndex = tokenCount - 1;
                let searchStartOffset = lineText.length;
                let searchEndOffset = lineText.length;
                if (lineNumber === position.lineNumber) {
                    tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
                    searchStartOffset = position.column - 1;
                    searchEndOffset = position.column - 1;
                    const tokenLanguageId = lineTokens.getLanguageId(tokenIndex);
                    if (languageId !== tokenLanguageId) {
                        languageId = tokenLanguageId;
                        modeBrackets = this.languageConfigurationService.getLanguageConfiguration(languageId).brackets;
                        bracketConfig = this.languageConfigurationService.getLanguageConfiguration(languageId).bracketsNew;
                    }
                }
                let prevSearchInToken = true;
                for (; tokenIndex >= 0; tokenIndex--) {
                    const tokenLanguageId = lineTokens.getLanguageId(tokenIndex);
                    if (languageId !== tokenLanguageId) {
                        // language id change!
                        if (modeBrackets && bracketConfig && prevSearchInToken && searchStartOffset !== searchEndOffset) {
                            const r = richEditBrackets_1.BracketsUtils.findPrevBracketInRange(modeBrackets.reversedRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
                            if (r) {
                                return this._toFoundBracket(bracketConfig, r);
                            }
                            prevSearchInToken = false;
                        }
                        languageId = tokenLanguageId;
                        modeBrackets = this.languageConfigurationService.getLanguageConfiguration(languageId).brackets;
                        bracketConfig = this.languageConfigurationService.getLanguageConfiguration(languageId).bracketsNew;
                    }
                    const searchInToken = (!!modeBrackets && !(0, supports_1.ignoreBracketsInToken)(lineTokens.getStandardTokenType(tokenIndex)));
                    if (searchInToken) {
                        // this token should be searched
                        if (prevSearchInToken) {
                            // the previous token should be searched, simply extend searchStartOffset
                            searchStartOffset = lineTokens.getStartOffset(tokenIndex);
                        }
                        else {
                            // the previous token should not be searched
                            searchStartOffset = lineTokens.getStartOffset(tokenIndex);
                            searchEndOffset = lineTokens.getEndOffset(tokenIndex);
                        }
                    }
                    else {
                        // this token should not be searched
                        if (bracketConfig && modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
                            const r = richEditBrackets_1.BracketsUtils.findPrevBracketInRange(modeBrackets.reversedRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
                            if (r) {
                                return this._toFoundBracket(bracketConfig, r);
                            }
                        }
                    }
                    prevSearchInToken = searchInToken;
                }
                if (bracketConfig && modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
                    const r = richEditBrackets_1.BracketsUtils.findPrevBracketInRange(modeBrackets.reversedRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
                    if (r) {
                        return this._toFoundBracket(bracketConfig, r);
                    }
                }
            }
            return null;
        }
        findNextBracket(_position) {
            const position = this.textModel.validatePosition(_position);
            if (this.canBuildAST) {
                this.bracketsRequested = true;
                this.updateBracketPairsTree();
                return this.bracketPairsTree.value?.object.getFirstBracketAfter(position) || null;
            }
            const lineCount = this.textModel.getLineCount();
            let languageId = null;
            let modeBrackets = null;
            let bracketConfig = null;
            for (let lineNumber = position.lineNumber; lineNumber <= lineCount; lineNumber++) {
                const lineTokens = this.textModel.tokenization.getLineTokens(lineNumber);
                const tokenCount = lineTokens.getCount();
                const lineText = this.textModel.getLineContent(lineNumber);
                let tokenIndex = 0;
                let searchStartOffset = 0;
                let searchEndOffset = 0;
                if (lineNumber === position.lineNumber) {
                    tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
                    searchStartOffset = position.column - 1;
                    searchEndOffset = position.column - 1;
                    const tokenLanguageId = lineTokens.getLanguageId(tokenIndex);
                    if (languageId !== tokenLanguageId) {
                        languageId = tokenLanguageId;
                        modeBrackets = this.languageConfigurationService.getLanguageConfiguration(languageId).brackets;
                        bracketConfig = this.languageConfigurationService.getLanguageConfiguration(languageId).bracketsNew;
                    }
                }
                let prevSearchInToken = true;
                for (; tokenIndex < tokenCount; tokenIndex++) {
                    const tokenLanguageId = lineTokens.getLanguageId(tokenIndex);
                    if (languageId !== tokenLanguageId) {
                        // language id change!
                        if (bracketConfig && modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
                            const r = richEditBrackets_1.BracketsUtils.findNextBracketInRange(modeBrackets.forwardRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
                            if (r) {
                                return this._toFoundBracket(bracketConfig, r);
                            }
                            prevSearchInToken = false;
                        }
                        languageId = tokenLanguageId;
                        modeBrackets = this.languageConfigurationService.getLanguageConfiguration(languageId).brackets;
                        bracketConfig = this.languageConfigurationService.getLanguageConfiguration(languageId).bracketsNew;
                    }
                    const searchInToken = (!!modeBrackets && !(0, supports_1.ignoreBracketsInToken)(lineTokens.getStandardTokenType(tokenIndex)));
                    if (searchInToken) {
                        // this token should be searched
                        if (prevSearchInToken) {
                            // the previous token should be searched, simply extend searchEndOffset
                            searchEndOffset = lineTokens.getEndOffset(tokenIndex);
                        }
                        else {
                            // the previous token should not be searched
                            searchStartOffset = lineTokens.getStartOffset(tokenIndex);
                            searchEndOffset = lineTokens.getEndOffset(tokenIndex);
                        }
                    }
                    else {
                        // this token should not be searched
                        if (bracketConfig && modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
                            const r = richEditBrackets_1.BracketsUtils.findNextBracketInRange(modeBrackets.forwardRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
                            if (r) {
                                return this._toFoundBracket(bracketConfig, r);
                            }
                        }
                    }
                    prevSearchInToken = searchInToken;
                }
                if (bracketConfig && modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
                    const r = richEditBrackets_1.BracketsUtils.findNextBracketInRange(modeBrackets.forwardRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
                    if (r) {
                        return this._toFoundBracket(bracketConfig, r);
                    }
                }
            }
            return null;
        }
        findEnclosingBrackets(_position, maxDuration) {
            const position = this.textModel.validatePosition(_position);
            if (this.canBuildAST) {
                const range = range_1.Range.fromPositions(position);
                const bracketPair = this.getBracketPairsInRange(range_1.Range.fromPositions(position, position)).findLast((item) => item.closingBracketRange !== undefined && item.range.strictContainsRange(range));
                if (bracketPair) {
                    return [bracketPair.openingBracketRange, bracketPair.closingBracketRange];
                }
                return null;
            }
            const continueSearchPredicate = createTimeBasedContinueBracketSearchPredicate(maxDuration);
            const lineCount = this.textModel.getLineCount();
            const savedCounts = new Map();
            let counts = [];
            const resetCounts = (languageId, modeBrackets) => {
                if (!savedCounts.has(languageId)) {
                    const tmp = [];
                    for (let i = 0, len = modeBrackets ? modeBrackets.brackets.length : 0; i < len; i++) {
                        tmp[i] = 0;
                    }
                    savedCounts.set(languageId, tmp);
                }
                counts = savedCounts.get(languageId);
            };
            let totalCallCount = 0;
            const searchInRange = (modeBrackets, lineNumber, lineText, searchStartOffset, searchEndOffset) => {
                while (true) {
                    if (continueSearchPredicate && (++totalCallCount) % 100 === 0 && !continueSearchPredicate()) {
                        return BracketSearchCanceled.INSTANCE;
                    }
                    const r = richEditBrackets_1.BracketsUtils.findNextBracketInRange(modeBrackets.forwardRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
                    if (!r) {
                        break;
                    }
                    const hitText = lineText.substring(r.startColumn - 1, r.endColumn - 1).toLowerCase();
                    const bracket = modeBrackets.textIsBracket[hitText];
                    if (bracket) {
                        if (bracket.isOpen(hitText)) {
                            counts[bracket.index]++;
                        }
                        else if (bracket.isClose(hitText)) {
                            counts[bracket.index]--;
                        }
                        if (counts[bracket.index] === -1) {
                            return this._matchFoundBracket(r, bracket, false, continueSearchPredicate);
                        }
                    }
                    searchStartOffset = r.endColumn - 1;
                }
                return null;
            };
            let languageId = null;
            let modeBrackets = null;
            for (let lineNumber = position.lineNumber; lineNumber <= lineCount; lineNumber++) {
                const lineTokens = this.textModel.tokenization.getLineTokens(lineNumber);
                const tokenCount = lineTokens.getCount();
                const lineText = this.textModel.getLineContent(lineNumber);
                let tokenIndex = 0;
                let searchStartOffset = 0;
                let searchEndOffset = 0;
                if (lineNumber === position.lineNumber) {
                    tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
                    searchStartOffset = position.column - 1;
                    searchEndOffset = position.column - 1;
                    const tokenLanguageId = lineTokens.getLanguageId(tokenIndex);
                    if (languageId !== tokenLanguageId) {
                        languageId = tokenLanguageId;
                        modeBrackets = this.languageConfigurationService.getLanguageConfiguration(languageId).brackets;
                        resetCounts(languageId, modeBrackets);
                    }
                }
                let prevSearchInToken = true;
                for (; tokenIndex < tokenCount; tokenIndex++) {
                    const tokenLanguageId = lineTokens.getLanguageId(tokenIndex);
                    if (languageId !== tokenLanguageId) {
                        // language id change!
                        if (modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
                            const r = searchInRange(modeBrackets, lineNumber, lineText, searchStartOffset, searchEndOffset);
                            if (r) {
                                return stripBracketSearchCanceled(r);
                            }
                            prevSearchInToken = false;
                        }
                        languageId = tokenLanguageId;
                        modeBrackets = this.languageConfigurationService.getLanguageConfiguration(languageId).brackets;
                        resetCounts(languageId, modeBrackets);
                    }
                    const searchInToken = (!!modeBrackets && !(0, supports_1.ignoreBracketsInToken)(lineTokens.getStandardTokenType(tokenIndex)));
                    if (searchInToken) {
                        // this token should be searched
                        if (prevSearchInToken) {
                            // the previous token should be searched, simply extend searchEndOffset
                            searchEndOffset = lineTokens.getEndOffset(tokenIndex);
                        }
                        else {
                            // the previous token should not be searched
                            searchStartOffset = lineTokens.getStartOffset(tokenIndex);
                            searchEndOffset = lineTokens.getEndOffset(tokenIndex);
                        }
                    }
                    else {
                        // this token should not be searched
                        if (modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
                            const r = searchInRange(modeBrackets, lineNumber, lineText, searchStartOffset, searchEndOffset);
                            if (r) {
                                return stripBracketSearchCanceled(r);
                            }
                        }
                    }
                    prevSearchInToken = searchInToken;
                }
                if (modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
                    const r = searchInRange(modeBrackets, lineNumber, lineText, searchStartOffset, searchEndOffset);
                    if (r) {
                        return stripBracketSearchCanceled(r);
                    }
                }
            }
            return null;
        }
        _toFoundBracket(bracketConfig, r) {
            if (!r) {
                return null;
            }
            let text = this.textModel.getValueInRange(r);
            text = text.toLowerCase();
            const bracketInfo = bracketConfig.getBracketInfo(text);
            if (!bracketInfo) {
                return null;
            }
            return {
                range: r,
                bracketInfo
            };
        }
    }
    exports.BracketPairsTextModelPart = BracketPairsTextModelPart;
    function createDisposableRef(object, disposable) {
        return {
            object,
            dispose: () => disposable?.dispose(),
        };
    }
    function createTimeBasedContinueBracketSearchPredicate(maxDuration) {
        if (typeof maxDuration === 'undefined') {
            return () => true;
        }
        else {
            const startTime = Date.now();
            return () => {
                return (Date.now() - startTime <= maxDuration);
            };
        }
    }
    class BracketSearchCanceled {
        static { this.INSTANCE = new BracketSearchCanceled(); }
        constructor() {
            this._searchCanceledBrand = undefined;
        }
    }
    function stripBracketSearchCanceled(result) {
        if (result instanceof BracketSearchCanceled) {
            return null;
        }
        return result;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[370/*vs/editor/common/model/editStack*/], __M([1/*require*/,0/*exports*/,3/*vs/nls*/,8/*vs/base/common/errors*/,23/*vs/editor/common/core/selection*/,22/*vs/base/common/uri*/,367/*vs/editor/common/core/textChange*/,160/*vs/base/common/buffer*/,48/*vs/base/common/resources*/]), function (require, exports, nls, errors_1, selection_1, uri_1, textChange_1, buffer, resources_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.EditStack = exports.MultiModelEditStackElement = exports.SingleModelEditStackElement = exports.SingleModelEditStackData = void 0;
    exports.isEditStackElement = isEditStackElement;
    function uriGetComparisonKey(resource) {
        return resource.toString();
    }
    class SingleModelEditStackData {
        static create(model, beforeCursorState) {
            const alternativeVersionId = model.getAlternativeVersionId();
            const eol = getModelEOL(model);
            return new SingleModelEditStackData(alternativeVersionId, alternativeVersionId, eol, eol, beforeCursorState, beforeCursorState, []);
        }
        constructor(beforeVersionId, afterVersionId, beforeEOL, afterEOL, beforeCursorState, afterCursorState, changes) {
            this.beforeVersionId = beforeVersionId;
            this.afterVersionId = afterVersionId;
            this.beforeEOL = beforeEOL;
            this.afterEOL = afterEOL;
            this.beforeCursorState = beforeCursorState;
            this.afterCursorState = afterCursorState;
            this.changes = changes;
        }
        append(model, textChanges, afterEOL, afterVersionId, afterCursorState) {
            if (textChanges.length > 0) {
                this.changes = (0, textChange_1.compressConsecutiveTextChanges)(this.changes, textChanges);
            }
            this.afterEOL = afterEOL;
            this.afterVersionId = afterVersionId;
            this.afterCursorState = afterCursorState;
        }
        static _writeSelectionsSize(selections) {
            return 4 + 4 * 4 * (selections ? selections.length : 0);
        }
        static _writeSelections(b, selections, offset) {
            buffer.writeUInt32BE(b, (selections ? selections.length : 0), offset);
            offset += 4;
            if (selections) {
                for (const selection of selections) {
                    buffer.writeUInt32BE(b, selection.selectionStartLineNumber, offset);
                    offset += 4;
                    buffer.writeUInt32BE(b, selection.selectionStartColumn, offset);
                    offset += 4;
                    buffer.writeUInt32BE(b, selection.positionLineNumber, offset);
                    offset += 4;
                    buffer.writeUInt32BE(b, selection.positionColumn, offset);
                    offset += 4;
                }
            }
            return offset;
        }
        static _readSelections(b, offset, dest) {
            const count = buffer.readUInt32BE(b, offset);
            offset += 4;
            for (let i = 0; i < count; i++) {
                const selectionStartLineNumber = buffer.readUInt32BE(b, offset);
                offset += 4;
                const selectionStartColumn = buffer.readUInt32BE(b, offset);
                offset += 4;
                const positionLineNumber = buffer.readUInt32BE(b, offset);
                offset += 4;
                const positionColumn = buffer.readUInt32BE(b, offset);
                offset += 4;
                dest.push(new selection_1.Selection(selectionStartLineNumber, selectionStartColumn, positionLineNumber, positionColumn));
            }
            return offset;
        }
        serialize() {
            let necessarySize = (+4 // beforeVersionId
                + 4 // afterVersionId
                + 1 // beforeEOL
                + 1 // afterEOL
                + SingleModelEditStackData._writeSelectionsSize(this.beforeCursorState)
                + SingleModelEditStackData._writeSelectionsSize(this.afterCursorState)
                + 4 // change count
            );
            for (const change of this.changes) {
                necessarySize += change.writeSize();
            }
            const b = new Uint8Array(necessarySize);
            let offset = 0;
            buffer.writeUInt32BE(b, this.beforeVersionId, offset);
            offset += 4;
            buffer.writeUInt32BE(b, this.afterVersionId, offset);
            offset += 4;
            buffer.writeUInt8(b, this.beforeEOL, offset);
            offset += 1;
            buffer.writeUInt8(b, this.afterEOL, offset);
            offset += 1;
            offset = SingleModelEditStackData._writeSelections(b, this.beforeCursorState, offset);
            offset = SingleModelEditStackData._writeSelections(b, this.afterCursorState, offset);
            buffer.writeUInt32BE(b, this.changes.length, offset);
            offset += 4;
            for (const change of this.changes) {
                offset = change.write(b, offset);
            }
            return b.buffer;
        }
        static deserialize(source) {
            const b = new Uint8Array(source);
            let offset = 0;
            const beforeVersionId = buffer.readUInt32BE(b, offset);
            offset += 4;
            const afterVersionId = buffer.readUInt32BE(b, offset);
            offset += 4;
            const beforeEOL = buffer.readUInt8(b, offset);
            offset += 1;
            const afterEOL = buffer.readUInt8(b, offset);
            offset += 1;
            const beforeCursorState = [];
            offset = SingleModelEditStackData._readSelections(b, offset, beforeCursorState);
            const afterCursorState = [];
            offset = SingleModelEditStackData._readSelections(b, offset, afterCursorState);
            const changeCount = buffer.readUInt32BE(b, offset);
            offset += 4;
            const changes = [];
            for (let i = 0; i < changeCount; i++) {
                offset = textChange_1.TextChange.read(b, offset, changes);
            }
            return new SingleModelEditStackData(beforeVersionId, afterVersionId, beforeEOL, afterEOL, beforeCursorState, afterCursorState, changes);
        }
    }
    exports.SingleModelEditStackData = SingleModelEditStackData;
    class SingleModelEditStackElement {
        get type() {
            return 0 /* UndoRedoElementType.Resource */;
        }
        get resource() {
            if (uri_1.URI.isUri(this.model)) {
                return this.model;
            }
            return this.model.uri;
        }
        constructor(label, code, model, beforeCursorState) {
            this.label = label;
            this.code = code;
            this.model = model;
            this._data = SingleModelEditStackData.create(model, beforeCursorState);
        }
        toString() {
            const data = (this._data instanceof SingleModelEditStackData ? this._data : SingleModelEditStackData.deserialize(this._data));
            return data.changes.map(change => change.toString()).join(', ');
        }
        matchesResource(resource) {
            const uri = (uri_1.URI.isUri(this.model) ? this.model : this.model.uri);
            return (uri.toString() === resource.toString());
        }
        setModel(model) {
            this.model = model;
        }
        canAppend(model) {
            return (this.model === model && this._data instanceof SingleModelEditStackData);
        }
        append(model, textChanges, afterEOL, afterVersionId, afterCursorState) {
            if (this._data instanceof SingleModelEditStackData) {
                this._data.append(model, textChanges, afterEOL, afterVersionId, afterCursorState);
            }
        }
        close() {
            if (this._data instanceof SingleModelEditStackData) {
                this._data = this._data.serialize();
            }
        }
        open() {
            if (!(this._data instanceof SingleModelEditStackData)) {
                this._data = SingleModelEditStackData.deserialize(this._data);
            }
        }
        undo() {
            if (uri_1.URI.isUri(this.model)) {
                // don't have a model
                throw new Error(`Invalid SingleModelEditStackElement`);
            }
            if (this._data instanceof SingleModelEditStackData) {
                this._data = this._data.serialize();
            }
            const data = SingleModelEditStackData.deserialize(this._data);
            this.model._applyUndo(data.changes, data.beforeEOL, data.beforeVersionId, data.beforeCursorState);
        }
        redo() {
            if (uri_1.URI.isUri(this.model)) {
                // don't have a model
                throw new Error(`Invalid SingleModelEditStackElement`);
            }
            if (this._data instanceof SingleModelEditStackData) {
                this._data = this._data.serialize();
            }
            const data = SingleModelEditStackData.deserialize(this._data);
            this.model._applyRedo(data.changes, data.afterEOL, data.afterVersionId, data.afterCursorState);
        }
        heapSize() {
            if (this._data instanceof SingleModelEditStackData) {
                this._data = this._data.serialize();
            }
            return this._data.byteLength + 168 /*heap overhead*/;
        }
    }
    exports.SingleModelEditStackElement = SingleModelEditStackElement;
    class MultiModelEditStackElement {
        get resources() {
            return this._editStackElementsArr.map(editStackElement => editStackElement.resource);
        }
        constructor(label, code, editStackElements) {
            this.label = label;
            this.code = code;
            this.type = 1 /* UndoRedoElementType.Workspace */;
            this._isOpen = true;
            this._editStackElementsArr = editStackElements.slice(0);
            this._editStackElementsMap = new Map();
            for (const editStackElement of this._editStackElementsArr) {
                const key = uriGetComparisonKey(editStackElement.resource);
                this._editStackElementsMap.set(key, editStackElement);
            }
            this._delegate = null;
        }
        prepareUndoRedo() {
            if (this._delegate) {
                return this._delegate.prepareUndoRedo(this);
            }
        }
        matchesResource(resource) {
            const key = uriGetComparisonKey(resource);
            return (this._editStackElementsMap.has(key));
        }
        setModel(model) {
            const key = uriGetComparisonKey(uri_1.URI.isUri(model) ? model : model.uri);
            if (this._editStackElementsMap.has(key)) {
                this._editStackElementsMap.get(key).setModel(model);
            }
        }
        canAppend(model) {
            if (!this._isOpen) {
                return false;
            }
            const key = uriGetComparisonKey(model.uri);
            if (this._editStackElementsMap.has(key)) {
                const editStackElement = this._editStackElementsMap.get(key);
                return editStackElement.canAppend(model);
            }
            return false;
        }
        append(model, textChanges, afterEOL, afterVersionId, afterCursorState) {
            const key = uriGetComparisonKey(model.uri);
            const editStackElement = this._editStackElementsMap.get(key);
            editStackElement.append(model, textChanges, afterEOL, afterVersionId, afterCursorState);
        }
        close() {
            this._isOpen = false;
        }
        open() {
            // cannot reopen
        }
        undo() {
            this._isOpen = false;
            for (const editStackElement of this._editStackElementsArr) {
                editStackElement.undo();
            }
        }
        redo() {
            for (const editStackElement of this._editStackElementsArr) {
                editStackElement.redo();
            }
        }
        heapSize(resource) {
            const key = uriGetComparisonKey(resource);
            if (this._editStackElementsMap.has(key)) {
                const editStackElement = this._editStackElementsMap.get(key);
                return editStackElement.heapSize();
            }
            return 0;
        }
        split() {
            return this._editStackElementsArr;
        }
        toString() {
            const result = [];
            for (const editStackElement of this._editStackElementsArr) {
                result.push(`${(0, resources_1.basename)(editStackElement.resource)}: ${editStackElement}`);
            }
            return `{${result.join(', ')}}`;
        }
    }
    exports.MultiModelEditStackElement = MultiModelEditStackElement;
    function getModelEOL(model) {
        const eol = model.getEOL();
        if (eol === '\n') {
            return 0 /* EndOfLineSequence.LF */;
        }
        else {
            return 1 /* EndOfLineSequence.CRLF */;
        }
    }
    function isEditStackElement(element) {
        if (!element) {
            return false;
        }
        return ((element instanceof SingleModelEditStackElement) || (element instanceof MultiModelEditStackElement));
    }
    class EditStack {
        constructor(model, undoRedoService) {
            this._model = model;
            this._undoRedoService = undoRedoService;
        }
        pushStackElement() {
            const lastElement = this._undoRedoService.getLastElement(this._model.uri);
            if (isEditStackElement(lastElement)) {
                lastElement.close();
            }
        }
        popStackElement() {
            const lastElement = this._undoRedoService.getLastElement(this._model.uri);
            if (isEditStackElement(lastElement)) {
                lastElement.open();
            }
        }
        clear() {
            this._undoRedoService.removeElements(this._model.uri);
        }
        _getOrCreateEditStackElement(beforeCursorState, group) {
            const lastElement = this._undoRedoService.getLastElement(this._model.uri);
            if (isEditStackElement(lastElement) && lastElement.canAppend(this._model)) {
                return lastElement;
            }
            const newElement = new SingleModelEditStackElement(nls.localize(697, "Typing"), 'undoredo.textBufferEdit', this._model, beforeCursorState);
            this._undoRedoService.pushElement(newElement, group);
            return newElement;
        }
        pushEOL(eol) {
            const editStackElement = this._getOrCreateEditStackElement(null, undefined);
            this._model.setEOL(eol);
            editStackElement.append(this._model, [], getModelEOL(this._model), this._model.getAlternativeVersionId(), null);
        }
        pushEditOperation(beforeCursorState, editOperations, cursorStateComputer, group) {
            const editStackElement = this._getOrCreateEditStackElement(beforeCursorState, group);
            const inverseEditOperations = this._model.applyEdits(editOperations, true);
            const afterCursorState = EditStack._computeCursorState(cursorStateComputer, inverseEditOperations);
            const textChanges = inverseEditOperations.map((op, index) => ({ index: index, textChange: op.textChange }));
            textChanges.sort((a, b) => {
                if (a.textChange.oldPosition === b.textChange.oldPosition) {
                    return a.index - b.index;
                }
                return a.textChange.oldPosition - b.textChange.oldPosition;
            });
            editStackElement.append(this._model, textChanges.map(op => op.textChange), getModelEOL(this._model), this._model.getAlternativeVersionId(), afterCursorState);
            return afterCursorState;
        }
        static _computeCursorState(cursorStateComputer, inverseEditOperations) {
            try {
                return cursorStateComputer ? cursorStateComputer(inverseEditOperations) : null;
            }
            catch (e) {
                (0, errors_1.onUnexpectedError)(e);
                return null;
            }
        }
    }
    exports.EditStack = EditStack;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[371/*vs/editor/common/model/pieceTreeTextBuffer/pieceTreeTextBuffer*/], __M([1/*require*/,0/*exports*/,6/*vs/base/common/event*/,11/*vs/base/common/strings*/,4/*vs/editor/common/core/range*/,40/*vs/editor/common/model*/,324/*vs/editor/common/model/pieceTreeTextBuffer/pieceTreeBase*/,145/*vs/editor/common/core/eolCounter*/,367/*vs/editor/common/core/textChange*/,2/*vs/base/common/lifecycle*/]), function (require, exports, event_1, strings, range_1, model_1, pieceTreeBase_1, eolCounter_1, textChange_1, lifecycle_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.PieceTreeTextBuffer = void 0;
    class PieceTreeTextBuffer extends lifecycle_1.Disposable {
        constructor(chunks, BOM, eol, containsRTL, containsUnusualLineTerminators, isBasicASCII, eolNormalized) {
            super();
            this._onDidChangeContent = this._register(new event_1.Emitter());
            this._BOM = BOM;
            this._mightContainNonBasicASCII = !isBasicASCII;
            this._mightContainRTL = containsRTL;
            this._mightContainUnusualLineTerminators = containsUnusualLineTerminators;
            this._pieceTree = new pieceTreeBase_1.PieceTreeBase(chunks, eol, eolNormalized);
        }
        mightContainRTL() {
            return this._mightContainRTL;
        }
        mightContainUnusualLineTerminators() {
            return this._mightContainUnusualLineTerminators;
        }
        resetMightContainUnusualLineTerminators() {
            this._mightContainUnusualLineTerminators = false;
        }
        mightContainNonBasicASCII() {
            return this._mightContainNonBasicASCII;
        }
        getBOM() {
            return this._BOM;
        }
        getEOL() {
            return this._pieceTree.getEOL();
        }
        createSnapshot(preserveBOM) {
            return this._pieceTree.createSnapshot(preserveBOM ? this._BOM : '');
        }
        getOffsetAt(lineNumber, column) {
            return this._pieceTree.getOffsetAt(lineNumber, column);
        }
        getPositionAt(offset) {
            return this._pieceTree.getPositionAt(offset);
        }
        getRangeAt(start, length) {
            const end = start + length;
            const startPosition = this.getPositionAt(start);
            const endPosition = this.getPositionAt(end);
            return new range_1.Range(startPosition.lineNumber, startPosition.column, endPosition.lineNumber, endPosition.column);
        }
        getValueInRange(range, eol = 0 /* EndOfLinePreference.TextDefined */) {
            if (range.isEmpty()) {
                return '';
            }
            const lineEnding = this._getEndOfLine(eol);
            return this._pieceTree.getValueInRange(range, lineEnding);
        }
        getValueLengthInRange(range, eol = 0 /* EndOfLinePreference.TextDefined */) {
            if (range.isEmpty()) {
                return 0;
            }
            if (range.startLineNumber === range.endLineNumber) {
                return (range.endColumn - range.startColumn);
            }
            const startOffset = this.getOffsetAt(range.startLineNumber, range.startColumn);
            const endOffset = this.getOffsetAt(range.endLineNumber, range.endColumn);
            // offsets use the text EOL, so we need to compensate for length differences
            // if the requested EOL doesn't match the text EOL
            let eolOffsetCompensation = 0;
            const desiredEOL = this._getEndOfLine(eol);
            const actualEOL = this.getEOL();
            if (desiredEOL.length !== actualEOL.length) {
                const delta = desiredEOL.length - actualEOL.length;
                const eolCount = range.endLineNumber - range.startLineNumber;
                eolOffsetCompensation = delta * eolCount;
            }
            return endOffset - startOffset + eolOffsetCompensation;
        }
        getCharacterCountInRange(range, eol = 0 /* EndOfLinePreference.TextDefined */) {
            if (this._mightContainNonBasicASCII) {
                // we must count by iterating
                let result = 0;
                const fromLineNumber = range.startLineNumber;
                const toLineNumber = range.endLineNumber;
                for (let lineNumber = fromLineNumber; lineNumber <= toLineNumber; lineNumber++) {
                    const lineContent = this.getLineContent(lineNumber);
                    const fromOffset = (lineNumber === fromLineNumber ? range.startColumn - 1 : 0);
                    const toOffset = (lineNumber === toLineNumber ? range.endColumn - 1 : lineContent.length);
                    for (let offset = fromOffset; offset < toOffset; offset++) {
                        if (strings.isHighSurrogate(lineContent.charCodeAt(offset))) {
                            result = result + 1;
                            offset = offset + 1;
                        }
                        else {
                            result = result + 1;
                        }
                    }
                }
                result += this._getEndOfLine(eol).length * (toLineNumber - fromLineNumber);
                return result;
            }
            return this.getValueLengthInRange(range, eol);
        }
        getLength() {
            return this._pieceTree.getLength();
        }
        getLineCount() {
            return this._pieceTree.getLineCount();
        }
        getLinesContent() {
            return this._pieceTree.getLinesContent();
        }
        getLineContent(lineNumber) {
            return this._pieceTree.getLineContent(lineNumber);
        }
        getLineCharCode(lineNumber, index) {
            return this._pieceTree.getLineCharCode(lineNumber, index);
        }
        getLineLength(lineNumber) {
            return this._pieceTree.getLineLength(lineNumber);
        }
        getLineFirstNonWhitespaceColumn(lineNumber) {
            const result = strings.firstNonWhitespaceIndex(this.getLineContent(lineNumber));
            if (result === -1) {
                return 0;
            }
            return result + 1;
        }
        getLineLastNonWhitespaceColumn(lineNumber) {
            const result = strings.lastNonWhitespaceIndex(this.getLineContent(lineNumber));
            if (result === -1) {
                return 0;
            }
            return result + 2;
        }
        _getEndOfLine(eol) {
            switch (eol) {
                case 1 /* EndOfLinePreference.LF */:
                    return '\n';
                case 2 /* EndOfLinePreference.CRLF */:
                    return '\r\n';
                case 0 /* EndOfLinePreference.TextDefined */:
                    return this.getEOL();
                default:
                    throw new Error('Unknown EOL preference');
            }
        }
        setEOL(newEOL) {
            this._pieceTree.setEOL(newEOL);
        }
        applyEdits(rawOperations, recordTrimAutoWhitespace, computeUndoEdits) {
            let mightContainRTL = this._mightContainRTL;
            let mightContainUnusualLineTerminators = this._mightContainUnusualLineTerminators;
            let mightContainNonBasicASCII = this._mightContainNonBasicASCII;
            let canReduceOperations = true;
            let operations = [];
            for (let i = 0; i < rawOperations.length; i++) {
                const op = rawOperations[i];
                if (canReduceOperations && op._isTracked) {
                    canReduceOperations = false;
                }
                const validatedRange = op.range;
                if (op.text) {
                    let textMightContainNonBasicASCII = true;
                    if (!mightContainNonBasicASCII) {
                        textMightContainNonBasicASCII = !strings.isBasicASCII(op.text);
                        mightContainNonBasicASCII = textMightContainNonBasicASCII;
                    }
                    if (!mightContainRTL && textMightContainNonBasicASCII) {
                        // check if the new inserted text contains RTL
                        mightContainRTL = strings.containsRTL(op.text);
                    }
                    if (!mightContainUnusualLineTerminators && textMightContainNonBasicASCII) {
                        // check if the new inserted text contains unusual line terminators
                        mightContainUnusualLineTerminators = strings.containsUnusualLineTerminators(op.text);
                    }
                }
                let validText = '';
                let eolCount = 0;
                let firstLineLength = 0;
                let lastLineLength = 0;
                if (op.text) {
                    let strEOL;
                    [eolCount, firstLineLength, lastLineLength, strEOL] = (0, eolCounter_1.countEOL)(op.text);
                    const bufferEOL = this.getEOL();
                    const expectedStrEOL = (bufferEOL === '\r\n' ? 2 /* StringEOL.CRLF */ : 1 /* StringEOL.LF */);
                    if (strEOL === 0 /* StringEOL.Unknown */ || strEOL === expectedStrEOL) {
                        validText = op.text;
                    }
                    else {
                        validText = op.text.replace(/\r\n|\r|\n/g, bufferEOL);
                    }
                }
                operations[i] = {
                    sortIndex: i,
                    identifier: op.identifier || null,
                    range: validatedRange,
                    rangeOffset: this.getOffsetAt(validatedRange.startLineNumber, validatedRange.startColumn),
                    rangeLength: this.getValueLengthInRange(validatedRange),
                    text: validText,
                    eolCount: eolCount,
                    firstLineLength: firstLineLength,
                    lastLineLength: lastLineLength,
                    forceMoveMarkers: Boolean(op.forceMoveMarkers),
                    isAutoWhitespaceEdit: op.isAutoWhitespaceEdit || false
                };
            }
            // Sort operations ascending
            operations.sort(PieceTreeTextBuffer._sortOpsAscending);
            let hasTouchingRanges = false;
            for (let i = 0, count = operations.length - 1; i < count; i++) {
                const rangeEnd = operations[i].range.getEndPosition();
                const nextRangeStart = operations[i + 1].range.getStartPosition();
                if (nextRangeStart.isBeforeOrEqual(rangeEnd)) {
                    if (nextRangeStart.isBefore(rangeEnd)) {
                        // overlapping ranges
                        throw new Error('Overlapping ranges are not allowed!');
                    }
                    hasTouchingRanges = true;
                }
            }
            if (canReduceOperations) {
                operations = this._reduceOperations(operations);
            }
            // Delta encode operations
            const reverseRanges = (computeUndoEdits || recordTrimAutoWhitespace ? PieceTreeTextBuffer._getInverseEditRanges(operations) : []);
            const newTrimAutoWhitespaceCandidates = [];
            if (recordTrimAutoWhitespace) {
                for (let i = 0; i < operations.length; i++) {
                    const op = operations[i];
                    const reverseRange = reverseRanges[i];
                    if (op.isAutoWhitespaceEdit && op.range.isEmpty()) {
                        // Record already the future line numbers that might be auto whitespace removal candidates on next edit
                        for (let lineNumber = reverseRange.startLineNumber; lineNumber <= reverseRange.endLineNumber; lineNumber++) {
                            let currentLineContent = '';
                            if (lineNumber === reverseRange.startLineNumber) {
                                currentLineContent = this.getLineContent(op.range.startLineNumber);
                                if (strings.firstNonWhitespaceIndex(currentLineContent) !== -1) {
                                    continue;
                                }
                            }
                            newTrimAutoWhitespaceCandidates.push({ lineNumber: lineNumber, oldContent: currentLineContent });
                        }
                    }
                }
            }
            let reverseOperations = null;
            if (computeUndoEdits) {
                let reverseRangeDeltaOffset = 0;
                reverseOperations = [];
                for (let i = 0; i < operations.length; i++) {
                    const op = operations[i];
                    const reverseRange = reverseRanges[i];
                    const bufferText = this.getValueInRange(op.range);
                    const reverseRangeOffset = op.rangeOffset + reverseRangeDeltaOffset;
                    reverseRangeDeltaOffset += (op.text.length - bufferText.length);
                    reverseOperations[i] = {
                        sortIndex: op.sortIndex,
                        identifier: op.identifier,
                        range: reverseRange,
                        text: bufferText,
                        textChange: new textChange_1.TextChange(op.rangeOffset, bufferText, reverseRangeOffset, op.text)
                    };
                }
                // Can only sort reverse operations when the order is not significant
                if (!hasTouchingRanges) {
                    reverseOperations.sort((a, b) => a.sortIndex - b.sortIndex);
                }
            }
            this._mightContainRTL = mightContainRTL;
            this._mightContainUnusualLineTerminators = mightContainUnusualLineTerminators;
            this._mightContainNonBasicASCII = mightContainNonBasicASCII;
            const contentChanges = this._doApplyEdits(operations);
            let trimAutoWhitespaceLineNumbers = null;
            if (recordTrimAutoWhitespace && newTrimAutoWhitespaceCandidates.length > 0) {
                // sort line numbers auto whitespace removal candidates for next edit descending
                newTrimAutoWhitespaceCandidates.sort((a, b) => b.lineNumber - a.lineNumber);
                trimAutoWhitespaceLineNumbers = [];
                for (let i = 0, len = newTrimAutoWhitespaceCandidates.length; i < len; i++) {
                    const lineNumber = newTrimAutoWhitespaceCandidates[i].lineNumber;
                    if (i > 0 && newTrimAutoWhitespaceCandidates[i - 1].lineNumber === lineNumber) {
                        // Do not have the same line number twice
                        continue;
                    }
                    const prevContent = newTrimAutoWhitespaceCandidates[i].oldContent;
                    const lineContent = this.getLineContent(lineNumber);
                    if (lineContent.length === 0 || lineContent === prevContent || strings.firstNonWhitespaceIndex(lineContent) !== -1) {
                        continue;
                    }
                    trimAutoWhitespaceLineNumbers.push(lineNumber);
                }
            }
            this._onDidChangeContent.fire();
            return new model_1.ApplyEditsResult(reverseOperations, contentChanges, trimAutoWhitespaceLineNumbers);
        }
        /**
         * Transform operations such that they represent the same logic edit,
         * but that they also do not cause OOM crashes.
         */
        _reduceOperations(operations) {
            if (operations.length < 1000) {
                // We know from empirical testing that a thousand edits work fine regardless of their shape.
                return operations;
            }
            // At one point, due to how events are emitted and how each operation is handled,
            // some operations can trigger a high amount of temporary string allocations,
            // that will immediately get edited again.
            // e.g. a formatter inserting ridiculous ammounts of \n on a model with a single line
            // Therefore, the strategy is to collapse all the operations into a huge single edit operation
            return [this._toSingleEditOperation(operations)];
        }
        _toSingleEditOperation(operations) {
            let forceMoveMarkers = false;
            const firstEditRange = operations[0].range;
            const lastEditRange = operations[operations.length - 1].range;
            const entireEditRange = new range_1.Range(firstEditRange.startLineNumber, firstEditRange.startColumn, lastEditRange.endLineNumber, lastEditRange.endColumn);
            let lastEndLineNumber = firstEditRange.startLineNumber;
            let lastEndColumn = firstEditRange.startColumn;
            const result = [];
            for (let i = 0, len = operations.length; i < len; i++) {
                const operation = operations[i];
                const range = operation.range;
                forceMoveMarkers = forceMoveMarkers || operation.forceMoveMarkers;
                // (1) -- Push old text
                result.push(this.getValueInRange(new range_1.Range(lastEndLineNumber, lastEndColumn, range.startLineNumber, range.startColumn)));
                // (2) -- Push new text
                if (operation.text.length > 0) {
                    result.push(operation.text);
                }
                lastEndLineNumber = range.endLineNumber;
                lastEndColumn = range.endColumn;
            }
            const text = result.join('');
            const [eolCount, firstLineLength, lastLineLength] = (0, eolCounter_1.countEOL)(text);
            return {
                sortIndex: 0,
                identifier: operations[0].identifier,
                range: entireEditRange,
                rangeOffset: this.getOffsetAt(entireEditRange.startLineNumber, entireEditRange.startColumn),
                rangeLength: this.getValueLengthInRange(entireEditRange, 0 /* EndOfLinePreference.TextDefined */),
                text: text,
                eolCount: eolCount,
                firstLineLength: firstLineLength,
                lastLineLength: lastLineLength,
                forceMoveMarkers: forceMoveMarkers,
                isAutoWhitespaceEdit: false
            };
        }
        _doApplyEdits(operations) {
            operations.sort(PieceTreeTextBuffer._sortOpsDescending);
            const contentChanges = [];
            // operations are from bottom to top
            for (let i = 0; i < operations.length; i++) {
                const op = operations[i];
                const startLineNumber = op.range.startLineNumber;
                const startColumn = op.range.startColumn;
                const endLineNumber = op.range.endLineNumber;
                const endColumn = op.range.endColumn;
                if (startLineNumber === endLineNumber && startColumn === endColumn && op.text.length === 0) {
                    // no-op
                    continue;
                }
                if (op.text) {
                    // replacement
                    this._pieceTree.delete(op.rangeOffset, op.rangeLength);
                    this._pieceTree.insert(op.rangeOffset, op.text, true);
                }
                else {
                    // deletion
                    this._pieceTree.delete(op.rangeOffset, op.rangeLength);
                }
                const contentChangeRange = new range_1.Range(startLineNumber, startColumn, endLineNumber, endColumn);
                contentChanges.push({
                    range: contentChangeRange,
                    rangeLength: op.rangeLength,
                    text: op.text,
                    rangeOffset: op.rangeOffset,
                    forceMoveMarkers: op.forceMoveMarkers
                });
            }
            return contentChanges;
        }
        findMatchesLineByLine(searchRange, searchData, captureMatches, limitResultCount) {
            return this._pieceTree.findMatchesLineByLine(searchRange, searchData, captureMatches, limitResultCount);
        }
        /**
         * Assumes `operations` are validated and sorted ascending
         */
        static _getInverseEditRanges(operations) {
            const result = [];
            let prevOpEndLineNumber = 0;
            let prevOpEndColumn = 0;
            let prevOp = null;
            for (let i = 0, len = operations.length; i < len; i++) {
                const op = operations[i];
                let startLineNumber;
                let startColumn;
                if (prevOp) {
                    if (prevOp.range.endLineNumber === op.range.startLineNumber) {
                        startLineNumber = prevOpEndLineNumber;
                        startColumn = prevOpEndColumn + (op.range.startColumn - prevOp.range.endColumn);
                    }
                    else {
                        startLineNumber = prevOpEndLineNumber + (op.range.startLineNumber - prevOp.range.endLineNumber);
                        startColumn = op.range.startColumn;
                    }
                }
                else {
                    startLineNumber = op.range.startLineNumber;
                    startColumn = op.range.startColumn;
                }
                let resultRange;
                if (op.text.length > 0) {
                    // the operation inserts something
                    const lineCount = op.eolCount + 1;
                    if (lineCount === 1) {
                        // single line insert
                        resultRange = new range_1.Range(startLineNumber, startColumn, startLineNumber, startColumn + op.firstLineLength);
                    }
                    else {
                        // multi line insert
                        resultRange = new range_1.Range(startLineNumber, startColumn, startLineNumber + lineCount - 1, op.lastLineLength + 1);
                    }
                }
                else {
                    // There is nothing to insert
                    resultRange = new range_1.Range(startLineNumber, startColumn, startLineNumber, startColumn);
                }
                prevOpEndLineNumber = resultRange.endLineNumber;
                prevOpEndColumn = resultRange.endColumn;
                result.push(resultRange);
                prevOp = op;
            }
            return result;
        }
        static _sortOpsAscending(a, b) {
            const r = range_1.Range.compareRangesUsingEnds(a.range, b.range);
            if (r === 0) {
                return a.sortIndex - b.sortIndex;
            }
            return r;
        }
        static _sortOpsDescending(a, b) {
            const r = range_1.Range.compareRangesUsingEnds(a.range, b.range);
            if (r === 0) {
                return b.sortIndex - a.sortIndex;
            }
            return -r;
        }
    }
    exports.PieceTreeTextBuffer = PieceTreeTextBuffer;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[662/*vs/editor/common/model/pieceTreeTextBuffer/pieceTreeTextBufferBuilder*/], __M([1/*require*/,0/*exports*/,11/*vs/base/common/strings*/,324/*vs/editor/common/model/pieceTreeTextBuffer/pieceTreeBase*/,371/*vs/editor/common/model/pieceTreeTextBuffer/pieceTreeTextBuffer*/]), function (require, exports, strings, pieceTreeBase_1, pieceTreeTextBuffer_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.PieceTreeTextBufferBuilder = void 0;
    class PieceTreeTextBufferFactory {
        constructor(_chunks, _bom, _cr, _lf, _crlf, _containsRTL, _containsUnusualLineTerminators, _isBasicASCII, _normalizeEOL) {
            this._chunks = _chunks;
            this._bom = _bom;
            this._cr = _cr;
            this._lf = _lf;
            this._crlf = _crlf;
            this._containsRTL = _containsRTL;
            this._containsUnusualLineTerminators = _containsUnusualLineTerminators;
            this._isBasicASCII = _isBasicASCII;
            this._normalizeEOL = _normalizeEOL;
        }
        _getEOL(defaultEOL) {
            const totalEOLCount = this._cr + this._lf + this._crlf;
            const totalCRCount = this._cr + this._crlf;
            if (totalEOLCount === 0) {
                // This is an empty file or a file with precisely one line
                return (defaultEOL === 1 /* DefaultEndOfLine.LF */ ? '\n' : '\r\n');
            }
            if (totalCRCount > totalEOLCount / 2) {
                // More than half of the file contains \r\n ending lines
                return '\r\n';
            }
            // At least one line more ends in \n
            return '\n';
        }
        create(defaultEOL) {
            const eol = this._getEOL(defaultEOL);
            const chunks = this._chunks;
            if (this._normalizeEOL &&
                ((eol === '\r\n' && (this._cr > 0 || this._lf > 0))
                    || (eol === '\n' && (this._cr > 0 || this._crlf > 0)))) {
                // Normalize pieces
                for (let i = 0, len = chunks.length; i < len; i++) {
                    const str = chunks[i].buffer.replace(/\r\n|\r|\n/g, eol);
                    const newLineStart = (0, pieceTreeBase_1.createLineStartsFast)(str);
                    chunks[i] = new pieceTreeBase_1.StringBuffer(str, newLineStart);
                }
            }
            const textBuffer = new pieceTreeTextBuffer_1.PieceTreeTextBuffer(chunks, this._bom, eol, this._containsRTL, this._containsUnusualLineTerminators, this._isBasicASCII, this._normalizeEOL);
            return { textBuffer: textBuffer, disposable: textBuffer };
        }
    }
    class PieceTreeTextBufferBuilder {
        constructor() {
            this.chunks = [];
            this.BOM = '';
            this._hasPreviousChar = false;
            this._previousChar = 0;
            this._tmpLineStarts = [];
            this.cr = 0;
            this.lf = 0;
            this.crlf = 0;
            this.containsRTL = false;
            this.containsUnusualLineTerminators = false;
            this.isBasicASCII = true;
        }
        acceptChunk(chunk) {
            if (chunk.length === 0) {
                return;
            }
            if (this.chunks.length === 0) {
                if (strings.startsWithUTF8BOM(chunk)) {
                    this.BOM = strings.UTF8_BOM_CHARACTER;
                    chunk = chunk.substr(1);
                }
            }
            const lastChar = chunk.charCodeAt(chunk.length - 1);
            if (lastChar === 13 /* CharCode.CarriageReturn */ || (lastChar >= 0xD800 && lastChar <= 0xDBFF)) {
                // last character is \r or a high surrogate => keep it back
                this._acceptChunk1(chunk.substr(0, chunk.length - 1), false);
                this._hasPreviousChar = true;
                this._previousChar = lastChar;
            }
            else {
                this._acceptChunk1(chunk, false);
                this._hasPreviousChar = false;
                this._previousChar = lastChar;
            }
        }
        _acceptChunk1(chunk, allowEmptyStrings) {
            if (!allowEmptyStrings && chunk.length === 0) {
                // Nothing to do
                return;
            }
            if (this._hasPreviousChar) {
                this._acceptChunk2(String.fromCharCode(this._previousChar) + chunk);
            }
            else {
                this._acceptChunk2(chunk);
            }
        }
        _acceptChunk2(chunk) {
            const lineStarts = (0, pieceTreeBase_1.createLineStarts)(this._tmpLineStarts, chunk);
            this.chunks.push(new pieceTreeBase_1.StringBuffer(chunk, lineStarts.lineStarts));
            this.cr += lineStarts.cr;
            this.lf += lineStarts.lf;
            this.crlf += lineStarts.crlf;
            if (!lineStarts.isBasicASCII) {
                // this chunk contains non basic ASCII characters
                this.isBasicASCII = false;
                if (!this.containsRTL) {
                    this.containsRTL = strings.containsRTL(chunk);
                }
                if (!this.containsUnusualLineTerminators) {
                    this.containsUnusualLineTerminators = strings.containsUnusualLineTerminators(chunk);
                }
            }
        }
        finish(normalizeEOL = true) {
            this._finish();
            return new PieceTreeTextBufferFactory(this.chunks, this.BOM, this.cr, this.lf, this.crlf, this.containsRTL, this.containsUnusualLineTerminators, this.isBasicASCII, normalizeEOL);
        }
        _finish() {
            if (this.chunks.length === 0) {
                this._acceptChunk1('', true);
            }
            if (this._hasPreviousChar) {
                this._hasPreviousChar = false;
                // recreate last chunk
                const lastChunk = this.chunks[this.chunks.length - 1];
                lastChunk.buffer += String.fromCharCode(this._previousChar);
                const newLineStarts = (0, pieceTreeBase_1.createLineStartsFast)(lastChunk.buffer);
                lastChunk.lineStarts = newLineStarts;
                if (this._previousChar === 13 /* CharCode.CarriageReturn */) {
                    this.cr++;
                }
            }
        }
    }
    exports.PieceTreeTextBufferBuilder = PieceTreeTextBufferBuilder;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[663/*vs/editor/common/model/textModelTokens*/], __M([1/*require*/,0/*exports*/,14/*vs/base/common/async*/,8/*vs/base/common/errors*/,16/*vs/base/common/platform*/,54/*vs/base/common/stopwatch*/,145/*vs/editor/common/core/eolCounter*/,55/*vs/editor/common/core/lineRange*/,68/*vs/editor/common/core/offsetRange*/,177/*vs/editor/common/languages/nullTokenize*/,576/*vs/editor/common/model/fixedArray*/,330/*vs/editor/common/tokens/contiguousMultilineTokensBuilder*/,83/*vs/editor/common/tokens/lineTokens*/]), function (require, exports, async_1, errors_1, platform_1, stopwatch_1, eolCounter_1, lineRange_1, offsetRange_1, nullTokenize_1, fixedArray_1, contiguousMultilineTokensBuilder_1, lineTokens_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DefaultBackgroundTokenizer = exports.RangePriorityQueueImpl = exports.TokenizationStateStore = exports.TrackingTokenizationStateStore = exports.TokenizerWithStateStoreAndTextModel = exports.TokenizerWithStateStore = void 0;
    class TokenizerWithStateStore {
        constructor(lineCount, tokenizationSupport) {
            this.tokenizationSupport = tokenizationSupport;
            this.initialState = this.tokenizationSupport.getInitialState();
            this.store = new TrackingTokenizationStateStore(lineCount);
        }
        getStartState(lineNumber) {
            return this.store.getStartState(lineNumber, this.initialState);
        }
        getFirstInvalidLine() {
            return this.store.getFirstInvalidLine(this.initialState);
        }
    }
    exports.TokenizerWithStateStore = TokenizerWithStateStore;
    class TokenizerWithStateStoreAndTextModel extends TokenizerWithStateStore {
        constructor(lineCount, tokenizationSupport, _textModel, _languageIdCodec) {
            super(lineCount, tokenizationSupport);
            this._textModel = _textModel;
            this._languageIdCodec = _languageIdCodec;
        }
        updateTokensUntilLine(builder, lineNumber) {
            const languageId = this._textModel.getLanguageId();
            while (true) {
                const lineToTokenize = this.getFirstInvalidLine();
                if (!lineToTokenize || lineToTokenize.lineNumber > lineNumber) {
                    break;
                }
                const text = this._textModel.getLineContent(lineToTokenize.lineNumber);
                const r = safeTokenize(this._languageIdCodec, languageId, this.tokenizationSupport, text, true, lineToTokenize.startState);
                builder.add(lineToTokenize.lineNumber, r.tokens);
                this.store.setEndState(lineToTokenize.lineNumber, r.endState);
            }
        }
        /** assumes state is up to date */
        getTokenTypeIfInsertingCharacter(position, character) {
            // TODO@hediet: use tokenizeLineWithEdit
            const lineStartState = this.getStartState(position.lineNumber);
            if (!lineStartState) {
                return 0 /* StandardTokenType.Other */;
            }
            const languageId = this._textModel.getLanguageId();
            const lineContent = this._textModel.getLineContent(position.lineNumber);
            // Create the text as if `character` was inserted
            const text = (lineContent.substring(0, position.column - 1)
                + character
                + lineContent.substring(position.column - 1));
            const r = safeTokenize(this._languageIdCodec, languageId, this.tokenizationSupport, text, true, lineStartState);
            const lineTokens = new lineTokens_1.LineTokens(r.tokens, text, this._languageIdCodec);
            if (lineTokens.getCount() === 0) {
                return 0 /* StandardTokenType.Other */;
            }
            const tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
            return lineTokens.getStandardTokenType(tokenIndex);
        }
        /** assumes state is up to date */
        tokenizeLineWithEdit(position, length, newText) {
            const lineNumber = position.lineNumber;
            const column = position.column;
            const lineStartState = this.getStartState(lineNumber);
            if (!lineStartState) {
                return null;
            }
            const curLineContent = this._textModel.getLineContent(lineNumber);
            const newLineContent = curLineContent.substring(0, column - 1)
                + newText + curLineContent.substring(column - 1 + length);
            const languageId = this._textModel.getLanguageIdAtPosition(lineNumber, 0);
            const result = safeTokenize(this._languageIdCodec, languageId, this.tokenizationSupport, newLineContent, true, lineStartState);
            const lineTokens = new lineTokens_1.LineTokens(result.tokens, newLineContent, this._languageIdCodec);
            return lineTokens;
        }
        hasAccurateTokensForLine(lineNumber) {
            const firstInvalidLineNumber = this.store.getFirstInvalidEndStateLineNumberOrMax();
            return (lineNumber < firstInvalidLineNumber);
        }
        isCheapToTokenize(lineNumber) {
            const firstInvalidLineNumber = this.store.getFirstInvalidEndStateLineNumberOrMax();
            if (lineNumber < firstInvalidLineNumber) {
                return true;
            }
            if (lineNumber === firstInvalidLineNumber
                && this._textModel.getLineLength(lineNumber) < 2048 /* Constants.CHEAP_TOKENIZATION_LENGTH_LIMIT */) {
                return true;
            }
            return false;
        }
        /**
         * The result is not cached.
         */
        tokenizeHeuristically(builder, startLineNumber, endLineNumber) {
            if (endLineNumber <= this.store.getFirstInvalidEndStateLineNumberOrMax()) {
                // nothing to do
                return { heuristicTokens: false };
            }
            if (startLineNumber <= this.store.getFirstInvalidEndStateLineNumberOrMax()) {
                // tokenization has reached the viewport start...
                this.updateTokensUntilLine(builder, endLineNumber);
                return { heuristicTokens: false };
            }
            let state = this.guessStartState(startLineNumber);
            const languageId = this._textModel.getLanguageId();
            for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
                const text = this._textModel.getLineContent(lineNumber);
                const r = safeTokenize(this._languageIdCodec, languageId, this.tokenizationSupport, text, true, state);
                builder.add(lineNumber, r.tokens);
                state = r.endState;
            }
            return { heuristicTokens: true };
        }
        guessStartState(lineNumber) {
            let nonWhitespaceColumn = this._textModel.getLineFirstNonWhitespaceColumn(lineNumber);
            const likelyRelevantLines = [];
            let initialState = null;
            for (let i = lineNumber - 1; nonWhitespaceColumn > 1 && i >= 1; i--) {
                const newNonWhitespaceIndex = this._textModel.getLineFirstNonWhitespaceColumn(i);
                // Ignore lines full of whitespace
                if (newNonWhitespaceIndex === 0) {
                    continue;
                }
                if (newNonWhitespaceIndex < nonWhitespaceColumn) {
                    likelyRelevantLines.push(this._textModel.getLineContent(i));
                    nonWhitespaceColumn = newNonWhitespaceIndex;
                    initialState = this.getStartState(i);
                    if (initialState) {
                        break;
                    }
                }
            }
            if (!initialState) {
                initialState = this.tokenizationSupport.getInitialState();
            }
            likelyRelevantLines.reverse();
            const languageId = this._textModel.getLanguageId();
            let state = initialState;
            for (const line of likelyRelevantLines) {
                const r = safeTokenize(this._languageIdCodec, languageId, this.tokenizationSupport, line, false, state);
                state = r.endState;
            }
            return state;
        }
    }
    exports.TokenizerWithStateStoreAndTextModel = TokenizerWithStateStoreAndTextModel;
    /**
     * **Invariant:**
     * If the text model is retokenized from line 1 to {@link getFirstInvalidEndStateLineNumber}() - 1,
     * then the recomputed end state for line l will be equal to {@link getEndState}(l).
     */
    class TrackingTokenizationStateStore {
        constructor(lineCount) {
            this.lineCount = lineCount;
            this._tokenizationStateStore = new TokenizationStateStore();
            this._invalidEndStatesLineNumbers = new RangePriorityQueueImpl();
            this._invalidEndStatesLineNumbers.addRange(new offsetRange_1.OffsetRange(1, lineCount + 1));
        }
        getEndState(lineNumber) {
            return this._tokenizationStateStore.getEndState(lineNumber);
        }
        /**
         * @returns if the end state has changed.
         */
        setEndState(lineNumber, state) {
            if (!state) {
                throw new errors_1.BugIndicatingError('Cannot set null/undefined state');
            }
            this._invalidEndStatesLineNumbers.delete(lineNumber);
            const r = this._tokenizationStateStore.setEndState(lineNumber, state);
            if (r && lineNumber < this.lineCount) {
                // because the state changed, we cannot trust the next state anymore and have to invalidate it.
                this._invalidEndStatesLineNumbers.addRange(new offsetRange_1.OffsetRange(lineNumber + 1, lineNumber + 2));
            }
            return r;
        }
        acceptChange(range, newLineCount) {
            this.lineCount += newLineCount - range.length;
            this._tokenizationStateStore.acceptChange(range, newLineCount);
            this._invalidEndStatesLineNumbers.addRangeAndResize(new offsetRange_1.OffsetRange(range.startLineNumber, range.endLineNumberExclusive), newLineCount);
        }
        acceptChanges(changes) {
            for (const c of changes) {
                const [eolCount] = (0, eolCounter_1.countEOL)(c.text);
                this.acceptChange(new lineRange_1.LineRange(c.range.startLineNumber, c.range.endLineNumber + 1), eolCount + 1);
            }
        }
        invalidateEndStateRange(range) {
            this._invalidEndStatesLineNumbers.addRange(new offsetRange_1.OffsetRange(range.startLineNumber, range.endLineNumberExclusive));
        }
        getFirstInvalidEndStateLineNumber() { return this._invalidEndStatesLineNumbers.min; }
        getFirstInvalidEndStateLineNumberOrMax() {
            return this.getFirstInvalidEndStateLineNumber() || Number.MAX_SAFE_INTEGER;
        }
        allStatesValid() { return this._invalidEndStatesLineNumbers.min === null; }
        getStartState(lineNumber, initialState) {
            if (lineNumber === 1) {
                return initialState;
            }
            return this.getEndState(lineNumber - 1);
        }
        getFirstInvalidLine(initialState) {
            const lineNumber = this.getFirstInvalidEndStateLineNumber();
            if (lineNumber === null) {
                return null;
            }
            const startState = this.getStartState(lineNumber, initialState);
            if (!startState) {
                throw new errors_1.BugIndicatingError('Start state must be defined');
            }
            return { lineNumber, startState };
        }
    }
    exports.TrackingTokenizationStateStore = TrackingTokenizationStateStore;
    class TokenizationStateStore {
        constructor() {
            this._lineEndStates = new fixedArray_1.FixedArray(null);
        }
        getEndState(lineNumber) {
            return this._lineEndStates.get(lineNumber);
        }
        setEndState(lineNumber, state) {
            const oldState = this._lineEndStates.get(lineNumber);
            if (oldState && oldState.equals(state)) {
                return false;
            }
            this._lineEndStates.set(lineNumber, state);
            return true;
        }
        acceptChange(range, newLineCount) {
            let length = range.length;
            if (newLineCount > 0 && length > 0) {
                // Keep the last state, even though it is unrelated.
                // But if the new state happens to agree with this last state, then we know we can stop tokenizing.
                length--;
                newLineCount--;
            }
            this._lineEndStates.replace(range.startLineNumber, length, newLineCount);
        }
    }
    exports.TokenizationStateStore = TokenizationStateStore;
    class RangePriorityQueueImpl {
        constructor() {
            this._ranges = [];
        }
        get min() {
            if (this._ranges.length === 0) {
                return null;
            }
            return this._ranges[0].start;
        }
        delete(value) {
            const idx = this._ranges.findIndex(r => r.contains(value));
            if (idx !== -1) {
                const range = this._ranges[idx];
                if (range.start === value) {
                    if (range.endExclusive === value + 1) {
                        this._ranges.splice(idx, 1);
                    }
                    else {
                        this._ranges[idx] = new offsetRange_1.OffsetRange(value + 1, range.endExclusive);
                    }
                }
                else {
                    if (range.endExclusive === value + 1) {
                        this._ranges[idx] = new offsetRange_1.OffsetRange(range.start, value);
                    }
                    else {
                        this._ranges.splice(idx, 1, new offsetRange_1.OffsetRange(range.start, value), new offsetRange_1.OffsetRange(value + 1, range.endExclusive));
                    }
                }
            }
        }
        addRange(range) {
            offsetRange_1.OffsetRange.addRange(range, this._ranges);
        }
        addRangeAndResize(range, newLength) {
            let idxFirstMightBeIntersecting = 0;
            while (!(idxFirstMightBeIntersecting >= this._ranges.length || range.start <= this._ranges[idxFirstMightBeIntersecting].endExclusive)) {
                idxFirstMightBeIntersecting++;
            }
            let idxFirstIsAfter = idxFirstMightBeIntersecting;
            while (!(idxFirstIsAfter >= this._ranges.length || range.endExclusive < this._ranges[idxFirstIsAfter].start)) {
                idxFirstIsAfter++;
            }
            const delta = newLength - range.length;
            for (let i = idxFirstIsAfter; i < this._ranges.length; i++) {
                this._ranges[i] = this._ranges[i].delta(delta);
            }
            if (idxFirstMightBeIntersecting === idxFirstIsAfter) {
                const newRange = new offsetRange_1.OffsetRange(range.start, range.start + newLength);
                if (!newRange.isEmpty) {
                    this._ranges.splice(idxFirstMightBeIntersecting, 0, newRange);
                }
            }
            else {
                const start = Math.min(range.start, this._ranges[idxFirstMightBeIntersecting].start);
                const endEx = Math.max(range.endExclusive, this._ranges[idxFirstIsAfter - 1].endExclusive);
                const newRange = new offsetRange_1.OffsetRange(start, endEx + delta);
                if (!newRange.isEmpty) {
                    this._ranges.splice(idxFirstMightBeIntersecting, idxFirstIsAfter - idxFirstMightBeIntersecting, newRange);
                }
                else {
                    this._ranges.splice(idxFirstMightBeIntersecting, idxFirstIsAfter - idxFirstMightBeIntersecting);
                }
            }
        }
        toString() {
            return this._ranges.map(r => r.toString()).join(' + ');
        }
    }
    exports.RangePriorityQueueImpl = RangePriorityQueueImpl;
    function safeTokenize(languageIdCodec, languageId, tokenizationSupport, text, hasEOL, state) {
        let r = null;
        if (tokenizationSupport) {
            try {
                r = tokenizationSupport.tokenizeEncoded(text, hasEOL, state.clone());
            }
            catch (e) {
                (0, errors_1.onUnexpectedError)(e);
            }
        }
        if (!r) {
            r = (0, nullTokenize_1.nullTokenizeEncoded)(languageIdCodec.encodeLanguageId(languageId), state);
        }
        lineTokens_1.LineTokens.convertToEndOffset(r.tokens, text.length);
        return r;
    }
    class DefaultBackgroundTokenizer {
        constructor(_tokenizerWithStateStore, _backgroundTokenStore) {
            this._tokenizerWithStateStore = _tokenizerWithStateStore;
            this._backgroundTokenStore = _backgroundTokenStore;
            this._isDisposed = false;
            this._isScheduled = false;
        }
        dispose() {
            this._isDisposed = true;
        }
        handleChanges() {
            this._beginBackgroundTokenization();
        }
        _beginBackgroundTokenization() {
            if (this._isScheduled || !this._tokenizerWithStateStore._textModel.isAttachedToEditor() || !this._hasLinesToTokenize()) {
                return;
            }
            this._isScheduled = true;
            (0, async_1.runWhenGlobalIdle)((deadline) => {
                this._isScheduled = false;
                this._backgroundTokenizeWithDeadline(deadline);
            });
        }
        /**
         * Tokenize until the deadline occurs, but try to yield every 1-2ms.
         */
        _backgroundTokenizeWithDeadline(deadline) {
            // Read the time remaining from the `deadline` immediately because it is unclear
            // if the `deadline` object will be valid after execution leaves this function.
            const endTime = Date.now() + deadline.timeRemaining();
            const execute = () => {
                if (this._isDisposed || !this._tokenizerWithStateStore._textModel.isAttachedToEditor() || !this._hasLinesToTokenize()) {
                    // disposed in the meantime or detached or finished
                    return;
                }
                this._backgroundTokenizeForAtLeast1ms();
                if (Date.now() < endTime) {
                    // There is still time before reaching the deadline, so yield to the browser and then
                    // continue execution
                    (0, platform_1.setTimeout0)(execute);
                }
                else {
                    // The deadline has been reached, so schedule a new idle callback if necessary
                    this._beginBackgroundTokenization();
                }
            };
            execute();
        }
        /**
         * Tokenize for at least 1ms.
         */
        _backgroundTokenizeForAtLeast1ms() {
            const lineCount = this._tokenizerWithStateStore._textModel.getLineCount();
            const builder = new contiguousMultilineTokensBuilder_1.ContiguousMultilineTokensBuilder();
            const sw = stopwatch_1.StopWatch.create(false);
            do {
                if (sw.elapsed() > 1) {
                    // the comparison is intentionally > 1 and not >= 1 to ensure that
                    // a full millisecond has elapsed, given how microseconds are rounded
                    // to milliseconds
                    break;
                }
                const tokenizedLineNumber = this._tokenizeOneInvalidLine(builder);
                if (tokenizedLineNumber >= lineCount) {
                    break;
                }
            } while (this._hasLinesToTokenize());
            this._backgroundTokenStore.setTokens(builder.finalize());
            this.checkFinished();
        }
        _hasLinesToTokenize() {
            if (!this._tokenizerWithStateStore) {
                return false;
            }
            return !this._tokenizerWithStateStore.store.allStatesValid();
        }
        _tokenizeOneInvalidLine(builder) {
            const firstInvalidLine = this._tokenizerWithStateStore?.getFirstInvalidLine();
            if (!firstInvalidLine) {
                return this._tokenizerWithStateStore._textModel.getLineCount() + 1;
            }
            this._tokenizerWithStateStore.updateTokensUntilLine(builder, firstInvalidLine.lineNumber);
            return firstInvalidLine.lineNumber;
        }
        checkFinished() {
            if (this._isDisposed) {
                return;
            }
            if (this._tokenizerWithStateStore.store.allStatesValid()) {
                this._backgroundTokenStore.backgroundTokenizationFinished();
            }
        }
        requestTokens(startLineNumber, endLineNumberExclusive) {
            this._tokenizerWithStateStore.store.invalidateEndStateRange(new lineRange_1.LineRange(startLineNumber, endLineNumberExclusive));
        }
    }
    exports.DefaultBackgroundTokenizer = DefaultBackgroundTokenizer;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[263/*vs/editor/common/model/tokens*/], __M([1/*require*/,0/*exports*/,13/*vs/base/common/arrays*/,14/*vs/base/common/async*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,55/*vs/editor/common/core/lineRange*/]), function (require, exports, arrays_1, async_1, event_1, lifecycle_1, lineRange_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AbstractTokens = exports.AttachedViewHandler = exports.AttachedViews = void 0;
    /**
     * @internal
     */
    class AttachedViews {
        constructor() {
            this._onDidChangeVisibleRanges = new event_1.Emitter();
            this.onDidChangeVisibleRanges = this._onDidChangeVisibleRanges.event;
            this._views = new Set();
        }
        attachView() {
            const view = new AttachedViewImpl((state) => {
                this._onDidChangeVisibleRanges.fire({ view, state });
            });
            this._views.add(view);
            return view;
        }
        detachView(view) {
            this._views.delete(view);
            this._onDidChangeVisibleRanges.fire({ view, state: undefined });
        }
    }
    exports.AttachedViews = AttachedViews;
    class AttachedViewImpl {
        constructor(handleStateChange) {
            this.handleStateChange = handleStateChange;
        }
        setVisibleLines(visibleLines, stabilized) {
            const visibleLineRanges = visibleLines.map((line) => new lineRange_1.LineRange(line.startLineNumber, line.endLineNumber + 1));
            this.handleStateChange({ visibleLineRanges, stabilized });
        }
    }
    class AttachedViewHandler extends lifecycle_1.Disposable {
        get lineRanges() { return this._lineRanges; }
        constructor(_refreshTokens) {
            super();
            this._refreshTokens = _refreshTokens;
            this.runner = this._register(new async_1.RunOnceScheduler(() => this.update(), 50));
            this._computedLineRanges = [];
            this._lineRanges = [];
        }
        update() {
            if ((0, arrays_1.equals)(this._computedLineRanges, this._lineRanges, (a, b) => a.equals(b))) {
                return;
            }
            this._computedLineRanges = this._lineRanges;
            this._refreshTokens();
        }
        handleStateChange(state) {
            this._lineRanges = state.visibleLineRanges;
            if (state.stabilized) {
                this.runner.cancel();
                this.update();
            }
            else {
                this.runner.schedule();
            }
        }
    }
    exports.AttachedViewHandler = AttachedViewHandler;
    class AbstractTokens extends lifecycle_1.Disposable {
        get backgroundTokenizationState() {
            return this._backgroundTokenizationState;
        }
        constructor(_languageIdCodec, _textModel, getLanguageId) {
            super();
            this._languageIdCodec = _languageIdCodec;
            this._textModel = _textModel;
            this.getLanguageId = getLanguageId;
            this._backgroundTokenizationState = 1 /* BackgroundTokenizationState.InProgress */;
            this._onDidChangeBackgroundTokenizationState = this._register(new event_1.Emitter());
            /** @internal, should not be exposed by the text model! */
            this.onDidChangeBackgroundTokenizationState = this._onDidChangeBackgroundTokenizationState.event;
            this._onDidChangeTokens = this._register(new event_1.Emitter());
            /** @internal, should not be exposed by the text model! */
            this.onDidChangeTokens = this._onDidChangeTokens.event;
        }
        tokenizeIfCheap(lineNumber) {
            if (this.isCheapToTokenize(lineNumber)) {
                this.forceTokenization(lineNumber);
            }
        }
    }
    exports.AbstractTokens = AbstractTokens;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[664/*vs/editor/common/model/treeSitterTokens*/], __M([1/*require*/,0/*exports*/,27/*vs/editor/common/languages*/,83/*vs/editor/common/tokens/lineTokens*/,263/*vs/editor/common/model/tokens*/]), function (require, exports, languages_1, lineTokens_1, tokens_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.TreeSitterTokens = void 0;
    class TreeSitterTokens extends tokens_1.AbstractTokens {
        constructor(_treeSitterService, languageIdCodec, textModel, languageId) {
            super(languageIdCodec, textModel, languageId);
            this._treeSitterService = _treeSitterService;
            this._tokenizationSupport = null;
            this._initialize();
        }
        _initialize() {
            const newLanguage = this.getLanguageId();
            if (!this._tokenizationSupport || this._lastLanguageId !== newLanguage) {
                this._lastLanguageId = newLanguage;
                this._tokenizationSupport = languages_1.TreeSitterTokenizationRegistry.get(newLanguage);
            }
        }
        getLineTokens(lineNumber) {
            const content = this._textModel.getLineContent(lineNumber);
            if (this._tokenizationSupport) {
                const rawTokens = this._tokenizationSupport.tokenizeEncoded(lineNumber, this._textModel);
                if (rawTokens) {
                    return new lineTokens_1.LineTokens(rawTokens, content, this._languageIdCodec);
                }
            }
            return lineTokens_1.LineTokens.createEmpty(content, this._languageIdCodec);
        }
        resetTokenization(fireTokenChangeEvent = true) {
            if (fireTokenChangeEvent) {
                this._onDidChangeTokens.fire({
                    semanticTokensApplied: false,
                    ranges: [
                        {
                            fromLineNumber: 1,
                            toLineNumber: this._textModel.getLineCount(),
                        },
                    ],
                });
            }
            this._initialize();
        }
        handleDidChangeAttached() {
            // TODO @alexr00 implement for background tokenization
        }
        handleDidChangeContent(e) {
            if (e.isFlush) {
                // Don't fire the event, as the view might not have got the text change event yet
                this.resetTokenization(false);
            }
        }
        forceTokenization(lineNumber) {
            // TODO @alexr00 implement
        }
        hasAccurateTokensForLine(lineNumber) {
            // TODO @alexr00 update for background tokenization
            return true;
        }
        isCheapToTokenize(lineNumber) {
            // TODO @alexr00 update for background tokenization
            return true;
        }
        getTokenTypeIfInsertingCharacter(lineNumber, column, character) {
            // TODO @alexr00 implement once we have custom parsing and don't just feed in the whole text model value
            return 0 /* StandardTokenType.Other */;
        }
        tokenizeLineWithEdit(position, length, newText) {
            // TODO @alexr00 understand what this is for and implement
            return null;
        }
        get hasTokens() {
            // TODO @alexr00 once we have a token store, implement properly
            const hasTree = this._treeSitterService.getParseResult(this._textModel) !== undefined;
            return hasTree;
        }
    }
    exports.TreeSitterTokens = TreeSitterTokens;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[372/*vs/editor/common/services/editorBaseApi*/], __M([1/*require*/,0/*exports*/,18/*vs/base/common/cancellation*/,6/*vs/base/common/event*/,72/*vs/base/common/keyCodes*/,22/*vs/base/common/uri*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/,23/*vs/editor/common/core/selection*/,27/*vs/editor/common/languages*/,238/*vs/editor/common/standalone/standaloneEnums*/]), function (require, exports, cancellation_1, event_1, keyCodes_1, uri_1, position_1, range_1, selection_1, languages_1, standaloneEnums) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.KeyMod = void 0;
    exports.createMonacoBaseAPI = createMonacoBaseAPI;
    class KeyMod {
        static { this.CtrlCmd = 2048 /* ConstKeyMod.CtrlCmd */; }
        static { this.Shift = 1024 /* ConstKeyMod.Shift */; }
        static { this.Alt = 512 /* ConstKeyMod.Alt */; }
        static { this.WinCtrl = 256 /* ConstKeyMod.WinCtrl */; }
        static chord(firstPart, secondPart) {
            return (0, keyCodes_1.KeyChord)(firstPart, secondPart);
        }
    }
    exports.KeyMod = KeyMod;
    function createMonacoBaseAPI() {
        return {
            editor: undefined, // undefined override expected here
            languages: undefined, // undefined override expected here
            CancellationTokenSource: cancellation_1.CancellationTokenSource,
            Emitter: event_1.Emitter,
            KeyCode: standaloneEnums.KeyCode,
            KeyMod: KeyMod,
            Position: position_1.Position,
            Range: range_1.Range,
            Selection: selection_1.Selection,
            SelectionDirection: standaloneEnums.SelectionDirection,
            MarkerSeverity: standaloneEnums.MarkerSeverity,
            MarkerTag: standaloneEnums.MarkerTag,
            Uri: uri_1.URI,
            Token: languages_1.Token
        };
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[665/*vs/editor/common/services/semanticTokensDto*/], __M([1/*require*/,0/*exports*/,160/*vs/base/common/buffer*/,16/*vs/base/common/platform*/]), function (require, exports, buffer_1, platform) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.encodeSemanticTokensDto = encodeSemanticTokensDto;
    function reverseEndianness(arr) {
        for (let i = 0, len = arr.length; i < len; i += 4) {
            // flip bytes 0<->3 and 1<->2
            const b0 = arr[i + 0];
            const b1 = arr[i + 1];
            const b2 = arr[i + 2];
            const b3 = arr[i + 3];
            arr[i + 0] = b3;
            arr[i + 1] = b2;
            arr[i + 2] = b1;
            arr[i + 3] = b0;
        }
    }
    function toLittleEndianBuffer(arr) {
        const uint8Arr = new Uint8Array(arr.buffer, arr.byteOffset, arr.length * 4);
        if (!platform.isLittleEndian()) {
            // the byte order must be changed
            reverseEndianness(uint8Arr);
        }
        return buffer_1.VSBuffer.wrap(uint8Arr);
    }
    function encodeSemanticTokensDto(semanticTokens) {
        const dest = new Uint32Array(encodeSemanticTokensDtoSize(semanticTokens));
        let offset = 0;
        dest[offset++] = semanticTokens.id;
        if (semanticTokens.type === 'full') {
            dest[offset++] = 1 /* EncodedSemanticTokensType.Full */;
            dest[offset++] = semanticTokens.data.length;
            dest.set(semanticTokens.data, offset);
            offset += semanticTokens.data.length;
        }
        else {
            dest[offset++] = 2 /* EncodedSemanticTokensType.Delta */;
            dest[offset++] = semanticTokens.deltas.length;
            for (const delta of semanticTokens.deltas) {
                dest[offset++] = delta.start;
                dest[offset++] = delta.deleteCount;
                if (delta.data) {
                    dest[offset++] = delta.data.length;
                    dest.set(delta.data, offset);
                    offset += delta.data.length;
                }
                else {
                    dest[offset++] = 0;
                }
            }
        }
        return toLittleEndianBuffer(dest);
    }
    function encodeSemanticTokensDtoSize(semanticTokens) {
        let result = 0;
        result += (+1 // id
            + 1 // type
        );
        if (semanticTokens.type === 'full') {
            result += (+1 // data length
                + semanticTokens.data.length);
        }
        else {
            result += (+1 // delta count
            );
            result += (+1 // start
                + 1 // deleteCount
                + 1 // data length
            ) * semanticTokens.deltas.length;
            for (const delta of semanticTokens.deltas) {
                if (delta.data) {
                    result += delta.data.length;
                }
            }
        }
        return result;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[373/*vs/editor/common/services/textModelSync/textModelSync.impl*/], __M([1/*require*/,0/*exports*/,14/*vs/base/common/async*/,2/*vs/base/common/lifecycle*/,22/*vs/base/common/uri*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/,147/*vs/editor/common/core/wordHelper*/,580/*vs/editor/common/model/mirrorTextModel*/]), function (require, exports, async_1, lifecycle_1, uri_1, position_1, range_1, wordHelper_1, mirrorTextModel_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MirrorModel = exports.WorkerTextModelSyncServer = exports.WorkerTextModelSyncClient = exports.STOP_SYNC_MODEL_DELTA_TIME_MS = void 0;
    /**
     * Stop syncing a model to the worker if it was not needed for 1 min.
     */
    exports.STOP_SYNC_MODEL_DELTA_TIME_MS = 60 * 1000;
    class WorkerTextModelSyncClient extends lifecycle_1.Disposable {
        constructor(proxy, modelService, keepIdleModels = false) {
            super();
            this._syncedModels = Object.create(null);
            this._syncedModelsLastUsedTime = Object.create(null);
            this._proxy = proxy;
            this._modelService = modelService;
            if (!keepIdleModels) {
                const timer = new async_1.IntervalTimer();
                timer.cancelAndSet(() => this._checkStopModelSync(), Math.round(exports.STOP_SYNC_MODEL_DELTA_TIME_MS / 2));
                this._register(timer);
            }
        }
        dispose() {
            for (const modelUrl in this._syncedModels) {
                (0, lifecycle_1.dispose)(this._syncedModels[modelUrl]);
            }
            this._syncedModels = Object.create(null);
            this._syncedModelsLastUsedTime = Object.create(null);
            super.dispose();
        }
        ensureSyncedResources(resources, forceLargeModels = false) {
            for (const resource of resources) {
                const resourceStr = resource.toString();
                if (!this._syncedModels[resourceStr]) {
                    this._beginModelSync(resource, forceLargeModels);
                }
                if (this._syncedModels[resourceStr]) {
                    this._syncedModelsLastUsedTime[resourceStr] = (new Date()).getTime();
                }
            }
        }
        _checkStopModelSync() {
            const currentTime = (new Date()).getTime();
            const toRemove = [];
            for (const modelUrl in this._syncedModelsLastUsedTime) {
                const elapsedTime = currentTime - this._syncedModelsLastUsedTime[modelUrl];
                if (elapsedTime > exports.STOP_SYNC_MODEL_DELTA_TIME_MS) {
                    toRemove.push(modelUrl);
                }
            }
            for (const e of toRemove) {
                this._stopModelSync(e);
            }
        }
        _beginModelSync(resource, forceLargeModels) {
            const model = this._modelService.getModel(resource);
            if (!model) {
                return;
            }
            if (!forceLargeModels && model.isTooLargeForSyncing()) {
                return;
            }
            const modelUrl = resource.toString();
            this._proxy.$acceptNewModel({
                url: model.uri.toString(),
                lines: model.getLinesContent(),
                EOL: model.getEOL(),
                versionId: model.getVersionId()
            });
            const toDispose = new lifecycle_1.DisposableStore();
            toDispose.add(model.onDidChangeContent((e) => {
                this._proxy.$acceptModelChanged(modelUrl.toString(), e);
            }));
            toDispose.add(model.onWillDispose(() => {
                this._stopModelSync(modelUrl);
            }));
            toDispose.add((0, lifecycle_1.toDisposable)(() => {
                this._proxy.$acceptRemovedModel(modelUrl);
            }));
            this._syncedModels[modelUrl] = toDispose;
        }
        _stopModelSync(modelUrl) {
            const toDispose = this._syncedModels[modelUrl];
            delete this._syncedModels[modelUrl];
            delete this._syncedModelsLastUsedTime[modelUrl];
            (0, lifecycle_1.dispose)(toDispose);
        }
    }
    exports.WorkerTextModelSyncClient = WorkerTextModelSyncClient;
    class WorkerTextModelSyncServer {
        constructor() {
            this._models = Object.create(null);
        }
        getModel(uri) {
            return this._models[uri];
        }
        getModels() {
            const all = [];
            Object.keys(this._models).forEach((key) => all.push(this._models[key]));
            return all;
        }
        $acceptNewModel(data) {
            this._models[data.url] = new MirrorModel(uri_1.URI.parse(data.url), data.lines, data.EOL, data.versionId);
        }
        $acceptModelChanged(uri, e) {
            if (!this._models[uri]) {
                return;
            }
            const model = this._models[uri];
            model.onEvents(e);
        }
        $acceptRemovedModel(uri) {
            if (!this._models[uri]) {
                return;
            }
            delete this._models[uri];
        }
    }
    exports.WorkerTextModelSyncServer = WorkerTextModelSyncServer;
    class MirrorModel extends mirrorTextModel_1.MirrorTextModel {
        get uri() {
            return this._uri;
        }
        get eol() {
            return this._eol;
        }
        getValue() {
            return this.getText();
        }
        findMatches(regex) {
            const matches = [];
            for (let i = 0; i < this._lines.length; i++) {
                const line = this._lines[i];
                const offsetToAdd = this.offsetAt(new position_1.Position(i + 1, 1));
                const iteratorOverMatches = line.matchAll(regex);
                for (const match of iteratorOverMatches) {
                    if (match.index || match.index === 0) {
                        match.index = match.index + offsetToAdd;
                    }
                    matches.push(match);
                }
            }
            return matches;
        }
        getLinesContent() {
            return this._lines.slice(0);
        }
        getLineCount() {
            return this._lines.length;
        }
        getLineContent(lineNumber) {
            return this._lines[lineNumber - 1];
        }
        getWordAtPosition(position, wordDefinition) {
            const wordAtText = (0, wordHelper_1.getWordAtText)(position.column, (0, wordHelper_1.ensureValidWordDefinition)(wordDefinition), this._lines[position.lineNumber - 1], 0);
            if (wordAtText) {
                return new range_1.Range(position.lineNumber, wordAtText.startColumn, position.lineNumber, wordAtText.endColumn);
            }
            return null;
        }
        words(wordDefinition) {
            const lines = this._lines;
            const wordenize = this._wordenize.bind(this);
            let lineNumber = 0;
            let lineText = '';
            let wordRangesIdx = 0;
            let wordRanges = [];
            return {
                *[Symbol.iterator]() {
                    while (true) {
                        if (wordRangesIdx < wordRanges.length) {
                            const value = lineText.substring(wordRanges[wordRangesIdx].start, wordRanges[wordRangesIdx].end);
                            wordRangesIdx += 1;
                            yield value;
                        }
                        else {
                            if (lineNumber < lines.length) {
                                lineText = lines[lineNumber];
                                wordRanges = wordenize(lineText, wordDefinition);
                                wordRangesIdx = 0;
                                lineNumber += 1;
                            }
                            else {
                                break;
                            }
                        }
                    }
                }
            };
        }
        getLineWords(lineNumber, wordDefinition) {
            const content = this._lines[lineNumber - 1];
            const ranges = this._wordenize(content, wordDefinition);
            const words = [];
            for (const range of ranges) {
                words.push({
                    word: content.substring(range.start, range.end),
                    startColumn: range.start + 1,
                    endColumn: range.end + 1
                });
            }
            return words;
        }
        _wordenize(content, wordDefinition) {
            const result = [];
            let match;
            wordDefinition.lastIndex = 0; // reset lastIndex just to be sure
            while (match = wordDefinition.exec(content)) {
                if (match[0].length === 0) {
                    // it did match the empty string
                    break;
                }
                result.push({ start: match.index, end: match.index + match[0].length });
            }
            return result;
        }
        getValueInRange(range) {
            range = this._validateRange(range);
            if (range.startLineNumber === range.endLineNumber) {
                return this._lines[range.startLineNumber - 1].substring(range.startColumn - 1, range.endColumn - 1);
            }
            const lineEnding = this._eol;
            const startLineIndex = range.startLineNumber - 1;
            const endLineIndex = range.endLineNumber - 1;
            const resultLines = [];
            resultLines.push(this._lines[startLineIndex].substring(range.startColumn - 1));
            for (let i = startLineIndex + 1; i < endLineIndex; i++) {
                resultLines.push(this._lines[i]);
            }
            resultLines.push(this._lines[endLineIndex].substring(0, range.endColumn - 1));
            return resultLines.join(lineEnding);
        }
        offsetAt(position) {
            position = this._validatePosition(position);
            this._ensureLineStarts();
            return this._lineStarts.getPrefixSum(position.lineNumber - 2) + (position.column - 1);
        }
        positionAt(offset) {
            offset = Math.floor(offset);
            offset = Math.max(0, offset);
            this._ensureLineStarts();
            const out = this._lineStarts.getIndexOf(offset);
            const lineLength = this._lines[out.index].length;
            // Ensure we return a valid position
            return {
                lineNumber: 1 + out.index,
                column: 1 + Math.min(out.remainder, lineLength)
            };
        }
        _validateRange(range) {
            const start = this._validatePosition({ lineNumber: range.startLineNumber, column: range.startColumn });
            const end = this._validatePosition({ lineNumber: range.endLineNumber, column: range.endColumn });
            if (start.lineNumber !== range.startLineNumber
                || start.column !== range.startColumn
                || end.lineNumber !== range.endLineNumber
                || end.column !== range.endColumn) {
                return {
                    startLineNumber: start.lineNumber,
                    startColumn: start.column,
                    endLineNumber: end.lineNumber,
                    endColumn: end.column
                };
            }
            return range;
        }
        _validatePosition(position) {
            if (!position_1.Position.isIPosition(position)) {
                throw new Error('bad position');
            }
            let { lineNumber, column } = position;
            let hasChanged = false;
            if (lineNumber < 1) {
                lineNumber = 1;
                column = 1;
                hasChanged = true;
            }
            else if (lineNumber > this._lines.length) {
                lineNumber = this._lines.length;
                column = this._lines[lineNumber - 1].length + 1;
                hasChanged = true;
            }
            else {
                const maxCharacter = this._lines[lineNumber - 1].length + 1;
                if (column < 1) {
                    column = 1;
                    hasChanged = true;
                }
                else if (column > maxCharacter) {
                    column = maxCharacter;
                    hasChanged = true;
                }
            }
            if (!hasChanged) {
                return position;
            }
            else {
                return { lineNumber, column };
            }
        }
    }
    exports.MirrorModel = MirrorModel;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[666/*vs/editor/common/services/editorSimpleWorker*/], __M([1/*require*/,0/*exports*/,190/*vs/base/common/diff/diff*/,4/*vs/editor/common/core/range*/,564/*vs/editor/common/languages/linkComputer*/,570/*vs/editor/common/languages/supports/inplaceReplaceSupport*/,372/*vs/editor/common/services/editorBaseApi*/,326/*vs/editor/common/services/editorWorkerHost*/,54/*vs/base/common/stopwatch*/,328/*vs/editor/common/services/unicodeTextModelHighlighter*/,561/*vs/editor/common/diff/linesDiffComputers*/,60/*vs/base/common/objects*/,42/*vs/base/common/network*/,563/*vs/editor/common/languages/defaultDocumentColorsComputer*/,582/*vs/editor/common/services/findSectionHeaders*/,373/*vs/editor/common/services/textModelSync/textModelSync.impl*/]), function (require, exports, diff_1, range_1, linkComputer_1, inplaceReplaceSupport_1, editorBaseApi_1, editorWorkerHost_1, stopwatch_1, unicodeTextModelHighlighter_1, linesDiffComputers_1, objects_1, network_1, defaultDocumentColorsComputer_1, findSectionHeaders_1, textModelSync_impl_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.EditorSimpleWorker = exports.BaseEditorSimpleWorker = void 0;
    exports.create = create;
    // ESM-comment-begin
    const isESM = false;
    /**
     * @internal
     */
    class BaseEditorSimpleWorker {
        constructor() {
            this._workerTextModelSyncServer = new textModelSync_impl_1.WorkerTextModelSyncServer();
        }
        dispose() {
        }
        _getModel(uri) {
            return this._workerTextModelSyncServer.getModel(uri);
        }
        _getModels() {
            return this._workerTextModelSyncServer.getModels();
        }
        $acceptNewModel(data) {
            this._workerTextModelSyncServer.$acceptNewModel(data);
        }
        $acceptModelChanged(uri, e) {
            this._workerTextModelSyncServer.$acceptModelChanged(uri, e);
        }
        $acceptRemovedModel(uri) {
            this._workerTextModelSyncServer.$acceptRemovedModel(uri);
        }
        async $computeUnicodeHighlights(url, options, range) {
            const model = this._getModel(url);
            if (!model) {
                return { ranges: [], hasMore: false, ambiguousCharacterCount: 0, invisibleCharacterCount: 0, nonBasicAsciiCharacterCount: 0 };
            }
            return unicodeTextModelHighlighter_1.UnicodeTextModelHighlighter.computeUnicodeHighlights(model, options, range);
        }
        async $findSectionHeaders(url, options) {
            const model = this._getModel(url);
            if (!model) {
                return [];
            }
            return (0, findSectionHeaders_1.findSectionHeaders)(model, options);
        }
        // ---- BEGIN diff --------------------------------------------------------------------------
        async $computeDiff(originalUrl, modifiedUrl, options, algorithm) {
            const original = this._getModel(originalUrl);
            const modified = this._getModel(modifiedUrl);
            if (!original || !modified) {
                return null;
            }
            const result = EditorSimpleWorker.computeDiff(original, modified, options, algorithm);
            return result;
        }
        static computeDiff(originalTextModel, modifiedTextModel, options, algorithm) {
            const diffAlgorithm = algorithm === 'advanced' ? linesDiffComputers_1.linesDiffComputers.getDefault() : linesDiffComputers_1.linesDiffComputers.getLegacy();
            const originalLines = originalTextModel.getLinesContent();
            const modifiedLines = modifiedTextModel.getLinesContent();
            const result = diffAlgorithm.computeDiff(originalLines, modifiedLines, options);
            const identical = (result.changes.length > 0 ? false : this._modelsAreIdentical(originalTextModel, modifiedTextModel));
            function getLineChanges(changes) {
                return changes.map(m => ([m.original.startLineNumber, m.original.endLineNumberExclusive, m.modified.startLineNumber, m.modified.endLineNumberExclusive, m.innerChanges?.map(m => [
                        m.originalRange.startLineNumber,
                        m.originalRange.startColumn,
                        m.originalRange.endLineNumber,
                        m.originalRange.endColumn,
                        m.modifiedRange.startLineNumber,
                        m.modifiedRange.startColumn,
                        m.modifiedRange.endLineNumber,
                        m.modifiedRange.endColumn,
                    ])]));
            }
            return {
                identical,
                quitEarly: result.hitTimeout,
                changes: getLineChanges(result.changes),
                moves: result.moves.map(m => ([
                    m.lineRangeMapping.original.startLineNumber,
                    m.lineRangeMapping.original.endLineNumberExclusive,
                    m.lineRangeMapping.modified.startLineNumber,
                    m.lineRangeMapping.modified.endLineNumberExclusive,
                    getLineChanges(m.changes)
                ])),
            };
        }
        static _modelsAreIdentical(original, modified) {
            const originalLineCount = original.getLineCount();
            const modifiedLineCount = modified.getLineCount();
            if (originalLineCount !== modifiedLineCount) {
                return false;
            }
            for (let line = 1; line <= originalLineCount; line++) {
                const originalLine = original.getLineContent(line);
                const modifiedLine = modified.getLineContent(line);
                if (originalLine !== modifiedLine) {
                    return false;
                }
            }
            return true;
        }
        // ---- END diff --------------------------------------------------------------------------
        // ---- BEGIN minimal edits ---------------------------------------------------------------
        static { this._diffLimit = 100000; }
        async $computeMoreMinimalEdits(modelUrl, edits, pretty) {
            const model = this._getModel(modelUrl);
            if (!model) {
                return edits;
            }
            const result = [];
            let lastEol = undefined;
            edits = edits.slice(0).sort((a, b) => {
                if (a.range && b.range) {
                    return range_1.Range.compareRangesUsingStarts(a.range, b.range);
                }
                // eol only changes should go to the end
                const aRng = a.range ? 0 : 1;
                const bRng = b.range ? 0 : 1;
                return aRng - bRng;
            });
            // merge adjacent edits
            let writeIndex = 0;
            for (let readIndex = 1; readIndex < edits.length; readIndex++) {
                if (range_1.Range.getEndPosition(edits[writeIndex].range).equals(range_1.Range.getStartPosition(edits[readIndex].range))) {
                    edits[writeIndex].range = range_1.Range.fromPositions(range_1.Range.getStartPosition(edits[writeIndex].range), range_1.Range.getEndPosition(edits[readIndex].range));
                    edits[writeIndex].text += edits[readIndex].text;
                }
                else {
                    writeIndex++;
                    edits[writeIndex] = edits[readIndex];
                }
            }
            edits.length = writeIndex + 1;
            for (let { range, text, eol } of edits) {
                if (typeof eol === 'number') {
                    lastEol = eol;
                }
                if (range_1.Range.isEmpty(range) && !text) {
                    // empty change
                    continue;
                }
                const original = model.getValueInRange(range);
                text = text.replace(/\r\n|\n|\r/g, model.eol);
                if (original === text) {
                    // noop
                    continue;
                }
                // make sure diff won't take too long
                if (Math.max(text.length, original.length) > EditorSimpleWorker._diffLimit) {
                    result.push({ range, text });
                    continue;
                }
                // compute diff between original and edit.text
                const changes = (0, diff_1.stringDiff)(original, text, pretty);
                const editOffset = model.offsetAt(range_1.Range.lift(range).getStartPosition());
                for (const change of changes) {
                    const start = model.positionAt(editOffset + change.originalStart);
                    const end = model.positionAt(editOffset + change.originalStart + change.originalLength);
                    const newEdit = {
                        text: text.substr(change.modifiedStart, change.modifiedLength),
                        range: { startLineNumber: start.lineNumber, startColumn: start.column, endLineNumber: end.lineNumber, endColumn: end.column }
                    };
                    if (model.getValueInRange(newEdit.range) !== newEdit.text) {
                        result.push(newEdit);
                    }
                }
            }
            if (typeof lastEol === 'number') {
                result.push({ eol: lastEol, text: '', range: { startLineNumber: 0, startColumn: 0, endLineNumber: 0, endColumn: 0 } });
            }
            return result;
        }
        // ---- END minimal edits ---------------------------------------------------------------
        async $computeLinks(modelUrl) {
            const model = this._getModel(modelUrl);
            if (!model) {
                return null;
            }
            return (0, linkComputer_1.computeLinks)(model);
        }
        // --- BEGIN default document colors -----------------------------------------------------------
        async $computeDefaultDocumentColors(modelUrl) {
            const model = this._getModel(modelUrl);
            if (!model) {
                return null;
            }
            return (0, defaultDocumentColorsComputer_1.computeDefaultDocumentColors)(model);
        }
        // ---- BEGIN suggest --------------------------------------------------------------------------
        static { this._suggestionsLimit = 10000; }
        async $textualSuggest(modelUrls, leadingWord, wordDef, wordDefFlags) {
            const sw = new stopwatch_1.StopWatch();
            const wordDefRegExp = new RegExp(wordDef, wordDefFlags);
            const seen = new Set();
            outer: for (const url of modelUrls) {
                const model = this._getModel(url);
                if (!model) {
                    continue;
                }
                for (const word of model.words(wordDefRegExp)) {
                    if (word === leadingWord || !isNaN(Number(word))) {
                        continue;
                    }
                    seen.add(word);
                    if (seen.size > EditorSimpleWorker._suggestionsLimit) {
                        break outer;
                    }
                }
            }
            return { words: Array.from(seen), duration: sw.elapsed() };
        }
        // ---- END suggest --------------------------------------------------------------------------
        //#region -- word ranges --
        async $computeWordRanges(modelUrl, range, wordDef, wordDefFlags) {
            const model = this._getModel(modelUrl);
            if (!model) {
                return Object.create(null);
            }
            const wordDefRegExp = new RegExp(wordDef, wordDefFlags);
            const result = Object.create(null);
            for (let line = range.startLineNumber; line < range.endLineNumber; line++) {
                const words = model.getLineWords(line, wordDefRegExp);
                for (const word of words) {
                    if (!isNaN(Number(word.word))) {
                        continue;
                    }
                    let array = result[word.word];
                    if (!array) {
                        array = [];
                        result[word.word] = array;
                    }
                    array.push({
                        startLineNumber: line,
                        startColumn: word.startColumn,
                        endLineNumber: line,
                        endColumn: word.endColumn
                    });
                }
            }
            return result;
        }
        //#endregion
        async $navigateValueSet(modelUrl, range, up, wordDef, wordDefFlags) {
            const model = this._getModel(modelUrl);
            if (!model) {
                return null;
            }
            const wordDefRegExp = new RegExp(wordDef, wordDefFlags);
            if (range.startColumn === range.endColumn) {
                range = {
                    startLineNumber: range.startLineNumber,
                    startColumn: range.startColumn,
                    endLineNumber: range.endLineNumber,
                    endColumn: range.endColumn + 1
                };
            }
            const selectionText = model.getValueInRange(range);
            const wordRange = model.getWordAtPosition({ lineNumber: range.startLineNumber, column: range.startColumn }, wordDefRegExp);
            if (!wordRange) {
                return null;
            }
            const word = model.getValueInRange(wordRange);
            const result = inplaceReplaceSupport_1.BasicInplaceReplace.INSTANCE.navigateValueSet(range, selectionText, wordRange, word, up);
            return result;
        }
    }
    exports.BaseEditorSimpleWorker = BaseEditorSimpleWorker;
    /**
     * @internal
     */
    class EditorSimpleWorker extends BaseEditorSimpleWorker {
        constructor(_host, _foreignModuleFactory) {
            super();
            this._host = _host;
            this._foreignModuleFactory = _foreignModuleFactory;
            this._foreignModule = null;
        }
        async $ping() {
            return 'pong';
        }
        // ---- BEGIN foreign module support --------------------------------------------------------------------------
        $loadForeignModule(moduleId, createData, foreignHostMethods) {
            const proxyMethodRequest = (method, args) => {
                return this._host.$fhr(method, args);
            };
            const foreignHost = (0, objects_1.createProxyObject)(foreignHostMethods, proxyMethodRequest);
            const ctx = {
                host: foreignHost,
                getMirrorModels: () => {
                    return this._getModels();
                }
            };
            if (this._foreignModuleFactory) {
                this._foreignModule = this._foreignModuleFactory(ctx, createData);
                // static foreing module
                return Promise.resolve((0, objects_1.getAllMethodNames)(this._foreignModule));
            }
            return new Promise((resolve, reject) => {
                const onModuleCallback = (foreignModule) => {
                    this._foreignModule = foreignModule.create(ctx, createData);
                    resolve((0, objects_1.getAllMethodNames)(this._foreignModule));
                };
                if (!isESM) {
                    require([`${moduleId}`], onModuleCallback, reject);
                }
                else {
                    const url = network_1.FileAccess.asBrowserUri(`${moduleId}.js`).toString(true);
                    new Promise((resolve_1, reject_1) => { require([`${url}`], resolve_1, reject_1); }).then(onModuleCallback).catch(reject);
                }
            });
        }
        // foreign method request
        $fmr(method, args) {
            if (!this._foreignModule || typeof this._foreignModule[method] !== 'function') {
                return Promise.reject(new Error('Missing requestHandler or method: ' + method));
            }
            try {
                return Promise.resolve(this._foreignModule[method].apply(this._foreignModule, args));
            }
            catch (e) {
                return Promise.reject(e);
            }
        }
    }
    exports.EditorSimpleWorker = EditorSimpleWorker;
    /**
     * Defines the worker entry point. Must be exported and named `create`.
     * @skipMangle
     * @internal
     */
    function create(workerServer) {
        return new EditorSimpleWorker(editorWorkerHost_1.EditorWorkerHost.getChannel(workerServer), null);
    }
    if (typeof importScripts === 'function') {
        // Running in a web worker
        globalThis.monaco = (0, editorBaseApi_1.createMonacoBaseAPI)();
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[107/*vs/editor/common/standaloneStrings*/], __M([1/*require*/,0/*exports*/,3/*vs/nls*/]), function (require, exports, nls) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.StandaloneServicesNLS = exports.ToggleHighContrastNLS = exports.StandaloneCodeEditorNLS = exports.QuickOutlineNLS = exports.QuickCommandNLS = exports.QuickHelpNLS = exports.GoToLineNLS = exports.InspectTokensNLS = void 0;
    var InspectTokensNLS;
    (function (InspectTokensNLS) {
        InspectTokensNLS.inspectTokensAction = nls.localize(698, "Developer: Inspect Tokens");
    })(InspectTokensNLS || (exports.InspectTokensNLS = InspectTokensNLS = {}));
    var GoToLineNLS;
    (function (GoToLineNLS) {
        GoToLineNLS.gotoLineActionLabel = nls.localize(699, "Go to Line/Column...");
    })(GoToLineNLS || (exports.GoToLineNLS = GoToLineNLS = {}));
    var QuickHelpNLS;
    (function (QuickHelpNLS) {
        QuickHelpNLS.helpQuickAccessActionLabel = nls.localize(700, "Show all Quick Access Providers");
    })(QuickHelpNLS || (exports.QuickHelpNLS = QuickHelpNLS = {}));
    var QuickCommandNLS;
    (function (QuickCommandNLS) {
        QuickCommandNLS.quickCommandActionLabel = nls.localize(701, "Command Palette");
        QuickCommandNLS.quickCommandHelp = nls.localize(702, "Show And Run Commands");
    })(QuickCommandNLS || (exports.QuickCommandNLS = QuickCommandNLS = {}));
    var QuickOutlineNLS;
    (function (QuickOutlineNLS) {
        QuickOutlineNLS.quickOutlineActionLabel = nls.localize(703, "Go to Symbol...");
        QuickOutlineNLS.quickOutlineByCategoryActionLabel = nls.localize(704, "Go to Symbol by Category...");
    })(QuickOutlineNLS || (exports.QuickOutlineNLS = QuickOutlineNLS = {}));
    var StandaloneCodeEditorNLS;
    (function (StandaloneCodeEditorNLS) {
        StandaloneCodeEditorNLS.editorViewAccessibleLabel = nls.localize(705, "Editor content");
    })(StandaloneCodeEditorNLS || (exports.StandaloneCodeEditorNLS = StandaloneCodeEditorNLS = {}));
    var ToggleHighContrastNLS;
    (function (ToggleHighContrastNLS) {
        ToggleHighContrastNLS.toggleHighContrast = nls.localize(706, "Toggle High Contrast Theme");
    })(ToggleHighContrastNLS || (exports.ToggleHighContrastNLS = ToggleHighContrastNLS = {}));
    var StandaloneServicesNLS;
    (function (StandaloneServicesNLS) {
        StandaloneServicesNLS.bulkEditServiceSummary = nls.localize(707, "Made {0} edits in {1} files");
    })(StandaloneServicesNLS || (exports.StandaloneServicesNLS = StandaloneServicesNLS = {}));
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[136/*vs/editor/common/viewLayout/viewLineRenderer*/], __M([1/*require*/,0/*exports*/,3/*vs/nls*/,11/*vs/base/common/strings*/,116/*vs/editor/common/core/stringBuilder*/,150/*vs/editor/common/viewLayout/lineDecorations*/,598/*vs/editor/common/viewLayout/linePart*/]), function (require, exports, nls, strings, stringBuilder_1, lineDecorations_1, linePart_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.RenderLineOutput2 = exports.RenderLineOutput = exports.CharacterMapping = exports.DomPosition = exports.RenderLineInput = exports.LineRange = void 0;
    exports.renderViewLine = renderViewLine;
    exports.renderViewLine2 = renderViewLine2;
    class LineRange {
        constructor(startIndex, endIndex) {
            this.startOffset = startIndex;
            this.endOffset = endIndex;
        }
        equals(otherLineRange) {
            return this.startOffset === otherLineRange.startOffset
                && this.endOffset === otherLineRange.endOffset;
        }
    }
    exports.LineRange = LineRange;
    class RenderLineInput {
        constructor(useMonospaceOptimizations, canUseHalfwidthRightwardsArrow, lineContent, continuesWithWrappedLine, isBasicASCII, containsRTL, fauxIndentLength, lineTokens, lineDecorations, tabSize, startVisibleColumn, spaceWidth, middotWidth, wsmiddotWidth, stopRenderingLineAfter, renderWhitespace, renderControlCharacters, fontLigatures, selectionsOnLine) {
            this.useMonospaceOptimizations = useMonospaceOptimizations;
            this.canUseHalfwidthRightwardsArrow = canUseHalfwidthRightwardsArrow;
            this.lineContent = lineContent;
            this.continuesWithWrappedLine = continuesWithWrappedLine;
            this.isBasicASCII = isBasicASCII;
            this.containsRTL = containsRTL;
            this.fauxIndentLength = fauxIndentLength;
            this.lineTokens = lineTokens;
            this.lineDecorations = lineDecorations.sort(lineDecorations_1.LineDecoration.compare);
            this.tabSize = tabSize;
            this.startVisibleColumn = startVisibleColumn;
            this.spaceWidth = spaceWidth;
            this.stopRenderingLineAfter = stopRenderingLineAfter;
            this.renderWhitespace = (renderWhitespace === 'all'
                ? 4 /* RenderWhitespace.All */
                : renderWhitespace === 'boundary'
                    ? 1 /* RenderWhitespace.Boundary */
                    : renderWhitespace === 'selection'
                        ? 2 /* RenderWhitespace.Selection */
                        : renderWhitespace === 'trailing'
                            ? 3 /* RenderWhitespace.Trailing */
                            : 0 /* RenderWhitespace.None */);
            this.renderControlCharacters = renderControlCharacters;
            this.fontLigatures = fontLigatures;
            this.selectionsOnLine = selectionsOnLine && selectionsOnLine.sort((a, b) => a.startOffset < b.startOffset ? -1 : 1);
            const wsmiddotDiff = Math.abs(wsmiddotWidth - spaceWidth);
            const middotDiff = Math.abs(middotWidth - spaceWidth);
            if (wsmiddotDiff < middotDiff) {
                this.renderSpaceWidth = wsmiddotWidth;
                this.renderSpaceCharCode = 0x2E31; // U+2E31 - WORD SEPARATOR MIDDLE DOT
            }
            else {
                this.renderSpaceWidth = middotWidth;
                this.renderSpaceCharCode = 0xB7; // U+00B7 - MIDDLE DOT
            }
        }
        sameSelection(otherSelections) {
            if (this.selectionsOnLine === null) {
                return otherSelections === null;
            }
            if (otherSelections === null) {
                return false;
            }
            if (otherSelections.length !== this.selectionsOnLine.length) {
                return false;
            }
            for (let i = 0; i < this.selectionsOnLine.length; i++) {
                if (!this.selectionsOnLine[i].equals(otherSelections[i])) {
                    return false;
                }
            }
            return true;
        }
        equals(other) {
            return (this.useMonospaceOptimizations === other.useMonospaceOptimizations
                && this.canUseHalfwidthRightwardsArrow === other.canUseHalfwidthRightwardsArrow
                && this.lineContent === other.lineContent
                && this.continuesWithWrappedLine === other.continuesWithWrappedLine
                && this.isBasicASCII === other.isBasicASCII
                && this.containsRTL === other.containsRTL
                && this.fauxIndentLength === other.fauxIndentLength
                && this.tabSize === other.tabSize
                && this.startVisibleColumn === other.startVisibleColumn
                && this.spaceWidth === other.spaceWidth
                && this.renderSpaceWidth === other.renderSpaceWidth
                && this.renderSpaceCharCode === other.renderSpaceCharCode
                && this.stopRenderingLineAfter === other.stopRenderingLineAfter
                && this.renderWhitespace === other.renderWhitespace
                && this.renderControlCharacters === other.renderControlCharacters
                && this.fontLigatures === other.fontLigatures
                && lineDecorations_1.LineDecoration.equalsArr(this.lineDecorations, other.lineDecorations)
                && this.lineTokens.equals(other.lineTokens)
                && this.sameSelection(other.selectionsOnLine));
        }
    }
    exports.RenderLineInput = RenderLineInput;
    class DomPosition {
        constructor(partIndex, charIndex) {
            this.partIndex = partIndex;
            this.charIndex = charIndex;
        }
    }
    exports.DomPosition = DomPosition;
    /**
     * Provides a both direction mapping between a line's character and its rendered position.
     */
    class CharacterMapping {
        static getPartIndex(partData) {
            return (partData & 4294901760 /* CharacterMappingConstants.PART_INDEX_MASK */) >>> 16 /* CharacterMappingConstants.PART_INDEX_OFFSET */;
        }
        static getCharIndex(partData) {
            return (partData & 65535 /* CharacterMappingConstants.CHAR_INDEX_MASK */) >>> 0 /* CharacterMappingConstants.CHAR_INDEX_OFFSET */;
        }
        constructor(length, partCount) {
            this.length = length;
            this._data = new Uint32Array(this.length);
            this._horizontalOffset = new Uint32Array(this.length);
        }
        setColumnInfo(column, partIndex, charIndex, horizontalOffset) {
            const partData = ((partIndex << 16 /* CharacterMappingConstants.PART_INDEX_OFFSET */)
                | (charIndex << 0 /* CharacterMappingConstants.CHAR_INDEX_OFFSET */)) >>> 0;
            this._data[column - 1] = partData;
            this._horizontalOffset[column - 1] = horizontalOffset;
        }
        getHorizontalOffset(column) {
            if (this._horizontalOffset.length === 0) {
                // No characters on this line
                return 0;
            }
            return this._horizontalOffset[column - 1];
        }
        charOffsetToPartData(charOffset) {
            if (this.length === 0) {
                return 0;
            }
            if (charOffset < 0) {
                return this._data[0];
            }
            if (charOffset >= this.length) {
                return this._data[this.length - 1];
            }
            return this._data[charOffset];
        }
        getDomPosition(column) {
            const partData = this.charOffsetToPartData(column - 1);
            const partIndex = CharacterMapping.getPartIndex(partData);
            const charIndex = CharacterMapping.getCharIndex(partData);
            return new DomPosition(partIndex, charIndex);
        }
        getColumn(domPosition, partLength) {
            const charOffset = this.partDataToCharOffset(domPosition.partIndex, partLength, domPosition.charIndex);
            return charOffset + 1;
        }
        partDataToCharOffset(partIndex, partLength, charIndex) {
            if (this.length === 0) {
                return 0;
            }
            const searchEntry = ((partIndex << 16 /* CharacterMappingConstants.PART_INDEX_OFFSET */)
                | (charIndex << 0 /* CharacterMappingConstants.CHAR_INDEX_OFFSET */)) >>> 0;
            let min = 0;
            let max = this.length - 1;
            while (min + 1 < max) {
                const mid = ((min + max) >>> 1);
                const midEntry = this._data[mid];
                if (midEntry === searchEntry) {
                    return mid;
                }
                else if (midEntry > searchEntry) {
                    max = mid;
                }
                else {
                    min = mid;
                }
            }
            if (min === max) {
                return min;
            }
            const minEntry = this._data[min];
            const maxEntry = this._data[max];
            if (minEntry === searchEntry) {
                return min;
            }
            if (maxEntry === searchEntry) {
                return max;
            }
            const minPartIndex = CharacterMapping.getPartIndex(minEntry);
            const minCharIndex = CharacterMapping.getCharIndex(minEntry);
            const maxPartIndex = CharacterMapping.getPartIndex(maxEntry);
            let maxCharIndex;
            if (minPartIndex !== maxPartIndex) {
                // sitting between parts
                maxCharIndex = partLength;
            }
            else {
                maxCharIndex = CharacterMapping.getCharIndex(maxEntry);
            }
            const minEntryDistance = charIndex - minCharIndex;
            const maxEntryDistance = maxCharIndex - charIndex;
            if (minEntryDistance <= maxEntryDistance) {
                return min;
            }
            return max;
        }
    }
    exports.CharacterMapping = CharacterMapping;
    class RenderLineOutput {
        constructor(characterMapping, containsRTL, containsForeignElements) {
            this._renderLineOutputBrand = undefined;
            this.characterMapping = characterMapping;
            this.containsRTL = containsRTL;
            this.containsForeignElements = containsForeignElements;
        }
    }
    exports.RenderLineOutput = RenderLineOutput;
    function renderViewLine(input, sb) {
        if (input.lineContent.length === 0) {
            if (input.lineDecorations.length > 0) {
                // This line is empty, but it contains inline decorations
                sb.appendString(`<span>`);
                let beforeCount = 0;
                let afterCount = 0;
                let containsForeignElements = 0 /* ForeignElementType.None */;
                for (const lineDecoration of input.lineDecorations) {
                    if (lineDecoration.type === 1 /* InlineDecorationType.Before */ || lineDecoration.type === 2 /* InlineDecorationType.After */) {
                        sb.appendString(`<span class="`);
                        sb.appendString(lineDecoration.className);
                        sb.appendString(`"></span>`);
                        if (lineDecoration.type === 1 /* InlineDecorationType.Before */) {
                            containsForeignElements |= 1 /* ForeignElementType.Before */;
                            beforeCount++;
                        }
                        if (lineDecoration.type === 2 /* InlineDecorationType.After */) {
                            containsForeignElements |= 2 /* ForeignElementType.After */;
                            afterCount++;
                        }
                    }
                }
                sb.appendString(`</span>`);
                const characterMapping = new CharacterMapping(1, beforeCount + afterCount);
                characterMapping.setColumnInfo(1, beforeCount, 0, 0);
                return new RenderLineOutput(characterMapping, false, containsForeignElements);
            }
            // completely empty line
            sb.appendString('<span><span></span></span>');
            return new RenderLineOutput(new CharacterMapping(0, 0), false, 0 /* ForeignElementType.None */);
        }
        return _renderLine(resolveRenderLineInput(input), sb);
    }
    class RenderLineOutput2 {
        constructor(characterMapping, html, containsRTL, containsForeignElements) {
            this.characterMapping = characterMapping;
            this.html = html;
            this.containsRTL = containsRTL;
            this.containsForeignElements = containsForeignElements;
        }
    }
    exports.RenderLineOutput2 = RenderLineOutput2;
    function renderViewLine2(input) {
        const sb = new stringBuilder_1.StringBuilder(10000);
        const out = renderViewLine(input, sb);
        return new RenderLineOutput2(out.characterMapping, sb.build(), out.containsRTL, out.containsForeignElements);
    }
    class ResolvedRenderLineInput {
        constructor(fontIsMonospace, canUseHalfwidthRightwardsArrow, lineContent, len, isOverflowing, overflowingCharCount, parts, containsForeignElements, fauxIndentLength, tabSize, startVisibleColumn, containsRTL, spaceWidth, renderSpaceCharCode, renderWhitespace, renderControlCharacters) {
            this.fontIsMonospace = fontIsMonospace;
            this.canUseHalfwidthRightwardsArrow = canUseHalfwidthRightwardsArrow;
            this.lineContent = lineContent;
            this.len = len;
            this.isOverflowing = isOverflowing;
            this.overflowingCharCount = overflowingCharCount;
            this.parts = parts;
            this.containsForeignElements = containsForeignElements;
            this.fauxIndentLength = fauxIndentLength;
            this.tabSize = tabSize;
            this.startVisibleColumn = startVisibleColumn;
            this.containsRTL = containsRTL;
            this.spaceWidth = spaceWidth;
            this.renderSpaceCharCode = renderSpaceCharCode;
            this.renderWhitespace = renderWhitespace;
            this.renderControlCharacters = renderControlCharacters;
            //
        }
    }
    function resolveRenderLineInput(input) {
        const lineContent = input.lineContent;
        let isOverflowing;
        let overflowingCharCount;
        let len;
        if (input.stopRenderingLineAfter !== -1 && input.stopRenderingLineAfter < lineContent.length) {
            isOverflowing = true;
            overflowingCharCount = lineContent.length - input.stopRenderingLineAfter;
            len = input.stopRenderingLineAfter;
        }
        else {
            isOverflowing = false;
            overflowingCharCount = 0;
            len = lineContent.length;
        }
        let tokens = transformAndRemoveOverflowing(lineContent, input.containsRTL, input.lineTokens, input.fauxIndentLength, len);
        if (input.renderControlCharacters && !input.isBasicASCII) {
            // Calling `extractControlCharacters` before adding (possibly empty) line parts
            // for inline decorations. `extractControlCharacters` removes empty line parts.
            tokens = extractControlCharacters(lineContent, tokens);
        }
        if (input.renderWhitespace === 4 /* RenderWhitespace.All */ ||
            input.renderWhitespace === 1 /* RenderWhitespace.Boundary */ ||
            (input.renderWhitespace === 2 /* RenderWhitespace.Selection */ && !!input.selectionsOnLine) ||
            (input.renderWhitespace === 3 /* RenderWhitespace.Trailing */ && !input.continuesWithWrappedLine)) {
            tokens = _applyRenderWhitespace(input, lineContent, len, tokens);
        }
        let containsForeignElements = 0 /* ForeignElementType.None */;
        if (input.lineDecorations.length > 0) {
            for (let i = 0, len = input.lineDecorations.length; i < len; i++) {
                const lineDecoration = input.lineDecorations[i];
                if (lineDecoration.type === 3 /* InlineDecorationType.RegularAffectingLetterSpacing */) {
                    // Pretend there are foreign elements... although not 100% accurate.
                    containsForeignElements |= 1 /* ForeignElementType.Before */;
                }
                else if (lineDecoration.type === 1 /* InlineDecorationType.Before */) {
                    containsForeignElements |= 1 /* ForeignElementType.Before */;
                }
                else if (lineDecoration.type === 2 /* InlineDecorationType.After */) {
                    containsForeignElements |= 2 /* ForeignElementType.After */;
                }
            }
            tokens = _applyInlineDecorations(lineContent, len, tokens, input.lineDecorations);
        }
        if (!input.containsRTL) {
            // We can never split RTL text, as it ruins the rendering
            tokens = splitLargeTokens(lineContent, tokens, !input.isBasicASCII || input.fontLigatures);
        }
        return new ResolvedRenderLineInput(input.useMonospaceOptimizations, input.canUseHalfwidthRightwardsArrow, lineContent, len, isOverflowing, overflowingCharCount, tokens, containsForeignElements, input.fauxIndentLength, input.tabSize, input.startVisibleColumn, input.containsRTL, input.spaceWidth, input.renderSpaceCharCode, input.renderWhitespace, input.renderControlCharacters);
    }
    /**
     * In the rendering phase, characters are always looped until token.endIndex.
     * Ensure that all tokens end before `len` and the last one ends precisely at `len`.
     */
    function transformAndRemoveOverflowing(lineContent, lineContainsRTL, tokens, fauxIndentLength, len) {
        const result = [];
        let resultLen = 0;
        // The faux indent part of the line should have no token type
        if (fauxIndentLength > 0) {
            result[resultLen++] = new linePart_1.LinePart(fauxIndentLength, '', 0, false);
        }
        let startOffset = fauxIndentLength;
        for (let tokenIndex = 0, tokensLen = tokens.getCount(); tokenIndex < tokensLen; tokenIndex++) {
            const endIndex = tokens.getEndOffset(tokenIndex);
            if (endIndex <= fauxIndentLength) {
                // The faux indent part of the line should have no token type
                continue;
            }
            const type = tokens.getClassName(tokenIndex);
            if (endIndex >= len) {
                const tokenContainsRTL = (lineContainsRTL ? strings.containsRTL(lineContent.substring(startOffset, len)) : false);
                result[resultLen++] = new linePart_1.LinePart(len, type, 0, tokenContainsRTL);
                break;
            }
            const tokenContainsRTL = (lineContainsRTL ? strings.containsRTL(lineContent.substring(startOffset, endIndex)) : false);
            result[resultLen++] = new linePart_1.LinePart(endIndex, type, 0, tokenContainsRTL);
            startOffset = endIndex;
        }
        return result;
    }
    /**
     * See https://github.com/microsoft/vscode/issues/6885.
     * It appears that having very large spans causes very slow reading of character positions.
     * So here we try to avoid that.
     */
    function splitLargeTokens(lineContent, tokens, onlyAtSpaces) {
        let lastTokenEndIndex = 0;
        const result = [];
        let resultLen = 0;
        if (onlyAtSpaces) {
            // Split only at spaces => we need to walk each character
            for (let i = 0, len = tokens.length; i < len; i++) {
                const token = tokens[i];
                const tokenEndIndex = token.endIndex;
                if (lastTokenEndIndex + 50 /* Constants.LongToken */ < tokenEndIndex) {
                    const tokenType = token.type;
                    const tokenMetadata = token.metadata;
                    const tokenContainsRTL = token.containsRTL;
                    let lastSpaceOffset = -1;
                    let currTokenStart = lastTokenEndIndex;
                    for (let j = lastTokenEndIndex; j < tokenEndIndex; j++) {
                        if (lineContent.charCodeAt(j) === 32 /* CharCode.Space */) {
                            lastSpaceOffset = j;
                        }
                        if (lastSpaceOffset !== -1 && j - currTokenStart >= 50 /* Constants.LongToken */) {
                            // Split at `lastSpaceOffset` + 1
                            result[resultLen++] = new linePart_1.LinePart(lastSpaceOffset + 1, tokenType, tokenMetadata, tokenContainsRTL);
                            currTokenStart = lastSpaceOffset + 1;
                            lastSpaceOffset = -1;
                        }
                    }
                    if (currTokenStart !== tokenEndIndex) {
                        result[resultLen++] = new linePart_1.LinePart(tokenEndIndex, tokenType, tokenMetadata, tokenContainsRTL);
                    }
                }
                else {
                    result[resultLen++] = token;
                }
                lastTokenEndIndex = tokenEndIndex;
            }
        }
        else {
            // Split anywhere => we don't need to walk each character
            for (let i = 0, len = tokens.length; i < len; i++) {
                const token = tokens[i];
                const tokenEndIndex = token.endIndex;
                const diff = (tokenEndIndex - lastTokenEndIndex);
                if (diff > 50 /* Constants.LongToken */) {
                    const tokenType = token.type;
                    const tokenMetadata = token.metadata;
                    const tokenContainsRTL = token.containsRTL;
                    const piecesCount = Math.ceil(diff / 50 /* Constants.LongToken */);
                    for (let j = 1; j < piecesCount; j++) {
                        const pieceEndIndex = lastTokenEndIndex + (j * 50 /* Constants.LongToken */);
                        result[resultLen++] = new linePart_1.LinePart(pieceEndIndex, tokenType, tokenMetadata, tokenContainsRTL);
                    }
                    result[resultLen++] = new linePart_1.LinePart(tokenEndIndex, tokenType, tokenMetadata, tokenContainsRTL);
                }
                else {
                    result[resultLen++] = token;
                }
                lastTokenEndIndex = tokenEndIndex;
            }
        }
        return result;
    }
    function isControlCharacter(charCode) {
        if (charCode < 32) {
            return (charCode !== 9 /* CharCode.Tab */);
        }
        if (charCode === 127) {
            // DEL
            return true;
        }
        if ((charCode >= 0x202A && charCode <= 0x202E)
            || (charCode >= 0x2066 && charCode <= 0x2069)
            || (charCode >= 0x200E && charCode <= 0x200F)
            || charCode === 0x061C) {
            // Unicode Directional Formatting Characters
            // LRE	U+202A	LEFT-TO-RIGHT EMBEDDING
            // RLE	U+202B	RIGHT-TO-LEFT EMBEDDING
            // PDF	U+202C	POP DIRECTIONAL FORMATTING
            // LRO	U+202D	LEFT-TO-RIGHT OVERRIDE
            // RLO	U+202E	RIGHT-TO-LEFT OVERRIDE
            // LRI	U+2066	LEFT-TO-RIGHT ISOLATE
            // RLI	U+2067	RIGHT-TO-LEFT ISOLATE
            // FSI	U+2068	FIRST STRONG ISOLATE
            // PDI	U+2069	POP DIRECTIONAL ISOLATE
            // LRM	U+200E	LEFT-TO-RIGHT MARK
            // RLM	U+200F	RIGHT-TO-LEFT MARK
            // ALM	U+061C	ARABIC LETTER MARK
            return true;
        }
        return false;
    }
    function extractControlCharacters(lineContent, tokens) {
        const result = [];
        let lastLinePart = new linePart_1.LinePart(0, '', 0, false);
        let charOffset = 0;
        for (const token of tokens) {
            const tokenEndIndex = token.endIndex;
            for (; charOffset < tokenEndIndex; charOffset++) {
                const charCode = lineContent.charCodeAt(charOffset);
                if (isControlCharacter(charCode)) {
                    if (charOffset > lastLinePart.endIndex) {
                        // emit previous part if it has text
                        lastLinePart = new linePart_1.LinePart(charOffset, token.type, token.metadata, token.containsRTL);
                        result.push(lastLinePart);
                    }
                    lastLinePart = new linePart_1.LinePart(charOffset + 1, 'mtkcontrol', token.metadata, false);
                    result.push(lastLinePart);
                }
            }
            if (charOffset > lastLinePart.endIndex) {
                // emit previous part if it has text
                lastLinePart = new linePart_1.LinePart(tokenEndIndex, token.type, token.metadata, token.containsRTL);
                result.push(lastLinePart);
            }
        }
        return result;
    }
    /**
     * Whitespace is rendered by "replacing" tokens with a special-purpose `mtkw` type that is later recognized in the rendering phase.
     * Moreover, a token is created for every visual indent because on some fonts the glyphs used for rendering whitespace (&rarr; or &middot;) do not have the same width as &nbsp;.
     * The rendering phase will generate `style="width:..."` for these tokens.
     */
    function _applyRenderWhitespace(input, lineContent, len, tokens) {
        const continuesWithWrappedLine = input.continuesWithWrappedLine;
        const fauxIndentLength = input.fauxIndentLength;
        const tabSize = input.tabSize;
        const startVisibleColumn = input.startVisibleColumn;
        const useMonospaceOptimizations = input.useMonospaceOptimizations;
        const selections = input.selectionsOnLine;
        const onlyBoundary = (input.renderWhitespace === 1 /* RenderWhitespace.Boundary */);
        const onlyTrailing = (input.renderWhitespace === 3 /* RenderWhitespace.Trailing */);
        const generateLinePartForEachWhitespace = (input.renderSpaceWidth !== input.spaceWidth);
        const result = [];
        let resultLen = 0;
        let tokenIndex = 0;
        let tokenType = tokens[tokenIndex].type;
        let tokenContainsRTL = tokens[tokenIndex].containsRTL;
        let tokenEndIndex = tokens[tokenIndex].endIndex;
        const tokensLength = tokens.length;
        let lineIsEmptyOrWhitespace = false;
        let firstNonWhitespaceIndex = strings.firstNonWhitespaceIndex(lineContent);
        let lastNonWhitespaceIndex;
        if (firstNonWhitespaceIndex === -1) {
            lineIsEmptyOrWhitespace = true;
            firstNonWhitespaceIndex = len;
            lastNonWhitespaceIndex = len;
        }
        else {
            lastNonWhitespaceIndex = strings.lastNonWhitespaceIndex(lineContent);
        }
        let wasInWhitespace = false;
        let currentSelectionIndex = 0;
        let currentSelection = selections && selections[currentSelectionIndex];
        let tmpIndent = startVisibleColumn % tabSize;
        for (let charIndex = fauxIndentLength; charIndex < len; charIndex++) {
            const chCode = lineContent.charCodeAt(charIndex);
            if (currentSelection && charIndex >= currentSelection.endOffset) {
                currentSelectionIndex++;
                currentSelection = selections && selections[currentSelectionIndex];
            }
            let isInWhitespace;
            if (charIndex < firstNonWhitespaceIndex || charIndex > lastNonWhitespaceIndex) {
                // in leading or trailing whitespace
                isInWhitespace = true;
            }
            else if (chCode === 9 /* CharCode.Tab */) {
                // a tab character is rendered both in all and boundary cases
                isInWhitespace = true;
            }
            else if (chCode === 32 /* CharCode.Space */) {
                // hit a space character
                if (onlyBoundary) {
                    // rendering only boundary whitespace
                    if (wasInWhitespace) {
                        isInWhitespace = true;
                    }
                    else {
                        const nextChCode = (charIndex + 1 < len ? lineContent.charCodeAt(charIndex + 1) : 0 /* CharCode.Null */);
                        isInWhitespace = (nextChCode === 32 /* CharCode.Space */ || nextChCode === 9 /* CharCode.Tab */);
                    }
                }
                else {
                    isInWhitespace = true;
                }
            }
            else {
                isInWhitespace = false;
            }
            // If rendering whitespace on selection, check that the charIndex falls within a selection
            if (isInWhitespace && selections) {
                isInWhitespace = !!currentSelection && currentSelection.startOffset <= charIndex && currentSelection.endOffset > charIndex;
            }
            // If rendering only trailing whitespace, check that the charIndex points to trailing whitespace.
            if (isInWhitespace && onlyTrailing) {
                isInWhitespace = lineIsEmptyOrWhitespace || charIndex > lastNonWhitespaceIndex;
            }
            if (isInWhitespace && tokenContainsRTL) {
                // If the token contains RTL text, breaking it up into multiple line parts
                // to render whitespace might affect the browser's bidi layout.
                //
                // We render whitespace in such tokens only if the whitespace
                // is the leading or the trailing whitespace of the line,
                // which doesn't affect the browser's bidi layout.
                if (charIndex >= firstNonWhitespaceIndex && charIndex <= lastNonWhitespaceIndex) {
                    isInWhitespace = false;
                }
            }
            if (wasInWhitespace) {
                // was in whitespace token
                if (!isInWhitespace || (!useMonospaceOptimizations && tmpIndent >= tabSize)) {
                    // leaving whitespace token or entering a new indent
                    if (generateLinePartForEachWhitespace) {
                        const lastEndIndex = (resultLen > 0 ? result[resultLen - 1].endIndex : fauxIndentLength);
                        for (let i = lastEndIndex + 1; i <= charIndex; i++) {
                            result[resultLen++] = new linePart_1.LinePart(i, 'mtkw', 1 /* LinePartMetadata.IS_WHITESPACE */, false);
                        }
                    }
                    else {
                        result[resultLen++] = new linePart_1.LinePart(charIndex, 'mtkw', 1 /* LinePartMetadata.IS_WHITESPACE */, false);
                    }
                    tmpIndent = tmpIndent % tabSize;
                }
            }
            else {
                // was in regular token
                if (charIndex === tokenEndIndex || (isInWhitespace && charIndex > fauxIndentLength)) {
                    result[resultLen++] = new linePart_1.LinePart(charIndex, tokenType, 0, tokenContainsRTL);
                    tmpIndent = tmpIndent % tabSize;
                }
            }
            if (chCode === 9 /* CharCode.Tab */) {
                tmpIndent = tabSize;
            }
            else if (strings.isFullWidthCharacter(chCode)) {
                tmpIndent += 2;
            }
            else {
                tmpIndent++;
            }
            wasInWhitespace = isInWhitespace;
            while (charIndex === tokenEndIndex) {
                tokenIndex++;
                if (tokenIndex < tokensLength) {
                    tokenType = tokens[tokenIndex].type;
                    tokenContainsRTL = tokens[tokenIndex].containsRTL;
                    tokenEndIndex = tokens[tokenIndex].endIndex;
                }
                else {
                    break;
                }
            }
        }
        let generateWhitespace = false;
        if (wasInWhitespace) {
            // was in whitespace token
            if (continuesWithWrappedLine && onlyBoundary) {
                const lastCharCode = (len > 0 ? lineContent.charCodeAt(len - 1) : 0 /* CharCode.Null */);
                const prevCharCode = (len > 1 ? lineContent.charCodeAt(len - 2) : 0 /* CharCode.Null */);
                const isSingleTrailingSpace = (lastCharCode === 32 /* CharCode.Space */ && (prevCharCode !== 32 /* CharCode.Space */ && prevCharCode !== 9 /* CharCode.Tab */));
                if (!isSingleTrailingSpace) {
                    generateWhitespace = true;
                }
            }
            else {
                generateWhitespace = true;
            }
        }
        if (generateWhitespace) {
            if (generateLinePartForEachWhitespace) {
                const lastEndIndex = (resultLen > 0 ? result[resultLen - 1].endIndex : fauxIndentLength);
                for (let i = lastEndIndex + 1; i <= len; i++) {
                    result[resultLen++] = new linePart_1.LinePart(i, 'mtkw', 1 /* LinePartMetadata.IS_WHITESPACE */, false);
                }
            }
            else {
                result[resultLen++] = new linePart_1.LinePart(len, 'mtkw', 1 /* LinePartMetadata.IS_WHITESPACE */, false);
            }
        }
        else {
            result[resultLen++] = new linePart_1.LinePart(len, tokenType, 0, tokenContainsRTL);
        }
        return result;
    }
    /**
     * Inline decorations are "merged" on top of tokens.
     * Special care must be taken when multiple inline decorations are at play and they overlap.
     */
    function _applyInlineDecorations(lineContent, len, tokens, _lineDecorations) {
        _lineDecorations.sort(lineDecorations_1.LineDecoration.compare);
        const lineDecorations = lineDecorations_1.LineDecorationsNormalizer.normalize(lineContent, _lineDecorations);
        const lineDecorationsLen = lineDecorations.length;
        let lineDecorationIndex = 0;
        const result = [];
        let resultLen = 0;
        let lastResultEndIndex = 0;
        for (let tokenIndex = 0, len = tokens.length; tokenIndex < len; tokenIndex++) {
            const token = tokens[tokenIndex];
            const tokenEndIndex = token.endIndex;
            const tokenType = token.type;
            const tokenMetadata = token.metadata;
            const tokenContainsRTL = token.containsRTL;
            while (lineDecorationIndex < lineDecorationsLen && lineDecorations[lineDecorationIndex].startOffset < tokenEndIndex) {
                const lineDecoration = lineDecorations[lineDecorationIndex];
                if (lineDecoration.startOffset > lastResultEndIndex) {
                    lastResultEndIndex = lineDecoration.startOffset;
                    result[resultLen++] = new linePart_1.LinePart(lastResultEndIndex, tokenType, tokenMetadata, tokenContainsRTL);
                }
                if (lineDecoration.endOffset + 1 <= tokenEndIndex) {
                    // This line decoration ends before this token ends
                    lastResultEndIndex = lineDecoration.endOffset + 1;
                    result[resultLen++] = new linePart_1.LinePart(lastResultEndIndex, tokenType + ' ' + lineDecoration.className, tokenMetadata | lineDecoration.metadata, tokenContainsRTL);
                    lineDecorationIndex++;
                }
                else {
                    // This line decoration continues on to the next token
                    lastResultEndIndex = tokenEndIndex;
                    result[resultLen++] = new linePart_1.LinePart(lastResultEndIndex, tokenType + ' ' + lineDecoration.className, tokenMetadata | lineDecoration.metadata, tokenContainsRTL);
                    break;
                }
            }
            if (tokenEndIndex > lastResultEndIndex) {
                lastResultEndIndex = tokenEndIndex;
                result[resultLen++] = new linePart_1.LinePart(lastResultEndIndex, tokenType, tokenMetadata, tokenContainsRTL);
            }
        }
        const lastTokenEndIndex = tokens[tokens.length - 1].endIndex;
        if (lineDecorationIndex < lineDecorationsLen && lineDecorations[lineDecorationIndex].startOffset === lastTokenEndIndex) {
            while (lineDecorationIndex < lineDecorationsLen && lineDecorations[lineDecorationIndex].startOffset === lastTokenEndIndex) {
                const lineDecoration = lineDecorations[lineDecorationIndex];
                result[resultLen++] = new linePart_1.LinePart(lastResultEndIndex, lineDecoration.className, lineDecoration.metadata, false);
                lineDecorationIndex++;
            }
        }
        return result;
    }
    /**
     * This function is on purpose not split up into multiple functions to allow runtime type inference (i.e. performance reasons).
     * Notice how all the needed data is fully resolved and passed in (i.e. no other calls).
     */
    function _renderLine(input, sb) {
        const fontIsMonospace = input.fontIsMonospace;
        const canUseHalfwidthRightwardsArrow = input.canUseHalfwidthRightwardsArrow;
        const containsForeignElements = input.containsForeignElements;
        const lineContent = input.lineContent;
        const len = input.len;
        const isOverflowing = input.isOverflowing;
        const overflowingCharCount = input.overflowingCharCount;
        const parts = input.parts;
        const fauxIndentLength = input.fauxIndentLength;
        const tabSize = input.tabSize;
        const startVisibleColumn = input.startVisibleColumn;
        const containsRTL = input.containsRTL;
        const spaceWidth = input.spaceWidth;
        const renderSpaceCharCode = input.renderSpaceCharCode;
        const renderWhitespace = input.renderWhitespace;
        const renderControlCharacters = input.renderControlCharacters;
        const characterMapping = new CharacterMapping(len + 1, parts.length);
        let lastCharacterMappingDefined = false;
        let charIndex = 0;
        let visibleColumn = startVisibleColumn;
        let charOffsetInPart = 0; // the character offset in the current part
        let charHorizontalOffset = 0; // the character horizontal position in terms of chars relative to line start
        let partDisplacement = 0;
        if (containsRTL) {
            sb.appendString('<span dir="ltr">');
        }
        else {
            sb.appendString('<span>');
        }
        for (let partIndex = 0, tokensLen = parts.length; partIndex < tokensLen; partIndex++) {
            const part = parts[partIndex];
            const partEndIndex = part.endIndex;
            const partType = part.type;
            const partContainsRTL = part.containsRTL;
            const partRendersWhitespace = (renderWhitespace !== 0 /* RenderWhitespace.None */ && part.isWhitespace());
            const partRendersWhitespaceWithWidth = partRendersWhitespace && !fontIsMonospace && (partType === 'mtkw' /*only whitespace*/ || !containsForeignElements);
            const partIsEmptyAndHasPseudoAfter = (charIndex === partEndIndex && part.isPseudoAfter());
            charOffsetInPart = 0;
            sb.appendString('<span ');
            if (partContainsRTL) {
                sb.appendString('style="unicode-bidi:isolate" ');
            }
            sb.appendString('class="');
            sb.appendString(partRendersWhitespaceWithWidth ? 'mtkz' : partType);
            sb.appendASCIICharCode(34 /* CharCode.DoubleQuote */);
            if (partRendersWhitespace) {
                let partWidth = 0;
                {
                    let _charIndex = charIndex;
                    let _visibleColumn = visibleColumn;
                    for (; _charIndex < partEndIndex; _charIndex++) {
                        const charCode = lineContent.charCodeAt(_charIndex);
                        const charWidth = (charCode === 9 /* CharCode.Tab */ ? (tabSize - (_visibleColumn % tabSize)) : 1) | 0;
                        partWidth += charWidth;
                        if (_charIndex >= fauxIndentLength) {
                            _visibleColumn += charWidth;
                        }
                    }
                }
                if (partRendersWhitespaceWithWidth) {
                    sb.appendString(' style="width:');
                    sb.appendString(String(spaceWidth * partWidth));
                    sb.appendString('px"');
                }
                sb.appendASCIICharCode(62 /* CharCode.GreaterThan */);
                for (; charIndex < partEndIndex; charIndex++) {
                    characterMapping.setColumnInfo(charIndex + 1, partIndex - partDisplacement, charOffsetInPart, charHorizontalOffset);
                    partDisplacement = 0;
                    const charCode = lineContent.charCodeAt(charIndex);
                    let producedCharacters;
                    let charWidth;
                    if (charCode === 9 /* CharCode.Tab */) {
                        producedCharacters = (tabSize - (visibleColumn % tabSize)) | 0;
                        charWidth = producedCharacters;
                        if (!canUseHalfwidthRightwardsArrow || charWidth > 1) {
                            sb.appendCharCode(0x2192); // RIGHTWARDS ARROW
                        }
                        else {
                            sb.appendCharCode(0xFFEB); // HALFWIDTH RIGHTWARDS ARROW
                        }
                        for (let space = 2; space <= charWidth; space++) {
                            sb.appendCharCode(0xA0); // &nbsp;
                        }
                    }
                    else { // must be CharCode.Space
                        producedCharacters = 2;
                        charWidth = 1;
                        sb.appendCharCode(renderSpaceCharCode); // &middot; or word separator middle dot
                        sb.appendCharCode(0x200C); // ZERO WIDTH NON-JOINER
                    }
                    charOffsetInPart += producedCharacters;
                    charHorizontalOffset += charWidth;
                    if (charIndex >= fauxIndentLength) {
                        visibleColumn += charWidth;
                    }
                }
            }
            else {
                sb.appendASCIICharCode(62 /* CharCode.GreaterThan */);
                for (; charIndex < partEndIndex; charIndex++) {
                    characterMapping.setColumnInfo(charIndex + 1, partIndex - partDisplacement, charOffsetInPart, charHorizontalOffset);
                    partDisplacement = 0;
                    const charCode = lineContent.charCodeAt(charIndex);
                    let producedCharacters = 1;
                    let charWidth = 1;
                    switch (charCode) {
                        case 9 /* CharCode.Tab */:
                            producedCharacters = (tabSize - (visibleColumn % tabSize));
                            charWidth = producedCharacters;
                            for (let space = 1; space <= producedCharacters; space++) {
                                sb.appendCharCode(0xA0); // &nbsp;
                            }
                            break;
                        case 32 /* CharCode.Space */:
                            sb.appendCharCode(0xA0); // &nbsp;
                            break;
                        case 60 /* CharCode.LessThan */:
                            sb.appendString('&lt;');
                            break;
                        case 62 /* CharCode.GreaterThan */:
                            sb.appendString('&gt;');
                            break;
                        case 38 /* CharCode.Ampersand */:
                            sb.appendString('&amp;');
                            break;
                        case 0 /* CharCode.Null */:
                            if (renderControlCharacters) {
                                // See https://unicode-table.com/en/blocks/control-pictures/
                                sb.appendCharCode(9216);
                            }
                            else {
                                sb.appendString('&#00;');
                            }
                            break;
                        case 65279 /* CharCode.UTF8_BOM */:
                        case 8232 /* CharCode.LINE_SEPARATOR */:
                        case 8233 /* CharCode.PARAGRAPH_SEPARATOR */:
                        case 133 /* CharCode.NEXT_LINE */:
                            sb.appendCharCode(0xFFFD);
                            break;
                        default:
                            if (strings.isFullWidthCharacter(charCode)) {
                                charWidth++;
                            }
                            // See https://unicode-table.com/en/blocks/control-pictures/
                            if (renderControlCharacters && charCode < 32) {
                                sb.appendCharCode(9216 + charCode);
                            }
                            else if (renderControlCharacters && charCode === 127) {
                                // DEL
                                sb.appendCharCode(9249);
                            }
                            else if (renderControlCharacters && isControlCharacter(charCode)) {
                                sb.appendString('[U+');
                                sb.appendString(to4CharHex(charCode));
                                sb.appendString(']');
                                producedCharacters = 8;
                                charWidth = producedCharacters;
                            }
                            else {
                                sb.appendCharCode(charCode);
                            }
                    }
                    charOffsetInPart += producedCharacters;
                    charHorizontalOffset += charWidth;
                    if (charIndex >= fauxIndentLength) {
                        visibleColumn += charWidth;
                    }
                }
            }
            if (partIsEmptyAndHasPseudoAfter) {
                partDisplacement++;
            }
            else {
                partDisplacement = 0;
            }
            if (charIndex >= len && !lastCharacterMappingDefined && part.isPseudoAfter()) {
                lastCharacterMappingDefined = true;
                characterMapping.setColumnInfo(charIndex + 1, partIndex, charOffsetInPart, charHorizontalOffset);
            }
            sb.appendString('</span>');
        }
        if (!lastCharacterMappingDefined) {
            // When getting client rects for the last character, we will position the
            // text range at the end of the span, insteaf of at the beginning of next span
            characterMapping.setColumnInfo(len + 1, parts.length - 1, charOffsetInPart, charHorizontalOffset);
        }
        if (isOverflowing) {
            sb.appendString('<span class="mtkoverflow">');
            sb.appendString(nls.localize(708, "Show more ({0})", renderOverflowingCharCount(overflowingCharCount)));
            sb.appendString('</span>');
        }
        sb.appendString('</span>');
        return new RenderLineOutput(characterMapping, containsRTL, containsForeignElements);
    }
    function to4CharHex(n) {
        return n.toString(16).toUpperCase().padStart(4, '0');
    }
    function renderOverflowingCharCount(n) {
        if (n < 1024) {
            return nls.localize(709, "{0} chars", n);
        }
        if (n < 1024 * 1024) {
            return `${(n / 1024).toFixed(1)} KB`;
        }
        return `${(n / 1024 / 1024).toFixed(1)} MB`;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[667/*vs/editor/browser/widget/diffEditor/components/diffEditorViewZones/renderLines*/], __M([1/*require*/,0/*exports*/,103/*vs/base/browser/trustedTypes*/,74/*vs/editor/browser/config/domFontInfo*/,37/*vs/editor/common/config/editorOptions*/,116/*vs/editor/common/core/stringBuilder*/,150/*vs/editor/common/viewLayout/lineDecorations*/,136/*vs/editor/common/viewLayout/viewLineRenderer*/,95/*vs/editor/common/viewModel*/]), function (require, exports, trustedTypes_1, domFontInfo_1, editorOptions_1, stringBuilder_1, lineDecorations_1, viewLineRenderer_1, viewModel_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.RenderOptions = exports.LineSource = void 0;
    exports.renderLines = renderLines;
    const ttPolicy = (0, trustedTypes_1.createTrustedTypesPolicy)('diffEditorWidget', { createHTML: value => value });
    function renderLines(source, options, decorations, domNode) {
        (0, domFontInfo_1.applyFontInfo)(domNode, options.fontInfo);
        const hasCharChanges = (decorations.length > 0);
        const sb = new stringBuilder_1.StringBuilder(10000);
        let maxCharsPerLine = 0;
        let renderedLineCount = 0;
        const viewLineCounts = [];
        for (let lineIndex = 0; lineIndex < source.lineTokens.length; lineIndex++) {
            const lineNumber = lineIndex + 1;
            const lineTokens = source.lineTokens[lineIndex];
            const lineBreakData = source.lineBreakData[lineIndex];
            const actualDecorations = lineDecorations_1.LineDecoration.filter(decorations, lineNumber, 1, Number.MAX_SAFE_INTEGER);
            if (lineBreakData) {
                let lastBreakOffset = 0;
                for (const breakOffset of lineBreakData.breakOffsets) {
                    const viewLineTokens = lineTokens.sliceAndInflate(lastBreakOffset, breakOffset, 0);
                    maxCharsPerLine = Math.max(maxCharsPerLine, renderOriginalLine(renderedLineCount, viewLineTokens, lineDecorations_1.LineDecoration.extractWrapped(actualDecorations, lastBreakOffset, breakOffset), hasCharChanges, source.mightContainNonBasicASCII, source.mightContainRTL, options, sb));
                    renderedLineCount++;
                    lastBreakOffset = breakOffset;
                }
                viewLineCounts.push(lineBreakData.breakOffsets.length);
            }
            else {
                viewLineCounts.push(1);
                maxCharsPerLine = Math.max(maxCharsPerLine, renderOriginalLine(renderedLineCount, lineTokens, actualDecorations, hasCharChanges, source.mightContainNonBasicASCII, source.mightContainRTL, options, sb));
                renderedLineCount++;
            }
        }
        maxCharsPerLine += options.scrollBeyondLastColumn;
        const html = sb.build();
        const trustedhtml = ttPolicy ? ttPolicy.createHTML(html) : html;
        domNode.innerHTML = trustedhtml;
        const minWidthInPx = (maxCharsPerLine * options.typicalHalfwidthCharacterWidth);
        return {
            heightInLines: renderedLineCount,
            minWidthInPx,
            viewLineCounts,
        };
    }
    class LineSource {
        constructor(lineTokens, lineBreakData, mightContainNonBasicASCII, mightContainRTL) {
            this.lineTokens = lineTokens;
            this.lineBreakData = lineBreakData;
            this.mightContainNonBasicASCII = mightContainNonBasicASCII;
            this.mightContainRTL = mightContainRTL;
        }
    }
    exports.LineSource = LineSource;
    class RenderOptions {
        static fromEditor(editor) {
            const modifiedEditorOptions = editor.getOptions();
            const fontInfo = modifiedEditorOptions.get(50 /* EditorOption.fontInfo */);
            const layoutInfo = modifiedEditorOptions.get(146 /* EditorOption.layoutInfo */);
            return new RenderOptions(editor.getModel()?.getOptions().tabSize || 0, fontInfo, modifiedEditorOptions.get(33 /* EditorOption.disableMonospaceOptimizations */), fontInfo.typicalHalfwidthCharacterWidth, modifiedEditorOptions.get(105 /* EditorOption.scrollBeyondLastColumn */), modifiedEditorOptions.get(67 /* EditorOption.lineHeight */), layoutInfo.decorationsWidth, modifiedEditorOptions.get(118 /* EditorOption.stopRenderingLineAfter */), modifiedEditorOptions.get(100 /* EditorOption.renderWhitespace */), modifiedEditorOptions.get(95 /* EditorOption.renderControlCharacters */), modifiedEditorOptions.get(51 /* EditorOption.fontLigatures */));
        }
        constructor(tabSize, fontInfo, disableMonospaceOptimizations, typicalHalfwidthCharacterWidth, scrollBeyondLastColumn, lineHeight, lineDecorationsWidth, stopRenderingLineAfter, renderWhitespace, renderControlCharacters, fontLigatures) {
            this.tabSize = tabSize;
            this.fontInfo = fontInfo;
            this.disableMonospaceOptimizations = disableMonospaceOptimizations;
            this.typicalHalfwidthCharacterWidth = typicalHalfwidthCharacterWidth;
            this.scrollBeyondLastColumn = scrollBeyondLastColumn;
            this.lineHeight = lineHeight;
            this.lineDecorationsWidth = lineDecorationsWidth;
            this.stopRenderingLineAfter = stopRenderingLineAfter;
            this.renderWhitespace = renderWhitespace;
            this.renderControlCharacters = renderControlCharacters;
            this.fontLigatures = fontLigatures;
        }
    }
    exports.RenderOptions = RenderOptions;
    function renderOriginalLine(viewLineIdx, lineTokens, decorations, hasCharChanges, mightContainNonBasicASCII, mightContainRTL, options, sb) {
        sb.appendString('<div class="view-line');
        if (!hasCharChanges) {
            // No char changes
            sb.appendString(' char-delete');
        }
        sb.appendString('" style="top:');
        sb.appendString(String(viewLineIdx * options.lineHeight));
        sb.appendString('px;width:1000000px;">');
        const lineContent = lineTokens.getLineContent();
        const isBasicASCII = viewModel_1.ViewLineRenderingData.isBasicASCII(lineContent, mightContainNonBasicASCII);
        const containsRTL = viewModel_1.ViewLineRenderingData.containsRTL(lineContent, isBasicASCII, mightContainRTL);
        const output = (0, viewLineRenderer_1.renderViewLine)(new viewLineRenderer_1.RenderLineInput((options.fontInfo.isMonospace && !options.disableMonospaceOptimizations), options.fontInfo.canUseHalfwidthRightwardsArrow, lineContent, false, isBasicASCII, containsRTL, 0, lineTokens, decorations, options.tabSize, 0, options.fontInfo.spaceWidth, options.fontInfo.middotWidth, options.fontInfo.wsmiddotWidth, options.stopRenderingLineAfter, options.renderWhitespace, options.renderControlCharacters, options.fontLigatures !== editorOptions_1.EditorFontLigatures.OFF, null // Send no selections, original line cannot be selected
        ), sb);
        sb.appendString('</div>');
        return output.characterMapping.getHorizontalOffset(output.characterMapping.length);
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[374/*vs/editor/common/viewModel/minimapTokensColorTracker*/], __M([1/*require*/,0/*exports*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,311/*vs/editor/common/core/rgba*/,27/*vs/editor/common/languages*/]), function (require, exports, event_1, lifecycle_1, rgba_1, languages_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MinimapTokensColorTracker = void 0;
    class MinimapTokensColorTracker extends lifecycle_1.Disposable {
        static { this._INSTANCE = null; }
        static getInstance() {
            if (!this._INSTANCE) {
                this._INSTANCE = (0, lifecycle_1.markAsSingleton)(new MinimapTokensColorTracker());
            }
            return this._INSTANCE;
        }
        constructor() {
            super();
            this._onDidChange = new event_1.Emitter();
            this.onDidChange = this._onDidChange.event;
            this._updateColorMap();
            this._register(languages_1.TokenizationRegistry.onDidChange(e => {
                if (e.changedColorMap) {
                    this._updateColorMap();
                }
            }));
        }
        _updateColorMap() {
            const colorMap = languages_1.TokenizationRegistry.getColorMap();
            if (!colorMap) {
                this._colors = [rgba_1.RGBA8.Empty];
                this._backgroundIsLight = true;
                return;
            }
            this._colors = [rgba_1.RGBA8.Empty];
            for (let colorId = 1; colorId < colorMap.length; colorId++) {
                const source = colorMap[colorId].rgba;
                // Use a VM friendly data-type
                this._colors[colorId] = new rgba_1.RGBA8(source.r, source.g, source.b, Math.round(source.a * 255));
            }
            const backgroundLuminosity = colorMap[2 /* ColorId.DefaultBackground */].getRelativeLuminance();
            this._backgroundIsLight = backgroundLuminosity >= 0.5;
            this._onDidChange.fire(undefined);
        }
        getColor(colorId) {
            if (colorId < 1 || colorId >= this._colors.length) {
                // background color (basically invisible)
                colorId = 2 /* ColorId.DefaultBackground */;
            }
            return this._colors[colorId];
        }
        backgroundIsLight() {
            return this._backgroundIsLight;
        }
    }
    exports.MinimapTokensColorTracker = MinimapTokensColorTracker;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[375/*vs/editor/common/viewModel/viewModelDecorations*/], __M([1/*require*/,0/*exports*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/,95/*vs/editor/common/viewModel*/,37/*vs/editor/common/config/editorOptions*/]), function (require, exports, position_1, range_1, viewModel_1, editorOptions_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ViewModelDecorations = void 0;
    exports.isModelDecorationVisible = isModelDecorationVisible;
    exports.isModelDecorationInComment = isModelDecorationInComment;
    exports.isModelDecorationInString = isModelDecorationInString;
    class ViewModelDecorations {
        constructor(editorId, model, configuration, linesCollection, coordinatesConverter) {
            this.editorId = editorId;
            this.model = model;
            this.configuration = configuration;
            this._linesCollection = linesCollection;
            this._coordinatesConverter = coordinatesConverter;
            this._decorationsCache = Object.create(null);
            this._cachedModelDecorationsResolver = null;
            this._cachedModelDecorationsResolverViewRange = null;
        }
        _clearCachedModelDecorationsResolver() {
            this._cachedModelDecorationsResolver = null;
            this._cachedModelDecorationsResolverViewRange = null;
        }
        dispose() {
            this._decorationsCache = Object.create(null);
            this._clearCachedModelDecorationsResolver();
        }
        reset() {
            this._decorationsCache = Object.create(null);
            this._clearCachedModelDecorationsResolver();
        }
        onModelDecorationsChanged() {
            this._decorationsCache = Object.create(null);
            this._clearCachedModelDecorationsResolver();
        }
        onLineMappingChanged() {
            this._decorationsCache = Object.create(null);
            this._clearCachedModelDecorationsResolver();
        }
        _getOrCreateViewModelDecoration(modelDecoration) {
            const id = modelDecoration.id;
            let r = this._decorationsCache[id];
            if (!r) {
                const modelRange = modelDecoration.range;
                const options = modelDecoration.options;
                let viewRange;
                if (options.isWholeLine) {
                    const start = this._coordinatesConverter.convertModelPositionToViewPosition(new position_1.Position(modelRange.startLineNumber, 1), 0 /* PositionAffinity.Left */, false, true);
                    const end = this._coordinatesConverter.convertModelPositionToViewPosition(new position_1.Position(modelRange.endLineNumber, this.model.getLineMaxColumn(modelRange.endLineNumber)), 1 /* PositionAffinity.Right */);
                    viewRange = new range_1.Range(start.lineNumber, start.column, end.lineNumber, end.column);
                }
                else {
                    // For backwards compatibility reasons, we want injected text before any decoration.
                    // Thus, move decorations to the right.
                    viewRange = this._coordinatesConverter.convertModelRangeToViewRange(modelRange, 1 /* PositionAffinity.Right */);
                }
                r = new viewModel_1.ViewModelDecoration(viewRange, options);
                this._decorationsCache[id] = r;
            }
            return r;
        }
        getMinimapDecorationsInRange(range) {
            return this._getDecorationsInRange(range, true, false).decorations;
        }
        getDecorationsViewportData(viewRange) {
            let cacheIsValid = (this._cachedModelDecorationsResolver !== null);
            cacheIsValid = cacheIsValid && (viewRange.equalsRange(this._cachedModelDecorationsResolverViewRange));
            if (!cacheIsValid) {
                this._cachedModelDecorationsResolver = this._getDecorationsInRange(viewRange, false, false);
                this._cachedModelDecorationsResolverViewRange = viewRange;
            }
            return this._cachedModelDecorationsResolver;
        }
        getInlineDecorationsOnLine(lineNumber, onlyMinimapDecorations = false, onlyMarginDecorations = false) {
            const range = new range_1.Range(lineNumber, this._linesCollection.getViewLineMinColumn(lineNumber), lineNumber, this._linesCollection.getViewLineMaxColumn(lineNumber));
            return this._getDecorationsInRange(range, onlyMinimapDecorations, onlyMarginDecorations).inlineDecorations[0];
        }
        _getDecorationsInRange(viewRange, onlyMinimapDecorations, onlyMarginDecorations) {
            const modelDecorations = this._linesCollection.getDecorationsInRange(viewRange, this.editorId, (0, editorOptions_1.filterValidationDecorations)(this.configuration.options), onlyMinimapDecorations, onlyMarginDecorations);
            const startLineNumber = viewRange.startLineNumber;
            const endLineNumber = viewRange.endLineNumber;
            const decorationsInViewport = [];
            let decorationsInViewportLen = 0;
            const inlineDecorations = [];
            for (let j = startLineNumber; j <= endLineNumber; j++) {
                inlineDecorations[j - startLineNumber] = [];
            }
            for (let i = 0, len = modelDecorations.length; i < len; i++) {
                const modelDecoration = modelDecorations[i];
                const decorationOptions = modelDecoration.options;
                if (!isModelDecorationVisible(this.model, modelDecoration)) {
                    continue;
                }
                const viewModelDecoration = this._getOrCreateViewModelDecoration(modelDecoration);
                const viewRange = viewModelDecoration.range;
                decorationsInViewport[decorationsInViewportLen++] = viewModelDecoration;
                if (decorationOptions.inlineClassName) {
                    const inlineDecoration = new viewModel_1.InlineDecoration(viewRange, decorationOptions.inlineClassName, decorationOptions.inlineClassNameAffectsLetterSpacing ? 3 /* InlineDecorationType.RegularAffectingLetterSpacing */ : 0 /* InlineDecorationType.Regular */);
                    const intersectedStartLineNumber = Math.max(startLineNumber, viewRange.startLineNumber);
                    const intersectedEndLineNumber = Math.min(endLineNumber, viewRange.endLineNumber);
                    for (let j = intersectedStartLineNumber; j <= intersectedEndLineNumber; j++) {
                        inlineDecorations[j - startLineNumber].push(inlineDecoration);
                    }
                }
                if (decorationOptions.beforeContentClassName) {
                    if (startLineNumber <= viewRange.startLineNumber && viewRange.startLineNumber <= endLineNumber) {
                        const inlineDecoration = new viewModel_1.InlineDecoration(new range_1.Range(viewRange.startLineNumber, viewRange.startColumn, viewRange.startLineNumber, viewRange.startColumn), decorationOptions.beforeContentClassName, 1 /* InlineDecorationType.Before */);
                        inlineDecorations[viewRange.startLineNumber - startLineNumber].push(inlineDecoration);
                    }
                }
                if (decorationOptions.afterContentClassName) {
                    if (startLineNumber <= viewRange.endLineNumber && viewRange.endLineNumber <= endLineNumber) {
                        const inlineDecoration = new viewModel_1.InlineDecoration(new range_1.Range(viewRange.endLineNumber, viewRange.endColumn, viewRange.endLineNumber, viewRange.endColumn), decorationOptions.afterContentClassName, 2 /* InlineDecorationType.After */);
                        inlineDecorations[viewRange.endLineNumber - startLineNumber].push(inlineDecoration);
                    }
                }
            }
            return {
                decorations: decorationsInViewport,
                inlineDecorations: inlineDecorations
            };
        }
    }
    exports.ViewModelDecorations = ViewModelDecorations;
    function isModelDecorationVisible(model, decoration) {
        if (decoration.options.hideInCommentTokens && isModelDecorationInComment(model, decoration)) {
            return false;
        }
        if (decoration.options.hideInStringTokens && isModelDecorationInString(model, decoration)) {
            return false;
        }
        return true;
    }
    function isModelDecorationInComment(model, decoration) {
        return testTokensInRange(model, decoration.range, (tokenType) => tokenType === 1 /* StandardTokenType.Comment */);
    }
    function isModelDecorationInString(model, decoration) {
        return testTokensInRange(model, decoration.range, (tokenType) => tokenType === 2 /* StandardTokenType.String */);
    }
    /**
     * Calls the callback for every token that intersects the range.
     * If the callback returns `false`, iteration stops and `false` is returned.
     * Otherwise, `true` is returned.
     */
    function testTokensInRange(model, range, callback) {
        for (let lineNumber = range.startLineNumber; lineNumber <= range.endLineNumber; lineNumber++) {
            const lineTokens = model.tokenization.getLineTokens(lineNumber);
            const isFirstLine = lineNumber === range.startLineNumber;
            const isEndLine = lineNumber === range.endLineNumber;
            let tokenIdx = isFirstLine ? lineTokens.findTokenIndexAtOffset(range.startColumn - 1) : 0;
            while (tokenIdx < lineTokens.getCount()) {
                if (isEndLine) {
                    const startOffset = lineTokens.getStartOffset(tokenIdx);
                    if (startOffset > range.endColumn - 1) {
                        break;
                    }
                }
                const callbackResult = callback(lineTokens.getStandardTokenType(tokenIdx));
                if (!callbackResult) {
                    return false;
                }
                tokenIdx++;
            }
        }
        return true;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[209/*vs/editor/contrib/gotoSymbol/browser/link/clickLinkGesture*/], __M([1/*require*/,0/*exports*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,16/*vs/base/common/platform*/]), function (require, exports, event_1, lifecycle_1, platform) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ClickLinkGesture = exports.ClickLinkOptions = exports.ClickLinkKeyboardEvent = exports.ClickLinkMouseEvent = void 0;
    function hasModifier(e, modifier) {
        return !!e[modifier];
    }
    /**
     * An event that encapsulates the various trigger modifiers logic needed for go to definition.
     */
    class ClickLinkMouseEvent {
        constructor(source, opts) {
            this.target = source.target;
            this.isLeftClick = source.event.leftButton;
            this.isMiddleClick = source.event.middleButton;
            this.isRightClick = source.event.rightButton;
            this.hasTriggerModifier = hasModifier(source.event, opts.triggerModifier);
            this.hasSideBySideModifier = hasModifier(source.event, opts.triggerSideBySideModifier);
            this.isNoneOrSingleMouseDown = (source.event.detail <= 1);
        }
    }
    exports.ClickLinkMouseEvent = ClickLinkMouseEvent;
    /**
     * An event that encapsulates the various trigger modifiers logic needed for go to definition.
     */
    class ClickLinkKeyboardEvent {
        constructor(source, opts) {
            this.keyCodeIsTriggerKey = (source.keyCode === opts.triggerKey);
            this.keyCodeIsSideBySideKey = (source.keyCode === opts.triggerSideBySideKey);
            this.hasTriggerModifier = hasModifier(source, opts.triggerModifier);
        }
    }
    exports.ClickLinkKeyboardEvent = ClickLinkKeyboardEvent;
    class ClickLinkOptions {
        constructor(triggerKey, triggerModifier, triggerSideBySideKey, triggerSideBySideModifier) {
            this.triggerKey = triggerKey;
            this.triggerModifier = triggerModifier;
            this.triggerSideBySideKey = triggerSideBySideKey;
            this.triggerSideBySideModifier = triggerSideBySideModifier;
        }
        equals(other) {
            return (this.triggerKey === other.triggerKey
                && this.triggerModifier === other.triggerModifier
                && this.triggerSideBySideKey === other.triggerSideBySideKey
                && this.triggerSideBySideModifier === other.triggerSideBySideModifier);
        }
    }
    exports.ClickLinkOptions = ClickLinkOptions;
    function createOptions(multiCursorModifier) {
        if (multiCursorModifier === 'altKey') {
            if (platform.isMacintosh) {
                return new ClickLinkOptions(57 /* KeyCode.Meta */, 'metaKey', 6 /* KeyCode.Alt */, 'altKey');
            }
            return new ClickLinkOptions(5 /* KeyCode.Ctrl */, 'ctrlKey', 6 /* KeyCode.Alt */, 'altKey');
        }
        if (platform.isMacintosh) {
            return new ClickLinkOptions(6 /* KeyCode.Alt */, 'altKey', 57 /* KeyCode.Meta */, 'metaKey');
        }
        return new ClickLinkOptions(6 /* KeyCode.Alt */, 'altKey', 5 /* KeyCode.Ctrl */, 'ctrlKey');
    }
    class ClickLinkGesture extends lifecycle_1.Disposable {
        constructor(editor, opts) {
            super();
            this._onMouseMoveOrRelevantKeyDown = this._register(new event_1.Emitter());
            this.onMouseMoveOrRelevantKeyDown = this._onMouseMoveOrRelevantKeyDown.event;
            this._onExecute = this._register(new event_1.Emitter());
            this.onExecute = this._onExecute.event;
            this._onCancel = this._register(new event_1.Emitter());
            this.onCancel = this._onCancel.event;
            this._editor = editor;
            this._extractLineNumberFromMouseEvent = opts?.extractLineNumberFromMouseEvent ?? ((e) => e.target.position ? e.target.position.lineNumber : 0);
            this._opts = createOptions(this._editor.getOption(78 /* EditorOption.multiCursorModifier */));
            this._lastMouseMoveEvent = null;
            this._hasTriggerKeyOnMouseDown = false;
            this._lineNumberOnMouseDown = 0;
            this._register(this._editor.onDidChangeConfiguration((e) => {
                if (e.hasChanged(78 /* EditorOption.multiCursorModifier */)) {
                    const newOpts = createOptions(this._editor.getOption(78 /* EditorOption.multiCursorModifier */));
                    if (this._opts.equals(newOpts)) {
                        return;
                    }
                    this._opts = newOpts;
                    this._lastMouseMoveEvent = null;
                    this._hasTriggerKeyOnMouseDown = false;
                    this._lineNumberOnMouseDown = 0;
                    this._onCancel.fire();
                }
            }));
            this._register(this._editor.onMouseMove((e) => this._onEditorMouseMove(new ClickLinkMouseEvent(e, this._opts))));
            this._register(this._editor.onMouseDown((e) => this._onEditorMouseDown(new ClickLinkMouseEvent(e, this._opts))));
            this._register(this._editor.onMouseUp((e) => this._onEditorMouseUp(new ClickLinkMouseEvent(e, this._opts))));
            this._register(this._editor.onKeyDown((e) => this._onEditorKeyDown(new ClickLinkKeyboardEvent(e, this._opts))));
            this._register(this._editor.onKeyUp((e) => this._onEditorKeyUp(new ClickLinkKeyboardEvent(e, this._opts))));
            this._register(this._editor.onMouseDrag(() => this._resetHandler()));
            this._register(this._editor.onDidChangeCursorSelection((e) => this._onDidChangeCursorSelection(e)));
            this._register(this._editor.onDidChangeModel((e) => this._resetHandler()));
            this._register(this._editor.onDidChangeModelContent(() => this._resetHandler()));
            this._register(this._editor.onDidScrollChange((e) => {
                if (e.scrollTopChanged || e.scrollLeftChanged) {
                    this._resetHandler();
                }
            }));
        }
        _onDidChangeCursorSelection(e) {
            if (e.selection && e.selection.startColumn !== e.selection.endColumn) {
                this._resetHandler(); // immediately stop this feature if the user starts to select (https://github.com/microsoft/vscode/issues/7827)
            }
        }
        _onEditorMouseMove(mouseEvent) {
            this._lastMouseMoveEvent = mouseEvent;
            this._onMouseMoveOrRelevantKeyDown.fire([mouseEvent, null]);
        }
        _onEditorMouseDown(mouseEvent) {
            // We need to record if we had the trigger key on mouse down because someone might select something in the editor
            // holding the mouse down and then while mouse is down start to press Ctrl/Cmd to start a copy operation and then
            // release the mouse button without wanting to do the navigation.
            // With this flag we prevent goto definition if the mouse was down before the trigger key was pressed.
            this._hasTriggerKeyOnMouseDown = mouseEvent.hasTriggerModifier;
            this._lineNumberOnMouseDown = this._extractLineNumberFromMouseEvent(mouseEvent);
        }
        _onEditorMouseUp(mouseEvent) {
            const currentLineNumber = this._extractLineNumberFromMouseEvent(mouseEvent);
            if (this._hasTriggerKeyOnMouseDown && this._lineNumberOnMouseDown && this._lineNumberOnMouseDown === currentLineNumber) {
                this._onExecute.fire(mouseEvent);
            }
        }
        _onEditorKeyDown(e) {
            if (this._lastMouseMoveEvent
                && (e.keyCodeIsTriggerKey // User just pressed Ctrl/Cmd (normal goto definition)
                    || (e.keyCodeIsSideBySideKey && e.hasTriggerModifier) // User pressed Ctrl/Cmd+Alt (goto definition to the side)
                )) {
                this._onMouseMoveOrRelevantKeyDown.fire([this._lastMouseMoveEvent, e]);
            }
            else if (e.hasTriggerModifier) {
                this._onCancel.fire(); // remove decorations if user holds another key with ctrl/cmd to prevent accident goto declaration
            }
        }
        _onEditorKeyUp(e) {
            if (e.keyCodeIsTriggerKey) {
                this._onCancel.fire();
            }
        }
        _resetHandler() {
            this._lastMouseMoveEvent = null;
            this._hasTriggerKeyOnMouseDown = false;
            this._onCancel.fire();
        }
    }
    exports.ClickLinkGesture = ClickLinkGesture;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[178/*vs/editor/contrib/gotoSymbol/browser/referencesModel*/], __M([1/*require*/,0/*exports*/,8/*vs/base/common/errors*/,6/*vs/base/common/event*/,187/*vs/base/common/idGenerator*/,2/*vs/base/common/lifecycle*/,45/*vs/base/common/map*/,48/*vs/base/common/resources*/,11/*vs/base/common/strings*/,4/*vs/editor/common/core/range*/,3/*vs/nls*/]), function (require, exports, errors_1, event_1, idGenerator_1, lifecycle_1, map_1, resources_1, strings, range_1, nls_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ReferencesModel = exports.FileReferences = exports.FilePreview = exports.OneReference = void 0;
    class OneReference {
        constructor(isProviderFirst, parent, link, _rangeCallback) {
            this.isProviderFirst = isProviderFirst;
            this.parent = parent;
            this.link = link;
            this._rangeCallback = _rangeCallback;
            this.id = idGenerator_1.defaultGenerator.nextId();
        }
        get uri() {
            return this.link.uri;
        }
        get range() {
            return this._range ?? this.link.targetSelectionRange ?? this.link.range;
        }
        set range(value) {
            this._range = value;
            this._rangeCallback(this);
        }
        get ariaMessage() {
            const preview = this.parent.getPreview(this)?.preview(this.range);
            if (!preview) {
                return (0, nls_1.localize)(995, "in {0} on line {1} at column {2}", (0, resources_1.basename)(this.uri), this.range.startLineNumber, this.range.startColumn);
            }
            else {
                return (0, nls_1.localize)(996, "{0} in {1} on line {2} at column {3}", preview.value, (0, resources_1.basename)(this.uri), this.range.startLineNumber, this.range.startColumn);
            }
        }
    }
    exports.OneReference = OneReference;
    class FilePreview {
        constructor(_modelReference) {
            this._modelReference = _modelReference;
        }
        dispose() {
            this._modelReference.dispose();
        }
        preview(range, n = 8) {
            const model = this._modelReference.object.textEditorModel;
            if (!model) {
                return undefined;
            }
            const { startLineNumber, startColumn, endLineNumber, endColumn } = range;
            const word = model.getWordUntilPosition({ lineNumber: startLineNumber, column: startColumn - n });
            const beforeRange = new range_1.Range(startLineNumber, word.startColumn, startLineNumber, startColumn);
            const afterRange = new range_1.Range(endLineNumber, endColumn, endLineNumber, 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */);
            const before = model.getValueInRange(beforeRange).replace(/^\s+/, '');
            const inside = model.getValueInRange(range);
            const after = model.getValueInRange(afterRange).replace(/\s+$/, '');
            return {
                value: before + inside + after,
                highlight: { start: before.length, end: before.length + inside.length }
            };
        }
    }
    exports.FilePreview = FilePreview;
    class FileReferences {
        constructor(parent, uri) {
            this.parent = parent;
            this.uri = uri;
            this.children = [];
            this._previews = new map_1.ResourceMap();
        }
        dispose() {
            (0, lifecycle_1.dispose)(this._previews.values());
            this._previews.clear();
        }
        getPreview(child) {
            return this._previews.get(child.uri);
        }
        get ariaMessage() {
            const len = this.children.length;
            if (len === 1) {
                return (0, nls_1.localize)(997, "1 symbol in {0}, full path {1}", (0, resources_1.basename)(this.uri), this.uri.fsPath);
            }
            else {
                return (0, nls_1.localize)(998, "{0} symbols in {1}, full path {2}", len, (0, resources_1.basename)(this.uri), this.uri.fsPath);
            }
        }
        async resolve(textModelResolverService) {
            if (this._previews.size !== 0) {
                return this;
            }
            for (const child of this.children) {
                if (this._previews.has(child.uri)) {
                    continue;
                }
                try {
                    const ref = await textModelResolverService.createModelReference(child.uri);
                    this._previews.set(child.uri, new FilePreview(ref));
                }
                catch (err) {
                    (0, errors_1.onUnexpectedError)(err);
                }
            }
            return this;
        }
    }
    exports.FileReferences = FileReferences;
    class ReferencesModel {
        constructor(links, title) {
            this.groups = [];
            this.references = [];
            this._onDidChangeReferenceRange = new event_1.Emitter();
            this.onDidChangeReferenceRange = this._onDidChangeReferenceRange.event;
            this._links = links;
            this._title = title;
            // grouping and sorting
            const [providersFirst] = links;
            links.sort(ReferencesModel._compareReferences);
            let current;
            for (const link of links) {
                if (!current || !resources_1.extUri.isEqual(current.uri, link.uri, true)) {
                    // new group
                    current = new FileReferences(this, link.uri);
                    this.groups.push(current);
                }
                // append, check for equality first!
                if (current.children.length === 0 || ReferencesModel._compareReferences(link, current.children[current.children.length - 1]) !== 0) {
                    const oneRef = new OneReference(providersFirst === link, current, link, ref => this._onDidChangeReferenceRange.fire(ref));
                    this.references.push(oneRef);
                    current.children.push(oneRef);
                }
            }
        }
        dispose() {
            (0, lifecycle_1.dispose)(this.groups);
            this._onDidChangeReferenceRange.dispose();
            this.groups.length = 0;
        }
        clone() {
            return new ReferencesModel(this._links, this._title);
        }
        get title() {
            return this._title;
        }
        get isEmpty() {
            return this.groups.length === 0;
        }
        get ariaMessage() {
            if (this.isEmpty) {
                return (0, nls_1.localize)(999, "No results found");
            }
            else if (this.references.length === 1) {
                return (0, nls_1.localize)(1000, "Found 1 symbol in {0}", this.references[0].uri.fsPath);
            }
            else if (this.groups.length === 1) {
                return (0, nls_1.localize)(1001, "Found {0} symbols in {1}", this.references.length, this.groups[0].uri.fsPath);
            }
            else {
                return (0, nls_1.localize)(1002, "Found {0} symbols in {1} files", this.references.length, this.groups.length);
            }
        }
        nextOrPreviousReference(reference, next) {
            const { parent } = reference;
            let idx = parent.children.indexOf(reference);
            const childCount = parent.children.length;
            const groupCount = parent.parent.groups.length;
            if (groupCount === 1 || next && idx + 1 < childCount || !next && idx > 0) {
                // cycling within one file
                if (next) {
                    idx = (idx + 1) % childCount;
                }
                else {
                    idx = (idx + childCount - 1) % childCount;
                }
                return parent.children[idx];
            }
            idx = parent.parent.groups.indexOf(parent);
            if (next) {
                idx = (idx + 1) % groupCount;
                return parent.parent.groups[idx].children[0];
            }
            else {
                idx = (idx + groupCount - 1) % groupCount;
                return parent.parent.groups[idx].children[parent.parent.groups[idx].children.length - 1];
            }
        }
        nearestReference(resource, position) {
            const nearest = this.references.map((ref, idx) => {
                return {
                    idx,
                    prefixLen: strings.commonPrefixLength(ref.uri.toString(), resource.toString()),
                    offsetDist: Math.abs(ref.range.startLineNumber - position.lineNumber) * 100 + Math.abs(ref.range.startColumn - position.column)
                };
            }).sort((a, b) => {
                if (a.prefixLen > b.prefixLen) {
                    return -1;
                }
                else if (a.prefixLen < b.prefixLen) {
                    return 1;
                }
                else if (a.offsetDist < b.offsetDist) {
                    return -1;
                }
                else if (a.offsetDist > b.offsetDist) {
                    return 1;
                }
                else {
                    return 0;
                }
            })[0];
            if (nearest) {
                return this.references[nearest.idx];
            }
            return undefined;
        }
        referenceAt(resource, position) {
            for (const ref of this.references) {
                if (ref.uri.toString() === resource.toString()) {
                    if (range_1.Range.containsPosition(ref.range, position)) {
                        return ref;
                    }
                }
            }
            return undefined;
        }
        firstReference() {
            for (const ref of this.references) {
                if (ref.isProviderFirst) {
                    return ref;
                }
            }
            return this.references[0];
        }
        static _compareReferences(a, b) {
            return resources_1.extUri.compare(a.uri, b.uri) || range_1.Range.compareRangesUsingStarts(a.range, b.range);
        }
    }
    exports.ReferencesModel = ReferencesModel;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[668/*vs/editor/contrib/hover/browser/contentHoverComputer*/], __M([1/*require*/,0/*exports*/,13/*vs/base/common/arrays*/,14/*vs/base/common/async*/]), function (require, exports, arrays_1, async_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ContentHoverComputer = void 0;
    class ContentHoverComputer {
        get anchor() { return this._anchor; }
        set anchor(value) { this._anchor = value; }
        get shouldFocus() { return this._shouldFocus; }
        set shouldFocus(value) { this._shouldFocus = value; }
        get source() { return this._source; }
        set source(value) { this._source = value; }
        get insistOnKeepingHoverVisible() { return this._insistOnKeepingHoverVisible; }
        set insistOnKeepingHoverVisible(value) { this._insistOnKeepingHoverVisible = value; }
        constructor(_editor, _participants) {
            this._editor = _editor;
            this._participants = _participants;
            this._anchor = null;
            this._shouldFocus = false;
            this._source = 0 /* HoverStartSource.Mouse */;
            this._insistOnKeepingHoverVisible = false;
        }
        static _getLineDecorations(editor, anchor) {
            if (anchor.type !== 1 /* HoverAnchorType.Range */ && !anchor.supportsMarkerHover) {
                return [];
            }
            const model = editor.getModel();
            const lineNumber = anchor.range.startLineNumber;
            if (lineNumber > model.getLineCount()) {
                // invalid line
                return [];
            }
            const maxColumn = model.getLineMaxColumn(lineNumber);
            return editor.getLineDecorations(lineNumber).filter((d) => {
                if (d.options.isWholeLine) {
                    return true;
                }
                const startColumn = (d.range.startLineNumber === lineNumber) ? d.range.startColumn : 1;
                const endColumn = (d.range.endLineNumber === lineNumber) ? d.range.endColumn : maxColumn;
                if (d.options.showIfCollapsed) {
                    // Relax check around `showIfCollapsed` decorations to also include +/- 1 character
                    if (startColumn > anchor.range.startColumn + 1 || anchor.range.endColumn - 1 > endColumn) {
                        return false;
                    }
                }
                else {
                    if (startColumn > anchor.range.startColumn || anchor.range.endColumn > endColumn) {
                        return false;
                    }
                }
                return true;
            });
        }
        computeAsync(token) {
            const anchor = this._anchor;
            if (!this._editor.hasModel() || !anchor) {
                return async_1.AsyncIterableObject.EMPTY;
            }
            const lineDecorations = ContentHoverComputer._getLineDecorations(this._editor, anchor);
            return async_1.AsyncIterableObject.merge(this._participants.map((participant) => {
                if (!participant.computeAsync) {
                    return async_1.AsyncIterableObject.EMPTY;
                }
                return participant.computeAsync(anchor, lineDecorations, token);
            }));
        }
        computeSync() {
            if (!this._editor.hasModel() || !this._anchor) {
                return [];
            }
            const lineDecorations = ContentHoverComputer._getLineDecorations(this._editor, this._anchor);
            let result = [];
            for (const participant of this._participants) {
                result = result.concat(participant.computeSync(this._anchor, lineDecorations));
            }
            return (0, arrays_1.coalesce)(result);
        }
    }
    exports.ContentHoverComputer = ContentHoverComputer;
});

define(__m[264/*vs/editor/contrib/hover/browser/hoverActionIds*/], __M([1/*require*/,0/*exports*/,3/*vs/nls*/]), function (require, exports, nls) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DECREASE_HOVER_VERBOSITY_ACTION_LABEL = exports.DECREASE_HOVER_VERBOSITY_ACTION_ID = exports.INCREASE_HOVER_VERBOSITY_ACTION_LABEL = exports.INCREASE_HOVER_VERBOSITY_ACTION_ID = exports.GO_TO_BOTTOM_HOVER_ACTION_ID = exports.GO_TO_TOP_HOVER_ACTION_ID = exports.PAGE_DOWN_HOVER_ACTION_ID = exports.PAGE_UP_HOVER_ACTION_ID = exports.SCROLL_RIGHT_HOVER_ACTION_ID = exports.SCROLL_LEFT_HOVER_ACTION_ID = exports.SCROLL_DOWN_HOVER_ACTION_ID = exports.SCROLL_UP_HOVER_ACTION_ID = exports.SHOW_DEFINITION_PREVIEW_HOVER_ACTION_ID = exports.SHOW_OR_FOCUS_HOVER_ACTION_ID = void 0;
    exports.SHOW_OR_FOCUS_HOVER_ACTION_ID = 'editor.action.showHover';
    exports.SHOW_DEFINITION_PREVIEW_HOVER_ACTION_ID = 'editor.action.showDefinitionPreviewHover';
    exports.SCROLL_UP_HOVER_ACTION_ID = 'editor.action.scrollUpHover';
    exports.SCROLL_DOWN_HOVER_ACTION_ID = 'editor.action.scrollDownHover';
    exports.SCROLL_LEFT_HOVER_ACTION_ID = 'editor.action.scrollLeftHover';
    exports.SCROLL_RIGHT_HOVER_ACTION_ID = 'editor.action.scrollRightHover';
    exports.PAGE_UP_HOVER_ACTION_ID = 'editor.action.pageUpHover';
    exports.PAGE_DOWN_HOVER_ACTION_ID = 'editor.action.pageDownHover';
    exports.GO_TO_TOP_HOVER_ACTION_ID = 'editor.action.goToTopHover';
    exports.GO_TO_BOTTOM_HOVER_ACTION_ID = 'editor.action.goToBottomHover';
    exports.INCREASE_HOVER_VERBOSITY_ACTION_ID = 'editor.action.increaseHoverVerbosityLevel';
    exports.INCREASE_HOVER_VERBOSITY_ACTION_LABEL = nls.localize(1006, "Increase Hover Verbosity Level");
    exports.DECREASE_HOVER_VERBOSITY_ACTION_ID = 'editor.action.decreaseHoverVerbosityLevel';
    exports.DECREASE_HOVER_VERBOSITY_ACTION_LABEL = nls.localize(1007, "Decrease Hover Verbosity Level");
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[376/*vs/editor/contrib/hover/browser/hoverOperation*/], __M([1/*require*/,0/*exports*/,14/*vs/base/common/async*/,8/*vs/base/common/errors*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/]), function (require, exports, async_1, errors_1, event_1, lifecycle_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.HoverOperation = exports.HoverResult = void 0;
    class HoverResult {
        constructor(value, isComplete, hasLoadingMessage) {
            this.value = value;
            this.isComplete = isComplete;
            this.hasLoadingMessage = hasLoadingMessage;
        }
    }
    exports.HoverResult = HoverResult;
    /**
     * Computing the hover is very fine tuned.
     *
     * Suppose the hover delay is 300ms (the default). Then, when resting the mouse at an anchor:
     * - at 150ms, the async computation is triggered (i.e. semantic hover)
     *   - if async results already come in, they are not rendered yet.
     * - at 300ms, the sync computation is triggered (i.e. decorations, markers)
     *   - if there are sync or async results, they are rendered.
     * - at 900ms, if the async computation hasn't finished, a "Loading..." result is added.
     */
    class HoverOperation extends lifecycle_1.Disposable {
        constructor(_editor, _computer) {
            super();
            this._editor = _editor;
            this._computer = _computer;
            this._onResult = this._register(new event_1.Emitter());
            this.onResult = this._onResult.event;
            this._firstWaitScheduler = this._register(new async_1.RunOnceScheduler(() => this._triggerAsyncComputation(), 0));
            this._secondWaitScheduler = this._register(new async_1.RunOnceScheduler(() => this._triggerSyncComputation(), 0));
            this._loadingMessageScheduler = this._register(new async_1.RunOnceScheduler(() => this._triggerLoadingMessage(), 0));
            this._state = 0 /* HoverOperationState.Idle */;
            this._asyncIterable = null;
            this._asyncIterableDone = false;
            this._result = [];
        }
        dispose() {
            if (this._asyncIterable) {
                this._asyncIterable.cancel();
                this._asyncIterable = null;
            }
            super.dispose();
        }
        get _hoverTime() {
            return this._editor.getOption(60 /* EditorOption.hover */).delay;
        }
        get _firstWaitTime() {
            return this._hoverTime / 2;
        }
        get _secondWaitTime() {
            return this._hoverTime - this._firstWaitTime;
        }
        get _loadingMessageTime() {
            return 3 * this._hoverTime;
        }
        _setState(state, fireResult = true) {
            this._state = state;
            if (fireResult) {
                this._fireResult();
            }
        }
        _triggerAsyncComputation() {
            this._setState(2 /* HoverOperationState.SecondWait */);
            this._secondWaitScheduler.schedule(this._secondWaitTime);
            if (this._computer.computeAsync) {
                this._asyncIterableDone = false;
                this._asyncIterable = (0, async_1.createCancelableAsyncIterable)(token => this._computer.computeAsync(token));
                (async () => {
                    try {
                        for await (const item of this._asyncIterable) {
                            if (item) {
                                this._result.push(item);
                                this._fireResult();
                            }
                        }
                        this._asyncIterableDone = true;
                        if (this._state === 3 /* HoverOperationState.WaitingForAsync */ || this._state === 4 /* HoverOperationState.WaitingForAsyncShowingLoading */) {
                            this._setState(0 /* HoverOperationState.Idle */);
                        }
                    }
                    catch (e) {
                        (0, errors_1.onUnexpectedError)(e);
                    }
                })();
            }
            else {
                this._asyncIterableDone = true;
            }
        }
        _triggerSyncComputation() {
            if (this._computer.computeSync) {
                this._result = this._result.concat(this._computer.computeSync());
            }
            this._setState(this._asyncIterableDone ? 0 /* HoverOperationState.Idle */ : 3 /* HoverOperationState.WaitingForAsync */);
        }
        _triggerLoadingMessage() {
            if (this._state === 3 /* HoverOperationState.WaitingForAsync */) {
                this._setState(4 /* HoverOperationState.WaitingForAsyncShowingLoading */);
            }
        }
        _fireResult() {
            if (this._state === 1 /* HoverOperationState.FirstWait */ || this._state === 2 /* HoverOperationState.SecondWait */) {
                // Do not send out results before the hover time
                return;
            }
            const isComplete = (this._state === 0 /* HoverOperationState.Idle */);
            const hasLoadingMessage = (this._state === 4 /* HoverOperationState.WaitingForAsyncShowingLoading */);
            this._onResult.fire(new HoverResult(this._result.slice(0), isComplete, hasLoadingMessage));
        }
        start(mode) {
            if (mode === 0 /* HoverStartMode.Delayed */) {
                if (this._state === 0 /* HoverOperationState.Idle */) {
                    this._setState(1 /* HoverOperationState.FirstWait */);
                    this._firstWaitScheduler.schedule(this._firstWaitTime);
                    this._loadingMessageScheduler.schedule(this._loadingMessageTime);
                }
            }
            else {
                switch (this._state) {
                    case 0 /* HoverOperationState.Idle */:
                        this._triggerAsyncComputation();
                        this._secondWaitScheduler.cancel();
                        this._triggerSyncComputation();
                        break;
                    case 2 /* HoverOperationState.SecondWait */:
                        this._secondWaitScheduler.cancel();
                        this._triggerSyncComputation();
                        break;
                }
            }
        }
        cancel() {
            this._firstWaitScheduler.cancel();
            this._secondWaitScheduler.cancel();
            this._loadingMessageScheduler.cancel();
            if (this._asyncIterable) {
                this._asyncIterable.cancel();
                this._asyncIterable = null;
            }
            this._result = [];
            this._setState(0 /* HoverOperationState.Idle */, false);
        }
    }
    exports.HoverOperation = HoverOperation;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[210/*vs/editor/contrib/hover/browser/hoverUtils*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/]), function (require, exports, dom) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.isMousePositionWithinElement = isMousePositionWithinElement;
    function isMousePositionWithinElement(element, posx, posy) {
        const elementRect = dom.getDomNodePagePosition(element);
        if (posx < elementRect.left
            || posx > elementRect.left + elementRect.width
            || posy < elementRect.top
            || posy > elementRect.top + elementRect.height) {
            return false;
        }
        return true;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[669/*vs/editor/contrib/hover/browser/marginHoverComputer*/], __M([1/*require*/,0/*exports*/,13/*vs/base/common/arrays*/,57/*vs/base/common/htmlContent*/,40/*vs/editor/common/model*/]), function (require, exports, arrays_1, htmlContent_1, model_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MarginHoverComputer = void 0;
    class MarginHoverComputer {
        get lineNumber() {
            return this._lineNumber;
        }
        set lineNumber(value) {
            this._lineNumber = value;
        }
        get lane() {
            return this._laneOrLine;
        }
        set lane(value) {
            this._laneOrLine = value;
        }
        constructor(_editor) {
            this._editor = _editor;
            this._lineNumber = -1;
            this._laneOrLine = model_1.GlyphMarginLane.Center;
        }
        computeSync() {
            const toHoverMessage = (contents) => {
                return {
                    value: contents
                };
            };
            const lineDecorations = this._editor.getLineDecorations(this._lineNumber);
            const result = [];
            const isLineHover = this._laneOrLine === 'lineNo';
            if (!lineDecorations) {
                return result;
            }
            for (const d of lineDecorations) {
                const lane = d.options.glyphMargin?.position ?? model_1.GlyphMarginLane.Center;
                if (!isLineHover && lane !== this._laneOrLine) {
                    continue;
                }
                const hoverMessage = isLineHover ? d.options.lineNumberHoverMessage : d.options.glyphMarginHoverMessage;
                if (!hoverMessage || (0, htmlContent_1.isEmptyMarkdownString)(hoverMessage)) {
                    continue;
                }
                result.push(...(0, arrays_1.asArray)(hoverMessage).map(toHoverMessage));
            }
            return result;
        }
    }
    exports.MarginHoverComputer = MarginHoverComputer;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[670/*vs/editor/contrib/hover/browser/resizableContentWidget*/], __M([1/*require*/,0/*exports*/,255/*vs/base/browser/ui/resizable/resizable*/,2/*vs/base/common/lifecycle*/,9/*vs/editor/common/core/position*/,5/*vs/base/browser/dom*/]), function (require, exports, resizable_1, lifecycle_1, position_1, dom) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ResizableContentWidget = void 0;
    const TOP_HEIGHT = 30;
    const BOTTOM_HEIGHT = 24;
    class ResizableContentWidget extends lifecycle_1.Disposable {
        constructor(_editor, minimumSize = new dom.Dimension(10, 10)) {
            super();
            this._editor = _editor;
            this.allowEditorOverflow = true;
            this.suppressMouseDown = false;
            this._resizableNode = this._register(new resizable_1.ResizableHTMLElement());
            this._contentPosition = null;
            this._isResizing = false;
            this._resizableNode.domNode.style.position = 'absolute';
            this._resizableNode.minSize = dom.Dimension.lift(minimumSize);
            this._resizableNode.layout(minimumSize.height, minimumSize.width);
            this._resizableNode.enableSashes(true, true, true, true);
            this._register(this._resizableNode.onDidResize(e => {
                this._resize(new dom.Dimension(e.dimension.width, e.dimension.height));
                if (e.done) {
                    this._isResizing = false;
                }
            }));
            this._register(this._resizableNode.onDidWillResize(() => {
                this._isResizing = true;
            }));
        }
        get isResizing() {
            return this._isResizing;
        }
        getDomNode() {
            return this._resizableNode.domNode;
        }
        getPosition() {
            return this._contentPosition;
        }
        get position() {
            return this._contentPosition?.position ? position_1.Position.lift(this._contentPosition.position) : undefined;
        }
        _availableVerticalSpaceAbove(position) {
            const editorDomNode = this._editor.getDomNode();
            const mouseBox = this._editor.getScrolledVisiblePosition(position);
            if (!editorDomNode || !mouseBox) {
                return;
            }
            const editorBox = dom.getDomNodePagePosition(editorDomNode);
            return editorBox.top + mouseBox.top - TOP_HEIGHT;
        }
        _availableVerticalSpaceBelow(position) {
            const editorDomNode = this._editor.getDomNode();
            const mouseBox = this._editor.getScrolledVisiblePosition(position);
            if (!editorDomNode || !mouseBox) {
                return;
            }
            const editorBox = dom.getDomNodePagePosition(editorDomNode);
            const bodyBox = dom.getClientArea(editorDomNode.ownerDocument.body);
            const mouseBottom = editorBox.top + mouseBox.top + mouseBox.height;
            return bodyBox.height - mouseBottom - BOTTOM_HEIGHT;
        }
        _findPositionPreference(widgetHeight, showAtPosition) {
            const maxHeightBelow = Math.min(this._availableVerticalSpaceBelow(showAtPosition) ?? Infinity, widgetHeight);
            const maxHeightAbove = Math.min(this._availableVerticalSpaceAbove(showAtPosition) ?? Infinity, widgetHeight);
            const maxHeight = Math.min(Math.max(maxHeightAbove, maxHeightBelow), widgetHeight);
            const height = Math.min(widgetHeight, maxHeight);
            let renderingAbove;
            if (this._editor.getOption(60 /* EditorOption.hover */).above) {
                renderingAbove = height <= maxHeightAbove ? 1 /* ContentWidgetPositionPreference.ABOVE */ : 2 /* ContentWidgetPositionPreference.BELOW */;
            }
            else {
                renderingAbove = height <= maxHeightBelow ? 2 /* ContentWidgetPositionPreference.BELOW */ : 1 /* ContentWidgetPositionPreference.ABOVE */;
            }
            if (renderingAbove === 1 /* ContentWidgetPositionPreference.ABOVE */) {
                this._resizableNode.enableSashes(true, true, false, false);
            }
            else {
                this._resizableNode.enableSashes(false, true, true, false);
            }
            return renderingAbove;
        }
        _resize(dimension) {
            this._resizableNode.layout(dimension.height, dimension.width);
        }
    }
    exports.ResizableContentWidget = ResizableContentWidget;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[377/*vs/editor/contrib/inlayHints/browser/inlayHints*/], __M([1/*require*/,0/*exports*/,8/*vs/base/common/errors*/,2/*vs/base/common/lifecycle*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/,42/*vs/base/common/network*/,22/*vs/base/common/uri*/]), function (require, exports, errors_1, lifecycle_1, position_1, range_1, network_1, uri_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.InlayHintsFragments = exports.InlayHintItem = exports.InlayHintAnchor = void 0;
    exports.asCommandLink = asCommandLink;
    class InlayHintAnchor {
        constructor(range, direction) {
            this.range = range;
            this.direction = direction;
        }
    }
    exports.InlayHintAnchor = InlayHintAnchor;
    class InlayHintItem {
        constructor(hint, anchor, provider) {
            this.hint = hint;
            this.anchor = anchor;
            this.provider = provider;
            this._isResolved = false;
        }
        with(delta) {
            const result = new InlayHintItem(this.hint, delta.anchor, this.provider);
            result._isResolved = this._isResolved;
            result._currentResolve = this._currentResolve;
            return result;
        }
        async resolve(token) {
            if (typeof this.provider.resolveInlayHint !== 'function') {
                return;
            }
            if (this._currentResolve) {
                // wait for an active resolve operation and try again
                // when that's done.
                await this._currentResolve;
                if (token.isCancellationRequested) {
                    return;
                }
                return this.resolve(token);
            }
            if (!this._isResolved) {
                this._currentResolve = this._doResolve(token)
                    .finally(() => this._currentResolve = undefined);
            }
            await this._currentResolve;
        }
        async _doResolve(token) {
            try {
                const newHint = await Promise.resolve(this.provider.resolveInlayHint(this.hint, token));
                this.hint.tooltip = newHint?.tooltip ?? this.hint.tooltip;
                this.hint.label = newHint?.label ?? this.hint.label;
                this.hint.textEdits = newHint?.textEdits ?? this.hint.textEdits;
                this._isResolved = true;
            }
            catch (err) {
                (0, errors_1.onUnexpectedExternalError)(err);
                this._isResolved = false;
            }
        }
    }
    exports.InlayHintItem = InlayHintItem;
    class InlayHintsFragments {
        static { this._emptyInlayHintList = Object.freeze({ dispose() { }, hints: [] }); }
        static async create(registry, model, ranges, token) {
            const data = [];
            const promises = registry.ordered(model).reverse().map(provider => ranges.map(async (range) => {
                try {
                    const result = await provider.provideInlayHints(model, range, token);
                    if (result?.hints.length || provider.onDidChangeInlayHints) {
                        data.push([result ?? InlayHintsFragments._emptyInlayHintList, provider]);
                    }
                }
                catch (err) {
                    (0, errors_1.onUnexpectedExternalError)(err);
                }
            }));
            await Promise.all(promises.flat());
            if (token.isCancellationRequested || model.isDisposed()) {
                throw new errors_1.CancellationError();
            }
            return new InlayHintsFragments(ranges, data, model);
        }
        constructor(ranges, data, model) {
            this._disposables = new lifecycle_1.DisposableStore();
            this.ranges = ranges;
            this.provider = new Set();
            const items = [];
            for (const [list, provider] of data) {
                this._disposables.add(list);
                this.provider.add(provider);
                for (const hint of list.hints) {
                    // compute the range to which the item should be attached to
                    const position = model.validatePosition(hint.position);
                    let direction = 'before';
                    const wordRange = InlayHintsFragments._getRangeAtPosition(model, position);
                    let range;
                    if (wordRange.getStartPosition().isBefore(position)) {
                        range = range_1.Range.fromPositions(wordRange.getStartPosition(), position);
                        direction = 'after';
                    }
                    else {
                        range = range_1.Range.fromPositions(position, wordRange.getEndPosition());
                        direction = 'before';
                    }
                    items.push(new InlayHintItem(hint, new InlayHintAnchor(range, direction), provider));
                }
            }
            this.items = items.sort((a, b) => position_1.Position.compare(a.hint.position, b.hint.position));
        }
        dispose() {
            this._disposables.dispose();
        }
        static _getRangeAtPosition(model, position) {
            const line = position.lineNumber;
            const word = model.getWordAtPosition(position);
            if (word) {
                // always prefer the word range
                return new range_1.Range(line, word.startColumn, line, word.endColumn);
            }
            model.tokenization.tokenizeIfCheap(line);
            const tokens = model.tokenization.getLineTokens(line);
            const offset = position.column - 1;
            const idx = tokens.findTokenIndexAtOffset(offset);
            let start = tokens.getStartOffset(idx);
            let end = tokens.getEndOffset(idx);
            if (end - start === 1) {
                // single character token, when at its end try leading/trailing token instead
                if (start === offset && idx > 1) {
                    // leading token
                    start = tokens.getStartOffset(idx - 1);
                    end = tokens.getEndOffset(idx - 1);
                }
                else if (end === offset && idx < tokens.getCount() - 1) {
                    // trailing token
                    start = tokens.getStartOffset(idx + 1);
                    end = tokens.getEndOffset(idx + 1);
                }
            }
            return new range_1.Range(line, start + 1, line, end + 1);
        }
    }
    exports.InlayHintsFragments = InlayHintsFragments;
    function asCommandLink(command) {
        return uri_1.URI.from({
            scheme: network_1.Schemas.command,
            path: command.id,
            query: command.arguments && encodeURIComponent(JSON.stringify(command.arguments))
        }).toString();
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[378/*vs/editor/contrib/inlineCompletions/browser/model/provideInlineCompletions*/], __M([1/*require*/,0/*exports*/,90/*vs/base/common/assert*/,14/*vs/base/common/async*/,18/*vs/base/common/cancellation*/,45/*vs/base/common/map*/,8/*vs/base/common/errors*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/,575/*vs/editor/common/model/bracketPairsTextModelPart/fixBrackets*/,104/*vs/editor/common/core/textEdit*/,205/*vs/editor/contrib/inlineCompletions/browser/utils*/,135/*vs/editor/contrib/snippet/browser/snippetParser*/]), function (require, exports, assert_1, async_1, cancellation_1, map_1, errors_1, position_1, range_1, fixBrackets_1, textEdit_1, utils_1, snippetParser_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.InlineCompletionItem = exports.InlineCompletionList = exports.InlineCompletionProviderResult = void 0;
    exports.provideInlineCompletions = provideInlineCompletions;
    async function provideInlineCompletions(registry, positionOrRange, model, context, token = cancellation_1.CancellationToken.None, languageConfigurationService) {
        // Important: Don't use position after the await calls, as the model could have been changed in the meantime!
        const defaultReplaceRange = positionOrRange instanceof position_1.Position ? getDefaultRange(positionOrRange, model) : positionOrRange;
        const providers = registry.all(model);
        const multiMap = new map_1.SetMap();
        for (const provider of providers) {
            if (provider.groupId) {
                multiMap.add(provider.groupId, provider);
            }
        }
        function getPreferredProviders(provider) {
            if (!provider.yieldsToGroupIds) {
                return [];
            }
            const result = [];
            for (const groupId of provider.yieldsToGroupIds || []) {
                const providers = multiMap.get(groupId);
                for (const p of providers) {
                    result.push(p);
                }
            }
            return result;
        }
        const states = new Map();
        const seen = new Set();
        function findPreferredProviderCircle(provider, stack) {
            stack = [...stack, provider];
            if (seen.has(provider)) {
                return stack;
            }
            seen.add(provider);
            try {
                const preferred = getPreferredProviders(provider);
                for (const p of preferred) {
                    const c = findPreferredProviderCircle(p, stack);
                    if (c) {
                        return c;
                    }
                }
            }
            finally {
                seen.delete(provider);
            }
            return undefined;
        }
        function processProvider(provider) {
            const state = states.get(provider);
            if (state) {
                return state;
            }
            const circle = findPreferredProviderCircle(provider, []);
            if (circle) {
                (0, errors_1.onUnexpectedExternalError)(new Error(`Inline completions: cyclic yield-to dependency detected. Path: ${circle.map(s => s.toString ? s.toString() : ('' + s)).join(' -> ')}`));
            }
            const deferredPromise = new async_1.DeferredPromise();
            states.set(provider, deferredPromise.p);
            (async () => {
                if (!circle) {
                    const preferred = getPreferredProviders(provider);
                    for (const p of preferred) {
                        const result = await processProvider(p);
                        if (result && result.items.length > 0) {
                            // Skip provider
                            return undefined;
                        }
                    }
                }
                try {
                    if (positionOrRange instanceof position_1.Position) {
                        const completions = await provider.provideInlineCompletions(model, positionOrRange, context, token);
                        return completions;
                    }
                    else {
                        const completions = await provider.provideInlineEdits?.(model, positionOrRange, context, token);
                        return completions;
                    }
                }
                catch (e) {
                    (0, errors_1.onUnexpectedExternalError)(e);
                    return undefined;
                }
            })().then(c => deferredPromise.complete(c), e => deferredPromise.error(e));
            return deferredPromise.p;
        }
        const providerResults = await Promise.all(providers.map(async (provider) => ({ provider, completions: await processProvider(provider) })));
        const itemsByHash = new Map();
        const lists = [];
        for (const result of providerResults) {
            const completions = result.completions;
            if (!completions) {
                continue;
            }
            const list = new InlineCompletionList(completions, result.provider);
            lists.push(list);
            for (const item of completions.items) {
                const inlineCompletionItem = InlineCompletionItem.from(item, list, defaultReplaceRange, model, languageConfigurationService);
                itemsByHash.set(inlineCompletionItem.hash(), inlineCompletionItem);
            }
        }
        return new InlineCompletionProviderResult(Array.from(itemsByHash.values()), new Set(itemsByHash.keys()), lists);
    }
    class InlineCompletionProviderResult {
        constructor(
        /**
         * Free of duplicates.
         */
        completions, hashs, providerResults) {
            this.completions = completions;
            this.hashs = hashs;
            this.providerResults = providerResults;
        }
        has(item) {
            return this.hashs.has(item.hash());
        }
        dispose() {
            for (const result of this.providerResults) {
                result.removeRef();
            }
        }
    }
    exports.InlineCompletionProviderResult = InlineCompletionProviderResult;
    /**
     * A ref counted pointer to the computed `InlineCompletions` and the `InlineCompletionsProvider` that
     * computed them.
     */
    class InlineCompletionList {
        constructor(inlineCompletions, provider) {
            this.inlineCompletions = inlineCompletions;
            this.provider = provider;
            this.refCount = 1;
        }
        addRef() {
            this.refCount++;
        }
        removeRef() {
            this.refCount--;
            if (this.refCount === 0) {
                this.provider.freeInlineCompletions(this.inlineCompletions);
            }
        }
    }
    exports.InlineCompletionList = InlineCompletionList;
    class InlineCompletionItem {
        static from(inlineCompletion, source, defaultReplaceRange, textModel, languageConfigurationService) {
            let insertText;
            let snippetInfo;
            let range = inlineCompletion.range ? range_1.Range.lift(inlineCompletion.range) : defaultReplaceRange;
            if (typeof inlineCompletion.insertText === 'string') {
                insertText = inlineCompletion.insertText;
                if (languageConfigurationService && inlineCompletion.completeBracketPairs) {
                    insertText = closeBrackets(insertText, range.getStartPosition(), textModel, languageConfigurationService);
                    // Modify range depending on if brackets are added or removed
                    const diff = insertText.length - inlineCompletion.insertText.length;
                    if (diff !== 0) {
                        range = new range_1.Range(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn + diff);
                    }
                }
                snippetInfo = undefined;
            }
            else if ('snippet' in inlineCompletion.insertText) {
                const preBracketCompletionLength = inlineCompletion.insertText.snippet.length;
                if (languageConfigurationService && inlineCompletion.completeBracketPairs) {
                    inlineCompletion.insertText.snippet = closeBrackets(inlineCompletion.insertText.snippet, range.getStartPosition(), textModel, languageConfigurationService);
                    // Modify range depending on if brackets are added or removed
                    const diff = inlineCompletion.insertText.snippet.length - preBracketCompletionLength;
                    if (diff !== 0) {
                        range = new range_1.Range(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn + diff);
                    }
                }
                const snippet = new snippetParser_1.SnippetParser().parse(inlineCompletion.insertText.snippet);
                if (snippet.children.length === 1 && snippet.children[0] instanceof snippetParser_1.Text) {
                    insertText = snippet.children[0].value;
                    snippetInfo = undefined;
                }
                else {
                    insertText = snippet.toString();
                    snippetInfo = {
                        snippet: inlineCompletion.insertText.snippet,
                        range: range
                    };
                }
            }
            else {
                (0, assert_1.assertNever)(inlineCompletion.insertText);
            }
            return new InlineCompletionItem(insertText, inlineCompletion.command, range, insertText, snippetInfo, inlineCompletion.additionalTextEdits || (0, utils_1.getReadonlyEmptyArray)(), inlineCompletion, source);
        }
        constructor(filterText, command, range, insertText, snippetInfo, additionalTextEdits, 
        /**
         * A reference to the original inline completion this inline completion has been constructed from.
         * Used for event data to ensure referential equality.
        */
        sourceInlineCompletion, 
        /**
         * A reference to the original inline completion list this inline completion has been constructed from.
         * Used for event data to ensure referential equality.
        */
        source) {
            this.filterText = filterText;
            this.command = command;
            this.range = range;
            this.insertText = insertText;
            this.snippetInfo = snippetInfo;
            this.additionalTextEdits = additionalTextEdits;
            this.sourceInlineCompletion = sourceInlineCompletion;
            this.source = source;
            filterText = filterText.replace(/\r\n|\r/g, '\n');
            insertText = filterText.replace(/\r\n|\r/g, '\n');
        }
        withRange(updatedRange) {
            return new InlineCompletionItem(this.filterText, this.command, updatedRange, this.insertText, this.snippetInfo, this.additionalTextEdits, this.sourceInlineCompletion, this.source);
        }
        hash() {
            return JSON.stringify({ insertText: this.insertText, range: this.range.toString() });
        }
        toSingleTextEdit() {
            return new textEdit_1.SingleTextEdit(this.range, this.insertText);
        }
    }
    exports.InlineCompletionItem = InlineCompletionItem;
    function getDefaultRange(position, model) {
        const word = model.getWordAtPosition(position);
        const maxColumn = model.getLineMaxColumn(position.lineNumber);
        // By default, always replace up until the end of the current line.
        // This default might be subject to change!
        return word
            ? new range_1.Range(position.lineNumber, word.startColumn, position.lineNumber, maxColumn)
            : range_1.Range.fromPositions(position, position.with(undefined, maxColumn));
    }
    function closeBrackets(text, position, model, languageConfigurationService) {
        const lineStart = model.getLineContent(position.lineNumber).substring(0, position.column - 1);
        const newLine = lineStart + text;
        const newTokens = model.tokenization.tokenizeLineWithEdit(position, newLine.length - (position.column - 1), text);
        const slicedTokens = newTokens?.sliceAndInflate(position.column - 1, newLine.length, 0);
        if (!slicedTokens) {
            return text;
        }
        const newText = (0, fixBrackets_1.fixBracketsInLine)(slicedTokens, languageConfigurationService);
        return newText;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[379/*vs/editor/contrib/placeholderText/browser/placeholderTextContribution*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,102/*vs/base/common/equals*/,2/*vs/base/common/lifecycle*/,21/*vs/base/common/observable*/,65/*vs/base/common/observableInternal/derived*/,112/*vs/editor/browser/observableCodeEditor*/]), function (require, exports, dom_1, equals_1, lifecycle_1, observable_1, derived_1, observableCodeEditor_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.PlaceholderTextContribution = void 0;
    /**
     * Use the editor option to set the placeholder text.
    */
    class PlaceholderTextContribution extends lifecycle_1.Disposable {
        static { this.ID = 'editor.contrib.placeholderText'; }
        constructor(_editor) {
            super();
            this._editor = _editor;
            this._editorObs = (0, observableCodeEditor_1.observableCodeEditor)(this._editor);
            this._placeholderText = this._editorObs.getOption(88 /* EditorOption.placeholder */);
            this._state = (0, observable_1.derivedOpts)({ owner: this, equalsFn: equals_1.structuralEquals }, reader => {
                const p = this._placeholderText.read(reader);
                if (!p) {
                    return undefined;
                }
                if (!this._editorObs.valueIsEmpty.read(reader)) {
                    return undefined;
                }
                return { placeholder: p };
            });
            this._shouldViewBeAlive = isOrWasTrue(this, reader => this._state.read(reader)?.placeholder !== undefined);
            this._view = (0, derived_1.derivedWithStore)((reader, store) => {
                if (!this._shouldViewBeAlive.read(reader)) {
                    return;
                }
                const element = (0, dom_1.h)('div.editorPlaceholder');
                store.add((0, observable_1.autorun)(reader => {
                    const data = this._state.read(reader);
                    const shouldBeVisibile = data?.placeholder !== undefined;
                    element.root.style.display = shouldBeVisibile ? 'block' : 'none';
                    element.root.innerText = data?.placeholder ?? '';
                }));
                store.add((0, observable_1.autorun)(reader => {
                    const info = this._editorObs.layoutInfo.read(reader);
                    element.root.style.left = `${info.contentLeft}px`;
                    element.root.style.width = (info.contentWidth - info.verticalScrollbarWidth) + 'px';
                    element.root.style.top = `${this._editor.getTopForLineNumber(0)}px`;
                }));
                store.add((0, observable_1.autorun)(reader => {
                    element.root.style.fontFamily = this._editorObs.getOption(49 /* EditorOption.fontFamily */).read(reader);
                    element.root.style.fontSize = this._editorObs.getOption(52 /* EditorOption.fontSize */).read(reader) + 'px';
                    element.root.style.lineHeight = this._editorObs.getOption(67 /* EditorOption.lineHeight */).read(reader) + 'px';
                }));
                store.add(this._editorObs.createOverlayWidget({
                    allowEditorOverflow: false,
                    minContentWidthInPx: (0, observable_1.constObservable)(0),
                    position: (0, observable_1.constObservable)(null),
                    domNode: element.root,
                }));
            });
            this._view.recomputeInitiallyAndOnChange(this._store);
        }
    }
    exports.PlaceholderTextContribution = PlaceholderTextContribution;
    function isOrWasTrue(owner, fn) {
        return (0, observable_1.derivedObservableWithCache)(owner, (reader, lastValue) => {
            if (lastValue === true) {
                return true;
            }
            return fn(reader);
        });
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[380/*vs/platform/accessibility/browser/accessibleViewRegistry*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AccessibleViewRegistry = void 0;
    exports.AccessibleViewRegistry = new class AccessibleViewRegistry {
        constructor() {
            this._implementations = [];
        }
        register(implementation) {
            this._implementations.push(implementation);
            return {
                dispose: () => {
                    const idx = this._implementations.indexOf(implementation);
                    if (idx !== -1) {
                        this._implementations.splice(idx, 1);
                    }
                }
            };
        }
        getImplementations() {
            return this._implementations;
        }
    };
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[381/*vs/platform/action/common/action*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.isLocalizedString = isLocalizedString;
    exports.isICommandActionToggleInfo = isICommandActionToggleInfo;
    function isLocalizedString(thing) {
        return thing
            && typeof thing === 'object'
            && typeof thing.original === 'string'
            && typeof thing.value === 'string';
    }
    function isICommandActionToggleInfo(thing) {
        return thing ? thing.condition !== undefined : false;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[671/*vs/platform/action/common/actionCommonCategories*/], __M([1/*require*/,0/*exports*/,3/*vs/nls*/]), function (require, exports, nls_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Categories = void 0;
    exports.Categories = Object.freeze({
        View: (0, nls_1.localize2)(1477, 'View'),
        Help: (0, nls_1.localize2)(1478, 'Help'),
        Test: (0, nls_1.localize2)(1479, 'Test'),
        File: (0, nls_1.localize2)(1480, 'File'),
        Preferences: (0, nls_1.localize2)(1481, 'Preferences'),
        Developer: (0, nls_1.localize2)(1482, "Developer"),
    });
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[672/*vs/platform/contextkey/common/scanner*/], __M([1/*require*/,0/*exports*/,8/*vs/base/common/errors*/,3/*vs/nls*/]), function (require, exports, errors_1, nls_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Scanner = void 0;
    function hintDidYouMean(...meant) {
        switch (meant.length) {
            case 1:
                return (0, nls_1.localize)(1532, "Did you mean {0}?", meant[0]);
            case 2:
                return (0, nls_1.localize)(1533, "Did you mean {0} or {1}?", meant[0], meant[1]);
            case 3:
                return (0, nls_1.localize)(1534, "Did you mean {0}, {1} or {2}?", meant[0], meant[1], meant[2]);
            default: // we just don't expect that many
                return undefined;
        }
    }
    const hintDidYouForgetToOpenOrCloseQuote = (0, nls_1.localize)(1535, "Did you forget to open or close the quote?");
    const hintDidYouForgetToEscapeSlash = (0, nls_1.localize)(1536, "Did you forget to escape the '/' (slash) character? Put two backslashes before it to escape, e.g., '\\\\/\'.");
    /**
     * A simple scanner for context keys.
     *
     * Example:
     *
     * ```ts
     * const scanner = new Scanner().reset('resourceFileName =~ /docker/ && !config.docker.enabled');
     * const tokens = [...scanner];
     * if (scanner.errorTokens.length > 0) {
     *     scanner.errorTokens.forEach(err => console.error(`Unexpected token at ${err.offset}: ${err.lexeme}\nHint: ${err.additional}`));
     * } else {
     *     // process tokens
     * }
     * ```
     */
    class Scanner {
        constructor() {
            this._input = '';
            this._start = 0;
            this._current = 0;
            this._tokens = [];
            this._errors = [];
            // u - unicode, y - sticky // TODO@ulugbekna: we accept double quotes as part of the string rather than as a delimiter (to preserve old parser's behavior)
            this.stringRe = /[a-zA-Z0-9_<>\-\./\\:\*\?\+\[\]\^,#@;"%\$\p{L}-]+/uy;
        }
        static getLexeme(token) {
            switch (token.type) {
                case 0 /* TokenType.LParen */:
                    return '(';
                case 1 /* TokenType.RParen */:
                    return ')';
                case 2 /* TokenType.Neg */:
                    return '!';
                case 3 /* TokenType.Eq */:
                    return token.isTripleEq ? '===' : '==';
                case 4 /* TokenType.NotEq */:
                    return token.isTripleEq ? '!==' : '!=';
                case 5 /* TokenType.Lt */:
                    return '<';
                case 6 /* TokenType.LtEq */:
                    return '<=';
                case 7 /* TokenType.Gt */:
                    return '>=';
                case 8 /* TokenType.GtEq */:
                    return '>=';
                case 9 /* TokenType.RegexOp */:
                    return '=~';
                case 10 /* TokenType.RegexStr */:
                    return token.lexeme;
                case 11 /* TokenType.True */:
                    return 'true';
                case 12 /* TokenType.False */:
                    return 'false';
                case 13 /* TokenType.In */:
                    return 'in';
                case 14 /* TokenType.Not */:
                    return 'not';
                case 15 /* TokenType.And */:
                    return '&&';
                case 16 /* TokenType.Or */:
                    return '||';
                case 17 /* TokenType.Str */:
                    return token.lexeme;
                case 18 /* TokenType.QuotedStr */:
                    return token.lexeme;
                case 19 /* TokenType.Error */:
                    return token.lexeme;
                case 20 /* TokenType.EOF */:
                    return 'EOF';
                default:
                    throw (0, errors_1.illegalState)(`unhandled token type: ${JSON.stringify(token)}; have you forgotten to add a case?`);
            }
        }
        static { this._regexFlags = new Set(['i', 'g', 's', 'm', 'y', 'u'].map(ch => ch.charCodeAt(0))); }
        static { this._keywords = new Map([
            ['not', 14 /* TokenType.Not */],
            ['in', 13 /* TokenType.In */],
            ['false', 12 /* TokenType.False */],
            ['true', 11 /* TokenType.True */],
        ]); }
        reset(value) {
            this._input = value;
            this._start = 0;
            this._current = 0;
            this._tokens = [];
            this._errors = [];
            return this;
        }
        scan() {
            while (!this._isAtEnd()) {
                this._start = this._current;
                const ch = this._advance();
                switch (ch) {
                    case 40 /* CharCode.OpenParen */:
                        this._addToken(0 /* TokenType.LParen */);
                        break;
                    case 41 /* CharCode.CloseParen */:
                        this._addToken(1 /* TokenType.RParen */);
                        break;
                    case 33 /* CharCode.ExclamationMark */:
                        if (this._match(61 /* CharCode.Equals */)) {
                            const isTripleEq = this._match(61 /* CharCode.Equals */); // eat last `=` if `!==`
                            this._tokens.push({ type: 4 /* TokenType.NotEq */, offset: this._start, isTripleEq });
                        }
                        else {
                            this._addToken(2 /* TokenType.Neg */);
                        }
                        break;
                    case 39 /* CharCode.SingleQuote */:
                        this._quotedString();
                        break;
                    case 47 /* CharCode.Slash */:
                        this._regex();
                        break;
                    case 61 /* CharCode.Equals */:
                        if (this._match(61 /* CharCode.Equals */)) { // support `==`
                            const isTripleEq = this._match(61 /* CharCode.Equals */); // eat last `=` if `===`
                            this._tokens.push({ type: 3 /* TokenType.Eq */, offset: this._start, isTripleEq });
                        }
                        else if (this._match(126 /* CharCode.Tilde */)) {
                            this._addToken(9 /* TokenType.RegexOp */);
                        }
                        else {
                            this._error(hintDidYouMean('==', '=~'));
                        }
                        break;
                    case 60 /* CharCode.LessThan */:
                        this._addToken(this._match(61 /* CharCode.Equals */) ? 6 /* TokenType.LtEq */ : 5 /* TokenType.Lt */);
                        break;
                    case 62 /* CharCode.GreaterThan */:
                        this._addToken(this._match(61 /* CharCode.Equals */) ? 8 /* TokenType.GtEq */ : 7 /* TokenType.Gt */);
                        break;
                    case 38 /* CharCode.Ampersand */:
                        if (this._match(38 /* CharCode.Ampersand */)) {
                            this._addToken(15 /* TokenType.And */);
                        }
                        else {
                            this._error(hintDidYouMean('&&'));
                        }
                        break;
                    case 124 /* CharCode.Pipe */:
                        if (this._match(124 /* CharCode.Pipe */)) {
                            this._addToken(16 /* TokenType.Or */);
                        }
                        else {
                            this._error(hintDidYouMean('||'));
                        }
                        break;
                    // TODO@ulugbekna: 1) rewrite using a regex 2) reconsider what characters are considered whitespace, including unicode, nbsp, etc.
                    case 32 /* CharCode.Space */:
                    case 13 /* CharCode.CarriageReturn */:
                    case 9 /* CharCode.Tab */:
                    case 10 /* CharCode.LineFeed */:
                    case 160 /* CharCode.NoBreakSpace */: // &nbsp
                        break;
                    default:
                        this._string();
                }
            }
            this._start = this._current;
            this._addToken(20 /* TokenType.EOF */);
            return Array.from(this._tokens);
        }
        _match(expected) {
            if (this._isAtEnd()) {
                return false;
            }
            if (this._input.charCodeAt(this._current) !== expected) {
                return false;
            }
            this._current++;
            return true;
        }
        _advance() {
            return this._input.charCodeAt(this._current++);
        }
        _peek() {
            return this._isAtEnd() ? 0 /* CharCode.Null */ : this._input.charCodeAt(this._current);
        }
        _addToken(type) {
            this._tokens.push({ type, offset: this._start });
        }
        _error(additional) {
            const offset = this._start;
            const lexeme = this._input.substring(this._start, this._current);
            const errToken = { type: 19 /* TokenType.Error */, offset: this._start, lexeme };
            this._errors.push({ offset, lexeme, additionalInfo: additional });
            this._tokens.push(errToken);
        }
        _string() {
            this.stringRe.lastIndex = this._start;
            const match = this.stringRe.exec(this._input);
            if (match) {
                this._current = this._start + match[0].length;
                const lexeme = this._input.substring(this._start, this._current);
                const keyword = Scanner._keywords.get(lexeme);
                if (keyword) {
                    this._addToken(keyword);
                }
                else {
                    this._tokens.push({ type: 17 /* TokenType.Str */, lexeme, offset: this._start });
                }
            }
        }
        // captures the lexeme without the leading and trailing '
        _quotedString() {
            while (this._peek() !== 39 /* CharCode.SingleQuote */ && !this._isAtEnd()) { // TODO@ulugbekna: add support for escaping ' ?
                this._advance();
            }
            if (this._isAtEnd()) {
                this._error(hintDidYouForgetToOpenOrCloseQuote);
                return;
            }
            // consume the closing '
            this._advance();
            this._tokens.push({ type: 18 /* TokenType.QuotedStr */, lexeme: this._input.substring(this._start + 1, this._current - 1), offset: this._start + 1 });
        }
        /*
         * Lexing a regex expression: /.../[igsmyu]*
         * Based on https://github.com/microsoft/TypeScript/blob/9247ef115e617805983740ba795d7a8164babf89/src/compiler/scanner.ts#L2129-L2181
         *
         * Note that we want slashes within a regex to be escaped, e.g., /file:\\/\\/\\// should match `file:///`
         */
        _regex() {
            let p = this._current;
            let inEscape = false;
            let inCharacterClass = false;
            while (true) {
                if (p >= this._input.length) {
                    this._current = p;
                    this._error(hintDidYouForgetToEscapeSlash);
                    return;
                }
                const ch = this._input.charCodeAt(p);
                if (inEscape) { // parsing an escape character
                    inEscape = false;
                }
                else if (ch === 47 /* CharCode.Slash */ && !inCharacterClass) { // end of regex
                    p++;
                    break;
                }
                else if (ch === 91 /* CharCode.OpenSquareBracket */) {
                    inCharacterClass = true;
                }
                else if (ch === 92 /* CharCode.Backslash */) {
                    inEscape = true;
                }
                else if (ch === 93 /* CharCode.CloseSquareBracket */) {
                    inCharacterClass = false;
                }
                p++;
            }
            // Consume flags // TODO@ulugbekna: use regex instead
            while (p < this._input.length && Scanner._regexFlags.has(this._input.charCodeAt(p))) {
                p++;
            }
            this._current = p;
            const lexeme = this._input.substring(this._start, this._current);
            this._tokens.push({ type: 10 /* TokenType.RegexStr */, lexeme, offset: this._start });
        }
        _isAtEnd() {
            return this._current >= this._input.length;
        }
    }
    exports.Scanner = Scanner;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[673/*vs/platform/editor/common/editor*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.EditorOpenSource = void 0;
    var EditorOpenSource;
    (function (EditorOpenSource) {
        /**
         * Default: the editor is opening via a programmatic call
         * to the editor service API.
         */
        EditorOpenSource[EditorOpenSource["API"] = 0] = "API";
        /**
         * Indicates that a user action triggered the opening, e.g.
         * via mouse or keyboard use.
         */
        EditorOpenSource[EditorOpenSource["USER"] = 1] = "USER";
    })(EditorOpenSource || (exports.EditorOpenSource = EditorOpenSource = {}));
});

define(__m[674/*vs/platform/extensions/common/extensions*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ExtensionIdentifierSet = exports.ExtensionIdentifier = void 0;
    /**
     * **!Do not construct directly!**
     *
     * **!Only static methods because it gets serialized!**
     *
     * This represents the "canonical" version for an extension identifier. Extension ids
     * have to be case-insensitive (due to the marketplace), but we must ensure case
     * preservation because the extension API is already public at this time.
     *
     * For example, given an extension with the publisher `"Hello"` and the name `"World"`,
     * its canonical extension identifier is `"Hello.World"`. This extension could be
     * referenced in some other extension's dependencies using the string `"hello.world"`.
     *
     * To make matters more complicated, an extension can optionally have an UUID. When two
     * extensions have the same UUID, they are considered equal even if their identifier is different.
     */
    class ExtensionIdentifier {
        constructor(value) {
            this.value = value;
            this._lower = value.toLowerCase();
        }
        /**
         * Gives the value by which to index (for equality).
         */
        static toKey(id) {
            if (typeof id === 'string') {
                return id.toLowerCase();
            }
            return id._lower;
        }
    }
    exports.ExtensionIdentifier = ExtensionIdentifier;
    class ExtensionIdentifierSet {
        constructor(iterable) {
            this._set = new Set();
            if (iterable) {
                for (const value of iterable) {
                    this.add(value);
                }
            }
        }
        add(id) {
            this._set.add(ExtensionIdentifier.toKey(id));
        }
        has(id) {
            return this._set.has(ExtensionIdentifier.toKey(id));
        }
    }
    exports.ExtensionIdentifierSet = ExtensionIdentifierSet;
});

//#endregion
define(__m[382/*vs/platform/files/common/files*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.FileKind = void 0;
    //#region Utilities
    var FileKind;
    (function (FileKind) {
        FileKind[FileKind["FILE"] = 0] = "FILE";
        FileKind[FileKind["FOLDER"] = 1] = "FOLDER";
        FileKind[FileKind["ROOT_FOLDER"] = 2] = "ROOT_FOLDER";
    })(FileKind || (exports.FileKind = FileKind = {}));
});
//#endregion

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[675/*vs/platform/history/browser/historyWidgetKeybindingHint*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.showHistoryKeybindingHint = showHistoryKeybindingHint;
    function showHistoryKeybindingHint(keybindingService) {
        return keybindingService.lookupKeybinding('history.showPrevious')?.getElectronAccelerator() === 'Up' && keybindingService.lookupKeybinding('history.showNext')?.getElectronAccelerator() === 'Down';
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[265/*vs/platform/instantiation/common/descriptors*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SyncDescriptor = void 0;
    class SyncDescriptor {
        constructor(ctor, staticArguments = [], supportsDelayedInstantiation = false) {
            this.ctor = ctor;
            this.staticArguments = staticArguments;
            this.supportsDelayedInstantiation = supportsDelayedInstantiation;
        }
    }
    exports.SyncDescriptor = SyncDescriptor;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[49/*vs/platform/instantiation/common/extensions*/], __M([1/*require*/,0/*exports*/,265/*vs/platform/instantiation/common/descriptors*/]), function (require, exports, descriptors_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.registerSingleton = registerSingleton;
    exports.getSingletonServiceDescriptors = getSingletonServiceDescriptors;
    const _registry = [];
    function registerSingleton(id, ctorOrDescriptor, supportsDelayedInstantiation) {
        if (!(ctorOrDescriptor instanceof descriptors_1.SyncDescriptor)) {
            ctorOrDescriptor = new descriptors_1.SyncDescriptor(ctorOrDescriptor, [], Boolean(supportsDelayedInstantiation));
        }
        _registry.push([id, ctorOrDescriptor]);
    }
    function getSingletonServiceDescriptors() {
        return _registry;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[676/*vs/platform/instantiation/common/graph*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Graph = exports.Node = void 0;
    class Node {
        constructor(key, data) {
            this.key = key;
            this.data = data;
            this.incoming = new Map();
            this.outgoing = new Map();
        }
    }
    exports.Node = Node;
    class Graph {
        constructor(_hashFn) {
            this._hashFn = _hashFn;
            this._nodes = new Map();
            // empty
        }
        roots() {
            const ret = [];
            for (const node of this._nodes.values()) {
                if (node.outgoing.size === 0) {
                    ret.push(node);
                }
            }
            return ret;
        }
        insertEdge(from, to) {
            const fromNode = this.lookupOrInsertNode(from);
            const toNode = this.lookupOrInsertNode(to);
            fromNode.outgoing.set(toNode.key, toNode);
            toNode.incoming.set(fromNode.key, fromNode);
        }
        removeNode(data) {
            const key = this._hashFn(data);
            this._nodes.delete(key);
            for (const node of this._nodes.values()) {
                node.outgoing.delete(key);
                node.incoming.delete(key);
            }
        }
        lookupOrInsertNode(data) {
            const key = this._hashFn(data);
            let node = this._nodes.get(key);
            if (!node) {
                node = new Node(key, data);
                this._nodes.set(key, node);
            }
            return node;
        }
        isEmpty() {
            return this._nodes.size === 0;
        }
        toString() {
            const data = [];
            for (const [key, value] of this._nodes) {
                data.push(`${key}\n\t(-> incoming)[${[...value.incoming.keys()].join(', ')}]\n\t(outgoing ->)[${[...value.outgoing.keys()].join(',')}]\n`);
            }
            return data.join('\n');
        }
        /**
         * This is brute force and slow and **only** be used
         * to trouble shoot.
         */
        findCycleSlow() {
            for (const [id, node] of this._nodes) {
                const seen = new Set([id]);
                const res = this._findCycle(node, seen);
                if (res) {
                    return res;
                }
            }
            return undefined;
        }
        _findCycle(node, seen) {
            for (const [id, outgoing] of node.outgoing) {
                if (seen.has(id)) {
                    return [...seen, id].join(' -> ');
                }
                seen.add(id);
                const value = this._findCycle(outgoing, seen);
                if (value) {
                    return value;
                }
                seen.delete(id);
            }
            return undefined;
        }
    }
    exports.Graph = Graph;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[7/*vs/platform/instantiation/common/instantiation*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.IInstantiationService = exports._util = void 0;
    exports.createDecorator = createDecorator;
    // ------ internal util
    var _util;
    (function (_util) {
        _util.serviceIds = new Map();
        _util.DI_TARGET = '$di$target';
        _util.DI_DEPENDENCIES = '$di$dependencies';
        function getServiceDependencies(ctor) {
            return ctor[_util.DI_DEPENDENCIES] || [];
        }
        _util.getServiceDependencies = getServiceDependencies;
    })(_util || (exports._util = _util = {}));
    exports.IInstantiationService = createDecorator('instantiationService');
    function storeServiceDependency(id, target, index) {
        if (target[_util.DI_TARGET] === target) {
            target[_util.DI_DEPENDENCIES].push({ id, index });
        }
        else {
            target[_util.DI_DEPENDENCIES] = [{ id, index }];
            target[_util.DI_TARGET] = target;
        }
    }
    /**
     * The *only* valid way to create a {{ServiceIdentifier}}.
     */
    function createDecorator(serviceId) {
        if (_util.serviceIds.has(serviceId)) {
            return _util.serviceIds.get(serviceId);
        }
        const id = function (target, key, index) {
            if (arguments.length !== 3) {
                throw new Error('@IServiceName-decorator can only be used to decorate a parameter');
            }
            storeServiceDependency(id, target, index);
        };
        id.toString = () => serviceId;
        _util.serviceIds.set(serviceId, id);
        return id;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[152/*vs/editor/browser/services/bulkEditService*/], __M([1/*require*/,0/*exports*/,7/*vs/platform/instantiation/common/instantiation*/,22/*vs/base/common/uri*/,19/*vs/base/common/types*/]), function (require, exports, instantiation_1, uri_1, types_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ResourceFileEdit = exports.ResourceTextEdit = exports.ResourceEdit = exports.IBulkEditService = void 0;
    exports.IBulkEditService = (0, instantiation_1.createDecorator)('IWorkspaceEditService');
    class ResourceEdit {
        constructor(metadata) {
            this.metadata = metadata;
        }
        static convert(edit) {
            return edit.edits.map(edit => {
                if (ResourceTextEdit.is(edit)) {
                    return ResourceTextEdit.lift(edit);
                }
                if (ResourceFileEdit.is(edit)) {
                    return ResourceFileEdit.lift(edit);
                }
                throw new Error('Unsupported edit');
            });
        }
    }
    exports.ResourceEdit = ResourceEdit;
    class ResourceTextEdit extends ResourceEdit {
        static is(candidate) {
            if (candidate instanceof ResourceTextEdit) {
                return true;
            }
            return (0, types_1.isObject)(candidate)
                && uri_1.URI.isUri(candidate.resource)
                && (0, types_1.isObject)(candidate.textEdit);
        }
        static lift(edit) {
            if (edit instanceof ResourceTextEdit) {
                return edit;
            }
            else {
                return new ResourceTextEdit(edit.resource, edit.textEdit, edit.versionId, edit.metadata);
            }
        }
        constructor(resource, textEdit, versionId = undefined, metadata) {
            super(metadata);
            this.resource = resource;
            this.textEdit = textEdit;
            this.versionId = versionId;
        }
    }
    exports.ResourceTextEdit = ResourceTextEdit;
    class ResourceFileEdit extends ResourceEdit {
        static is(candidate) {
            if (candidate instanceof ResourceFileEdit) {
                return true;
            }
            else {
                return (0, types_1.isObject)(candidate)
                    && (Boolean(candidate.newResource) || Boolean(candidate.oldResource));
            }
        }
        static lift(edit) {
            if (edit instanceof ResourceFileEdit) {
                return edit;
            }
            else {
                return new ResourceFileEdit(edit.oldResource, edit.newResource, edit.options, edit.metadata);
            }
        }
        constructor(oldResource, newResource, options = {}, metadata) {
            super(metadata);
            this.oldResource = oldResource;
            this.newResource = newResource;
            this.options = options;
        }
    }
    exports.ResourceFileEdit = ResourceFileEdit;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[34/*vs/editor/browser/services/codeEditorService*/], __M([1/*require*/,0/*exports*/,7/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ICodeEditorService = void 0;
    exports.ICodeEditorService = (0, instantiation_1.createDecorator)('codeEditorService');
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/






var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
define(__m[383/*vs/editor/browser/widget/diffEditor/features/hideUnchangedRegionsFeature*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,114/*vs/base/browser/ui/iconLabel/iconLabels*/,26/*vs/base/common/codicons*/,57/*vs/base/common/htmlContent*/,2/*vs/base/common/lifecycle*/,21/*vs/base/common/observable*/,65/*vs/base/common/observableInternal/derived*/,30/*vs/base/common/themables*/,19/*vs/base/common/types*/,112/*vs/editor/browser/observableCodeEditor*/,88/*vs/editor/browser/widget/diffEditor/utils*/,55/*vs/editor/common/core/lineRange*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/,27/*vs/editor/common/languages*/,3/*vs/nls*/,7/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, dom_1, iconLabels_1, codicons_1, htmlContent_1, lifecycle_1, observable_1, derived_1, themables_1, types_1, observableCodeEditor_1, utils_1, lineRange_1, position_1, range_1, languages_1, nls_1, instantiation_1) {
    "use strict";
    var HideUnchangedRegionsFeature_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.HideUnchangedRegionsFeature = void 0;
    /**
     * Make sure to add the view zones to the editor!
     */
    let HideUnchangedRegionsFeature = class HideUnchangedRegionsFeature extends lifecycle_1.Disposable {
        static { HideUnchangedRegionsFeature_1 = this; }
        static { this._breadcrumbsSourceFactory = (0, observable_1.observableValue)(HideUnchangedRegionsFeature_1, () => ({
            dispose() {
            },
            getBreadcrumbItems(startRange, reader) {
                return [];
            },
        })); }
        static setBreadcrumbsSourceFactory(factory) {
            this._breadcrumbsSourceFactory.set(factory, undefined);
        }
        get isUpdatingHiddenAreas() { return this._isUpdatingHiddenAreas; }
        constructor(_editors, _diffModel, _options, _instantiationService) {
            super();
            this._editors = _editors;
            this._diffModel = _diffModel;
            this._options = _options;
            this._instantiationService = _instantiationService;
            this._modifiedOutlineSource = (0, derived_1.derivedDisposable)(this, (reader) => {
                const m = this._editors.modifiedModel.read(reader);
                const factory = HideUnchangedRegionsFeature_1._breadcrumbsSourceFactory.read(reader);
                return (!m || !factory) ? undefined : factory(m, this._instantiationService);
            });
            this._isUpdatingHiddenAreas = false;
            this._register(this._editors.original.onDidChangeCursorPosition(e => {
                if (e.reason === 1 /* CursorChangeReason.ContentFlush */) {
                    return;
                }
                const m = this._diffModel.get();
                (0, observable_1.transaction)(tx => {
                    for (const s of this._editors.original.getSelections() || []) {
                        m?.ensureOriginalLineIsVisible(s.getStartPosition().lineNumber, 0 /* RevealPreference.FromCloserSide */, tx);
                        m?.ensureOriginalLineIsVisible(s.getEndPosition().lineNumber, 0 /* RevealPreference.FromCloserSide */, tx);
                    }
                });
            }));
            this._register(this._editors.modified.onDidChangeCursorPosition(e => {
                if (e.reason === 1 /* CursorChangeReason.ContentFlush */) {
                    return;
                }
                const m = this._diffModel.get();
                (0, observable_1.transaction)(tx => {
                    for (const s of this._editors.modified.getSelections() || []) {
                        m?.ensureModifiedLineIsVisible(s.getStartPosition().lineNumber, 0 /* RevealPreference.FromCloserSide */, tx);
                        m?.ensureModifiedLineIsVisible(s.getEndPosition().lineNumber, 0 /* RevealPreference.FromCloserSide */, tx);
                    }
                });
            }));
            const unchangedRegions = this._diffModel.map((m, reader) => {
                const regions = m?.unchangedRegions.read(reader) ?? [];
                if (regions.length === 1 && regions[0].modifiedLineNumber === 1 && regions[0].lineCount === this._editors.modifiedModel.read(reader)?.getLineCount()) {
                    return [];
                }
                return regions;
            });
            this.viewZones = (0, observable_1.derivedWithStore)(this, (reader, store) => {
                /** @description view Zones */
                const modifiedOutlineSource = this._modifiedOutlineSource.read(reader);
                if (!modifiedOutlineSource) {
                    return { origViewZones: [], modViewZones: [] };
                }
                const origViewZones = [];
                const modViewZones = [];
                const sideBySide = this._options.renderSideBySide.read(reader);
                const compactMode = this._options.compactMode.read(reader);
                const curUnchangedRegions = unchangedRegions.read(reader);
                for (let i = 0; i < curUnchangedRegions.length; i++) {
                    const r = curUnchangedRegions[i];
                    if (r.shouldHideControls(reader)) {
                        continue;
                    }
                    if (compactMode && (i === 0 || i === curUnchangedRegions.length - 1)) {
                        continue;
                    }
                    if (compactMode) {
                        {
                            const d = (0, observable_1.derived)(this, reader => /** @description hiddenOriginalRangeStart */ r.getHiddenOriginalRange(reader).startLineNumber - 1);
                            const origVz = new utils_1.PlaceholderViewZone(d, 12);
                            origViewZones.push(origVz);
                            store.add(new CompactCollapsedCodeOverlayWidget(this._editors.original, origVz, r, !sideBySide));
                        }
                        {
                            const d = (0, observable_1.derived)(this, reader => /** @description hiddenModifiedRangeStart */ r.getHiddenModifiedRange(reader).startLineNumber - 1);
                            const modViewZone = new utils_1.PlaceholderViewZone(d, 12);
                            modViewZones.push(modViewZone);
                            store.add(new CompactCollapsedCodeOverlayWidget(this._editors.modified, modViewZone, r));
                        }
                    }
                    else {
                        {
                            const d = (0, observable_1.derived)(this, reader => /** @description hiddenOriginalRangeStart */ r.getHiddenOriginalRange(reader).startLineNumber - 1);
                            const origVz = new utils_1.PlaceholderViewZone(d, 24);
                            origViewZones.push(origVz);
                            store.add(new CollapsedCodeOverlayWidget(this._editors.original, origVz, r, r.originalUnchangedRange, !sideBySide, modifiedOutlineSource, l => this._diffModel.get().ensureModifiedLineIsVisible(l, 2 /* RevealPreference.FromBottom */, undefined), this._options));
                        }
                        {
                            const d = (0, observable_1.derived)(this, reader => /** @description hiddenModifiedRangeStart */ r.getHiddenModifiedRange(reader).startLineNumber - 1);
                            const modViewZone = new utils_1.PlaceholderViewZone(d, 24);
                            modViewZones.push(modViewZone);
                            store.add(new CollapsedCodeOverlayWidget(this._editors.modified, modViewZone, r, r.modifiedUnchangedRange, false, modifiedOutlineSource, l => this._diffModel.get().ensureModifiedLineIsVisible(l, 2 /* RevealPreference.FromBottom */, undefined), this._options));
                        }
                    }
                }
                return { origViewZones, modViewZones, };
            });
            const unchangedLinesDecoration = {
                description: 'unchanged lines',
                className: 'diff-unchanged-lines',
                isWholeLine: true,
            };
            const unchangedLinesDecorationShow = {
                description: 'Fold Unchanged',
                glyphMarginHoverMessage: new htmlContent_1.MarkdownString(undefined, { isTrusted: true, supportThemeIcons: true })
                    .appendMarkdown((0, nls_1.localize)(111, 'Fold Unchanged Region')),
                glyphMarginClassName: 'fold-unchanged ' + themables_1.ThemeIcon.asClassName(codicons_1.Codicon.fold),
                zIndex: 10001,
            };
            this._register((0, utils_1.applyObservableDecorations)(this._editors.original, (0, observable_1.derived)(this, reader => {
                /** @description decorations */
                const curUnchangedRegions = unchangedRegions.read(reader);
                const result = curUnchangedRegions.map(r => ({
                    range: r.originalUnchangedRange.toInclusiveRange(),
                    options: unchangedLinesDecoration,
                }));
                for (const r of curUnchangedRegions) {
                    if (r.shouldHideControls(reader)) {
                        result.push({
                            range: range_1.Range.fromPositions(new position_1.Position(r.originalLineNumber, 1)),
                            options: unchangedLinesDecorationShow,
                        });
                    }
                }
                return result;
            })));
            this._register((0, utils_1.applyObservableDecorations)(this._editors.modified, (0, observable_1.derived)(this, reader => {
                /** @description decorations */
                const curUnchangedRegions = unchangedRegions.read(reader);
                const result = curUnchangedRegions.map(r => ({
                    range: r.modifiedUnchangedRange.toInclusiveRange(),
                    options: unchangedLinesDecoration,
                }));
                for (const r of curUnchangedRegions) {
                    if (r.shouldHideControls(reader)) {
                        result.push({
                            range: lineRange_1.LineRange.ofLength(r.modifiedLineNumber, 1).toInclusiveRange(),
                            options: unchangedLinesDecorationShow,
                        });
                    }
                }
                return result;
            })));
            this._register((0, observable_1.autorun)((reader) => {
                /** @description update folded unchanged regions */
                const curUnchangedRegions = unchangedRegions.read(reader);
                this._isUpdatingHiddenAreas = true;
                try {
                    this._editors.original.setHiddenAreas(curUnchangedRegions.map(r => r.getHiddenOriginalRange(reader).toInclusiveRange()).filter(types_1.isDefined));
                    this._editors.modified.setHiddenAreas(curUnchangedRegions.map(r => r.getHiddenModifiedRange(reader).toInclusiveRange()).filter(types_1.isDefined));
                }
                finally {
                    this._isUpdatingHiddenAreas = false;
                }
            }));
            this._register(this._editors.modified.onMouseUp(event => {
                if (!event.event.rightButton && event.target.position && event.target.element?.className.includes('fold-unchanged')) {
                    const lineNumber = event.target.position.lineNumber;
                    const model = this._diffModel.get();
                    if (!model) {
                        return;
                    }
                    const region = model.unchangedRegions.get().find(r => r.modifiedUnchangedRange.includes(lineNumber));
                    if (!region) {
                        return;
                    }
                    region.collapseAll(undefined);
                    event.event.stopPropagation();
                    event.event.preventDefault();
                }
            }));
            this._register(this._editors.original.onMouseUp(event => {
                if (!event.event.rightButton && event.target.position && event.target.element?.className.includes('fold-unchanged')) {
                    const lineNumber = event.target.position.lineNumber;
                    const model = this._diffModel.get();
                    if (!model) {
                        return;
                    }
                    const region = model.unchangedRegions.get().find(r => r.originalUnchangedRange.includes(lineNumber));
                    if (!region) {
                        return;
                    }
                    region.collapseAll(undefined);
                    event.event.stopPropagation();
                    event.event.preventDefault();
                }
            }));
        }
    };
    exports.HideUnchangedRegionsFeature = HideUnchangedRegionsFeature;
    exports.HideUnchangedRegionsFeature = HideUnchangedRegionsFeature = HideUnchangedRegionsFeature_1 = __decorate([
        __param(3, instantiation_1.IInstantiationService)
    ], HideUnchangedRegionsFeature);
    class CompactCollapsedCodeOverlayWidget extends utils_1.ViewZoneOverlayWidget {
        constructor(editor, _viewZone, _unchangedRegion, _hide = false) {
            const root = (0, dom_1.h)('div.diff-hidden-lines-widget');
            super(editor, _viewZone, root.root);
            this._unchangedRegion = _unchangedRegion;
            this._hide = _hide;
            this._nodes = (0, dom_1.h)('div.diff-hidden-lines-compact', [
                (0, dom_1.h)('div.line-left', []),
                (0, dom_1.h)('div.text@text', []),
                (0, dom_1.h)('div.line-right', [])
            ]);
            root.root.appendChild(this._nodes.root);
            if (this._hide) {
                this._nodes.root.replaceChildren();
            }
            this._register((0, observable_1.autorun)(reader => {
                /** @description update labels */
                if (!this._hide) {
                    const lineCount = this._unchangedRegion.getHiddenModifiedRange(reader).length;
                    const linesHiddenText = (0, nls_1.localize)(112, '{0} hidden lines', lineCount);
                    this._nodes.text.innerText = linesHiddenText;
                }
            }));
        }
    }
    class CollapsedCodeOverlayWidget extends utils_1.ViewZoneOverlayWidget {
        constructor(_editor, _viewZone, _unchangedRegion, _unchangedRegionRange, _hide, _modifiedOutlineSource, _revealModifiedHiddenLine, _options) {
            const root = (0, dom_1.h)('div.diff-hidden-lines-widget');
            super(_editor, _viewZone, root.root);
            this._editor = _editor;
            this._unchangedRegion = _unchangedRegion;
            this._unchangedRegionRange = _unchangedRegionRange;
            this._hide = _hide;
            this._modifiedOutlineSource = _modifiedOutlineSource;
            this._revealModifiedHiddenLine = _revealModifiedHiddenLine;
            this._options = _options;
            this._nodes = (0, dom_1.h)('div.diff-hidden-lines', [
                (0, dom_1.h)('div.top@top', { title: (0, nls_1.localize)(113, 'Click or drag to show more above') }),
                (0, dom_1.h)('div.center@content', { style: { display: 'flex' } }, [
                    (0, dom_1.h)('div@first', { style: { display: 'flex', justifyContent: 'center', alignItems: 'center', flexShrink: '0' } }, [(0, dom_1.$)('a', { title: (0, nls_1.localize)(114, 'Show Unchanged Region'), role: 'button', onclick: () => { this._unchangedRegion.showAll(undefined); } }, ...(0, iconLabels_1.renderLabelWithIcons)('$(unfold)'))]),
                    (0, dom_1.h)('div@others', { style: { display: 'flex', justifyContent: 'center', alignItems: 'center' } }),
                ]),
                (0, dom_1.h)('div.bottom@bottom', { title: (0, nls_1.localize)(115, 'Click or drag to show more below'), role: 'button' }),
            ]);
            root.root.appendChild(this._nodes.root);
            if (!this._hide) {
                this._register((0, utils_1.applyStyle)(this._nodes.first, { width: (0, observableCodeEditor_1.observableCodeEditor)(this._editor).layoutInfoContentLeft }));
            }
            else {
                (0, dom_1.reset)(this._nodes.first);
            }
            this._register((0, observable_1.autorun)(reader => {
                /** @description Update CollapsedCodeOverlayWidget canMove* css classes */
                const isFullyRevealed = this._unchangedRegion.visibleLineCountTop.read(reader) + this._unchangedRegion.visibleLineCountBottom.read(reader) === this._unchangedRegion.lineCount;
                this._nodes.bottom.classList.toggle('canMoveTop', !isFullyRevealed);
                this._nodes.bottom.classList.toggle('canMoveBottom', this._unchangedRegion.visibleLineCountBottom.read(reader) > 0);
                this._nodes.top.classList.toggle('canMoveTop', this._unchangedRegion.visibleLineCountTop.read(reader) > 0);
                this._nodes.top.classList.toggle('canMoveBottom', !isFullyRevealed);
                const isDragged = this._unchangedRegion.isDragged.read(reader);
                const domNode = this._editor.getDomNode();
                if (domNode) {
                    domNode.classList.toggle('draggingUnchangedRegion', !!isDragged);
                    if (isDragged === 'top') {
                        domNode.classList.toggle('canMoveTop', this._unchangedRegion.visibleLineCountTop.read(reader) > 0);
                        domNode.classList.toggle('canMoveBottom', !isFullyRevealed);
                    }
                    else if (isDragged === 'bottom') {
                        domNode.classList.toggle('canMoveTop', !isFullyRevealed);
                        domNode.classList.toggle('canMoveBottom', this._unchangedRegion.visibleLineCountBottom.read(reader) > 0);
                    }
                    else {
                        domNode.classList.toggle('canMoveTop', false);
                        domNode.classList.toggle('canMoveBottom', false);
                    }
                }
            }));
            const editor = this._editor;
            this._register((0, dom_1.addDisposableListener)(this._nodes.top, 'mousedown', e => {
                if (e.button !== 0) {
                    return;
                }
                this._nodes.top.classList.toggle('dragging', true);
                this._nodes.root.classList.toggle('dragging', true);
                e.preventDefault();
                const startTop = e.clientY;
                let didMove = false;
                const cur = this._unchangedRegion.visibleLineCountTop.get();
                this._unchangedRegion.isDragged.set('top', undefined);
                const window = (0, dom_1.getWindow)(this._nodes.top);
                const mouseMoveListener = (0, dom_1.addDisposableListener)(window, 'mousemove', e => {
                    const currentTop = e.clientY;
                    const delta = currentTop - startTop;
                    didMove = didMove || Math.abs(delta) > 2;
                    const lineDelta = Math.round(delta / editor.getOption(67 /* EditorOption.lineHeight */));
                    const newVal = Math.max(0, Math.min(cur + lineDelta, this._unchangedRegion.getMaxVisibleLineCountTop()));
                    this._unchangedRegion.visibleLineCountTop.set(newVal, undefined);
                });
                const mouseUpListener = (0, dom_1.addDisposableListener)(window, 'mouseup', e => {
                    if (!didMove) {
                        this._unchangedRegion.showMoreAbove(this._options.hideUnchangedRegionsRevealLineCount.get(), undefined);
                    }
                    this._nodes.top.classList.toggle('dragging', false);
                    this._nodes.root.classList.toggle('dragging', false);
                    this._unchangedRegion.isDragged.set(undefined, undefined);
                    mouseMoveListener.dispose();
                    mouseUpListener.dispose();
                });
            }));
            this._register((0, dom_1.addDisposableListener)(this._nodes.bottom, 'mousedown', e => {
                if (e.button !== 0) {
                    return;
                }
                this._nodes.bottom.classList.toggle('dragging', true);
                this._nodes.root.classList.toggle('dragging', true);
                e.preventDefault();
                const startTop = e.clientY;
                let didMove = false;
                const cur = this._unchangedRegion.visibleLineCountBottom.get();
                this._unchangedRegion.isDragged.set('bottom', undefined);
                const window = (0, dom_1.getWindow)(this._nodes.bottom);
                const mouseMoveListener = (0, dom_1.addDisposableListener)(window, 'mousemove', e => {
                    const currentTop = e.clientY;
                    const delta = currentTop - startTop;
                    didMove = didMove || Math.abs(delta) > 2;
                    const lineDelta = Math.round(delta / editor.getOption(67 /* EditorOption.lineHeight */));
                    const newVal = Math.max(0, Math.min(cur - lineDelta, this._unchangedRegion.getMaxVisibleLineCountBottom()));
                    const top = this._unchangedRegionRange.endLineNumberExclusive > editor.getModel().getLineCount()
                        ? editor.getContentHeight()
                        : editor.getTopForLineNumber(this._unchangedRegionRange.endLineNumberExclusive);
                    this._unchangedRegion.visibleLineCountBottom.set(newVal, undefined);
                    const top2 = this._unchangedRegionRange.endLineNumberExclusive > editor.getModel().getLineCount()
                        ? editor.getContentHeight()
                        : editor.getTopForLineNumber(this._unchangedRegionRange.endLineNumberExclusive);
                    editor.setScrollTop(editor.getScrollTop() + (top2 - top));
                });
                const mouseUpListener = (0, dom_1.addDisposableListener)(window, 'mouseup', e => {
                    this._unchangedRegion.isDragged.set(undefined, undefined);
                    if (!didMove) {
                        const top = editor.getTopForLineNumber(this._unchangedRegionRange.endLineNumberExclusive);
                        this._unchangedRegion.showMoreBelow(this._options.hideUnchangedRegionsRevealLineCount.get(), undefined);
                        const top2 = editor.getTopForLineNumber(this._unchangedRegionRange.endLineNumberExclusive);
                        editor.setScrollTop(editor.getScrollTop() + (top2 - top));
                    }
                    this._nodes.bottom.classList.toggle('dragging', false);
                    this._nodes.root.classList.toggle('dragging', false);
                    mouseMoveListener.dispose();
                    mouseUpListener.dispose();
                });
            }));
            this._register((0, observable_1.autorun)(reader => {
                /** @description update labels */
                const children = [];
                if (!this._hide) {
                    const lineCount = _unchangedRegion.getHiddenModifiedRange(reader).length;
                    const linesHiddenText = (0, nls_1.localize)(116, '{0} hidden lines', lineCount);
                    const span = (0, dom_1.$)('span', { title: (0, nls_1.localize)(117, 'Double click to unfold') }, linesHiddenText);
                    span.addEventListener('dblclick', e => {
                        if (e.button !== 0) {
                            return;
                        }
                        e.preventDefault();
                        this._unchangedRegion.showAll(undefined);
                    });
                    children.push(span);
                    const range = this._unchangedRegion.getHiddenModifiedRange(reader);
                    const items = this._modifiedOutlineSource.getBreadcrumbItems(range, reader);
                    if (items.length > 0) {
                        children.push((0, dom_1.$)('span', undefined, '\u00a0\u00a0|\u00a0\u00a0'));
                        for (let i = 0; i < items.length; i++) {
                            const item = items[i];
                            const icon = languages_1.SymbolKinds.toIcon(item.kind);
                            const divItem = (0, dom_1.h)('div.breadcrumb-item', {
                                style: { display: 'flex', alignItems: 'center' },
                            }, [
                                (0, iconLabels_1.renderIcon)(icon),
                                '\u00a0',
                                item.name,
                                ...(i === items.length - 1
                                    ? []
                                    : [(0, iconLabels_1.renderIcon)(codicons_1.Codicon.chevronRight)])
                            ]).root;
                            children.push(divItem);
                            divItem.onclick = () => {
                                this._revealModifiedHiddenLine(item.startLineNumber);
                            };
                        }
                    }
                }
                (0, dom_1.reset)(this._nodes.others, ...children);
            }));
        }
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[43/*vs/editor/common/languages/language*/], __M([1/*require*/,0/*exports*/,7/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ILanguageService = void 0;
    exports.ILanguageService = (0, instantiation_1.createDecorator)('languageService');
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[100/*vs/editor/common/services/editorWorker*/], __M([1/*require*/,0/*exports*/,7/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.IEditorWorkerService = void 0;
    exports.IEditorWorkerService = (0, instantiation_1.createDecorator)('editorWorkerService');
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[17/*vs/editor/common/services/languageFeatures*/], __M([1/*require*/,0/*exports*/,7/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ILanguageFeaturesService = void 0;
    exports.ILanguageFeaturesService = (0, instantiation_1.createDecorator)('ILanguageFeaturesService');
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[677/*vs/editor/common/services/languageFeaturesService*/], __M([1/*require*/,0/*exports*/,658/*vs/editor/common/languageFeatureRegistry*/,17/*vs/editor/common/services/languageFeatures*/,49/*vs/platform/instantiation/common/extensions*/]), function (require, exports, languageFeatureRegistry_1, languageFeatures_1, extensions_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.LanguageFeaturesService = void 0;
    class LanguageFeaturesService {
        constructor() {
            this.referenceProvider = new languageFeatureRegistry_1.LanguageFeatureRegistry(this._score.bind(this));
            this.renameProvider = new languageFeatureRegistry_1.LanguageFeatureRegistry(this._score.bind(this));
            this.newSymbolNamesProvider = new languageFeatureRegistry_1.LanguageFeatureRegistry(this._score.bind(this));
            this.codeActionProvider = new languageFeatureRegistry_1.LanguageFeatureRegistry(this._score.bind(this));
            this.definitionProvider = new languageFeatureRegistry_1.LanguageFeatureRegistry(this._score.bind(this));
            this.typeDefinitionProvider = new languageFeatureRegistry_1.LanguageFeatureRegistry(this._score.bind(this));
            this.declarationProvider = new languageFeatureRegistry_1.LanguageFeatureRegistry(this._score.bind(this));
            this.implementationProvider = new languageFeatureRegistry_1.LanguageFeatureRegistry(this._score.bind(this));
            this.documentSymbolProvider = new languageFeatureRegistry_1.LanguageFeatureRegistry(this._score.bind(this));
            this.inlayHintsProvider = new languageFeatureRegistry_1.LanguageFeatureRegistry(this._score.bind(this));
            this.colorProvider = new languageFeatureRegistry_1.LanguageFeatureRegistry(this._score.bind(this));
            this.codeLensProvider = new languageFeatureRegistry_1.LanguageFeatureRegistry(this._score.bind(this));
            this.documentFormattingEditProvider = new languageFeatureRegistry_1.LanguageFeatureRegistry(this._score.bind(this));
            this.documentRangeFormattingEditProvider = new languageFeatureRegistry_1.LanguageFeatureRegistry(this._score.bind(this));
            this.onTypeFormattingEditProvider = new languageFeatureRegistry_1.LanguageFeatureRegistry(this._score.bind(this));
            this.signatureHelpProvider = new languageFeatureRegistry_1.LanguageFeatureRegistry(this._score.bind(this));
            this.hoverProvider = new languageFeatureRegistry_1.LanguageFeatureRegistry(this._score.bind(this));
            this.documentHighlightProvider = new languageFeatureRegistry_1.LanguageFeatureRegistry(this._score.bind(this));
            this.multiDocumentHighlightProvider = new languageFeatureRegistry_1.LanguageFeatureRegistry(this._score.bind(this));
            this.selectionRangeProvider = new languageFeatureRegistry_1.LanguageFeatureRegistry(this._score.bind(this));
            this.foldingRangeProvider = new languageFeatureRegistry_1.LanguageFeatureRegistry(this._score.bind(this));
            this.linkProvider = new languageFeatureRegistry_1.LanguageFeatureRegistry(this._score.bind(this));
            this.inlineCompletionsProvider = new languageFeatureRegistry_1.LanguageFeatureRegistry(this._score.bind(this));
            this.inlineEditProvider = new languageFeatureRegistry_1.LanguageFeatureRegistry(this._score.bind(this));
            this.completionProvider = new languageFeatureRegistry_1.LanguageFeatureRegistry(this._score.bind(this));
            this.linkedEditingRangeProvider = new languageFeatureRegistry_1.LanguageFeatureRegistry(this._score.bind(this));
            this.documentRangeSemanticTokensProvider = new languageFeatureRegistry_1.LanguageFeatureRegistry(this._score.bind(this));
            this.documentSemanticTokensProvider = new languageFeatureRegistry_1.LanguageFeatureRegistry(this._score.bind(this));
            this.documentDropEditProvider = new languageFeatureRegistry_1.LanguageFeatureRegistry(this._score.bind(this));
            this.documentPasteEditProvider = new languageFeatureRegistry_1.LanguageFeatureRegistry(this._score.bind(this));
        }
        _score(uri) {
            return this._notebookTypeResolver?.(uri);
        }
    }
    exports.LanguageFeaturesService = LanguageFeaturesService;
    (0, extensions_1.registerSingleton)(languageFeatures_1.ILanguageFeaturesService, LanguageFeaturesService, 1 /* InstantiationType.Delayed */);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[266/*vs/editor/common/services/markerDecorations*/], __M([1/*require*/,0/*exports*/,7/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.IMarkerDecorationsService = void 0;
    exports.IMarkerDecorationsService = (0, instantiation_1.createDecorator)('markerDecorationsService');
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[51/*vs/editor/common/services/model*/], __M([1/*require*/,0/*exports*/,7/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.IModelService = void 0;
    exports.IModelService = (0, instantiation_1.createDecorator)('modelService');
});

define(__m[78/*vs/editor/common/services/resolverService*/], __M([1/*require*/,0/*exports*/,7/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ITextModelService = void 0;
    exports.ITextModelService = (0, instantiation_1.createDecorator)('textModelService');
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[267/*vs/editor/common/services/semanticTokensStyling*/], __M([1/*require*/,0/*exports*/,7/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ISemanticTokensStylingService = void 0;
    exports.ISemanticTokensStylingService = (0, instantiation_1.createDecorator)('semanticTokensStylingService');
});

define(__m[211/*vs/editor/common/services/textResourceConfiguration*/], __M([1/*require*/,0/*exports*/,7/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ITextResourcePropertiesService = exports.ITextResourceConfigurationService = void 0;
    exports.ITextResourceConfigurationService = (0, instantiation_1.createDecorator)('textResourceConfigurationService');
    exports.ITextResourcePropertiesService = (0, instantiation_1.createDecorator)('textResourcePropertiesService');
});

define(__m[384/*vs/editor/common/services/treeSitterParserService*/], __M([1/*require*/,0/*exports*/,7/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ITreeSitterParserService = void 0;
    exports.ITreeSitterParserService = (0, instantiation_1.createDecorator)('treeSitterParserService');
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[678/*vs/editor/common/services/treeViewsDndService*/], __M([1/*require*/,0/*exports*/,49/*vs/platform/instantiation/common/extensions*/,7/*vs/platform/instantiation/common/instantiation*/,327/*vs/editor/common/services/treeViewsDnd*/]), function (require, exports, extensions_1, instantiation_1, treeViewsDnd_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ITreeViewsDnDService = void 0;
    exports.ITreeViewsDnDService = (0, instantiation_1.createDecorator)('treeViewsDndService');
    (0, extensions_1.registerSingleton)(exports.ITreeViewsDnDService, treeViewsDnd_1.TreeViewsDnDService, 1 /* InstantiationType.Delayed */);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[385/*vs/editor/contrib/colorPicker/browser/defaultDocumentColorProvider*/], __M([1/*require*/,0/*exports*/,33/*vs/base/common/color*/,2/*vs/base/common/lifecycle*/,17/*vs/editor/common/services/languageFeatures*/,130/*vs/editor/common/editorFeatures*/,100/*vs/editor/common/services/editorWorker*/]), function (require, exports, color_1, lifecycle_1, languageFeatures_1, editorFeatures_1, editorWorker_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DefaultDocumentColorProvider = void 0;
    let DefaultDocumentColorProvider = class DefaultDocumentColorProvider {
        constructor(_editorWorkerService) {
            this._editorWorkerService = _editorWorkerService;
        }
        async provideDocumentColors(model, _token) {
            return this._editorWorkerService.computeDefaultDocumentColors(model.uri);
        }
        provideColorPresentations(_model, colorInfo, _token) {
            const range = colorInfo.range;
            const colorFromInfo = colorInfo.color;
            const alpha = colorFromInfo.alpha;
            const color = new color_1.Color(new color_1.RGBA(Math.round(255 * colorFromInfo.red), Math.round(255 * colorFromInfo.green), Math.round(255 * colorFromInfo.blue), alpha));
            const rgb = alpha ? color_1.Color.Format.CSS.formatRGB(color) : color_1.Color.Format.CSS.formatRGBA(color);
            const hsl = alpha ? color_1.Color.Format.CSS.formatHSL(color) : color_1.Color.Format.CSS.formatHSLA(color);
            const hex = alpha ? color_1.Color.Format.CSS.formatHex(color) : color_1.Color.Format.CSS.formatHexA(color);
            const colorPresentations = [];
            colorPresentations.push({ label: rgb, textEdit: { range: range, text: rgb } });
            colorPresentations.push({ label: hsl, textEdit: { range: range, text: hsl } });
            colorPresentations.push({ label: hex, textEdit: { range: range, text: hex } });
            return colorPresentations;
        }
    };
    exports.DefaultDocumentColorProvider = DefaultDocumentColorProvider;
    exports.DefaultDocumentColorProvider = DefaultDocumentColorProvider = __decorate([
        __param(0, editorWorker_1.IEditorWorkerService)
    ], DefaultDocumentColorProvider);
    let DefaultDocumentColorProviderFeature = class DefaultDocumentColorProviderFeature extends lifecycle_1.Disposable {
        constructor(_languageFeaturesService, editorWorkerService) {
            super();
            this._register(_languageFeaturesService.colorProvider.register('*', new DefaultDocumentColorProvider(editorWorkerService)));
        }
    };
    DefaultDocumentColorProviderFeature = __decorate([
        __param(0, languageFeatures_1.ILanguageFeaturesService),
        __param(1, editorWorker_1.IEditorWorkerService)
    ], DefaultDocumentColorProviderFeature);
    (0, editorFeatures_1.registerEditorFeature)(DefaultDocumentColorProviderFeature);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[268/*vs/editor/contrib/dropOrPasteInto/browser/edit*/], __M([1/*require*/,0/*exports*/,152/*vs/editor/browser/services/bulkEditService*/,135/*vs/editor/contrib/snippet/browser/snippetParser*/]), function (require, exports, bulkEditService_1, snippetParser_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.createCombinedWorkspaceEdit = createCombinedWorkspaceEdit;
    exports.sortEditsByYieldTo = sortEditsByYieldTo;
    /**
     * Given a {@link DropOrPasteEdit} and set of ranges, creates a {@link WorkspaceEdit} that applies the insert text from
     * the {@link DropOrPasteEdit} at each range plus any additional edits.
     */
    function createCombinedWorkspaceEdit(uri, ranges, edit) {
        // If the edit insert text is empty, skip applying at each range
        if (typeof edit.insertText === 'string' ? edit.insertText === '' : edit.insertText.snippet === '') {
            return {
                edits: edit.additionalEdit?.edits ?? []
            };
        }
        return {
            edits: [
                ...ranges.map(range => new bulkEditService_1.ResourceTextEdit(uri, { range, text: typeof edit.insertText === 'string' ? snippetParser_1.SnippetParser.escape(edit.insertText) + '$0' : edit.insertText.snippet, insertAsSnippet: true })),
                ...(edit.additionalEdit?.edits ?? [])
            ]
        };
    }
    function sortEditsByYieldTo(edits) {
        function yieldsTo(yTo, other) {
            if ('mimeType' in yTo) {
                return yTo.mimeType === other.handledMimeType;
            }
            return !!other.kind && yTo.kind.contains(other.kind);
        }
        // Build list of nodes each node yields to
        const yieldsToMap = new Map();
        for (const edit of edits) {
            for (const yTo of edit.yieldTo ?? []) {
                for (const other of edits) {
                    if (other === edit) {
                        continue;
                    }
                    if (yieldsTo(yTo, other)) {
                        let arr = yieldsToMap.get(edit);
                        if (!arr) {
                            arr = [];
                            yieldsToMap.set(edit, arr);
                        }
                        arr.push(other);
                    }
                }
            }
        }
        if (!yieldsToMap.size) {
            return Array.from(edits);
        }
        // Topological sort
        const visited = new Set();
        const tempStack = [];
        function visit(nodes) {
            if (!nodes.length) {
                return [];
            }
            const node = nodes[0];
            if (tempStack.includes(node)) {
                console.warn('Yield to cycle detected', node);
                return nodes;
            }
            if (visited.has(node)) {
                return visit(nodes.slice(1));
            }
            let pre = [];
            const yTo = yieldsToMap.get(node);
            if (yTo) {
                tempStack.push(node);
                pre = visit(yTo);
                tempStack.pop();
            }
            visited.add(node);
            return [...pre, node, ...visit(nodes.slice(1))];
        }
        return visit(Array.from(edits));
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[679/*vs/editor/contrib/inlineCompletions/browser/view/ghostTextView*/], __M([1/*require*/,0/*exports*/,103/*vs/base/browser/trustedTypes*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,21/*vs/base/common/observable*/,11/*vs/base/common/strings*/,74/*vs/editor/browser/config/domFontInfo*/,37/*vs/editor/common/config/editorOptions*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/,116/*vs/editor/common/core/stringBuilder*/,43/*vs/editor/common/languages/language*/,40/*vs/editor/common/model*/,83/*vs/editor/common/tokens/lineTokens*/,150/*vs/editor/common/viewLayout/lineDecorations*/,136/*vs/editor/common/viewLayout/viewLineRenderer*/,204/*vs/editor/contrib/inlineCompletions/browser/model/ghostText*/,205/*vs/editor/contrib/inlineCompletions/browser/utils*/,517/*vs/css!vs/editor/contrib/inlineCompletions/browser/view/ghostTextView*/]), function (require, exports, trustedTypes_1, event_1, lifecycle_1, observable_1, strings, domFontInfo_1, editorOptions_1, position_1, range_1, stringBuilder_1, language_1, model_1, lineTokens_1, lineDecorations_1, viewLineRenderer_1, ghostText_1, utils_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ttPolicy = exports.AdditionalLinesWidget = exports.GhostTextView = exports.GHOST_TEXT_DESCRIPTION = void 0;
    exports.GHOST_TEXT_DESCRIPTION = 'ghost-text';
    let GhostTextView = class GhostTextView extends lifecycle_1.Disposable {
        constructor(editor, model, languageService) {
            super();
            this.editor = editor;
            this.model = model;
            this.languageService = languageService;
            this.isDisposed = (0, observable_1.observableValue)(this, false);
            this.currentTextModel = (0, observable_1.observableFromEvent)(this, this.editor.onDidChangeModel, () => /** @description editor.model */ this.editor.getModel());
            this.uiState = (0, observable_1.derived)(this, reader => {
                if (this.isDisposed.read(reader)) {
                    return undefined;
                }
                const textModel = this.currentTextModel.read(reader);
                if (textModel !== this.model.targetTextModel.read(reader)) {
                    return undefined;
                }
                const ghostText = this.model.ghostText.read(reader);
                if (!ghostText) {
                    return undefined;
                }
                const replacedRange = ghostText instanceof ghostText_1.GhostTextReplacement ? ghostText.columnRange : undefined;
                const inlineTexts = [];
                const additionalLines = [];
                function addToAdditionalLines(lines, className) {
                    if (additionalLines.length > 0) {
                        const lastLine = additionalLines[additionalLines.length - 1];
                        if (className) {
                            lastLine.decorations.push(new lineDecorations_1.LineDecoration(lastLine.content.length + 1, lastLine.content.length + 1 + lines[0].length, className, 0 /* InlineDecorationType.Regular */));
                        }
                        lastLine.content += lines[0];
                        lines = lines.slice(1);
                    }
                    for (const line of lines) {
                        additionalLines.push({
                            content: line,
                            decorations: className ? [new lineDecorations_1.LineDecoration(1, line.length + 1, className, 0 /* InlineDecorationType.Regular */)] : []
                        });
                    }
                }
                const textBufferLine = textModel.getLineContent(ghostText.lineNumber);
                let hiddenTextStartColumn = undefined;
                let lastIdx = 0;
                for (const part of ghostText.parts) {
                    let lines = part.lines;
                    if (hiddenTextStartColumn === undefined) {
                        inlineTexts.push({
                            column: part.column,
                            text: lines[0],
                            preview: part.preview,
                        });
                        lines = lines.slice(1);
                    }
                    else {
                        addToAdditionalLines([textBufferLine.substring(lastIdx, part.column - 1)], undefined);
                    }
                    if (lines.length > 0) {
                        addToAdditionalLines(lines, exports.GHOST_TEXT_DESCRIPTION);
                        if (hiddenTextStartColumn === undefined && part.column <= textBufferLine.length) {
                            hiddenTextStartColumn = part.column;
                        }
                    }
                    lastIdx = part.column - 1;
                }
                if (hiddenTextStartColumn !== undefined) {
                    addToAdditionalLines([textBufferLine.substring(lastIdx)], undefined);
                }
                const hiddenRange = hiddenTextStartColumn !== undefined ? new utils_1.ColumnRange(hiddenTextStartColumn, textBufferLine.length + 1) : undefined;
                return {
                    replacedRange,
                    inlineTexts,
                    additionalLines,
                    hiddenRange,
                    lineNumber: ghostText.lineNumber,
                    additionalReservedLineCount: this.model.minReservedLineCount.read(reader),
                    targetTextModel: textModel,
                };
            });
            this.decorations = (0, observable_1.derived)(this, reader => {
                const uiState = this.uiState.read(reader);
                if (!uiState) {
                    return [];
                }
                const decorations = [];
                if (uiState.replacedRange) {
                    decorations.push({
                        range: uiState.replacedRange.toRange(uiState.lineNumber),
                        options: { inlineClassName: 'inline-completion-text-to-replace', description: 'GhostTextReplacement' }
                    });
                }
                if (uiState.hiddenRange) {
                    decorations.push({
                        range: uiState.hiddenRange.toRange(uiState.lineNumber),
                        options: { inlineClassName: 'ghost-text-hidden', description: 'ghost-text-hidden', }
                    });
                }
                for (const p of uiState.inlineTexts) {
                    decorations.push({
                        range: range_1.Range.fromPositions(new position_1.Position(uiState.lineNumber, p.column)),
                        options: {
                            description: exports.GHOST_TEXT_DESCRIPTION,
                            after: { content: p.text, inlineClassName: p.preview ? 'ghost-text-decoration-preview' : 'ghost-text-decoration', cursorStops: model_1.InjectedTextCursorStops.Left },
                            showIfCollapsed: true,
                        }
                    });
                }
                return decorations;
            });
            this.additionalLinesWidget = this._register(new AdditionalLinesWidget(this.editor, this.languageService.languageIdCodec, (0, observable_1.derived)(reader => {
                /** @description lines */
                const uiState = this.uiState.read(reader);
                return uiState ? {
                    lineNumber: uiState.lineNumber,
                    additionalLines: uiState.additionalLines,
                    minReservedLineCount: uiState.additionalReservedLineCount,
                    targetTextModel: uiState.targetTextModel,
                } : undefined;
            })));
            this._register((0, lifecycle_1.toDisposable)(() => { this.isDisposed.set(true, undefined); }));
            this._register((0, utils_1.applyObservableDecorations)(this.editor, this.decorations));
        }
        ownsViewZone(viewZoneId) {
            return this.additionalLinesWidget.viewZoneId === viewZoneId;
        }
    };
    exports.GhostTextView = GhostTextView;
    exports.GhostTextView = GhostTextView = __decorate([
        __param(2, language_1.ILanguageService)
    ], GhostTextView);
    class AdditionalLinesWidget extends lifecycle_1.Disposable {
        get viewZoneId() { return this._viewZoneId; }
        constructor(editor, languageIdCodec, lines) {
            super();
            this.editor = editor;
            this.languageIdCodec = languageIdCodec;
            this.lines = lines;
            this._viewZoneId = undefined;
            this.editorOptionsChanged = (0, observable_1.observableSignalFromEvent)('editorOptionChanged', event_1.Event.filter(this.editor.onDidChangeConfiguration, e => e.hasChanged(33 /* EditorOption.disableMonospaceOptimizations */)
                || e.hasChanged(118 /* EditorOption.stopRenderingLineAfter */)
                || e.hasChanged(100 /* EditorOption.renderWhitespace */)
                || e.hasChanged(95 /* EditorOption.renderControlCharacters */)
                || e.hasChanged(51 /* EditorOption.fontLigatures */)
                || e.hasChanged(50 /* EditorOption.fontInfo */)
                || e.hasChanged(67 /* EditorOption.lineHeight */)));
            this._register((0, observable_1.autorun)(reader => {
                /** @description update view zone */
                const lines = this.lines.read(reader);
                this.editorOptionsChanged.read(reader);
                if (lines) {
                    this.updateLines(lines.lineNumber, lines.additionalLines, lines.minReservedLineCount);
                }
                else {
                    this.clear();
                }
            }));
        }
        dispose() {
            super.dispose();
            this.clear();
        }
        clear() {
            this.editor.changeViewZones((changeAccessor) => {
                if (this._viewZoneId) {
                    changeAccessor.removeZone(this._viewZoneId);
                    this._viewZoneId = undefined;
                }
            });
        }
        updateLines(lineNumber, additionalLines, minReservedLineCount) {
            const textModel = this.editor.getModel();
            if (!textModel) {
                return;
            }
            const { tabSize } = textModel.getOptions();
            this.editor.changeViewZones((changeAccessor) => {
                if (this._viewZoneId) {
                    changeAccessor.removeZone(this._viewZoneId);
                    this._viewZoneId = undefined;
                }
                const heightInLines = Math.max(additionalLines.length, minReservedLineCount);
                if (heightInLines > 0) {
                    const domNode = document.createElement('div');
                    renderLines(domNode, tabSize, additionalLines, this.editor.getOptions(), this.languageIdCodec);
                    this._viewZoneId = changeAccessor.addZone({
                        afterLineNumber: lineNumber,
                        heightInLines: heightInLines,
                        domNode,
                        afterColumnAffinity: 1 /* PositionAffinity.Right */
                    });
                }
            });
        }
    }
    exports.AdditionalLinesWidget = AdditionalLinesWidget;
    function renderLines(domNode, tabSize, lines, opts, languageIdCodec) {
        const disableMonospaceOptimizations = opts.get(33 /* EditorOption.disableMonospaceOptimizations */);
        const stopRenderingLineAfter = opts.get(118 /* EditorOption.stopRenderingLineAfter */);
        // To avoid visual confusion, we don't want to render visible whitespace
        const renderWhitespace = 'none';
        const renderControlCharacters = opts.get(95 /* EditorOption.renderControlCharacters */);
        const fontLigatures = opts.get(51 /* EditorOption.fontLigatures */);
        const fontInfo = opts.get(50 /* EditorOption.fontInfo */);
        const lineHeight = opts.get(67 /* EditorOption.lineHeight */);
        const sb = new stringBuilder_1.StringBuilder(10000);
        sb.appendString('<div class="suggest-preview-text">');
        for (let i = 0, len = lines.length; i < len; i++) {
            const lineData = lines[i];
            const line = lineData.content;
            sb.appendString('<div class="view-line');
            sb.appendString('" style="top:');
            sb.appendString(String(i * lineHeight));
            sb.appendString('px;width:1000000px;">');
            const isBasicASCII = strings.isBasicASCII(line);
            const containsRTL = strings.containsRTL(line);
            const lineTokens = lineTokens_1.LineTokens.createEmpty(line, languageIdCodec);
            (0, viewLineRenderer_1.renderViewLine)(new viewLineRenderer_1.RenderLineInput((fontInfo.isMonospace && !disableMonospaceOptimizations), fontInfo.canUseHalfwidthRightwardsArrow, line, false, isBasicASCII, containsRTL, 0, lineTokens, lineData.decorations, tabSize, 0, fontInfo.spaceWidth, fontInfo.middotWidth, fontInfo.wsmiddotWidth, stopRenderingLineAfter, renderWhitespace, renderControlCharacters, fontLigatures !== editorOptions_1.EditorFontLigatures.OFF, null), sb);
            sb.appendString('</div>');
        }
        sb.appendString('</div>');
        (0, domFontInfo_1.applyFontInfo)(domNode, fontInfo);
        const html = sb.build();
        const trustedhtml = exports.ttPolicy ? exports.ttPolicy.createHTML(html) : html;
        domNode.innerHTML = trustedhtml;
    }
    exports.ttPolicy = (0, trustedTypes_1.createTrustedTypesPolicy)('editorGhostText', { createHTML: value => value });
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[680/*vs/editor/contrib/wordHighlighter/browser/textualHighlightProvider*/], __M([1/*require*/,0/*exports*/,147/*vs/editor/common/core/wordHelper*/,17/*vs/editor/common/services/languageFeatures*/,27/*vs/editor/common/languages*/,2/*vs/base/common/lifecycle*/,45/*vs/base/common/map*/]), function (require, exports, wordHelper_1, languageFeatures_1, languages_1, lifecycle_1, map_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.TextualMultiDocumentHighlightFeature = void 0;
    class TextualDocumentHighlightProvider {
        constructor() {
            this.selector = { language: '*' };
        }
        provideDocumentHighlights(model, position, token) {
            const result = [];
            const word = model.getWordAtPosition({
                lineNumber: position.lineNumber,
                column: position.column
            });
            if (!word) {
                return Promise.resolve(result);
            }
            if (model.isDisposed()) {
                return;
            }
            const matches = model.findMatches(word.word, true, false, true, wordHelper_1.USUAL_WORD_SEPARATORS, false);
            return matches.map(m => ({
                range: m.range,
                kind: languages_1.DocumentHighlightKind.Text
            }));
        }
        provideMultiDocumentHighlights(primaryModel, position, otherModels, token) {
            const result = new map_1.ResourceMap();
            const word = primaryModel.getWordAtPosition({
                lineNumber: position.lineNumber,
                column: position.column
            });
            if (!word) {
                return Promise.resolve(result);
            }
            for (const model of [primaryModel, ...otherModels]) {
                if (model.isDisposed()) {
                    continue;
                }
                const matches = model.findMatches(word.word, true, false, true, wordHelper_1.USUAL_WORD_SEPARATORS, false);
                const highlights = matches.map(m => ({
                    range: m.range,
                    kind: languages_1.DocumentHighlightKind.Text
                }));
                if (highlights) {
                    result.set(model.uri, highlights);
                }
            }
            return result;
        }
    }
    let TextualMultiDocumentHighlightFeature = class TextualMultiDocumentHighlightFeature extends lifecycle_1.Disposable {
        constructor(languageFeaturesService) {
            super();
            this._register(languageFeaturesService.documentHighlightProvider.register('*', new TextualDocumentHighlightProvider()));
            this._register(languageFeaturesService.multiDocumentHighlightProvider.register('*', new TextualDocumentHighlightProvider()));
        }
    };
    exports.TextualMultiDocumentHighlightFeature = TextualMultiDocumentHighlightFeature;
    exports.TextualMultiDocumentHighlightFeature = TextualMultiDocumentHighlightFeature = __decorate([
        __param(0, languageFeatures_1.ILanguageFeaturesService)
    ], TextualMultiDocumentHighlightFeature);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[153/*vs/editor/standalone/common/standaloneTheme*/], __M([1/*require*/,0/*exports*/,7/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.IStandaloneThemeService = void 0;
    exports.IStandaloneThemeService = (0, instantiation_1.createDecorator)('themeService');
});

define(__m[137/*vs/platform/accessibilitySignal/browser/accessibilitySignalService*/], __M([1/*require*/,0/*exports*/,3/*vs/nls*/,7/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, nls_1, instantiation_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AccessibilitySignal = exports.SoundSource = exports.Sound = exports.AcknowledgeDocCommentsToken = exports.IAccessibilitySignalService = void 0;
    exports.IAccessibilitySignalService = (0, instantiation_1.createDecorator)('accessibilitySignalService');
    /** Make sure you understand the doc comments of the method you want to call when using this token! */
    exports.AcknowledgeDocCommentsToken = Symbol('AcknowledgeDocCommentsToken');
    /**
     * Corresponds to the audio files in ./media.
    */
    class Sound {
        static register(options) {
            const sound = new Sound(options.fileName);
            return sound;
        }
        static { this.error = Sound.register({ fileName: 'error.mp3' }); }
        static { this.warning = Sound.register({ fileName: 'warning.mp3' }); }
        static { this.success = Sound.register({ fileName: 'success.mp3' }); }
        static { this.foldedArea = Sound.register({ fileName: 'foldedAreas.mp3' }); }
        static { this.break = Sound.register({ fileName: 'break.mp3' }); }
        static { this.quickFixes = Sound.register({ fileName: 'quickFixes.mp3' }); }
        static { this.taskCompleted = Sound.register({ fileName: 'taskCompleted.mp3' }); }
        static { this.taskFailed = Sound.register({ fileName: 'taskFailed.mp3' }); }
        static { this.terminalBell = Sound.register({ fileName: 'terminalBell.mp3' }); }
        static { this.diffLineInserted = Sound.register({ fileName: 'diffLineInserted.mp3' }); }
        static { this.diffLineDeleted = Sound.register({ fileName: 'diffLineDeleted.mp3' }); }
        static { this.diffLineModified = Sound.register({ fileName: 'diffLineModified.mp3' }); }
        static { this.chatRequestSent = Sound.register({ fileName: 'chatRequestSent.mp3' }); }
        static { this.chatResponseReceived1 = Sound.register({ fileName: 'chatResponseReceived1.mp3' }); }
        static { this.chatResponseReceived2 = Sound.register({ fileName: 'chatResponseReceived2.mp3' }); }
        static { this.chatResponseReceived3 = Sound.register({ fileName: 'chatResponseReceived3.mp3' }); }
        static { this.chatResponseReceived4 = Sound.register({ fileName: 'chatResponseReceived4.mp3' }); }
        static { this.clear = Sound.register({ fileName: 'clear.mp3' }); }
        static { this.save = Sound.register({ fileName: 'save.mp3' }); }
        static { this.format = Sound.register({ fileName: 'format.mp3' }); }
        static { this.voiceRecordingStarted = Sound.register({ fileName: 'voiceRecordingStarted.mp3' }); }
        static { this.voiceRecordingStopped = Sound.register({ fileName: 'voiceRecordingStopped.mp3' }); }
        static { this.progress = Sound.register({ fileName: 'progress.mp3' }); }
        constructor(fileName) {
            this.fileName = fileName;
        }
    }
    exports.Sound = Sound;
    class SoundSource {
        constructor(randomOneOf) {
            this.randomOneOf = randomOneOf;
        }
    }
    exports.SoundSource = SoundSource;
    class AccessibilitySignal {
        constructor(sound, name, legacySoundSettingsKey, settingsKey, legacyAnnouncementSettingsKey, announcementMessage) {
            this.sound = sound;
            this.name = name;
            this.legacySoundSettingsKey = legacySoundSettingsKey;
            this.settingsKey = settingsKey;
            this.legacyAnnouncementSettingsKey = legacyAnnouncementSettingsKey;
            this.announcementMessage = announcementMessage;
        }
        static { this._signals = new Set(); }
        static register(options) {
            const soundSource = new SoundSource('randomOneOf' in options.sound ? options.sound.randomOneOf : [options.sound]);
            const signal = new AccessibilitySignal(soundSource, options.name, options.legacySoundSettingsKey, options.settingsKey, options.legacyAnnouncementSettingsKey, options.announcementMessage);
            AccessibilitySignal._signals.add(signal);
            return signal;
        }
        static { this.errorAtPosition = AccessibilitySignal.register({
            name: (0, nls_1.localize)(1428, 'Error at Position'),
            sound: Sound.error,
            announcementMessage: (0, nls_1.localize)(1429, 'Error'),
            settingsKey: 'accessibility.signals.positionHasError',
            delaySettingsKey: 'accessibility.signalOptions.delays.errorAtPosition'
        }); }
        static { this.warningAtPosition = AccessibilitySignal.register({
            name: (0, nls_1.localize)(1430, 'Warning at Position'),
            sound: Sound.warning,
            announcementMessage: (0, nls_1.localize)(1431, 'Warning'),
            settingsKey: 'accessibility.signals.positionHasWarning',
            delaySettingsKey: 'accessibility.signalOptions.delays.warningAtPosition'
        }); }
        static { this.errorOnLine = AccessibilitySignal.register({
            name: (0, nls_1.localize)(1432, 'Error on Line'),
            sound: Sound.error,
            legacySoundSettingsKey: 'audioCues.lineHasError',
            legacyAnnouncementSettingsKey: 'accessibility.alert.error',
            announcementMessage: (0, nls_1.localize)(1433, 'Error on Line'),
            settingsKey: 'accessibility.signals.lineHasError',
        }); }
        static { this.warningOnLine = AccessibilitySignal.register({
            name: (0, nls_1.localize)(1434, 'Warning on Line'),
            sound: Sound.warning,
            legacySoundSettingsKey: 'audioCues.lineHasWarning',
            legacyAnnouncementSettingsKey: 'accessibility.alert.warning',
            announcementMessage: (0, nls_1.localize)(1435, 'Warning on Line'),
            settingsKey: 'accessibility.signals.lineHasWarning',
        }); }
        static { this.foldedArea = AccessibilitySignal.register({
            name: (0, nls_1.localize)(1436, 'Folded Area on Line'),
            sound: Sound.foldedArea,
            legacySoundSettingsKey: 'audioCues.lineHasFoldedArea',
            legacyAnnouncementSettingsKey: 'accessibility.alert.foldedArea',
            announcementMessage: (0, nls_1.localize)(1437, 'Folded'),
            settingsKey: 'accessibility.signals.lineHasFoldedArea',
        }); }
        static { this.break = AccessibilitySignal.register({
            name: (0, nls_1.localize)(1438, 'Breakpoint on Line'),
            sound: Sound.break,
            legacySoundSettingsKey: 'audioCues.lineHasBreakpoint',
            legacyAnnouncementSettingsKey: 'accessibility.alert.breakpoint',
            announcementMessage: (0, nls_1.localize)(1439, 'Breakpoint'),
            settingsKey: 'accessibility.signals.lineHasBreakpoint',
        }); }
        static { this.inlineSuggestion = AccessibilitySignal.register({
            name: (0, nls_1.localize)(1440, 'Inline Suggestion on Line'),
            sound: Sound.quickFixes,
            legacySoundSettingsKey: 'audioCues.lineHasInlineSuggestion',
            settingsKey: 'accessibility.signals.lineHasInlineSuggestion',
        }); }
        static { this.terminalQuickFix = AccessibilitySignal.register({
            name: (0, nls_1.localize)(1441, 'Terminal Quick Fix'),
            sound: Sound.quickFixes,
            legacySoundSettingsKey: 'audioCues.terminalQuickFix',
            legacyAnnouncementSettingsKey: 'accessibility.alert.terminalQuickFix',
            announcementMessage: (0, nls_1.localize)(1442, 'Quick Fix'),
            settingsKey: 'accessibility.signals.terminalQuickFix',
        }); }
        static { this.onDebugBreak = AccessibilitySignal.register({
            name: (0, nls_1.localize)(1443, 'Debugger Stopped on Breakpoint'),
            sound: Sound.break,
            legacySoundSettingsKey: 'audioCues.onDebugBreak',
            legacyAnnouncementSettingsKey: 'accessibility.alert.onDebugBreak',
            announcementMessage: (0, nls_1.localize)(1444, 'Breakpoint'),
            settingsKey: 'accessibility.signals.onDebugBreak',
        }); }
        static { this.noInlayHints = AccessibilitySignal.register({
            name: (0, nls_1.localize)(1445, 'No Inlay Hints on Line'),
            sound: Sound.error,
            legacySoundSettingsKey: 'audioCues.noInlayHints',
            legacyAnnouncementSettingsKey: 'accessibility.alert.noInlayHints',
            announcementMessage: (0, nls_1.localize)(1446, 'No Inlay Hints'),
            settingsKey: 'accessibility.signals.noInlayHints',
        }); }
        static { this.taskCompleted = AccessibilitySignal.register({
            name: (0, nls_1.localize)(1447, 'Task Completed'),
            sound: Sound.taskCompleted,
            legacySoundSettingsKey: 'audioCues.taskCompleted',
            legacyAnnouncementSettingsKey: 'accessibility.alert.taskCompleted',
            announcementMessage: (0, nls_1.localize)(1448, 'Task Completed'),
            settingsKey: 'accessibility.signals.taskCompleted',
        }); }
        static { this.taskFailed = AccessibilitySignal.register({
            name: (0, nls_1.localize)(1449, 'Task Failed'),
            sound: Sound.taskFailed,
            legacySoundSettingsKey: 'audioCues.taskFailed',
            legacyAnnouncementSettingsKey: 'accessibility.alert.taskFailed',
            announcementMessage: (0, nls_1.localize)(1450, 'Task Failed'),
            settingsKey: 'accessibility.signals.taskFailed',
        }); }
        static { this.terminalCommandFailed = AccessibilitySignal.register({
            name: (0, nls_1.localize)(1451, 'Terminal Command Failed'),
            sound: Sound.error,
            legacySoundSettingsKey: 'audioCues.terminalCommandFailed',
            legacyAnnouncementSettingsKey: 'accessibility.alert.terminalCommandFailed',
            announcementMessage: (0, nls_1.localize)(1452, 'Command Failed'),
            settingsKey: 'accessibility.signals.terminalCommandFailed',
        }); }
        static { this.terminalCommandSucceeded = AccessibilitySignal.register({
            name: (0, nls_1.localize)(1453, 'Terminal Command Succeeded'),
            sound: Sound.success,
            announcementMessage: (0, nls_1.localize)(1454, 'Command Succeeded'),
            settingsKey: 'accessibility.signals.terminalCommandSucceeded',
        }); }
        static { this.terminalBell = AccessibilitySignal.register({
            name: (0, nls_1.localize)(1455, 'Terminal Bell'),
            sound: Sound.terminalBell,
            legacySoundSettingsKey: 'audioCues.terminalBell',
            legacyAnnouncementSettingsKey: 'accessibility.alert.terminalBell',
            announcementMessage: (0, nls_1.localize)(1456, 'Terminal Bell'),
            settingsKey: 'accessibility.signals.terminalBell',
        }); }
        static { this.notebookCellCompleted = AccessibilitySignal.register({
            name: (0, nls_1.localize)(1457, 'Notebook Cell Completed'),
            sound: Sound.taskCompleted,
            legacySoundSettingsKey: 'audioCues.notebookCellCompleted',
            legacyAnnouncementSettingsKey: 'accessibility.alert.notebookCellCompleted',
            announcementMessage: (0, nls_1.localize)(1458, 'Notebook Cell Completed'),
            settingsKey: 'accessibility.signals.notebookCellCompleted',
        }); }
        static { this.notebookCellFailed = AccessibilitySignal.register({
            name: (0, nls_1.localize)(1459, 'Notebook Cell Failed'),
            sound: Sound.taskFailed,
            legacySoundSettingsKey: 'audioCues.notebookCellFailed',
            legacyAnnouncementSettingsKey: 'accessibility.alert.notebookCellFailed',
            announcementMessage: (0, nls_1.localize)(1460, 'Notebook Cell Failed'),
            settingsKey: 'accessibility.signals.notebookCellFailed',
        }); }
        static { this.diffLineInserted = AccessibilitySignal.register({
            name: (0, nls_1.localize)(1461, 'Diff Line Inserted'),
            sound: Sound.diffLineInserted,
            legacySoundSettingsKey: 'audioCues.diffLineInserted',
            settingsKey: 'accessibility.signals.diffLineInserted',
        }); }
        static { this.diffLineDeleted = AccessibilitySignal.register({
            name: (0, nls_1.localize)(1462, 'Diff Line Deleted'),
            sound: Sound.diffLineDeleted,
            legacySoundSettingsKey: 'audioCues.diffLineDeleted',
            settingsKey: 'accessibility.signals.diffLineDeleted',
        }); }
        static { this.diffLineModified = AccessibilitySignal.register({
            name: (0, nls_1.localize)(1463, 'Diff Line Modified'),
            sound: Sound.diffLineModified,
            legacySoundSettingsKey: 'audioCues.diffLineModified',
            settingsKey: 'accessibility.signals.diffLineModified',
        }); }
        static { this.chatRequestSent = AccessibilitySignal.register({
            name: (0, nls_1.localize)(1464, 'Chat Request Sent'),
            sound: Sound.chatRequestSent,
            legacySoundSettingsKey: 'audioCues.chatRequestSent',
            legacyAnnouncementSettingsKey: 'accessibility.alert.chatRequestSent',
            announcementMessage: (0, nls_1.localize)(1465, 'Chat Request Sent'),
            settingsKey: 'accessibility.signals.chatRequestSent',
        }); }
        static { this.chatResponseReceived = AccessibilitySignal.register({
            name: (0, nls_1.localize)(1466, 'Chat Response Received'),
            legacySoundSettingsKey: 'audioCues.chatResponseReceived',
            sound: {
                randomOneOf: [
                    Sound.chatResponseReceived1,
                    Sound.chatResponseReceived2,
                    Sound.chatResponseReceived3,
                    Sound.chatResponseReceived4
                ]
            },
            settingsKey: 'accessibility.signals.chatResponseReceived'
        }); }
        static { this.progress = AccessibilitySignal.register({
            name: (0, nls_1.localize)(1467, 'Progress'),
            sound: Sound.progress,
            legacySoundSettingsKey: 'audioCues.chatResponsePending',
            legacyAnnouncementSettingsKey: 'accessibility.alert.progress',
            announcementMessage: (0, nls_1.localize)(1468, 'Progress'),
            settingsKey: 'accessibility.signals.progress'
        }); }
        static { this.clear = AccessibilitySignal.register({
            name: (0, nls_1.localize)(1469, 'Clear'),
            sound: Sound.clear,
            legacySoundSettingsKey: 'audioCues.clear',
            legacyAnnouncementSettingsKey: 'accessibility.alert.clear',
            announcementMessage: (0, nls_1.localize)(1470, 'Clear'),
            settingsKey: 'accessibility.signals.clear'
        }); }
        static { this.save = AccessibilitySignal.register({
            name: (0, nls_1.localize)(1471, 'Save'),
            sound: Sound.save,
            legacySoundSettingsKey: 'audioCues.save',
            legacyAnnouncementSettingsKey: 'accessibility.alert.save',
            announcementMessage: (0, nls_1.localize)(1472, 'Save'),
            settingsKey: 'accessibility.signals.save'
        }); }
        static { this.format = AccessibilitySignal.register({
            name: (0, nls_1.localize)(1473, 'Format'),
            sound: Sound.format,
            legacySoundSettingsKey: 'audioCues.format',
            legacyAnnouncementSettingsKey: 'accessibility.alert.format',
            announcementMessage: (0, nls_1.localize)(1474, 'Format'),
            settingsKey: 'accessibility.signals.format'
        }); }
        static { this.voiceRecordingStarted = AccessibilitySignal.register({
            name: (0, nls_1.localize)(1475, 'Voice Recording Started'),
            sound: Sound.voiceRecordingStarted,
            legacySoundSettingsKey: 'audioCues.voiceRecordingStarted',
            settingsKey: 'accessibility.signals.voiceRecordingStarted'
        }); }
        static { this.voiceRecordingStopped = AccessibilitySignal.register({
            name: (0, nls_1.localize)(1476, 'Voice Recording Stopped'),
            sound: Sound.voiceRecordingStopped,
            legacySoundSettingsKey: 'audioCues.voiceRecordingStopped',
            settingsKey: 'accessibility.signals.voiceRecordingStopped'
        }); }
    }
    exports.AccessibilitySignal = AccessibilitySignal;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[117/*vs/platform/clipboard/common/clipboardService*/], __M([1/*require*/,0/*exports*/,7/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.IClipboardService = void 0;
    exports.IClipboardService = (0, instantiation_1.createDecorator)('clipboardService');
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[24/*vs/platform/commands/common/commands*/], __M([1/*require*/,0/*exports*/,6/*vs/base/common/event*/,53/*vs/base/common/iterator*/,2/*vs/base/common/lifecycle*/,73/*vs/base/common/linkedList*/,19/*vs/base/common/types*/,7/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, event_1, iterator_1, lifecycle_1, linkedList_1, types_1, instantiation_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CommandsRegistry = exports.ICommandService = void 0;
    exports.ICommandService = (0, instantiation_1.createDecorator)('commandService');
    exports.CommandsRegistry = new class {
        constructor() {
            this._commands = new Map();
            this._onDidRegisterCommand = new event_1.Emitter();
            this.onDidRegisterCommand = this._onDidRegisterCommand.event;
        }
        registerCommand(idOrCommand, handler) {
            if (!idOrCommand) {
                throw new Error(`invalid command`);
            }
            if (typeof idOrCommand === 'string') {
                if (!handler) {
                    throw new Error(`invalid command`);
                }
                return this.registerCommand({ id: idOrCommand, handler });
            }
            // add argument validation if rich command metadata is provided
            if (idOrCommand.metadata && Array.isArray(idOrCommand.metadata.args)) {
                const constraints = [];
                for (const arg of idOrCommand.metadata.args) {
                    constraints.push(arg.constraint);
                }
                const actualHandler = idOrCommand.handler;
                idOrCommand.handler = function (accessor, ...args) {
                    (0, types_1.validateConstraints)(args, constraints);
                    return actualHandler(accessor, ...args);
                };
            }
            // find a place to store the command
            const { id } = idOrCommand;
            let commands = this._commands.get(id);
            if (!commands) {
                commands = new linkedList_1.LinkedList();
                this._commands.set(id, commands);
            }
            const removeFn = commands.unshift(idOrCommand);
            const ret = (0, lifecycle_1.toDisposable)(() => {
                removeFn();
                const command = this._commands.get(id);
                if (command?.isEmpty()) {
                    this._commands.delete(id);
                }
            });
            // tell the world about this command
            this._onDidRegisterCommand.fire(id);
            return ret;
        }
        registerCommandAlias(oldId, newId) {
            return exports.CommandsRegistry.registerCommand(oldId, (accessor, ...args) => accessor.get(exports.ICommandService).executeCommand(newId, ...args));
        }
        getCommand(id) {
            const list = this._commands.get(id);
            if (!list || list.isEmpty()) {
                return undefined;
            }
            return iterator_1.Iterable.first(list);
        }
        getCommands() {
            const result = new Map();
            for (const key of this._commands.keys()) {
                const command = this.getCommand(key);
                if (command) {
                    result.set(key, command);
                }
            }
            return result;
        }
    };
    exports.CommandsRegistry.registerCommand('noop', () => { });
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[386/*vs/editor/contrib/codelens/browser/codelens*/], __M([1/*require*/,0/*exports*/,18/*vs/base/common/cancellation*/,8/*vs/base/common/errors*/,2/*vs/base/common/lifecycle*/,19/*vs/base/common/types*/,22/*vs/base/common/uri*/,51/*vs/editor/common/services/model*/,24/*vs/platform/commands/common/commands*/,17/*vs/editor/common/services/languageFeatures*/]), function (require, exports, cancellation_1, errors_1, lifecycle_1, types_1, uri_1, model_1, commands_1, languageFeatures_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CodeLensModel = void 0;
    exports.getCodeLensModel = getCodeLensModel;
    class CodeLensModel {
        constructor() {
            this.lenses = [];
            this._disposables = new lifecycle_1.DisposableStore();
        }
        dispose() {
            this._disposables.dispose();
        }
        get isDisposed() {
            return this._disposables.isDisposed;
        }
        add(list, provider) {
            this._disposables.add(list);
            for (const symbol of list.lenses) {
                this.lenses.push({ symbol, provider });
            }
        }
    }
    exports.CodeLensModel = CodeLensModel;
    async function getCodeLensModel(registry, model, token) {
        const provider = registry.ordered(model);
        const providerRanks = new Map();
        const result = new CodeLensModel();
        const promises = provider.map(async (provider, i) => {
            providerRanks.set(provider, i);
            try {
                const list = await Promise.resolve(provider.provideCodeLenses(model, token));
                if (list) {
                    result.add(list, provider);
                }
            }
            catch (err) {
                (0, errors_1.onUnexpectedExternalError)(err);
            }
        });
        await Promise.all(promises);
        result.lenses = result.lenses.sort((a, b) => {
            // sort by lineNumber, provider-rank, and column
            if (a.symbol.range.startLineNumber < b.symbol.range.startLineNumber) {
                return -1;
            }
            else if (a.symbol.range.startLineNumber > b.symbol.range.startLineNumber) {
                return 1;
            }
            else if ((providerRanks.get(a.provider)) < (providerRanks.get(b.provider))) {
                return -1;
            }
            else if ((providerRanks.get(a.provider)) > (providerRanks.get(b.provider))) {
                return 1;
            }
            else if (a.symbol.range.startColumn < b.symbol.range.startColumn) {
                return -1;
            }
            else if (a.symbol.range.startColumn > b.symbol.range.startColumn) {
                return 1;
            }
            else {
                return 0;
            }
        });
        return result;
    }
    commands_1.CommandsRegistry.registerCommand('_executeCodeLensProvider', function (accessor, ...args) {
        let [uri, itemResolveCount] = args;
        (0, types_1.assertType)(uri_1.URI.isUri(uri));
        (0, types_1.assertType)(typeof itemResolveCount === 'number' || !itemResolveCount);
        const { codeLensProvider } = accessor.get(languageFeatures_1.ILanguageFeaturesService);
        const model = accessor.get(model_1.IModelService).getModel(uri);
        if (!model) {
            throw (0, errors_1.illegalArgument)();
        }
        const result = [];
        const disposables = new lifecycle_1.DisposableStore();
        return getCodeLensModel(codeLensProvider, model, cancellation_1.CancellationToken.None).then(value => {
            disposables.add(value);
            const resolve = [];
            for (const item of value.lenses) {
                if (itemResolveCount === undefined || itemResolveCount === null || Boolean(item.symbol.command)) {
                    result.push(item.symbol);
                }
                else if (itemResolveCount-- > 0 && item.provider.resolveCodeLens) {
                    resolve.push(Promise.resolve(item.provider.resolveCodeLens(model, item.symbol, cancellation_1.CancellationToken.None)).then(symbol => result.push(symbol || item.symbol)));
                }
            }
            return Promise.all(resolve);
        }).then(() => {
            return result;
        }).finally(() => {
            // make sure to return results, then (on next tick)
            // dispose the results
            setTimeout(() => disposables.dispose(), 100);
        });
    });
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[681/*vs/editor/contrib/links/browser/getLinks*/], __M([1/*require*/,0/*exports*/,13/*vs/base/common/arrays*/,18/*vs/base/common/cancellation*/,8/*vs/base/common/errors*/,2/*vs/base/common/lifecycle*/,19/*vs/base/common/types*/,22/*vs/base/common/uri*/,4/*vs/editor/common/core/range*/,51/*vs/editor/common/services/model*/,24/*vs/platform/commands/common/commands*/,17/*vs/editor/common/services/languageFeatures*/]), function (require, exports, arrays_1, cancellation_1, errors_1, lifecycle_1, types_1, uri_1, range_1, model_1, commands_1, languageFeatures_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.LinksList = exports.Link = void 0;
    exports.getLinks = getLinks;
    class Link {
        constructor(link, provider) {
            this._link = link;
            this._provider = provider;
        }
        toJSON() {
            return {
                range: this.range,
                url: this.url,
                tooltip: this.tooltip
            };
        }
        get range() {
            return this._link.range;
        }
        get url() {
            return this._link.url;
        }
        get tooltip() {
            return this._link.tooltip;
        }
        async resolve(token) {
            if (this._link.url) {
                return this._link.url;
            }
            if (typeof this._provider.resolveLink === 'function') {
                return Promise.resolve(this._provider.resolveLink(this._link, token)).then(value => {
                    this._link = value || this._link;
                    if (this._link.url) {
                        // recurse
                        return this.resolve(token);
                    }
                    return Promise.reject(new Error('missing'));
                });
            }
            return Promise.reject(new Error('missing'));
        }
    }
    exports.Link = Link;
    class LinksList {
        constructor(tuples) {
            this._disposables = new lifecycle_1.DisposableStore();
            let links = [];
            for (const [list, provider] of tuples) {
                // merge all links
                const newLinks = list.links.map(link => new Link(link, provider));
                links = LinksList._union(links, newLinks);
                // register disposables
                if ((0, lifecycle_1.isDisposable)(list)) {
                    this._disposables.add(list);
                }
            }
            this.links = links;
        }
        dispose() {
            this._disposables.dispose();
            this.links.length = 0;
        }
        static _union(oldLinks, newLinks) {
            // reunite oldLinks with newLinks and remove duplicates
            const result = [];
            let oldIndex;
            let oldLen;
            let newIndex;
            let newLen;
            for (oldIndex = 0, newIndex = 0, oldLen = oldLinks.length, newLen = newLinks.length; oldIndex < oldLen && newIndex < newLen;) {
                const oldLink = oldLinks[oldIndex];
                const newLink = newLinks[newIndex];
                if (range_1.Range.areIntersectingOrTouching(oldLink.range, newLink.range)) {
                    // Remove the oldLink
                    oldIndex++;
                    continue;
                }
                const comparisonResult = range_1.Range.compareRangesUsingStarts(oldLink.range, newLink.range);
                if (comparisonResult < 0) {
                    // oldLink is before
                    result.push(oldLink);
                    oldIndex++;
                }
                else {
                    // newLink is before
                    result.push(newLink);
                    newIndex++;
                }
            }
            for (; oldIndex < oldLen; oldIndex++) {
                result.push(oldLinks[oldIndex]);
            }
            for (; newIndex < newLen; newIndex++) {
                result.push(newLinks[newIndex]);
            }
            return result;
        }
    }
    exports.LinksList = LinksList;
    function getLinks(providers, model, token) {
        const lists = [];
        // ask all providers for links in parallel
        const promises = providers.ordered(model).reverse().map((provider, i) => {
            return Promise.resolve(provider.provideLinks(model, token)).then(result => {
                if (result) {
                    lists[i] = [result, provider];
                }
            }, errors_1.onUnexpectedExternalError);
        });
        return Promise.all(promises).then(() => {
            const result = new LinksList((0, arrays_1.coalesce)(lists));
            if (!token.isCancellationRequested) {
                return result;
            }
            result.dispose();
            return new LinksList([]);
        });
    }
    commands_1.CommandsRegistry.registerCommand('_executeLinkProvider', async (accessor, ...args) => {
        let [uri, resolveCount] = args;
        (0, types_1.assertType)(uri instanceof uri_1.URI);
        if (typeof resolveCount !== 'number') {
            resolveCount = 0;
        }
        const { linkProvider } = accessor.get(languageFeatures_1.ILanguageFeaturesService);
        const model = accessor.get(model_1.IModelService).getModel(uri);
        if (!model) {
            return [];
        }
        const list = await getLinks(linkProvider, model, cancellation_1.CancellationToken.None);
        if (!list) {
            return [];
        }
        // resolve links
        for (let i = 0; i < Math.min(resolveCount, list.links.length); i++) {
            await list.links[i].resolve(cancellation_1.CancellationToken.None);
        }
        const result = list.links.slice(0);
        list.dispose();
        return result;
    });
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[387/*vs/editor/contrib/semanticTokens/common/getSemanticTokens*/], __M([1/*require*/,0/*exports*/,18/*vs/base/common/cancellation*/,8/*vs/base/common/errors*/,22/*vs/base/common/uri*/,51/*vs/editor/common/services/model*/,24/*vs/platform/commands/common/commands*/,19/*vs/base/common/types*/,665/*vs/editor/common/services/semanticTokensDto*/,4/*vs/editor/common/core/range*/,17/*vs/editor/common/services/languageFeatures*/]), function (require, exports, cancellation_1, errors_1, uri_1, model_1, commands_1, types_1, semanticTokensDto_1, range_1, languageFeatures_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DocumentSemanticTokensResult = void 0;
    exports.isSemanticTokens = isSemanticTokens;
    exports.isSemanticTokensEdits = isSemanticTokensEdits;
    exports.hasDocumentSemanticTokensProvider = hasDocumentSemanticTokensProvider;
    exports.getDocumentSemanticTokens = getDocumentSemanticTokens;
    exports.hasDocumentRangeSemanticTokensProvider = hasDocumentRangeSemanticTokensProvider;
    exports.getDocumentRangeSemanticTokens = getDocumentRangeSemanticTokens;
    function isSemanticTokens(v) {
        return v && !!(v.data);
    }
    function isSemanticTokensEdits(v) {
        return v && Array.isArray(v.edits);
    }
    class DocumentSemanticTokensResult {
        constructor(provider, tokens, error) {
            this.provider = provider;
            this.tokens = tokens;
            this.error = error;
        }
    }
    exports.DocumentSemanticTokensResult = DocumentSemanticTokensResult;
    function hasDocumentSemanticTokensProvider(registry, model) {
        return registry.has(model);
    }
    function getDocumentSemanticTokensProviders(registry, model) {
        const groups = registry.orderedGroups(model);
        return (groups.length > 0 ? groups[0] : []);
    }
    async function getDocumentSemanticTokens(registry, model, lastProvider, lastResultId, token) {
        const providers = getDocumentSemanticTokensProviders(registry, model);
        // Get tokens from all providers at the same time.
        const results = await Promise.all(providers.map(async (provider) => {
            let result;
            let error = null;
            try {
                result = await provider.provideDocumentSemanticTokens(model, (provider === lastProvider ? lastResultId : null), token);
            }
            catch (err) {
                error = err;
                result = null;
            }
            if (!result || (!isSemanticTokens(result) && !isSemanticTokensEdits(result))) {
                result = null;
            }
            return new DocumentSemanticTokensResult(provider, result, error);
        }));
        // Try to return the first result with actual tokens or
        // the first result which threw an error (!!)
        for (const result of results) {
            if (result.error) {
                throw result.error;
            }
            if (result.tokens) {
                return result;
            }
        }
        // Return the first result, even if it doesn't have tokens
        if (results.length > 0) {
            return results[0];
        }
        return null;
    }
    function _getDocumentSemanticTokensProviderHighestGroup(registry, model) {
        const result = registry.orderedGroups(model);
        return (result.length > 0 ? result[0] : null);
    }
    class DocumentRangeSemanticTokensResult {
        constructor(provider, tokens) {
            this.provider = provider;
            this.tokens = tokens;
        }
    }
    function hasDocumentRangeSemanticTokensProvider(providers, model) {
        return providers.has(model);
    }
    function getDocumentRangeSemanticTokensProviders(providers, model) {
        const groups = providers.orderedGroups(model);
        return (groups.length > 0 ? groups[0] : []);
    }
    async function getDocumentRangeSemanticTokens(registry, model, range, token) {
        const providers = getDocumentRangeSemanticTokensProviders(registry, model);
        // Get tokens from all providers at the same time.
        const results = await Promise.all(providers.map(async (provider) => {
            let result;
            try {
                result = await provider.provideDocumentRangeSemanticTokens(model, range, token);
            }
            catch (err) {
                (0, errors_1.onUnexpectedExternalError)(err);
                result = null;
            }
            if (!result || !isSemanticTokens(result)) {
                result = null;
            }
            return new DocumentRangeSemanticTokensResult(provider, result);
        }));
        // Try to return the first result with actual tokens
        for (const result of results) {
            if (result.tokens) {
                return result;
            }
        }
        // Return the first result, even if it doesn't have tokens
        if (results.length > 0) {
            return results[0];
        }
        return null;
    }
    commands_1.CommandsRegistry.registerCommand('_provideDocumentSemanticTokensLegend', async (accessor, ...args) => {
        const [uri] = args;
        (0, types_1.assertType)(uri instanceof uri_1.URI);
        const model = accessor.get(model_1.IModelService).getModel(uri);
        if (!model) {
            return undefined;
        }
        const { documentSemanticTokensProvider } = accessor.get(languageFeatures_1.ILanguageFeaturesService);
        const providers = _getDocumentSemanticTokensProviderHighestGroup(documentSemanticTokensProvider, model);
        if (!providers) {
            // there is no provider => fall back to a document range semantic tokens provider
            return accessor.get(commands_1.ICommandService).executeCommand('_provideDocumentRangeSemanticTokensLegend', uri);
        }
        return providers[0].getLegend();
    });
    commands_1.CommandsRegistry.registerCommand('_provideDocumentSemanticTokens', async (accessor, ...args) => {
        const [uri] = args;
        (0, types_1.assertType)(uri instanceof uri_1.URI);
        const model = accessor.get(model_1.IModelService).getModel(uri);
        if (!model) {
            return undefined;
        }
        const { documentSemanticTokensProvider } = accessor.get(languageFeatures_1.ILanguageFeaturesService);
        if (!hasDocumentSemanticTokensProvider(documentSemanticTokensProvider, model)) {
            // there is no provider => fall back to a document range semantic tokens provider
            return accessor.get(commands_1.ICommandService).executeCommand('_provideDocumentRangeSemanticTokens', uri, model.getFullModelRange());
        }
        const r = await getDocumentSemanticTokens(documentSemanticTokensProvider, model, null, null, cancellation_1.CancellationToken.None);
        if (!r) {
            return undefined;
        }
        const { provider, tokens } = r;
        if (!tokens || !isSemanticTokens(tokens)) {
            return undefined;
        }
        const buff = (0, semanticTokensDto_1.encodeSemanticTokensDto)({
            id: 0,
            type: 'full',
            data: tokens.data
        });
        if (tokens.resultId) {
            provider.releaseDocumentSemanticTokens(tokens.resultId);
        }
        return buff;
    });
    commands_1.CommandsRegistry.registerCommand('_provideDocumentRangeSemanticTokensLegend', async (accessor, ...args) => {
        const [uri, range] = args;
        (0, types_1.assertType)(uri instanceof uri_1.URI);
        const model = accessor.get(model_1.IModelService).getModel(uri);
        if (!model) {
            return undefined;
        }
        const { documentRangeSemanticTokensProvider } = accessor.get(languageFeatures_1.ILanguageFeaturesService);
        const providers = getDocumentRangeSemanticTokensProviders(documentRangeSemanticTokensProvider, model);
        if (providers.length === 0) {
            // no providers
            return undefined;
        }
        if (providers.length === 1) {
            // straight forward case, just a single provider
            return providers[0].getLegend();
        }
        if (!range || !range_1.Range.isIRange(range)) {
            // if no range is provided, we cannot support multiple providers
            // as we cannot fall back to the one which would give results
            // => return the first legend for backwards compatibility and print a warning
            console.warn(`provideDocumentRangeSemanticTokensLegend might be out-of-sync with provideDocumentRangeSemanticTokens unless a range argument is passed in`);
            return providers[0].getLegend();
        }
        const result = await getDocumentRangeSemanticTokens(documentRangeSemanticTokensProvider, model, range_1.Range.lift(range), cancellation_1.CancellationToken.None);
        if (!result) {
            return undefined;
        }
        return result.provider.getLegend();
    });
    commands_1.CommandsRegistry.registerCommand('_provideDocumentRangeSemanticTokens', async (accessor, ...args) => {
        const [uri, range] = args;
        (0, types_1.assertType)(uri instanceof uri_1.URI);
        (0, types_1.assertType)(range_1.Range.isIRange(range));
        const model = accessor.get(model_1.IModelService).getModel(uri);
        if (!model) {
            return undefined;
        }
        const { documentRangeSemanticTokensProvider } = accessor.get(languageFeatures_1.ILanguageFeaturesService);
        const result = await getDocumentRangeSemanticTokens(documentRangeSemanticTokensProvider, model, range_1.Range.lift(range), cancellation_1.CancellationToken.None);
        if (!result || !result.tokens) {
            // there is no provider or it didn't return tokens
            return undefined;
        }
        return (0, semanticTokensDto_1.encodeSemanticTokensDto)({
            id: 0,
            type: 'full',
            data: result.tokens.data
        });
    });
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[28/*vs/platform/configuration/common/configuration*/], __M([1/*require*/,0/*exports*/,7/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.IConfigurationService = void 0;
    exports.toValuesTree = toValuesTree;
    exports.addToValueTree = addToValueTree;
    exports.removeFromValueTree = removeFromValueTree;
    exports.getConfigurationValue = getConfigurationValue;
    exports.getLanguageTagSettingPlainKey = getLanguageTagSettingPlainKey;
    exports.IConfigurationService = (0, instantiation_1.createDecorator)('configurationService');
    function toValuesTree(properties, conflictReporter) {
        const root = Object.create(null);
        for (const key in properties) {
            addToValueTree(root, key, properties[key], conflictReporter);
        }
        return root;
    }
    function addToValueTree(settingsTreeRoot, key, value, conflictReporter) {
        const segments = key.split('.');
        const last = segments.pop();
        let curr = settingsTreeRoot;
        for (let i = 0; i < segments.length; i++) {
            const s = segments[i];
            let obj = curr[s];
            switch (typeof obj) {
                case 'undefined':
                    obj = curr[s] = Object.create(null);
                    break;
                case 'object':
                    if (obj === null) {
                        conflictReporter(`Ignoring ${key} as ${segments.slice(0, i + 1).join('.')} is null`);
                        return;
                    }
                    break;
                default:
                    conflictReporter(`Ignoring ${key} as ${segments.slice(0, i + 1).join('.')} is ${JSON.stringify(obj)}`);
                    return;
            }
            curr = obj;
        }
        if (typeof curr === 'object' && curr !== null) {
            try {
                curr[last] = value; // workaround https://github.com/microsoft/vscode/issues/13606
            }
            catch (e) {
                conflictReporter(`Ignoring ${key} as ${segments.join('.')} is ${JSON.stringify(curr)}`);
            }
        }
        else {
            conflictReporter(`Ignoring ${key} as ${segments.join('.')} is ${JSON.stringify(curr)}`);
        }
    }
    function removeFromValueTree(valueTree, key) {
        const segments = key.split('.');
        doRemoveFromValueTree(valueTree, segments);
    }
    function doRemoveFromValueTree(valueTree, segments) {
        const first = segments.shift();
        if (segments.length === 0) {
            // Reached last segment
            delete valueTree[first];
            return;
        }
        if (Object.keys(valueTree).indexOf(first) !== -1) {
            const value = valueTree[first];
            if (typeof value === 'object' && !Array.isArray(value)) {
                doRemoveFromValueTree(value, segments);
                if (Object.keys(value).length === 0) {
                    delete valueTree[first];
                }
            }
        }
    }
    /**
     * A helper function to get the configuration value with a specific settings path (e.g. config.some.setting)
     */
    function getConfigurationValue(config, settingPath, defaultValue) {
        function accessSetting(config, path) {
            let current = config;
            for (const component of path) {
                if (typeof current !== 'object' || current === null) {
                    return undefined;
                }
                current = current[component];
            }
            return current;
        }
        const path = settingPath.split('.');
        const result = accessSetting(config, path);
        return typeof result === 'undefined' ? defaultValue : result;
    }
    function getLanguageTagSettingPlainKey(settingKey) {
        return settingKey.replace(/[\[\]]/g, '');
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[388/*vs/editor/contrib/colorPicker/browser/color*/], __M([1/*require*/,0/*exports*/,18/*vs/base/common/cancellation*/,8/*vs/base/common/errors*/,22/*vs/base/common/uri*/,4/*vs/editor/common/core/range*/,51/*vs/editor/common/services/model*/,24/*vs/platform/commands/common/commands*/,17/*vs/editor/common/services/languageFeatures*/,385/*vs/editor/contrib/colorPicker/browser/defaultDocumentColorProvider*/,28/*vs/platform/configuration/common/configuration*/]), function (require, exports, cancellation_1, errors_1, uri_1, range_1, model_1, commands_1, languageFeatures_1, defaultDocumentColorProvider_1, configuration_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.getColors = getColors;
    exports.getColorPresentations = getColorPresentations;
    async function getColors(colorProviderRegistry, model, token, isDefaultColorDecoratorsEnabled = true) {
        return _findColorData(new ColorDataCollector(), colorProviderRegistry, model, token, isDefaultColorDecoratorsEnabled);
    }
    function getColorPresentations(model, colorInfo, provider, token) {
        return Promise.resolve(provider.provideColorPresentations(model, colorInfo, token));
    }
    class ColorDataCollector {
        constructor() { }
        async compute(provider, model, token, colors) {
            const documentColors = await provider.provideDocumentColors(model, token);
            if (Array.isArray(documentColors)) {
                for (const colorInfo of documentColors) {
                    colors.push({ colorInfo, provider });
                }
            }
            return Array.isArray(documentColors);
        }
    }
    class ExtColorDataCollector {
        constructor() { }
        async compute(provider, model, token, colors) {
            const documentColors = await provider.provideDocumentColors(model, token);
            if (Array.isArray(documentColors)) {
                for (const colorInfo of documentColors) {
                    colors.push({ range: colorInfo.range, color: [colorInfo.color.red, colorInfo.color.green, colorInfo.color.blue, colorInfo.color.alpha] });
                }
            }
            return Array.isArray(documentColors);
        }
    }
    class ColorPresentationsCollector {
        constructor(colorInfo) {
            this.colorInfo = colorInfo;
        }
        async compute(provider, model, _token, colors) {
            const documentColors = await provider.provideColorPresentations(model, this.colorInfo, cancellation_1.CancellationToken.None);
            if (Array.isArray(documentColors)) {
                colors.push(...documentColors);
            }
            return Array.isArray(documentColors);
        }
    }
    async function _findColorData(collector, colorProviderRegistry, model, token, isDefaultColorDecoratorsEnabled) {
        let validDocumentColorProviderFound = false;
        let defaultProvider;
        const colorData = [];
        const documentColorProviders = colorProviderRegistry.ordered(model);
        for (let i = documentColorProviders.length - 1; i >= 0; i--) {
            const provider = documentColorProviders[i];
            if (provider instanceof defaultDocumentColorProvider_1.DefaultDocumentColorProvider) {
                defaultProvider = provider;
            }
            else {
                try {
                    if (await collector.compute(provider, model, token, colorData)) {
                        validDocumentColorProviderFound = true;
                    }
                }
                catch (e) {
                    (0, errors_1.onUnexpectedExternalError)(e);
                }
            }
        }
        if (validDocumentColorProviderFound) {
            return colorData;
        }
        if (defaultProvider && isDefaultColorDecoratorsEnabled) {
            await collector.compute(defaultProvider, model, token, colorData);
            return colorData;
        }
        return [];
    }
    function _setupColorCommand(accessor, resource) {
        const { colorProvider: colorProviderRegistry } = accessor.get(languageFeatures_1.ILanguageFeaturesService);
        const model = accessor.get(model_1.IModelService).getModel(resource);
        if (!model) {
            throw (0, errors_1.illegalArgument)();
        }
        const isDefaultColorDecoratorsEnabled = accessor.get(configuration_1.IConfigurationService).getValue('editor.defaultColorDecorators', { resource });
        return { model, colorProviderRegistry, isDefaultColorDecoratorsEnabled };
    }
    commands_1.CommandsRegistry.registerCommand('_executeDocumentColorProvider', function (accessor, ...args) {
        const [resource] = args;
        if (!(resource instanceof uri_1.URI)) {
            throw (0, errors_1.illegalArgument)();
        }
        const { model, colorProviderRegistry, isDefaultColorDecoratorsEnabled } = _setupColorCommand(accessor, resource);
        return _findColorData(new ExtColorDataCollector(), colorProviderRegistry, model, cancellation_1.CancellationToken.None, isDefaultColorDecoratorsEnabled);
    });
    commands_1.CommandsRegistry.registerCommand('_executeColorPresentationProvider', function (accessor, ...args) {
        const [color, context] = args;
        const { uri, range } = context;
        if (!(uri instanceof uri_1.URI) || !Array.isArray(color) || color.length !== 4 || !range_1.Range.isIRange(range)) {
            throw (0, errors_1.illegalArgument)();
        }
        const { model, colorProviderRegistry, isDefaultColorDecoratorsEnabled } = _setupColorCommand(accessor, uri);
        const [red, green, blue, alpha] = color;
        return _findColorData(new ColorPresentationsCollector({ range: range, color: { red, green, blue, alpha } }), colorProviderRegistry, model, cancellation_1.CancellationToken.None, isDefaultColorDecoratorsEnabled);
    });
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[389/*vs/editor/standalone/common/monarch/monarchLexer*/], __M([1/*require*/,0/*exports*/,2/*vs/base/common/lifecycle*/,27/*vs/editor/common/languages*/,177/*vs/editor/common/languages/nullTokenize*/,344/*vs/editor/standalone/common/monarch/monarchCommon*/,28/*vs/platform/configuration/common/configuration*/]), function (require, exports, lifecycle_1, languages, nullTokenize_1, monarchCommon, configuration_1) {
    "use strict";
    var MonarchTokenizer_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MonarchTokenizer = void 0;
    const CACHE_STACK_DEPTH = 5;
    /**
     * Reuse the same stack elements up to a certain depth.
     */
    class MonarchStackElementFactory {
        static { this._INSTANCE = new MonarchStackElementFactory(CACHE_STACK_DEPTH); }
        static create(parent, state) {
            return this._INSTANCE.create(parent, state);
        }
        constructor(maxCacheDepth) {
            this._maxCacheDepth = maxCacheDepth;
            this._entries = Object.create(null);
        }
        create(parent, state) {
            if (parent !== null && parent.depth >= this._maxCacheDepth) {
                // no caching above a certain depth
                return new MonarchStackElement(parent, state);
            }
            let stackElementId = MonarchStackElement.getStackElementId(parent);
            if (stackElementId.length > 0) {
                stackElementId += '|';
            }
            stackElementId += state;
            let result = this._entries[stackElementId];
            if (result) {
                return result;
            }
            result = new MonarchStackElement(parent, state);
            this._entries[stackElementId] = result;
            return result;
        }
    }
    class MonarchStackElement {
        constructor(parent, state) {
            this.parent = parent;
            this.state = state;
            this.depth = (this.parent ? this.parent.depth : 0) + 1;
        }
        static getStackElementId(element) {
            let result = '';
            while (element !== null) {
                if (result.length > 0) {
                    result += '|';
                }
                result += element.state;
                element = element.parent;
            }
            return result;
        }
        static _equals(a, b) {
            while (a !== null && b !== null) {
                if (a === b) {
                    return true;
                }
                if (a.state !== b.state) {
                    return false;
                }
                a = a.parent;
                b = b.parent;
            }
            if (a === null && b === null) {
                return true;
            }
            return false;
        }
        equals(other) {
            return MonarchStackElement._equals(this, other);
        }
        push(state) {
            return MonarchStackElementFactory.create(this, state);
        }
        pop() {
            return this.parent;
        }
        popall() {
            let result = this;
            while (result.parent) {
                result = result.parent;
            }
            return result;
        }
        switchTo(state) {
            return MonarchStackElementFactory.create(this.parent, state);
        }
    }
    class EmbeddedLanguageData {
        constructor(languageId, state) {
            this.languageId = languageId;
            this.state = state;
        }
        equals(other) {
            return (this.languageId === other.languageId
                && this.state.equals(other.state));
        }
        clone() {
            const stateClone = this.state.clone();
            // save an object
            if (stateClone === this.state) {
                return this;
            }
            return new EmbeddedLanguageData(this.languageId, this.state);
        }
    }
    /**
     * Reuse the same line states up to a certain depth.
     */
    class MonarchLineStateFactory {
        static { this._INSTANCE = new MonarchLineStateFactory(CACHE_STACK_DEPTH); }
        static create(stack, embeddedLanguageData) {
            return this._INSTANCE.create(stack, embeddedLanguageData);
        }
        constructor(maxCacheDepth) {
            this._maxCacheDepth = maxCacheDepth;
            this._entries = Object.create(null);
        }
        create(stack, embeddedLanguageData) {
            if (embeddedLanguageData !== null) {
                // no caching when embedding
                return new MonarchLineState(stack, embeddedLanguageData);
            }
            if (stack !== null && stack.depth >= this._maxCacheDepth) {
                // no caching above a certain depth
                return new MonarchLineState(stack, embeddedLanguageData);
            }
            const stackElementId = MonarchStackElement.getStackElementId(stack);
            let result = this._entries[stackElementId];
            if (result) {
                return result;
            }
            result = new MonarchLineState(stack, null);
            this._entries[stackElementId] = result;
            return result;
        }
    }
    class MonarchLineState {
        constructor(stack, embeddedLanguageData) {
            this.stack = stack;
            this.embeddedLanguageData = embeddedLanguageData;
        }
        clone() {
            const embeddedlanguageDataClone = this.embeddedLanguageData ? this.embeddedLanguageData.clone() : null;
            // save an object
            if (embeddedlanguageDataClone === this.embeddedLanguageData) {
                return this;
            }
            return MonarchLineStateFactory.create(this.stack, this.embeddedLanguageData);
        }
        equals(other) {
            if (!(other instanceof MonarchLineState)) {
                return false;
            }
            if (!this.stack.equals(other.stack)) {
                return false;
            }
            if (this.embeddedLanguageData === null && other.embeddedLanguageData === null) {
                return true;
            }
            if (this.embeddedLanguageData === null || other.embeddedLanguageData === null) {
                return false;
            }
            return this.embeddedLanguageData.equals(other.embeddedLanguageData);
        }
    }
    class MonarchClassicTokensCollector {
        constructor() {
            this._tokens = [];
            this._languageId = null;
            this._lastTokenType = null;
            this._lastTokenLanguage = null;
        }
        enterLanguage(languageId) {
            this._languageId = languageId;
        }
        emit(startOffset, type) {
            if (this._lastTokenType === type && this._lastTokenLanguage === this._languageId) {
                return;
            }
            this._lastTokenType = type;
            this._lastTokenLanguage = this._languageId;
            this._tokens.push(new languages.Token(startOffset, type, this._languageId));
        }
        nestedLanguageTokenize(embeddedLanguageLine, hasEOL, embeddedLanguageData, offsetDelta) {
            const nestedLanguageId = embeddedLanguageData.languageId;
            const embeddedModeState = embeddedLanguageData.state;
            const nestedLanguageTokenizationSupport = languages.TokenizationRegistry.get(nestedLanguageId);
            if (!nestedLanguageTokenizationSupport) {
                this.enterLanguage(nestedLanguageId);
                this.emit(offsetDelta, '');
                return embeddedModeState;
            }
            const nestedResult = nestedLanguageTokenizationSupport.tokenize(embeddedLanguageLine, hasEOL, embeddedModeState);
            if (offsetDelta !== 0) {
                for (const token of nestedResult.tokens) {
                    this._tokens.push(new languages.Token(token.offset + offsetDelta, token.type, token.language));
                }
            }
            else {
                this._tokens = this._tokens.concat(nestedResult.tokens);
            }
            this._lastTokenType = null;
            this._lastTokenLanguage = null;
            this._languageId = null;
            return nestedResult.endState;
        }
        finalize(endState) {
            return new languages.TokenizationResult(this._tokens, endState);
        }
    }
    class MonarchModernTokensCollector {
        constructor(languageService, theme) {
            this._languageService = languageService;
            this._theme = theme;
            this._prependTokens = null;
            this._tokens = [];
            this._currentLanguageId = 0 /* LanguageId.Null */;
            this._lastTokenMetadata = 0;
        }
        enterLanguage(languageId) {
            this._currentLanguageId = this._languageService.languageIdCodec.encodeLanguageId(languageId);
        }
        emit(startOffset, type) {
            const metadata = this._theme.match(this._currentLanguageId, type) | 1024 /* MetadataConsts.BALANCED_BRACKETS_MASK */;
            if (this._lastTokenMetadata === metadata) {
                return;
            }
            this._lastTokenMetadata = metadata;
            this._tokens.push(startOffset);
            this._tokens.push(metadata);
        }
        static _merge(a, b, c) {
            const aLen = (a !== null ? a.length : 0);
            const bLen = b.length;
            const cLen = (c !== null ? c.length : 0);
            if (aLen === 0 && bLen === 0 && cLen === 0) {
                return new Uint32Array(0);
            }
            if (aLen === 0 && bLen === 0) {
                return c;
            }
            if (bLen === 0 && cLen === 0) {
                return a;
            }
            const result = new Uint32Array(aLen + bLen + cLen);
            if (a !== null) {
                result.set(a);
            }
            for (let i = 0; i < bLen; i++) {
                result[aLen + i] = b[i];
            }
            if (c !== null) {
                result.set(c, aLen + bLen);
            }
            return result;
        }
        nestedLanguageTokenize(embeddedLanguageLine, hasEOL, embeddedLanguageData, offsetDelta) {
            const nestedLanguageId = embeddedLanguageData.languageId;
            const embeddedModeState = embeddedLanguageData.state;
            const nestedLanguageTokenizationSupport = languages.TokenizationRegistry.get(nestedLanguageId);
            if (!nestedLanguageTokenizationSupport) {
                this.enterLanguage(nestedLanguageId);
                this.emit(offsetDelta, '');
                return embeddedModeState;
            }
            const nestedResult = nestedLanguageTokenizationSupport.tokenizeEncoded(embeddedLanguageLine, hasEOL, embeddedModeState);
            if (offsetDelta !== 0) {
                for (let i = 0, len = nestedResult.tokens.length; i < len; i += 2) {
                    nestedResult.tokens[i] += offsetDelta;
                }
            }
            this._prependTokens = MonarchModernTokensCollector._merge(this._prependTokens, this._tokens, nestedResult.tokens);
            this._tokens = [];
            this._currentLanguageId = 0;
            this._lastTokenMetadata = 0;
            return nestedResult.endState;
        }
        finalize(endState) {
            return new languages.EncodedTokenizationResult(MonarchModernTokensCollector._merge(this._prependTokens, this._tokens, null), endState);
        }
    }
    let MonarchTokenizer = MonarchTokenizer_1 = class MonarchTokenizer extends lifecycle_1.Disposable {
        constructor(languageService, standaloneThemeService, languageId, lexer, _configurationService) {
            super();
            this._configurationService = _configurationService;
            this._languageService = languageService;
            this._standaloneThemeService = standaloneThemeService;
            this._languageId = languageId;
            this._lexer = lexer;
            this._embeddedLanguages = Object.create(null);
            this.embeddedLoaded = Promise.resolve(undefined);
            // Set up listening for embedded modes
            let emitting = false;
            this._register(languages.TokenizationRegistry.onDidChange((e) => {
                if (emitting) {
                    return;
                }
                let isOneOfMyEmbeddedModes = false;
                for (let i = 0, len = e.changedLanguages.length; i < len; i++) {
                    const language = e.changedLanguages[i];
                    if (this._embeddedLanguages[language]) {
                        isOneOfMyEmbeddedModes = true;
                        break;
                    }
                }
                if (isOneOfMyEmbeddedModes) {
                    emitting = true;
                    languages.TokenizationRegistry.handleChange([this._languageId]);
                    emitting = false;
                }
            }));
            this._maxTokenizationLineLength = this._configurationService.getValue('editor.maxTokenizationLineLength', {
                overrideIdentifier: this._languageId
            });
            this._register(this._configurationService.onDidChangeConfiguration(e => {
                if (e.affectsConfiguration('editor.maxTokenizationLineLength')) {
                    this._maxTokenizationLineLength = this._configurationService.getValue('editor.maxTokenizationLineLength', {
                        overrideIdentifier: this._languageId
                    });
                }
            }));
        }
        getLoadStatus() {
            const promises = [];
            for (const nestedLanguageId in this._embeddedLanguages) {
                const tokenizationSupport = languages.TokenizationRegistry.get(nestedLanguageId);
                if (tokenizationSupport) {
                    // The nested language is already loaded
                    if (tokenizationSupport instanceof MonarchTokenizer_1) {
                        const nestedModeStatus = tokenizationSupport.getLoadStatus();
                        if (nestedModeStatus.loaded === false) {
                            promises.push(nestedModeStatus.promise);
                        }
                    }
                    continue;
                }
                if (!languages.TokenizationRegistry.isResolved(nestedLanguageId)) {
                    // The nested language is in the process of being loaded
                    promises.push(languages.TokenizationRegistry.getOrCreate(nestedLanguageId));
                }
            }
            if (promises.length === 0) {
                return {
                    loaded: true
                };
            }
            return {
                loaded: false,
                promise: Promise.all(promises).then(_ => undefined)
            };
        }
        getInitialState() {
            const rootState = MonarchStackElementFactory.create(null, this._lexer.start);
            return MonarchLineStateFactory.create(rootState, null);
        }
        tokenize(line, hasEOL, lineState) {
            if (line.length >= this._maxTokenizationLineLength) {
                return (0, nullTokenize_1.nullTokenize)(this._languageId, lineState);
            }
            const tokensCollector = new MonarchClassicTokensCollector();
            const endLineState = this._tokenize(line, hasEOL, lineState, tokensCollector);
            return tokensCollector.finalize(endLineState);
        }
        tokenizeEncoded(line, hasEOL, lineState) {
            if (line.length >= this._maxTokenizationLineLength) {
                return (0, nullTokenize_1.nullTokenizeEncoded)(this._languageService.languageIdCodec.encodeLanguageId(this._languageId), lineState);
            }
            const tokensCollector = new MonarchModernTokensCollector(this._languageService, this._standaloneThemeService.getColorTheme().tokenTheme);
            const endLineState = this._tokenize(line, hasEOL, lineState, tokensCollector);
            return tokensCollector.finalize(endLineState);
        }
        _tokenize(line, hasEOL, lineState, collector) {
            if (lineState.embeddedLanguageData) {
                return this._nestedTokenize(line, hasEOL, lineState, 0, collector);
            }
            else {
                return this._myTokenize(line, hasEOL, lineState, 0, collector);
            }
        }
        _findLeavingNestedLanguageOffset(line, state) {
            let rules = this._lexer.tokenizer[state.stack.state];
            if (!rules) {
                rules = monarchCommon.findRules(this._lexer, state.stack.state); // do parent matching
                if (!rules) {
                    throw monarchCommon.createError(this._lexer, 'tokenizer state is not defined: ' + state.stack.state);
                }
            }
            let popOffset = -1;
            let hasEmbeddedPopRule = false;
            for (const rule of rules) {
                if (!monarchCommon.isIAction(rule.action) || rule.action.nextEmbedded !== '@pop') {
                    continue;
                }
                hasEmbeddedPopRule = true;
                let regex = rule.resolveRegex(state.stack.state);
                const regexSource = regex.source;
                if (regexSource.substr(0, 4) === '^(?:' && regexSource.substr(regexSource.length - 1, 1) === ')') {
                    const flags = (regex.ignoreCase ? 'i' : '') + (regex.unicode ? 'u' : '');
                    regex = new RegExp(regexSource.substr(4, regexSource.length - 5), flags);
                }
                const result = line.search(regex);
                if (result === -1 || (result !== 0 && rule.matchOnlyAtLineStart)) {
                    continue;
                }
                if (popOffset === -1 || result < popOffset) {
                    popOffset = result;
                }
            }
            if (!hasEmbeddedPopRule) {
                throw monarchCommon.createError(this._lexer, 'no rule containing nextEmbedded: "@pop" in tokenizer embedded state: ' + state.stack.state);
            }
            return popOffset;
        }
        _nestedTokenize(line, hasEOL, lineState, offsetDelta, tokensCollector) {
            const popOffset = this._findLeavingNestedLanguageOffset(line, lineState);
            if (popOffset === -1) {
                // tokenization will not leave nested language
                const nestedEndState = tokensCollector.nestedLanguageTokenize(line, hasEOL, lineState.embeddedLanguageData, offsetDelta);
                return MonarchLineStateFactory.create(lineState.stack, new EmbeddedLanguageData(lineState.embeddedLanguageData.languageId, nestedEndState));
            }
            const nestedLanguageLine = line.substring(0, popOffset);
            if (nestedLanguageLine.length > 0) {
                // tokenize with the nested language
                tokensCollector.nestedLanguageTokenize(nestedLanguageLine, false, lineState.embeddedLanguageData, offsetDelta);
            }
            const restOfTheLine = line.substring(popOffset);
            return this._myTokenize(restOfTheLine, hasEOL, lineState, offsetDelta + popOffset, tokensCollector);
        }
        _safeRuleName(rule) {
            if (rule) {
                return rule.name;
            }
            return '(unknown)';
        }
        _myTokenize(lineWithoutLF, hasEOL, lineState, offsetDelta, tokensCollector) {
            tokensCollector.enterLanguage(this._languageId);
            const lineWithoutLFLength = lineWithoutLF.length;
            const line = (hasEOL && this._lexer.includeLF ? lineWithoutLF + '\n' : lineWithoutLF);
            const lineLength = line.length;
            let embeddedLanguageData = lineState.embeddedLanguageData;
            let stack = lineState.stack;
            let pos = 0;
            let groupMatching = null;
            // See https://github.com/microsoft/monaco-editor/issues/1235
            // Evaluate rules at least once for an empty line
            let forceEvaluation = true;
            while (forceEvaluation || pos < lineLength) {
                const pos0 = pos;
                const stackLen0 = stack.depth;
                const groupLen0 = groupMatching ? groupMatching.groups.length : 0;
                const state = stack.state;
                let matches = null;
                let matched = null;
                let action = null;
                let rule = null;
                let enteringEmbeddedLanguage = null;
                // check if we need to process group matches first
                if (groupMatching) {
                    matches = groupMatching.matches;
                    const groupEntry = groupMatching.groups.shift();
                    matched = groupEntry.matched;
                    action = groupEntry.action;
                    rule = groupMatching.rule;
                    // cleanup if necessary
                    if (groupMatching.groups.length === 0) {
                        groupMatching = null;
                    }
                }
                else {
                    // otherwise we match on the token stream
                    if (!forceEvaluation && pos >= lineLength) {
                        // nothing to do
                        break;
                    }
                    forceEvaluation = false;
                    // get the rules for this state
                    let rules = this._lexer.tokenizer[state];
                    if (!rules) {
                        rules = monarchCommon.findRules(this._lexer, state); // do parent matching
                        if (!rules) {
                            throw monarchCommon.createError(this._lexer, 'tokenizer state is not defined: ' + state);
                        }
                    }
                    // try each rule until we match
                    const restOfLine = line.substr(pos);
                    for (const rule of rules) {
                        if (pos === 0 || !rule.matchOnlyAtLineStart) {
                            matches = restOfLine.match(rule.resolveRegex(state));
                            if (matches) {
                                matched = matches[0];
                                action = rule.action;
                                break;
                            }
                        }
                    }
                }
                // We matched 'rule' with 'matches' and 'action'
                if (!matches) {
                    matches = [''];
                    matched = '';
                }
                if (!action) {
                    // bad: we didn't match anything, and there is no action to take
                    // we need to advance the stream or we get progress trouble
                    if (pos < lineLength) {
                        matches = [line.charAt(pos)];
                        matched = matches[0];
                    }
                    action = this._lexer.defaultToken;
                }
                if (matched === null) {
                    // should never happen, needed for strict null checking
                    break;
                }
                // advance stream
                pos += matched.length;
                // maybe call action function (used for 'cases')
                while (monarchCommon.isFuzzyAction(action) && monarchCommon.isIAction(action) && action.test) {
                    action = action.test(matched, matches, state, pos === lineLength);
                }
                let result = null;
                // set the result: either a string or an array of actions
                if (typeof action === 'string' || Array.isArray(action)) {
                    result = action;
                }
                else if (action.group) {
                    result = action.group;
                }
                else if (action.token !== null && action.token !== undefined) {
                    // do $n replacements?
                    if (action.tokenSubst) {
                        result = monarchCommon.substituteMatches(this._lexer, action.token, matched, matches, state);
                    }
                    else {
                        result = action.token;
                    }
                    // enter embedded language?
                    if (action.nextEmbedded) {
                        if (action.nextEmbedded === '@pop') {
                            if (!embeddedLanguageData) {
                                throw monarchCommon.createError(this._lexer, 'cannot pop embedded language if not inside one');
                            }
                            embeddedLanguageData = null;
                        }
                        else if (embeddedLanguageData) {
                            throw monarchCommon.createError(this._lexer, 'cannot enter embedded language from within an embedded language');
                        }
                        else {
                            enteringEmbeddedLanguage = monarchCommon.substituteMatches(this._lexer, action.nextEmbedded, matched, matches, state);
                        }
                    }
                    // state transformations
                    if (action.goBack) { // back up the stream..
                        pos = Math.max(0, pos - action.goBack);
                    }
                    if (action.switchTo && typeof action.switchTo === 'string') {
                        let nextState = monarchCommon.substituteMatches(this._lexer, action.switchTo, matched, matches, state); // switch state without a push...
                        if (nextState[0] === '@') {
                            nextState = nextState.substr(1); // peel off starting '@'
                        }
                        if (!monarchCommon.findRules(this._lexer, nextState)) {
                            throw monarchCommon.createError(this._lexer, 'trying to switch to a state \'' + nextState + '\' that is undefined in rule: ' + this._safeRuleName(rule));
                        }
                        else {
                            stack = stack.switchTo(nextState);
                        }
                    }
                    else if (action.transform && typeof action.transform === 'function') {
                        throw monarchCommon.createError(this._lexer, 'action.transform not supported');
                    }
                    else if (action.next) {
                        if (action.next === '@push') {
                            if (stack.depth >= this._lexer.maxStack) {
                                throw monarchCommon.createError(this._lexer, 'maximum tokenizer stack size reached: [' +
                                    stack.state + ',' + stack.parent.state + ',...]');
                            }
                            else {
                                stack = stack.push(state);
                            }
                        }
                        else if (action.next === '@pop') {
                            if (stack.depth <= 1) {
                                throw monarchCommon.createError(this._lexer, 'trying to pop an empty stack in rule: ' + this._safeRuleName(rule));
                            }
                            else {
                                stack = stack.pop();
                            }
                        }
                        else if (action.next === '@popall') {
                            stack = stack.popall();
                        }
                        else {
                            let nextState = monarchCommon.substituteMatches(this._lexer, action.next, matched, matches, state);
                            if (nextState[0] === '@') {
                                nextState = nextState.substr(1); // peel off starting '@'
                            }
                            if (!monarchCommon.findRules(this._lexer, nextState)) {
                                throw monarchCommon.createError(this._lexer, 'trying to set a next state \'' + nextState + '\' that is undefined in rule: ' + this._safeRuleName(rule));
                            }
                            else {
                                stack = stack.push(nextState);
                            }
                        }
                    }
                    if (action.log && typeof (action.log) === 'string') {
                        monarchCommon.log(this._lexer, this._lexer.languageId + ': ' + monarchCommon.substituteMatches(this._lexer, action.log, matched, matches, state));
                    }
                }
                // check result
                if (result === null) {
                    throw monarchCommon.createError(this._lexer, 'lexer rule has no well-defined action in rule: ' + this._safeRuleName(rule));
                }
                const computeNewStateForEmbeddedLanguage = (enteringEmbeddedLanguage) => {
                    // support language names, mime types, and language ids
                    const languageId = (this._languageService.getLanguageIdByLanguageName(enteringEmbeddedLanguage)
                        || this._languageService.getLanguageIdByMimeType(enteringEmbeddedLanguage)
                        || enteringEmbeddedLanguage);
                    const embeddedLanguageData = this._getNestedEmbeddedLanguageData(languageId);
                    if (pos < lineLength) {
                        // there is content from the embedded language on this line
                        const restOfLine = lineWithoutLF.substr(pos);
                        return this._nestedTokenize(restOfLine, hasEOL, MonarchLineStateFactory.create(stack, embeddedLanguageData), offsetDelta + pos, tokensCollector);
                    }
                    else {
                        return MonarchLineStateFactory.create(stack, embeddedLanguageData);
                    }
                };
                // is the result a group match?
                if (Array.isArray(result)) {
                    if (groupMatching && groupMatching.groups.length > 0) {
                        throw monarchCommon.createError(this._lexer, 'groups cannot be nested: ' + this._safeRuleName(rule));
                    }
                    if (matches.length !== result.length + 1) {
                        throw monarchCommon.createError(this._lexer, 'matched number of groups does not match the number of actions in rule: ' + this._safeRuleName(rule));
                    }
                    let totalLen = 0;
                    for (let i = 1; i < matches.length; i++) {
                        totalLen += matches[i].length;
                    }
                    if (totalLen !== matched.length) {
                        throw monarchCommon.createError(this._lexer, 'with groups, all characters should be matched in consecutive groups in rule: ' + this._safeRuleName(rule));
                    }
                    groupMatching = {
                        rule: rule,
                        matches: matches,
                        groups: []
                    };
                    for (let i = 0; i < result.length; i++) {
                        groupMatching.groups[i] = {
                            action: result[i],
                            matched: matches[i + 1]
                        };
                    }
                    pos -= matched.length;
                    // call recursively to initiate first result match
                    continue;
                }
                else {
                    // regular result
                    // check for '@rematch'
                    if (result === '@rematch') {
                        pos -= matched.length;
                        matched = ''; // better set the next state too..
                        matches = null;
                        result = '';
                        // Even though `@rematch` was specified, if `nextEmbedded` also specified,
                        // a state transition should occur.
                        if (enteringEmbeddedLanguage !== null) {
                            return computeNewStateForEmbeddedLanguage(enteringEmbeddedLanguage);
                        }
                    }
                    // check progress
                    if (matched.length === 0) {
                        if (lineLength === 0 || stackLen0 !== stack.depth || state !== stack.state || (!groupMatching ? 0 : groupMatching.groups.length) !== groupLen0) {
                            continue;
                        }
                        else {
                            throw monarchCommon.createError(this._lexer, 'no progress in tokenizer in rule: ' + this._safeRuleName(rule));
                        }
                    }
                    // return the result (and check for brace matching)
                    // todo: for efficiency we could pre-sanitize tokenPostfix and substitutions
                    let tokenType = null;
                    if (monarchCommon.isString(result) && result.indexOf('@brackets') === 0) {
                        const rest = result.substr('@brackets'.length);
                        const bracket = findBracket(this._lexer, matched);
                        if (!bracket) {
                            throw monarchCommon.createError(this._lexer, '@brackets token returned but no bracket defined as: ' + matched);
                        }
                        tokenType = monarchCommon.sanitize(bracket.token + rest);
                    }
                    else {
                        const token = (result === '' ? '' : result + this._lexer.tokenPostfix);
                        tokenType = monarchCommon.sanitize(token);
                    }
                    if (pos0 < lineWithoutLFLength) {
                        tokensCollector.emit(pos0 + offsetDelta, tokenType);
                    }
                }
                if (enteringEmbeddedLanguage !== null) {
                    return computeNewStateForEmbeddedLanguage(enteringEmbeddedLanguage);
                }
            }
            return MonarchLineStateFactory.create(stack, embeddedLanguageData);
        }
        _getNestedEmbeddedLanguageData(languageId) {
            if (!this._languageService.isRegisteredLanguageId(languageId)) {
                return new EmbeddedLanguageData(languageId, nullTokenize_1.NullState);
            }
            if (languageId !== this._languageId) {
                // Fire language loading event
                this._languageService.requestBasicLanguageFeatures(languageId);
                languages.TokenizationRegistry.getOrCreate(languageId);
                this._embeddedLanguages[languageId] = true;
            }
            const tokenizationSupport = languages.TokenizationRegistry.get(languageId);
            if (tokenizationSupport) {
                return new EmbeddedLanguageData(languageId, tokenizationSupport.getInitialState());
            }
            return new EmbeddedLanguageData(languageId, nullTokenize_1.NullState);
        }
    };
    exports.MonarchTokenizer = MonarchTokenizer;
    exports.MonarchTokenizer = MonarchTokenizer = MonarchTokenizer_1 = __decorate([
        __param(4, configuration_1.IConfigurationService)
    ], MonarchTokenizer);
    /**
     * Searches for a bracket in the 'brackets' attribute that matches the input.
     */
    function findBracket(lexer, matched) {
        if (!matched) {
            return null;
        }
        matched = monarchCommon.fixCase(lexer, matched);
        const brackets = lexer.brackets;
        for (const bracket of brackets) {
            if (bracket.open === matched) {
                return { token: bracket.token, bracketType: 1 /* monarchCommon.MonarchBracket.Open */ };
            }
            else if (bracket.close === matched) {
                return { token: bracket.token, bracketType: -1 /* monarchCommon.MonarchBracket.Close */ };
            }
        }
        return null;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[682/*vs/editor/standalone/browser/colorizer*/], __M([1/*require*/,0/*exports*/,103/*vs/base/browser/trustedTypes*/,11/*vs/base/common/strings*/,27/*vs/editor/common/languages*/,83/*vs/editor/common/tokens/lineTokens*/,136/*vs/editor/common/viewLayout/viewLineRenderer*/,95/*vs/editor/common/viewModel*/,389/*vs/editor/standalone/common/monarch/monarchLexer*/]), function (require, exports, trustedTypes_1, strings, languages_1, lineTokens_1, viewLineRenderer_1, viewModel_1, monarchLexer_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Colorizer = void 0;
    const ttPolicy = (0, trustedTypes_1.createTrustedTypesPolicy)('standaloneColorizer', { createHTML: value => value });
    class Colorizer {
        static colorizeElement(themeService, languageService, domNode, options) {
            options = options || {};
            const theme = options.theme || 'vs';
            const mimeType = options.mimeType || domNode.getAttribute('lang') || domNode.getAttribute('data-lang');
            if (!mimeType) {
                console.error('Mode not detected');
                return Promise.resolve();
            }
            const languageId = languageService.getLanguageIdByMimeType(mimeType) || mimeType;
            themeService.setTheme(theme);
            const text = domNode.firstChild ? domNode.firstChild.nodeValue : '';
            domNode.className += ' ' + theme;
            const render = (str) => {
                const trustedhtml = ttPolicy?.createHTML(str) ?? str;
                domNode.innerHTML = trustedhtml;
            };
            return this.colorize(languageService, text || '', languageId, options).then(render, (err) => console.error(err));
        }
        static async colorize(languageService, text, languageId, options) {
            const languageIdCodec = languageService.languageIdCodec;
            let tabSize = 4;
            if (options && typeof options.tabSize === 'number') {
                tabSize = options.tabSize;
            }
            if (strings.startsWithUTF8BOM(text)) {
                text = text.substr(1);
            }
            const lines = strings.splitLines(text);
            if (!languageService.isRegisteredLanguageId(languageId)) {
                return _fakeColorize(lines, tabSize, languageIdCodec);
            }
            const tokenizationSupport = await languages_1.TokenizationRegistry.getOrCreate(languageId);
            if (tokenizationSupport) {
                return _colorize(lines, tabSize, tokenizationSupport, languageIdCodec);
            }
            return _fakeColorize(lines, tabSize, languageIdCodec);
        }
        static colorizeLine(line, mightContainNonBasicASCII, mightContainRTL, tokens, tabSize = 4) {
            const isBasicASCII = viewModel_1.ViewLineRenderingData.isBasicASCII(line, mightContainNonBasicASCII);
            const containsRTL = viewModel_1.ViewLineRenderingData.containsRTL(line, isBasicASCII, mightContainRTL);
            const renderResult = (0, viewLineRenderer_1.renderViewLine2)(new viewLineRenderer_1.RenderLineInput(false, true, line, false, isBasicASCII, containsRTL, 0, tokens, [], tabSize, 0, 0, 0, 0, -1, 'none', false, false, null));
            return renderResult.html;
        }
        static colorizeModelLine(model, lineNumber, tabSize = 4) {
            const content = model.getLineContent(lineNumber);
            model.tokenization.forceTokenization(lineNumber);
            const tokens = model.tokenization.getLineTokens(lineNumber);
            const inflatedTokens = tokens.inflate();
            return this.colorizeLine(content, model.mightContainNonBasicASCII(), model.mightContainRTL(), inflatedTokens, tabSize);
        }
    }
    exports.Colorizer = Colorizer;
    function _colorize(lines, tabSize, tokenizationSupport, languageIdCodec) {
        return new Promise((c, e) => {
            const execute = () => {
                const result = _actualColorize(lines, tabSize, tokenizationSupport, languageIdCodec);
                if (tokenizationSupport instanceof monarchLexer_1.MonarchTokenizer) {
                    const status = tokenizationSupport.getLoadStatus();
                    if (status.loaded === false) {
                        status.promise.then(execute, e);
                        return;
                    }
                }
                c(result);
            };
            execute();
        });
    }
    function _fakeColorize(lines, tabSize, languageIdCodec) {
        let html = [];
        const defaultMetadata = ((0 /* FontStyle.None */ << 11 /* MetadataConsts.FONT_STYLE_OFFSET */)
            | (1 /* ColorId.DefaultForeground */ << 15 /* MetadataConsts.FOREGROUND_OFFSET */)
            | (2 /* ColorId.DefaultBackground */ << 24 /* MetadataConsts.BACKGROUND_OFFSET */)) >>> 0;
        const tokens = new Uint32Array(2);
        tokens[0] = 0;
        tokens[1] = defaultMetadata;
        for (let i = 0, length = lines.length; i < length; i++) {
            const line = lines[i];
            tokens[0] = line.length;
            const lineTokens = new lineTokens_1.LineTokens(tokens, line, languageIdCodec);
            const isBasicASCII = viewModel_1.ViewLineRenderingData.isBasicASCII(line, /* check for basic ASCII */ true);
            const containsRTL = viewModel_1.ViewLineRenderingData.containsRTL(line, isBasicASCII, /* check for RTL */ true);
            const renderResult = (0, viewLineRenderer_1.renderViewLine2)(new viewLineRenderer_1.RenderLineInput(false, true, line, false, isBasicASCII, containsRTL, 0, lineTokens, [], tabSize, 0, 0, 0, 0, -1, 'none', false, false, null));
            html = html.concat(renderResult.html);
            html.push('<br/>');
        }
        return html.join('');
    }
    function _actualColorize(lines, tabSize, tokenizationSupport, languageIdCodec) {
        let html = [];
        let state = tokenizationSupport.getInitialState();
        for (let i = 0, length = lines.length; i < length; i++) {
            const line = lines[i];
            const tokenizeResult = tokenizationSupport.tokenizeEncoded(line, true, state);
            lineTokens_1.LineTokens.convertToEndOffset(tokenizeResult.tokens, line.length);
            const lineTokens = new lineTokens_1.LineTokens(tokenizeResult.tokens, line, languageIdCodec);
            const isBasicASCII = viewModel_1.ViewLineRenderingData.isBasicASCII(line, /* check for basic ASCII */ true);
            const containsRTL = viewModel_1.ViewLineRenderingData.containsRTL(line, isBasicASCII, /* check for RTL */ true);
            const renderResult = (0, viewLineRenderer_1.renderViewLine2)(new viewLineRenderer_1.RenderLineInput(false, true, line, false, isBasicASCII, containsRTL, 0, lineTokens.inflate(), [], tabSize, 0, 0, 0, 0, -1, 'none', false, false, null));
            html = html.concat(renderResult.html);
            html.push('<br/>');
            state = tokenizeResult.endState;
        }
        return html.join('');
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[12/*vs/platform/contextkey/common/contextkey*/], __M([1/*require*/,0/*exports*/,16/*vs/base/common/platform*/,11/*vs/base/common/strings*/,672/*vs/platform/contextkey/common/scanner*/,7/*vs/platform/instantiation/common/instantiation*/,3/*vs/nls*/]), function (require, exports, platform_1, strings_1, scanner_1, instantiation_1, nls_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.IContextKeyService = exports.RawContextKey = exports.ContextKeyOrExpr = exports.ContextKeyAndExpr = exports.ContextKeyNotRegexExpr = exports.ContextKeyRegexExpr = exports.ContextKeySmallerEqualsExpr = exports.ContextKeySmallerExpr = exports.ContextKeyGreaterEqualsExpr = exports.ContextKeyGreaterExpr = exports.ContextKeyNotExpr = exports.ContextKeyNotEqualsExpr = exports.ContextKeyNotInExpr = exports.ContextKeyInExpr = exports.ContextKeyEqualsExpr = exports.ContextKeyDefinedExpr = exports.ContextKeyTrueExpr = exports.ContextKeyFalseExpr = exports.ContextKeyExpr = exports.Parser = void 0;
    exports.expressionsAreEqualWithConstantSubstitution = expressionsAreEqualWithConstantSubstitution;
    exports.implies = implies;
    const CONSTANT_VALUES = new Map();
    CONSTANT_VALUES.set('false', false);
    CONSTANT_VALUES.set('true', true);
    CONSTANT_VALUES.set('isMac', platform_1.isMacintosh);
    CONSTANT_VALUES.set('isLinux', platform_1.isLinux);
    CONSTANT_VALUES.set('isWindows', platform_1.isWindows);
    CONSTANT_VALUES.set('isWeb', platform_1.isWeb);
    CONSTANT_VALUES.set('isMacNative', platform_1.isMacintosh && !platform_1.isWeb);
    CONSTANT_VALUES.set('isEdge', platform_1.isEdge);
    CONSTANT_VALUES.set('isFirefox', platform_1.isFirefox);
    CONSTANT_VALUES.set('isChrome', platform_1.isChrome);
    CONSTANT_VALUES.set('isSafari', platform_1.isSafari);
    const hasOwnProperty = Object.prototype.hasOwnProperty;
    const defaultConfig = {
        regexParsingWithErrorRecovery: true
    };
    const errorEmptyString = (0, nls_1.localize)(1514, "Empty context key expression");
    const hintEmptyString = (0, nls_1.localize)(1515, "Did you forget to write an expression? You can also put 'false' or 'true' to always evaluate to false or true, respectively.");
    const errorNoInAfterNot = (0, nls_1.localize)(1516, "'in' after 'not'.");
    const errorClosingParenthesis = (0, nls_1.localize)(1517, "closing parenthesis ')'");
    const errorUnexpectedToken = (0, nls_1.localize)(1518, "Unexpected token");
    const hintUnexpectedToken = (0, nls_1.localize)(1519, "Did you forget to put && or || before the token?");
    const errorUnexpectedEOF = (0, nls_1.localize)(1520, "Unexpected end of expression");
    const hintUnexpectedEOF = (0, nls_1.localize)(1521, "Did you forget to put a context key?");
    /**
     * A parser for context key expressions.
     *
     * Example:
     * ```ts
     * const parser = new Parser();
     * const expr = parser.parse('foo == "bar" && baz == true');
     *
     * if (expr === undefined) {
     * 	// there were lexing or parsing errors
     * 	// process lexing errors with `parser.lexingErrors`
     *  // process parsing errors with `parser.parsingErrors`
     * } else {
     * 	// expr is a valid expression
     * }
     * ```
     */
    class Parser {
        // Note: this doesn't produce an exact syntax tree but a normalized one
        // ContextKeyExpression's that we use as AST nodes do not expose constructors that do not normalize
        static { this._parseError = new Error(); }
        constructor(_config = defaultConfig) {
            this._config = _config;
            // lifetime note: `_scanner` lives as long as the parser does, i.e., is not reset between calls to `parse`
            this._scanner = new scanner_1.Scanner();
            // lifetime note: `_tokens`, `_current`, and `_parsingErrors` must be reset between calls to `parse`
            this._tokens = [];
            this._current = 0; // invariant: 0 <= this._current < this._tokens.length ; any incrementation of this value must first call `_isAtEnd`
            this._parsingErrors = [];
            this._flagsGYRe = /g|y/g;
        }
        /**
         * Parse a context key expression.
         *
         * @param input the expression to parse
         * @returns the parsed expression or `undefined` if there's an error - call `lexingErrors` and `parsingErrors` to see the errors
         */
        parse(input) {
            if (input === '') {
                this._parsingErrors.push({ message: errorEmptyString, offset: 0, lexeme: '', additionalInfo: hintEmptyString });
                return undefined;
            }
            this._tokens = this._scanner.reset(input).scan();
            // @ulugbekna: we do not stop parsing if there are lexing errors to be able to reconstruct regexes with unescaped slashes; TODO@ulugbekna: make this respect config option for recovery
            this._current = 0;
            this._parsingErrors = [];
            try {
                const expr = this._expr();
                if (!this._isAtEnd()) {
                    const peek = this._peek();
                    const additionalInfo = peek.type === 17 /* TokenType.Str */ ? hintUnexpectedToken : undefined;
                    this._parsingErrors.push({ message: errorUnexpectedToken, offset: peek.offset, lexeme: scanner_1.Scanner.getLexeme(peek), additionalInfo });
                    throw Parser._parseError;
                }
                return expr;
            }
            catch (e) {
                if (!(e === Parser._parseError)) {
                    throw e;
                }
                return undefined;
            }
        }
        _expr() {
            return this._or();
        }
        _or() {
            const expr = [this._and()];
            while (this._matchOne(16 /* TokenType.Or */)) {
                const right = this._and();
                expr.push(right);
            }
            return expr.length === 1 ? expr[0] : ContextKeyExpr.or(...expr);
        }
        _and() {
            const expr = [this._term()];
            while (this._matchOne(15 /* TokenType.And */)) {
                const right = this._term();
                expr.push(right);
            }
            return expr.length === 1 ? expr[0] : ContextKeyExpr.and(...expr);
        }
        _term() {
            if (this._matchOne(2 /* TokenType.Neg */)) {
                const peek = this._peek();
                switch (peek.type) {
                    case 11 /* TokenType.True */:
                        this._advance();
                        return ContextKeyFalseExpr.INSTANCE;
                    case 12 /* TokenType.False */:
                        this._advance();
                        return ContextKeyTrueExpr.INSTANCE;
                    case 0 /* TokenType.LParen */: {
                        this._advance();
                        const expr = this._expr();
                        this._consume(1 /* TokenType.RParen */, errorClosingParenthesis);
                        return expr?.negate();
                    }
                    case 17 /* TokenType.Str */:
                        this._advance();
                        return ContextKeyNotExpr.create(peek.lexeme);
                    default:
                        throw this._errExpectedButGot(`KEY | true | false | '(' expression ')'`, peek);
                }
            }
            return this._primary();
        }
        _primary() {
            const peek = this._peek();
            switch (peek.type) {
                case 11 /* TokenType.True */:
                    this._advance();
                    return ContextKeyExpr.true();
                case 12 /* TokenType.False */:
                    this._advance();
                    return ContextKeyExpr.false();
                case 0 /* TokenType.LParen */: {
                    this._advance();
                    const expr = this._expr();
                    this._consume(1 /* TokenType.RParen */, errorClosingParenthesis);
                    return expr;
                }
                case 17 /* TokenType.Str */: {
                    // KEY
                    const key = peek.lexeme;
                    this._advance();
                    // =~ regex
                    if (this._matchOne(9 /* TokenType.RegexOp */)) {
                        // @ulugbekna: we need to reconstruct the regex from the tokens because some extensions use unescaped slashes in regexes
                        const expr = this._peek();
                        if (!this._config.regexParsingWithErrorRecovery) {
                            this._advance();
                            if (expr.type !== 10 /* TokenType.RegexStr */) {
                                throw this._errExpectedButGot(`REGEX`, expr);
                            }
                            const regexLexeme = expr.lexeme;
                            const closingSlashIndex = regexLexeme.lastIndexOf('/');
                            const flags = closingSlashIndex === regexLexeme.length - 1 ? undefined : this._removeFlagsGY(regexLexeme.substring(closingSlashIndex + 1));
                            let regexp;
                            try {
                                regexp = new RegExp(regexLexeme.substring(1, closingSlashIndex), flags);
                            }
                            catch (e) {
                                throw this._errExpectedButGot(`REGEX`, expr);
                            }
                            return ContextKeyRegexExpr.create(key, regexp);
                        }
                        switch (expr.type) {
                            case 10 /* TokenType.RegexStr */:
                            case 19 /* TokenType.Error */: { // also handle an ErrorToken in case of smth such as /(/file)/
                                const lexemeReconstruction = [expr.lexeme]; // /REGEX/ or /REGEX/FLAGS
                                this._advance();
                                let followingToken = this._peek();
                                let parenBalance = 0;
                                for (let i = 0; i < expr.lexeme.length; i++) {
                                    if (expr.lexeme.charCodeAt(i) === 40 /* CharCode.OpenParen */) {
                                        parenBalance++;
                                    }
                                    else if (expr.lexeme.charCodeAt(i) === 41 /* CharCode.CloseParen */) {
                                        parenBalance--;
                                    }
                                }
                                while (!this._isAtEnd() && followingToken.type !== 15 /* TokenType.And */ && followingToken.type !== 16 /* TokenType.Or */) {
                                    switch (followingToken.type) {
                                        case 0 /* TokenType.LParen */:
                                            parenBalance++;
                                            break;
                                        case 1 /* TokenType.RParen */:
                                            parenBalance--;
                                            break;
                                        case 10 /* TokenType.RegexStr */:
                                        case 18 /* TokenType.QuotedStr */:
                                            for (let i = 0; i < followingToken.lexeme.length; i++) {
                                                if (followingToken.lexeme.charCodeAt(i) === 40 /* CharCode.OpenParen */) {
                                                    parenBalance++;
                                                }
                                                else if (expr.lexeme.charCodeAt(i) === 41 /* CharCode.CloseParen */) {
                                                    parenBalance--;
                                                }
                                            }
                                    }
                                    if (parenBalance < 0) {
                                        break;
                                    }
                                    lexemeReconstruction.push(scanner_1.Scanner.getLexeme(followingToken));
                                    this._advance();
                                    followingToken = this._peek();
                                }
                                const regexLexeme = lexemeReconstruction.join('');
                                const closingSlashIndex = regexLexeme.lastIndexOf('/');
                                const flags = closingSlashIndex === regexLexeme.length - 1 ? undefined : this._removeFlagsGY(regexLexeme.substring(closingSlashIndex + 1));
                                let regexp;
                                try {
                                    regexp = new RegExp(regexLexeme.substring(1, closingSlashIndex), flags);
                                }
                                catch (e) {
                                    throw this._errExpectedButGot(`REGEX`, expr);
                                }
                                return ContextKeyExpr.regex(key, regexp);
                            }
                            case 18 /* TokenType.QuotedStr */: {
                                const serializedValue = expr.lexeme;
                                this._advance();
                                // replicate old regex parsing behavior
                                let regex = null;
                                if (!(0, strings_1.isFalsyOrWhitespace)(serializedValue)) {
                                    const start = serializedValue.indexOf('/');
                                    const end = serializedValue.lastIndexOf('/');
                                    if (start !== end && start >= 0) {
                                        const value = serializedValue.slice(start + 1, end);
                                        const caseIgnoreFlag = serializedValue[end + 1] === 'i' ? 'i' : '';
                                        try {
                                            regex = new RegExp(value, caseIgnoreFlag);
                                        }
                                        catch (_e) {
                                            throw this._errExpectedButGot(`REGEX`, expr);
                                        }
                                    }
                                }
                                if (regex === null) {
                                    throw this._errExpectedButGot('REGEX', expr);
                                }
                                return ContextKeyRegexExpr.create(key, regex);
                            }
                            default:
                                throw this._errExpectedButGot('REGEX', this._peek());
                        }
                    }
                    // [ 'not' 'in' value ]
                    if (this._matchOne(14 /* TokenType.Not */)) {
                        this._consume(13 /* TokenType.In */, errorNoInAfterNot);
                        const right = this._value();
                        return ContextKeyExpr.notIn(key, right);
                    }
                    // [ ('==' | '!=' | '<' | '<=' | '>' | '>=' | 'in') value ]
                    const maybeOp = this._peek().type;
                    switch (maybeOp) {
                        case 3 /* TokenType.Eq */: {
                            this._advance();
                            const right = this._value();
                            if (this._previous().type === 18 /* TokenType.QuotedStr */) { // to preserve old parser behavior: "foo == 'true'" is preserved as "foo == 'true'", but "foo == true" is optimized as "foo"
                                return ContextKeyExpr.equals(key, right);
                            }
                            switch (right) {
                                case 'true':
                                    return ContextKeyExpr.has(key);
                                case 'false':
                                    return ContextKeyExpr.not(key);
                                default:
                                    return ContextKeyExpr.equals(key, right);
                            }
                        }
                        case 4 /* TokenType.NotEq */: {
                            this._advance();
                            const right = this._value();
                            if (this._previous().type === 18 /* TokenType.QuotedStr */) { // same as above with "foo != 'true'"
                                return ContextKeyExpr.notEquals(key, right);
                            }
                            switch (right) {
                                case 'true':
                                    return ContextKeyExpr.not(key);
                                case 'false':
                                    return ContextKeyExpr.has(key);
                                default:
                                    return ContextKeyExpr.notEquals(key, right);
                            }
                        }
                        // TODO: ContextKeyExpr.smaller(key, right) accepts only `number` as `right` AND during eval of this node, we just eval to `false` if `right` is not a number
                        // consequently, package.json linter should _warn_ the user if they're passing undesired things to ops
                        case 5 /* TokenType.Lt */:
                            this._advance();
                            return ContextKeySmallerExpr.create(key, this._value());
                        case 6 /* TokenType.LtEq */:
                            this._advance();
                            return ContextKeySmallerEqualsExpr.create(key, this._value());
                        case 7 /* TokenType.Gt */:
                            this._advance();
                            return ContextKeyGreaterExpr.create(key, this._value());
                        case 8 /* TokenType.GtEq */:
                            this._advance();
                            return ContextKeyGreaterEqualsExpr.create(key, this._value());
                        case 13 /* TokenType.In */:
                            this._advance();
                            return ContextKeyExpr.in(key, this._value());
                        default:
                            return ContextKeyExpr.has(key);
                    }
                }
                case 20 /* TokenType.EOF */:
                    this._parsingErrors.push({ message: errorUnexpectedEOF, offset: peek.offset, lexeme: '', additionalInfo: hintUnexpectedEOF });
                    throw Parser._parseError;
                default:
                    throw this._errExpectedButGot(`true | false | KEY \n\t| KEY '=~' REGEX \n\t| KEY ('==' | '!=' | '<' | '<=' | '>' | '>=' | 'in' | 'not' 'in') value`, this._peek());
            }
        }
        _value() {
            const token = this._peek();
            switch (token.type) {
                case 17 /* TokenType.Str */:
                case 18 /* TokenType.QuotedStr */:
                    this._advance();
                    return token.lexeme;
                case 11 /* TokenType.True */:
                    this._advance();
                    return 'true';
                case 12 /* TokenType.False */:
                    this._advance();
                    return 'false';
                case 13 /* TokenType.In */: // we support `in` as a value, e.g., "when": "languageId == in" - exists in existing extensions
                    this._advance();
                    return 'in';
                default:
                    // this allows "when": "foo == " which's used by existing extensions
                    // we do not call `_advance` on purpose - we don't want to eat unintended tokens
                    return '';
            }
        }
        _removeFlagsGY(flags) {
            return flags.replaceAll(this._flagsGYRe, '');
        }
        // careful: this can throw if current token is the initial one (ie index = 0)
        _previous() {
            return this._tokens[this._current - 1];
        }
        _matchOne(token) {
            if (this._check(token)) {
                this._advance();
                return true;
            }
            return false;
        }
        _advance() {
            if (!this._isAtEnd()) {
                this._current++;
            }
            return this._previous();
        }
        _consume(type, message) {
            if (this._check(type)) {
                return this._advance();
            }
            throw this._errExpectedButGot(message, this._peek());
        }
        _errExpectedButGot(expected, got, additionalInfo) {
            const message = (0, nls_1.localize)(1522, "Expected: {0}\nReceived: '{1}'.", expected, scanner_1.Scanner.getLexeme(got));
            const offset = got.offset;
            const lexeme = scanner_1.Scanner.getLexeme(got);
            this._parsingErrors.push({ message, offset, lexeme, additionalInfo });
            return Parser._parseError;
        }
        _check(type) {
            return this._peek().type === type;
        }
        _peek() {
            return this._tokens[this._current];
        }
        _isAtEnd() {
            return this._peek().type === 20 /* TokenType.EOF */;
        }
    }
    exports.Parser = Parser;
    class ContextKeyExpr {
        static false() {
            return ContextKeyFalseExpr.INSTANCE;
        }
        static true() {
            return ContextKeyTrueExpr.INSTANCE;
        }
        static has(key) {
            return ContextKeyDefinedExpr.create(key);
        }
        static equals(key, value) {
            return ContextKeyEqualsExpr.create(key, value);
        }
        static notEquals(key, value) {
            return ContextKeyNotEqualsExpr.create(key, value);
        }
        static regex(key, value) {
            return ContextKeyRegexExpr.create(key, value);
        }
        static in(key, value) {
            return ContextKeyInExpr.create(key, value);
        }
        static notIn(key, value) {
            return ContextKeyNotInExpr.create(key, value);
        }
        static not(key) {
            return ContextKeyNotExpr.create(key);
        }
        static and(...expr) {
            return ContextKeyAndExpr.create(expr, null, true);
        }
        static or(...expr) {
            return ContextKeyOrExpr.create(expr, null, true);
        }
        static { this._parser = new Parser({ regexParsingWithErrorRecovery: false }); }
        static deserialize(serialized) {
            if (serialized === undefined || serialized === null) { // an empty string needs to be handled by the parser to get a corresponding parsing error reported
                return undefined;
            }
            const expr = this._parser.parse(serialized);
            return expr;
        }
    }
    exports.ContextKeyExpr = ContextKeyExpr;
    function expressionsAreEqualWithConstantSubstitution(a, b) {
        const aExpr = a ? a.substituteConstants() : undefined;
        const bExpr = b ? b.substituteConstants() : undefined;
        if (!aExpr && !bExpr) {
            return true;
        }
        if (!aExpr || !bExpr) {
            return false;
        }
        return aExpr.equals(bExpr);
    }
    function cmp(a, b) {
        return a.cmp(b);
    }
    class ContextKeyFalseExpr {
        static { this.INSTANCE = new ContextKeyFalseExpr(); }
        constructor() {
            this.type = 0 /* ContextKeyExprType.False */;
        }
        cmp(other) {
            return this.type - other.type;
        }
        equals(other) {
            return (other.type === this.type);
        }
        substituteConstants() {
            return this;
        }
        evaluate(context) {
            return false;
        }
        serialize() {
            return 'false';
        }
        keys() {
            return [];
        }
        negate() {
            return ContextKeyTrueExpr.INSTANCE;
        }
    }
    exports.ContextKeyFalseExpr = ContextKeyFalseExpr;
    class ContextKeyTrueExpr {
        static { this.INSTANCE = new ContextKeyTrueExpr(); }
        constructor() {
            this.type = 1 /* ContextKeyExprType.True */;
        }
        cmp(other) {
            return this.type - other.type;
        }
        equals(other) {
            return (other.type === this.type);
        }
        substituteConstants() {
            return this;
        }
        evaluate(context) {
            return true;
        }
        serialize() {
            return 'true';
        }
        keys() {
            return [];
        }
        negate() {
            return ContextKeyFalseExpr.INSTANCE;
        }
    }
    exports.ContextKeyTrueExpr = ContextKeyTrueExpr;
    class ContextKeyDefinedExpr {
        static create(key, negated = null) {
            const constantValue = CONSTANT_VALUES.get(key);
            if (typeof constantValue === 'boolean') {
                return constantValue ? ContextKeyTrueExpr.INSTANCE : ContextKeyFalseExpr.INSTANCE;
            }
            return new ContextKeyDefinedExpr(key, negated);
        }
        constructor(key, negated) {
            this.key = key;
            this.negated = negated;
            this.type = 2 /* ContextKeyExprType.Defined */;
        }
        cmp(other) {
            if (other.type !== this.type) {
                return this.type - other.type;
            }
            return cmp1(this.key, other.key);
        }
        equals(other) {
            if (other.type === this.type) {
                return (this.key === other.key);
            }
            return false;
        }
        substituteConstants() {
            const constantValue = CONSTANT_VALUES.get(this.key);
            if (typeof constantValue === 'boolean') {
                return constantValue ? ContextKeyTrueExpr.INSTANCE : ContextKeyFalseExpr.INSTANCE;
            }
            return this;
        }
        evaluate(context) {
            return (!!context.getValue(this.key));
        }
        serialize() {
            return this.key;
        }
        keys() {
            return [this.key];
        }
        negate() {
            if (!this.negated) {
                this.negated = ContextKeyNotExpr.create(this.key, this);
            }
            return this.negated;
        }
    }
    exports.ContextKeyDefinedExpr = ContextKeyDefinedExpr;
    class ContextKeyEqualsExpr {
        static create(key, value, negated = null) {
            if (typeof value === 'boolean') {
                return (value ? ContextKeyDefinedExpr.create(key, negated) : ContextKeyNotExpr.create(key, negated));
            }
            const constantValue = CONSTANT_VALUES.get(key);
            if (typeof constantValue === 'boolean') {
                const trueValue = constantValue ? 'true' : 'false';
                return (value === trueValue ? ContextKeyTrueExpr.INSTANCE : ContextKeyFalseExpr.INSTANCE);
            }
            return new ContextKeyEqualsExpr(key, value, negated);
        }
        constructor(key, value, negated) {
            this.key = key;
            this.value = value;
            this.negated = negated;
            this.type = 4 /* ContextKeyExprType.Equals */;
        }
        cmp(other) {
            if (other.type !== this.type) {
                return this.type - other.type;
            }
            return cmp2(this.key, this.value, other.key, other.value);
        }
        equals(other) {
            if (other.type === this.type) {
                return (this.key === other.key && this.value === other.value);
            }
            return false;
        }
        substituteConstants() {
            const constantValue = CONSTANT_VALUES.get(this.key);
            if (typeof constantValue === 'boolean') {
                const trueValue = constantValue ? 'true' : 'false';
                return (this.value === trueValue ? ContextKeyTrueExpr.INSTANCE : ContextKeyFalseExpr.INSTANCE);
            }
            return this;
        }
        evaluate(context) {
            // Intentional ==
            // eslint-disable-next-line eqeqeq
            return (context.getValue(this.key) == this.value);
        }
        serialize() {
            return `${this.key} == '${this.value}'`;
        }
        keys() {
            return [this.key];
        }
        negate() {
            if (!this.negated) {
                this.negated = ContextKeyNotEqualsExpr.create(this.key, this.value, this);
            }
            return this.negated;
        }
    }
    exports.ContextKeyEqualsExpr = ContextKeyEqualsExpr;
    class ContextKeyInExpr {
        static create(key, valueKey) {
            return new ContextKeyInExpr(key, valueKey);
        }
        constructor(key, valueKey) {
            this.key = key;
            this.valueKey = valueKey;
            this.type = 10 /* ContextKeyExprType.In */;
            this.negated = null;
        }
        cmp(other) {
            if (other.type !== this.type) {
                return this.type - other.type;
            }
            return cmp2(this.key, this.valueKey, other.key, other.valueKey);
        }
        equals(other) {
            if (other.type === this.type) {
                return (this.key === other.key && this.valueKey === other.valueKey);
            }
            return false;
        }
        substituteConstants() {
            return this;
        }
        evaluate(context) {
            const source = context.getValue(this.valueKey);
            const item = context.getValue(this.key);
            if (Array.isArray(source)) {
                return source.includes(item);
            }
            if (typeof item === 'string' && typeof source === 'object' && source !== null) {
                return hasOwnProperty.call(source, item);
            }
            return false;
        }
        serialize() {
            return `${this.key} in '${this.valueKey}'`;
        }
        keys() {
            return [this.key, this.valueKey];
        }
        negate() {
            if (!this.negated) {
                this.negated = ContextKeyNotInExpr.create(this.key, this.valueKey);
            }
            return this.negated;
        }
    }
    exports.ContextKeyInExpr = ContextKeyInExpr;
    class ContextKeyNotInExpr {
        static create(key, valueKey) {
            return new ContextKeyNotInExpr(key, valueKey);
        }
        constructor(key, valueKey) {
            this.key = key;
            this.valueKey = valueKey;
            this.type = 11 /* ContextKeyExprType.NotIn */;
            this._negated = ContextKeyInExpr.create(key, valueKey);
        }
        cmp(other) {
            if (other.type !== this.type) {
                return this.type - other.type;
            }
            return this._negated.cmp(other._negated);
        }
        equals(other) {
            if (other.type === this.type) {
                return this._negated.equals(other._negated);
            }
            return false;
        }
        substituteConstants() {
            return this;
        }
        evaluate(context) {
            return !this._negated.evaluate(context);
        }
        serialize() {
            return `${this.key} not in '${this.valueKey}'`;
        }
        keys() {
            return this._negated.keys();
        }
        negate() {
            return this._negated;
        }
    }
    exports.ContextKeyNotInExpr = ContextKeyNotInExpr;
    class ContextKeyNotEqualsExpr {
        static create(key, value, negated = null) {
            if (typeof value === 'boolean') {
                if (value) {
                    return ContextKeyNotExpr.create(key, negated);
                }
                return ContextKeyDefinedExpr.create(key, negated);
            }
            const constantValue = CONSTANT_VALUES.get(key);
            if (typeof constantValue === 'boolean') {
                const falseValue = constantValue ? 'true' : 'false';
                return (value === falseValue ? ContextKeyFalseExpr.INSTANCE : ContextKeyTrueExpr.INSTANCE);
            }
            return new ContextKeyNotEqualsExpr(key, value, negated);
        }
        constructor(key, value, negated) {
            this.key = key;
            this.value = value;
            this.negated = negated;
            this.type = 5 /* ContextKeyExprType.NotEquals */;
        }
        cmp(other) {
            if (other.type !== this.type) {
                return this.type - other.type;
            }
            return cmp2(this.key, this.value, other.key, other.value);
        }
        equals(other) {
            if (other.type === this.type) {
                return (this.key === other.key && this.value === other.value);
            }
            return false;
        }
        substituteConstants() {
            const constantValue = CONSTANT_VALUES.get(this.key);
            if (typeof constantValue === 'boolean') {
                const falseValue = constantValue ? 'true' : 'false';
                return (this.value === falseValue ? ContextKeyFalseExpr.INSTANCE : ContextKeyTrueExpr.INSTANCE);
            }
            return this;
        }
        evaluate(context) {
            // Intentional !=
            // eslint-disable-next-line eqeqeq
            return (context.getValue(this.key) != this.value);
        }
        serialize() {
            return `${this.key} != '${this.value}'`;
        }
        keys() {
            return [this.key];
        }
        negate() {
            if (!this.negated) {
                this.negated = ContextKeyEqualsExpr.create(this.key, this.value, this);
            }
            return this.negated;
        }
    }
    exports.ContextKeyNotEqualsExpr = ContextKeyNotEqualsExpr;
    class ContextKeyNotExpr {
        static create(key, negated = null) {
            const constantValue = CONSTANT_VALUES.get(key);
            if (typeof constantValue === 'boolean') {
                return (constantValue ? ContextKeyFalseExpr.INSTANCE : ContextKeyTrueExpr.INSTANCE);
            }
            return new ContextKeyNotExpr(key, negated);
        }
        constructor(key, negated) {
            this.key = key;
            this.negated = negated;
            this.type = 3 /* ContextKeyExprType.Not */;
        }
        cmp(other) {
            if (other.type !== this.type) {
                return this.type - other.type;
            }
            return cmp1(this.key, other.key);
        }
        equals(other) {
            if (other.type === this.type) {
                return (this.key === other.key);
            }
            return false;
        }
        substituteConstants() {
            const constantValue = CONSTANT_VALUES.get(this.key);
            if (typeof constantValue === 'boolean') {
                return (constantValue ? ContextKeyFalseExpr.INSTANCE : ContextKeyTrueExpr.INSTANCE);
            }
            return this;
        }
        evaluate(context) {
            return (!context.getValue(this.key));
        }
        serialize() {
            return `!${this.key}`;
        }
        keys() {
            return [this.key];
        }
        negate() {
            if (!this.negated) {
                this.negated = ContextKeyDefinedExpr.create(this.key, this);
            }
            return this.negated;
        }
    }
    exports.ContextKeyNotExpr = ContextKeyNotExpr;
    function withFloatOrStr(value, callback) {
        if (typeof value === 'string') {
            const n = parseFloat(value);
            if (!isNaN(n)) {
                value = n;
            }
        }
        if (typeof value === 'string' || typeof value === 'number') {
            return callback(value);
        }
        return ContextKeyFalseExpr.INSTANCE;
    }
    class ContextKeyGreaterExpr {
        static create(key, _value, negated = null) {
            return withFloatOrStr(_value, (value) => new ContextKeyGreaterExpr(key, value, negated));
        }
        constructor(key, value, negated) {
            this.key = key;
            this.value = value;
            this.negated = negated;
            this.type = 12 /* ContextKeyExprType.Greater */;
        }
        cmp(other) {
            if (other.type !== this.type) {
                return this.type - other.type;
            }
            return cmp2(this.key, this.value, other.key, other.value);
        }
        equals(other) {
            if (other.type === this.type) {
                return (this.key === other.key && this.value === other.value);
            }
            return false;
        }
        substituteConstants() {
            return this;
        }
        evaluate(context) {
            if (typeof this.value === 'string') {
                return false;
            }
            return (parseFloat(context.getValue(this.key)) > this.value);
        }
        serialize() {
            return `${this.key} > ${this.value}`;
        }
        keys() {
            return [this.key];
        }
        negate() {
            if (!this.negated) {
                this.negated = ContextKeySmallerEqualsExpr.create(this.key, this.value, this);
            }
            return this.negated;
        }
    }
    exports.ContextKeyGreaterExpr = ContextKeyGreaterExpr;
    class ContextKeyGreaterEqualsExpr {
        static create(key, _value, negated = null) {
            return withFloatOrStr(_value, (value) => new ContextKeyGreaterEqualsExpr(key, value, negated));
        }
        constructor(key, value, negated) {
            this.key = key;
            this.value = value;
            this.negated = negated;
            this.type = 13 /* ContextKeyExprType.GreaterEquals */;
        }
        cmp(other) {
            if (other.type !== this.type) {
                return this.type - other.type;
            }
            return cmp2(this.key, this.value, other.key, other.value);
        }
        equals(other) {
            if (other.type === this.type) {
                return (this.key === other.key && this.value === other.value);
            }
            return false;
        }
        substituteConstants() {
            return this;
        }
        evaluate(context) {
            if (typeof this.value === 'string') {
                return false;
            }
            return (parseFloat(context.getValue(this.key)) >= this.value);
        }
        serialize() {
            return `${this.key} >= ${this.value}`;
        }
        keys() {
            return [this.key];
        }
        negate() {
            if (!this.negated) {
                this.negated = ContextKeySmallerExpr.create(this.key, this.value, this);
            }
            return this.negated;
        }
    }
    exports.ContextKeyGreaterEqualsExpr = ContextKeyGreaterEqualsExpr;
    class ContextKeySmallerExpr {
        static create(key, _value, negated = null) {
            return withFloatOrStr(_value, (value) => new ContextKeySmallerExpr(key, value, negated));
        }
        constructor(key, value, negated) {
            this.key = key;
            this.value = value;
            this.negated = negated;
            this.type = 14 /* ContextKeyExprType.Smaller */;
        }
        cmp(other) {
            if (other.type !== this.type) {
                return this.type - other.type;
            }
            return cmp2(this.key, this.value, other.key, other.value);
        }
        equals(other) {
            if (other.type === this.type) {
                return (this.key === other.key && this.value === other.value);
            }
            return false;
        }
        substituteConstants() {
            return this;
        }
        evaluate(context) {
            if (typeof this.value === 'string') {
                return false;
            }
            return (parseFloat(context.getValue(this.key)) < this.value);
        }
        serialize() {
            return `${this.key} < ${this.value}`;
        }
        keys() {
            return [this.key];
        }
        negate() {
            if (!this.negated) {
                this.negated = ContextKeyGreaterEqualsExpr.create(this.key, this.value, this);
            }
            return this.negated;
        }
    }
    exports.ContextKeySmallerExpr = ContextKeySmallerExpr;
    class ContextKeySmallerEqualsExpr {
        static create(key, _value, negated = null) {
            return withFloatOrStr(_value, (value) => new ContextKeySmallerEqualsExpr(key, value, negated));
        }
        constructor(key, value, negated) {
            this.key = key;
            this.value = value;
            this.negated = negated;
            this.type = 15 /* ContextKeyExprType.SmallerEquals */;
        }
        cmp(other) {
            if (other.type !== this.type) {
                return this.type - other.type;
            }
            return cmp2(this.key, this.value, other.key, other.value);
        }
        equals(other) {
            if (other.type === this.type) {
                return (this.key === other.key && this.value === other.value);
            }
            return false;
        }
        substituteConstants() {
            return this;
        }
        evaluate(context) {
            if (typeof this.value === 'string') {
                return false;
            }
            return (parseFloat(context.getValue(this.key)) <= this.value);
        }
        serialize() {
            return `${this.key} <= ${this.value}`;
        }
        keys() {
            return [this.key];
        }
        negate() {
            if (!this.negated) {
                this.negated = ContextKeyGreaterExpr.create(this.key, this.value, this);
            }
            return this.negated;
        }
    }
    exports.ContextKeySmallerEqualsExpr = ContextKeySmallerEqualsExpr;
    class ContextKeyRegexExpr {
        static create(key, regexp) {
            return new ContextKeyRegexExpr(key, regexp);
        }
        constructor(key, regexp) {
            this.key = key;
            this.regexp = regexp;
            this.type = 7 /* ContextKeyExprType.Regex */;
            this.negated = null;
            //
        }
        cmp(other) {
            if (other.type !== this.type) {
                return this.type - other.type;
            }
            if (this.key < other.key) {
                return -1;
            }
            if (this.key > other.key) {
                return 1;
            }
            const thisSource = this.regexp ? this.regexp.source : '';
            const otherSource = other.regexp ? other.regexp.source : '';
            if (thisSource < otherSource) {
                return -1;
            }
            if (thisSource > otherSource) {
                return 1;
            }
            return 0;
        }
        equals(other) {
            if (other.type === this.type) {
                const thisSource = this.regexp ? this.regexp.source : '';
                const otherSource = other.regexp ? other.regexp.source : '';
                return (this.key === other.key && thisSource === otherSource);
            }
            return false;
        }
        substituteConstants() {
            return this;
        }
        evaluate(context) {
            const value = context.getValue(this.key);
            return this.regexp ? this.regexp.test(value) : false;
        }
        serialize() {
            const value = this.regexp
                ? `/${this.regexp.source}/${this.regexp.flags}`
                : '/invalid/';
            return `${this.key} =~ ${value}`;
        }
        keys() {
            return [this.key];
        }
        negate() {
            if (!this.negated) {
                this.negated = ContextKeyNotRegexExpr.create(this);
            }
            return this.negated;
        }
    }
    exports.ContextKeyRegexExpr = ContextKeyRegexExpr;
    class ContextKeyNotRegexExpr {
        static create(actual) {
            return new ContextKeyNotRegexExpr(actual);
        }
        constructor(_actual) {
            this._actual = _actual;
            this.type = 8 /* ContextKeyExprType.NotRegex */;
            //
        }
        cmp(other) {
            if (other.type !== this.type) {
                return this.type - other.type;
            }
            return this._actual.cmp(other._actual);
        }
        equals(other) {
            if (other.type === this.type) {
                return this._actual.equals(other._actual);
            }
            return false;
        }
        substituteConstants() {
            return this;
        }
        evaluate(context) {
            return !this._actual.evaluate(context);
        }
        serialize() {
            return `!(${this._actual.serialize()})`;
        }
        keys() {
            return this._actual.keys();
        }
        negate() {
            return this._actual;
        }
    }
    exports.ContextKeyNotRegexExpr = ContextKeyNotRegexExpr;
    /**
     * @returns the same instance if nothing changed.
     */
    function eliminateConstantsInArray(arr) {
        // Allocate array only if there is a difference
        let newArr = null;
        for (let i = 0, len = arr.length; i < len; i++) {
            const newExpr = arr[i].substituteConstants();
            if (arr[i] !== newExpr) {
                // something has changed!
                // allocate array on first difference
                if (newArr === null) {
                    newArr = [];
                    for (let j = 0; j < i; j++) {
                        newArr[j] = arr[j];
                    }
                }
            }
            if (newArr !== null) {
                newArr[i] = newExpr;
            }
        }
        if (newArr === null) {
            return arr;
        }
        return newArr;
    }
    class ContextKeyAndExpr {
        static create(_expr, negated, extraRedundantCheck) {
            return ContextKeyAndExpr._normalizeArr(_expr, negated, extraRedundantCheck);
        }
        constructor(expr, negated) {
            this.expr = expr;
            this.negated = negated;
            this.type = 6 /* ContextKeyExprType.And */;
        }
        cmp(other) {
            if (other.type !== this.type) {
                return this.type - other.type;
            }
            if (this.expr.length < other.expr.length) {
                return -1;
            }
            if (this.expr.length > other.expr.length) {
                return 1;
            }
            for (let i = 0, len = this.expr.length; i < len; i++) {
                const r = cmp(this.expr[i], other.expr[i]);
                if (r !== 0) {
                    return r;
                }
            }
            return 0;
        }
        equals(other) {
            if (other.type === this.type) {
                if (this.expr.length !== other.expr.length) {
                    return false;
                }
                for (let i = 0, len = this.expr.length; i < len; i++) {
                    if (!this.expr[i].equals(other.expr[i])) {
                        return false;
                    }
                }
                return true;
            }
            return false;
        }
        substituteConstants() {
            const exprArr = eliminateConstantsInArray(this.expr);
            if (exprArr === this.expr) {
                // no change
                return this;
            }
            return ContextKeyAndExpr.create(exprArr, this.negated, false);
        }
        evaluate(context) {
            for (let i = 0, len = this.expr.length; i < len; i++) {
                if (!this.expr[i].evaluate(context)) {
                    return false;
                }
            }
            return true;
        }
        static _normalizeArr(arr, negated, extraRedundantCheck) {
            const expr = [];
            let hasTrue = false;
            for (const e of arr) {
                if (!e) {
                    continue;
                }
                if (e.type === 1 /* ContextKeyExprType.True */) {
                    // anything && true ==> anything
                    hasTrue = true;
                    continue;
                }
                if (e.type === 0 /* ContextKeyExprType.False */) {
                    // anything && false ==> false
                    return ContextKeyFalseExpr.INSTANCE;
                }
                if (e.type === 6 /* ContextKeyExprType.And */) {
                    expr.push(...e.expr);
                    continue;
                }
                expr.push(e);
            }
            if (expr.length === 0 && hasTrue) {
                return ContextKeyTrueExpr.INSTANCE;
            }
            if (expr.length === 0) {
                return undefined;
            }
            if (expr.length === 1) {
                return expr[0];
            }
            expr.sort(cmp);
            // eliminate duplicate terms
            for (let i = 1; i < expr.length; i++) {
                if (expr[i - 1].equals(expr[i])) {
                    expr.splice(i, 1);
                    i--;
                }
            }
            if (expr.length === 1) {
                return expr[0];
            }
            // We must distribute any OR expression because we don't support parens
            // OR extensions will be at the end (due to sorting rules)
            while (expr.length > 1) {
                const lastElement = expr[expr.length - 1];
                if (lastElement.type !== 9 /* ContextKeyExprType.Or */) {
                    break;
                }
                // pop the last element
                expr.pop();
                // pop the second to last element
                const secondToLastElement = expr.pop();
                const isFinished = (expr.length === 0);
                // distribute `lastElement` over `secondToLastElement`
                const resultElement = ContextKeyOrExpr.create(lastElement.expr.map(el => ContextKeyAndExpr.create([el, secondToLastElement], null, extraRedundantCheck)), null, isFinished);
                if (resultElement) {
                    expr.push(resultElement);
                    expr.sort(cmp);
                }
            }
            if (expr.length === 1) {
                return expr[0];
            }
            // resolve false AND expressions
            if (extraRedundantCheck) {
                for (let i = 0; i < expr.length; i++) {
                    for (let j = i + 1; j < expr.length; j++) {
                        if (expr[i].negate().equals(expr[j])) {
                            // A && !A case
                            return ContextKeyFalseExpr.INSTANCE;
                        }
                    }
                }
                if (expr.length === 1) {
                    return expr[0];
                }
            }
            return new ContextKeyAndExpr(expr, negated);
        }
        serialize() {
            return this.expr.map(e => e.serialize()).join(' && ');
        }
        keys() {
            const result = [];
            for (const expr of this.expr) {
                result.push(...expr.keys());
            }
            return result;
        }
        negate() {
            if (!this.negated) {
                const result = [];
                for (const expr of this.expr) {
                    result.push(expr.negate());
                }
                this.negated = ContextKeyOrExpr.create(result, this, true);
            }
            return this.negated;
        }
    }
    exports.ContextKeyAndExpr = ContextKeyAndExpr;
    class ContextKeyOrExpr {
        static create(_expr, negated, extraRedundantCheck) {
            return ContextKeyOrExpr._normalizeArr(_expr, negated, extraRedundantCheck);
        }
        constructor(expr, negated) {
            this.expr = expr;
            this.negated = negated;
            this.type = 9 /* ContextKeyExprType.Or */;
        }
        cmp(other) {
            if (other.type !== this.type) {
                return this.type - other.type;
            }
            if (this.expr.length < other.expr.length) {
                return -1;
            }
            if (this.expr.length > other.expr.length) {
                return 1;
            }
            for (let i = 0, len = this.expr.length; i < len; i++) {
                const r = cmp(this.expr[i], other.expr[i]);
                if (r !== 0) {
                    return r;
                }
            }
            return 0;
        }
        equals(other) {
            if (other.type === this.type) {
                if (this.expr.length !== other.expr.length) {
                    return false;
                }
                for (let i = 0, len = this.expr.length; i < len; i++) {
                    if (!this.expr[i].equals(other.expr[i])) {
                        return false;
                    }
                }
                return true;
            }
            return false;
        }
        substituteConstants() {
            const exprArr = eliminateConstantsInArray(this.expr);
            if (exprArr === this.expr) {
                // no change
                return this;
            }
            return ContextKeyOrExpr.create(exprArr, this.negated, false);
        }
        evaluate(context) {
            for (let i = 0, len = this.expr.length; i < len; i++) {
                if (this.expr[i].evaluate(context)) {
                    return true;
                }
            }
            return false;
        }
        static _normalizeArr(arr, negated, extraRedundantCheck) {
            let expr = [];
            let hasFalse = false;
            if (arr) {
                for (let i = 0, len = arr.length; i < len; i++) {
                    const e = arr[i];
                    if (!e) {
                        continue;
                    }
                    if (e.type === 0 /* ContextKeyExprType.False */) {
                        // anything || false ==> anything
                        hasFalse = true;
                        continue;
                    }
                    if (e.type === 1 /* ContextKeyExprType.True */) {
                        // anything || true ==> true
                        return ContextKeyTrueExpr.INSTANCE;
                    }
                    if (e.type === 9 /* ContextKeyExprType.Or */) {
                        expr = expr.concat(e.expr);
                        continue;
                    }
                    expr.push(e);
                }
                if (expr.length === 0 && hasFalse) {
                    return ContextKeyFalseExpr.INSTANCE;
                }
                expr.sort(cmp);
            }
            if (expr.length === 0) {
                return undefined;
            }
            if (expr.length === 1) {
                return expr[0];
            }
            // eliminate duplicate terms
            for (let i = 1; i < expr.length; i++) {
                if (expr[i - 1].equals(expr[i])) {
                    expr.splice(i, 1);
                    i--;
                }
            }
            if (expr.length === 1) {
                return expr[0];
            }
            // resolve true OR expressions
            if (extraRedundantCheck) {
                for (let i = 0; i < expr.length; i++) {
                    for (let j = i + 1; j < expr.length; j++) {
                        if (expr[i].negate().equals(expr[j])) {
                            // A || !A case
                            return ContextKeyTrueExpr.INSTANCE;
                        }
                    }
                }
                if (expr.length === 1) {
                    return expr[0];
                }
            }
            return new ContextKeyOrExpr(expr, negated);
        }
        serialize() {
            return this.expr.map(e => e.serialize()).join(' || ');
        }
        keys() {
            const result = [];
            for (const expr of this.expr) {
                result.push(...expr.keys());
            }
            return result;
        }
        negate() {
            if (!this.negated) {
                const result = [];
                for (const expr of this.expr) {
                    result.push(expr.negate());
                }
                // We don't support parens, so here we distribute the AND over the OR terminals
                // We always take the first 2 AND pairs and distribute them
                while (result.length > 1) {
                    const LEFT = result.shift();
                    const RIGHT = result.shift();
                    const all = [];
                    for (const left of getTerminals(LEFT)) {
                        for (const right of getTerminals(RIGHT)) {
                            all.push(ContextKeyAndExpr.create([left, right], null, false));
                        }
                    }
                    result.unshift(ContextKeyOrExpr.create(all, null, false));
                }
                this.negated = ContextKeyOrExpr.create(result, this, true);
            }
            return this.negated;
        }
    }
    exports.ContextKeyOrExpr = ContextKeyOrExpr;
    class RawContextKey extends ContextKeyDefinedExpr {
        static { this._info = []; }
        static all() {
            return RawContextKey._info.values();
        }
        constructor(key, defaultValue, metaOrHide) {
            super(key, null);
            this._defaultValue = defaultValue;
            // collect all context keys into a central place
            if (typeof metaOrHide === 'object') {
                RawContextKey._info.push({ ...metaOrHide, key });
            }
            else if (metaOrHide !== true) {
                RawContextKey._info.push({ key, description: metaOrHide, type: defaultValue !== null && defaultValue !== undefined ? typeof defaultValue : undefined });
            }
        }
        bindTo(target) {
            return target.createKey(this.key, this._defaultValue);
        }
        getValue(target) {
            return target.getContextKeyValue(this.key);
        }
        toNegated() {
            return this.negate();
        }
        isEqualTo(value) {
            return ContextKeyEqualsExpr.create(this.key, value);
        }
    }
    exports.RawContextKey = RawContextKey;
    exports.IContextKeyService = (0, instantiation_1.createDecorator)('contextKeyService');
    function cmp1(key1, key2) {
        if (key1 < key2) {
            return -1;
        }
        if (key1 > key2) {
            return 1;
        }
        return 0;
    }
    function cmp2(key1, value1, key2, value2) {
        if (key1 < key2) {
            return -1;
        }
        if (key1 > key2) {
            return 1;
        }
        if (value1 < value2) {
            return -1;
        }
        if (value1 > value2) {
            return 1;
        }
        return 0;
    }
    /**
     * Returns true if it is provable `p` implies `q`.
     */
    function implies(p, q) {
        if (p.type === 0 /* ContextKeyExprType.False */ || q.type === 1 /* ContextKeyExprType.True */) {
            // false implies anything
            // anything implies true
            return true;
        }
        if (p.type === 9 /* ContextKeyExprType.Or */) {
            if (q.type === 9 /* ContextKeyExprType.Or */) {
                // `a || b || c` can only imply something like `a || b || c || d`
                return allElementsIncluded(p.expr, q.expr);
            }
            return false;
        }
        if (q.type === 9 /* ContextKeyExprType.Or */) {
            for (const element of q.expr) {
                if (implies(p, element)) {
                    return true;
                }
            }
            return false;
        }
        if (p.type === 6 /* ContextKeyExprType.And */) {
            if (q.type === 6 /* ContextKeyExprType.And */) {
                // `a && b && c` implies `a && c`
                return allElementsIncluded(q.expr, p.expr);
            }
            for (const element of p.expr) {
                if (implies(element, q)) {
                    return true;
                }
            }
            return false;
        }
        return p.equals(q);
    }
    /**
     * Returns true if all elements in `p` are also present in `q`.
     * The two arrays are assumed to be sorted
     */
    function allElementsIncluded(p, q) {
        let pIndex = 0;
        let qIndex = 0;
        while (pIndex < p.length && qIndex < q.length) {
            const cmp = p[pIndex].cmp(q[qIndex]);
            if (cmp < 0) {
                // an element from `p` is missing from `q`
                return false;
            }
            else if (cmp === 0) {
                pIndex++;
                qIndex++;
            }
            else {
                qIndex++;
            }
        }
        return (pIndex === p.length);
    }
    function getTerminals(node) {
        if (node.type === 9 /* ContextKeyExprType.Or */) {
            return node.expr;
        }
        return [node];
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[20/*vs/editor/common/editorContextKeys*/], __M([1/*require*/,0/*exports*/,3/*vs/nls*/,12/*vs/platform/contextkey/common/contextkey*/]), function (require, exports, nls, contextkey_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.EditorContextKeys = void 0;
    var EditorContextKeys;
    (function (EditorContextKeys) {
        EditorContextKeys.editorSimpleInput = new contextkey_1.RawContextKey('editorSimpleInput', false, true);
        /**
         * A context key that is set when the editor's text has focus (cursor is blinking).
         * Is false when focus is in simple editor widgets (repl input, scm commit input).
         */
        EditorContextKeys.editorTextFocus = new contextkey_1.RawContextKey('editorTextFocus', false, nls.localize(622, "Whether the editor text has focus (cursor is blinking)"));
        /**
         * A context key that is set when the editor's text or an editor's widget has focus.
         */
        EditorContextKeys.focus = new contextkey_1.RawContextKey('editorFocus', false, nls.localize(623, "Whether the editor or an editor widget has focus (e.g. focus is in the find widget)"));
        /**
         * A context key that is set when any editor input has focus (regular editor, repl input...).
         */
        EditorContextKeys.textInputFocus = new contextkey_1.RawContextKey('textInputFocus', false, nls.localize(624, "Whether an editor or a rich text input has focus (cursor is blinking)"));
        EditorContextKeys.readOnly = new contextkey_1.RawContextKey('editorReadonly', false, nls.localize(625, "Whether the editor is read-only"));
        EditorContextKeys.inDiffEditor = new contextkey_1.RawContextKey('inDiffEditor', false, nls.localize(626, "Whether the context is a diff editor"));
        EditorContextKeys.isEmbeddedDiffEditor = new contextkey_1.RawContextKey('isEmbeddedDiffEditor', false, nls.localize(627, "Whether the context is an embedded diff editor"));
        EditorContextKeys.inMultiDiffEditor = new contextkey_1.RawContextKey('inMultiDiffEditor', false, nls.localize(628, "Whether the context is a multi diff editor"));
        EditorContextKeys.multiDiffEditorAllCollapsed = new contextkey_1.RawContextKey('multiDiffEditorAllCollapsed', undefined, nls.localize(629, "Whether all files in multi diff editor are collapsed"));
        EditorContextKeys.hasChanges = new contextkey_1.RawContextKey('diffEditorHasChanges', false, nls.localize(630, "Whether the diff editor has changes"));
        EditorContextKeys.comparingMovedCode = new contextkey_1.RawContextKey('comparingMovedCode', false, nls.localize(631, "Whether a moved code block is selected for comparison"));
        EditorContextKeys.accessibleDiffViewerVisible = new contextkey_1.RawContextKey('accessibleDiffViewerVisible', false, nls.localize(632, "Whether the accessible diff viewer is visible"));
        EditorContextKeys.diffEditorRenderSideBySideInlineBreakpointReached = new contextkey_1.RawContextKey('diffEditorRenderSideBySideInlineBreakpointReached', false, nls.localize(633, "Whether the diff editor render side by side inline breakpoint is reached"));
        EditorContextKeys.diffEditorInlineMode = new contextkey_1.RawContextKey('diffEditorInlineMode', false, nls.localize(634, "Whether inline mode is active"));
        EditorContextKeys.diffEditorOriginalWritable = new contextkey_1.RawContextKey('diffEditorOriginalWritable', false, nls.localize(635, "Whether modified is writable in the diff editor"));
        EditorContextKeys.diffEditorModifiedWritable = new contextkey_1.RawContextKey('diffEditorModifiedWritable', false, nls.localize(636, "Whether modified is writable in the diff editor"));
        EditorContextKeys.diffEditorOriginalUri = new contextkey_1.RawContextKey('diffEditorOriginalUri', '', nls.localize(637, "The uri of the original document"));
        EditorContextKeys.diffEditorModifiedUri = new contextkey_1.RawContextKey('diffEditorModifiedUri', '', nls.localize(638, "The uri of the modified document"));
        EditorContextKeys.columnSelection = new contextkey_1.RawContextKey('editorColumnSelection', false, nls.localize(639, "Whether `editor.columnSelection` is enabled"));
        EditorContextKeys.writable = EditorContextKeys.readOnly.toNegated();
        EditorContextKeys.hasNonEmptySelection = new contextkey_1.RawContextKey('editorHasSelection', false, nls.localize(640, "Whether the editor has text selected"));
        EditorContextKeys.hasOnlyEmptySelection = EditorContextKeys.hasNonEmptySelection.toNegated();
        EditorContextKeys.hasMultipleSelections = new contextkey_1.RawContextKey('editorHasMultipleSelections', false, nls.localize(641, "Whether the editor has multiple selections"));
        EditorContextKeys.hasSingleSelection = EditorContextKeys.hasMultipleSelections.toNegated();
        EditorContextKeys.tabMovesFocus = new contextkey_1.RawContextKey('editorTabMovesFocus', false, nls.localize(642, "Whether `Tab` will move focus out of the editor"));
        EditorContextKeys.tabDoesNotMoveFocus = EditorContextKeys.tabMovesFocus.toNegated();
        EditorContextKeys.isInEmbeddedEditor = new contextkey_1.RawContextKey('isInEmbeddedEditor', false, true);
        EditorContextKeys.canUndo = new contextkey_1.RawContextKey('canUndo', false, true);
        EditorContextKeys.canRedo = new contextkey_1.RawContextKey('canRedo', false, true);
        EditorContextKeys.hoverVisible = new contextkey_1.RawContextKey('editorHoverVisible', false, nls.localize(643, "Whether the editor hover is visible"));
        EditorContextKeys.hoverFocused = new contextkey_1.RawContextKey('editorHoverFocused', false, nls.localize(644, "Whether the editor hover is focused"));
        EditorContextKeys.stickyScrollFocused = new contextkey_1.RawContextKey('stickyScrollFocused', false, nls.localize(645, "Whether the sticky scroll is focused"));
        EditorContextKeys.stickyScrollVisible = new contextkey_1.RawContextKey('stickyScrollVisible', false, nls.localize(646, "Whether the sticky scroll is visible"));
        EditorContextKeys.standaloneColorPickerVisible = new contextkey_1.RawContextKey('standaloneColorPickerVisible', false, nls.localize(647, "Whether the standalone color picker is visible"));
        EditorContextKeys.standaloneColorPickerFocused = new contextkey_1.RawContextKey('standaloneColorPickerFocused', false, nls.localize(648, "Whether the standalone color picker is focused"));
        /**
         * A context key that is set when an editor is part of a larger editor, like notebooks or
         * (future) a diff editor
         */
        EditorContextKeys.inCompositeEditor = new contextkey_1.RawContextKey('inCompositeEditor', undefined, nls.localize(649, "Whether the editor is part of a larger editor (e.g. notebooks)"));
        EditorContextKeys.notInCompositeEditor = EditorContextKeys.inCompositeEditor.toNegated();
        // -- mode context keys
        EditorContextKeys.languageId = new contextkey_1.RawContextKey('editorLangId', '', nls.localize(650, "The language identifier of the editor"));
        EditorContextKeys.hasCompletionItemProvider = new contextkey_1.RawContextKey('editorHasCompletionItemProvider', false, nls.localize(651, "Whether the editor has a completion item provider"));
        EditorContextKeys.hasCodeActionsProvider = new contextkey_1.RawContextKey('editorHasCodeActionsProvider', false, nls.localize(652, "Whether the editor has a code actions provider"));
        EditorContextKeys.hasCodeLensProvider = new contextkey_1.RawContextKey('editorHasCodeLensProvider', false, nls.localize(653, "Whether the editor has a code lens provider"));
        EditorContextKeys.hasDefinitionProvider = new contextkey_1.RawContextKey('editorHasDefinitionProvider', false, nls.localize(654, "Whether the editor has a definition provider"));
        EditorContextKeys.hasDeclarationProvider = new contextkey_1.RawContextKey('editorHasDeclarationProvider', false, nls.localize(655, "Whether the editor has a declaration provider"));
        EditorContextKeys.hasImplementationProvider = new contextkey_1.RawContextKey('editorHasImplementationProvider', false, nls.localize(656, "Whether the editor has an implementation provider"));
        EditorContextKeys.hasTypeDefinitionProvider = new contextkey_1.RawContextKey('editorHasTypeDefinitionProvider', false, nls.localize(657, "Whether the editor has a type definition provider"));
        EditorContextKeys.hasHoverProvider = new contextkey_1.RawContextKey('editorHasHoverProvider', false, nls.localize(658, "Whether the editor has a hover provider"));
        EditorContextKeys.hasDocumentHighlightProvider = new contextkey_1.RawContextKey('editorHasDocumentHighlightProvider', false, nls.localize(659, "Whether the editor has a document highlight provider"));
        EditorContextKeys.hasDocumentSymbolProvider = new contextkey_1.RawContextKey('editorHasDocumentSymbolProvider', false, nls.localize(660, "Whether the editor has a document symbol provider"));
        EditorContextKeys.hasReferenceProvider = new contextkey_1.RawContextKey('editorHasReferenceProvider', false, nls.localize(661, "Whether the editor has a reference provider"));
        EditorContextKeys.hasRenameProvider = new contextkey_1.RawContextKey('editorHasRenameProvider', false, nls.localize(662, "Whether the editor has a rename provider"));
        EditorContextKeys.hasSignatureHelpProvider = new contextkey_1.RawContextKey('editorHasSignatureHelpProvider', false, nls.localize(663, "Whether the editor has a signature help provider"));
        EditorContextKeys.hasInlayHintsProvider = new contextkey_1.RawContextKey('editorHasInlayHintsProvider', false, nls.localize(664, "Whether the editor has an inline hints provider"));
        // -- mode context keys: formatting
        EditorContextKeys.hasDocumentFormattingProvider = new contextkey_1.RawContextKey('editorHasDocumentFormattingProvider', false, nls.localize(665, "Whether the editor has a document formatting provider"));
        EditorContextKeys.hasDocumentSelectionFormattingProvider = new contextkey_1.RawContextKey('editorHasDocumentSelectionFormattingProvider', false, nls.localize(666, "Whether the editor has a document selection formatting provider"));
        EditorContextKeys.hasMultipleDocumentFormattingProvider = new contextkey_1.RawContextKey('editorHasMultipleDocumentFormattingProvider', false, nls.localize(667, "Whether the editor has multiple document formatting providers"));
        EditorContextKeys.hasMultipleDocumentSelectionFormattingProvider = new contextkey_1.RawContextKey('editorHasMultipleDocumentSelectionFormattingProvider', false, nls.localize(668, "Whether the editor has multiple document selection formatting providers"));
    })(EditorContextKeys || (exports.EditorContextKeys = EditorContextKeys = {}));
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[269/*vs/editor/contrib/inlineCompletions/browser/controller/inlineCompletionContextKeys*/], __M([1/*require*/,0/*exports*/,21/*vs/base/common/observable*/,11/*vs/base/common/strings*/,94/*vs/editor/common/core/cursorColumns*/,12/*vs/platform/contextkey/common/contextkey*/,2/*vs/base/common/lifecycle*/,3/*vs/nls*/]), function (require, exports, observable_1, strings_1, cursorColumns_1, contextkey_1, lifecycle_1, nls_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.InlineCompletionContextKeys = void 0;
    class InlineCompletionContextKeys extends lifecycle_1.Disposable {
        static { this.inlineSuggestionVisible = new contextkey_1.RawContextKey('inlineSuggestionVisible', false, (0, nls_1.localize)(1084, "Whether an inline suggestion is visible")); }
        static { this.inlineSuggestionHasIndentation = new contextkey_1.RawContextKey('inlineSuggestionHasIndentation', false, (0, nls_1.localize)(1085, "Whether the inline suggestion starts with whitespace")); }
        static { this.inlineSuggestionHasIndentationLessThanTabSize = new contextkey_1.RawContextKey('inlineSuggestionHasIndentationLessThanTabSize', true, (0, nls_1.localize)(1086, "Whether the inline suggestion starts with whitespace that is less than what would be inserted by tab")); }
        static { this.suppressSuggestions = new contextkey_1.RawContextKey('inlineSuggestionSuppressSuggestions', undefined, (0, nls_1.localize)(1087, "Whether suggestions should be suppressed for the current suggestion")); }
        constructor(contextKeyService, model) {
            super();
            this.contextKeyService = contextKeyService;
            this.model = model;
            this.inlineCompletionVisible = InlineCompletionContextKeys.inlineSuggestionVisible.bindTo(this.contextKeyService);
            this.inlineCompletionSuggestsIndentation = InlineCompletionContextKeys.inlineSuggestionHasIndentation.bindTo(this.contextKeyService);
            this.inlineCompletionSuggestsIndentationLessThanTabSize = InlineCompletionContextKeys.inlineSuggestionHasIndentationLessThanTabSize.bindTo(this.contextKeyService);
            this.suppressSuggestions = InlineCompletionContextKeys.suppressSuggestions.bindTo(this.contextKeyService);
            this._register((0, observable_1.autorun)(reader => {
                /** @description update context key: inlineCompletionVisible, suppressSuggestions */
                const model = this.model.read(reader);
                const state = model?.state.read(reader);
                const isInlineCompletionVisible = !!state?.inlineCompletion && state?.primaryGhostText !== undefined && !state?.primaryGhostText.isEmpty();
                this.inlineCompletionVisible.set(isInlineCompletionVisible);
                if (state?.primaryGhostText && state?.inlineCompletion) {
                    this.suppressSuggestions.set(state.inlineCompletion.inlineCompletion.source.inlineCompletions.suppressSuggestions);
                }
            }));
            this._register((0, observable_1.autorun)(reader => {
                /** @description update context key: inlineCompletionSuggestsIndentation, inlineCompletionSuggestsIndentationLessThanTabSize */
                const model = this.model.read(reader);
                let startsWithIndentation = false;
                let startsWithIndentationLessThanTabSize = true;
                const ghostText = model?.primaryGhostText.read(reader);
                if (!!model?.selectedSuggestItem && ghostText && ghostText.parts.length > 0) {
                    const { column, lines } = ghostText.parts[0];
                    const firstLine = lines[0];
                    const indentationEndColumn = model.textModel.getLineIndentColumn(ghostText.lineNumber);
                    const inIndentation = column <= indentationEndColumn;
                    if (inIndentation) {
                        let firstNonWsIdx = (0, strings_1.firstNonWhitespaceIndex)(firstLine);
                        if (firstNonWsIdx === -1) {
                            firstNonWsIdx = firstLine.length - 1;
                        }
                        startsWithIndentation = firstNonWsIdx > 0;
                        const tabSize = model.textModel.getOptions().tabSize;
                        const visibleColumnIndentation = cursorColumns_1.CursorColumns.visibleColumnFromColumn(firstLine, firstNonWsIdx + 1, tabSize);
                        startsWithIndentationLessThanTabSize = visibleColumnIndentation < tabSize;
                    }
                }
                this.inlineCompletionSuggestsIndentation.set(startsWithIndentation);
                this.inlineCompletionSuggestsIndentationLessThanTabSize.set(startsWithIndentationLessThanTabSize);
            }));
        }
    }
    exports.InlineCompletionContextKeys = InlineCompletionContextKeys;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[390/*vs/editor/contrib/inlineEdits/browser/consts*/], __M([1/*require*/,0/*exports*/,3/*vs/nls*/,12/*vs/platform/contextkey/common/contextkey*/]), function (require, exports, nls_1, contextkey_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.isPinnedContextKey = exports.inlineEditVisible = exports.showNextInlineEditActionId = exports.showPreviousInlineEditActionId = exports.inlineEditAcceptId = void 0;
    exports.inlineEditAcceptId = 'editor.action.inlineEdits.accept';
    exports.showPreviousInlineEditActionId = 'editor.action.inlineEdits.showPrevious';
    exports.showNextInlineEditActionId = 'editor.action.inlineEdits.showNext';
    exports.inlineEditVisible = new contextkey_1.RawContextKey('inlineEditsVisible', false, (0, nls_1.localize)(1101, "Whether an inline edit is visible"));
    exports.isPinnedContextKey = new contextkey_1.RawContextKey('inlineEditsIsPinned', false, (0, nls_1.localize)(1102, "Whether an inline edit is visible"));
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[270/*vs/editor/contrib/parameterHints/browser/provideSignatureHelp*/], __M([1/*require*/,0/*exports*/,18/*vs/base/common/cancellation*/,8/*vs/base/common/errors*/,19/*vs/base/common/types*/,22/*vs/base/common/uri*/,9/*vs/editor/common/core/position*/,27/*vs/editor/common/languages*/,17/*vs/editor/common/services/languageFeatures*/,78/*vs/editor/common/services/resolverService*/,24/*vs/platform/commands/common/commands*/,12/*vs/platform/contextkey/common/contextkey*/]), function (require, exports, cancellation_1, errors_1, types_1, uri_1, position_1, languages, languageFeatures_1, resolverService_1, commands_1, contextkey_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Context = void 0;
    exports.provideSignatureHelp = provideSignatureHelp;
    exports.Context = {
        Visible: new contextkey_1.RawContextKey('parameterHintsVisible', false),
        MultipleSignatures: new contextkey_1.RawContextKey('parameterHintsMultipleSignatures', false),
    };
    async function provideSignatureHelp(registry, model, position, context, token) {
        const supports = registry.ordered(model);
        for (const support of supports) {
            try {
                const result = await support.provideSignatureHelp(model, position, token, context);
                if (result) {
                    return result;
                }
            }
            catch (err) {
                (0, errors_1.onUnexpectedExternalError)(err);
            }
        }
        return undefined;
    }
    commands_1.CommandsRegistry.registerCommand('_executeSignatureHelpProvider', async (accessor, ...args) => {
        const [uri, position, triggerCharacter] = args;
        (0, types_1.assertType)(uri_1.URI.isUri(uri));
        (0, types_1.assertType)(position_1.Position.isIPosition(position));
        (0, types_1.assertType)(typeof triggerCharacter === 'string' || !triggerCharacter);
        const languageFeaturesService = accessor.get(languageFeatures_1.ILanguageFeaturesService);
        const ref = await accessor.get(resolverService_1.ITextModelService).createModelReference(uri);
        try {
            const result = await provideSignatureHelp(languageFeaturesService.signatureHelpProvider, ref.object.textEditorModel, position_1.Position.lift(position), {
                triggerKind: languages.SignatureHelpTriggerKind.Invoke,
                isRetrigger: false,
                triggerCharacter,
            }, cancellation_1.CancellationToken.None);
            if (!result) {
                return undefined;
            }
            setTimeout(() => result.dispose(), 0);
            return result.value;
        }
        finally {
            ref.dispose();
        }
    });
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[683/*vs/editor/contrib/parameterHints/browser/parameterHintsModel*/], __M([1/*require*/,0/*exports*/,14/*vs/base/common/async*/,8/*vs/base/common/errors*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,144/*vs/editor/common/core/characterClassifier*/,27/*vs/editor/common/languages*/,270/*vs/editor/contrib/parameterHints/browser/provideSignatureHelp*/]), function (require, exports, async_1, errors_1, event_1, lifecycle_1, characterClassifier_1, languages, provideSignatureHelp_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ParameterHintsModel = void 0;
    var ParameterHintState;
    (function (ParameterHintState) {
        ParameterHintState.Default = { type: 0 /* Type.Default */ };
        class Pending {
            constructor(request, previouslyActiveHints) {
                this.request = request;
                this.previouslyActiveHints = previouslyActiveHints;
                this.type = 2 /* Type.Pending */;
            }
        }
        ParameterHintState.Pending = Pending;
        class Active {
            constructor(hints) {
                this.hints = hints;
                this.type = 1 /* Type.Active */;
            }
        }
        ParameterHintState.Active = Active;
    })(ParameterHintState || (ParameterHintState = {}));
    class ParameterHintsModel extends lifecycle_1.Disposable {
        static { this.DEFAULT_DELAY = 120; } // ms
        constructor(editor, providers, delay = ParameterHintsModel.DEFAULT_DELAY) {
            super();
            this._onChangedHints = this._register(new event_1.Emitter());
            this.onChangedHints = this._onChangedHints.event;
            this.triggerOnType = false;
            this._state = ParameterHintState.Default;
            this._pendingTriggers = [];
            this._lastSignatureHelpResult = this._register(new lifecycle_1.MutableDisposable());
            this.triggerChars = new characterClassifier_1.CharacterSet();
            this.retriggerChars = new characterClassifier_1.CharacterSet();
            this.triggerId = 0;
            this.editor = editor;
            this.providers = providers;
            this.throttledDelayer = new async_1.Delayer(delay);
            this._register(this.editor.onDidBlurEditorWidget(() => this.cancel()));
            this._register(this.editor.onDidChangeConfiguration(() => this.onEditorConfigurationChange()));
            this._register(this.editor.onDidChangeModel(e => this.onModelChanged()));
            this._register(this.editor.onDidChangeModelLanguage(_ => this.onModelChanged()));
            this._register(this.editor.onDidChangeCursorSelection(e => this.onCursorChange(e)));
            this._register(this.editor.onDidChangeModelContent(e => this.onModelContentChange()));
            this._register(this.providers.onDidChange(this.onModelChanged, this));
            this._register(this.editor.onDidType(text => this.onDidType(text)));
            this.onEditorConfigurationChange();
            this.onModelChanged();
        }
        get state() { return this._state; }
        set state(value) {
            if (this._state.type === 2 /* ParameterHintState.Type.Pending */) {
                this._state.request.cancel();
            }
            this._state = value;
        }
        cancel(silent = false) {
            this.state = ParameterHintState.Default;
            this.throttledDelayer.cancel();
            if (!silent) {
                this._onChangedHints.fire(undefined);
            }
        }
        trigger(context, delay) {
            const model = this.editor.getModel();
            if (!model || !this.providers.has(model)) {
                return;
            }
            const triggerId = ++this.triggerId;
            this._pendingTriggers.push(context);
            this.throttledDelayer.trigger(() => {
                return this.doTrigger(triggerId);
            }, delay)
                .catch(errors_1.onUnexpectedError);
        }
        next() {
            if (this.state.type !== 1 /* ParameterHintState.Type.Active */) {
                return;
            }
            const length = this.state.hints.signatures.length;
            const activeSignature = this.state.hints.activeSignature;
            const last = (activeSignature % length) === (length - 1);
            const cycle = this.editor.getOption(86 /* EditorOption.parameterHints */).cycle;
            // If there is only one signature, or we're on last signature of list
            if ((length < 2 || last) && !cycle) {
                this.cancel();
                return;
            }
            this.updateActiveSignature(last && cycle ? 0 : activeSignature + 1);
        }
        previous() {
            if (this.state.type !== 1 /* ParameterHintState.Type.Active */) {
                return;
            }
            const length = this.state.hints.signatures.length;
            const activeSignature = this.state.hints.activeSignature;
            const first = activeSignature === 0;
            const cycle = this.editor.getOption(86 /* EditorOption.parameterHints */).cycle;
            // If there is only one signature, or we're on first signature of list
            if ((length < 2 || first) && !cycle) {
                this.cancel();
                return;
            }
            this.updateActiveSignature(first && cycle ? length - 1 : activeSignature - 1);
        }
        updateActiveSignature(activeSignature) {
            if (this.state.type !== 1 /* ParameterHintState.Type.Active */) {
                return;
            }
            this.state = new ParameterHintState.Active({ ...this.state.hints, activeSignature });
            this._onChangedHints.fire(this.state.hints);
        }
        async doTrigger(triggerId) {
            const isRetrigger = this.state.type === 1 /* ParameterHintState.Type.Active */ || this.state.type === 2 /* ParameterHintState.Type.Pending */;
            const activeSignatureHelp = this.getLastActiveHints();
            this.cancel(true);
            if (this._pendingTriggers.length === 0) {
                return false;
            }
            const context = this._pendingTriggers.reduce(mergeTriggerContexts);
            this._pendingTriggers = [];
            const triggerContext = {
                triggerKind: context.triggerKind,
                triggerCharacter: context.triggerCharacter,
                isRetrigger: isRetrigger,
                activeSignatureHelp: activeSignatureHelp
            };
            if (!this.editor.hasModel()) {
                return false;
            }
            const model = this.editor.getModel();
            const position = this.editor.getPosition();
            this.state = new ParameterHintState.Pending((0, async_1.createCancelablePromise)(token => (0, provideSignatureHelp_1.provideSignatureHelp)(this.providers, model, position, triggerContext, token)), activeSignatureHelp);
            try {
                const result = await this.state.request;
                // Check that we are still resolving the correct signature help
                if (triggerId !== this.triggerId) {
                    result?.dispose();
                    return false;
                }
                if (!result || !result.value.signatures || result.value.signatures.length === 0) {
                    result?.dispose();
                    this._lastSignatureHelpResult.clear();
                    this.cancel();
                    return false;
                }
                else {
                    this.state = new ParameterHintState.Active(result.value);
                    this._lastSignatureHelpResult.value = result;
                    this._onChangedHints.fire(this.state.hints);
                    return true;
                }
            }
            catch (error) {
                if (triggerId === this.triggerId) {
                    this.state = ParameterHintState.Default;
                }
                (0, errors_1.onUnexpectedError)(error);
                return false;
            }
        }
        getLastActiveHints() {
            switch (this.state.type) {
                case 1 /* ParameterHintState.Type.Active */: return this.state.hints;
                case 2 /* ParameterHintState.Type.Pending */: return this.state.previouslyActiveHints;
                default: return undefined;
            }
        }
        get isTriggered() {
            return this.state.type === 1 /* ParameterHintState.Type.Active */
                || this.state.type === 2 /* ParameterHintState.Type.Pending */
                || this.throttledDelayer.isTriggered();
        }
        onModelChanged() {
            this.cancel();
            this.triggerChars.clear();
            this.retriggerChars.clear();
            const model = this.editor.getModel();
            if (!model) {
                return;
            }
            for (const support of this.providers.ordered(model)) {
                for (const ch of support.signatureHelpTriggerCharacters || []) {
                    if (ch.length) {
                        const charCode = ch.charCodeAt(0);
                        this.triggerChars.add(charCode);
                        // All trigger characters are also considered retrigger characters
                        this.retriggerChars.add(charCode);
                    }
                }
                for (const ch of support.signatureHelpRetriggerCharacters || []) {
                    if (ch.length) {
                        this.retriggerChars.add(ch.charCodeAt(0));
                    }
                }
            }
        }
        onDidType(text) {
            if (!this.triggerOnType) {
                return;
            }
            const lastCharIndex = text.length - 1;
            const triggerCharCode = text.charCodeAt(lastCharIndex);
            if (this.triggerChars.has(triggerCharCode) || this.isTriggered && this.retriggerChars.has(triggerCharCode)) {
                this.trigger({
                    triggerKind: languages.SignatureHelpTriggerKind.TriggerCharacter,
                    triggerCharacter: text.charAt(lastCharIndex),
                });
            }
        }
        onCursorChange(e) {
            if (e.source === 'mouse') {
                this.cancel();
            }
            else if (this.isTriggered) {
                this.trigger({ triggerKind: languages.SignatureHelpTriggerKind.ContentChange });
            }
        }
        onModelContentChange() {
            if (this.isTriggered) {
                this.trigger({ triggerKind: languages.SignatureHelpTriggerKind.ContentChange });
            }
        }
        onEditorConfigurationChange() {
            this.triggerOnType = this.editor.getOption(86 /* EditorOption.parameterHints */).enabled;
            if (!this.triggerOnType) {
                this.cancel();
            }
        }
        dispose() {
            this.cancel(true);
            super.dispose();
        }
    }
    exports.ParameterHintsModel = ParameterHintsModel;
    function mergeTriggerContexts(previous, current) {
        switch (current.triggerKind) {
            case languages.SignatureHelpTriggerKind.Invoke:
                // Invoke overrides previous triggers.
                return current;
            case languages.SignatureHelpTriggerKind.ContentChange:
                // Ignore content changes triggers
                return previous;
            case languages.SignatureHelpTriggerKind.TriggerCharacter:
            default:
                return current;
        }
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[684/*vs/editor/contrib/suggest/browser/suggestAlternatives*/], __M([1/*require*/,0/*exports*/,12/*vs/platform/contextkey/common/contextkey*/]), function (require, exports, contextkey_1) {
    "use strict";
    var SuggestAlternatives_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SuggestAlternatives = void 0;
    let SuggestAlternatives = class SuggestAlternatives {
        static { SuggestAlternatives_1 = this; }
        static { this.OtherSuggestions = new contextkey_1.RawContextKey('hasOtherSuggestions', false); }
        constructor(_editor, contextKeyService) {
            this._editor = _editor;
            this._index = 0;
            this._ckOtherSuggestions = SuggestAlternatives_1.OtherSuggestions.bindTo(contextKeyService);
        }
        dispose() {
            this.reset();
        }
        reset() {
            this._ckOtherSuggestions.reset();
            this._listener?.dispose();
            this._model = undefined;
            this._acceptNext = undefined;
            this._ignore = false;
        }
        set({ model, index }, acceptNext) {
            // no suggestions -> nothing to do
            if (model.items.length === 0) {
                this.reset();
                return;
            }
            // no alternative suggestions -> nothing to do
            const nextIndex = SuggestAlternatives_1._moveIndex(true, model, index);
            if (nextIndex === index) {
                this.reset();
                return;
            }
            this._acceptNext = acceptNext;
            this._model = model;
            this._index = index;
            this._listener = this._editor.onDidChangeCursorPosition(() => {
                if (!this._ignore) {
                    this.reset();
                }
            });
            this._ckOtherSuggestions.set(true);
        }
        static _moveIndex(fwd, model, index) {
            let newIndex = index;
            for (let rounds = model.items.length; rounds > 0; rounds--) {
                newIndex = (newIndex + model.items.length + (fwd ? +1 : -1)) % model.items.length;
                if (newIndex === index) {
                    break;
                }
                if (!model.items[newIndex].completion.additionalTextEdits) {
                    break;
                }
            }
            return newIndex;
        }
        next() {
            this._move(true);
        }
        prev() {
            this._move(false);
        }
        _move(fwd) {
            if (!this._model) {
                // nothing to reason about
                return;
            }
            try {
                this._ignore = true;
                this._index = SuggestAlternatives_1._moveIndex(fwd, this._model, this._index);
                this._acceptNext({ index: this._index, item: this._model.items[this._index], model: this._model });
            }
            finally {
                this._ignore = false;
            }
        }
    };
    exports.SuggestAlternatives = SuggestAlternatives;
    exports.SuggestAlternatives = SuggestAlternatives = SuggestAlternatives_1 = __decorate([
        __param(1, contextkey_1.IContextKeyService)
    ], SuggestAlternatives);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[685/*vs/editor/contrib/suggest/browser/wordContextKey*/], __M([1/*require*/,0/*exports*/,12/*vs/platform/contextkey/common/contextkey*/]), function (require, exports, contextkey_1) {
    "use strict";
    var WordContextKey_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.WordContextKey = void 0;
    let WordContextKey = class WordContextKey {
        static { WordContextKey_1 = this; }
        static { this.AtEnd = new contextkey_1.RawContextKey('atEndOfWord', false); }
        constructor(_editor, contextKeyService) {
            this._editor = _editor;
            this._enabled = false;
            this._ckAtEnd = WordContextKey_1.AtEnd.bindTo(contextKeyService);
            this._configListener = this._editor.onDidChangeConfiguration(e => e.hasChanged(124 /* EditorOption.tabCompletion */) && this._update());
            this._update();
        }
        dispose() {
            this._configListener.dispose();
            this._selectionListener?.dispose();
            this._ckAtEnd.reset();
        }
        _update() {
            // only update this when tab completions are enabled
            const enabled = this._editor.getOption(124 /* EditorOption.tabCompletion */) === 'on';
            if (this._enabled === enabled) {
                return;
            }
            this._enabled = enabled;
            if (this._enabled) {
                const checkForWordEnd = () => {
                    if (!this._editor.hasModel()) {
                        this._ckAtEnd.set(false);
                        return;
                    }
                    const model = this._editor.getModel();
                    const selection = this._editor.getSelection();
                    const word = model.getWordAtPosition(selection.getStartPosition());
                    if (!word) {
                        this._ckAtEnd.set(false);
                        return;
                    }
                    this._ckAtEnd.set(word.endColumn === selection.getStartPosition().column);
                };
                this._selectionListener = this._editor.onDidChangeCursorSelection(checkForWordEnd);
                checkForWordEnd();
            }
            else if (this._selectionListener) {
                this._ckAtEnd.reset();
                this._selectionListener.dispose();
                this._selectionListener = undefined;
            }
        }
    };
    exports.WordContextKey = WordContextKey;
    exports.WordContextKey = WordContextKey = WordContextKey_1 = __decorate([
        __param(1, contextkey_1.IContextKeyService)
    ], WordContextKey);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[61/*vs/platform/accessibility/common/accessibility*/], __M([1/*require*/,0/*exports*/,12/*vs/platform/contextkey/common/contextkey*/,7/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, contextkey_1, instantiation_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CONTEXT_ACCESSIBILITY_MODE_ENABLED = exports.IAccessibilityService = void 0;
    exports.IAccessibilityService = (0, instantiation_1.createDecorator)('accessibilityService');
    exports.CONTEXT_ACCESSIBILITY_MODE_ENABLED = new contextkey_1.RawContextKey('accessibilityModeEnabled', false);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[686/*vs/editor/browser/config/editorConfiguration*/], __M([1/*require*/,0/*exports*/,64/*vs/base/browser/browser*/,13/*vs/base/common/arrays*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,60/*vs/base/common/objects*/,16/*vs/base/common/platform*/,362/*vs/editor/browser/config/elementSizeObserver*/,366/*vs/editor/browser/config/fontMeasurements*/,546/*vs/editor/browser/config/migrateOptions*/,229/*vs/editor/browser/config/tabFocus*/,37/*vs/editor/common/config/editorOptions*/,165/*vs/editor/common/config/editorZoom*/,261/*vs/editor/common/config/fontInfo*/,61/*vs/platform/accessibility/common/accessibility*/,5/*vs/base/browser/dom*/,253/*vs/base/browser/pixelRatio*/]), function (require, exports, browser, arrays, event_1, lifecycle_1, objects, platform, elementSizeObserver_1, fontMeasurements_1, migrateOptions_1, tabFocus_1, editorOptions_1, editorZoom_1, fontInfo_1, accessibility_1, dom_1, pixelRatio_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ComputedEditorOptions = exports.EditorConfiguration = void 0;
    let EditorConfiguration = class EditorConfiguration extends lifecycle_1.Disposable {
        constructor(isSimpleWidget, contextMenuId, options, container, _accessibilityService) {
            super();
            this._accessibilityService = _accessibilityService;
            this._onDidChange = this._register(new event_1.Emitter());
            this.onDidChange = this._onDidChange.event;
            this._onDidChangeFast = this._register(new event_1.Emitter());
            this.onDidChangeFast = this._onDidChangeFast.event;
            this._isDominatedByLongLines = false;
            this._viewLineCount = 1;
            this._lineNumbersDigitCount = 1;
            this._reservedHeight = 0;
            this._glyphMarginDecorationLaneCount = 1;
            this._computeOptionsMemory = new editorOptions_1.ComputeOptionsMemory();
            this.isSimpleWidget = isSimpleWidget;
            this.contextMenuId = contextMenuId;
            this._containerObserver = this._register(new elementSizeObserver_1.ElementSizeObserver(container, options.dimension));
            this._targetWindowId = (0, dom_1.getWindow)(container).vscodeWindowId;
            this._rawOptions = deepCloneAndMigrateOptions(options);
            this._validatedOptions = EditorOptionsUtil.validateOptions(this._rawOptions);
            this.options = this._computeOptions();
            if (this.options.get(13 /* EditorOption.automaticLayout */)) {
                this._containerObserver.startObserving();
            }
            this._register(editorZoom_1.EditorZoom.onDidChangeZoomLevel(() => this._recomputeOptions()));
            this._register(tabFocus_1.TabFocus.onDidChangeTabFocus(() => this._recomputeOptions()));
            this._register(this._containerObserver.onDidChange(() => this._recomputeOptions()));
            this._register(fontMeasurements_1.FontMeasurements.onDidChange(() => this._recomputeOptions()));
            this._register(pixelRatio_1.PixelRatio.getInstance((0, dom_1.getWindow)(container)).onDidChange(() => this._recomputeOptions()));
            this._register(this._accessibilityService.onDidChangeScreenReaderOptimized(() => this._recomputeOptions()));
        }
        _recomputeOptions() {
            const newOptions = this._computeOptions();
            const changeEvent = EditorOptionsUtil.checkEquals(this.options, newOptions);
            if (changeEvent === null) {
                // nothing changed!
                return;
            }
            this.options = newOptions;
            this._onDidChangeFast.fire(changeEvent);
            this._onDidChange.fire(changeEvent);
        }
        _computeOptions() {
            const partialEnv = this._readEnvConfiguration();
            const bareFontInfo = fontInfo_1.BareFontInfo.createFromValidatedSettings(this._validatedOptions, partialEnv.pixelRatio, this.isSimpleWidget);
            const fontInfo = this._readFontInfo(bareFontInfo);
            const env = {
                memory: this._computeOptionsMemory,
                outerWidth: partialEnv.outerWidth,
                outerHeight: partialEnv.outerHeight - this._reservedHeight,
                fontInfo: fontInfo,
                extraEditorClassName: partialEnv.extraEditorClassName,
                isDominatedByLongLines: this._isDominatedByLongLines,
                viewLineCount: this._viewLineCount,
                lineNumbersDigitCount: this._lineNumbersDigitCount,
                emptySelectionClipboard: partialEnv.emptySelectionClipboard,
                pixelRatio: partialEnv.pixelRatio,
                tabFocusMode: tabFocus_1.TabFocus.getTabFocusMode(),
                accessibilitySupport: partialEnv.accessibilitySupport,
                glyphMarginDecorationLaneCount: this._glyphMarginDecorationLaneCount
            };
            return EditorOptionsUtil.computeOptions(this._validatedOptions, env);
        }
        _readEnvConfiguration() {
            return {
                extraEditorClassName: getExtraEditorClassName(),
                outerWidth: this._containerObserver.getWidth(),
                outerHeight: this._containerObserver.getHeight(),
                emptySelectionClipboard: browser.isWebKit || browser.isFirefox,
                pixelRatio: pixelRatio_1.PixelRatio.getInstance((0, dom_1.getWindowById)(this._targetWindowId, true).window).value,
                accessibilitySupport: (this._accessibilityService.isScreenReaderOptimized()
                    ? 2 /* AccessibilitySupport.Enabled */
                    : this._accessibilityService.getAccessibilitySupport())
            };
        }
        _readFontInfo(bareFontInfo) {
            return fontMeasurements_1.FontMeasurements.readFontInfo((0, dom_1.getWindowById)(this._targetWindowId, true).window, bareFontInfo);
        }
        getRawOptions() {
            return this._rawOptions;
        }
        updateOptions(_newOptions) {
            const newOptions = deepCloneAndMigrateOptions(_newOptions);
            const didChange = EditorOptionsUtil.applyUpdate(this._rawOptions, newOptions);
            if (!didChange) {
                return;
            }
            this._validatedOptions = EditorOptionsUtil.validateOptions(this._rawOptions);
            this._recomputeOptions();
        }
        observeContainer(dimension) {
            this._containerObserver.observe(dimension);
        }
        setIsDominatedByLongLines(isDominatedByLongLines) {
            if (this._isDominatedByLongLines === isDominatedByLongLines) {
                return;
            }
            this._isDominatedByLongLines = isDominatedByLongLines;
            this._recomputeOptions();
        }
        setModelLineCount(modelLineCount) {
            const lineNumbersDigitCount = digitCount(modelLineCount);
            if (this._lineNumbersDigitCount === lineNumbersDigitCount) {
                return;
            }
            this._lineNumbersDigitCount = lineNumbersDigitCount;
            this._recomputeOptions();
        }
        setViewLineCount(viewLineCount) {
            if (this._viewLineCount === viewLineCount) {
                return;
            }
            this._viewLineCount = viewLineCount;
            this._recomputeOptions();
        }
        setReservedHeight(reservedHeight) {
            if (this._reservedHeight === reservedHeight) {
                return;
            }
            this._reservedHeight = reservedHeight;
            this._recomputeOptions();
        }
        setGlyphMarginDecorationLaneCount(decorationLaneCount) {
            if (this._glyphMarginDecorationLaneCount === decorationLaneCount) {
                return;
            }
            this._glyphMarginDecorationLaneCount = decorationLaneCount;
            this._recomputeOptions();
        }
    };
    exports.EditorConfiguration = EditorConfiguration;
    exports.EditorConfiguration = EditorConfiguration = __decorate([
        __param(4, accessibility_1.IAccessibilityService)
    ], EditorConfiguration);
    function digitCount(n) {
        let r = 0;
        while (n) {
            n = Math.floor(n / 10);
            r++;
        }
        return r ? r : 1;
    }
    function getExtraEditorClassName() {
        let extra = '';
        if (!browser.isSafari && !browser.isWebkitWebView) {
            // Use user-select: none in all browsers except Safari and native macOS WebView
            extra += 'no-user-select ';
        }
        if (browser.isSafari) {
            // See https://github.com/microsoft/vscode/issues/108822
            extra += 'no-minimap-shadow ';
            extra += 'enable-user-select ';
        }
        if (platform.isMacintosh) {
            extra += 'mac ';
        }
        return extra;
    }
    class ValidatedEditorOptions {
        constructor() {
            this._values = [];
        }
        _read(option) {
            return this._values[option];
        }
        get(id) {
            return this._values[id];
        }
        _write(option, value) {
            this._values[option] = value;
        }
    }
    class ComputedEditorOptions {
        constructor() {
            this._values = [];
        }
        _read(id) {
            if (id >= this._values.length) {
                throw new Error('Cannot read uninitialized value');
            }
            return this._values[id];
        }
        get(id) {
            return this._read(id);
        }
        _write(id, value) {
            this._values[id] = value;
        }
    }
    exports.ComputedEditorOptions = ComputedEditorOptions;
    class EditorOptionsUtil {
        static validateOptions(options) {
            const result = new ValidatedEditorOptions();
            for (const editorOption of editorOptions_1.editorOptionsRegistry) {
                const value = (editorOption.name === '_never_' ? undefined : options[editorOption.name]);
                result._write(editorOption.id, editorOption.validate(value));
            }
            return result;
        }
        static computeOptions(options, env) {
            const result = new ComputedEditorOptions();
            for (const editorOption of editorOptions_1.editorOptionsRegistry) {
                result._write(editorOption.id, editorOption.compute(env, result, options._read(editorOption.id)));
            }
            return result;
        }
        static _deepEquals(a, b) {
            if (typeof a !== 'object' || typeof b !== 'object' || !a || !b) {
                return a === b;
            }
            if (Array.isArray(a) || Array.isArray(b)) {
                return (Array.isArray(a) && Array.isArray(b) ? arrays.equals(a, b) : false);
            }
            if (Object.keys(a).length !== Object.keys(b).length) {
                return false;
            }
            for (const key in a) {
                if (!EditorOptionsUtil._deepEquals(a[key], b[key])) {
                    return false;
                }
            }
            return true;
        }
        static checkEquals(a, b) {
            const result = [];
            let somethingChanged = false;
            for (const editorOption of editorOptions_1.editorOptionsRegistry) {
                const changed = !EditorOptionsUtil._deepEquals(a._read(editorOption.id), b._read(editorOption.id));
                result[editorOption.id] = changed;
                if (changed) {
                    somethingChanged = true;
                }
            }
            return (somethingChanged ? new editorOptions_1.ConfigurationChangedEvent(result) : null);
        }
        /**
         * Returns true if something changed.
         * Modifies `options`.
        */
        static applyUpdate(options, update) {
            let changed = false;
            for (const editorOption of editorOptions_1.editorOptionsRegistry) {
                if (update.hasOwnProperty(editorOption.name)) {
                    const result = editorOption.applyUpdate(options[editorOption.name], update[editorOption.name]);
                    options[editorOption.name] = result.newValue;
                    changed = changed || result.didChange;
                }
            }
            return changed;
        }
    }
    function deepCloneAndMigrateOptions(_options) {
        const options = objects.deepClone(_options);
        (0, migrateOptions_1.migrateOptions)(options);
        return options;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[687/*vs/platform/contextkey/browser/contextKeyService*/], __M([1/*require*/,0/*exports*/,6/*vs/base/common/event*/,53/*vs/base/common/iterator*/,2/*vs/base/common/lifecycle*/,60/*vs/base/common/objects*/,225/*vs/base/common/ternarySearchTree*/,22/*vs/base/common/uri*/,3/*vs/nls*/,24/*vs/platform/commands/common/commands*/,28/*vs/platform/configuration/common/configuration*/,12/*vs/platform/contextkey/common/contextkey*/]), function (require, exports, event_1, iterator_1, lifecycle_1, objects_1, ternarySearchTree_1, uri_1, nls_1, commands_1, configuration_1, contextkey_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ContextKeyService = exports.AbstractContextKeyService = exports.Context = void 0;
    exports.setContext = setContext;
    const KEYBINDING_CONTEXT_ATTR = 'data-keybinding-context';
    class Context {
        constructor(id, parent) {
            this._id = id;
            this._parent = parent;
            this._value = Object.create(null);
            this._value['_contextId'] = id;
        }
        get value() {
            return { ...this._value };
        }
        setValue(key, value) {
            // console.log('SET ' + key + ' = ' + value + ' ON ' + this._id);
            if (this._value[key] !== value) {
                this._value[key] = value;
                return true;
            }
            return false;
        }
        removeValue(key) {
            // console.log('REMOVE ' + key + ' FROM ' + this._id);
            if (key in this._value) {
                delete this._value[key];
                return true;
            }
            return false;
        }
        getValue(key) {
            const ret = this._value[key];
            if (typeof ret === 'undefined' && this._parent) {
                return this._parent.getValue(key);
            }
            return ret;
        }
    }
    exports.Context = Context;
    class NullContext extends Context {
        static { this.INSTANCE = new NullContext(); }
        constructor() {
            super(-1, null);
        }
        setValue(key, value) {
            return false;
        }
        removeValue(key) {
            return false;
        }
        getValue(key) {
            return undefined;
        }
    }
    class ConfigAwareContextValuesContainer extends Context {
        static { this._keyPrefix = 'config.'; }
        constructor(id, _configurationService, emitter) {
            super(id, null);
            this._configurationService = _configurationService;
            this._values = ternarySearchTree_1.TernarySearchTree.forConfigKeys();
            this._listener = this._configurationService.onDidChangeConfiguration(event => {
                if (event.source === 7 /* ConfigurationTarget.DEFAULT */) {
                    // new setting, reset everything
                    const allKeys = Array.from(this._values, ([k]) => k);
                    this._values.clear();
                    emitter.fire(new ArrayContextKeyChangeEvent(allKeys));
                }
                else {
                    const changedKeys = [];
                    for (const configKey of event.affectedKeys) {
                        const contextKey = `config.${configKey}`;
                        const cachedItems = this._values.findSuperstr(contextKey);
                        if (cachedItems !== undefined) {
                            changedKeys.push(...iterator_1.Iterable.map(cachedItems, ([key]) => key));
                            this._values.deleteSuperstr(contextKey);
                        }
                        if (this._values.has(contextKey)) {
                            changedKeys.push(contextKey);
                            this._values.delete(contextKey);
                        }
                    }
                    emitter.fire(new ArrayContextKeyChangeEvent(changedKeys));
                }
            });
        }
        dispose() {
            this._listener.dispose();
        }
        getValue(key) {
            if (key.indexOf(ConfigAwareContextValuesContainer._keyPrefix) !== 0) {
                return super.getValue(key);
            }
            if (this._values.has(key)) {
                return this._values.get(key);
            }
            const configKey = key.substr(ConfigAwareContextValuesContainer._keyPrefix.length);
            const configValue = this._configurationService.getValue(configKey);
            let value = undefined;
            switch (typeof configValue) {
                case 'number':
                case 'boolean':
                case 'string':
                    value = configValue;
                    break;
                default:
                    if (Array.isArray(configValue)) {
                        value = JSON.stringify(configValue);
                    }
                    else {
                        value = configValue;
                    }
            }
            this._values.set(key, value);
            return value;
        }
        setValue(key, value) {
            return super.setValue(key, value);
        }
        removeValue(key) {
            return super.removeValue(key);
        }
    }
    class ContextKey {
        constructor(service, key, defaultValue) {
            this._service = service;
            this._key = key;
            this._defaultValue = defaultValue;
            this.reset();
        }
        set(value) {
            this._service.setContext(this._key, value);
        }
        reset() {
            if (typeof this._defaultValue === 'undefined') {
                this._service.removeContext(this._key);
            }
            else {
                this._service.setContext(this._key, this._defaultValue);
            }
        }
        get() {
            return this._service.getContextKeyValue(this._key);
        }
    }
    class SimpleContextKeyChangeEvent {
        constructor(key) {
            this.key = key;
        }
        affectsSome(keys) {
            return keys.has(this.key);
        }
        allKeysContainedIn(keys) {
            return this.affectsSome(keys);
        }
    }
    class ArrayContextKeyChangeEvent {
        constructor(keys) {
            this.keys = keys;
        }
        affectsSome(keys) {
            for (const key of this.keys) {
                if (keys.has(key)) {
                    return true;
                }
            }
            return false;
        }
        allKeysContainedIn(keys) {
            return this.keys.every(key => keys.has(key));
        }
    }
    class CompositeContextKeyChangeEvent {
        constructor(events) {
            this.events = events;
        }
        affectsSome(keys) {
            for (const e of this.events) {
                if (e.affectsSome(keys)) {
                    return true;
                }
            }
            return false;
        }
        allKeysContainedIn(keys) {
            return this.events.every(evt => evt.allKeysContainedIn(keys));
        }
    }
    function allEventKeysInContext(event, context) {
        return event.allKeysContainedIn(new Set(Object.keys(context)));
    }
    class AbstractContextKeyService extends lifecycle_1.Disposable {
        constructor(myContextId) {
            super();
            this._onDidChangeContext = this._register(new event_1.PauseableEmitter({ merge: input => new CompositeContextKeyChangeEvent(input) }));
            this.onDidChangeContext = this._onDidChangeContext.event;
            this._isDisposed = false;
            this._myContextId = myContextId;
        }
        createKey(key, defaultValue) {
            if (this._isDisposed) {
                throw new Error(`AbstractContextKeyService has been disposed`);
            }
            return new ContextKey(this, key, defaultValue);
        }
        bufferChangeEvents(callback) {
            this._onDidChangeContext.pause();
            try {
                callback();
            }
            finally {
                this._onDidChangeContext.resume();
            }
        }
        createScoped(domNode) {
            if (this._isDisposed) {
                throw new Error(`AbstractContextKeyService has been disposed`);
            }
            return new ScopedContextKeyService(this, domNode);
        }
        contextMatchesRules(rules) {
            if (this._isDisposed) {
                throw new Error(`AbstractContextKeyService has been disposed`);
            }
            const context = this.getContextValuesContainer(this._myContextId);
            const result = (rules ? rules.evaluate(context) : true);
            // console.group(rules.serialize() + ' -> ' + result);
            // rules.keys().forEach(key => { console.log(key, ctx[key]); });
            // console.groupEnd();
            return result;
        }
        getContextKeyValue(key) {
            if (this._isDisposed) {
                return undefined;
            }
            return this.getContextValuesContainer(this._myContextId).getValue(key);
        }
        setContext(key, value) {
            if (this._isDisposed) {
                return;
            }
            const myContext = this.getContextValuesContainer(this._myContextId);
            if (!myContext) {
                return;
            }
            if (myContext.setValue(key, value)) {
                this._onDidChangeContext.fire(new SimpleContextKeyChangeEvent(key));
            }
        }
        removeContext(key) {
            if (this._isDisposed) {
                return;
            }
            if (this.getContextValuesContainer(this._myContextId).removeValue(key)) {
                this._onDidChangeContext.fire(new SimpleContextKeyChangeEvent(key));
            }
        }
        getContext(target) {
            if (this._isDisposed) {
                return NullContext.INSTANCE;
            }
            return this.getContextValuesContainer(findContextAttr(target));
        }
        dispose() {
            super.dispose();
            this._isDisposed = true;
        }
    }
    exports.AbstractContextKeyService = AbstractContextKeyService;
    let ContextKeyService = class ContextKeyService extends AbstractContextKeyService {
        constructor(configurationService) {
            super(0);
            this._contexts = new Map();
            this._lastContextId = 0;
            const myContext = this._register(new ConfigAwareContextValuesContainer(this._myContextId, configurationService, this._onDidChangeContext));
            this._contexts.set(this._myContextId, myContext);
            // Uncomment this to see the contexts continuously logged
            // let lastLoggedValue: string | null = null;
            // setInterval(() => {
            // 	let values = Object.keys(this._contexts).map((key) => this._contexts[key]);
            // 	let logValue = values.map(v => JSON.stringify(v._value, null, '\t')).join('\n');
            // 	if (lastLoggedValue !== logValue) {
            // 		lastLoggedValue = logValue;
            // 		console.log(lastLoggedValue);
            // 	}
            // }, 2000);
        }
        getContextValuesContainer(contextId) {
            if (this._isDisposed) {
                return NullContext.INSTANCE;
            }
            return this._contexts.get(contextId) || NullContext.INSTANCE;
        }
        createChildContext(parentContextId = this._myContextId) {
            if (this._isDisposed) {
                throw new Error(`ContextKeyService has been disposed`);
            }
            const id = (++this._lastContextId);
            this._contexts.set(id, new Context(id, this.getContextValuesContainer(parentContextId)));
            return id;
        }
        disposeContext(contextId) {
            if (!this._isDisposed) {
                this._contexts.delete(contextId);
            }
        }
    };
    exports.ContextKeyService = ContextKeyService;
    exports.ContextKeyService = ContextKeyService = __decorate([
        __param(0, configuration_1.IConfigurationService)
    ], ContextKeyService);
    class ScopedContextKeyService extends AbstractContextKeyService {
        constructor(parent, domNode) {
            super(parent.createChildContext());
            this._parentChangeListener = this._register(new lifecycle_1.MutableDisposable());
            this._parent = parent;
            this._updateParentChangeListener();
            this._domNode = domNode;
            if (this._domNode.hasAttribute(KEYBINDING_CONTEXT_ATTR)) {
                let extraInfo = '';
                if (this._domNode.classList) {
                    extraInfo = Array.from(this._domNode.classList.values()).join(', ');
                }
                console.error(`Element already has context attribute${extraInfo ? ': ' + extraInfo : ''}`);
            }
            this._domNode.setAttribute(KEYBINDING_CONTEXT_ATTR, String(this._myContextId));
        }
        _updateParentChangeListener() {
            // Forward parent events to this listener. Parent will change.
            this._parentChangeListener.value = this._parent.onDidChangeContext(e => {
                const thisContainer = this._parent.getContextValuesContainer(this._myContextId);
                const thisContextValues = thisContainer.value;
                if (!allEventKeysInContext(e, thisContextValues)) {
                    this._onDidChangeContext.fire(e);
                }
            });
        }
        dispose() {
            if (this._isDisposed) {
                return;
            }
            this._parent.disposeContext(this._myContextId);
            this._domNode.removeAttribute(KEYBINDING_CONTEXT_ATTR);
            super.dispose();
        }
        getContextValuesContainer(contextId) {
            if (this._isDisposed) {
                return NullContext.INSTANCE;
            }
            return this._parent.getContextValuesContainer(contextId);
        }
        createChildContext(parentContextId = this._myContextId) {
            if (this._isDisposed) {
                throw new Error(`ScopedContextKeyService has been disposed`);
            }
            return this._parent.createChildContext(parentContextId);
        }
        disposeContext(contextId) {
            if (this._isDisposed) {
                return;
            }
            this._parent.disposeContext(contextId);
        }
    }
    function findContextAttr(domNode) {
        while (domNode) {
            if (domNode.hasAttribute(KEYBINDING_CONTEXT_ATTR)) {
                const attr = domNode.getAttribute(KEYBINDING_CONTEXT_ATTR);
                if (attr) {
                    return parseInt(attr, 10);
                }
                return NaN;
            }
            domNode = domNode.parentElement;
        }
        return 0;
    }
    function setContext(accessor, contextKey, contextValue) {
        const contextKeyService = accessor.get(contextkey_1.IContextKeyService);
        contextKeyService.createKey(String(contextKey), stringifyURIs(contextValue));
    }
    function stringifyURIs(contextValue) {
        return (0, objects_1.cloneAndChange)(contextValue, (obj) => {
            if (typeof obj === 'object' && obj.$mid === 1 /* MarshalledId.Uri */) {
                return uri_1.URI.revive(obj).toString();
            }
            if (obj instanceof uri_1.URI) {
                return obj.toString();
            }
            return undefined;
        });
    }
    commands_1.CommandsRegistry.registerCommand('_setContext', setContext);
    commands_1.CommandsRegistry.registerCommand({
        id: 'getContextKeyInfo',
        handler() {
            return [...contextkey_1.RawContextKey.all()].sort((a, b) => a.key.localeCompare(b.key));
        },
        metadata: {
            description: (0, nls_1.localize)(1513, "A command that returns information about context keys"),
            args: []
        }
    });
    commands_1.CommandsRegistry.registerCommand('_generateContextKeyInfo', function () {
        const result = [];
        const seen = new Set();
        for (const info of contextkey_1.RawContextKey.all()) {
            if (!seen.has(info.key)) {
                seen.add(info.key);
                result.push(info);
            }
        }
        result.sort((a, b) => a.key.localeCompare(b.key));
        console.log(JSON.stringify(result, undefined, 2));
    });
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[179/*vs/platform/contextkey/common/contextkeys*/], __M([1/*require*/,0/*exports*/,16/*vs/base/common/platform*/,3/*vs/nls*/,12/*vs/platform/contextkey/common/contextkey*/]), function (require, exports, platform_1, nls_1, contextkey_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.InputFocusedContext = exports.InputFocusedContextKey = exports.ProductQualityContext = exports.IsDevelopmentContext = exports.IsMobileContext = exports.IsIOSContext = exports.IsMacNativeContext = exports.IsWebContext = exports.IsWindowsContext = exports.IsLinuxContext = exports.IsMacContext = void 0;
    exports.IsMacContext = new contextkey_1.RawContextKey('isMac', platform_1.isMacintosh, (0, nls_1.localize)(1523, "Whether the operating system is macOS"));
    exports.IsLinuxContext = new contextkey_1.RawContextKey('isLinux', platform_1.isLinux, (0, nls_1.localize)(1524, "Whether the operating system is Linux"));
    exports.IsWindowsContext = new contextkey_1.RawContextKey('isWindows', platform_1.isWindows, (0, nls_1.localize)(1525, "Whether the operating system is Windows"));
    exports.IsWebContext = new contextkey_1.RawContextKey('isWeb', platform_1.isWeb, (0, nls_1.localize)(1526, "Whether the platform is a web browser"));
    exports.IsMacNativeContext = new contextkey_1.RawContextKey('isMacNative', platform_1.isMacintosh && !platform_1.isWeb, (0, nls_1.localize)(1527, "Whether the operating system is macOS on a non-browser platform"));
    exports.IsIOSContext = new contextkey_1.RawContextKey('isIOS', platform_1.isIOS, (0, nls_1.localize)(1528, "Whether the operating system is iOS"));
    exports.IsMobileContext = new contextkey_1.RawContextKey('isMobile', platform_1.isMobile, (0, nls_1.localize)(1529, "Whether the platform is a mobile web browser"));
    exports.IsDevelopmentContext = new contextkey_1.RawContextKey('isDevelopment', false, true);
    exports.ProductQualityContext = new contextkey_1.RawContextKey('productQualityType', '', (0, nls_1.localize)(1530, "Quality type of VS Code"));
    exports.InputFocusedContextKey = 'inputFocus';
    exports.InputFocusedContext = new contextkey_1.RawContextKey(exports.InputFocusedContextKey, false, (0, nls_1.localize)(1531, "Whether keyboard focus is inside an input box"));
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[58/*vs/platform/contextview/browser/contextView*/], __M([1/*require*/,0/*exports*/,7/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.IContextMenuService = exports.IContextViewService = void 0;
    exports.IContextViewService = (0, instantiation_1.createDecorator)('contextViewService');
    exports.IContextMenuService = (0, instantiation_1.createDecorator)('contextMenuService');
});

define(__m[180/*vs/platform/dialogs/common/dialogs*/], __M([1/*require*/,0/*exports*/,7/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.IDialogService = void 0;
    exports.IDialogService = (0, instantiation_1.createDecorator)('dialogService');
});

define(__m[271/*vs/platform/environment/common/environment*/], __M([1/*require*/,0/*exports*/,7/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.IEnvironmentService = void 0;
    exports.IEnvironmentService = (0, instantiation_1.createDecorator)('environmentService');
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[118/*vs/platform/hover/browser/hover*/], __M([1/*require*/,0/*exports*/,7/*vs/platform/instantiation/common/instantiation*/,2/*vs/base/common/lifecycle*/,28/*vs/platform/configuration/common/configuration*/,5/*vs/base/browser/dom*/]), function (require, exports, instantiation_1, lifecycle_1, configuration_1, dom_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.nativeHoverDelegate = exports.WorkbenchHoverDelegate = exports.IHoverService = void 0;
    exports.IHoverService = (0, instantiation_1.createDecorator)('hoverService');
    let WorkbenchHoverDelegate = class WorkbenchHoverDelegate extends lifecycle_1.Disposable {
        get delay() {
            if (this.isInstantlyHovering()) {
                return 0; // show instantly when a hover was recently shown
            }
            return this._delay;
        }
        constructor(placement, instantHover, overrideOptions = {}, configurationService, hoverService) {
            super();
            this.placement = placement;
            this.instantHover = instantHover;
            this.overrideOptions = overrideOptions;
            this.configurationService = configurationService;
            this.hoverService = hoverService;
            this.lastHoverHideTime = 0;
            this.timeLimit = 200;
            this.hoverDisposables = this._register(new lifecycle_1.DisposableStore());
            this._delay = this.configurationService.getValue('workbench.hover.delay');
            this._register(this.configurationService.onDidChangeConfiguration(e => {
                if (e.affectsConfiguration('workbench.hover.delay')) {
                    this._delay = this.configurationService.getValue('workbench.hover.delay');
                }
            }));
        }
        showHover(options, focus) {
            const overrideOptions = typeof this.overrideOptions === 'function' ? this.overrideOptions(options, focus) : this.overrideOptions;
            // close hover on escape
            this.hoverDisposables.clear();
            const targets = (0, dom_1.isHTMLElement)(options.target) ? [options.target] : options.target.targetElements;
            for (const target of targets) {
                this.hoverDisposables.add((0, dom_1.addStandardDisposableListener)(target, 'keydown', (e) => {
                    if (e.equals(9 /* KeyCode.Escape */)) {
                        this.hoverService.hideHover();
                    }
                }));
            }
            const id = (0, dom_1.isHTMLElement)(options.content) ? undefined : options.content.toString();
            return this.hoverService.showHover({
                ...options,
                ...overrideOptions,
                persistence: {
                    hideOnKeyDown: true,
                    ...overrideOptions.persistence
                },
                id,
                appearance: {
                    ...options.appearance,
                    compact: true,
                    skipFadeInAnimation: this.isInstantlyHovering(),
                    ...overrideOptions.appearance
                }
            }, focus);
        }
        isInstantlyHovering() {
            return this.instantHover && Date.now() - this.lastHoverHideTime < this.timeLimit;
        }
        onDidHideHover() {
            this.hoverDisposables.clear();
            if (this.instantHover) {
                this.lastHoverHideTime = Date.now();
            }
        }
    };
    exports.WorkbenchHoverDelegate = WorkbenchHoverDelegate;
    exports.WorkbenchHoverDelegate = WorkbenchHoverDelegate = __decorate([
        __param(3, configuration_1.IConfigurationService),
        __param(4, exports.IHoverService)
    ], WorkbenchHoverDelegate);
    // TODO@benibenj remove this, only temp fix for contextviews
    exports.nativeHoverDelegate = {
        showHover: function () {
            throw new Error('Native hover function not implemented.');
        },
        delay: 0,
        showNativeHover: true
    };
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[154/*vs/platform/instantiation/common/serviceCollection*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ServiceCollection = void 0;
    class ServiceCollection {
        constructor(...entries) {
            this._entries = new Map();
            for (const [id, service] of entries) {
                this.set(id, service);
            }
        }
        set(id, instanceOrDescriptor) {
            const result = this._entries.get(id);
            this._entries.set(id, instanceOrDescriptor);
            return result;
        }
        get(id) {
            return this._entries.get(id);
        }
    }
    exports.ServiceCollection = ServiceCollection;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[688/*vs/platform/instantiation/common/instantiationService*/], __M([1/*require*/,0/*exports*/,14/*vs/base/common/async*/,8/*vs/base/common/errors*/,2/*vs/base/common/lifecycle*/,265/*vs/platform/instantiation/common/descriptors*/,676/*vs/platform/instantiation/common/graph*/,7/*vs/platform/instantiation/common/instantiation*/,154/*vs/platform/instantiation/common/serviceCollection*/,73/*vs/base/common/linkedList*/]), function (require, exports, async_1, errors_1, lifecycle_1, descriptors_1, graph_1, instantiation_1, serviceCollection_1, linkedList_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Trace = exports.InstantiationService = void 0;
    // TRACING
    const _enableAllTracing = false;
    class CyclicDependencyError extends Error {
        constructor(graph) {
            super('cyclic dependency between services');
            this.message = graph.findCycleSlow() ?? `UNABLE to detect cycle, dumping graph: \n${graph.toString()}`;
        }
    }
    class InstantiationService {
        constructor(_services = new serviceCollection_1.ServiceCollection(), _strict = false, _parent, _enableTracing = _enableAllTracing) {
            this._services = _services;
            this._strict = _strict;
            this._parent = _parent;
            this._enableTracing = _enableTracing;
            this._isDisposed = false;
            this._servicesToMaybeDispose = new Set();
            this._children = new Set();
            this._activeInstantiations = new Set();
            this._services.set(instantiation_1.IInstantiationService, this);
            this._globalGraph = _enableTracing ? _parent?._globalGraph ?? new graph_1.Graph(e => e) : undefined;
        }
        dispose() {
            if (!this._isDisposed) {
                this._isDisposed = true;
                // dispose all child services
                (0, lifecycle_1.dispose)(this._children);
                this._children.clear();
                // dispose all services created by this service
                for (const candidate of this._servicesToMaybeDispose) {
                    if ((0, lifecycle_1.isDisposable)(candidate)) {
                        candidate.dispose();
                    }
                }
                this._servicesToMaybeDispose.clear();
            }
        }
        _throwIfDisposed() {
            if (this._isDisposed) {
                throw new Error('InstantiationService has been disposed');
            }
        }
        createChild(services, store) {
            this._throwIfDisposed();
            const that = this;
            const result = new class extends InstantiationService {
                dispose() {
                    that._children.delete(result);
                    super.dispose();
                }
            }(services, this._strict, this, this._enableTracing);
            this._children.add(result);
            store?.add(result);
            return result;
        }
        invokeFunction(fn, ...args) {
            this._throwIfDisposed();
            const _trace = Trace.traceInvocation(this._enableTracing, fn);
            let _done = false;
            try {
                const accessor = {
                    get: (id) => {
                        if (_done) {
                            throw (0, errors_1.illegalState)('service accessor is only valid during the invocation of its target method');
                        }
                        const result = this._getOrCreateServiceInstance(id, _trace);
                        if (!result) {
                            throw new Error(`[invokeFunction] unknown service '${id}'`);
                        }
                        return result;
                    }
                };
                return fn(accessor, ...args);
            }
            finally {
                _done = true;
                _trace.stop();
            }
        }
        createInstance(ctorOrDescriptor, ...rest) {
            this._throwIfDisposed();
            let _trace;
            let result;
            if (ctorOrDescriptor instanceof descriptors_1.SyncDescriptor) {
                _trace = Trace.traceCreation(this._enableTracing, ctorOrDescriptor.ctor);
                result = this._createInstance(ctorOrDescriptor.ctor, ctorOrDescriptor.staticArguments.concat(rest), _trace);
            }
            else {
                _trace = Trace.traceCreation(this._enableTracing, ctorOrDescriptor);
                result = this._createInstance(ctorOrDescriptor, rest, _trace);
            }
            _trace.stop();
            return result;
        }
        _createInstance(ctor, args = [], _trace) {
            // arguments defined by service decorators
            const serviceDependencies = instantiation_1._util.getServiceDependencies(ctor).sort((a, b) => a.index - b.index);
            const serviceArgs = [];
            for (const dependency of serviceDependencies) {
                const service = this._getOrCreateServiceInstance(dependency.id, _trace);
                if (!service) {
                    this._throwIfStrict(`[createInstance] ${ctor.name} depends on UNKNOWN service ${dependency.id}.`, false);
                }
                serviceArgs.push(service);
            }
            const firstServiceArgPos = serviceDependencies.length > 0 ? serviceDependencies[0].index : args.length;
            // check for argument mismatches, adjust static args if needed
            if (args.length !== firstServiceArgPos) {
                console.trace(`[createInstance] First service dependency of ${ctor.name} at position ${firstServiceArgPos + 1} conflicts with ${args.length} static arguments`);
                const delta = firstServiceArgPos - args.length;
                if (delta > 0) {
                    args = args.concat(new Array(delta));
                }
                else {
                    args = args.slice(0, firstServiceArgPos);
                }
            }
            // now create the instance
            return Reflect.construct(ctor, args.concat(serviceArgs));
        }
        _setCreatedServiceInstance(id, instance) {
            if (this._services.get(id) instanceof descriptors_1.SyncDescriptor) {
                this._services.set(id, instance);
            }
            else if (this._parent) {
                this._parent._setCreatedServiceInstance(id, instance);
            }
            else {
                throw new Error('illegalState - setting UNKNOWN service instance');
            }
        }
        _getServiceInstanceOrDescriptor(id) {
            const instanceOrDesc = this._services.get(id);
            if (!instanceOrDesc && this._parent) {
                return this._parent._getServiceInstanceOrDescriptor(id);
            }
            else {
                return instanceOrDesc;
            }
        }
        _getOrCreateServiceInstance(id, _trace) {
            if (this._globalGraph && this._globalGraphImplicitDependency) {
                this._globalGraph.insertEdge(this._globalGraphImplicitDependency, String(id));
            }
            const thing = this._getServiceInstanceOrDescriptor(id);
            if (thing instanceof descriptors_1.SyncDescriptor) {
                return this._safeCreateAndCacheServiceInstance(id, thing, _trace.branch(id, true));
            }
            else {
                _trace.branch(id, false);
                return thing;
            }
        }
        _safeCreateAndCacheServiceInstance(id, desc, _trace) {
            if (this._activeInstantiations.has(id)) {
                throw new Error(`illegal state - RECURSIVELY instantiating service '${id}'`);
            }
            this._activeInstantiations.add(id);
            try {
                return this._createAndCacheServiceInstance(id, desc, _trace);
            }
            finally {
                this._activeInstantiations.delete(id);
            }
        }
        _createAndCacheServiceInstance(id, desc, _trace) {
            const graph = new graph_1.Graph(data => data.id.toString());
            let cycleCount = 0;
            const stack = [{ id, desc, _trace }];
            const seen = new Set();
            while (stack.length) {
                const item = stack.pop();
                if (seen.has(String(item.id))) {
                    continue;
                }
                seen.add(String(item.id));
                graph.lookupOrInsertNode(item);
                // a weak but working heuristic for cycle checks
                if (cycleCount++ > 1000) {
                    throw new CyclicDependencyError(graph);
                }
                // check all dependencies for existence and if they need to be created first
                for (const dependency of instantiation_1._util.getServiceDependencies(item.desc.ctor)) {
                    const instanceOrDesc = this._getServiceInstanceOrDescriptor(dependency.id);
                    if (!instanceOrDesc) {
                        this._throwIfStrict(`[createInstance] ${id} depends on ${dependency.id} which is NOT registered.`, true);
                    }
                    // take note of all service dependencies
                    this._globalGraph?.insertEdge(String(item.id), String(dependency.id));
                    if (instanceOrDesc instanceof descriptors_1.SyncDescriptor) {
                        const d = { id: dependency.id, desc: instanceOrDesc, _trace: item._trace.branch(dependency.id, true) };
                        graph.insertEdge(item, d);
                        stack.push(d);
                    }
                }
            }
            while (true) {
                const roots = graph.roots();
                // if there is no more roots but still
                // nodes in the graph we have a cycle
                if (roots.length === 0) {
                    if (!graph.isEmpty()) {
                        throw new CyclicDependencyError(graph);
                    }
                    break;
                }
                for (const { data } of roots) {
                    // Repeat the check for this still being a service sync descriptor. That's because
                    // instantiating a dependency might have side-effect and recursively trigger instantiation
                    // so that some dependencies are now fullfilled already.
                    const instanceOrDesc = this._getServiceInstanceOrDescriptor(data.id);
                    if (instanceOrDesc instanceof descriptors_1.SyncDescriptor) {
                        // create instance and overwrite the service collections
                        const instance = this._createServiceInstanceWithOwner(data.id, data.desc.ctor, data.desc.staticArguments, data.desc.supportsDelayedInstantiation, data._trace);
                        this._setCreatedServiceInstance(data.id, instance);
                    }
                    graph.removeNode(data);
                }
            }
            return this._getServiceInstanceOrDescriptor(id);
        }
        _createServiceInstanceWithOwner(id, ctor, args = [], supportsDelayedInstantiation, _trace) {
            if (this._services.get(id) instanceof descriptors_1.SyncDescriptor) {
                return this._createServiceInstance(id, ctor, args, supportsDelayedInstantiation, _trace, this._servicesToMaybeDispose);
            }
            else if (this._parent) {
                return this._parent._createServiceInstanceWithOwner(id, ctor, args, supportsDelayedInstantiation, _trace);
            }
            else {
                throw new Error(`illegalState - creating UNKNOWN service instance ${ctor.name}`);
            }
        }
        _createServiceInstance(id, ctor, args = [], supportsDelayedInstantiation, _trace, disposeBucket) {
            if (!supportsDelayedInstantiation) {
                // eager instantiation
                const result = this._createInstance(ctor, args, _trace);
                disposeBucket.add(result);
                return result;
            }
            else {
                const child = new InstantiationService(undefined, this._strict, this, this._enableTracing);
                child._globalGraphImplicitDependency = String(id);
                // Return a proxy object that's backed by an idle value. That
                // strategy is to instantiate services in our idle time or when actually
                // needed but not when injected into a consumer
                // return "empty events" when the service isn't instantiated yet
                const earlyListeners = new Map();
                const idle = new async_1.GlobalIdleValue(() => {
                    const result = child._createInstance(ctor, args, _trace);
                    // early listeners that we kept are now being subscribed to
                    // the real service
                    for (const [key, values] of earlyListeners) {
                        const candidate = result[key];
                        if (typeof candidate === 'function') {
                            for (const value of values) {
                                value.disposable = candidate.apply(result, value.listener);
                            }
                        }
                    }
                    earlyListeners.clear();
                    disposeBucket.add(result);
                    return result;
                });
                return new Proxy(Object.create(null), {
                    get(target, key) {
                        if (!idle.isInitialized) {
                            // looks like an event
                            if (typeof key === 'string' && (key.startsWith('onDid') || key.startsWith('onWill'))) {
                                let list = earlyListeners.get(key);
                                if (!list) {
                                    list = new linkedList_1.LinkedList();
                                    earlyListeners.set(key, list);
                                }
                                const event = (callback, thisArg, disposables) => {
                                    if (idle.isInitialized) {
                                        return idle.value[key](callback, thisArg, disposables);
                                    }
                                    else {
                                        const entry = { listener: [callback, thisArg, disposables], disposable: undefined };
                                        const rm = list.push(entry);
                                        const result = (0, lifecycle_1.toDisposable)(() => {
                                            rm();
                                            entry.disposable?.dispose();
                                        });
                                        return result;
                                    }
                                };
                                return event;
                            }
                        }
                        // value already exists
                        if (key in target) {
                            return target[key];
                        }
                        // create value
                        const obj = idle.value;
                        let prop = obj[key];
                        if (typeof prop !== 'function') {
                            return prop;
                        }
                        prop = prop.bind(obj);
                        target[key] = prop;
                        return prop;
                    },
                    set(_target, p, value) {
                        idle.value[p] = value;
                        return true;
                    },
                    getPrototypeOf(_target) {
                        return ctor.prototype;
                    }
                });
            }
        }
        _throwIfStrict(msg, printWarning) {
            if (printWarning) {
                console.warn(msg);
            }
            if (this._strict) {
                throw new Error(msg);
            }
        }
    }
    exports.InstantiationService = InstantiationService;
    class Trace {
        static { this.all = new Set(); }
        static { this._None = new class extends Trace {
            constructor() { super(0 /* TraceType.None */, null); }
            stop() { }
            branch() { return this; }
        }; }
        static traceInvocation(_enableTracing, ctor) {
            return !_enableTracing ? Trace._None : new Trace(2 /* TraceType.Invocation */, ctor.name || new Error().stack.split('\n').slice(3, 4).join('\n'));
        }
        static traceCreation(_enableTracing, ctor) {
            return !_enableTracing ? Trace._None : new Trace(1 /* TraceType.Creation */, ctor.name);
        }
        static { this._totals = 0; }
        constructor(type, name) {
            this.type = type;
            this.name = name;
            this._start = Date.now();
            this._dep = [];
        }
        branch(id, first) {
            const child = new Trace(3 /* TraceType.Branch */, id.toString());
            this._dep.push([id, first, child]);
            return child;
        }
        stop() {
            const dur = Date.now() - this._start;
            Trace._totals += dur;
            let causedCreation = false;
            function printChild(n, trace) {
                const res = [];
                const prefix = new Array(n + 1).join('\t');
                for (const [id, first, child] of trace._dep) {
                    if (first && child) {
                        causedCreation = true;
                        res.push(`${prefix}CREATES -> ${id}`);
                        const nested = printChild(n + 1, child);
                        if (nested) {
                            res.push(nested);
                        }
                    }
                    else {
                        res.push(`${prefix}uses -> ${id}`);
                    }
                }
                return res.join('\n');
            }
            const lines = [
                `${this.type === 1 /* TraceType.Creation */ ? 'CREATE' : 'CALL'} ${this.name}`,
                `${printChild(1, this)}`,
                `DONE, took ${dur.toFixed(2)}ms (grand total ${Trace._totals.toFixed(2)}ms)`
            ];
            if (dur > 2 || causedCreation) {
                Trace.all.add(lines.join('\n'));
            }
        }
    }
    exports.Trace = Trace;
});
//#endregion

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[689/*vs/platform/keybinding/common/baseResolvedKeybinding*/], __M([1/*require*/,0/*exports*/,8/*vs/base/common/errors*/,247/*vs/base/common/keybindingLabels*/,140/*vs/base/common/keybindings*/]), function (require, exports, errors_1, keybindingLabels_1, keybindings_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.BaseResolvedKeybinding = void 0;
    class BaseResolvedKeybinding extends keybindings_1.ResolvedKeybinding {
        constructor(os, chords) {
            super();
            if (chords.length === 0) {
                throw (0, errors_1.illegalArgument)(`chords`);
            }
            this._os = os;
            this._chords = chords;
        }
        getLabel() {
            return keybindingLabels_1.UILabelProvider.toLabel(this._os, this._chords, (keybinding) => this._getLabel(keybinding));
        }
        getAriaLabel() {
            return keybindingLabels_1.AriaLabelProvider.toLabel(this._os, this._chords, (keybinding) => this._getAriaLabel(keybinding));
        }
        getElectronAccelerator() {
            if (this._chords.length > 1) {
                // [Electron Accelerators] Electron cannot handle chords
                return null;
            }
            if (this._chords[0].isDuplicateModifierCase()) {
                // [Electron Accelerators] Electron cannot handle modifier only keybindings
                // e.g. "shift shift"
                return null;
            }
            return keybindingLabels_1.ElectronAcceleratorLabelProvider.toLabel(this._os, this._chords, (keybinding) => this._getElectronAccelerator(keybinding));
        }
        getUserSettingsLabel() {
            return keybindingLabels_1.UserSettingsLabelProvider.toLabel(this._os, this._chords, (keybinding) => this._getUserSettingsLabel(keybinding));
        }
        hasMultipleChords() {
            return (this._chords.length > 1);
        }
        getChords() {
            return this._chords.map((keybinding) => this._getChord(keybinding));
        }
        _getChord(keybinding) {
            return new keybindings_1.ResolvedChord(keybinding.ctrlKey, keybinding.shiftKey, keybinding.altKey, keybinding.metaKey, this._getLabel(keybinding), this._getAriaLabel(keybinding));
        }
        getDispatchChords() {
            return this._chords.map((keybinding) => this._getChordDispatch(keybinding));
        }
        getSingleModifierDispatchChords() {
            return this._chords.map((keybinding) => this._getSingleModifierChordDispatch(keybinding));
        }
    }
    exports.BaseResolvedKeybinding = BaseResolvedKeybinding;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[31/*vs/platform/keybinding/common/keybinding*/], __M([1/*require*/,0/*exports*/,7/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.IKeybindingService = void 0;
    exports.IKeybindingService = (0, instantiation_1.createDecorator)('keybindingService');
});










define(__m[391/*vs/editor/contrib/hover/browser/contentHoverStatusBar*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,174/*vs/base/browser/ui/hover/hoverWidget*/,2/*vs/base/common/lifecycle*/,31/*vs/platform/keybinding/common/keybinding*/]), function (require, exports, dom, hoverWidget_1, lifecycle_1, keybinding_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.EditorHoverStatusBar = void 0;
    const $ = dom.$;
    let EditorHoverStatusBar = class EditorHoverStatusBar extends lifecycle_1.Disposable {
        get hasContent() {
            return this._hasContent;
        }
        constructor(_keybindingService) {
            super();
            this._keybindingService = _keybindingService;
            this.actions = [];
            this._hasContent = false;
            this.hoverElement = $('div.hover-row.status-bar');
            this.hoverElement.tabIndex = 0;
            this.actionsElement = dom.append(this.hoverElement, $('div.actions'));
        }
        addAction(actionOptions) {
            const keybinding = this._keybindingService.lookupKeybinding(actionOptions.commandId);
            const keybindingLabel = keybinding ? keybinding.getLabel() : null;
            this._hasContent = true;
            const action = this._register(hoverWidget_1.HoverAction.render(this.actionsElement, actionOptions, keybindingLabel));
            this.actions.push(action);
            return action;
        }
        append(element) {
            const result = dom.append(this.actionsElement, element);
            this._hasContent = true;
            return result;
        }
    };
    exports.EditorHoverStatusBar = EditorHoverStatusBar;
    exports.EditorHoverStatusBar = EditorHoverStatusBar = __decorate([
        __param(0, keybinding_1.IKeybindingService)
    ], EditorHoverStatusBar);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[690/*vs/editor/contrib/hover/browser/contentHoverWidget*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,31/*vs/platform/keybinding/common/keybinding*/,670/*vs/editor/contrib/hover/browser/resizableContentWidget*/,12/*vs/platform/contextkey/common/contextkey*/,28/*vs/platform/configuration/common/configuration*/,61/*vs/platform/accessibility/common/accessibility*/,20/*vs/editor/common/editorContextKeys*/,174/*vs/base/browser/ui/hover/hoverWidget*/,6/*vs/base/common/event*/]), function (require, exports, dom, keybinding_1, resizableContentWidget_1, contextkey_1, configuration_1, accessibility_1, editorContextKeys_1, hoverWidget_1, event_1) {
    "use strict";
    var ContentHoverWidget_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ContentHoverWidget = void 0;
    const HORIZONTAL_SCROLLING_BY = 30;
    const CONTAINER_HEIGHT_PADDING = 6;
    let ContentHoverWidget = class ContentHoverWidget extends resizableContentWidget_1.ResizableContentWidget {
        static { ContentHoverWidget_1 = this; }
        static { this.ID = 'editor.contrib.resizableContentHoverWidget'; }
        static { this._lastDimensions = new dom.Dimension(0, 0); }
        get isVisibleFromKeyboard() {
            return (this._renderedHover?.source === 1 /* HoverStartSource.Keyboard */);
        }
        get isVisible() {
            return this._hoverVisibleKey.get() ?? false;
        }
        get isFocused() {
            return this._hoverFocusedKey.get() ?? false;
        }
        constructor(editor, contextKeyService, _configurationService, _accessibilityService, _keybindingService) {
            const minimumHeight = editor.getOption(67 /* EditorOption.lineHeight */) + 8;
            const minimumWidth = 150;
            const minimumSize = new dom.Dimension(minimumWidth, minimumHeight);
            super(editor, minimumSize);
            this._configurationService = _configurationService;
            this._accessibilityService = _accessibilityService;
            this._keybindingService = _keybindingService;
            this._hover = this._register(new hoverWidget_1.HoverWidget());
            this._onDidResize = this._register(new event_1.Emitter());
            this.onDidResize = this._onDidResize.event;
            this._minimumSize = minimumSize;
            this._hoverVisibleKey = editorContextKeys_1.EditorContextKeys.hoverVisible.bindTo(contextKeyService);
            this._hoverFocusedKey = editorContextKeys_1.EditorContextKeys.hoverFocused.bindTo(contextKeyService);
            dom.append(this._resizableNode.domNode, this._hover.containerDomNode);
            this._resizableNode.domNode.style.zIndex = '50';
            this._register(this._editor.onDidLayoutChange(() => {
                if (this.isVisible) {
                    this._updateMaxDimensions();
                }
            }));
            this._register(this._editor.onDidChangeConfiguration((e) => {
                if (e.hasChanged(50 /* EditorOption.fontInfo */)) {
                    this._updateFont();
                }
            }));
            const focusTracker = this._register(dom.trackFocus(this._resizableNode.domNode));
            this._register(focusTracker.onDidFocus(() => {
                this._hoverFocusedKey.set(true);
            }));
            this._register(focusTracker.onDidBlur(() => {
                this._hoverFocusedKey.set(false);
            }));
            this._setRenderedHover(undefined);
            this._editor.addContentWidget(this);
        }
        dispose() {
            super.dispose();
            this._renderedHover?.dispose();
            this._editor.removeContentWidget(this);
        }
        getId() {
            return ContentHoverWidget_1.ID;
        }
        static _applyDimensions(container, width, height) {
            const transformedWidth = typeof width === 'number' ? `${width}px` : width;
            const transformedHeight = typeof height === 'number' ? `${height}px` : height;
            container.style.width = transformedWidth;
            container.style.height = transformedHeight;
        }
        _setContentsDomNodeDimensions(width, height) {
            const contentsDomNode = this._hover.contentsDomNode;
            return ContentHoverWidget_1._applyDimensions(contentsDomNode, width, height);
        }
        _setContainerDomNodeDimensions(width, height) {
            const containerDomNode = this._hover.containerDomNode;
            return ContentHoverWidget_1._applyDimensions(containerDomNode, width, height);
        }
        _setHoverWidgetDimensions(width, height) {
            this._setContentsDomNodeDimensions(width, height);
            this._setContainerDomNodeDimensions(width, height);
            this._layoutContentWidget();
        }
        static _applyMaxDimensions(container, width, height) {
            const transformedWidth = typeof width === 'number' ? `${width}px` : width;
            const transformedHeight = typeof height === 'number' ? `${height}px` : height;
            container.style.maxWidth = transformedWidth;
            container.style.maxHeight = transformedHeight;
        }
        _setHoverWidgetMaxDimensions(width, height) {
            ContentHoverWidget_1._applyMaxDimensions(this._hover.contentsDomNode, width, height);
            ContentHoverWidget_1._applyMaxDimensions(this._hover.containerDomNode, width, height);
            this._hover.containerDomNode.style.setProperty('--vscode-hover-maxWidth', typeof width === 'number' ? `${width}px` : width);
            this._layoutContentWidget();
        }
        _setAdjustedHoverWidgetDimensions(size) {
            this._setHoverWidgetMaxDimensions('none', 'none');
            const width = size.width;
            const height = size.height;
            this._setHoverWidgetDimensions(width, height);
        }
        _updateResizableNodeMaxDimensions() {
            const maxRenderingWidth = this._findMaximumRenderingWidth() ?? Infinity;
            const maxRenderingHeight = this._findMaximumRenderingHeight() ?? Infinity;
            this._resizableNode.maxSize = new dom.Dimension(maxRenderingWidth, maxRenderingHeight);
            this._setHoverWidgetMaxDimensions(maxRenderingWidth, maxRenderingHeight);
        }
        _resize(size) {
            ContentHoverWidget_1._lastDimensions = new dom.Dimension(size.width, size.height);
            this._setAdjustedHoverWidgetDimensions(size);
            this._resizableNode.layout(size.height, size.width);
            this._updateResizableNodeMaxDimensions();
            this._hover.scrollbar.scanDomNode();
            this._editor.layoutContentWidget(this);
            this._onDidResize.fire();
        }
        _findAvailableSpaceVertically() {
            const position = this._renderedHover?.showAtPosition;
            if (!position) {
                return;
            }
            return this._positionPreference === 1 /* ContentWidgetPositionPreference.ABOVE */ ?
                this._availableVerticalSpaceAbove(position)
                : this._availableVerticalSpaceBelow(position);
        }
        _findMaximumRenderingHeight() {
            const availableSpace = this._findAvailableSpaceVertically();
            if (!availableSpace) {
                return;
            }
            // Padding needed in order to stop the resizing down to a smaller height
            let maximumHeight = CONTAINER_HEIGHT_PADDING;
            Array.from(this._hover.contentsDomNode.children).forEach((hoverPart) => {
                maximumHeight += hoverPart.clientHeight;
            });
            return Math.min(availableSpace, maximumHeight);
        }
        _isHoverTextOverflowing() {
            // To find out if the text is overflowing, we will disable wrapping, check the widths, and then re-enable wrapping
            this._hover.containerDomNode.style.setProperty('--vscode-hover-whiteSpace', 'nowrap');
            this._hover.containerDomNode.style.setProperty('--vscode-hover-sourceWhiteSpace', 'nowrap');
            const overflowing = Array.from(this._hover.contentsDomNode.children).some((hoverElement) => {
                return hoverElement.scrollWidth > hoverElement.clientWidth;
            });
            this._hover.containerDomNode.style.removeProperty('--vscode-hover-whiteSpace');
            this._hover.containerDomNode.style.removeProperty('--vscode-hover-sourceWhiteSpace');
            return overflowing;
        }
        _findMaximumRenderingWidth() {
            if (!this._editor || !this._editor.hasModel()) {
                return;
            }
            const overflowing = this._isHoverTextOverflowing();
            const initialWidth = (typeof this._contentWidth === 'undefined'
                ? 0
                : this._contentWidth - 2 // - 2 for the borders
            );
            if (overflowing || this._hover.containerDomNode.clientWidth < initialWidth) {
                const bodyBoxWidth = dom.getClientArea(this._hover.containerDomNode.ownerDocument.body).width;
                const horizontalPadding = 14;
                return bodyBoxWidth - horizontalPadding;
            }
            else {
                return this._hover.containerDomNode.clientWidth + 2;
            }
        }
        isMouseGettingCloser(posx, posy) {
            if (!this._renderedHover) {
                return false;
            }
            if (this._renderedHover.initialMousePosX === undefined || this._renderedHover.initialMousePosY === undefined) {
                this._renderedHover.initialMousePosX = posx;
                this._renderedHover.initialMousePosY = posy;
                return false;
            }
            const widgetRect = dom.getDomNodePagePosition(this.getDomNode());
            if (this._renderedHover.closestMouseDistance === undefined) {
                this._renderedHover.closestMouseDistance = computeDistanceFromPointToRectangle(this._renderedHover.initialMousePosX, this._renderedHover.initialMousePosY, widgetRect.left, widgetRect.top, widgetRect.width, widgetRect.height);
            }
            const distance = computeDistanceFromPointToRectangle(posx, posy, widgetRect.left, widgetRect.top, widgetRect.width, widgetRect.height);
            if (distance > this._renderedHover.closestMouseDistance + 4 /* tolerance of 4 pixels */) {
                // The mouse is getting farther away
                return false;
            }
            this._renderedHover.closestMouseDistance = Math.min(this._renderedHover.closestMouseDistance, distance);
            return true;
        }
        _setRenderedHover(renderedHover) {
            this._renderedHover?.dispose();
            this._renderedHover = renderedHover;
            this._hoverVisibleKey.set(!!renderedHover);
            this._hover.containerDomNode.classList.toggle('hidden', !renderedHover);
        }
        _updateFont() {
            const { fontSize, lineHeight } = this._editor.getOption(50 /* EditorOption.fontInfo */);
            const contentsDomNode = this._hover.contentsDomNode;
            contentsDomNode.style.fontSize = `${fontSize}px`;
            contentsDomNode.style.lineHeight = `${lineHeight / fontSize}`;
            const codeClasses = Array.prototype.slice.call(this._hover.contentsDomNode.getElementsByClassName('code'));
            codeClasses.forEach(node => this._editor.applyFontInfo(node));
        }
        _updateContent(node) {
            const contentsDomNode = this._hover.contentsDomNode;
            contentsDomNode.style.paddingBottom = '';
            contentsDomNode.textContent = '';
            contentsDomNode.appendChild(node);
        }
        _layoutContentWidget() {
            this._editor.layoutContentWidget(this);
            this._hover.onContentsChanged();
        }
        _updateMaxDimensions() {
            const height = Math.max(this._editor.getLayoutInfo().height / 4, 250, ContentHoverWidget_1._lastDimensions.height);
            const width = Math.max(this._editor.getLayoutInfo().width * 0.66, 500, ContentHoverWidget_1._lastDimensions.width);
            this._setHoverWidgetMaxDimensions(width, height);
        }
        _render(renderedHover) {
            this._setRenderedHover(renderedHover);
            this._updateFont();
            this._updateContent(renderedHover.domNode);
            this._updateMaxDimensions();
            this.onContentsChanged();
            // Simply force a synchronous render on the editor
            // such that the widget does not really render with left = '0px'
            this._editor.render();
        }
        getPosition() {
            if (!this._renderedHover) {
                return null;
            }
            return {
                position: this._renderedHover.showAtPosition,
                secondaryPosition: this._renderedHover.showAtSecondaryPosition,
                positionAffinity: this._renderedHover.shouldAppearBeforeContent ? 3 /* PositionAffinity.LeftOfInjectedText */ : undefined,
                preference: [this._positionPreference ?? 1 /* ContentWidgetPositionPreference.ABOVE */]
            };
        }
        show(renderedHover) {
            if (!this._editor || !this._editor.hasModel()) {
                return;
            }
            this._render(renderedHover);
            const widgetHeight = dom.getTotalHeight(this._hover.containerDomNode);
            const widgetPosition = renderedHover.showAtPosition;
            this._positionPreference = this._findPositionPreference(widgetHeight, widgetPosition) ?? 1 /* ContentWidgetPositionPreference.ABOVE */;
            // See https://github.com/microsoft/vscode/issues/140339
            // TODO: Doing a second layout of the hover after force rendering the editor
            this.onContentsChanged();
            if (renderedHover.shouldFocus) {
                this._hover.containerDomNode.focus();
            }
            this._onDidResize.fire();
            // The aria label overrides the label, so if we add to it, add the contents of the hover
            const hoverFocused = this._hover.containerDomNode.ownerDocument.activeElement === this._hover.containerDomNode;
            const accessibleViewHint = hoverFocused && (0, hoverWidget_1.getHoverAccessibleViewHint)(this._configurationService.getValue('accessibility.verbosity.hover') === true && this._accessibilityService.isScreenReaderOptimized(), this._keybindingService.lookupKeybinding('editor.action.accessibleView')?.getAriaLabel() ?? '');
            if (accessibleViewHint) {
                this._hover.contentsDomNode.ariaLabel = this._hover.contentsDomNode.textContent + ', ' + accessibleViewHint;
            }
        }
        hide() {
            if (!this._renderedHover) {
                return;
            }
            const hoverStoleFocus = this._renderedHover.shouldFocus || this._hoverFocusedKey.get();
            this._setRenderedHover(undefined);
            this._resizableNode.maxSize = new dom.Dimension(Infinity, Infinity);
            this._resizableNode.clearSashHoverState();
            this._hoverFocusedKey.set(false);
            this._editor.layoutContentWidget(this);
            if (hoverStoleFocus) {
                this._editor.focus();
            }
        }
        _removeConstraintsRenderNormally() {
            // Added because otherwise the initial size of the hover content is smaller than should be
            const layoutInfo = this._editor.getLayoutInfo();
            this._resizableNode.layout(layoutInfo.height, layoutInfo.width);
            this._setHoverWidgetDimensions('auto', 'auto');
        }
        setMinimumDimensions(dimensions) {
            // We combine the new minimum dimensions with the previous ones
            this._minimumSize = new dom.Dimension(Math.max(this._minimumSize.width, dimensions.width), Math.max(this._minimumSize.height, dimensions.height));
            this._updateMinimumWidth();
        }
        _updateMinimumWidth() {
            const width = (typeof this._contentWidth === 'undefined'
                ? this._minimumSize.width
                : Math.min(this._contentWidth, this._minimumSize.width));
            // We want to avoid that the hover is artificially large, so we use the content width as minimum width
            this._resizableNode.minSize = new dom.Dimension(width, this._minimumSize.height);
        }
        onContentsChanged() {
            this._removeConstraintsRenderNormally();
            const containerDomNode = this._hover.containerDomNode;
            let height = dom.getTotalHeight(containerDomNode);
            let width = dom.getTotalWidth(containerDomNode);
            this._resizableNode.layout(height, width);
            this._setHoverWidgetDimensions(width, height);
            height = dom.getTotalHeight(containerDomNode);
            width = dom.getTotalWidth(containerDomNode);
            this._contentWidth = width;
            this._updateMinimumWidth();
            this._resizableNode.layout(height, width);
            if (this._renderedHover?.showAtPosition) {
                const widgetHeight = dom.getTotalHeight(this._hover.containerDomNode);
                this._positionPreference = this._findPositionPreference(widgetHeight, this._renderedHover.showAtPosition);
            }
            this._layoutContentWidget();
        }
        focus() {
            this._hover.containerDomNode.focus();
        }
        scrollUp() {
            const scrollTop = this._hover.scrollbar.getScrollPosition().scrollTop;
            const fontInfo = this._editor.getOption(50 /* EditorOption.fontInfo */);
            this._hover.scrollbar.setScrollPosition({ scrollTop: scrollTop - fontInfo.lineHeight });
        }
        scrollDown() {
            const scrollTop = this._hover.scrollbar.getScrollPosition().scrollTop;
            const fontInfo = this._editor.getOption(50 /* EditorOption.fontInfo */);
            this._hover.scrollbar.setScrollPosition({ scrollTop: scrollTop + fontInfo.lineHeight });
        }
        scrollLeft() {
            const scrollLeft = this._hover.scrollbar.getScrollPosition().scrollLeft;
            this._hover.scrollbar.setScrollPosition({ scrollLeft: scrollLeft - HORIZONTAL_SCROLLING_BY });
        }
        scrollRight() {
            const scrollLeft = this._hover.scrollbar.getScrollPosition().scrollLeft;
            this._hover.scrollbar.setScrollPosition({ scrollLeft: scrollLeft + HORIZONTAL_SCROLLING_BY });
        }
        pageUp() {
            const scrollTop = this._hover.scrollbar.getScrollPosition().scrollTop;
            const scrollHeight = this._hover.scrollbar.getScrollDimensions().height;
            this._hover.scrollbar.setScrollPosition({ scrollTop: scrollTop - scrollHeight });
        }
        pageDown() {
            const scrollTop = this._hover.scrollbar.getScrollPosition().scrollTop;
            const scrollHeight = this._hover.scrollbar.getScrollDimensions().height;
            this._hover.scrollbar.setScrollPosition({ scrollTop: scrollTop + scrollHeight });
        }
        goToTop() {
            this._hover.scrollbar.setScrollPosition({ scrollTop: 0 });
        }
        goToBottom() {
            this._hover.scrollbar.setScrollPosition({ scrollTop: this._hover.scrollbar.getScrollDimensions().scrollHeight });
        }
    };
    exports.ContentHoverWidget = ContentHoverWidget;
    exports.ContentHoverWidget = ContentHoverWidget = ContentHoverWidget_1 = __decorate([
        __param(1, contextkey_1.IContextKeyService),
        __param(2, configuration_1.IConfigurationService),
        __param(3, accessibility_1.IAccessibilityService),
        __param(4, keybinding_1.IKeybindingService)
    ], ContentHoverWidget);
    function computeDistanceFromPointToRectangle(pointX, pointY, left, top, width, height) {
        const x = (left + width / 2); // x center of rectangle
        const y = (top + height / 2); // y center of rectangle
        const dx = Math.max(Math.abs(pointX - x) - width / 2, 0);
        const dy = Math.max(Math.abs(pointY - y) - height / 2, 0);
        return Math.sqrt(dx * dx + dy * dy);
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[392/*vs/platform/keybinding/common/keybindingResolver*/], __M([1/*require*/,0/*exports*/,12/*vs/platform/contextkey/common/contextkey*/]), function (require, exports, contextkey_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.KeybindingResolver = exports.NoMatchingKb = void 0;
    // util definitions to make working with the above types easier within this module:
    exports.NoMatchingKb = { kind: 0 /* ResultKind.NoMatchingKb */ };
    const MoreChordsNeeded = { kind: 1 /* ResultKind.MoreChordsNeeded */ };
    function KbFound(commandId, commandArgs, isBubble) {
        return { kind: 2 /* ResultKind.KbFound */, commandId, commandArgs, isBubble };
    }
    //#endregion
    /**
     * Stores mappings from keybindings to commands and from commands to keybindings.
     * Given a sequence of chords, `resolve`s which keybinding it matches
     */
    class KeybindingResolver {
        constructor(
        /** built-in and extension-provided keybindings */
        defaultKeybindings, 
        /** user's keybindings */
        overrides, log) {
            this._log = log;
            this._defaultKeybindings = defaultKeybindings;
            this._defaultBoundCommands = new Map();
            for (const defaultKeybinding of defaultKeybindings) {
                const command = defaultKeybinding.command;
                if (command && command.charAt(0) !== '-') {
                    this._defaultBoundCommands.set(command, true);
                }
            }
            this._map = new Map();
            this._lookupMap = new Map();
            this._keybindings = KeybindingResolver.handleRemovals([].concat(defaultKeybindings).concat(overrides));
            for (let i = 0, len = this._keybindings.length; i < len; i++) {
                const k = this._keybindings[i];
                if (k.chords.length === 0) {
                    // unbound
                    continue;
                }
                // substitute with constants that are registered after startup - https://github.com/microsoft/vscode/issues/174218#issuecomment-1437972127
                const when = k.when?.substituteConstants();
                if (when && when.type === 0 /* ContextKeyExprType.False */) {
                    // when condition is false
                    continue;
                }
                this._addKeyPress(k.chords[0], k);
            }
        }
        static _isTargetedForRemoval(defaultKb, keypress, when) {
            if (keypress) {
                for (let i = 0; i < keypress.length; i++) {
                    if (keypress[i] !== defaultKb.chords[i]) {
                        return false;
                    }
                }
            }
            // `true` means always, as does `undefined`
            // so we will treat `true` === `undefined`
            if (when && when.type !== 1 /* ContextKeyExprType.True */) {
                if (!defaultKb.when) {
                    return false;
                }
                if (!(0, contextkey_1.expressionsAreEqualWithConstantSubstitution)(when, defaultKb.when)) {
                    return false;
                }
            }
            return true;
        }
        /**
         * Looks for rules containing "-commandId" and removes them.
         */
        static handleRemovals(rules) {
            // Do a first pass and construct a hash-map for removals
            const removals = new Map();
            for (let i = 0, len = rules.length; i < len; i++) {
                const rule = rules[i];
                if (rule.command && rule.command.charAt(0) === '-') {
                    const command = rule.command.substring(1);
                    if (!removals.has(command)) {
                        removals.set(command, [rule]);
                    }
                    else {
                        removals.get(command).push(rule);
                    }
                }
            }
            if (removals.size === 0) {
                // There are no removals
                return rules;
            }
            // Do a second pass and keep only non-removed keybindings
            const result = [];
            for (let i = 0, len = rules.length; i < len; i++) {
                const rule = rules[i];
                if (!rule.command || rule.command.length === 0) {
                    result.push(rule);
                    continue;
                }
                if (rule.command.charAt(0) === '-') {
                    continue;
                }
                const commandRemovals = removals.get(rule.command);
                if (!commandRemovals || !rule.isDefault) {
                    result.push(rule);
                    continue;
                }
                let isRemoved = false;
                for (const commandRemoval of commandRemovals) {
                    const when = commandRemoval.when;
                    if (this._isTargetedForRemoval(rule, commandRemoval.chords, when)) {
                        isRemoved = true;
                        break;
                    }
                }
                if (!isRemoved) {
                    result.push(rule);
                    continue;
                }
            }
            return result;
        }
        _addKeyPress(keypress, item) {
            const conflicts = this._map.get(keypress);
            if (typeof conflicts === 'undefined') {
                // There is no conflict so far
                this._map.set(keypress, [item]);
                this._addToLookupMap(item);
                return;
            }
            for (let i = conflicts.length - 1; i >= 0; i--) {
                const conflict = conflicts[i];
                if (conflict.command === item.command) {
                    continue;
                }
                // Test if the shorter keybinding is a prefix of the longer one.
                // If the shorter keybinding is a prefix, it effectively will shadow the longer one and is considered a conflict.
                let isShorterKbPrefix = true;
                for (let i = 1; i < conflict.chords.length && i < item.chords.length; i++) {
                    if (conflict.chords[i] !== item.chords[i]) {
                        // The ith step does not conflict
                        isShorterKbPrefix = false;
                        break;
                    }
                }
                if (!isShorterKbPrefix) {
                    continue;
                }
                if (KeybindingResolver.whenIsEntirelyIncluded(conflict.when, item.when)) {
                    // `item` completely overwrites `conflict`
                    // Remove conflict from the lookupMap
                    this._removeFromLookupMap(conflict);
                }
            }
            conflicts.push(item);
            this._addToLookupMap(item);
        }
        _addToLookupMap(item) {
            if (!item.command) {
                return;
            }
            let arr = this._lookupMap.get(item.command);
            if (typeof arr === 'undefined') {
                arr = [item];
                this._lookupMap.set(item.command, arr);
            }
            else {
                arr.push(item);
            }
        }
        _removeFromLookupMap(item) {
            if (!item.command) {
                return;
            }
            const arr = this._lookupMap.get(item.command);
            if (typeof arr === 'undefined') {
                return;
            }
            for (let i = 0, len = arr.length; i < len; i++) {
                if (arr[i] === item) {
                    arr.splice(i, 1);
                    return;
                }
            }
        }
        /**
         * Returns true if it is provable `a` implies `b`.
         */
        static whenIsEntirelyIncluded(a, b) {
            if (!b || b.type === 1 /* ContextKeyExprType.True */) {
                return true;
            }
            if (!a || a.type === 1 /* ContextKeyExprType.True */) {
                return false;
            }
            return (0, contextkey_1.implies)(a, b);
        }
        getKeybindings() {
            return this._keybindings;
        }
        lookupPrimaryKeybinding(commandId, context) {
            const items = this._lookupMap.get(commandId);
            if (typeof items === 'undefined' || items.length === 0) {
                return null;
            }
            if (items.length === 1) {
                return items[0];
            }
            for (let i = items.length - 1; i >= 0; i--) {
                const item = items[i];
                if (context.contextMatchesRules(item.when)) {
                    return item;
                }
            }
            return items[items.length - 1];
        }
        /**
         * Looks up a keybinding trigged as a result of pressing a sequence of chords - `[...currentChords, keypress]`
         *
         * Example: resolving 3 chords pressed sequentially - `cmd+k cmd+p cmd+i`:
         * 	`currentChords = [ 'cmd+k' , 'cmd+p' ]` and `keypress = `cmd+i` - last pressed chord
         */
        resolve(context, currentChords, keypress) {
            const pressedChords = [...currentChords, keypress];
            this._log(`| Resolving ${pressedChords}`);
            const kbCandidates = this._map.get(pressedChords[0]);
            if (kbCandidates === undefined) {
                // No bindings with such 0-th chord
                this._log(`\\ No keybinding entries.`);
                return exports.NoMatchingKb;
            }
            let lookupMap = null;
            if (pressedChords.length < 2) {
                lookupMap = kbCandidates;
            }
            else {
                // Fetch all chord bindings for `currentChords`
                lookupMap = [];
                for (let i = 0, len = kbCandidates.length; i < len; i++) {
                    const candidate = kbCandidates[i];
                    if (pressedChords.length > candidate.chords.length) { // # of pressed chords can't be less than # of chords in a keybinding to invoke
                        continue;
                    }
                    let prefixMatches = true;
                    for (let i = 1; i < pressedChords.length; i++) {
                        if (candidate.chords[i] !== pressedChords[i]) {
                            prefixMatches = false;
                            break;
                        }
                    }
                    if (prefixMatches) {
                        lookupMap.push(candidate);
                    }
                }
            }
            // check there's a keybinding with a matching when clause
            const result = this._findCommand(context, lookupMap);
            if (!result) {
                this._log(`\\ From ${lookupMap.length} keybinding entries, no when clauses matched the context.`);
                return exports.NoMatchingKb;
            }
            // check we got all chords necessary to be sure a particular keybinding needs to be invoked
            if (pressedChords.length < result.chords.length) {
                // The chord sequence is not complete
                this._log(`\\ From ${lookupMap.length} keybinding entries, awaiting ${result.chords.length - pressedChords.length} more chord(s), when: ${printWhenExplanation(result.when)}, source: ${printSourceExplanation(result)}.`);
                return MoreChordsNeeded;
            }
            this._log(`\\ From ${lookupMap.length} keybinding entries, matched ${result.command}, when: ${printWhenExplanation(result.when)}, source: ${printSourceExplanation(result)}.`);
            return KbFound(result.command, result.commandArgs, result.bubble);
        }
        _findCommand(context, matches) {
            for (let i = matches.length - 1; i >= 0; i--) {
                const k = matches[i];
                if (!KeybindingResolver._contextMatchesRules(context, k.when)) {
                    continue;
                }
                return k;
            }
            return null;
        }
        static _contextMatchesRules(context, rules) {
            if (!rules) {
                return true;
            }
            return rules.evaluate(context);
        }
    }
    exports.KeybindingResolver = KeybindingResolver;
    function printWhenExplanation(when) {
        if (!when) {
            return `no when condition`;
        }
        return `${when.serialize()}`;
    }
    function printSourceExplanation(kb) {
        return (kb.extensionId
            ? (kb.isBuiltinExtension ? `built-in extension ${kb.extensionId}` : `user extension ${kb.extensionId}`)
            : (kb.isDefault ? `built-in` : `user`));
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[691/*vs/platform/keybinding/common/abstractKeybindingService*/], __M([1/*require*/,0/*exports*/,14/*vs/base/common/async*/,8/*vs/base/common/errors*/,6/*vs/base/common/event*/,300/*vs/base/common/ime*/,2/*vs/base/common/lifecycle*/,3/*vs/nls*/,392/*vs/platform/keybinding/common/keybindingResolver*/]), function (require, exports, async_1, errors_1, event_1, ime_1, lifecycle_1, nls, keybindingResolver_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AbstractKeybindingService = void 0;
    const HIGH_FREQ_COMMANDS = /^(cursor|delete|undo|redo|tab|editor\.action\.clipboard)/;
    class AbstractKeybindingService extends lifecycle_1.Disposable {
        get onDidUpdateKeybindings() {
            return this._onDidUpdateKeybindings ? this._onDidUpdateKeybindings.event : event_1.Event.None; // Sinon stubbing walks properties on prototype
        }
        get inChordMode() {
            return this._currentChords.length > 0;
        }
        constructor(_contextKeyService, _commandService, _telemetryService, _notificationService, _logService) {
            super();
            this._contextKeyService = _contextKeyService;
            this._commandService = _commandService;
            this._telemetryService = _telemetryService;
            this._notificationService = _notificationService;
            this._logService = _logService;
            this._onDidUpdateKeybindings = this._register(new event_1.Emitter());
            this._currentChords = [];
            this._currentChordChecker = new async_1.IntervalTimer();
            this._currentChordStatusMessage = null;
            this._ignoreSingleModifiers = KeybindingModifierSet.EMPTY;
            this._currentSingleModifier = null;
            this._currentSingleModifierClearTimeout = new async_1.TimeoutTimer();
            this._currentlyDispatchingCommandId = null;
            this._logging = false;
        }
        dispose() {
            super.dispose();
        }
        _log(str) {
            if (this._logging) {
                this._logService.info(`[KeybindingService]: ${str}`);
            }
        }
        getKeybindings() {
            return this._getResolver().getKeybindings();
        }
        lookupKeybinding(commandId, context) {
            const result = this._getResolver().lookupPrimaryKeybinding(commandId, context || this._contextKeyService);
            if (!result) {
                return undefined;
            }
            return result.resolvedKeybinding;
        }
        dispatchEvent(e, target) {
            return this._dispatch(e, target);
        }
        // TODO@ulugbekna: update namings to align with `_doDispatch`
        // TODO@ulugbekna: this fn doesn't seem to take into account single-modifier keybindings, eg `shift shift`
        softDispatch(e, target) {
            this._log(`/ Soft dispatching keyboard event`);
            const keybinding = this.resolveKeyboardEvent(e);
            if (keybinding.hasMultipleChords()) {
                console.warn('keyboard event should not be mapped to multiple chords');
                return keybindingResolver_1.NoMatchingKb;
            }
            const [firstChord,] = keybinding.getDispatchChords();
            if (firstChord === null) {
                // cannot be dispatched, probably only modifier keys
                this._log(`\\ Keyboard event cannot be dispatched`);
                return keybindingResolver_1.NoMatchingKb;
            }
            const contextValue = this._contextKeyService.getContext(target);
            const currentChords = this._currentChords.map((({ keypress }) => keypress));
            return this._getResolver().resolve(contextValue, currentChords, firstChord);
        }
        _scheduleLeaveChordMode() {
            const chordLastInteractedTime = Date.now();
            this._currentChordChecker.cancelAndSet(() => {
                if (!this._documentHasFocus()) {
                    // Focus has been lost => leave chord mode
                    this._leaveChordMode();
                    return;
                }
                if (Date.now() - chordLastInteractedTime > 5000) {
                    // 5 seconds elapsed => leave chord mode
                    this._leaveChordMode();
                }
            }, 500);
        }
        _expectAnotherChord(firstChord, keypressLabel) {
            this._currentChords.push({ keypress: firstChord, label: keypressLabel });
            switch (this._currentChords.length) {
                case 0:
                    throw (0, errors_1.illegalState)('impossible');
                case 1:
                    // TODO@ulugbekna: revise this message and the one below (at least, fix terminology)
                    this._currentChordStatusMessage = this._notificationService.status(nls.localize(1538, "({0}) was pressed. Waiting for second key of chord...", keypressLabel));
                    break;
                default: {
                    const fullKeypressLabel = this._currentChords.map(({ label }) => label).join(', ');
                    this._currentChordStatusMessage = this._notificationService.status(nls.localize(1539, "({0}) was pressed. Waiting for next key of chord...", fullKeypressLabel));
                }
            }
            this._scheduleLeaveChordMode();
            if (ime_1.IME.enabled) {
                ime_1.IME.disable();
            }
        }
        _leaveChordMode() {
            if (this._currentChordStatusMessage) {
                this._currentChordStatusMessage.dispose();
                this._currentChordStatusMessage = null;
            }
            this._currentChordChecker.cancel();
            this._currentChords = [];
            ime_1.IME.enable();
        }
        _dispatch(e, target) {
            return this._doDispatch(this.resolveKeyboardEvent(e), target, /*isSingleModiferChord*/ false);
        }
        _singleModifierDispatch(e, target) {
            const keybinding = this.resolveKeyboardEvent(e);
            const [singleModifier,] = keybinding.getSingleModifierDispatchChords();
            if (singleModifier) {
                if (this._ignoreSingleModifiers.has(singleModifier)) {
                    this._log(`+ Ignoring single modifier ${singleModifier} due to it being pressed together with other keys.`);
                    this._ignoreSingleModifiers = KeybindingModifierSet.EMPTY;
                    this._currentSingleModifierClearTimeout.cancel();
                    this._currentSingleModifier = null;
                    return false;
                }
                this._ignoreSingleModifiers = KeybindingModifierSet.EMPTY;
                if (this._currentSingleModifier === null) {
                    // we have a valid `singleModifier`, store it for the next keyup, but clear it in 300ms
                    this._log(`+ Storing single modifier for possible chord ${singleModifier}.`);
                    this._currentSingleModifier = singleModifier;
                    this._currentSingleModifierClearTimeout.cancelAndSet(() => {
                        this._log(`+ Clearing single modifier due to 300ms elapsed.`);
                        this._currentSingleModifier = null;
                    }, 300);
                    return false;
                }
                if (singleModifier === this._currentSingleModifier) {
                    // bingo!
                    this._log(`/ Dispatching single modifier chord ${singleModifier} ${singleModifier}`);
                    this._currentSingleModifierClearTimeout.cancel();
                    this._currentSingleModifier = null;
                    return this._doDispatch(keybinding, target, /*isSingleModiferChord*/ true);
                }
                this._log(`+ Clearing single modifier due to modifier mismatch: ${this._currentSingleModifier} ${singleModifier}`);
                this._currentSingleModifierClearTimeout.cancel();
                this._currentSingleModifier = null;
                return false;
            }
            // When pressing a modifier and holding it pressed with any other modifier or key combination,
            // the pressed modifiers should no longer be considered for single modifier dispatch.
            const [firstChord,] = keybinding.getChords();
            this._ignoreSingleModifiers = new KeybindingModifierSet(firstChord);
            if (this._currentSingleModifier !== null) {
                this._log(`+ Clearing single modifier due to other key up.`);
            }
            this._currentSingleModifierClearTimeout.cancel();
            this._currentSingleModifier = null;
            return false;
        }
        _doDispatch(userKeypress, target, isSingleModiferChord = false) {
            let shouldPreventDefault = false;
            if (userKeypress.hasMultipleChords()) { // warn - because user can press a single chord at a time
                console.warn('Unexpected keyboard event mapped to multiple chords');
                return false;
            }
            let userPressedChord = null;
            let currentChords = null;
            if (isSingleModiferChord) {
                // The keybinding is the second keypress of a single modifier chord, e.g. "shift shift".
                // A single modifier can only occur when the same modifier is pressed in short sequence,
                // hence we disregard `_currentChord` and use the same modifier instead.
                const [dispatchKeyname,] = userKeypress.getSingleModifierDispatchChords();
                userPressedChord = dispatchKeyname;
                currentChords = dispatchKeyname ? [dispatchKeyname] : []; // TODO@ulugbekna: in the `else` case we assign an empty array - make sure `resolve` can handle an empty array well
            }
            else {
                [userPressedChord,] = userKeypress.getDispatchChords();
                currentChords = this._currentChords.map(({ keypress }) => keypress);
            }
            if (userPressedChord === null) {
                this._log(`\\ Keyboard event cannot be dispatched in keydown phase.`);
                // cannot be dispatched, probably only modifier keys
                return shouldPreventDefault;
            }
            const contextValue = this._contextKeyService.getContext(target);
            const keypressLabel = userKeypress.getLabel();
            const resolveResult = this._getResolver().resolve(contextValue, currentChords, userPressedChord);
            switch (resolveResult.kind) {
                case 0 /* ResultKind.NoMatchingKb */: {
                    this._logService.trace('KeybindingService#dispatch', keypressLabel, `[ No matching keybinding ]`);
                    if (this.inChordMode) {
                        const currentChordsLabel = this._currentChords.map(({ label }) => label).join(', ');
                        this._log(`+ Leaving multi-chord mode: Nothing bound to "${currentChordsLabel}, ${keypressLabel}".`);
                        this._notificationService.status(nls.localize(1540, "The key combination ({0}, {1}) is not a command.", currentChordsLabel, keypressLabel), { hideAfter: 10 * 1000 /* 10s */ });
                        this._leaveChordMode();
                        shouldPreventDefault = true;
                    }
                    return shouldPreventDefault;
                }
                case 1 /* ResultKind.MoreChordsNeeded */: {
                    this._logService.trace('KeybindingService#dispatch', keypressLabel, `[ Several keybindings match - more chords needed ]`);
                    shouldPreventDefault = true;
                    this._expectAnotherChord(userPressedChord, keypressLabel);
                    this._log(this._currentChords.length === 1 ? `+ Entering multi-chord mode...` : `+ Continuing multi-chord mode...`);
                    return shouldPreventDefault;
                }
                case 2 /* ResultKind.KbFound */: {
                    this._logService.trace('KeybindingService#dispatch', keypressLabel, `[ Will dispatch command ${resolveResult.commandId} ]`);
                    if (resolveResult.commandId === null || resolveResult.commandId === '') {
                        if (this.inChordMode) {
                            const currentChordsLabel = this._currentChords.map(({ label }) => label).join(', ');
                            this._log(`+ Leaving chord mode: Nothing bound to "${currentChordsLabel}, ${keypressLabel}".`);
                            this._notificationService.status(nls.localize(1541, "The key combination ({0}, {1}) is not a command.", currentChordsLabel, keypressLabel), { hideAfter: 10 * 1000 /* 10s */ });
                            this._leaveChordMode();
                            shouldPreventDefault = true;
                        }
                    }
                    else {
                        if (this.inChordMode) {
                            this._leaveChordMode();
                        }
                        if (!resolveResult.isBubble) {
                            shouldPreventDefault = true;
                        }
                        this._log(`+ Invoking command ${resolveResult.commandId}.`);
                        this._currentlyDispatchingCommandId = resolveResult.commandId;
                        try {
                            if (typeof resolveResult.commandArgs === 'undefined') {
                                this._commandService.executeCommand(resolveResult.commandId).then(undefined, err => this._notificationService.warn(err));
                            }
                            else {
                                this._commandService.executeCommand(resolveResult.commandId, resolveResult.commandArgs).then(undefined, err => this._notificationService.warn(err));
                            }
                        }
                        finally {
                            this._currentlyDispatchingCommandId = null;
                        }
                        if (!HIGH_FREQ_COMMANDS.test(resolveResult.commandId)) {
                            this._telemetryService.publicLog2('workbenchActionExecuted', { id: resolveResult.commandId, from: 'keybinding', detail: userKeypress.getUserSettingsLabel() ?? undefined });
                        }
                    }
                    return shouldPreventDefault;
                }
            }
        }
        mightProducePrintableCharacter(event) {
            if (event.ctrlKey || event.metaKey) {
                // ignore ctrl/cmd-combination but not shift/alt-combinatios
                return false;
            }
            // weak check for certain ranges. this is properly implemented in a subclass
            // with access to the KeyboardMapperFactory.
            if ((event.keyCode >= 31 /* KeyCode.KeyA */ && event.keyCode <= 56 /* KeyCode.KeyZ */)
                || (event.keyCode >= 21 /* KeyCode.Digit0 */ && event.keyCode <= 30 /* KeyCode.Digit9 */)) {
                return true;
            }
            return false;
        }
    }
    exports.AbstractKeybindingService = AbstractKeybindingService;
    class KeybindingModifierSet {
        static { this.EMPTY = new KeybindingModifierSet(null); }
        constructor(source) {
            this._ctrlKey = source ? source.ctrlKey : false;
            this._shiftKey = source ? source.shiftKey : false;
            this._altKey = source ? source.altKey : false;
            this._metaKey = source ? source.metaKey : false;
        }
        has(modifier) {
            switch (modifier) {
                case 'ctrl': return this._ctrlKey;
                case 'shift': return this._shiftKey;
                case 'alt': return this._altKey;
                case 'meta': return this._metaKey;
            }
        }
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[393/*vs/platform/keybinding/common/resolvedKeybindingItem*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ResolvedKeybindingItem = void 0;
    exports.toEmptyArrayIfContainsNull = toEmptyArrayIfContainsNull;
    class ResolvedKeybindingItem {
        constructor(resolvedKeybinding, command, commandArgs, when, isDefault, extensionId, isBuiltinExtension) {
            this._resolvedKeybindingItemBrand = undefined;
            this.resolvedKeybinding = resolvedKeybinding;
            this.chords = resolvedKeybinding ? toEmptyArrayIfContainsNull(resolvedKeybinding.getDispatchChords()) : [];
            if (resolvedKeybinding && this.chords.length === 0) {
                // handle possible single modifier chord keybindings
                this.chords = toEmptyArrayIfContainsNull(resolvedKeybinding.getSingleModifierDispatchChords());
            }
            this.bubble = (command ? command.charCodeAt(0) === 94 /* CharCode.Caret */ : false);
            this.command = this.bubble ? command.substr(1) : command;
            this.commandArgs = commandArgs;
            this.when = when;
            this.isDefault = isDefault;
            this.extensionId = extensionId;
            this.isBuiltinExtension = isBuiltinExtension;
        }
    }
    exports.ResolvedKeybindingItem = ResolvedKeybindingItem;
    function toEmptyArrayIfContainsNull(arr) {
        const result = [];
        for (let i = 0, len = arr.length; i < len; i++) {
            const element = arr[i];
            if (!element) {
                return [];
            }
            result.push(element);
        }
        return result;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[692/*vs/platform/keybinding/common/usLayoutResolvedKeybinding*/], __M([1/*require*/,0/*exports*/,72/*vs/base/common/keyCodes*/,140/*vs/base/common/keybindings*/,689/*vs/platform/keybinding/common/baseResolvedKeybinding*/,393/*vs/platform/keybinding/common/resolvedKeybindingItem*/]), function (require, exports, keyCodes_1, keybindings_1, baseResolvedKeybinding_1, resolvedKeybindingItem_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.USLayoutResolvedKeybinding = void 0;
    /**
     * Do not instantiate. Use KeybindingService to get a ResolvedKeybinding seeded with information about the current kb layout.
     */
    class USLayoutResolvedKeybinding extends baseResolvedKeybinding_1.BaseResolvedKeybinding {
        constructor(chords, os) {
            super(os, chords);
        }
        _keyCodeToUILabel(keyCode) {
            if (this._os === 2 /* OperatingSystem.Macintosh */) {
                switch (keyCode) {
                    case 15 /* KeyCode.LeftArrow */:
                        return '←';
                    case 16 /* KeyCode.UpArrow */:
                        return '↑';
                    case 17 /* KeyCode.RightArrow */:
                        return '→';
                    case 18 /* KeyCode.DownArrow */:
                        return '↓';
                }
            }
            return keyCodes_1.KeyCodeUtils.toString(keyCode);
        }
        _getLabel(chord) {
            if (chord.isDuplicateModifierCase()) {
                return '';
            }
            return this._keyCodeToUILabel(chord.keyCode);
        }
        _getAriaLabel(chord) {
            if (chord.isDuplicateModifierCase()) {
                return '';
            }
            return keyCodes_1.KeyCodeUtils.toString(chord.keyCode);
        }
        _getElectronAccelerator(chord) {
            return keyCodes_1.KeyCodeUtils.toElectronAccelerator(chord.keyCode);
        }
        _getUserSettingsLabel(chord) {
            if (chord.isDuplicateModifierCase()) {
                return '';
            }
            const result = keyCodes_1.KeyCodeUtils.toUserSettingsUS(chord.keyCode);
            return (result ? result.toLowerCase() : result);
        }
        _getChordDispatch(chord) {
            return USLayoutResolvedKeybinding.getDispatchStr(chord);
        }
        static getDispatchStr(chord) {
            if (chord.isModifierKey()) {
                return null;
            }
            let result = '';
            if (chord.ctrlKey) {
                result += 'ctrl+';
            }
            if (chord.shiftKey) {
                result += 'shift+';
            }
            if (chord.altKey) {
                result += 'alt+';
            }
            if (chord.metaKey) {
                result += 'meta+';
            }
            result += keyCodes_1.KeyCodeUtils.toString(chord.keyCode);
            return result;
        }
        _getSingleModifierChordDispatch(keybinding) {
            if (keybinding.keyCode === 5 /* KeyCode.Ctrl */ && !keybinding.shiftKey && !keybinding.altKey && !keybinding.metaKey) {
                return 'ctrl';
            }
            if (keybinding.keyCode === 4 /* KeyCode.Shift */ && !keybinding.ctrlKey && !keybinding.altKey && !keybinding.metaKey) {
                return 'shift';
            }
            if (keybinding.keyCode === 6 /* KeyCode.Alt */ && !keybinding.ctrlKey && !keybinding.shiftKey && !keybinding.metaKey) {
                return 'alt';
            }
            if (keybinding.keyCode === 57 /* KeyCode.Meta */ && !keybinding.ctrlKey && !keybinding.shiftKey && !keybinding.altKey) {
                return 'meta';
            }
            return null;
        }
        /**
         * *NOTE*: Check return value for `KeyCode.Unknown`.
         */
        static _scanCodeToKeyCode(scanCode) {
            const immutableKeyCode = keyCodes_1.IMMUTABLE_CODE_TO_KEY_CODE[scanCode];
            if (immutableKeyCode !== -1 /* KeyCode.DependsOnKbLayout */) {
                return immutableKeyCode;
            }
            switch (scanCode) {
                case 10 /* ScanCode.KeyA */: return 31 /* KeyCode.KeyA */;
                case 11 /* ScanCode.KeyB */: return 32 /* KeyCode.KeyB */;
                case 12 /* ScanCode.KeyC */: return 33 /* KeyCode.KeyC */;
                case 13 /* ScanCode.KeyD */: return 34 /* KeyCode.KeyD */;
                case 14 /* ScanCode.KeyE */: return 35 /* KeyCode.KeyE */;
                case 15 /* ScanCode.KeyF */: return 36 /* KeyCode.KeyF */;
                case 16 /* ScanCode.KeyG */: return 37 /* KeyCode.KeyG */;
                case 17 /* ScanCode.KeyH */: return 38 /* KeyCode.KeyH */;
                case 18 /* ScanCode.KeyI */: return 39 /* KeyCode.KeyI */;
                case 19 /* ScanCode.KeyJ */: return 40 /* KeyCode.KeyJ */;
                case 20 /* ScanCode.KeyK */: return 41 /* KeyCode.KeyK */;
                case 21 /* ScanCode.KeyL */: return 42 /* KeyCode.KeyL */;
                case 22 /* ScanCode.KeyM */: return 43 /* KeyCode.KeyM */;
                case 23 /* ScanCode.KeyN */: return 44 /* KeyCode.KeyN */;
                case 24 /* ScanCode.KeyO */: return 45 /* KeyCode.KeyO */;
                case 25 /* ScanCode.KeyP */: return 46 /* KeyCode.KeyP */;
                case 26 /* ScanCode.KeyQ */: return 47 /* KeyCode.KeyQ */;
                case 27 /* ScanCode.KeyR */: return 48 /* KeyCode.KeyR */;
                case 28 /* ScanCode.KeyS */: return 49 /* KeyCode.KeyS */;
                case 29 /* ScanCode.KeyT */: return 50 /* KeyCode.KeyT */;
                case 30 /* ScanCode.KeyU */: return 51 /* KeyCode.KeyU */;
                case 31 /* ScanCode.KeyV */: return 52 /* KeyCode.KeyV */;
                case 32 /* ScanCode.KeyW */: return 53 /* KeyCode.KeyW */;
                case 33 /* ScanCode.KeyX */: return 54 /* KeyCode.KeyX */;
                case 34 /* ScanCode.KeyY */: return 55 /* KeyCode.KeyY */;
                case 35 /* ScanCode.KeyZ */: return 56 /* KeyCode.KeyZ */;
                case 36 /* ScanCode.Digit1 */: return 22 /* KeyCode.Digit1 */;
                case 37 /* ScanCode.Digit2 */: return 23 /* KeyCode.Digit2 */;
                case 38 /* ScanCode.Digit3 */: return 24 /* KeyCode.Digit3 */;
                case 39 /* ScanCode.Digit4 */: return 25 /* KeyCode.Digit4 */;
                case 40 /* ScanCode.Digit5 */: return 26 /* KeyCode.Digit5 */;
                case 41 /* ScanCode.Digit6 */: return 27 /* KeyCode.Digit6 */;
                case 42 /* ScanCode.Digit7 */: return 28 /* KeyCode.Digit7 */;
                case 43 /* ScanCode.Digit8 */: return 29 /* KeyCode.Digit8 */;
                case 44 /* ScanCode.Digit9 */: return 30 /* KeyCode.Digit9 */;
                case 45 /* ScanCode.Digit0 */: return 21 /* KeyCode.Digit0 */;
                case 51 /* ScanCode.Minus */: return 88 /* KeyCode.Minus */;
                case 52 /* ScanCode.Equal */: return 86 /* KeyCode.Equal */;
                case 53 /* ScanCode.BracketLeft */: return 92 /* KeyCode.BracketLeft */;
                case 54 /* ScanCode.BracketRight */: return 94 /* KeyCode.BracketRight */;
                case 55 /* ScanCode.Backslash */: return 93 /* KeyCode.Backslash */;
                case 56 /* ScanCode.IntlHash */: return 0 /* KeyCode.Unknown */; // missing
                case 57 /* ScanCode.Semicolon */: return 85 /* KeyCode.Semicolon */;
                case 58 /* ScanCode.Quote */: return 95 /* KeyCode.Quote */;
                case 59 /* ScanCode.Backquote */: return 91 /* KeyCode.Backquote */;
                case 60 /* ScanCode.Comma */: return 87 /* KeyCode.Comma */;
                case 61 /* ScanCode.Period */: return 89 /* KeyCode.Period */;
                case 62 /* ScanCode.Slash */: return 90 /* KeyCode.Slash */;
                case 106 /* ScanCode.IntlBackslash */: return 97 /* KeyCode.IntlBackslash */;
            }
            return 0 /* KeyCode.Unknown */;
        }
        static _toKeyCodeChord(chord) {
            if (!chord) {
                return null;
            }
            if (chord instanceof keybindings_1.KeyCodeChord) {
                return chord;
            }
            const keyCode = this._scanCodeToKeyCode(chord.scanCode);
            if (keyCode === 0 /* KeyCode.Unknown */) {
                return null;
            }
            return new keybindings_1.KeyCodeChord(chord.ctrlKey, chord.shiftKey, chord.altKey, chord.metaKey, keyCode);
        }
        static resolveKeybinding(keybinding, os) {
            const chords = (0, resolvedKeybindingItem_1.toEmptyArrayIfContainsNull)(keybinding.chords.map(chord => this._toKeyCodeChord(chord)));
            if (chords.length > 0) {
                return [new USLayoutResolvedKeybinding(chords, os)];
            }
            return [];
        }
    }
    exports.USLayoutResolvedKeybinding = USLayoutResolvedKeybinding;
});

define(__m[181/*vs/platform/label/common/label*/], __M([1/*require*/,0/*exports*/,7/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ILabelService = void 0;
    exports.ILabelService = (0, instantiation_1.createDecorator)('labelService');
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[119/*vs/platform/layout/browser/layoutService*/], __M([1/*require*/,0/*exports*/,7/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ILayoutService = void 0;
    exports.ILayoutService = (0, instantiation_1.createDecorator)('layoutService');
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[394/*vs/editor/standalone/browser/standaloneLayoutService*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,52/*vs/base/browser/window*/,13/*vs/base/common/arrays*/,6/*vs/base/common/event*/,34/*vs/editor/browser/services/codeEditorService*/,49/*vs/platform/instantiation/common/extensions*/,119/*vs/platform/layout/browser/layoutService*/]), function (require, exports, dom, window_1, arrays_1, event_1, codeEditorService_1, extensions_1, layoutService_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.EditorScopedLayoutService = void 0;
    let StandaloneLayoutService = class StandaloneLayoutService {
        get mainContainer() {
            return (0, arrays_1.firstOrDefault)(this._codeEditorService.listCodeEditors())?.getContainerDomNode() ?? window_1.mainWindow.document.body;
        }
        get activeContainer() {
            const activeCodeEditor = this._codeEditorService.getFocusedCodeEditor() ?? this._codeEditorService.getActiveCodeEditor();
            return activeCodeEditor?.getContainerDomNode() ?? this.mainContainer;
        }
        get mainContainerDimension() {
            return dom.getClientArea(this.mainContainer);
        }
        get activeContainerDimension() {
            return dom.getClientArea(this.activeContainer);
        }
        get containers() {
            return (0, arrays_1.coalesce)(this._codeEditorService.listCodeEditors().map(codeEditor => codeEditor.getContainerDomNode()));
        }
        getContainer() {
            return this.activeContainer;
        }
        whenContainerStylesLoaded() { return undefined; }
        focus() {
            this._codeEditorService.getFocusedCodeEditor()?.focus();
        }
        constructor(_codeEditorService) {
            this._codeEditorService = _codeEditorService;
            this.onDidLayoutMainContainer = event_1.Event.None;
            this.onDidLayoutActiveContainer = event_1.Event.None;
            this.onDidLayoutContainer = event_1.Event.None;
            this.onDidChangeActiveContainer = event_1.Event.None;
            this.onDidAddContainer = event_1.Event.None;
            this.mainContainerOffset = { top: 0, quickPickTop: 0 };
            this.activeContainerOffset = { top: 0, quickPickTop: 0 };
        }
    };
    StandaloneLayoutService = __decorate([
        __param(0, codeEditorService_1.ICodeEditorService)
    ], StandaloneLayoutService);
    let EditorScopedLayoutService = class EditorScopedLayoutService extends StandaloneLayoutService {
        get mainContainer() {
            return this._container;
        }
        constructor(_container, codeEditorService) {
            super(codeEditorService);
            this._container = _container;
        }
    };
    exports.EditorScopedLayoutService = EditorScopedLayoutService;
    exports.EditorScopedLayoutService = EditorScopedLayoutService = __decorate([
        __param(1, codeEditorService_1.ICodeEditorService)
    ], EditorScopedLayoutService);
    (0, extensions_1.registerSingleton)(layoutService_1.ILayoutService, StandaloneLayoutService, 1 /* InstantiationType.Delayed */);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[693/*vs/platform/accessibility/browser/accessibilityService*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,52/*vs/base/browser/window*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,61/*vs/platform/accessibility/common/accessibility*/,28/*vs/platform/configuration/common/configuration*/,12/*vs/platform/contextkey/common/contextkey*/,119/*vs/platform/layout/browser/layoutService*/]), function (require, exports, dom_1, window_1, event_1, lifecycle_1, accessibility_1, configuration_1, contextkey_1, layoutService_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AccessibilityService = void 0;
    let AccessibilityService = class AccessibilityService extends lifecycle_1.Disposable {
        constructor(_contextKeyService, _layoutService, _configurationService) {
            super();
            this._contextKeyService = _contextKeyService;
            this._layoutService = _layoutService;
            this._configurationService = _configurationService;
            this._accessibilitySupport = 0 /* AccessibilitySupport.Unknown */;
            this._onDidChangeScreenReaderOptimized = new event_1.Emitter();
            this._onDidChangeReducedMotion = new event_1.Emitter();
            this._onDidChangeLinkUnderline = new event_1.Emitter();
            this._accessibilityModeEnabledContext = accessibility_1.CONTEXT_ACCESSIBILITY_MODE_ENABLED.bindTo(this._contextKeyService);
            const updateContextKey = () => this._accessibilityModeEnabledContext.set(this.isScreenReaderOptimized());
            this._register(this._configurationService.onDidChangeConfiguration(e => {
                if (e.affectsConfiguration('editor.accessibilitySupport')) {
                    updateContextKey();
                    this._onDidChangeScreenReaderOptimized.fire();
                }
                if (e.affectsConfiguration('workbench.reduceMotion')) {
                    this._configMotionReduced = this._configurationService.getValue('workbench.reduceMotion');
                    this._onDidChangeReducedMotion.fire();
                }
            }));
            updateContextKey();
            this._register(this.onDidChangeScreenReaderOptimized(() => updateContextKey()));
            const reduceMotionMatcher = window_1.mainWindow.matchMedia(`(prefers-reduced-motion: reduce)`);
            this._systemMotionReduced = reduceMotionMatcher.matches;
            this._configMotionReduced = this._configurationService.getValue('workbench.reduceMotion');
            this._linkUnderlinesEnabled = this._configurationService.getValue('accessibility.underlineLinks');
            this.initReducedMotionListeners(reduceMotionMatcher);
            this.initLinkUnderlineListeners();
        }
        initReducedMotionListeners(reduceMotionMatcher) {
            this._register((0, dom_1.addDisposableListener)(reduceMotionMatcher, 'change', () => {
                this._systemMotionReduced = reduceMotionMatcher.matches;
                if (this._configMotionReduced === 'auto') {
                    this._onDidChangeReducedMotion.fire();
                }
            }));
            const updateRootClasses = () => {
                const reduce = this.isMotionReduced();
                this._layoutService.mainContainer.classList.toggle('reduce-motion', reduce);
                this._layoutService.mainContainer.classList.toggle('enable-motion', !reduce);
            };
            updateRootClasses();
            this._register(this.onDidChangeReducedMotion(() => updateRootClasses()));
        }
        initLinkUnderlineListeners() {
            this._register(this._configurationService.onDidChangeConfiguration(e => {
                if (e.affectsConfiguration('accessibility.underlineLinks')) {
                    const linkUnderlinesEnabled = this._configurationService.getValue('accessibility.underlineLinks');
                    this._linkUnderlinesEnabled = linkUnderlinesEnabled;
                    this._onDidChangeLinkUnderline.fire();
                }
            }));
            const updateLinkUnderlineClasses = () => {
                const underlineLinks = this._linkUnderlinesEnabled;
                this._layoutService.mainContainer.classList.toggle('underline-links', underlineLinks);
            };
            updateLinkUnderlineClasses();
            this._register(this.onDidChangeLinkUnderlines(() => updateLinkUnderlineClasses()));
        }
        onDidChangeLinkUnderlines(listener) {
            return this._onDidChangeLinkUnderline.event(listener);
        }
        get onDidChangeScreenReaderOptimized() {
            return this._onDidChangeScreenReaderOptimized.event;
        }
        isScreenReaderOptimized() {
            const config = this._configurationService.getValue('editor.accessibilitySupport');
            return config === 'on' || (config === 'auto' && this._accessibilitySupport === 2 /* AccessibilitySupport.Enabled */);
        }
        get onDidChangeReducedMotion() {
            return this._onDidChangeReducedMotion.event;
        }
        isMotionReduced() {
            const config = this._configMotionReduced;
            return config === 'on' || (config === 'auto' && this._systemMotionReduced);
        }
        getAccessibilitySupport() {
            return this._accessibilitySupport;
        }
    };
    exports.AccessibilityService = AccessibilityService;
    exports.AccessibilityService = AccessibilityService = __decorate([
        __param(0, contextkey_1.IContextKeyService),
        __param(1, layoutService_1.ILayoutService),
        __param(2, configuration_1.IConfigurationService)
    ], AccessibilityService);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[395/*vs/platform/contextview/browser/contextViewService*/], __M([1/*require*/,0/*exports*/,353/*vs/base/browser/ui/contextview/contextview*/,2/*vs/base/common/lifecycle*/,119/*vs/platform/layout/browser/layoutService*/,5/*vs/base/browser/dom*/]), function (require, exports, contextview_1, lifecycle_1, layoutService_1, dom_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ContextViewService = exports.ContextViewHandler = void 0;
    let ContextViewHandler = class ContextViewHandler extends lifecycle_1.Disposable {
        constructor(layoutService) {
            super();
            this.layoutService = layoutService;
            this.contextView = this._register(new contextview_1.ContextView(this.layoutService.mainContainer, 1 /* ContextViewDOMPosition.ABSOLUTE */));
            this.layout();
            this._register(layoutService.onDidLayoutContainer(() => this.layout()));
        }
        // ContextView
        showContextView(delegate, container, shadowRoot) {
            let domPosition;
            if (container) {
                if (container === this.layoutService.getContainer((0, dom_1.getWindow)(container))) {
                    domPosition = 1 /* ContextViewDOMPosition.ABSOLUTE */;
                }
                else if (shadowRoot) {
                    domPosition = 3 /* ContextViewDOMPosition.FIXED_SHADOW */;
                }
                else {
                    domPosition = 2 /* ContextViewDOMPosition.FIXED */;
                }
            }
            else {
                domPosition = 1 /* ContextViewDOMPosition.ABSOLUTE */;
            }
            this.contextView.setContainer(container ?? this.layoutService.activeContainer, domPosition);
            this.contextView.show(delegate);
            const openContextView = {
                close: () => {
                    if (this.openContextView === openContextView) {
                        this.hideContextView();
                    }
                }
            };
            this.openContextView = openContextView;
            return openContextView;
        }
        layout() {
            this.contextView.layout();
        }
        hideContextView(data) {
            this.contextView.hide(data);
            this.openContextView = undefined;
        }
    };
    exports.ContextViewHandler = ContextViewHandler;
    exports.ContextViewHandler = ContextViewHandler = __decorate([
        __param(0, layoutService_1.ILayoutService)
    ], ContextViewHandler);
    class ContextViewService extends ContextViewHandler {
        getContextViewElement() {
            return this.contextView.getViewElement();
        }
    }
    exports.ContextViewService = ContextViewService;
});

define(__m[62/*vs/platform/log/common/log*/], __M([1/*require*/,0/*exports*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,12/*vs/platform/contextkey/common/contextkey*/,7/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, event_1, lifecycle_1, contextkey_1, instantiation_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CONTEXT_LOG_LEVEL = exports.MultiplexLogger = exports.ConsoleLogger = exports.AbstractLogger = exports.DEFAULT_LOG_LEVEL = exports.LogLevel = exports.ILogService = void 0;
    exports.LogLevelToString = LogLevelToString;
    exports.ILogService = (0, instantiation_1.createDecorator)('logService');
    var LogLevel;
    (function (LogLevel) {
        LogLevel[LogLevel["Off"] = 0] = "Off";
        LogLevel[LogLevel["Trace"] = 1] = "Trace";
        LogLevel[LogLevel["Debug"] = 2] = "Debug";
        LogLevel[LogLevel["Info"] = 3] = "Info";
        LogLevel[LogLevel["Warning"] = 4] = "Warning";
        LogLevel[LogLevel["Error"] = 5] = "Error";
    })(LogLevel || (exports.LogLevel = LogLevel = {}));
    exports.DEFAULT_LOG_LEVEL = LogLevel.Info;
    class AbstractLogger extends lifecycle_1.Disposable {
        constructor() {
            super(...arguments);
            this.level = exports.DEFAULT_LOG_LEVEL;
            this._onDidChangeLogLevel = this._register(new event_1.Emitter());
            this.onDidChangeLogLevel = this._onDidChangeLogLevel.event;
        }
        setLevel(level) {
            if (this.level !== level) {
                this.level = level;
                this._onDidChangeLogLevel.fire(this.level);
            }
        }
        getLevel() {
            return this.level;
        }
        checkLogLevel(level) {
            return this.level !== LogLevel.Off && this.level <= level;
        }
    }
    exports.AbstractLogger = AbstractLogger;
    class ConsoleLogger extends AbstractLogger {
        constructor(logLevel = exports.DEFAULT_LOG_LEVEL, useColors = true) {
            super();
            this.useColors = useColors;
            this.setLevel(logLevel);
        }
        trace(message, ...args) {
            if (this.checkLogLevel(LogLevel.Trace)) {
                if (this.useColors) {
                    console.log('%cTRACE', 'color: #888', message, ...args);
                }
                else {
                    console.log(message, ...args);
                }
            }
        }
        debug(message, ...args) {
            if (this.checkLogLevel(LogLevel.Debug)) {
                if (this.useColors) {
                    console.log('%cDEBUG', 'background: #eee; color: #888', message, ...args);
                }
                else {
                    console.log(message, ...args);
                }
            }
        }
        info(message, ...args) {
            if (this.checkLogLevel(LogLevel.Info)) {
                if (this.useColors) {
                    console.log('%c INFO', 'color: #33f', message, ...args);
                }
                else {
                    console.log(message, ...args);
                }
            }
        }
        warn(message, ...args) {
            if (this.checkLogLevel(LogLevel.Warning)) {
                if (this.useColors) {
                    console.log('%c WARN', 'color: #993', message, ...args);
                }
                else {
                    console.log(message, ...args);
                }
            }
        }
        error(message, ...args) {
            if (this.checkLogLevel(LogLevel.Error)) {
                if (this.useColors) {
                    console.log('%c  ERR', 'color: #f33', message, ...args);
                }
                else {
                    console.error(message, ...args);
                }
            }
        }
    }
    exports.ConsoleLogger = ConsoleLogger;
    class MultiplexLogger extends AbstractLogger {
        constructor(loggers) {
            super();
            this.loggers = loggers;
            if (loggers.length) {
                this.setLevel(loggers[0].getLevel());
            }
        }
        setLevel(level) {
            for (const logger of this.loggers) {
                logger.setLevel(level);
            }
            super.setLevel(level);
        }
        trace(message, ...args) {
            for (const logger of this.loggers) {
                logger.trace(message, ...args);
            }
        }
        debug(message, ...args) {
            for (const logger of this.loggers) {
                logger.debug(message, ...args);
            }
        }
        info(message, ...args) {
            for (const logger of this.loggers) {
                logger.info(message, ...args);
            }
        }
        warn(message, ...args) {
            for (const logger of this.loggers) {
                logger.warn(message, ...args);
            }
        }
        error(message, ...args) {
            for (const logger of this.loggers) {
                logger.error(message, ...args);
            }
        }
        dispose() {
            for (const logger of this.loggers) {
                logger.dispose();
            }
            super.dispose();
        }
    }
    exports.MultiplexLogger = MultiplexLogger;
    function LogLevelToString(logLevel) {
        switch (logLevel) {
            case LogLevel.Trace: return 'trace';
            case LogLevel.Debug: return 'debug';
            case LogLevel.Info: return 'info';
            case LogLevel.Warning: return 'warn';
            case LogLevel.Error: return 'error';
            case LogLevel.Off: return 'off';
        }
    }
    // Contexts
    exports.CONTEXT_LOG_LEVEL = new contextkey_1.RawContextKey('logLevel', LogLevelToString(LogLevel.Info));
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[212/*vs/editor/browser/controller/textAreaInput*/], __M([1/*require*/,0/*exports*/,64/*vs/base/browser/browser*/,5/*vs/base/browser/dom*/,93/*vs/base/browser/event*/,47/*vs/base/browser/keyboardEvent*/,296/*vs/base/browser/performance*/,14/*vs/base/common/async*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,128/*vs/base/common/mime*/,11/*vs/base/common/strings*/,310/*vs/editor/browser/controller/textAreaState*/,23/*vs/editor/common/core/selection*/,61/*vs/platform/accessibility/common/accessibility*/,62/*vs/platform/log/common/log*/]), function (require, exports, browser, dom, event_1, keyboardEvent_1, performance_1, async_1, event_2, lifecycle_1, mime_1, strings, textAreaState_1, selection_1, accessibility_1, log_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.TextAreaWrapper = exports.ClipboardEventUtils = exports.TextAreaInput = exports.InMemoryClipboardMetadataManager = exports.CopyOptions = exports.TextAreaSyntethicEvents = void 0;
    var TextAreaSyntethicEvents;
    (function (TextAreaSyntethicEvents) {
        TextAreaSyntethicEvents.Tap = '-monaco-textarea-synthetic-tap';
    })(TextAreaSyntethicEvents || (exports.TextAreaSyntethicEvents = TextAreaSyntethicEvents = {}));
    exports.CopyOptions = {
        forceCopyWithSyntaxHighlighting: false
    };
    /**
     * Every time we write to the clipboard, we record a bit of extra metadata here.
     * Every time we read from the cipboard, if the text matches our last written text,
     * we can fetch the previous metadata.
     */
    class InMemoryClipboardMetadataManager {
        static { this.INSTANCE = new InMemoryClipboardMetadataManager(); }
        constructor() {
            this._lastState = null;
        }
        set(lastCopiedValue, data) {
            this._lastState = { lastCopiedValue, data };
        }
        get(pastedText) {
            if (this._lastState && this._lastState.lastCopiedValue === pastedText) {
                // match!
                return this._lastState.data;
            }
            this._lastState = null;
            return null;
        }
    }
    exports.InMemoryClipboardMetadataManager = InMemoryClipboardMetadataManager;
    class CompositionContext {
        constructor() {
            this._lastTypeTextLength = 0;
        }
        handleCompositionUpdate(text) {
            text = text || '';
            const typeInput = {
                text: text,
                replacePrevCharCnt: this._lastTypeTextLength,
                replaceNextCharCnt: 0,
                positionDelta: 0
            };
            this._lastTypeTextLength = text.length;
            return typeInput;
        }
    }
    /**
     * Writes screen reader content to the textarea and is able to analyze its input events to generate:
     *  - onCut
     *  - onPaste
     *  - onType
     *
     * Composition events are generated for presentation purposes (composition input is reflected in onType).
     */
    let TextAreaInput = class TextAreaInput extends lifecycle_1.Disposable {
        get textAreaState() {
            return this._textAreaState;
        }
        constructor(_host, _textArea, _OS, _browser, _accessibilityService, _logService) {
            super();
            this._host = _host;
            this._textArea = _textArea;
            this._OS = _OS;
            this._browser = _browser;
            this._accessibilityService = _accessibilityService;
            this._logService = _logService;
            this._onFocus = this._register(new event_2.Emitter());
            this.onFocus = this._onFocus.event;
            this._onBlur = this._register(new event_2.Emitter());
            this.onBlur = this._onBlur.event;
            this._onKeyDown = this._register(new event_2.Emitter());
            this.onKeyDown = this._onKeyDown.event;
            this._onKeyUp = this._register(new event_2.Emitter());
            this.onKeyUp = this._onKeyUp.event;
            this._onCut = this._register(new event_2.Emitter());
            this.onCut = this._onCut.event;
            this._onPaste = this._register(new event_2.Emitter());
            this.onPaste = this._onPaste.event;
            this._onType = this._register(new event_2.Emitter());
            this.onType = this._onType.event;
            this._onCompositionStart = this._register(new event_2.Emitter());
            this.onCompositionStart = this._onCompositionStart.event;
            this._onCompositionUpdate = this._register(new event_2.Emitter());
            this.onCompositionUpdate = this._onCompositionUpdate.event;
            this._onCompositionEnd = this._register(new event_2.Emitter());
            this.onCompositionEnd = this._onCompositionEnd.event;
            this._onSelectionChangeRequest = this._register(new event_2.Emitter());
            this.onSelectionChangeRequest = this._onSelectionChangeRequest.event;
            this._asyncFocusGainWriteScreenReaderContent = this._register(new lifecycle_1.MutableDisposable());
            this._asyncTriggerCut = this._register(new async_1.RunOnceScheduler(() => this._onCut.fire(), 0));
            this._textAreaState = textAreaState_1.TextAreaState.EMPTY;
            this._selectionChangeListener = null;
            if (this._accessibilityService.isScreenReaderOptimized()) {
                this.writeNativeTextAreaContent('ctor');
            }
            this._register(event_2.Event.runAndSubscribe(this._accessibilityService.onDidChangeScreenReaderOptimized, () => {
                if (this._accessibilityService.isScreenReaderOptimized() && !this._asyncFocusGainWriteScreenReaderContent.value) {
                    this._asyncFocusGainWriteScreenReaderContent.value = this._register(new async_1.RunOnceScheduler(() => this.writeNativeTextAreaContent('asyncFocusGain'), 0));
                }
                else {
                    this._asyncFocusGainWriteScreenReaderContent.clear();
                }
            }));
            this._hasFocus = false;
            this._currentComposition = null;
            let lastKeyDown = null;
            this._register(this._textArea.onKeyDown((_e) => {
                const e = new keyboardEvent_1.StandardKeyboardEvent(_e);
                if (e.keyCode === 114 /* KeyCode.KEY_IN_COMPOSITION */
                    || (this._currentComposition && e.keyCode === 1 /* KeyCode.Backspace */)) {
                    // Stop propagation for keyDown events if the IME is processing key input
                    e.stopPropagation();
                }
                if (e.equals(9 /* KeyCode.Escape */)) {
                    // Prevent default always for `Esc`, otherwise it will generate a keypress
                    // See https://msdn.microsoft.com/en-us/library/ie/ms536939(v=vs.85).aspx
                    e.preventDefault();
                }
                lastKeyDown = e;
                this._onKeyDown.fire(e);
            }));
            this._register(this._textArea.onKeyUp((_e) => {
                const e = new keyboardEvent_1.StandardKeyboardEvent(_e);
                this._onKeyUp.fire(e);
            }));
            this._register(this._textArea.onCompositionStart((e) => {
                if (textAreaState_1._debugComposition) {
                    console.log(`[compositionstart]`, e);
                }
                const currentComposition = new CompositionContext();
                if (this._currentComposition) {
                    // simply reset the composition context
                    this._currentComposition = currentComposition;
                    return;
                }
                this._currentComposition = currentComposition;
                if (this._OS === 2 /* OperatingSystem.Macintosh */
                    && lastKeyDown
                    && lastKeyDown.equals(114 /* KeyCode.KEY_IN_COMPOSITION */)
                    && this._textAreaState.selectionStart === this._textAreaState.selectionEnd
                    && this._textAreaState.selectionStart > 0
                    && this._textAreaState.value.substr(this._textAreaState.selectionStart - 1, 1) === e.data
                    && (lastKeyDown.code === 'ArrowRight' || lastKeyDown.code === 'ArrowLeft')) {
                    // Handling long press case on Chromium/Safari macOS + arrow key => pretend the character was selected
                    if (textAreaState_1._debugComposition) {
                        console.log(`[compositionstart] Handling long press case on macOS + arrow key`, e);
                    }
                    // Pretend the previous character was composed (in order to get it removed by subsequent compositionupdate events)
                    currentComposition.handleCompositionUpdate('x');
                    this._onCompositionStart.fire({ data: e.data });
                    return;
                }
                if (this._browser.isAndroid) {
                    // when tapping on the editor, Android enters composition mode to edit the current word
                    // so we cannot clear the textarea on Android and we must pretend the current word was selected
                    this._onCompositionStart.fire({ data: e.data });
                    return;
                }
                this._onCompositionStart.fire({ data: e.data });
            }));
            this._register(this._textArea.onCompositionUpdate((e) => {
                if (textAreaState_1._debugComposition) {
                    console.log(`[compositionupdate]`, e);
                }
                const currentComposition = this._currentComposition;
                if (!currentComposition) {
                    // should not be possible to receive a 'compositionupdate' without a 'compositionstart'
                    return;
                }
                if (this._browser.isAndroid) {
                    // On Android, the data sent with the composition update event is unusable.
                    // For example, if the cursor is in the middle of a word like Mic|osoft
                    // and Microsoft is chosen from the keyboard's suggestions, the e.data will contain "Microsoft".
                    // This is not really usable because it doesn't tell us where the edit began and where it ended.
                    const newState = textAreaState_1.TextAreaState.readFromTextArea(this._textArea, this._textAreaState);
                    const typeInput = textAreaState_1.TextAreaState.deduceAndroidCompositionInput(this._textAreaState, newState);
                    this._textAreaState = newState;
                    this._onType.fire(typeInput);
                    this._onCompositionUpdate.fire(e);
                    return;
                }
                const typeInput = currentComposition.handleCompositionUpdate(e.data);
                this._textAreaState = textAreaState_1.TextAreaState.readFromTextArea(this._textArea, this._textAreaState);
                this._onType.fire(typeInput);
                this._onCompositionUpdate.fire(e);
            }));
            this._register(this._textArea.onCompositionEnd((e) => {
                if (textAreaState_1._debugComposition) {
                    console.log(`[compositionend]`, e);
                }
                const currentComposition = this._currentComposition;
                if (!currentComposition) {
                    // https://github.com/microsoft/monaco-editor/issues/1663
                    // On iOS 13.2, Chinese system IME randomly trigger an additional compositionend event with empty data
                    return;
                }
                this._currentComposition = null;
                if (this._browser.isAndroid) {
                    // On Android, the data sent with the composition update event is unusable.
                    // For example, if the cursor is in the middle of a word like Mic|osoft
                    // and Microsoft is chosen from the keyboard's suggestions, the e.data will contain "Microsoft".
                    // This is not really usable because it doesn't tell us where the edit began and where it ended.
                    const newState = textAreaState_1.TextAreaState.readFromTextArea(this._textArea, this._textAreaState);
                    const typeInput = textAreaState_1.TextAreaState.deduceAndroidCompositionInput(this._textAreaState, newState);
                    this._textAreaState = newState;
                    this._onType.fire(typeInput);
                    this._onCompositionEnd.fire();
                    return;
                }
                const typeInput = currentComposition.handleCompositionUpdate(e.data);
                this._textAreaState = textAreaState_1.TextAreaState.readFromTextArea(this._textArea, this._textAreaState);
                this._onType.fire(typeInput);
                this._onCompositionEnd.fire();
            }));
            this._register(this._textArea.onInput((e) => {
                if (textAreaState_1._debugComposition) {
                    console.log(`[input]`, e);
                }
                // Pretend here we touched the text area, as the `input` event will most likely
                // result in a `selectionchange` event which we want to ignore
                this._textArea.setIgnoreSelectionChangeTime('received input event');
                if (this._currentComposition) {
                    return;
                }
                const newState = textAreaState_1.TextAreaState.readFromTextArea(this._textArea, this._textAreaState);
                const typeInput = textAreaState_1.TextAreaState.deduceInput(this._textAreaState, newState, /*couldBeEmojiInput*/ this._OS === 2 /* OperatingSystem.Macintosh */);
                if (typeInput.replacePrevCharCnt === 0 && typeInput.text.length === 1) {
                    // one character was typed
                    if (strings.isHighSurrogate(typeInput.text.charCodeAt(0))
                        || typeInput.text.charCodeAt(0) === 0x7f /* Delete */) {
                        // Ignore invalid input but keep it around for next time
                        return;
                    }
                }
                this._textAreaState = newState;
                if (typeInput.text !== ''
                    || typeInput.replacePrevCharCnt !== 0
                    || typeInput.replaceNextCharCnt !== 0
                    || typeInput.positionDelta !== 0) {
                    this._onType.fire(typeInput);
                }
            }));
            // --- Clipboard operations
            this._register(this._textArea.onCut((e) => {
                // Pretend here we touched the text area, as the `cut` event will most likely
                // result in a `selectionchange` event which we want to ignore
                this._textArea.setIgnoreSelectionChangeTime('received cut event');
                this._ensureClipboardGetsEditorSelection(e);
                this._asyncTriggerCut.schedule();
            }));
            this._register(this._textArea.onCopy((e) => {
                this._ensureClipboardGetsEditorSelection(e);
            }));
            this._register(this._textArea.onPaste((e) => {
                // Pretend here we touched the text area, as the `paste` event will most likely
                // result in a `selectionchange` event which we want to ignore
                this._textArea.setIgnoreSelectionChangeTime('received paste event');
                e.preventDefault();
                if (!e.clipboardData) {
                    return;
                }
                let [text, metadata] = exports.ClipboardEventUtils.getTextData(e.clipboardData);
                if (!text) {
                    return;
                }
                // try the in-memory store
                metadata = metadata || InMemoryClipboardMetadataManager.INSTANCE.get(text);
                this._onPaste.fire({
                    text: text,
                    metadata: metadata
                });
            }));
            this._register(this._textArea.onFocus(() => {
                const hadFocus = this._hasFocus;
                this._setHasFocus(true);
                if (this._accessibilityService.isScreenReaderOptimized() && this._browser.isSafari && !hadFocus && this._hasFocus) {
                    // When "tabbing into" the textarea, immediately after dispatching the 'focus' event,
                    // Safari will always move the selection at offset 0 in the textarea
                    if (!this._asyncFocusGainWriteScreenReaderContent.value) {
                        this._asyncFocusGainWriteScreenReaderContent.value = new async_1.RunOnceScheduler(() => this.writeNativeTextAreaContent('asyncFocusGain'), 0);
                    }
                    this._asyncFocusGainWriteScreenReaderContent.value.schedule();
                }
            }));
            this._register(this._textArea.onBlur(() => {
                if (this._currentComposition) {
                    // See https://github.com/microsoft/vscode/issues/112621
                    // where compositionend is not triggered when the editor
                    // is taken off-dom during a composition
                    // Clear the flag to be able to write to the textarea
                    this._currentComposition = null;
                    // Clear the textarea to avoid an unwanted cursor type
                    this.writeNativeTextAreaContent('blurWithoutCompositionEnd');
                    // Fire artificial composition end
                    this._onCompositionEnd.fire();
                }
                this._setHasFocus(false);
            }));
            this._register(this._textArea.onSyntheticTap(() => {
                if (this._browser.isAndroid && this._currentComposition) {
                    // on Android, tapping does not cancel the current composition, so the
                    // textarea is stuck showing the old composition
                    // Clear the flag to be able to write to the textarea
                    this._currentComposition = null;
                    // Clear the textarea to avoid an unwanted cursor type
                    this.writeNativeTextAreaContent('tapWithoutCompositionEnd');
                    // Fire artificial composition end
                    this._onCompositionEnd.fire();
                }
            }));
        }
        _installSelectionChangeListener() {
            // See https://github.com/microsoft/vscode/issues/27216 and https://github.com/microsoft/vscode/issues/98256
            // When using a Braille display, it is possible for users to reposition the
            // system caret. This is reflected in Chrome as a `selectionchange` event.
            //
            // The `selectionchange` event appears to be emitted under numerous other circumstances,
            // so it is quite a challenge to distinguish a `selectionchange` coming in from a user
            // using a Braille display from all the other cases.
            //
            // The problems with the `selectionchange` event are:
            //  * the event is emitted when the textarea is focused programmatically -- textarea.focus()
            //  * the event is emitted when the selection is changed in the textarea programmatically -- textarea.setSelectionRange(...)
            //  * the event is emitted when the value of the textarea is changed programmatically -- textarea.value = '...'
            //  * the event is emitted when tabbing into the textarea
            //  * the event is emitted asynchronously (sometimes with a delay as high as a few tens of ms)
            //  * the event sometimes comes in bursts for a single logical textarea operation
            // `selectionchange` events often come multiple times for a single logical change
            // so throttle multiple `selectionchange` events that burst in a short period of time.
            let previousSelectionChangeEventTime = 0;
            return dom.addDisposableListener(this._textArea.ownerDocument, 'selectionchange', (e) => {
                performance_1.inputLatency.onSelectionChange();
                if (!this._hasFocus) {
                    return;
                }
                if (this._currentComposition) {
                    return;
                }
                if (!this._browser.isChrome) {
                    // Support only for Chrome until testing happens on other browsers
                    return;
                }
                const now = Date.now();
                const delta1 = now - previousSelectionChangeEventTime;
                previousSelectionChangeEventTime = now;
                if (delta1 < 5) {
                    // received another `selectionchange` event within 5ms of the previous `selectionchange` event
                    // => ignore it
                    return;
                }
                const delta2 = now - this._textArea.getIgnoreSelectionChangeTime();
                this._textArea.resetSelectionChangeTime();
                if (delta2 < 100) {
                    // received a `selectionchange` event within 100ms since we touched the textarea
                    // => ignore it, since we caused it
                    return;
                }
                if (!this._textAreaState.selection) {
                    // Cannot correlate a position in the textarea with a position in the editor...
                    return;
                }
                const newValue = this._textArea.getValue();
                if (this._textAreaState.value !== newValue) {
                    // Cannot correlate a position in the textarea with a position in the editor...
                    return;
                }
                const newSelectionStart = this._textArea.getSelectionStart();
                const newSelectionEnd = this._textArea.getSelectionEnd();
                if (this._textAreaState.selectionStart === newSelectionStart && this._textAreaState.selectionEnd === newSelectionEnd) {
                    // Nothing to do...
                    return;
                }
                const _newSelectionStartPosition = this._textAreaState.deduceEditorPosition(newSelectionStart);
                const newSelectionStartPosition = this._host.deduceModelPosition(_newSelectionStartPosition[0], _newSelectionStartPosition[1], _newSelectionStartPosition[2]);
                const _newSelectionEndPosition = this._textAreaState.deduceEditorPosition(newSelectionEnd);
                const newSelectionEndPosition = this._host.deduceModelPosition(_newSelectionEndPosition[0], _newSelectionEndPosition[1], _newSelectionEndPosition[2]);
                const newSelection = new selection_1.Selection(newSelectionStartPosition.lineNumber, newSelectionStartPosition.column, newSelectionEndPosition.lineNumber, newSelectionEndPosition.column);
                this._onSelectionChangeRequest.fire(newSelection);
            });
        }
        dispose() {
            super.dispose();
            if (this._selectionChangeListener) {
                this._selectionChangeListener.dispose();
                this._selectionChangeListener = null;
            }
        }
        focusTextArea() {
            // Setting this._hasFocus and writing the screen reader content
            // will result in a focus() and setSelectionRange() in the textarea
            this._setHasFocus(true);
            // If the editor is off DOM, focus cannot be really set, so let's double check that we have managed to set the focus
            this.refreshFocusState();
        }
        isFocused() {
            return this._hasFocus;
        }
        refreshFocusState() {
            this._setHasFocus(this._textArea.hasFocus());
        }
        _setHasFocus(newHasFocus) {
            if (this._hasFocus === newHasFocus) {
                // no change
                return;
            }
            this._hasFocus = newHasFocus;
            if (this._selectionChangeListener) {
                this._selectionChangeListener.dispose();
                this._selectionChangeListener = null;
            }
            if (this._hasFocus) {
                this._selectionChangeListener = this._installSelectionChangeListener();
            }
            if (this._hasFocus) {
                this.writeNativeTextAreaContent('focusgain');
            }
            if (this._hasFocus) {
                this._onFocus.fire();
            }
            else {
                this._onBlur.fire();
            }
        }
        _setAndWriteTextAreaState(reason, textAreaState) {
            if (!this._hasFocus) {
                textAreaState = textAreaState.collapseSelection();
            }
            textAreaState.writeToTextArea(reason, this._textArea, this._hasFocus);
            this._textAreaState = textAreaState;
        }
        writeNativeTextAreaContent(reason) {
            if ((!this._accessibilityService.isScreenReaderOptimized() && reason === 'render') || this._currentComposition) {
                // Do not write to the text on render unless a screen reader is being used #192278
                // Do not write to the text area when doing composition
                return;
            }
            this._logService.trace(`writeTextAreaState(reason: ${reason})`);
            this._setAndWriteTextAreaState(reason, this._host.getScreenReaderContent());
        }
        _ensureClipboardGetsEditorSelection(e) {
            const dataToCopy = this._host.getDataToCopy();
            const storedMetadata = {
                version: 1,
                isFromEmptySelection: dataToCopy.isFromEmptySelection,
                multicursorText: dataToCopy.multicursorText,
                mode: dataToCopy.mode
            };
            InMemoryClipboardMetadataManager.INSTANCE.set(
            // When writing "LINE\r\n" to the clipboard and then pasting,
            // Firefox pastes "LINE\n", so let's work around this quirk
            (this._browser.isFirefox ? dataToCopy.text.replace(/\r\n/g, '\n') : dataToCopy.text), storedMetadata);
            e.preventDefault();
            if (e.clipboardData) {
                exports.ClipboardEventUtils.setTextData(e.clipboardData, dataToCopy.text, dataToCopy.html, storedMetadata);
            }
        }
    };
    exports.TextAreaInput = TextAreaInput;
    exports.TextAreaInput = TextAreaInput = __decorate([
        __param(4, accessibility_1.IAccessibilityService),
        __param(5, log_1.ILogService)
    ], TextAreaInput);
    exports.ClipboardEventUtils = {
        getTextData(clipboardData) {
            const text = clipboardData.getData(mime_1.Mimes.text);
            let metadata = null;
            const rawmetadata = clipboardData.getData('vscode-editor-data');
            if (typeof rawmetadata === 'string') {
                try {
                    metadata = JSON.parse(rawmetadata);
                    if (metadata.version !== 1) {
                        metadata = null;
                    }
                }
                catch (err) {
                    // no problem!
                }
            }
            if (text.length === 0 && metadata === null && clipboardData.files.length > 0) {
                // no textual data pasted, generate text from file names
                const files = Array.prototype.slice.call(clipboardData.files, 0);
                return [files.map(file => file.name).join('\n'), null];
            }
            return [text, metadata];
        },
        setTextData(clipboardData, text, html, metadata) {
            clipboardData.setData(mime_1.Mimes.text, text);
            if (typeof html === 'string') {
                clipboardData.setData('text/html', html);
            }
            clipboardData.setData('vscode-editor-data', JSON.stringify(metadata));
        }
    };
    class TextAreaWrapper extends lifecycle_1.Disposable {
        get ownerDocument() {
            return this._actual.ownerDocument;
        }
        constructor(_actual) {
            super();
            this._actual = _actual;
            this.onKeyDown = this._register(new event_1.DomEmitter(this._actual, 'keydown')).event;
            this.onKeyUp = this._register(new event_1.DomEmitter(this._actual, 'keyup')).event;
            this.onCompositionStart = this._register(new event_1.DomEmitter(this._actual, 'compositionstart')).event;
            this.onCompositionUpdate = this._register(new event_1.DomEmitter(this._actual, 'compositionupdate')).event;
            this.onCompositionEnd = this._register(new event_1.DomEmitter(this._actual, 'compositionend')).event;
            this.onBeforeInput = this._register(new event_1.DomEmitter(this._actual, 'beforeinput')).event;
            this.onInput = this._register(new event_1.DomEmitter(this._actual, 'input')).event;
            this.onCut = this._register(new event_1.DomEmitter(this._actual, 'cut')).event;
            this.onCopy = this._register(new event_1.DomEmitter(this._actual, 'copy')).event;
            this.onPaste = this._register(new event_1.DomEmitter(this._actual, 'paste')).event;
            this.onFocus = this._register(new event_1.DomEmitter(this._actual, 'focus')).event;
            this.onBlur = this._register(new event_1.DomEmitter(this._actual, 'blur')).event;
            this._onSyntheticTap = this._register(new event_2.Emitter());
            this.onSyntheticTap = this._onSyntheticTap.event;
            this._ignoreSelectionChangeTime = 0;
            this._register(this.onKeyDown(() => performance_1.inputLatency.onKeyDown()));
            this._register(this.onBeforeInput(() => performance_1.inputLatency.onBeforeInput()));
            this._register(this.onInput(() => performance_1.inputLatency.onInput()));
            this._register(this.onKeyUp(() => performance_1.inputLatency.onKeyUp()));
            this._register(dom.addDisposableListener(this._actual, TextAreaSyntethicEvents.Tap, () => this._onSyntheticTap.fire()));
        }
        hasFocus() {
            const shadowRoot = dom.getShadowRoot(this._actual);
            if (shadowRoot) {
                return shadowRoot.activeElement === this._actual;
            }
            else if (this._actual.isConnected) {
                return dom.getActiveElement() === this._actual;
            }
            else {
                return false;
            }
        }
        setIgnoreSelectionChangeTime(reason) {
            this._ignoreSelectionChangeTime = Date.now();
        }
        getIgnoreSelectionChangeTime() {
            return this._ignoreSelectionChangeTime;
        }
        resetSelectionChangeTime() {
            this._ignoreSelectionChangeTime = 0;
        }
        getValue() {
            // console.log('current value: ' + this._textArea.value);
            return this._actual.value;
        }
        setValue(reason, value) {
            const textArea = this._actual;
            if (textArea.value === value) {
                // No change
                return;
            }
            // console.log('reason: ' + reason + ', current value: ' + textArea.value + ' => new value: ' + value);
            this.setIgnoreSelectionChangeTime('setValue');
            textArea.value = value;
        }
        getSelectionStart() {
            return this._actual.selectionDirection === 'backward' ? this._actual.selectionEnd : this._actual.selectionStart;
        }
        getSelectionEnd() {
            return this._actual.selectionDirection === 'backward' ? this._actual.selectionStart : this._actual.selectionEnd;
        }
        setSelectionRange(reason, selectionStart, selectionEnd) {
            const textArea = this._actual;
            let activeElement = null;
            const shadowRoot = dom.getShadowRoot(textArea);
            if (shadowRoot) {
                activeElement = shadowRoot.activeElement;
            }
            else {
                activeElement = dom.getActiveElement();
            }
            const activeWindow = dom.getWindow(activeElement);
            const currentIsFocused = (activeElement === textArea);
            const currentSelectionStart = textArea.selectionStart;
            const currentSelectionEnd = textArea.selectionEnd;
            if (currentIsFocused && currentSelectionStart === selectionStart && currentSelectionEnd === selectionEnd) {
                // No change
                // Firefox iframe bug https://github.com/microsoft/monaco-editor/issues/643#issuecomment-367871377
                if (browser.isFirefox && activeWindow.parent !== activeWindow) {
                    textArea.focus();
                }
                return;
            }
            // console.log('reason: ' + reason + ', setSelectionRange: ' + selectionStart + ' -> ' + selectionEnd);
            if (currentIsFocused) {
                // No need to focus, only need to change the selection range
                this.setIgnoreSelectionChangeTime('setSelectionRange');
                textArea.setSelectionRange(selectionStart, selectionEnd);
                if (browser.isFirefox && activeWindow.parent !== activeWindow) {
                    textArea.focus();
                }
                return;
            }
            // If the focus is outside the textarea, browsers will try really hard to reveal the textarea.
            // Here, we try to undo the browser's desperate reveal.
            try {
                const scrollState = dom.saveParentsScrollTop(textArea);
                this.setIgnoreSelectionChangeTime('setSelectionRange');
                textArea.focus();
                textArea.setSelectionRange(selectionStart, selectionEnd);
                dom.restoreParentsScrollTop(textArea, scrollState);
            }
            catch (e) {
                // Sometimes IE throws when setting selection (e.g. textarea is off-DOM)
            }
        }
    }
    exports.TextAreaWrapper = TextAreaWrapper;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[79/*vs/editor/common/services/languageFeatureDebounce*/], __M([1/*require*/,0/*exports*/,129/*vs/base/common/hash*/,45/*vs/base/common/map*/,141/*vs/base/common/numbers*/,271/*vs/platform/environment/common/environment*/,49/*vs/platform/instantiation/common/extensions*/,7/*vs/platform/instantiation/common/instantiation*/,62/*vs/platform/log/common/log*/,42/*vs/base/common/network*/]), function (require, exports, hash_1, map_1, numbers_1, environment_1, extensions_1, instantiation_1, log_1, network_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.LanguageFeatureDebounceService = exports.ILanguageFeatureDebounceService = void 0;
    exports.ILanguageFeatureDebounceService = (0, instantiation_1.createDecorator)('ILanguageFeatureDebounceService');
    var IdentityHash;
    (function (IdentityHash) {
        const _hashes = new WeakMap();
        let pool = 0;
        function of(obj) {
            let value = _hashes.get(obj);
            if (value === undefined) {
                value = ++pool;
                _hashes.set(obj, value);
            }
            return value;
        }
        IdentityHash.of = of;
    })(IdentityHash || (IdentityHash = {}));
    class NullDebounceInformation {
        constructor(_default) {
            this._default = _default;
        }
        get(_model) {
            return this._default;
        }
        update(_model, _value) {
            return this._default;
        }
        default() {
            return this._default;
        }
    }
    class FeatureDebounceInformation {
        constructor(_logService, _name, _registry, _default, _min, _max) {
            this._logService = _logService;
            this._name = _name;
            this._registry = _registry;
            this._default = _default;
            this._min = _min;
            this._max = _max;
            this._cache = new map_1.LRUCache(50, 0.7);
        }
        _key(model) {
            return model.id + this._registry.all(model).reduce((hashVal, obj) => (0, hash_1.doHash)(IdentityHash.of(obj), hashVal), 0);
        }
        get(model) {
            const key = this._key(model);
            const avg = this._cache.get(key);
            return avg
                ? (0, numbers_1.clamp)(avg.value, this._min, this._max)
                : this.default();
        }
        update(model, value) {
            const key = this._key(model);
            let avg = this._cache.get(key);
            if (!avg) {
                avg = new numbers_1.SlidingWindowAverage(6);
                this._cache.set(key, avg);
            }
            const newValue = (0, numbers_1.clamp)(avg.update(value), this._min, this._max);
            if (!(0, network_1.matchesScheme)(model.uri, 'output')) {
                this._logService.trace(`[DEBOUNCE: ${this._name}] for ${model.uri.toString()} is ${newValue}ms`);
            }
            return newValue;
        }
        _overall() {
            const result = new numbers_1.MovingAverage();
            for (const [, avg] of this._cache) {
                result.update(avg.value);
            }
            return result.value;
        }
        default() {
            const value = (this._overall() | 0) || this._default;
            return (0, numbers_1.clamp)(value, this._min, this._max);
        }
    }
    let LanguageFeatureDebounceService = class LanguageFeatureDebounceService {
        constructor(_logService, envService) {
            this._logService = _logService;
            this._data = new Map();
            this._isDev = envService.isExtensionDevelopment || !envService.isBuilt;
        }
        for(feature, name, config) {
            const min = config?.min ?? 50;
            const max = config?.max ?? min ** 2;
            const extra = config?.key ?? undefined;
            const key = `${IdentityHash.of(feature)},${min}${extra ? ',' + extra : ''}`;
            let info = this._data.get(key);
            if (!info) {
                if (this._isDev) {
                    this._logService.debug(`[DEBOUNCE: ${name}] is disabled in developed mode`);
                    info = new NullDebounceInformation(min * 1.5);
                }
                else {
                    info = new FeatureDebounceInformation(this._logService, name, feature, (this._overallAverage() | 0) || (min * 1.5), // default is overall default or derived from min-value
                    min, max);
                }
                this._data.set(key, info);
            }
            return info;
        }
        _overallAverage() {
            // Average of all language features. Not a great value but an approximation
            const result = new numbers_1.MovingAverage();
            for (const info of this._data.values()) {
                result.update(info.default());
            }
            return result.value;
        }
    };
    exports.LanguageFeatureDebounceService = LanguageFeatureDebounceService;
    exports.LanguageFeatureDebounceService = LanguageFeatureDebounceService = __decorate([
        __param(0, log_1.ILogService),
        __param(1, environment_1.IEnvironmentService)
    ], LanguageFeatureDebounceService);
    (0, extensions_1.registerSingleton)(exports.ILanguageFeatureDebounceService, LanguageFeatureDebounceService, 1 /* InstantiationType.Delayed */);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[182/*vs/editor/contrib/documentSymbols/browser/outlineModel*/], __M([1/*require*/,0/*exports*/,13/*vs/base/common/arrays*/,18/*vs/base/common/cancellation*/,8/*vs/base/common/errors*/,53/*vs/base/common/iterator*/,45/*vs/base/common/map*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/,79/*vs/editor/common/services/languageFeatureDebounce*/,7/*vs/platform/instantiation/common/instantiation*/,49/*vs/platform/instantiation/common/extensions*/,51/*vs/editor/common/services/model*/,2/*vs/base/common/lifecycle*/,17/*vs/editor/common/services/languageFeatures*/]), function (require, exports, arrays_1, cancellation_1, errors_1, iterator_1, map_1, position_1, range_1, languageFeatureDebounce_1, instantiation_1, extensions_1, model_1, lifecycle_1, languageFeatures_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.OutlineModelService = exports.IOutlineModelService = exports.OutlineModel = exports.OutlineGroup = exports.OutlineElement = exports.TreeElement = void 0;
    class TreeElement {
        remove() {
            this.parent?.children.delete(this.id);
        }
        static findId(candidate, container) {
            // complex id-computation which contains the origin/extension,
            // the parent path, and some dedupe logic when names collide
            let candidateId;
            if (typeof candidate === 'string') {
                candidateId = `${container.id}/${candidate}`;
            }
            else {
                candidateId = `${container.id}/${candidate.name}`;
                if (container.children.get(candidateId) !== undefined) {
                    candidateId = `${container.id}/${candidate.name}_${candidate.range.startLineNumber}_${candidate.range.startColumn}`;
                }
            }
            let id = candidateId;
            for (let i = 0; container.children.get(id) !== undefined; i++) {
                id = `${candidateId}_${i}`;
            }
            return id;
        }
        static empty(element) {
            return element.children.size === 0;
        }
    }
    exports.TreeElement = TreeElement;
    class OutlineElement extends TreeElement {
        constructor(id, parent, symbol) {
            super();
            this.id = id;
            this.parent = parent;
            this.symbol = symbol;
            this.children = new Map();
        }
    }
    exports.OutlineElement = OutlineElement;
    class OutlineGroup extends TreeElement {
        constructor(id, parent, label, order) {
            super();
            this.id = id;
            this.parent = parent;
            this.label = label;
            this.order = order;
            this.children = new Map();
        }
    }
    exports.OutlineGroup = OutlineGroup;
    class OutlineModel extends TreeElement {
        static create(registry, textModel, token) {
            const cts = new cancellation_1.CancellationTokenSource(token);
            const result = new OutlineModel(textModel.uri);
            const provider = registry.ordered(textModel);
            const promises = provider.map((provider, index) => {
                const id = TreeElement.findId(`provider_${index}`, result);
                const group = new OutlineGroup(id, result, provider.displayName ?? 'Unknown Outline Provider', index);
                return Promise.resolve(provider.provideDocumentSymbols(textModel, cts.token)).then(result => {
                    for (const info of result || []) {
                        OutlineModel._makeOutlineElement(info, group);
                    }
                    return group;
                }, err => {
                    (0, errors_1.onUnexpectedExternalError)(err);
                    return group;
                }).then(group => {
                    if (!TreeElement.empty(group)) {
                        result._groups.set(id, group);
                    }
                    else {
                        group.remove();
                    }
                });
            });
            const listener = registry.onDidChange(() => {
                const newProvider = registry.ordered(textModel);
                if (!(0, arrays_1.equals)(newProvider, provider)) {
                    cts.cancel();
                }
            });
            return Promise.all(promises).then(() => {
                if (cts.token.isCancellationRequested && !token.isCancellationRequested) {
                    return OutlineModel.create(registry, textModel, token);
                }
                else {
                    return result._compact();
                }
            }).finally(() => {
                cts.dispose();
                listener.dispose();
                cts.dispose();
            });
        }
        static _makeOutlineElement(info, container) {
            const id = TreeElement.findId(info, container);
            const res = new OutlineElement(id, container, info);
            if (info.children) {
                for (const childInfo of info.children) {
                    OutlineModel._makeOutlineElement(childInfo, res);
                }
            }
            container.children.set(res.id, res);
        }
        constructor(uri) {
            super();
            this.uri = uri;
            this.id = 'root';
            this.parent = undefined;
            this._groups = new Map();
            this.children = new Map();
            this.id = 'root';
            this.parent = undefined;
        }
        _compact() {
            let count = 0;
            for (const [key, group] of this._groups) {
                if (group.children.size === 0) { // empty
                    this._groups.delete(key);
                }
                else {
                    count += 1;
                }
            }
            if (count !== 1) {
                //
                this.children = this._groups;
            }
            else {
                // adopt all elements of the first group
                const group = iterator_1.Iterable.first(this._groups.values());
                for (const [, child] of group.children) {
                    child.parent = this;
                    this.children.set(child.id, child);
                }
            }
            return this;
        }
        getTopLevelSymbols() {
            const roots = [];
            for (const child of this.children.values()) {
                if (child instanceof OutlineElement) {
                    roots.push(child.symbol);
                }
                else {
                    roots.push(...iterator_1.Iterable.map(child.children.values(), child => child.symbol));
                }
            }
            return roots.sort((a, b) => range_1.Range.compareRangesUsingStarts(a.range, b.range));
        }
        asListOfDocumentSymbols() {
            const roots = this.getTopLevelSymbols();
            const bucket = [];
            OutlineModel._flattenDocumentSymbols(bucket, roots, '');
            return bucket.sort((a, b) => position_1.Position.compare(range_1.Range.getStartPosition(a.range), range_1.Range.getStartPosition(b.range)) || position_1.Position.compare(range_1.Range.getEndPosition(b.range), range_1.Range.getEndPosition(a.range)));
        }
        static _flattenDocumentSymbols(bucket, entries, overrideContainerLabel) {
            for (const entry of entries) {
                bucket.push({
                    kind: entry.kind,
                    tags: entry.tags,
                    name: entry.name,
                    detail: entry.detail,
                    containerName: entry.containerName || overrideContainerLabel,
                    range: entry.range,
                    selectionRange: entry.selectionRange,
                    children: undefined, // we flatten it...
                });
                // Recurse over children
                if (entry.children) {
                    OutlineModel._flattenDocumentSymbols(bucket, entry.children, entry.name);
                }
            }
        }
    }
    exports.OutlineModel = OutlineModel;
    exports.IOutlineModelService = (0, instantiation_1.createDecorator)('IOutlineModelService');
    let OutlineModelService = class OutlineModelService {
        constructor(_languageFeaturesService, debounces, modelService) {
            this._languageFeaturesService = _languageFeaturesService;
            this._disposables = new lifecycle_1.DisposableStore();
            this._cache = new map_1.LRUCache(10, 0.7);
            this._debounceInformation = debounces.for(_languageFeaturesService.documentSymbolProvider, 'DocumentSymbols', { min: 350 });
            // don't cache outline models longer than their text model
            this._disposables.add(modelService.onModelRemoved(textModel => {
                this._cache.delete(textModel.id);
            }));
        }
        dispose() {
            this._disposables.dispose();
        }
        async getOrCreate(textModel, token) {
            const registry = this._languageFeaturesService.documentSymbolProvider;
            const provider = registry.ordered(textModel);
            let data = this._cache.get(textModel.id);
            if (!data || data.versionId !== textModel.getVersionId() || !(0, arrays_1.equals)(data.provider, provider)) {
                const source = new cancellation_1.CancellationTokenSource();
                data = {
                    versionId: textModel.getVersionId(),
                    provider,
                    promiseCnt: 0,
                    source,
                    promise: OutlineModel.create(registry, textModel, source.token),
                    model: undefined,
                };
                this._cache.set(textModel.id, data);
                const now = Date.now();
                data.promise.then(outlineModel => {
                    data.model = outlineModel;
                    this._debounceInformation.update(textModel, Date.now() - now);
                }).catch(_err => {
                    this._cache.delete(textModel.id);
                });
            }
            if (data.model) {
                // resolved -> return data
                return data.model;
            }
            // increase usage counter
            data.promiseCnt += 1;
            const listener = token.onCancellationRequested(() => {
                // last -> cancel provider request, remove cached promise
                if (--data.promiseCnt === 0) {
                    data.source.cancel();
                    this._cache.delete(textModel.id);
                }
            });
            try {
                return await data.promise;
            }
            finally {
                listener.dispose();
            }
        }
    };
    exports.OutlineModelService = OutlineModelService;
    exports.OutlineModelService = OutlineModelService = __decorate([
        __param(0, languageFeatures_1.ILanguageFeaturesService),
        __param(1, languageFeatureDebounce_1.ILanguageFeatureDebounceService),
        __param(2, model_1.IModelService)
    ], OutlineModelService);
    (0, extensions_1.registerSingleton)(exports.IOutlineModelService, OutlineModelService, 1 /* InstantiationType.Delayed */);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[694/*vs/editor/contrib/diffEditorBreadcrumbs/browser/contribution*/], __M([1/*require*/,0/*exports*/,13/*vs/base/common/arrays*/,21/*vs/base/common/observable*/,383/*vs/editor/browser/widget/diffEditor/features/hideUnchangedRegionsFeature*/,88/*vs/editor/browser/widget/diffEditor/utils*/,17/*vs/editor/common/services/languageFeatures*/,182/*vs/editor/contrib/documentSymbols/browser/outlineModel*/,2/*vs/base/common/lifecycle*/,6/*vs/base/common/event*/]), function (require, exports, arrays_1, observable_1, hideUnchangedRegionsFeature_1, utils_1, languageFeatures_1, outlineModel_1, lifecycle_1, event_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    let DiffEditorBreadcrumbsSource = class DiffEditorBreadcrumbsSource extends lifecycle_1.Disposable {
        constructor(_textModel, _languageFeaturesService, _outlineModelService) {
            super();
            this._textModel = _textModel;
            this._languageFeaturesService = _languageFeaturesService;
            this._outlineModelService = _outlineModelService;
            this._currentModel = (0, observable_1.observableValue)(this, undefined);
            const documentSymbolProviderChanged = (0, observable_1.observableSignalFromEvent)('documentSymbolProvider.onDidChange', this._languageFeaturesService.documentSymbolProvider.onDidChange);
            const textModelChanged = (0, observable_1.observableSignalFromEvent)('_textModel.onDidChangeContent', event_1.Event.debounce(e => this._textModel.onDidChangeContent(e), () => undefined, 100));
            this._register((0, observable_1.autorunWithStore)(async (reader, store) => {
                documentSymbolProviderChanged.read(reader);
                textModelChanged.read(reader);
                const src = store.add(new utils_1.DisposableCancellationTokenSource());
                const model = await this._outlineModelService.getOrCreate(this._textModel, src.token);
                if (store.isDisposed) {
                    return;
                }
                this._currentModel.set(model, undefined);
            }));
        }
        getBreadcrumbItems(startRange, reader) {
            const m = this._currentModel.read(reader);
            if (!m) {
                return [];
            }
            const symbols = m.asListOfDocumentSymbols()
                .filter(s => startRange.contains(s.range.startLineNumber) && !startRange.contains(s.range.endLineNumber));
            symbols.sort((0, arrays_1.reverseOrder)((0, arrays_1.compareBy)(s => s.range.endLineNumber - s.range.startLineNumber, arrays_1.numberComparator)));
            return symbols.map(s => ({ name: s.name, kind: s.kind, startLineNumber: s.range.startLineNumber }));
        }
    };
    DiffEditorBreadcrumbsSource = __decorate([
        __param(1, languageFeatures_1.ILanguageFeaturesService),
        __param(2, outlineModel_1.IOutlineModelService)
    ], DiffEditorBreadcrumbsSource);
    hideUnchangedRegionsFeature_1.HideUnchangedRegionsFeature.setBreadcrumbsSourceFactory((textModel, instantiationService) => {
        return instantiationService.createInstance(DiffEditorBreadcrumbsSource, textModel);
    });
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[695/*vs/editor/contrib/documentSymbols/browser/documentSymbols*/], __M([1/*require*/,0/*exports*/,18/*vs/base/common/cancellation*/,19/*vs/base/common/types*/,22/*vs/base/common/uri*/,78/*vs/editor/common/services/resolverService*/,182/*vs/editor/contrib/documentSymbols/browser/outlineModel*/,24/*vs/platform/commands/common/commands*/]), function (require, exports, cancellation_1, types_1, uri_1, resolverService_1, outlineModel_1, commands_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    commands_1.CommandsRegistry.registerCommand('_executeDocumentSymbolProvider', async function (accessor, ...args) {
        const [resource] = args;
        (0, types_1.assertType)(uri_1.URI.isUri(resource));
        const outlineService = accessor.get(outlineModel_1.IOutlineModelService);
        const modelService = accessor.get(resolverService_1.ITextModelService);
        const reference = await modelService.createModelReference(resource);
        try {
            return (await outlineService.getOrCreate(reference.object.textEditorModel, cancellation_1.CancellationToken.None)).getTopLevelSymbols();
        }
        finally {
            reference.dispose();
        }
    });
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[696/*vs/platform/clipboard/browser/clipboardService*/], __M([1/*require*/,0/*exports*/,64/*vs/base/browser/browser*/,5/*vs/base/browser/dom*/,52/*vs/base/browser/window*/,14/*vs/base/common/async*/,6/*vs/base/common/event*/,129/*vs/base/common/hash*/,2/*vs/base/common/lifecycle*/,22/*vs/base/common/uri*/,119/*vs/platform/layout/browser/layoutService*/,62/*vs/platform/log/common/log*/]), function (require, exports, browser_1, dom_1, window_1, async_1, event_1, hash_1, lifecycle_1, uri_1, layoutService_1, log_1) {
    "use strict";
    var BrowserClipboardService_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.BrowserClipboardService = void 0;
    /**
     * Custom mime type used for storing a list of uris in the clipboard.
     *
     * Requires support for custom web clipboards https://github.com/w3c/clipboard-apis/pull/175
     */
    const vscodeResourcesMime = 'application/vnd.code.resources';
    let BrowserClipboardService = class BrowserClipboardService extends lifecycle_1.Disposable {
        static { BrowserClipboardService_1 = this; }
        constructor(layoutService, logService) {
            super();
            this.layoutService = layoutService;
            this.logService = logService;
            this.mapTextToType = new Map(); // unsupported in web (only in-memory)
            this.findText = ''; // unsupported in web (only in-memory)
            this.resources = []; // unsupported in web (only in-memory)
            this.resourcesStateHash = undefined;
            if (browser_1.isSafari || browser_1.isWebkitWebView) {
                this.installWebKitWriteTextWorkaround();
            }
            // Keep track of copy operations to reset our set of
            // copied resources: since we keep resources in memory
            // and not in the clipboard, we have to invalidate
            // that state when the user copies other data.
            this._register(event_1.Event.runAndSubscribe(dom_1.onDidRegisterWindow, ({ window, disposables }) => {
                disposables.add((0, dom_1.addDisposableListener)(window.document, 'copy', () => this.clearResourcesState()));
            }, { window: window_1.mainWindow, disposables: this._store }));
        }
        // In Safari, it has the following note:
        //
        // "The request to write to the clipboard must be triggered during a user gesture.
        // A call to clipboard.write or clipboard.writeText outside the scope of a user
        // gesture(such as "click" or "touch" event handlers) will result in the immediate
        // rejection of the promise returned by the API call."
        // From: https://webkit.org/blog/10855/async-clipboard-api/
        //
        // Since extensions run in a web worker, and handle gestures in an asynchronous way,
        // they are not classified by Safari as "in response to a user gesture" and will reject.
        //
        // This function sets up some handlers to work around that behavior.
        installWebKitWriteTextWorkaround() {
            const handler = () => {
                const currentWritePromise = new async_1.DeferredPromise();
                // Cancel the previous promise since we just created a new one in response to this new event
                if (this.webKitPendingClipboardWritePromise && !this.webKitPendingClipboardWritePromise.isSettled) {
                    this.webKitPendingClipboardWritePromise.cancel();
                }
                this.webKitPendingClipboardWritePromise = currentWritePromise;
                // The ctor of ClipboardItem allows you to pass in a promise that will resolve to a string.
                // This allows us to pass in a Promise that will either be cancelled by another event or
                // resolved with the contents of the first call to this.writeText.
                // see https://developer.mozilla.org/en-US/docs/Web/API/ClipboardItem/ClipboardItem#parameters
                (0, dom_1.getActiveWindow)().navigator.clipboard.write([new ClipboardItem({
                        'text/plain': currentWritePromise.p,
                    })]).catch(async (err) => {
                    if (!(err instanceof Error) || err.name !== 'NotAllowedError' || !currentWritePromise.isRejected) {
                        this.logService.error(err);
                    }
                });
            };
            this._register(event_1.Event.runAndSubscribe(this.layoutService.onDidAddContainer, ({ container, disposables }) => {
                disposables.add((0, dom_1.addDisposableListener)(container, 'click', handler));
                disposables.add((0, dom_1.addDisposableListener)(container, 'keydown', handler));
            }, { container: this.layoutService.mainContainer, disposables: this._store }));
        }
        async writeText(text, type) {
            // Clear resources given we are writing text
            this.clearResourcesState();
            // With type: only in-memory is supported
            if (type) {
                this.mapTextToType.set(type, text);
                return;
            }
            if (this.webKitPendingClipboardWritePromise) {
                // For Safari, we complete this Promise which allows the call to `navigator.clipboard.write()`
                // above to resolve and successfully copy to the clipboard. If we let this continue, Safari
                // would throw an error because this call stack doesn't appear to originate from a user gesture.
                return this.webKitPendingClipboardWritePromise.complete(text);
            }
            // Guard access to navigator.clipboard with try/catch
            // as we have seen DOMExceptions in certain browsers
            // due to security policies.
            try {
                return await (0, dom_1.getActiveWindow)().navigator.clipboard.writeText(text);
            }
            catch (error) {
                console.error(error);
            }
            // Fallback to textarea and execCommand solution
            this.fallbackWriteText(text);
        }
        fallbackWriteText(text) {
            const activeDocument = (0, dom_1.getActiveDocument)();
            const activeElement = activeDocument.activeElement;
            const textArea = activeDocument.body.appendChild((0, dom_1.$)('textarea', { 'aria-hidden': true }));
            textArea.style.height = '1px';
            textArea.style.width = '1px';
            textArea.style.position = 'absolute';
            textArea.value = text;
            textArea.focus();
            textArea.select();
            activeDocument.execCommand('copy');
            if ((0, dom_1.isHTMLElement)(activeElement)) {
                activeElement.focus();
            }
            textArea.remove();
        }
        async readText(type) {
            // With type: only in-memory is supported
            if (type) {
                return this.mapTextToType.get(type) || '';
            }
            // Guard access to navigator.clipboard with try/catch
            // as we have seen DOMExceptions in certain browsers
            // due to security policies.
            try {
                return await (0, dom_1.getActiveWindow)().navigator.clipboard.readText();
            }
            catch (error) {
                console.error(error);
            }
            return '';
        }
        async readFindText() {
            return this.findText;
        }
        async writeFindText(text) {
            this.findText = text;
        }
        static { this.MAX_RESOURCE_STATE_SOURCE_LENGTH = 1000; }
        async readResources() {
            // Guard access to navigator.clipboard with try/catch
            // as we have seen DOMExceptions in certain browsers
            // due to security policies.
            try {
                const items = await (0, dom_1.getActiveWindow)().navigator.clipboard.read();
                for (const item of items) {
                    if (item.types.includes(`web ${vscodeResourcesMime}`)) {
                        const blob = await item.getType(`web ${vscodeResourcesMime}`);
                        const resources = JSON.parse(await blob.text()).map(x => uri_1.URI.from(x));
                        return resources;
                    }
                }
            }
            catch (error) {
                // Noop
            }
            const resourcesStateHash = await this.computeResourcesStateHash();
            if (this.resourcesStateHash !== resourcesStateHash) {
                this.clearResourcesState(); // state mismatch, resources no longer valid
            }
            return this.resources;
        }
        async computeResourcesStateHash() {
            if (this.resources.length === 0) {
                return undefined; // no resources, no hash needed
            }
            // Resources clipboard is managed in-memory only and thus
            // fails to invalidate when clipboard data is changing.
            // As such, we compute the hash of the current clipboard
            // and use that to later validate the resources clipboard.
            const clipboardText = await this.readText();
            return (0, hash_1.hash)(clipboardText.substring(0, BrowserClipboardService_1.MAX_RESOURCE_STATE_SOURCE_LENGTH));
        }
        clearInternalState() {
            this.clearResourcesState();
        }
        clearResourcesState() {
            this.resources = [];
            this.resourcesStateHash = undefined;
        }
    };
    exports.BrowserClipboardService = BrowserClipboardService;
    exports.BrowserClipboardService = BrowserClipboardService = BrowserClipboardService_1 = __decorate([
        __param(0, layoutService_1.ILayoutService),
        __param(1, log_1.ILogService)
    ], BrowserClipboardService);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[697/*vs/platform/log/common/logService*/], __M([1/*require*/,0/*exports*/,2/*vs/base/common/lifecycle*/,62/*vs/platform/log/common/log*/]), function (require, exports, lifecycle_1, log_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.LogService = void 0;
    class LogService extends lifecycle_1.Disposable {
        constructor(primaryLogger, otherLoggers = []) {
            super();
            this.logger = new log_1.MultiplexLogger([primaryLogger, ...otherLoggers]);
            this._register(primaryLogger.onDidChangeLogLevel(level => this.setLevel(level)));
        }
        get onDidChangeLogLevel() {
            return this.logger.onDidChangeLogLevel;
        }
        setLevel(level) {
            this.logger.setLevel(level);
        }
        getLevel() {
            return this.logger.getLevel();
        }
        trace(message, ...args) {
            this.logger.trace(message, ...args);
        }
        debug(message, ...args) {
            this.logger.debug(message, ...args);
        }
        info(message, ...args) {
            this.logger.info(message, ...args);
        }
        warn(message, ...args) {
            this.logger.warn(message, ...args);
        }
        error(message, ...args) {
            this.logger.error(message, ...args);
        }
    }
    exports.LogService = LogService;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[108/*vs/platform/markers/common/markers*/], __M([1/*require*/,0/*exports*/,111/*vs/base/common/severity*/,3/*vs/nls*/,7/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, severity_1, nls_1, instantiation_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.IMarkerService = exports.IMarkerData = exports.MarkerSeverity = void 0;
    var MarkerSeverity;
    (function (MarkerSeverity) {
        MarkerSeverity[MarkerSeverity["Hint"] = 1] = "Hint";
        MarkerSeverity[MarkerSeverity["Info"] = 2] = "Info";
        MarkerSeverity[MarkerSeverity["Warning"] = 4] = "Warning";
        MarkerSeverity[MarkerSeverity["Error"] = 8] = "Error";
    })(MarkerSeverity || (exports.MarkerSeverity = MarkerSeverity = {}));
    (function (MarkerSeverity) {
        function compare(a, b) {
            return b - a;
        }
        MarkerSeverity.compare = compare;
        const _displayStrings = Object.create(null);
        _displayStrings[MarkerSeverity.Error] = (0, nls_1.localize)(1569, "Error");
        _displayStrings[MarkerSeverity.Warning] = (0, nls_1.localize)(1570, "Warning");
        _displayStrings[MarkerSeverity.Info] = (0, nls_1.localize)(1571, "Info");
        function toString(a) {
            return _displayStrings[a] || '';
        }
        MarkerSeverity.toString = toString;
        function fromSeverity(severity) {
            switch (severity) {
                case severity_1.default.Error: return MarkerSeverity.Error;
                case severity_1.default.Warning: return MarkerSeverity.Warning;
                case severity_1.default.Info: return MarkerSeverity.Info;
                case severity_1.default.Ignore: return MarkerSeverity.Hint;
            }
        }
        MarkerSeverity.fromSeverity = fromSeverity;
        function toSeverity(severity) {
            switch (severity) {
                case MarkerSeverity.Error: return severity_1.default.Error;
                case MarkerSeverity.Warning: return severity_1.default.Warning;
                case MarkerSeverity.Info: return severity_1.default.Info;
                case MarkerSeverity.Hint: return severity_1.default.Ignore;
            }
        }
        MarkerSeverity.toSeverity = toSeverity;
    })(MarkerSeverity || (exports.MarkerSeverity = MarkerSeverity = {}));
    var IMarkerData;
    (function (IMarkerData) {
        const emptyString = '';
        function makeKey(markerData) {
            return makeKeyOptionalMessage(markerData, true);
        }
        IMarkerData.makeKey = makeKey;
        function makeKeyOptionalMessage(markerData, useMessage) {
            const result = [emptyString];
            if (markerData.source) {
                result.push(markerData.source.replace('¦', '\\¦'));
            }
            else {
                result.push(emptyString);
            }
            if (markerData.code) {
                if (typeof markerData.code === 'string') {
                    result.push(markerData.code.replace('¦', '\\¦'));
                }
                else {
                    result.push(markerData.code.value.replace('¦', '\\¦'));
                }
            }
            else {
                result.push(emptyString);
            }
            if (markerData.severity !== undefined && markerData.severity !== null) {
                result.push(MarkerSeverity.toString(markerData.severity));
            }
            else {
                result.push(emptyString);
            }
            // Modifed to not include the message as part of the marker key to work around
            // https://github.com/microsoft/vscode/issues/77475
            if (markerData.message && useMessage) {
                result.push(markerData.message.replace('¦', '\\¦'));
            }
            else {
                result.push(emptyString);
            }
            if (markerData.startLineNumber !== undefined && markerData.startLineNumber !== null) {
                result.push(markerData.startLineNumber.toString());
            }
            else {
                result.push(emptyString);
            }
            if (markerData.startColumn !== undefined && markerData.startColumn !== null) {
                result.push(markerData.startColumn.toString());
            }
            else {
                result.push(emptyString);
            }
            if (markerData.endLineNumber !== undefined && markerData.endLineNumber !== null) {
                result.push(markerData.endLineNumber.toString());
            }
            else {
                result.push(emptyString);
            }
            if (markerData.endColumn !== undefined && markerData.endColumn !== null) {
                result.push(markerData.endColumn.toString());
            }
            else {
                result.push(emptyString);
            }
            result.push(emptyString);
            return result.join('¦');
        }
        IMarkerData.makeKeyOptionalMessage = makeKeyOptionalMessage;
    })(IMarkerData || (exports.IMarkerData = IMarkerData = {}));
    exports.IMarkerService = (0, instantiation_1.createDecorator)('markerService');
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[698/*vs/editor/contrib/gotoError/browser/markerNavigationService*/], __M([1/*require*/,0/*exports*/,13/*vs/base/common/arrays*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,73/*vs/base/common/linkedList*/,11/*vs/base/common/strings*/,22/*vs/base/common/uri*/,4/*vs/editor/common/core/range*/,49/*vs/platform/instantiation/common/extensions*/,7/*vs/platform/instantiation/common/instantiation*/,108/*vs/platform/markers/common/markers*/,28/*vs/platform/configuration/common/configuration*/]), function (require, exports, arrays_1, event_1, lifecycle_1, linkedList_1, strings_1, uri_1, range_1, extensions_1, instantiation_1, markers_1, configuration_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.IMarkerNavigationService = exports.MarkerList = exports.MarkerCoordinate = void 0;
    class MarkerCoordinate {
        constructor(marker, index, total) {
            this.marker = marker;
            this.index = index;
            this.total = total;
        }
    }
    exports.MarkerCoordinate = MarkerCoordinate;
    let MarkerList = class MarkerList {
        constructor(resourceFilter, _markerService, _configService) {
            this._markerService = _markerService;
            this._configService = _configService;
            this._onDidChange = new event_1.Emitter();
            this.onDidChange = this._onDidChange.event;
            this._dispoables = new lifecycle_1.DisposableStore();
            this._markers = [];
            this._nextIdx = -1;
            if (uri_1.URI.isUri(resourceFilter)) {
                this._resourceFilter = uri => uri.toString() === resourceFilter.toString();
            }
            else if (resourceFilter) {
                this._resourceFilter = resourceFilter;
            }
            const compareOrder = this._configService.getValue('problems.sortOrder');
            const compareMarker = (a, b) => {
                let res = (0, strings_1.compare)(a.resource.toString(), b.resource.toString());
                if (res === 0) {
                    if (compareOrder === 'position') {
                        res = range_1.Range.compareRangesUsingStarts(a, b) || markers_1.MarkerSeverity.compare(a.severity, b.severity);
                    }
                    else {
                        res = markers_1.MarkerSeverity.compare(a.severity, b.severity) || range_1.Range.compareRangesUsingStarts(a, b);
                    }
                }
                return res;
            };
            const updateMarker = () => {
                this._markers = this._markerService.read({
                    resource: uri_1.URI.isUri(resourceFilter) ? resourceFilter : undefined,
                    severities: markers_1.MarkerSeverity.Error | markers_1.MarkerSeverity.Warning | markers_1.MarkerSeverity.Info
                });
                if (typeof resourceFilter === 'function') {
                    this._markers = this._markers.filter(m => this._resourceFilter(m.resource));
                }
                this._markers.sort(compareMarker);
            };
            updateMarker();
            this._dispoables.add(_markerService.onMarkerChanged(uris => {
                if (!this._resourceFilter || uris.some(uri => this._resourceFilter(uri))) {
                    updateMarker();
                    this._nextIdx = -1;
                    this._onDidChange.fire();
                }
            }));
        }
        dispose() {
            this._dispoables.dispose();
            this._onDidChange.dispose();
        }
        matches(uri) {
            if (!this._resourceFilter && !uri) {
                return true;
            }
            if (!this._resourceFilter || !uri) {
                return false;
            }
            return this._resourceFilter(uri);
        }
        get selected() {
            const marker = this._markers[this._nextIdx];
            return marker && new MarkerCoordinate(marker, this._nextIdx + 1, this._markers.length);
        }
        _initIdx(model, position, fwd) {
            let found = false;
            let idx = this._markers.findIndex(marker => marker.resource.toString() === model.uri.toString());
            if (idx < 0) {
                idx = (0, arrays_1.binarySearch)(this._markers, { resource: model.uri }, (a, b) => (0, strings_1.compare)(a.resource.toString(), b.resource.toString()));
                if (idx < 0) {
                    idx = ~idx;
                }
            }
            for (let i = idx; i < this._markers.length; i++) {
                let range = range_1.Range.lift(this._markers[i]);
                if (range.isEmpty()) {
                    const word = model.getWordAtPosition(range.getStartPosition());
                    if (word) {
                        range = new range_1.Range(range.startLineNumber, word.startColumn, range.startLineNumber, word.endColumn);
                    }
                }
                if (position && (range.containsPosition(position) || position.isBeforeOrEqual(range.getStartPosition()))) {
                    this._nextIdx = i;
                    found = true;
                    break;
                }
                if (this._markers[i].resource.toString() !== model.uri.toString()) {
                    break;
                }
            }
            if (!found) {
                // after the last change
                this._nextIdx = fwd ? 0 : this._markers.length - 1;
            }
            if (this._nextIdx < 0) {
                this._nextIdx = this._markers.length - 1;
            }
        }
        resetIndex() {
            this._nextIdx = -1;
        }
        move(fwd, model, position) {
            if (this._markers.length === 0) {
                return false;
            }
            const oldIdx = this._nextIdx;
            if (this._nextIdx === -1) {
                this._initIdx(model, position, fwd);
            }
            else if (fwd) {
                this._nextIdx = (this._nextIdx + 1) % this._markers.length;
            }
            else if (!fwd) {
                this._nextIdx = (this._nextIdx - 1 + this._markers.length) % this._markers.length;
            }
            if (oldIdx !== this._nextIdx) {
                return true;
            }
            return false;
        }
        find(uri, position) {
            let idx = this._markers.findIndex(marker => marker.resource.toString() === uri.toString());
            if (idx < 0) {
                return undefined;
            }
            for (; idx < this._markers.length; idx++) {
                if (range_1.Range.containsPosition(this._markers[idx], position)) {
                    return new MarkerCoordinate(this._markers[idx], idx + 1, this._markers.length);
                }
            }
            return undefined;
        }
    };
    exports.MarkerList = MarkerList;
    exports.MarkerList = MarkerList = __decorate([
        __param(1, markers_1.IMarkerService),
        __param(2, configuration_1.IConfigurationService)
    ], MarkerList);
    exports.IMarkerNavigationService = (0, instantiation_1.createDecorator)('IMarkerNavigationService');
    let MarkerNavigationService = class MarkerNavigationService {
        constructor(_markerService, _configService) {
            this._markerService = _markerService;
            this._configService = _configService;
            this._provider = new linkedList_1.LinkedList();
        }
        getMarkerList(resource) {
            for (const provider of this._provider) {
                const result = provider.getMarkerList(resource);
                if (result) {
                    return result;
                }
            }
            // default
            return new MarkerList(resource, this._markerService, this._configService);
        }
    };
    MarkerNavigationService = __decorate([
        __param(0, markers_1.IMarkerService),
        __param(1, configuration_1.IConfigurationService)
    ], MarkerNavigationService);
    (0, extensions_1.registerSingleton)(exports.IMarkerNavigationService, MarkerNavigationService, 1 /* InstantiationType.Delayed */);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[699/*vs/platform/markers/common/markerService*/], __M([1/*require*/,0/*exports*/,13/*vs/base/common/arrays*/,6/*vs/base/common/event*/,53/*vs/base/common/iterator*/,45/*vs/base/common/map*/,42/*vs/base/common/network*/,22/*vs/base/common/uri*/,108/*vs/platform/markers/common/markers*/]), function (require, exports, arrays_1, event_1, iterator_1, map_1, network_1, uri_1, markers_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MarkerService = exports.unsupportedSchemas = void 0;
    exports.unsupportedSchemas = new Set([
        network_1.Schemas.inMemory,
        network_1.Schemas.vscodeSourceControl,
        network_1.Schemas.walkThrough,
        network_1.Schemas.walkThroughSnippet,
        network_1.Schemas.vscodeChatCodeBlock,
    ]);
    class DoubleResourceMap {
        constructor() {
            this._byResource = new map_1.ResourceMap();
            this._byOwner = new Map();
        }
        set(resource, owner, value) {
            let ownerMap = this._byResource.get(resource);
            if (!ownerMap) {
                ownerMap = new Map();
                this._byResource.set(resource, ownerMap);
            }
            ownerMap.set(owner, value);
            let resourceMap = this._byOwner.get(owner);
            if (!resourceMap) {
                resourceMap = new map_1.ResourceMap();
                this._byOwner.set(owner, resourceMap);
            }
            resourceMap.set(resource, value);
        }
        get(resource, owner) {
            const ownerMap = this._byResource.get(resource);
            return ownerMap?.get(owner);
        }
        delete(resource, owner) {
            let removedA = false;
            let removedB = false;
            const ownerMap = this._byResource.get(resource);
            if (ownerMap) {
                removedA = ownerMap.delete(owner);
            }
            const resourceMap = this._byOwner.get(owner);
            if (resourceMap) {
                removedB = resourceMap.delete(resource);
            }
            if (removedA !== removedB) {
                throw new Error('illegal state');
            }
            return removedA && removedB;
        }
        values(key) {
            if (typeof key === 'string') {
                return this._byOwner.get(key)?.values() ?? iterator_1.Iterable.empty();
            }
            if (uri_1.URI.isUri(key)) {
                return this._byResource.get(key)?.values() ?? iterator_1.Iterable.empty();
            }
            return iterator_1.Iterable.map(iterator_1.Iterable.concat(...this._byOwner.values()), map => map[1]);
        }
    }
    class MarkerStats {
        constructor(service) {
            this.errors = 0;
            this.infos = 0;
            this.warnings = 0;
            this.unknowns = 0;
            this._data = new map_1.ResourceMap();
            this._service = service;
            this._subscription = service.onMarkerChanged(this._update, this);
        }
        dispose() {
            this._subscription.dispose();
        }
        _update(resources) {
            for (const resource of resources) {
                const oldStats = this._data.get(resource);
                if (oldStats) {
                    this._substract(oldStats);
                }
                const newStats = this._resourceStats(resource);
                this._add(newStats);
                this._data.set(resource, newStats);
            }
        }
        _resourceStats(resource) {
            const result = { errors: 0, warnings: 0, infos: 0, unknowns: 0 };
            // TODO this is a hack
            if (exports.unsupportedSchemas.has(resource.scheme)) {
                return result;
            }
            for (const { severity } of this._service.read({ resource })) {
                if (severity === markers_1.MarkerSeverity.Error) {
                    result.errors += 1;
                }
                else if (severity === markers_1.MarkerSeverity.Warning) {
                    result.warnings += 1;
                }
                else if (severity === markers_1.MarkerSeverity.Info) {
                    result.infos += 1;
                }
                else {
                    result.unknowns += 1;
                }
            }
            return result;
        }
        _substract(op) {
            this.errors -= op.errors;
            this.warnings -= op.warnings;
            this.infos -= op.infos;
            this.unknowns -= op.unknowns;
        }
        _add(op) {
            this.errors += op.errors;
            this.warnings += op.warnings;
            this.infos += op.infos;
            this.unknowns += op.unknowns;
        }
    }
    class MarkerService {
        constructor() {
            this._onMarkerChanged = new event_1.DebounceEmitter({
                delay: 0,
                merge: MarkerService._merge
            });
            this.onMarkerChanged = this._onMarkerChanged.event;
            this._data = new DoubleResourceMap();
            this._stats = new MarkerStats(this);
        }
        dispose() {
            this._stats.dispose();
            this._onMarkerChanged.dispose();
        }
        remove(owner, resources) {
            for (const resource of resources || []) {
                this.changeOne(owner, resource, []);
            }
        }
        changeOne(owner, resource, markerData) {
            if ((0, arrays_1.isFalsyOrEmpty)(markerData)) {
                // remove marker for this (owner,resource)-tuple
                const removed = this._data.delete(resource, owner);
                if (removed) {
                    this._onMarkerChanged.fire([resource]);
                }
            }
            else {
                // insert marker for this (owner,resource)-tuple
                const markers = [];
                for (const data of markerData) {
                    const marker = MarkerService._toMarker(owner, resource, data);
                    if (marker) {
                        markers.push(marker);
                    }
                }
                this._data.set(resource, owner, markers);
                this._onMarkerChanged.fire([resource]);
            }
        }
        static _toMarker(owner, resource, data) {
            let { code, severity, message, source, startLineNumber, startColumn, endLineNumber, endColumn, relatedInformation, tags, } = data;
            if (!message) {
                return undefined;
            }
            // santize data
            startLineNumber = startLineNumber > 0 ? startLineNumber : 1;
            startColumn = startColumn > 0 ? startColumn : 1;
            endLineNumber = endLineNumber >= startLineNumber ? endLineNumber : startLineNumber;
            endColumn = endColumn > 0 ? endColumn : startColumn;
            return {
                resource,
                owner,
                code,
                severity,
                message,
                source,
                startLineNumber,
                startColumn,
                endLineNumber,
                endColumn,
                relatedInformation,
                tags,
            };
        }
        changeAll(owner, data) {
            const changes = [];
            // remove old marker
            const existing = this._data.values(owner);
            if (existing) {
                for (const data of existing) {
                    const first = iterator_1.Iterable.first(data);
                    if (first) {
                        changes.push(first.resource);
                        this._data.delete(first.resource, owner);
                    }
                }
            }
            // add new markers
            if ((0, arrays_1.isNonEmptyArray)(data)) {
                // group by resource
                const groups = new map_1.ResourceMap();
                for (const { resource, marker: markerData } of data) {
                    const marker = MarkerService._toMarker(owner, resource, markerData);
                    if (!marker) {
                        // filter bad markers
                        continue;
                    }
                    const array = groups.get(resource);
                    if (!array) {
                        groups.set(resource, [marker]);
                        changes.push(resource);
                    }
                    else {
                        array.push(marker);
                    }
                }
                // insert all
                for (const [resource, value] of groups) {
                    this._data.set(resource, owner, value);
                }
            }
            if (changes.length > 0) {
                this._onMarkerChanged.fire(changes);
            }
        }
        read(filter = Object.create(null)) {
            let { owner, resource, severities, take } = filter;
            if (!take || take < 0) {
                take = -1;
            }
            if (owner && resource) {
                // exactly one owner AND resource
                const data = this._data.get(resource, owner);
                if (!data) {
                    return [];
                }
                else {
                    const result = [];
                    for (const marker of data) {
                        if (MarkerService._accept(marker, severities)) {
                            const newLen = result.push(marker);
                            if (take > 0 && newLen === take) {
                                break;
                            }
                        }
                    }
                    return result;
                }
            }
            else if (!owner && !resource) {
                // all
                const result = [];
                for (const markers of this._data.values()) {
                    for (const data of markers) {
                        if (MarkerService._accept(data, severities)) {
                            const newLen = result.push(data);
                            if (take > 0 && newLen === take) {
                                return result;
                            }
                        }
                    }
                }
                return result;
            }
            else {
                // of one resource OR owner
                const iterable = this._data.values(resource ?? owner);
                const result = [];
                for (const markers of iterable) {
                    for (const data of markers) {
                        if (MarkerService._accept(data, severities)) {
                            const newLen = result.push(data);
                            if (take > 0 && newLen === take) {
                                return result;
                            }
                        }
                    }
                }
                return result;
            }
        }
        static _accept(marker, severities) {
            return severities === undefined || (severities & marker.severity) === marker.severity;
        }
        // --- event debounce logic
        static _merge(all) {
            const set = new map_1.ResourceMap();
            for (const array of all) {
                for (const item of array) {
                    set.set(item, true);
                }
            }
            return Array.from(set.keys());
        }
    }
    exports.MarkerService = MarkerService;
});

define(__m[50/*vs/platform/notification/common/notification*/], __M([1/*require*/,0/*exports*/,111/*vs/base/common/severity*/,7/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, severity_1, instantiation_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.NoOpNotification = exports.INotificationService = exports.Severity = void 0;
    exports.Severity = severity_1.default;
    exports.INotificationService = (0, instantiation_1.createDecorator)('notificationService');
    class NoOpNotification {
    }
    exports.NoOpNotification = NoOpNotification;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[396/*vs/editor/contrib/dropOrPasteInto/browser/postEditWidget*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,258/*vs/base/browser/ui/button/button*/,41/*vs/base/common/actions*/,346/*vs/base/common/errorMessage*/,8/*vs/base/common/errors*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,152/*vs/editor/browser/services/bulkEditService*/,268/*vs/editor/contrib/dropOrPasteInto/browser/edit*/,3/*vs/nls*/,12/*vs/platform/contextkey/common/contextkey*/,58/*vs/platform/contextview/browser/contextView*/,7/*vs/platform/instantiation/common/instantiation*/,31/*vs/platform/keybinding/common/keybinding*/,50/*vs/platform/notification/common/notification*/,508/*vs/css!vs/editor/contrib/dropOrPasteInto/browser/postEditWidget*/]), function (require, exports, dom, button_1, actions_1, errorMessage_1, errors_1, event_1, lifecycle_1, bulkEditService_1, edit_1, nls_1, contextkey_1, contextView_1, instantiation_1, keybinding_1, notification_1) {
    "use strict";
    var PostEditWidget_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.PostEditWidgetManager = void 0;
    let PostEditWidget = class PostEditWidget extends lifecycle_1.Disposable {
        static { PostEditWidget_1 = this; }
        static { this.baseId = 'editor.widget.postEditWidget'; }
        constructor(typeId, editor, visibleContext, showCommand, range, edits, onSelectNewEdit, _contextMenuService, contextKeyService, _keybindingService) {
            super();
            this.typeId = typeId;
            this.editor = editor;
            this.showCommand = showCommand;
            this.range = range;
            this.edits = edits;
            this.onSelectNewEdit = onSelectNewEdit;
            this._contextMenuService = _contextMenuService;
            this._keybindingService = _keybindingService;
            this.allowEditorOverflow = true;
            this.suppressMouseDown = true;
            this.create();
            this.visibleContext = visibleContext.bindTo(contextKeyService);
            this.visibleContext.set(true);
            this._register((0, lifecycle_1.toDisposable)(() => this.visibleContext.reset()));
            this.editor.addContentWidget(this);
            this.editor.layoutContentWidget(this);
            this._register((0, lifecycle_1.toDisposable)((() => this.editor.removeContentWidget(this))));
            this._register(this.editor.onDidChangeCursorPosition(e => {
                if (!range.containsPosition(e.position)) {
                    this.dispose();
                }
            }));
            this._register(event_1.Event.runAndSubscribe(_keybindingService.onDidUpdateKeybindings, () => {
                this._updateButtonTitle();
            }));
        }
        _updateButtonTitle() {
            const binding = this._keybindingService.lookupKeybinding(this.showCommand.id)?.getLabel();
            this.button.element.title = this.showCommand.label + (binding ? ` (${binding})` : '');
        }
        create() {
            this.domNode = dom.$('.post-edit-widget');
            this.button = this._register(new button_1.Button(this.domNode, {
                supportIcons: true,
            }));
            this.button.label = '$(insert)';
            this._register(dom.addDisposableListener(this.domNode, dom.EventType.CLICK, () => this.showSelector()));
        }
        getId() {
            return PostEditWidget_1.baseId + '.' + this.typeId;
        }
        getDomNode() {
            return this.domNode;
        }
        getPosition() {
            return {
                position: this.range.getEndPosition(),
                preference: [2 /* ContentWidgetPositionPreference.BELOW */]
            };
        }
        showSelector() {
            this._contextMenuService.showContextMenu({
                getAnchor: () => {
                    const pos = dom.getDomNodePagePosition(this.button.element);
                    return { x: pos.left + pos.width, y: pos.top + pos.height };
                },
                getActions: () => {
                    return this.edits.allEdits.map((edit, i) => (0, actions_1.toAction)({
                        id: '',
                        label: edit.title,
                        checked: i === this.edits.activeEditIndex,
                        run: () => {
                            if (i !== this.edits.activeEditIndex) {
                                return this.onSelectNewEdit(i);
                            }
                        },
                    }));
                }
            });
        }
    };
    PostEditWidget = PostEditWidget_1 = __decorate([
        __param(7, contextView_1.IContextMenuService),
        __param(8, contextkey_1.IContextKeyService),
        __param(9, keybinding_1.IKeybindingService)
    ], PostEditWidget);
    let PostEditWidgetManager = class PostEditWidgetManager extends lifecycle_1.Disposable {
        constructor(_id, _editor, _visibleContext, _showCommand, _instantiationService, _bulkEditService, _notificationService) {
            super();
            this._id = _id;
            this._editor = _editor;
            this._visibleContext = _visibleContext;
            this._showCommand = _showCommand;
            this._instantiationService = _instantiationService;
            this._bulkEditService = _bulkEditService;
            this._notificationService = _notificationService;
            this._currentWidget = this._register(new lifecycle_1.MutableDisposable());
            this._register(event_1.Event.any(_editor.onDidChangeModel, _editor.onDidChangeModelContent)(() => this.clear()));
        }
        async applyEditAndShowIfNeeded(ranges, edits, canShowWidget, resolve, token) {
            const model = this._editor.getModel();
            if (!model || !ranges.length) {
                return;
            }
            const edit = edits.allEdits.at(edits.activeEditIndex);
            if (!edit) {
                return;
            }
            const onDidSelectEdit = async (newEditIndex) => {
                const model = this._editor.getModel();
                if (!model) {
                    return;
                }
                await model.undo();
                this.applyEditAndShowIfNeeded(ranges, { activeEditIndex: newEditIndex, allEdits: edits.allEdits }, canShowWidget, resolve, token);
            };
            const handleError = (e, message) => {
                if ((0, errors_1.isCancellationError)(e)) {
                    return;
                }
                this._notificationService.error(message);
                if (canShowWidget) {
                    this.show(ranges[0], edits, onDidSelectEdit);
                }
            };
            let resolvedEdit;
            try {
                resolvedEdit = await resolve(edit, token);
            }
            catch (e) {
                return handleError(e, (0, nls_1.localize)(845, "Error resolving edit '{0}':\n{1}", edit.title, (0, errorMessage_1.toErrorMessage)(e)));
            }
            if (token.isCancellationRequested) {
                return;
            }
            const combinedWorkspaceEdit = (0, edit_1.createCombinedWorkspaceEdit)(model.uri, ranges, resolvedEdit);
            // Use a decoration to track edits around the trigger range
            const primaryRange = ranges[0];
            const editTrackingDecoration = model.deltaDecorations([], [{
                    range: primaryRange,
                    options: { description: 'paste-line-suffix', stickiness: 0 /* TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges */ }
                }]);
            this._editor.focus();
            let editResult;
            let editRange;
            try {
                editResult = await this._bulkEditService.apply(combinedWorkspaceEdit, { editor: this._editor, token });
                editRange = model.getDecorationRange(editTrackingDecoration[0]);
            }
            catch (e) {
                return handleError(e, (0, nls_1.localize)(846, "Error applying edit '{0}':\n{1}", edit.title, (0, errorMessage_1.toErrorMessage)(e)));
            }
            finally {
                model.deltaDecorations(editTrackingDecoration, []);
            }
            if (token.isCancellationRequested) {
                return;
            }
            if (canShowWidget && editResult.isApplied && edits.allEdits.length > 1) {
                this.show(editRange ?? primaryRange, edits, onDidSelectEdit);
            }
        }
        show(range, edits, onDidSelectEdit) {
            this.clear();
            if (this._editor.hasModel()) {
                this._currentWidget.value = this._instantiationService.createInstance((PostEditWidget), this._id, this._editor, this._visibleContext, this._showCommand, range, edits, onDidSelectEdit);
            }
        }
        clear() {
            this._currentWidget.clear();
        }
        tryShowSelector() {
            this._currentWidget.value?.showSelector();
        }
    };
    exports.PostEditWidgetManager = PostEditWidgetManager;
    exports.PostEditWidgetManager = PostEditWidgetManager = __decorate([
        __param(4, instantiation_1.IInstantiationService),
        __param(5, bulkEditService_1.IBulkEditService),
        __param(6, notification_1.INotificationService)
    ], PostEditWidgetManager);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[397/*vs/platform/observable/common/platformObservableUtils*/], __M([1/*require*/,0/*exports*/,21/*vs/base/common/observable*/,189/*vs/base/common/observableInternal/utils*/]), function (require, exports, observable_1, utils_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.observableConfigValue = observableConfigValue;
    exports.bindContextKey = bindContextKey;
    /** Creates an observable update when a configuration key updates. */
    function observableConfigValue(key, defaultValue, configurationService) {
        return (0, utils_1.observableFromEventOpts)({ debugName: () => `Configuration Key "${key}"`, }, (handleChange) => configurationService.onDidChangeConfiguration(e => {
            if (e.affectsConfiguration(key)) {
                handleChange(e);
            }
        }), () => configurationService.getValue(key) ?? defaultValue);
    }
    /** Update the configuration key with a value derived from observables. */
    function bindContextKey(key, service, computeValue) {
        const boundKey = key.bindTo(service);
        return (0, observable_1.autorunOpts)({ debugName: () => `Set Context Key "${key.key}"` }, reader => {
            boundKey.set(computeValue(reader));
        });
    }
});










define(__m[700/*vs/platform/observable/common/wrapInReloadableClass*/], __M([1/*require*/,0/*exports*/,349/*vs/base/common/hotReload*/,171/*vs/base/common/hotReloadHelpers*/,21/*vs/base/common/observable*/,7/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, hotReload_1, hotReloadHelpers_1, observable_1, instantiation_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.wrapInReloadableClass1 = wrapInReloadableClass1;
    class BaseClass {
        constructor(instantiationService) {
            this.instantiationService = instantiationService;
        }
        init(...params) { }
    }
    function createWrapper(getClass, B) {
        return (class ReloadableWrapper extends B {
            constructor() {
                super(...arguments);
                this._autorun = undefined;
            }
            init(...params) {
                this._autorun = (0, observable_1.autorunWithStore)((reader, store) => {
                    const clazz = (0, hotReloadHelpers_1.readHotReloadableExport)(getClass(), reader);
                    store.add(this.instantiationService.createInstance(clazz, ...params));
                });
            }
            dispose() {
                this._autorun?.dispose();
            }
        });
    }
    /**
     * Wrap a class in a reloadable wrapper.
     * When the wrapper is created, the original class is created.
     * When the original class changes, the instance is re-created.
    */
    function wrapInReloadableClass1(getClass) {
        return !(0, hotReload_1.isHotReloadEnabled)() ? getClass() : createWrapper(getClass, BaseClass1);
    }
    let BaseClass1 = class BaseClass1 extends BaseClass {
        constructor(param1, i) { super(i); this.init(param1); }
    };
    BaseClass1 = __decorate([
        __param(1, instantiation_1.IInstantiationService)
    ], BaseClass1);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[59/*vs/platform/opener/common/opener*/], __M([1/*require*/,0/*exports*/,7/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.IOpenerService = void 0;
    exports.extractSelection = extractSelection;
    exports.IOpenerService = (0, instantiation_1.createDecorator)('openerService');
    /**
     * file:///some/file.js#73
     * file:///some/file.js#L73
     * file:///some/file.js#73,84
     * file:///some/file.js#L73,84
     * file:///some/file.js#73-83
     * file:///some/file.js#L73-L83
     * file:///some/file.js#73,84-83,52
     * file:///some/file.js#L73,84-L83,52
     */
    function extractSelection(uri) {
        let selection = undefined;
        const match = /^L?(\d+)(?:,(\d+))?(-L?(\d+)(?:,(\d+))?)?/.exec(uri.fragment);
        if (match) {
            selection = {
                startLineNumber: parseInt(match[1]),
                startColumn: match[2] ? parseInt(match[2]) : 1,
                endLineNumber: match[4] ? parseInt(match[4]) : undefined,
                endColumn: match[4] ? (match[5] ? parseInt(match[5]) : 1) : undefined
            };
            uri = uri.with({ fragment: '' });
        }
        return { selection, uri };
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[701/*vs/editor/browser/services/openerService*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,52/*vs/base/browser/window*/,18/*vs/base/common/cancellation*/,73/*vs/base/common/linkedList*/,45/*vs/base/common/map*/,252/*vs/base/common/marshalling*/,42/*vs/base/common/network*/,48/*vs/base/common/resources*/,22/*vs/base/common/uri*/,34/*vs/editor/browser/services/codeEditorService*/,24/*vs/platform/commands/common/commands*/,673/*vs/platform/editor/common/editor*/,59/*vs/platform/opener/common/opener*/]), function (require, exports, dom, window_1, cancellation_1, linkedList_1, map_1, marshalling_1, network_1, resources_1, uri_1, codeEditorService_1, commands_1, editor_1, opener_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.OpenerService = void 0;
    let CommandOpener = class CommandOpener {
        constructor(_commandService) {
            this._commandService = _commandService;
        }
        async open(target, options) {
            if (!(0, network_1.matchesScheme)(target, network_1.Schemas.command)) {
                return false;
            }
            if (!options?.allowCommands) {
                // silently ignore commands when command-links are disabled, also
                // suppress other openers by returning TRUE
                return true;
            }
            if (typeof target === 'string') {
                target = uri_1.URI.parse(target);
            }
            if (Array.isArray(options.allowCommands)) {
                // Only allow specific commands
                if (!options.allowCommands.includes(target.path)) {
                    // Suppress other openers by returning TRUE
                    return true;
                }
            }
            // execute as command
            let args = [];
            try {
                args = (0, marshalling_1.parse)(decodeURIComponent(target.query));
            }
            catch {
                // ignore and retry
                try {
                    args = (0, marshalling_1.parse)(target.query);
                }
                catch {
                    // ignore error
                }
            }
            if (!Array.isArray(args)) {
                args = [args];
            }
            await this._commandService.executeCommand(target.path, ...args);
            return true;
        }
    };
    CommandOpener = __decorate([
        __param(0, commands_1.ICommandService)
    ], CommandOpener);
    let EditorOpener = class EditorOpener {
        constructor(_editorService) {
            this._editorService = _editorService;
        }
        async open(target, options) {
            if (typeof target === 'string') {
                target = uri_1.URI.parse(target);
            }
            const { selection, uri } = (0, opener_1.extractSelection)(target);
            target = uri;
            if (target.scheme === network_1.Schemas.file) {
                target = (0, resources_1.normalizePath)(target); // workaround for non-normalized paths (https://github.com/microsoft/vscode/issues/12954)
            }
            await this._editorService.openCodeEditor({
                resource: target,
                options: {
                    selection,
                    source: options?.fromUserGesture ? editor_1.EditorOpenSource.USER : editor_1.EditorOpenSource.API,
                    ...options?.editorOptions
                }
            }, this._editorService.getFocusedCodeEditor(), options?.openToSide);
            return true;
        }
    };
    EditorOpener = __decorate([
        __param(0, codeEditorService_1.ICodeEditorService)
    ], EditorOpener);
    let OpenerService = class OpenerService {
        constructor(editorService, commandService) {
            this._openers = new linkedList_1.LinkedList();
            this._validators = new linkedList_1.LinkedList();
            this._resolvers = new linkedList_1.LinkedList();
            this._resolvedUriTargets = new map_1.ResourceMap(uri => uri.with({ path: null, fragment: null, query: null }).toString());
            this._externalOpeners = new linkedList_1.LinkedList();
            // Default external opener is going through window.open()
            this._defaultExternalOpener = {
                openExternal: async (href) => {
                    // ensure to open HTTP/HTTPS links into new windows
                    // to not trigger a navigation. Any other link is
                    // safe to be set as HREF to prevent a blank window
                    // from opening.
                    if ((0, network_1.matchesSomeScheme)(href, network_1.Schemas.http, network_1.Schemas.https)) {
                        dom.windowOpenNoOpener(href);
                    }
                    else {
                        window_1.mainWindow.location.href = href;
                    }
                    return true;
                }
            };
            // Default opener: any external, maito, http(s), command, and catch-all-editors
            this._openers.push({
                open: async (target, options) => {
                    if (options?.openExternal || (0, network_1.matchesSomeScheme)(target, network_1.Schemas.mailto, network_1.Schemas.http, network_1.Schemas.https, network_1.Schemas.vsls)) {
                        // open externally
                        await this._doOpenExternal(target, options);
                        return true;
                    }
                    return false;
                }
            });
            this._openers.push(new CommandOpener(commandService));
            this._openers.push(new EditorOpener(editorService));
        }
        registerOpener(opener) {
            const remove = this._openers.unshift(opener);
            return { dispose: remove };
        }
        async open(target, options) {
            // check with contributed validators
            const targetURI = typeof target === 'string' ? uri_1.URI.parse(target) : target;
            // validate against the original URI that this URI resolves to, if one exists
            const validationTarget = this._resolvedUriTargets.get(targetURI) ?? target;
            for (const validator of this._validators) {
                if (!(await validator.shouldOpen(validationTarget, options))) {
                    return false;
                }
            }
            // check with contributed openers
            for (const opener of this._openers) {
                const handled = await opener.open(target, options);
                if (handled) {
                    return true;
                }
            }
            return false;
        }
        async resolveExternalUri(resource, options) {
            for (const resolver of this._resolvers) {
                try {
                    const result = await resolver.resolveExternalUri(resource, options);
                    if (result) {
                        if (!this._resolvedUriTargets.has(result.resolved)) {
                            this._resolvedUriTargets.set(result.resolved, resource);
                        }
                        return result;
                    }
                }
                catch {
                    // noop
                }
            }
            throw new Error('Could not resolve external URI: ' + resource.toString());
        }
        async _doOpenExternal(resource, options) {
            //todo@jrieken IExternalUriResolver should support `uri: URI | string`
            const uri = typeof resource === 'string' ? uri_1.URI.parse(resource) : resource;
            let externalUri;
            try {
                externalUri = (await this.resolveExternalUri(uri, options)).resolved;
            }
            catch {
                externalUri = uri;
            }
            let href;
            if (typeof resource === 'string' && uri.toString() === externalUri.toString()) {
                // open the url-string AS IS
                href = resource;
            }
            else {
                // open URI using the toString(noEncode)+encodeURI-trick
                href = encodeURI(externalUri.toString(true));
            }
            if (options?.allowContributedOpeners) {
                const preferredOpenerId = typeof options?.allowContributedOpeners === 'string' ? options?.allowContributedOpeners : undefined;
                for (const opener of this._externalOpeners) {
                    const didOpen = await opener.openExternal(href, {
                        sourceUri: uri,
                        preferredOpenerId,
                    }, cancellation_1.CancellationToken.None);
                    if (didOpen) {
                        return true;
                    }
                }
            }
            return this._defaultExternalOpener.openExternal(href, { sourceUri: uri }, cancellation_1.CancellationToken.None);
        }
        dispose() {
            this._validators.clear();
        }
    };
    exports.OpenerService = OpenerService;
    exports.OpenerService = OpenerService = __decorate([
        __param(0, codeEditorService_1.ICodeEditorService),
        __param(1, commands_1.ICommandService)
    ], OpenerService);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[702/*vs/platform/opener/browser/link*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,93/*vs/base/browser/event*/,47/*vs/base/browser/keyboardEvent*/,69/*vs/base/browser/touch*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,59/*vs/platform/opener/common/opener*/,44/*vs/base/browser/ui/hover/hoverDelegateFactory*/,118/*vs/platform/hover/browser/hover*/,543/*vs/css!vs/platform/opener/browser/link*/]), function (require, exports, dom_1, event_1, keyboardEvent_1, touch_1, event_2, lifecycle_1, opener_1, hoverDelegateFactory_1, hover_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Link = void 0;
    let Link = class Link extends lifecycle_1.Disposable {
        get enabled() {
            return this._enabled;
        }
        set enabled(enabled) {
            if (enabled) {
                this.el.setAttribute('aria-disabled', 'false');
                this.el.tabIndex = 0;
                this.el.style.pointerEvents = 'auto';
                this.el.style.opacity = '1';
                this.el.style.cursor = 'pointer';
                this._enabled = false;
            }
            else {
                this.el.setAttribute('aria-disabled', 'true');
                this.el.tabIndex = -1;
                this.el.style.pointerEvents = 'none';
                this.el.style.opacity = '0.4';
                this.el.style.cursor = 'default';
                this._enabled = true;
            }
            this._enabled = enabled;
        }
        constructor(container, _link, options = {}, _hoverService, openerService) {
            super();
            this._link = _link;
            this._hoverService = _hoverService;
            this._enabled = true;
            this.el = (0, dom_1.append)(container, (0, dom_1.$)('a.monaco-link', {
                tabIndex: _link.tabIndex ?? 0,
                href: _link.href,
            }, _link.label));
            this.hoverDelegate = options.hoverDelegate ?? (0, hoverDelegateFactory_1.getDefaultHoverDelegate)('mouse');
            this.setTooltip(_link.title);
            this.el.setAttribute('role', 'button');
            const onClickEmitter = this._register(new event_1.DomEmitter(this.el, 'click'));
            const onKeyPress = this._register(new event_1.DomEmitter(this.el, 'keypress'));
            const onEnterPress = event_2.Event.chain(onKeyPress.event, $ => $.map(e => new keyboardEvent_1.StandardKeyboardEvent(e))
                .filter(e => e.keyCode === 3 /* KeyCode.Enter */));
            const onTap = this._register(new event_1.DomEmitter(this.el, touch_1.EventType.Tap)).event;
            this._register(touch_1.Gesture.addTarget(this.el));
            const onOpen = event_2.Event.any(onClickEmitter.event, onEnterPress, onTap);
            this._register(onOpen(e => {
                if (!this.enabled) {
                    return;
                }
                dom_1.EventHelper.stop(e, true);
                if (options?.opener) {
                    options.opener(this._link.href);
                }
                else {
                    openerService.open(this._link.href, { allowCommands: true });
                }
            }));
            this.enabled = true;
        }
        setTooltip(title) {
            if (this.hoverDelegate.showNativeHover) {
                this.el.title = title ?? '';
            }
            else if (!this.hover && title) {
                this.hover = this._register(this._hoverService.setupManagedHover(this.hoverDelegate, this.el, title));
            }
            else if (this.hover) {
                this.hover.update(title);
            }
        }
    };
    exports.Link = Link;
    exports.Link = Link = __decorate([
        __param(3, hover_1.IHoverService),
        __param(4, opener_1.IOpenerService)
    ], Link);
});

define(__m[96/*vs/platform/progress/common/progress*/], __M([1/*require*/,0/*exports*/,7/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.IEditorProgressService = exports.Progress = exports.emptyProgressRunner = exports.IProgressService = void 0;
    exports.IProgressService = (0, instantiation_1.createDecorator)('progressService');
    exports.emptyProgressRunner = Object.freeze({
        total() { },
        worked() { },
        done() { }
    });
    class Progress {
        static { this.None = Object.freeze({ report() { } }); }
        constructor(callback) {
            this.callback = callback;
        }
        report(item) {
            this._value = item;
            this.callback(this._value);
        }
    }
    exports.Progress = Progress;
    exports.IEditorProgressService = (0, instantiation_1.createDecorator)('editorProgressService');
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[703/*vs/platform/quickinput/browser/pickerQuickAccess*/], __M([1/*require*/,0/*exports*/,14/*vs/base/common/async*/,18/*vs/base/common/cancellation*/,2/*vs/base/common/lifecycle*/,19/*vs/base/common/types*/]), function (require, exports, async_1, cancellation_1, lifecycle_1, types_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.PickerQuickAccessProvider = exports.TriggerAction = void 0;
    var TriggerAction;
    (function (TriggerAction) {
        /**
         * Do nothing after the button was clicked.
         */
        TriggerAction[TriggerAction["NO_ACTION"] = 0] = "NO_ACTION";
        /**
         * Close the picker.
         */
        TriggerAction[TriggerAction["CLOSE_PICKER"] = 1] = "CLOSE_PICKER";
        /**
         * Update the results of the picker.
         */
        TriggerAction[TriggerAction["REFRESH_PICKER"] = 2] = "REFRESH_PICKER";
        /**
         * Remove the item from the picker.
         */
        TriggerAction[TriggerAction["REMOVE_ITEM"] = 3] = "REMOVE_ITEM";
    })(TriggerAction || (exports.TriggerAction = TriggerAction = {}));
    function isPicksWithActive(obj) {
        const candidate = obj;
        return Array.isArray(candidate.items);
    }
    function isFastAndSlowPicks(obj) {
        const candidate = obj;
        return !!candidate.picks && candidate.additionalPicks instanceof Promise;
    }
    class PickerQuickAccessProvider extends lifecycle_1.Disposable {
        constructor(prefix, options) {
            super();
            this.prefix = prefix;
            this.options = options;
        }
        provide(picker, token, runOptions) {
            const disposables = new lifecycle_1.DisposableStore();
            // Apply options if any
            picker.canAcceptInBackground = !!this.options?.canAcceptInBackground;
            // Disable filtering & sorting, we control the results
            picker.matchOnLabel = picker.matchOnDescription = picker.matchOnDetail = picker.sortByLabel = false;
            // Set initial picks and update on type
            let picksCts = undefined;
            const picksDisposable = disposables.add(new lifecycle_1.MutableDisposable());
            const updatePickerItems = async () => {
                const picksDisposables = picksDisposable.value = new lifecycle_1.DisposableStore();
                // Cancel any previous ask for picks and busy
                picksCts?.dispose(true);
                picker.busy = false;
                // Create new cancellation source for this run
                picksCts = new cancellation_1.CancellationTokenSource(token);
                // Collect picks and support both long running and short or combined
                const picksToken = picksCts.token;
                let picksFilter = picker.value.substring(this.prefix.length);
                if (!this.options?.shouldSkipTrimPickFilter) {
                    picksFilter = picksFilter.trim();
                }
                const providedPicks = this._getPicks(picksFilter, picksDisposables, picksToken, runOptions);
                const applyPicks = (picks, skipEmpty) => {
                    let items;
                    let activeItem = undefined;
                    if (isPicksWithActive(picks)) {
                        items = picks.items;
                        activeItem = picks.active;
                    }
                    else {
                        items = picks;
                    }
                    if (items.length === 0) {
                        if (skipEmpty) {
                            return false;
                        }
                        // We show the no results pick if we have no input to prevent completely empty pickers #172613
                        if ((picksFilter.length > 0 || picker.hideInput) && this.options?.noResultsPick) {
                            if ((0, types_1.isFunction)(this.options.noResultsPick)) {
                                items = [this.options.noResultsPick(picksFilter)];
                            }
                            else {
                                items = [this.options.noResultsPick];
                            }
                        }
                    }
                    picker.items = items;
                    if (activeItem) {
                        picker.activeItems = [activeItem];
                    }
                    return true;
                };
                const applyFastAndSlowPicks = async (fastAndSlowPicks) => {
                    let fastPicksApplied = false;
                    let slowPicksApplied = false;
                    await Promise.all([
                        // Fast Picks: if `mergeDelay` is configured, in order to reduce
                        // amount of flicker, we race against the slow picks over some delay
                        // and then set the fast picks.
                        // If the slow picks are faster, we reduce the flicker by only
                        // setting the items once.
                        (async () => {
                            if (typeof fastAndSlowPicks.mergeDelay === 'number') {
                                await (0, async_1.timeout)(fastAndSlowPicks.mergeDelay);
                                if (picksToken.isCancellationRequested) {
                                    return;
                                }
                            }
                            if (!slowPicksApplied) {
                                fastPicksApplied = applyPicks(fastAndSlowPicks.picks, true /* skip over empty to reduce flicker */);
                            }
                        })(),
                        // Slow Picks: we await the slow picks and then set them at
                        // once together with the fast picks, but only if we actually
                        // have additional results.
                        (async () => {
                            picker.busy = true;
                            try {
                                const awaitedAdditionalPicks = await fastAndSlowPicks.additionalPicks;
                                if (picksToken.isCancellationRequested) {
                                    return;
                                }
                                let picks;
                                let activePick = undefined;
                                if (isPicksWithActive(fastAndSlowPicks.picks)) {
                                    picks = fastAndSlowPicks.picks.items;
                                    activePick = fastAndSlowPicks.picks.active;
                                }
                                else {
                                    picks = fastAndSlowPicks.picks;
                                }
                                let additionalPicks;
                                let additionalActivePick = undefined;
                                if (isPicksWithActive(awaitedAdditionalPicks)) {
                                    additionalPicks = awaitedAdditionalPicks.items;
                                    additionalActivePick = awaitedAdditionalPicks.active;
                                }
                                else {
                                    additionalPicks = awaitedAdditionalPicks;
                                }
                                if (additionalPicks.length > 0 || !fastPicksApplied) {
                                    // If we do not have any activePick or additionalActivePick
                                    // we try to preserve the currently active pick from the
                                    // fast results. This fixes an issue where the user might
                                    // have made a pick active before the additional results
                                    // kick in.
                                    // See https://github.com/microsoft/vscode/issues/102480
                                    let fallbackActivePick = undefined;
                                    if (!activePick && !additionalActivePick) {
                                        const fallbackActivePickCandidate = picker.activeItems[0];
                                        if (fallbackActivePickCandidate && picks.indexOf(fallbackActivePickCandidate) !== -1) {
                                            fallbackActivePick = fallbackActivePickCandidate;
                                        }
                                    }
                                    applyPicks({
                                        items: [...picks, ...additionalPicks],
                                        active: activePick || additionalActivePick || fallbackActivePick
                                    });
                                }
                            }
                            finally {
                                if (!picksToken.isCancellationRequested) {
                                    picker.busy = false;
                                }
                                slowPicksApplied = true;
                            }
                        })()
                    ]);
                };
                // No Picks
                if (providedPicks === null) {
                    // Ignore
                }
                // Fast and Slow Picks
                else if (isFastAndSlowPicks(providedPicks)) {
                    await applyFastAndSlowPicks(providedPicks);
                }
                // Fast Picks
                else if (!(providedPicks instanceof Promise)) {
                    applyPicks(providedPicks);
                }
                // Slow Picks
                else {
                    picker.busy = true;
                    try {
                        const awaitedPicks = await providedPicks;
                        if (picksToken.isCancellationRequested) {
                            return;
                        }
                        if (isFastAndSlowPicks(awaitedPicks)) {
                            await applyFastAndSlowPicks(awaitedPicks);
                        }
                        else {
                            applyPicks(awaitedPicks);
                        }
                    }
                    finally {
                        if (!picksToken.isCancellationRequested) {
                            picker.busy = false;
                        }
                    }
                }
            };
            disposables.add(picker.onDidChangeValue(() => updatePickerItems()));
            updatePickerItems();
            // Accept the pick on accept and hide picker
            disposables.add(picker.onDidAccept(event => {
                if (runOptions?.handleAccept) {
                    if (!event.inBackground) {
                        picker.hide(); // hide picker unless we accept in background
                    }
                    runOptions.handleAccept?.(picker.activeItems[0]);
                    return;
                }
                const [item] = picker.selectedItems;
                if (typeof item?.accept === 'function') {
                    if (!event.inBackground) {
                        picker.hide(); // hide picker unless we accept in background
                    }
                    item.accept(picker.keyMods, event);
                }
            }));
            const buttonTrigger = async (button, item) => {
                if (typeof item.trigger !== 'function') {
                    return;
                }
                const buttonIndex = item.buttons?.indexOf(button) ?? -1;
                if (buttonIndex >= 0) {
                    const result = item.trigger(buttonIndex, picker.keyMods);
                    const action = (typeof result === 'number') ? result : await result;
                    if (token.isCancellationRequested) {
                        return;
                    }
                    switch (action) {
                        case TriggerAction.NO_ACTION:
                            break;
                        case TriggerAction.CLOSE_PICKER:
                            picker.hide();
                            break;
                        case TriggerAction.REFRESH_PICKER:
                            updatePickerItems();
                            break;
                        case TriggerAction.REMOVE_ITEM: {
                            const index = picker.items.indexOf(item);
                            if (index !== -1) {
                                const items = picker.items.slice();
                                const removed = items.splice(index, 1);
                                const activeItems = picker.activeItems.filter(activeItem => activeItem !== removed[0]);
                                const keepScrollPositionBefore = picker.keepScrollPosition;
                                picker.keepScrollPosition = true;
                                picker.items = items;
                                if (activeItems) {
                                    picker.activeItems = activeItems;
                                }
                                picker.keepScrollPosition = keepScrollPositionBefore;
                            }
                            break;
                        }
                    }
                }
            };
            // Trigger the pick with button index if button triggered
            disposables.add(picker.onDidTriggerItemButton(({ button, item }) => buttonTrigger(button, item)));
            disposables.add(picker.onDidTriggerSeparatorButton(({ button, separator }) => buttonTrigger(button, separator)));
            return disposables;
        }
    }
    exports.PickerQuickAccessProvider = PickerQuickAccessProvider;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[704/*vs/platform/quickinput/browser/quickInputBox*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,260/*vs/base/browser/ui/findinput/findInput*/,2/*vs/base/common/lifecycle*/,111/*vs/base/common/severity*/,228/*vs/css!vs/platform/quickinput/browser/media/quickInput*/]), function (require, exports, dom, findInput_1, lifecycle_1, severity_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.QuickInputBox = void 0;
    const $ = dom.$;
    class QuickInputBox extends lifecycle_1.Disposable {
        constructor(parent, inputBoxStyles, toggleStyles) {
            super();
            this.parent = parent;
            this.onKeyDown = (handler) => {
                return dom.addStandardDisposableListener(this.findInput.inputBox.inputElement, dom.EventType.KEY_DOWN, handler);
            };
            this.onDidChange = (handler) => {
                return this.findInput.onDidChange(handler);
            };
            this.container = dom.append(this.parent, $('.quick-input-box'));
            this.findInput = this._register(new findInput_1.FindInput(this.container, undefined, { label: '', inputBoxStyles, toggleStyles }));
            const input = this.findInput.inputBox.inputElement;
            input.role = 'combobox';
            input.ariaHasPopup = 'menu';
            input.ariaAutoComplete = 'list';
            input.ariaExpanded = 'true';
        }
        get value() {
            return this.findInput.getValue();
        }
        set value(value) {
            this.findInput.setValue(value);
        }
        select(range = null) {
            this.findInput.inputBox.select(range);
        }
        getSelection() {
            return this.findInput.inputBox.getSelection();
        }
        isSelectionAtEnd() {
            return this.findInput.inputBox.isSelectionAtEnd();
        }
        get placeholder() {
            return this.findInput.inputBox.inputElement.getAttribute('placeholder') || '';
        }
        set placeholder(placeholder) {
            this.findInput.inputBox.setPlaceHolder(placeholder);
        }
        get password() {
            return this.findInput.inputBox.inputElement.type === 'password';
        }
        set password(password) {
            this.findInput.inputBox.inputElement.type = password ? 'password' : 'text';
        }
        set enabled(enabled) {
            // We can't disable the input box because it is still used for
            // navigating the list. Instead, we disable the list and the OK
            // so that nothing can be selected.
            // TODO: should this be what we do for all find inputs? Or maybe some _other_ API
            // on findInput to change it to readonly?
            this.findInput.inputBox.inputElement.toggleAttribute('readonly', !enabled);
            // TODO: styles of the quick pick need to be moved to the CSS instead of being in line
            // so things like this can be done in CSS
            // this.findInput.inputBox.inputElement.classList.toggle('disabled', !enabled);
        }
        set toggles(toggles) {
            this.findInput.setAdditionalToggles(toggles);
        }
        setAttribute(name, value) {
            this.findInput.inputBox.inputElement.setAttribute(name, value);
        }
        showDecoration(decoration) {
            if (decoration === severity_1.default.Ignore) {
                this.findInput.clearMessage();
            }
            else {
                this.findInput.showMessage({ type: decoration === severity_1.default.Info ? 1 /* MessageType.INFO */ : decoration === severity_1.default.Warning ? 2 /* MessageType.WARNING */ : 3 /* MessageType.ERROR */, content: '' });
            }
        }
        stylesForType(decoration) {
            return this.findInput.inputBox.stylesForType(decoration === severity_1.default.Info ? 1 /* MessageType.INFO */ : decoration === severity_1.default.Warning ? 2 /* MessageType.WARNING */ : 3 /* MessageType.ERROR */);
        }
        setFocus() {
            this.findInput.focus();
        }
        layout() {
            this.findInput.inputBox.layout();
        }
    }
    exports.QuickInputBox = QuickInputBox;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[398/*vs/platform/quickinput/browser/quickInputUtils*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,93/*vs/base/browser/event*/,6/*vs/base/common/event*/,47/*vs/base/browser/keyboardEvent*/,69/*vs/base/browser/touch*/,114/*vs/base/browser/ui/iconLabel/iconLabels*/,187/*vs/base/common/idGenerator*/,446/*vs/base/common/linkedText*/,3/*vs/nls*/,228/*vs/css!vs/platform/quickinput/browser/media/quickInput*/]), function (require, exports, dom, event_1, event_2, keyboardEvent_1, touch_1, iconLabels_1, idGenerator_1, linkedText_1, nls_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.quickInputButtonToAction = quickInputButtonToAction;
    exports.renderQuickInputDescription = renderQuickInputDescription;
    const iconPathToClass = {};
    const iconClassGenerator = new idGenerator_1.IdGenerator('quick-input-button-icon-');
    function getIconClass(iconPath) {
        if (!iconPath) {
            return undefined;
        }
        let iconClass;
        const key = iconPath.dark.toString();
        if (iconPathToClass[key]) {
            iconClass = iconPathToClass[key];
        }
        else {
            iconClass = iconClassGenerator.nextId();
            dom.createCSSRule(`.${iconClass}, .hc-light .${iconClass}`, `background-image: ${dom.asCSSUrl(iconPath.light || iconPath.dark)}`);
            dom.createCSSRule(`.vs-dark .${iconClass}, .hc-black .${iconClass}`, `background-image: ${dom.asCSSUrl(iconPath.dark)}`);
            iconPathToClass[key] = iconClass;
        }
        return iconClass;
    }
    function quickInputButtonToAction(button, id, run) {
        let cssClasses = button.iconClass || getIconClass(button.iconPath);
        if (button.alwaysVisible) {
            cssClasses = cssClasses ? `${cssClasses} always-visible` : 'always-visible';
        }
        return {
            id,
            label: '',
            tooltip: button.tooltip || '',
            class: cssClasses,
            enabled: true,
            run
        };
    }
    function renderQuickInputDescription(description, container, actionHandler) {
        dom.reset(container);
        const parsed = (0, linkedText_1.parseLinkedText)(description);
        let tabIndex = 0;
        for (const node of parsed.nodes) {
            if (typeof node === 'string') {
                container.append(...(0, iconLabels_1.renderLabelWithIcons)(node));
            }
            else {
                let title = node.title;
                if (!title && node.href.startsWith('command:')) {
                    title = (0, nls_1.localize)(1598, "Click to execute command '{0}'", node.href.substring('command:'.length));
                }
                else if (!title) {
                    title = node.href;
                }
                const anchor = dom.$('a', { href: node.href, title, tabIndex: tabIndex++ }, node.label);
                anchor.style.textDecoration = 'underline';
                const handleOpen = (e) => {
                    if (dom.isEventLike(e)) {
                        dom.EventHelper.stop(e, true);
                    }
                    actionHandler.callback(node.href);
                };
                const onClick = actionHandler.disposables.add(new event_1.DomEmitter(anchor, dom.EventType.CLICK)).event;
                const onKeydown = actionHandler.disposables.add(new event_1.DomEmitter(anchor, dom.EventType.KEY_DOWN)).event;
                const onSpaceOrEnter = event_2.Event.chain(onKeydown, $ => $.filter(e => {
                    const event = new keyboardEvent_1.StandardKeyboardEvent(e);
                    return event.equals(10 /* KeyCode.Space */) || event.equals(3 /* KeyCode.Enter */);
                }));
                actionHandler.disposables.add(touch_1.Gesture.addTarget(anchor));
                const onTap = actionHandler.disposables.add(new event_1.DomEmitter(anchor, touch_1.EventType.Tap)).event;
                event_2.Event.any(onClick, onTap, onSpaceOrEnter)(handleOpen, null, actionHandler.disposables);
                container.appendChild(anchor);
            }
        }
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[66/*vs/platform/quickinput/common/quickInput*/], __M([1/*require*/,0/*exports*/,7/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.IQuickInputService = exports.quickPickItemScorerAccessor = exports.QuickPickItemScorerAccessor = exports.QuickInputButtonLocation = exports.QuickPickFocus = exports.ItemActivation = exports.QuickInputHideReason = exports.NO_KEY_MODS = void 0;
    exports.NO_KEY_MODS = { ctrlCmd: false, alt: false };
    var QuickInputHideReason;
    (function (QuickInputHideReason) {
        /**
         * Focus moved away from the quick input.
         */
        QuickInputHideReason[QuickInputHideReason["Blur"] = 1] = "Blur";
        /**
         * An explicit user gesture, e.g. pressing Escape key.
         */
        QuickInputHideReason[QuickInputHideReason["Gesture"] = 2] = "Gesture";
        /**
         * Anything else.
         */
        QuickInputHideReason[QuickInputHideReason["Other"] = 3] = "Other";
    })(QuickInputHideReason || (exports.QuickInputHideReason = QuickInputHideReason = {}));
    /**
     * Represents the activation behavior for items in a quick input. This means which item will be
     * "active" (aka focused).
     */
    var ItemActivation;
    (function (ItemActivation) {
        /**
         * No item will be active.
         */
        ItemActivation[ItemActivation["NONE"] = 0] = "NONE";
        /**
         * First item will be active.
         */
        ItemActivation[ItemActivation["FIRST"] = 1] = "FIRST";
        /**
         * Second item will be active.
         */
        ItemActivation[ItemActivation["SECOND"] = 2] = "SECOND";
        /**
         * Last item will be active.
         */
        ItemActivation[ItemActivation["LAST"] = 3] = "LAST";
    })(ItemActivation || (exports.ItemActivation = ItemActivation = {}));
    /**
     * Represents the focus options for a quick pick.
     */
    var QuickPickFocus;
    (function (QuickPickFocus) {
        /**
         * Focus the first item in the list.
         */
        QuickPickFocus[QuickPickFocus["First"] = 1] = "First";
        /**
         * Focus the second item in the list.
         */
        QuickPickFocus[QuickPickFocus["Second"] = 2] = "Second";
        /**
         * Focus the last item in the list.
         */
        QuickPickFocus[QuickPickFocus["Last"] = 3] = "Last";
        /**
         * Focus the next item in the list.
         */
        QuickPickFocus[QuickPickFocus["Next"] = 4] = "Next";
        /**
         * Focus the previous item in the list.
         */
        QuickPickFocus[QuickPickFocus["Previous"] = 5] = "Previous";
        /**
         * Focus the next page in the list.
         */
        QuickPickFocus[QuickPickFocus["NextPage"] = 6] = "NextPage";
        /**
         * Focus the previous page in the list.
         */
        QuickPickFocus[QuickPickFocus["PreviousPage"] = 7] = "PreviousPage";
        /**
         * Focus the first item under the next separator.
         */
        QuickPickFocus[QuickPickFocus["NextSeparator"] = 8] = "NextSeparator";
        /**
         * Focus the first item under the current separator.
         */
        QuickPickFocus[QuickPickFocus["PreviousSeparator"] = 9] = "PreviousSeparator";
    })(QuickPickFocus || (exports.QuickPickFocus = QuickPickFocus = {}));
    var QuickInputButtonLocation;
    (function (QuickInputButtonLocation) {
        /**
         * In the title bar.
         */
        QuickInputButtonLocation[QuickInputButtonLocation["Title"] = 1] = "Title";
        /**
         * To the right of the input box.
         */
        QuickInputButtonLocation[QuickInputButtonLocation["Inline"] = 2] = "Inline";
    })(QuickInputButtonLocation || (exports.QuickInputButtonLocation = QuickInputButtonLocation = {}));
    class QuickPickItemScorerAccessor {
        constructor(options) {
            this.options = options;
        }
    }
    exports.QuickPickItemScorerAccessor = QuickPickItemScorerAccessor;
    exports.quickPickItemScorerAccessor = new QuickPickItemScorerAccessor();
    //#endregion
    exports.IQuickInputService = (0, instantiation_1.createDecorator)('quickInputService');
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[272/*vs/platform/quickinput/browser/quickInput*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,47/*vs/base/browser/keyboardEvent*/,175/*vs/base/browser/ui/toggle/toggle*/,13/*vs/base/common/arrays*/,14/*vs/base/common/async*/,26/*vs/base/common/codicons*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,16/*vs/base/common/platform*/,111/*vs/base/common/severity*/,30/*vs/base/common/themables*/,3/*vs/nls*/,66/*vs/platform/quickinput/common/quickInput*/,398/*vs/platform/quickinput/browser/quickInputUtils*/,28/*vs/platform/configuration/common/configuration*/,118/*vs/platform/hover/browser/hover*/,12/*vs/platform/contextkey/common/contextkey*/,228/*vs/css!vs/platform/quickinput/browser/media/quickInput*/]), function (require, exports, dom, keyboardEvent_1, toggle_1, arrays_1, async_1, codicons_1, event_1, lifecycle_1, platform_1, severity_1, themables_1, nls_1, quickInput_1, quickInputUtils_1, configuration_1, hover_1, contextkey_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.QuickInputHoverDelegate = exports.InputBox = exports.QuickPick = exports.backButton = exports.endOfQuickInputBoxContext = exports.EndOfQuickInputBoxContextKey = exports.endOfQuickInputBoxContextKeyValue = exports.QuickInputTypeContextKey = exports.quickInputTypeContextKeyValue = exports.inQuickInputContext = exports.InQuickInputContextKey = exports.inQuickInputContextKeyValue = void 0;
    exports.inQuickInputContextKeyValue = 'inQuickInput';
    exports.InQuickInputContextKey = new contextkey_1.RawContextKey(exports.inQuickInputContextKeyValue, false, (0, nls_1.localize)(1580, "Whether keyboard focus is inside the quick input control"));
    exports.inQuickInputContext = contextkey_1.ContextKeyExpr.has(exports.inQuickInputContextKeyValue);
    exports.quickInputTypeContextKeyValue = 'quickInputType';
    exports.QuickInputTypeContextKey = new contextkey_1.RawContextKey(exports.quickInputTypeContextKeyValue, undefined, (0, nls_1.localize)(1581, "The type of the currently visible quick input"));
    exports.endOfQuickInputBoxContextKeyValue = 'cursorAtEndOfQuickInputBox';
    exports.EndOfQuickInputBoxContextKey = new contextkey_1.RawContextKey(exports.endOfQuickInputBoxContextKeyValue, false, (0, nls_1.localize)(1582, "Whether the cursor in the quick input is at the end of the input box"));
    exports.endOfQuickInputBoxContext = contextkey_1.ContextKeyExpr.has(exports.endOfQuickInputBoxContextKeyValue);
    exports.backButton = {
        iconClass: themables_1.ThemeIcon.asClassName(codicons_1.Codicon.quickInputBack),
        tooltip: (0, nls_1.localize)(1583, "Back"),
        handle: -1 // TODO
    };
    class QuickInput extends lifecycle_1.Disposable {
        static { this.noPromptMessage = (0, nls_1.localize)(1584, "Press 'Enter' to confirm your input or 'Escape' to cancel"); }
        constructor(ui) {
            super();
            this.ui = ui;
            this._widgetUpdated = false;
            this.visible = false;
            this._enabled = true;
            this._busy = false;
            this._ignoreFocusOut = false;
            this._leftButtons = [];
            this._rightButtons = [];
            this._inlineButtons = [];
            this.buttonsUpdated = false;
            this._toggles = [];
            this.togglesUpdated = false;
            this.noValidationMessage = QuickInput.noPromptMessage;
            this._severity = severity_1.default.Ignore;
            this.onDidTriggerButtonEmitter = this._register(new event_1.Emitter());
            this.onDidHideEmitter = this._register(new event_1.Emitter());
            this.onWillHideEmitter = this._register(new event_1.Emitter());
            this.onDisposeEmitter = this._register(new event_1.Emitter());
            this.visibleDisposables = this._register(new lifecycle_1.DisposableStore());
            this.onDidHide = this.onDidHideEmitter.event;
        }
        get title() {
            return this._title;
        }
        set title(title) {
            this._title = title;
            this.update();
        }
        get description() {
            return this._description;
        }
        set description(description) {
            this._description = description;
            this.update();
        }
        get step() {
            return this._steps;
        }
        set step(step) {
            this._steps = step;
            this.update();
        }
        get totalSteps() {
            return this._totalSteps;
        }
        set totalSteps(totalSteps) {
            this._totalSteps = totalSteps;
            this.update();
        }
        get enabled() {
            return this._enabled;
        }
        set enabled(enabled) {
            this._enabled = enabled;
            this.update();
        }
        get contextKey() {
            return this._contextKey;
        }
        set contextKey(contextKey) {
            this._contextKey = contextKey;
            this.update();
        }
        get busy() {
            return this._busy;
        }
        set busy(busy) {
            this._busy = busy;
            this.update();
        }
        get ignoreFocusOut() {
            return this._ignoreFocusOut;
        }
        set ignoreFocusOut(ignoreFocusOut) {
            const shouldUpdate = this._ignoreFocusOut !== ignoreFocusOut && !platform_1.isIOS;
            this._ignoreFocusOut = ignoreFocusOut && !platform_1.isIOS;
            if (shouldUpdate) {
                this.update();
            }
        }
        get titleButtons() {
            return this._leftButtons.length
                ? [...this._leftButtons, this._rightButtons]
                : this._rightButtons;
        }
        get buttons() {
            return [
                ...this._leftButtons,
                ...this._rightButtons,
                ...this._inlineButtons
            ];
        }
        set buttons(buttons) {
            this._leftButtons = buttons.filter(b => b === exports.backButton);
            this._rightButtons = buttons.filter(b => b !== exports.backButton && b.location !== quickInput_1.QuickInputButtonLocation.Inline);
            this._inlineButtons = buttons.filter(b => b.location === quickInput_1.QuickInputButtonLocation.Inline);
            this.buttonsUpdated = true;
            this.update();
        }
        get toggles() {
            return this._toggles;
        }
        set toggles(toggles) {
            this._toggles = toggles ?? [];
            this.togglesUpdated = true;
            this.update();
        }
        get validationMessage() {
            return this._validationMessage;
        }
        set validationMessage(validationMessage) {
            this._validationMessage = validationMessage;
            this.update();
        }
        get severity() {
            return this._severity;
        }
        set severity(severity) {
            this._severity = severity;
            this.update();
        }
        show() {
            if (this.visible) {
                return;
            }
            this.visibleDisposables.add(this.ui.onDidTriggerButton(button => {
                if (this.buttons.indexOf(button) !== -1) {
                    this.onDidTriggerButtonEmitter.fire(button);
                }
            }));
            this.ui.show(this);
            // update properties in the controller that get reset in the ui.show() call
            this.visible = true;
            // This ensures the message/prompt gets rendered
            this._lastValidationMessage = undefined;
            // This ensures the input box has the right severity applied
            this._lastSeverity = undefined;
            if (this.buttons.length) {
                // if there are buttons, the ui.show() clears them out of the UI so we should
                // rerender them.
                this.buttonsUpdated = true;
            }
            if (this.toggles.length) {
                // if there are toggles, the ui.show() clears them out of the UI so we should
                // rerender them.
                this.togglesUpdated = true;
            }
            this.update();
        }
        hide() {
            if (!this.visible) {
                return;
            }
            this.ui.hide();
        }
        didHide(reason = quickInput_1.QuickInputHideReason.Other) {
            this.visible = false;
            this.visibleDisposables.clear();
            this.onDidHideEmitter.fire({ reason });
        }
        willHide(reason = quickInput_1.QuickInputHideReason.Other) {
            this.onWillHideEmitter.fire({ reason });
        }
        update() {
            if (!this.visible) {
                return;
            }
            const title = this.getTitle();
            if (title && this.ui.title.textContent !== title) {
                this.ui.title.textContent = title;
            }
            else if (!title && this.ui.title.innerHTML !== '&nbsp;') {
                this.ui.title.innerText = '\u00a0';
            }
            const description = this.getDescription();
            if (this.ui.description1.textContent !== description) {
                this.ui.description1.textContent = description;
            }
            if (this.ui.description2.textContent !== description) {
                this.ui.description2.textContent = description;
            }
            if (this._widgetUpdated) {
                this._widgetUpdated = false;
                if (this._widget) {
                    dom.reset(this.ui.widget, this._widget);
                }
                else {
                    dom.reset(this.ui.widget);
                }
            }
            if (this.busy && !this.busyDelay) {
                this.busyDelay = new async_1.TimeoutTimer();
                this.busyDelay.setIfNotSet(() => {
                    if (this.visible) {
                        this.ui.progressBar.infinite();
                    }
                }, 800);
            }
            if (!this.busy && this.busyDelay) {
                this.ui.progressBar.stop();
                this.busyDelay.cancel();
                this.busyDelay = undefined;
            }
            if (this.buttonsUpdated) {
                this.buttonsUpdated = false;
                this.ui.leftActionBar.clear();
                const leftButtons = this._leftButtons
                    .map((button, index) => (0, quickInputUtils_1.quickInputButtonToAction)(button, `id-${index}`, async () => this.onDidTriggerButtonEmitter.fire(button)));
                this.ui.leftActionBar.push(leftButtons, { icon: true, label: false });
                this.ui.rightActionBar.clear();
                const rightButtons = this._rightButtons
                    .map((button, index) => (0, quickInputUtils_1.quickInputButtonToAction)(button, `id-${index}`, async () => this.onDidTriggerButtonEmitter.fire(button)));
                this.ui.rightActionBar.push(rightButtons, { icon: true, label: false });
                this.ui.inlineActionBar.clear();
                const inlineButtons = this._inlineButtons
                    .map((button, index) => (0, quickInputUtils_1.quickInputButtonToAction)(button, `id-${index}`, async () => this.onDidTriggerButtonEmitter.fire(button)));
                this.ui.inlineActionBar.push(inlineButtons, { icon: true, label: false });
            }
            if (this.togglesUpdated) {
                this.togglesUpdated = false;
                // HACK: Filter out toggles here that are not concrete Toggle objects. This is to workaround
                // a layering issue as quick input's interface is in common but Toggle is in browser and
                // it requires a HTMLElement on its interface
                const concreteToggles = this.toggles?.filter(opts => opts instanceof toggle_1.Toggle) ?? [];
                this.ui.inputBox.toggles = concreteToggles;
            }
            this.ui.ignoreFocusOut = this.ignoreFocusOut;
            this.ui.setEnabled(this.enabled);
            this.ui.setContextKey(this.contextKey);
            const validationMessage = this.validationMessage || this.noValidationMessage;
            if (this._lastValidationMessage !== validationMessage) {
                this._lastValidationMessage = validationMessage;
                dom.reset(this.ui.message);
                (0, quickInputUtils_1.renderQuickInputDescription)(validationMessage, this.ui.message, {
                    callback: (content) => {
                        this.ui.linkOpenerDelegate(content);
                    },
                    disposables: this.visibleDisposables,
                });
            }
            if (this._lastSeverity !== this.severity) {
                this._lastSeverity = this.severity;
                this.showMessageDecoration(this.severity);
            }
        }
        getTitle() {
            if (this.title && this.step) {
                return `${this.title} (${this.getSteps()})`;
            }
            if (this.title) {
                return this.title;
            }
            if (this.step) {
                return this.getSteps();
            }
            return '';
        }
        getDescription() {
            return this.description || '';
        }
        getSteps() {
            if (this.step && this.totalSteps) {
                return (0, nls_1.localize)(1585, "{0}/{1}", this.step, this.totalSteps);
            }
            if (this.step) {
                return String(this.step);
            }
            return '';
        }
        showMessageDecoration(severity) {
            this.ui.inputBox.showDecoration(severity);
            if (severity !== severity_1.default.Ignore) {
                const styles = this.ui.inputBox.stylesForType(severity);
                this.ui.message.style.color = styles.foreground ? `${styles.foreground}` : '';
                this.ui.message.style.backgroundColor = styles.background ? `${styles.background}` : '';
                this.ui.message.style.border = styles.border ? `1px solid ${styles.border}` : '';
                this.ui.message.style.marginBottom = '-2px';
            }
            else {
                this.ui.message.style.color = '';
                this.ui.message.style.backgroundColor = '';
                this.ui.message.style.border = '';
                this.ui.message.style.marginBottom = '';
            }
        }
        dispose() {
            this.hide();
            this.onDisposeEmitter.fire();
            super.dispose();
        }
    }
    class QuickPick extends QuickInput {
        constructor() {
            super(...arguments);
            this._value = '';
            this.onDidChangeValueEmitter = this._register(new event_1.Emitter());
            this.onWillAcceptEmitter = this._register(new event_1.Emitter());
            this.onDidAcceptEmitter = this._register(new event_1.Emitter());
            this.onDidCustomEmitter = this._register(new event_1.Emitter());
            this._items = [];
            this.itemsUpdated = false;
            this._canSelectMany = false;
            this._canAcceptInBackground = false;
            this._matchOnDescription = false;
            this._matchOnDetail = false;
            this._matchOnLabel = true;
            this._matchOnLabelMode = 'fuzzy';
            this._sortByLabel = true;
            this._keepScrollPosition = false;
            this._itemActivation = quickInput_1.ItemActivation.FIRST;
            this._activeItems = [];
            this.activeItemsUpdated = false;
            this.activeItemsToConfirm = [];
            this.onDidChangeActiveEmitter = this._register(new event_1.Emitter());
            this._selectedItems = [];
            this.selectedItemsUpdated = false;
            this.selectedItemsToConfirm = [];
            this.onDidChangeSelectionEmitter = this._register(new event_1.Emitter());
            this.onDidTriggerItemButtonEmitter = this._register(new event_1.Emitter());
            this.onDidTriggerSeparatorButtonEmitter = this._register(new event_1.Emitter());
            this.valueSelectionUpdated = true;
            this._ok = 'default';
            this._customButton = false;
            this._focusEventBufferer = new event_1.EventBufferer();
            this.type = "quickPick" /* QuickInputType.QuickPick */;
            this.filterValue = (value) => value;
            this.onDidChangeValue = this.onDidChangeValueEmitter.event;
            this.onWillAccept = this.onWillAcceptEmitter.event;
            this.onDidAccept = this.onDidAcceptEmitter.event;
            this.onDidChangeActive = this.onDidChangeActiveEmitter.event;
            this.onDidChangeSelection = this.onDidChangeSelectionEmitter.event;
            this.onDidTriggerItemButton = this.onDidTriggerItemButtonEmitter.event;
            this.onDidTriggerSeparatorButton = this.onDidTriggerSeparatorButtonEmitter.event;
        }
        static { this.DEFAULT_ARIA_LABEL = (0, nls_1.localize)(1586, "Type to narrow down results."); }
        get quickNavigate() {
            return this._quickNavigate;
        }
        set quickNavigate(quickNavigate) {
            this._quickNavigate = quickNavigate;
            this.update();
        }
        get value() {
            return this._value;
        }
        set value(value) {
            this.doSetValue(value);
        }
        doSetValue(value, skipUpdate) {
            if (this._value !== value) {
                this._value = value;
                if (!skipUpdate) {
                    this.update();
                }
                if (this.visible) {
                    const didFilter = this.ui.list.filter(this.filterValue(this._value));
                    if (didFilter) {
                        this.trySelectFirst();
                    }
                }
                this.onDidChangeValueEmitter.fire(this._value);
            }
        }
        set ariaLabel(ariaLabel) {
            this._ariaLabel = ariaLabel;
            this.update();
        }
        get ariaLabel() {
            return this._ariaLabel;
        }
        get placeholder() {
            return this._placeholder;
        }
        set placeholder(placeholder) {
            this._placeholder = placeholder;
            this.update();
        }
        get items() {
            return this._items;
        }
        get scrollTop() {
            return this.ui.list.scrollTop;
        }
        set scrollTop(scrollTop) {
            this.ui.list.scrollTop = scrollTop;
        }
        set items(items) {
            this._items = items;
            this.itemsUpdated = true;
            this.update();
        }
        get canSelectMany() {
            return this._canSelectMany;
        }
        set canSelectMany(canSelectMany) {
            this._canSelectMany = canSelectMany;
            this.update();
        }
        get canAcceptInBackground() {
            return this._canAcceptInBackground;
        }
        set canAcceptInBackground(canAcceptInBackground) {
            this._canAcceptInBackground = canAcceptInBackground;
        }
        get matchOnDescription() {
            return this._matchOnDescription;
        }
        set matchOnDescription(matchOnDescription) {
            this._matchOnDescription = matchOnDescription;
            this.update();
        }
        get matchOnDetail() {
            return this._matchOnDetail;
        }
        set matchOnDetail(matchOnDetail) {
            this._matchOnDetail = matchOnDetail;
            this.update();
        }
        get matchOnLabel() {
            return this._matchOnLabel;
        }
        set matchOnLabel(matchOnLabel) {
            this._matchOnLabel = matchOnLabel;
            this.update();
        }
        get matchOnLabelMode() {
            return this._matchOnLabelMode;
        }
        set matchOnLabelMode(matchOnLabelMode) {
            this._matchOnLabelMode = matchOnLabelMode;
            this.update();
        }
        get sortByLabel() {
            return this._sortByLabel;
        }
        set sortByLabel(sortByLabel) {
            this._sortByLabel = sortByLabel;
            this.update();
        }
        get keepScrollPosition() {
            return this._keepScrollPosition;
        }
        set keepScrollPosition(keepScrollPosition) {
            this._keepScrollPosition = keepScrollPosition;
        }
        get itemActivation() {
            return this._itemActivation;
        }
        set itemActivation(itemActivation) {
            this._itemActivation = itemActivation;
        }
        get activeItems() {
            return this._activeItems;
        }
        set activeItems(activeItems) {
            this._activeItems = activeItems;
            this.activeItemsUpdated = true;
            this.update();
        }
        get selectedItems() {
            return this._selectedItems;
        }
        set selectedItems(selectedItems) {
            this._selectedItems = selectedItems;
            this.selectedItemsUpdated = true;
            this.update();
        }
        get keyMods() {
            if (this._quickNavigate) {
                // Disable keyMods when quick navigate is enabled
                // because in this model the interaction is purely
                // keyboard driven and Ctrl/Alt are typically
                // pressed and hold during this interaction.
                return quickInput_1.NO_KEY_MODS;
            }
            return this.ui.keyMods;
        }
        get valueSelection() {
            const selection = this.ui.inputBox.getSelection();
            if (!selection) {
                return undefined;
            }
            return [selection.start, selection.end];
        }
        set valueSelection(valueSelection) {
            this._valueSelection = valueSelection;
            this.valueSelectionUpdated = true;
            this.update();
        }
        get customButton() {
            return this._customButton;
        }
        set customButton(showCustomButton) {
            this._customButton = showCustomButton;
            this.update();
        }
        get customLabel() {
            return this._customButtonLabel;
        }
        set customLabel(label) {
            this._customButtonLabel = label;
            this.update();
        }
        get customHover() {
            return this._customButtonHover;
        }
        set customHover(hover) {
            this._customButtonHover = hover;
            this.update();
        }
        get ok() {
            return this._ok;
        }
        set ok(showOkButton) {
            this._ok = showOkButton;
            this.update();
        }
        get hideInput() {
            return !!this._hideInput;
        }
        set hideInput(hideInput) {
            this._hideInput = hideInput;
            this.update();
        }
        trySelectFirst() {
            if (!this.canSelectMany) {
                this.ui.list.focus(quickInput_1.QuickPickFocus.First);
            }
        }
        show() {
            if (!this.visible) {
                this.visibleDisposables.add(this.ui.inputBox.onDidChange(value => {
                    this.doSetValue(value, true /* skip update since this originates from the UI */);
                }));
                this.visibleDisposables.add(this.ui.onDidAccept(() => {
                    if (this.canSelectMany) {
                        // if there are no checked elements, it means that an onDidChangeSelection never fired to overwrite
                        // `_selectedItems`. In that case, we should emit one with an empty array to ensure that
                        // `.selectedItems` is up to date.
                        if (!this.ui.list.getCheckedElements().length) {
                            this._selectedItems = [];
                            this.onDidChangeSelectionEmitter.fire(this.selectedItems);
                        }
                    }
                    else if (this.activeItems[0]) {
                        // For single-select, we set `selectedItems` to the item that was accepted.
                        this._selectedItems = [this.activeItems[0]];
                        this.onDidChangeSelectionEmitter.fire(this.selectedItems);
                    }
                    this.handleAccept(false);
                }));
                this.visibleDisposables.add(this.ui.onDidCustom(() => {
                    this.onDidCustomEmitter.fire();
                }));
                this.visibleDisposables.add(this._focusEventBufferer.wrapEvent(this.ui.list.onDidChangeFocus, 
                // Only fire the last event
                (_, e) => e)(focusedItems => {
                    if (this.activeItemsUpdated) {
                        return; // Expect another event.
                    }
                    if (this.activeItemsToConfirm !== this._activeItems && (0, arrays_1.equals)(focusedItems, this._activeItems, (a, b) => a === b)) {
                        return;
                    }
                    this._activeItems = focusedItems;
                    this.onDidChangeActiveEmitter.fire(focusedItems);
                }));
                this.visibleDisposables.add(this.ui.list.onDidChangeSelection(({ items: selectedItems, event }) => {
                    if (this.canSelectMany) {
                        if (selectedItems.length) {
                            this.ui.list.setSelectedElements([]);
                        }
                        return;
                    }
                    if (this.selectedItemsToConfirm !== this._selectedItems && (0, arrays_1.equals)(selectedItems, this._selectedItems, (a, b) => a === b)) {
                        return;
                    }
                    this._selectedItems = selectedItems;
                    this.onDidChangeSelectionEmitter.fire(selectedItems);
                    if (selectedItems.length) {
                        this.handleAccept(dom.isMouseEvent(event) && event.button === 1 /* mouse middle click */);
                    }
                }));
                this.visibleDisposables.add(this.ui.list.onChangedCheckedElements(checkedItems => {
                    if (!this.canSelectMany || !this.visible) {
                        return;
                    }
                    if (this.selectedItemsToConfirm !== this._selectedItems && (0, arrays_1.equals)(checkedItems, this._selectedItems, (a, b) => a === b)) {
                        return;
                    }
                    this._selectedItems = checkedItems;
                    this.onDidChangeSelectionEmitter.fire(checkedItems);
                }));
                this.visibleDisposables.add(this.ui.list.onButtonTriggered(event => this.onDidTriggerItemButtonEmitter.fire(event)));
                this.visibleDisposables.add(this.ui.list.onSeparatorButtonTriggered(event => this.onDidTriggerSeparatorButtonEmitter.fire(event)));
                this.visibleDisposables.add(this.registerQuickNavigation());
                this.valueSelectionUpdated = true;
            }
            super.show(); // TODO: Why have show() bubble up while update() trickles down?
        }
        handleAccept(inBackground) {
            // Figure out veto via `onWillAccept` event
            let veto = false;
            this.onWillAcceptEmitter.fire({ veto: () => veto = true });
            // Continue with `onDidAccept` if no veto
            if (!veto) {
                this.onDidAcceptEmitter.fire({ inBackground });
            }
        }
        registerQuickNavigation() {
            return dom.addDisposableListener(this.ui.container, dom.EventType.KEY_UP, e => {
                if (this.canSelectMany || !this._quickNavigate) {
                    return;
                }
                const keyboardEvent = new keyboardEvent_1.StandardKeyboardEvent(e);
                const keyCode = keyboardEvent.keyCode;
                // Select element when keys are pressed that signal it
                const quickNavKeys = this._quickNavigate.keybindings;
                const wasTriggerKeyPressed = quickNavKeys.some(k => {
                    const chords = k.getChords();
                    if (chords.length > 1) {
                        return false;
                    }
                    if (chords[0].shiftKey && keyCode === 4 /* KeyCode.Shift */) {
                        if (keyboardEvent.ctrlKey || keyboardEvent.altKey || keyboardEvent.metaKey) {
                            return false; // this is an optimistic check for the shift key being used to navigate back in quick input
                        }
                        return true;
                    }
                    if (chords[0].altKey && keyCode === 6 /* KeyCode.Alt */) {
                        return true;
                    }
                    if (chords[0].ctrlKey && keyCode === 5 /* KeyCode.Ctrl */) {
                        return true;
                    }
                    if (chords[0].metaKey && keyCode === 57 /* KeyCode.Meta */) {
                        return true;
                    }
                    return false;
                });
                if (wasTriggerKeyPressed) {
                    if (this.activeItems[0]) {
                        this._selectedItems = [this.activeItems[0]];
                        this.onDidChangeSelectionEmitter.fire(this.selectedItems);
                        this.handleAccept(false);
                    }
                    // Unset quick navigate after press. It is only valid once
                    // and should not result in any behaviour change afterwards
                    // if the picker remains open because there was no active item
                    this._quickNavigate = undefined;
                }
            });
        }
        update() {
            if (!this.visible) {
                return;
            }
            // store the scrollTop before it is reset
            const scrollTopBefore = this.keepScrollPosition ? this.scrollTop : 0;
            const hasDescription = !!this.description;
            const visibilities = {
                title: !!this.title || !!this.step || !!this.titleButtons.length,
                description: hasDescription,
                checkAll: this.canSelectMany && !this._hideCheckAll,
                checkBox: this.canSelectMany,
                inputBox: !this._hideInput,
                progressBar: !this._hideInput || hasDescription,
                visibleCount: true,
                count: this.canSelectMany && !this._hideCountBadge,
                ok: this.ok === 'default' ? this.canSelectMany : this.ok,
                list: true,
                message: !!this.validationMessage,
                customButton: this.customButton
            };
            this.ui.setVisibilities(visibilities);
            super.update();
            if (this.ui.inputBox.value !== this.value) {
                this.ui.inputBox.value = this.value;
            }
            if (this.valueSelectionUpdated) {
                this.valueSelectionUpdated = false;
                this.ui.inputBox.select(this._valueSelection && { start: this._valueSelection[0], end: this._valueSelection[1] });
            }
            if (this.ui.inputBox.placeholder !== (this.placeholder || '')) {
                this.ui.inputBox.placeholder = (this.placeholder || '');
            }
            let ariaLabel = this.ariaLabel;
            // Only set aria label to the input box placeholder if we actually have an input box.
            if (!ariaLabel && visibilities.inputBox) {
                ariaLabel = this.placeholder || QuickPick.DEFAULT_ARIA_LABEL;
                // If we have a title, include it in the aria label.
                if (this.title) {
                    ariaLabel += ` - ${this.title}`;
                }
            }
            if (this.ui.list.ariaLabel !== ariaLabel) {
                this.ui.list.ariaLabel = ariaLabel ?? null;
            }
            this.ui.list.matchOnDescription = this.matchOnDescription;
            this.ui.list.matchOnDetail = this.matchOnDetail;
            this.ui.list.matchOnLabel = this.matchOnLabel;
            this.ui.list.matchOnLabelMode = this.matchOnLabelMode;
            this.ui.list.sortByLabel = this.sortByLabel;
            if (this.itemsUpdated) {
                this.itemsUpdated = false;
                this._focusEventBufferer.bufferEvents(() => {
                    this.ui.list.setElements(this.items);
                    // We want focus to exist in the list if there are items so that space can be used to toggle
                    this.ui.list.shouldLoop = !this.canSelectMany;
                    this.ui.list.filter(this.filterValue(this.ui.inputBox.value));
                    switch (this._itemActivation) {
                        case quickInput_1.ItemActivation.NONE:
                            this._itemActivation = quickInput_1.ItemActivation.FIRST; // only valid once, then unset
                            break;
                        case quickInput_1.ItemActivation.SECOND:
                            this.ui.list.focus(quickInput_1.QuickPickFocus.Second);
                            this._itemActivation = quickInput_1.ItemActivation.FIRST; // only valid once, then unset
                            break;
                        case quickInput_1.ItemActivation.LAST:
                            this.ui.list.focus(quickInput_1.QuickPickFocus.Last);
                            this._itemActivation = quickInput_1.ItemActivation.FIRST; // only valid once, then unset
                            break;
                        default:
                            this.trySelectFirst();
                            break;
                    }
                });
            }
            if (this.ui.container.classList.contains('show-checkboxes') !== !!this.canSelectMany) {
                if (this.canSelectMany) {
                    this.ui.list.clearFocus();
                }
                else {
                    this.trySelectFirst();
                }
            }
            if (this.activeItemsUpdated) {
                this.activeItemsUpdated = false;
                this.activeItemsToConfirm = this._activeItems;
                this.ui.list.setFocusedElements(this.activeItems);
                if (this.activeItemsToConfirm === this._activeItems) {
                    this.activeItemsToConfirm = null;
                }
            }
            if (this.selectedItemsUpdated) {
                this.selectedItemsUpdated = false;
                this.selectedItemsToConfirm = this._selectedItems;
                if (this.canSelectMany) {
                    this.ui.list.setCheckedElements(this.selectedItems);
                }
                else {
                    this.ui.list.setSelectedElements(this.selectedItems);
                }
                if (this.selectedItemsToConfirm === this._selectedItems) {
                    this.selectedItemsToConfirm = null;
                }
            }
            this.ui.customButton.label = this.customLabel || '';
            this.ui.customButton.element.title = this.customHover || '';
            if (!visibilities.inputBox) {
                // we need to move focus into the tree to detect keybindings
                // properly when the input box is not visible (quick nav)
                this.ui.list.domFocus();
                // Focus the first element in the list if multiselect is enabled
                if (this.canSelectMany) {
                    this.ui.list.focus(quickInput_1.QuickPickFocus.First);
                }
            }
            // Set the scroll position to what it was before updating the items
            if (this.keepScrollPosition) {
                this.scrollTop = scrollTopBefore;
            }
        }
        focus(focus) {
            this.ui.list.focus(focus);
            // To allow things like space to check/uncheck items
            if (this.canSelectMany) {
                this.ui.list.domFocus();
            }
        }
        accept(inBackground) {
            if (inBackground && !this._canAcceptInBackground) {
                return; // needs to be enabled
            }
            if (this.activeItems[0]) {
                this._selectedItems = [this.activeItems[0]];
                this.onDidChangeSelectionEmitter.fire(this.selectedItems);
                this.handleAccept(inBackground ?? false);
            }
        }
    }
    exports.QuickPick = QuickPick;
    class InputBox extends QuickInput {
        constructor() {
            super(...arguments);
            this._value = '';
            this.valueSelectionUpdated = true;
            this._password = false;
            this.onDidValueChangeEmitter = this._register(new event_1.Emitter());
            this.onDidAcceptEmitter = this._register(new event_1.Emitter());
            this.type = "inputBox" /* QuickInputType.InputBox */;
            this.onDidChangeValue = this.onDidValueChangeEmitter.event;
            this.onDidAccept = this.onDidAcceptEmitter.event;
        }
        get value() {
            return this._value;
        }
        set value(value) {
            this._value = value || '';
            this.update();
        }
        get placeholder() {
            return this._placeholder;
        }
        set placeholder(placeholder) {
            this._placeholder = placeholder;
            this.update();
        }
        get password() {
            return this._password;
        }
        set password(password) {
            this._password = password;
            this.update();
        }
        show() {
            if (!this.visible) {
                this.visibleDisposables.add(this.ui.inputBox.onDidChange(value => {
                    if (value === this.value) {
                        return;
                    }
                    this._value = value;
                    this.onDidValueChangeEmitter.fire(value);
                }));
                this.visibleDisposables.add(this.ui.onDidAccept(() => this.onDidAcceptEmitter.fire()));
                this.valueSelectionUpdated = true;
            }
            super.show();
        }
        update() {
            if (!this.visible) {
                return;
            }
            this.ui.container.classList.remove('hidden-input');
            const visibilities = {
                title: !!this.title || !!this.step || !!this.titleButtons.length,
                description: !!this.description || !!this.step,
                inputBox: true,
                message: true,
                progressBar: true
            };
            this.ui.setVisibilities(visibilities);
            super.update();
            if (this.ui.inputBox.value !== this.value) {
                this.ui.inputBox.value = this.value;
            }
            if (this.valueSelectionUpdated) {
                this.valueSelectionUpdated = false;
                this.ui.inputBox.select(this._valueSelection && { start: this._valueSelection[0], end: this._valueSelection[1] });
            }
            if (this.ui.inputBox.placeholder !== (this.placeholder || '')) {
                this.ui.inputBox.placeholder = (this.placeholder || '');
            }
            if (this.ui.inputBox.password !== this.password) {
                this.ui.inputBox.password = this.password;
            }
        }
    }
    exports.InputBox = InputBox;
    let QuickInputHoverDelegate = class QuickInputHoverDelegate extends hover_1.WorkbenchHoverDelegate {
        constructor(configurationService, hoverService) {
            super('element', false, (options) => this.getOverrideOptions(options), configurationService, hoverService);
        }
        getOverrideOptions(options) {
            // Only show the hover hint if the content is of a decent size
            const showHoverHint = (dom.isHTMLElement(options.content)
                ? options.content.textContent ?? ''
                : typeof options.content === 'string'
                    ? options.content
                    : options.content.value).includes('\n');
            return {
                persistence: {
                    hideOnKeyDown: false,
                },
                appearance: {
                    showHoverHint,
                    skipFadeInAnimation: true,
                },
            };
        }
    };
    exports.QuickInputHoverDelegate = QuickInputHoverDelegate;
    exports.QuickInputHoverDelegate = QuickInputHoverDelegate = __decorate([
        __param(0, configuration_1.IConfigurationService),
        __param(1, hover_1.IHoverService)
    ], QuickInputHoverDelegate);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[38/*vs/platform/registry/common/platform*/], __M([1/*require*/,0/*exports*/,90/*vs/base/common/assert*/,19/*vs/base/common/types*/]), function (require, exports, Assert, Types) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Registry = void 0;
    class RegistryImpl {
        constructor() {
            this.data = new Map();
        }
        add(id, data) {
            Assert.ok(Types.isString(id));
            Assert.ok(Types.isObject(data));
            Assert.ok(!this.data.has(id), 'There is already an extension with this id');
            this.data.set(id, data);
        }
        as(id) {
            return this.data.get(id) || null;
        }
    }
    exports.Registry = new RegistryImpl();
});

define(__m[399/*vs/platform/dnd/browser/dnd*/], __M([1/*require*/,0/*exports*/,38/*vs/platform/registry/common/platform*/]), function (require, exports, platform_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.LocalSelectionTransfer = exports.Extensions = exports.CodeDataTransfers = void 0;
    //#region Editor / Resources DND
    exports.CodeDataTransfers = {
        EDITORS: 'CodeEditors',
        FILES: 'CodeFiles'
    };
    class DragAndDropContributionRegistry {
    }
    exports.Extensions = {
        DragAndDropContribution: 'workbench.contributions.dragAndDrop'
    };
    platform_1.Registry.add(exports.Extensions.DragAndDropContribution, new DragAndDropContributionRegistry());
    //#endregion
    //#region DND Utilities
    /**
     * A singleton to store transfer data during drag & drop operations that are only valid within the application.
     */
    class LocalSelectionTransfer {
        static { this.INSTANCE = new LocalSelectionTransfer(); }
        constructor() {
            // protect against external instantiation
        }
        static getInstance() {
            return LocalSelectionTransfer.INSTANCE;
        }
        hasData(proto) {
            return proto && proto === this.proto;
        }
        getData(proto) {
            if (this.hasData(proto)) {
                return this.data;
            }
            return undefined;
        }
    }
    exports.LocalSelectionTransfer = LocalSelectionTransfer;
});
//#endregion

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[400/*vs/editor/browser/dnd*/], __M([1/*require*/,0/*exports*/,224/*vs/base/browser/dnd*/,194/*vs/base/common/dataTransfer*/,128/*vs/base/common/mime*/,22/*vs/base/common/uri*/,399/*vs/platform/dnd/browser/dnd*/]), function (require, exports, dnd_1, dataTransfer_1, mime_1, uri_1, dnd_2) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.toVSDataTransfer = toVSDataTransfer;
    exports.toExternalVSDataTransfer = toExternalVSDataTransfer;
    function toVSDataTransfer(dataTransfer) {
        const vsDataTransfer = new dataTransfer_1.VSDataTransfer();
        for (const item of dataTransfer.items) {
            const type = item.type;
            if (item.kind === 'string') {
                const asStringValue = new Promise(resolve => item.getAsString(resolve));
                vsDataTransfer.append(type, (0, dataTransfer_1.createStringDataTransferItem)(asStringValue));
            }
            else if (item.kind === 'file') {
                const file = item.getAsFile();
                if (file) {
                    vsDataTransfer.append(type, createFileDataTransferItemFromFile(file));
                }
            }
        }
        return vsDataTransfer;
    }
    function createFileDataTransferItemFromFile(file) {
        const uri = file.path ? uri_1.URI.parse(file.path) : undefined;
        return (0, dataTransfer_1.createFileDataTransferItem)(file.name, uri, async () => {
            return new Uint8Array(await file.arrayBuffer());
        });
    }
    const INTERNAL_DND_MIME_TYPES = Object.freeze([
        dnd_2.CodeDataTransfers.EDITORS,
        dnd_2.CodeDataTransfers.FILES,
        dnd_1.DataTransfers.RESOURCES,
        dnd_1.DataTransfers.INTERNAL_URI_LIST,
    ]);
    function toExternalVSDataTransfer(sourceDataTransfer, overwriteUriList = false) {
        const vsDataTransfer = toVSDataTransfer(sourceDataTransfer);
        // Try to expose the internal uri-list type as the standard type
        const uriList = vsDataTransfer.get(dnd_1.DataTransfers.INTERNAL_URI_LIST);
        if (uriList) {
            vsDataTransfer.replace(mime_1.Mimes.uriList, uriList);
        }
        else {
            if (overwriteUriList || !vsDataTransfer.has(mime_1.Mimes.uriList)) {
                // Otherwise, fallback to adding dragged resources to the uri list
                const editorData = [];
                for (const item of sourceDataTransfer.items) {
                    const file = item.getAsFile();
                    if (file) {
                        const path = file.path;
                        try {
                            if (path) {
                                editorData.push(uri_1.URI.file(path).toString());
                            }
                            else {
                                editorData.push(uri_1.URI.parse(file.name, true).toString());
                            }
                        }
                        catch {
                            // Parsing failed. Leave out from list
                        }
                    }
                }
                if (editorData.length) {
                    vsDataTransfer.replace(mime_1.Mimes.uriList, (0, dataTransfer_1.createStringDataTransferItem)(dataTransfer_1.UriList.create(editorData)));
                }
            }
        }
        for (const internal of INTERNAL_DND_MIME_TYPES) {
            vsDataTransfer.delete(internal);
        }
        return vsDataTransfer;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[273/*vs/platform/jsonschemas/common/jsonContributionRegistry*/], __M([1/*require*/,0/*exports*/,6/*vs/base/common/event*/,38/*vs/platform/registry/common/platform*/]), function (require, exports, event_1, platform) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Extensions = void 0;
    exports.Extensions = {
        JSONContribution: 'base.contributions.json'
    };
    function normalizeId(id) {
        if (id.length > 0 && id.charAt(id.length - 1) === '#') {
            return id.substring(0, id.length - 1);
        }
        return id;
    }
    class JSONContributionRegistry {
        constructor() {
            this._onDidChangeSchema = new event_1.Emitter();
            this.schemasById = {};
        }
        registerSchema(uri, unresolvedSchemaContent) {
            this.schemasById[normalizeId(uri)] = unresolvedSchemaContent;
            this._onDidChangeSchema.fire(uri);
        }
        notifySchemaChanged(uri) {
            this._onDidChangeSchema.fire(uri);
        }
    }
    const jsonContributionRegistry = new JSONContributionRegistry();
    platform.Registry.add(exports.Extensions.JSONContribution, jsonContributionRegistry);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[109/*vs/platform/configuration/common/configurationRegistry*/], __M([1/*require*/,0/*exports*/,13/*vs/base/common/arrays*/,6/*vs/base/common/event*/,19/*vs/base/common/types*/,3/*vs/nls*/,28/*vs/platform/configuration/common/configuration*/,273/*vs/platform/jsonschemas/common/jsonContributionRegistry*/,38/*vs/platform/registry/common/platform*/]), function (require, exports, arrays_1, event_1, types, nls, configuration_1, jsonContributionRegistry_1, platform_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.OVERRIDE_PROPERTY_REGEX = exports.OVERRIDE_PROPERTY_PATTERN = exports.resourceLanguageSettingsSchemaId = exports.resourceSettings = exports.windowSettings = exports.machineOverridableSettings = exports.machineSettings = exports.applicationSettings = exports.allSettings = exports.Extensions = void 0;
    exports.overrideIdentifiersFromKey = overrideIdentifiersFromKey;
    exports.getDefaultValue = getDefaultValue;
    exports.validateProperty = validateProperty;
    exports.Extensions = {
        Configuration: 'base.contributions.configuration'
    };
    exports.allSettings = { properties: {}, patternProperties: {} };
    exports.applicationSettings = { properties: {}, patternProperties: {} };
    exports.machineSettings = { properties: {}, patternProperties: {} };
    exports.machineOverridableSettings = { properties: {}, patternProperties: {} };
    exports.windowSettings = { properties: {}, patternProperties: {} };
    exports.resourceSettings = { properties: {}, patternProperties: {} };
    exports.resourceLanguageSettingsSchemaId = 'vscode://schemas/settings/resourceLanguage';
    const contributionRegistry = platform_1.Registry.as(jsonContributionRegistry_1.Extensions.JSONContribution);
    class ConfigurationRegistry {
        constructor() {
            this.registeredConfigurationDefaults = [];
            this.overrideIdentifiers = new Set();
            this._onDidSchemaChange = new event_1.Emitter();
            this._onDidUpdateConfiguration = new event_1.Emitter();
            this.configurationDefaultsOverrides = new Map();
            this.defaultLanguageConfigurationOverridesNode = {
                id: 'defaultOverrides',
                title: nls.localize(1503, "Default Language Configuration Overrides"),
                properties: {}
            };
            this.configurationContributors = [this.defaultLanguageConfigurationOverridesNode];
            this.resourceLanguageSettingsSchema = {
                properties: {},
                patternProperties: {},
                additionalProperties: true,
                allowTrailingCommas: true,
                allowComments: true
            };
            this.configurationProperties = {};
            this.policyConfigurations = new Map();
            this.excludedConfigurationProperties = {};
            contributionRegistry.registerSchema(exports.resourceLanguageSettingsSchemaId, this.resourceLanguageSettingsSchema);
            this.registerOverridePropertyPatternKey();
        }
        registerConfiguration(configuration, validate = true) {
            this.registerConfigurations([configuration], validate);
        }
        registerConfigurations(configurations, validate = true) {
            const properties = new Set();
            this.doRegisterConfigurations(configurations, validate, properties);
            contributionRegistry.registerSchema(exports.resourceLanguageSettingsSchemaId, this.resourceLanguageSettingsSchema);
            this._onDidSchemaChange.fire();
            this._onDidUpdateConfiguration.fire({ properties });
        }
        registerDefaultConfigurations(configurationDefaults) {
            const properties = new Set();
            this.doRegisterDefaultConfigurations(configurationDefaults, properties);
            this._onDidSchemaChange.fire();
            this._onDidUpdateConfiguration.fire({ properties, defaultsOverrides: true });
        }
        doRegisterDefaultConfigurations(configurationDefaults, bucket) {
            this.registeredConfigurationDefaults.push(...configurationDefaults);
            const overrideIdentifiers = [];
            for (const { overrides, source } of configurationDefaults) {
                for (const key in overrides) {
                    bucket.add(key);
                    const configurationDefaultOverridesForKey = this.configurationDefaultsOverrides.get(key)
                        ?? this.configurationDefaultsOverrides.set(key, { configurationDefaultOverrides: [] }).get(key);
                    const value = overrides[key];
                    configurationDefaultOverridesForKey.configurationDefaultOverrides.push({ value, source });
                    // Configuration defaults for Override Identifiers
                    if (exports.OVERRIDE_PROPERTY_REGEX.test(key)) {
                        const newDefaultOverride = this.mergeDefaultConfigurationsForOverrideIdentifier(key, value, source, configurationDefaultOverridesForKey.configurationDefaultOverrideValue);
                        if (!newDefaultOverride) {
                            continue;
                        }
                        configurationDefaultOverridesForKey.configurationDefaultOverrideValue = newDefaultOverride;
                        this.updateDefaultOverrideProperty(key, newDefaultOverride, source);
                        overrideIdentifiers.push(...overrideIdentifiersFromKey(key));
                    }
                    // Configuration defaults for Configuration Properties
                    else {
                        const newDefaultOverride = this.mergeDefaultConfigurationsForConfigurationProperty(key, value, source, configurationDefaultOverridesForKey.configurationDefaultOverrideValue);
                        if (!newDefaultOverride) {
                            continue;
                        }
                        configurationDefaultOverridesForKey.configurationDefaultOverrideValue = newDefaultOverride;
                        const property = this.configurationProperties[key];
                        if (property) {
                            this.updatePropertyDefaultValue(key, property);
                            this.updateSchema(key, property);
                        }
                    }
                }
            }
            this.doRegisterOverrideIdentifiers(overrideIdentifiers);
        }
        updateDefaultOverrideProperty(key, newDefaultOverride, source) {
            const property = {
                type: 'object',
                default: newDefaultOverride.value,
                description: nls.localize(1504, "Configure settings to be overridden for the {0} language.", (0, configuration_1.getLanguageTagSettingPlainKey)(key)),
                $ref: exports.resourceLanguageSettingsSchemaId,
                defaultDefaultValue: newDefaultOverride.value,
                source,
                defaultValueSource: source
            };
            this.configurationProperties[key] = property;
            this.defaultLanguageConfigurationOverridesNode.properties[key] = property;
        }
        mergeDefaultConfigurationsForOverrideIdentifier(overrideIdentifier, configurationValueObject, valueSource, existingDefaultOverride) {
            const defaultValue = existingDefaultOverride?.value || {};
            const source = existingDefaultOverride?.source ?? new Map();
            // This should not happen
            if (!(source instanceof Map)) {
                console.error('objectConfigurationSources is not a Map');
                return undefined;
            }
            for (const propertyKey of Object.keys(configurationValueObject)) {
                const propertyDefaultValue = configurationValueObject[propertyKey];
                const isObjectSetting = types.isObject(propertyDefaultValue) &&
                    (types.isUndefined(defaultValue[propertyKey]) || types.isObject(defaultValue[propertyKey]));
                // If the default value is an object, merge the objects and store the source of each keys
                if (isObjectSetting) {
                    defaultValue[propertyKey] = { ...(defaultValue[propertyKey] ?? {}), ...propertyDefaultValue };
                    // Track the source of each value in the object
                    if (valueSource) {
                        for (const objectKey in propertyDefaultValue) {
                            source.set(`${propertyKey}.${objectKey}`, valueSource);
                        }
                    }
                }
                // Primitive values are overridden
                else {
                    defaultValue[propertyKey] = propertyDefaultValue;
                    if (valueSource) {
                        source.set(propertyKey, valueSource);
                    }
                    else {
                        source.delete(propertyKey);
                    }
                }
            }
            return { value: defaultValue, source };
        }
        mergeDefaultConfigurationsForConfigurationProperty(propertyKey, value, valuesSource, existingDefaultOverride) {
            const property = this.configurationProperties[propertyKey];
            const existingDefaultValue = existingDefaultOverride?.value ?? property?.defaultDefaultValue;
            let source = valuesSource;
            const isObjectSetting = types.isObject(value) &&
                (property !== undefined && property.type === 'object' ||
                    property === undefined && (types.isUndefined(existingDefaultValue) || types.isObject(existingDefaultValue)));
            // If the default value is an object, merge the objects and store the source of each keys
            if (isObjectSetting) {
                source = existingDefaultOverride?.source ?? new Map();
                // This should not happen
                if (!(source instanceof Map)) {
                    console.error('defaultValueSource is not a Map');
                    return undefined;
                }
                for (const objectKey in value) {
                    if (valuesSource) {
                        source.set(`${propertyKey}.${objectKey}`, valuesSource);
                    }
                }
                value = { ...(types.isObject(existingDefaultValue) ? existingDefaultValue : {}), ...value };
            }
            return { value, source };
        }
        registerOverrideIdentifiers(overrideIdentifiers) {
            this.doRegisterOverrideIdentifiers(overrideIdentifiers);
            this._onDidSchemaChange.fire();
        }
        doRegisterOverrideIdentifiers(overrideIdentifiers) {
            for (const overrideIdentifier of overrideIdentifiers) {
                this.overrideIdentifiers.add(overrideIdentifier);
            }
            this.updateOverridePropertyPatternKey();
        }
        doRegisterConfigurations(configurations, validate, bucket) {
            configurations.forEach(configuration => {
                this.validateAndRegisterProperties(configuration, validate, configuration.extensionInfo, configuration.restrictedProperties, undefined, bucket);
                this.configurationContributors.push(configuration);
                this.registerJSONConfiguration(configuration);
            });
        }
        validateAndRegisterProperties(configuration, validate = true, extensionInfo, restrictedProperties, scope = 3 /* ConfigurationScope.WINDOW */, bucket) {
            scope = types.isUndefinedOrNull(configuration.scope) ? scope : configuration.scope;
            const properties = configuration.properties;
            if (properties) {
                for (const key in properties) {
                    const property = properties[key];
                    if (validate && validateProperty(key, property)) {
                        delete properties[key];
                        continue;
                    }
                    property.source = extensionInfo;
                    // update default value
                    property.defaultDefaultValue = properties[key].default;
                    this.updatePropertyDefaultValue(key, property);
                    // update scope
                    if (exports.OVERRIDE_PROPERTY_REGEX.test(key)) {
                        property.scope = undefined; // No scope for overridable properties `[${identifier}]`
                    }
                    else {
                        property.scope = types.isUndefinedOrNull(property.scope) ? scope : property.scope;
                        property.restricted = types.isUndefinedOrNull(property.restricted) ? !!restrictedProperties?.includes(key) : property.restricted;
                    }
                    // Add to properties maps
                    // Property is included by default if 'included' is unspecified
                    if (properties[key].hasOwnProperty('included') && !properties[key].included) {
                        this.excludedConfigurationProperties[key] = properties[key];
                        delete properties[key];
                        continue;
                    }
                    else {
                        this.configurationProperties[key] = properties[key];
                        if (properties[key].policy?.name) {
                            this.policyConfigurations.set(properties[key].policy.name, key);
                        }
                    }
                    if (!properties[key].deprecationMessage && properties[key].markdownDeprecationMessage) {
                        // If not set, default deprecationMessage to the markdown source
                        properties[key].deprecationMessage = properties[key].markdownDeprecationMessage;
                    }
                    bucket.add(key);
                }
            }
            const subNodes = configuration.allOf;
            if (subNodes) {
                for (const node of subNodes) {
                    this.validateAndRegisterProperties(node, validate, extensionInfo, restrictedProperties, scope, bucket);
                }
            }
        }
        getConfigurationProperties() {
            return this.configurationProperties;
        }
        getPolicyConfigurations() {
            return this.policyConfigurations;
        }
        registerJSONConfiguration(configuration) {
            const register = (configuration) => {
                const properties = configuration.properties;
                if (properties) {
                    for (const key in properties) {
                        this.updateSchema(key, properties[key]);
                    }
                }
                const subNodes = configuration.allOf;
                subNodes?.forEach(register);
            };
            register(configuration);
        }
        updateSchema(key, property) {
            exports.allSettings.properties[key] = property;
            switch (property.scope) {
                case 1 /* ConfigurationScope.APPLICATION */:
                    exports.applicationSettings.properties[key] = property;
                    break;
                case 2 /* ConfigurationScope.MACHINE */:
                    exports.machineSettings.properties[key] = property;
                    break;
                case 6 /* ConfigurationScope.MACHINE_OVERRIDABLE */:
                    exports.machineOverridableSettings.properties[key] = property;
                    break;
                case 3 /* ConfigurationScope.WINDOW */:
                    exports.windowSettings.properties[key] = property;
                    break;
                case 4 /* ConfigurationScope.RESOURCE */:
                    exports.resourceSettings.properties[key] = property;
                    break;
                case 5 /* ConfigurationScope.LANGUAGE_OVERRIDABLE */:
                    exports.resourceSettings.properties[key] = property;
                    this.resourceLanguageSettingsSchema.properties[key] = property;
                    break;
            }
        }
        updateOverridePropertyPatternKey() {
            for (const overrideIdentifier of this.overrideIdentifiers.values()) {
                const overrideIdentifierProperty = `[${overrideIdentifier}]`;
                const resourceLanguagePropertiesSchema = {
                    type: 'object',
                    description: nls.localize(1505, "Configure editor settings to be overridden for a language."),
                    errorMessage: nls.localize(1506, "This setting does not support per-language configuration."),
                    $ref: exports.resourceLanguageSettingsSchemaId,
                };
                this.updatePropertyDefaultValue(overrideIdentifierProperty, resourceLanguagePropertiesSchema);
                exports.allSettings.properties[overrideIdentifierProperty] = resourceLanguagePropertiesSchema;
                exports.applicationSettings.properties[overrideIdentifierProperty] = resourceLanguagePropertiesSchema;
                exports.machineSettings.properties[overrideIdentifierProperty] = resourceLanguagePropertiesSchema;
                exports.machineOverridableSettings.properties[overrideIdentifierProperty] = resourceLanguagePropertiesSchema;
                exports.windowSettings.properties[overrideIdentifierProperty] = resourceLanguagePropertiesSchema;
                exports.resourceSettings.properties[overrideIdentifierProperty] = resourceLanguagePropertiesSchema;
            }
        }
        registerOverridePropertyPatternKey() {
            const resourceLanguagePropertiesSchema = {
                type: 'object',
                description: nls.localize(1507, "Configure editor settings to be overridden for a language."),
                errorMessage: nls.localize(1508, "This setting does not support per-language configuration."),
                $ref: exports.resourceLanguageSettingsSchemaId,
            };
            exports.allSettings.patternProperties[exports.OVERRIDE_PROPERTY_PATTERN] = resourceLanguagePropertiesSchema;
            exports.applicationSettings.patternProperties[exports.OVERRIDE_PROPERTY_PATTERN] = resourceLanguagePropertiesSchema;
            exports.machineSettings.patternProperties[exports.OVERRIDE_PROPERTY_PATTERN] = resourceLanguagePropertiesSchema;
            exports.machineOverridableSettings.patternProperties[exports.OVERRIDE_PROPERTY_PATTERN] = resourceLanguagePropertiesSchema;
            exports.windowSettings.patternProperties[exports.OVERRIDE_PROPERTY_PATTERN] = resourceLanguagePropertiesSchema;
            exports.resourceSettings.patternProperties[exports.OVERRIDE_PROPERTY_PATTERN] = resourceLanguagePropertiesSchema;
            this._onDidSchemaChange.fire();
        }
        updatePropertyDefaultValue(key, property) {
            const configurationdefaultOverride = this.configurationDefaultsOverrides.get(key)?.configurationDefaultOverrideValue;
            let defaultValue = undefined;
            let defaultSource = undefined;
            if (configurationdefaultOverride
                && (!property.disallowConfigurationDefault || !configurationdefaultOverride.source) // Prevent overriding the default value if the property is disallowed to be overridden by configuration defaults from extensions
            ) {
                defaultValue = configurationdefaultOverride.value;
                defaultSource = configurationdefaultOverride.source;
            }
            if (types.isUndefined(defaultValue)) {
                defaultValue = property.defaultDefaultValue;
                defaultSource = undefined;
            }
            if (types.isUndefined(defaultValue)) {
                defaultValue = getDefaultValue(property.type);
            }
            property.default = defaultValue;
            property.defaultValueSource = defaultSource;
        }
    }
    const OVERRIDE_IDENTIFIER_PATTERN = `\\[([^\\]]+)\\]`;
    const OVERRIDE_IDENTIFIER_REGEX = new RegExp(OVERRIDE_IDENTIFIER_PATTERN, 'g');
    exports.OVERRIDE_PROPERTY_PATTERN = `^(${OVERRIDE_IDENTIFIER_PATTERN})+$`;
    exports.OVERRIDE_PROPERTY_REGEX = new RegExp(exports.OVERRIDE_PROPERTY_PATTERN);
    function overrideIdentifiersFromKey(key) {
        const identifiers = [];
        if (exports.OVERRIDE_PROPERTY_REGEX.test(key)) {
            let matches = OVERRIDE_IDENTIFIER_REGEX.exec(key);
            while (matches?.length) {
                const identifier = matches[1].trim();
                if (identifier) {
                    identifiers.push(identifier);
                }
                matches = OVERRIDE_IDENTIFIER_REGEX.exec(key);
            }
        }
        return (0, arrays_1.distinct)(identifiers);
    }
    function getDefaultValue(type) {
        const t = Array.isArray(type) ? type[0] : type;
        switch (t) {
            case 'boolean':
                return false;
            case 'integer':
            case 'number':
                return 0;
            case 'string':
                return '';
            case 'array':
                return [];
            case 'object':
                return {};
            default:
                return null;
        }
    }
    const configurationRegistry = new ConfigurationRegistry();
    platform_1.Registry.add(exports.Extensions.Configuration, configurationRegistry);
    function validateProperty(property, schema) {
        if (!property.trim()) {
            return nls.localize(1509, "Cannot register an empty property");
        }
        if (exports.OVERRIDE_PROPERTY_REGEX.test(property)) {
            return nls.localize(1510, "Cannot register '{0}'. This matches property pattern '\\\\[.*\\\\]$' for describing language specific editor settings. Use 'configurationDefaults' contribution.", property);
        }
        if (configurationRegistry.getConfigurationProperties()[property] !== undefined) {
            return nls.localize(1511, "Cannot register '{0}'. This property is already registered.", property);
        }
        if (schema.policy?.name && configurationRegistry.getPolicyConfigurations().get(schema.policy?.name) !== undefined) {
            return nls.localize(1512, "Cannot register '{0}'. The associated policy {1} is already registered with {2}.", property, schema.policy?.name, configurationRegistry.getPolicyConfigurations().get(schema.policy?.name));
        }
        return null;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[274/*vs/editor/common/config/editorConfigurationSchema*/], __M([1/*require*/,0/*exports*/,308/*vs/editor/common/config/diffEditor*/,37/*vs/editor/common/config/editorOptions*/,197/*vs/editor/common/core/textModelDefaults*/,3/*vs/nls*/,109/*vs/platform/configuration/common/configurationRegistry*/,38/*vs/platform/registry/common/platform*/]), function (require, exports, diffEditor_1, editorOptions_1, textModelDefaults_1, nls, configurationRegistry_1, platform_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.editorConfigurationBaseNode = void 0;
    exports.isEditorConfigurationKey = isEditorConfigurationKey;
    exports.isDiffEditorConfigurationKey = isDiffEditorConfigurationKey;
    exports.editorConfigurationBaseNode = Object.freeze({
        id: 'editor',
        order: 5,
        type: 'object',
        title: nls.localize(133, "Editor"),
        scope: 5 /* ConfigurationScope.LANGUAGE_OVERRIDABLE */,
    });
    const editorConfiguration = {
        ...exports.editorConfigurationBaseNode,
        properties: {
            'editor.tabSize': {
                type: 'number',
                default: textModelDefaults_1.EDITOR_MODEL_DEFAULTS.tabSize,
                minimum: 1,
                markdownDescription: nls.localize(134, "The number of spaces a tab is equal to. This setting is overridden based on the file contents when {0} is on.", '`#editor.detectIndentation#`')
            },
            'editor.indentSize': {
                'anyOf': [
                    {
                        type: 'string',
                        enum: ['tabSize']
                    },
                    {
                        type: 'number',
                        minimum: 1
                    }
                ],
                default: 'tabSize',
                markdownDescription: nls.localize(135, "The number of spaces used for indentation or `\"tabSize\"` to use the value from `#editor.tabSize#`. This setting is overridden based on the file contents when `#editor.detectIndentation#` is on.")
            },
            'editor.insertSpaces': {
                type: 'boolean',
                default: textModelDefaults_1.EDITOR_MODEL_DEFAULTS.insertSpaces,
                markdownDescription: nls.localize(136, "Insert spaces when pressing `Tab`. This setting is overridden based on the file contents when {0} is on.", '`#editor.detectIndentation#`')
            },
            'editor.detectIndentation': {
                type: 'boolean',
                default: textModelDefaults_1.EDITOR_MODEL_DEFAULTS.detectIndentation,
                markdownDescription: nls.localize(137, "Controls whether {0} and {1} will be automatically detected when a file is opened based on the file contents.", '`#editor.tabSize#`', '`#editor.insertSpaces#`')
            },
            'editor.trimAutoWhitespace': {
                type: 'boolean',
                default: textModelDefaults_1.EDITOR_MODEL_DEFAULTS.trimAutoWhitespace,
                description: nls.localize(138, "Remove trailing auto inserted whitespace.")
            },
            'editor.largeFileOptimizations': {
                type: 'boolean',
                default: textModelDefaults_1.EDITOR_MODEL_DEFAULTS.largeFileOptimizations,
                description: nls.localize(139, "Special handling for large files to disable certain memory intensive features.")
            },
            'editor.wordBasedSuggestions': {
                enum: ['off', 'currentDocument', 'matchingDocuments', 'allDocuments'],
                default: 'matchingDocuments',
                enumDescriptions: [
                    nls.localize(140, 'Turn off Word Based Suggestions.'),
                    nls.localize(141, 'Only suggest words from the active document.'),
                    nls.localize(142, 'Suggest words from all open documents of the same language.'),
                    nls.localize(143, 'Suggest words from all open documents.')
                ],
                description: nls.localize(144, "Controls whether completions should be computed based on words in the document and from which documents they are computed.")
            },
            'editor.semanticHighlighting.enabled': {
                enum: [true, false, 'configuredByTheme'],
                enumDescriptions: [
                    nls.localize(145, 'Semantic highlighting enabled for all color themes.'),
                    nls.localize(146, 'Semantic highlighting disabled for all color themes.'),
                    nls.localize(147, 'Semantic highlighting is configured by the current color theme\'s `semanticHighlighting` setting.')
                ],
                default: 'configuredByTheme',
                description: nls.localize(148, "Controls whether the semanticHighlighting is shown for the languages that support it.")
            },
            'editor.stablePeek': {
                type: 'boolean',
                default: false,
                markdownDescription: nls.localize(149, "Keep peek editors open even when double-clicking their content or when hitting `Escape`.")
            },
            'editor.maxTokenizationLineLength': {
                type: 'integer',
                default: 20_000,
                description: nls.localize(150, "Lines above this length will not be tokenized for performance reasons")
            },
            'editor.experimental.asyncTokenization': {
                type: 'boolean',
                default: true,
                description: nls.localize(151, "Controls whether the tokenization should happen asynchronously on a web worker."),
                tags: ['experimental'],
            },
            'editor.experimental.asyncTokenizationLogging': {
                type: 'boolean',
                default: false,
                description: nls.localize(152, "Controls whether async tokenization should be logged. For debugging only."),
            },
            'editor.experimental.asyncTokenizationVerification': {
                type: 'boolean',
                default: false,
                description: nls.localize(153, "Controls whether async tokenization should be verified against legacy background tokenization. Might slow down tokenization. For debugging only."),
                tags: ['experimental'],
            },
            'editor.experimental.treeSitterTelemetry': {
                type: 'boolean',
                default: false,
                markdownDescription: nls.localize(154, "Controls whether tree sitter parsing should be turned on and telemetry collected. Setting `editor.experimental.preferTreeSitter` for specific languages will take precedence."),
                tags: ['experimental']
            },
            'editor.language.brackets': {
                type: ['array', 'null'],
                default: null, // We want to distinguish the empty array from not configured.
                description: nls.localize(155, 'Defines the bracket symbols that increase or decrease the indentation.'),
                items: {
                    type: 'array',
                    items: [
                        {
                            type: 'string',
                            description: nls.localize(156, 'The opening bracket character or string sequence.')
                        },
                        {
                            type: 'string',
                            description: nls.localize(157, 'The closing bracket character or string sequence.')
                        }
                    ]
                }
            },
            'editor.language.colorizedBracketPairs': {
                type: ['array', 'null'],
                default: null, // We want to distinguish the empty array from not configured.
                description: nls.localize(158, 'Defines the bracket pairs that are colorized by their nesting level if bracket pair colorization is enabled.'),
                items: {
                    type: 'array',
                    items: [
                        {
                            type: 'string',
                            description: nls.localize(159, 'The opening bracket character or string sequence.')
                        },
                        {
                            type: 'string',
                            description: nls.localize(160, 'The closing bracket character or string sequence.')
                        }
                    ]
                }
            },
            'diffEditor.maxComputationTime': {
                type: 'number',
                default: diffEditor_1.diffEditorDefaultOptions.maxComputationTime,
                description: nls.localize(161, "Timeout in milliseconds after which diff computation is cancelled. Use 0 for no timeout.")
            },
            'diffEditor.maxFileSize': {
                type: 'number',
                default: diffEditor_1.diffEditorDefaultOptions.maxFileSize,
                description: nls.localize(162, "Maximum file size in MB for which to compute diffs. Use 0 for no limit.")
            },
            'diffEditor.renderSideBySide': {
                type: 'boolean',
                default: diffEditor_1.diffEditorDefaultOptions.renderSideBySide,
                description: nls.localize(163, "Controls whether the diff editor shows the diff side by side or inline.")
            },
            'diffEditor.renderSideBySideInlineBreakpoint': {
                type: 'number',
                default: diffEditor_1.diffEditorDefaultOptions.renderSideBySideInlineBreakpoint,
                description: nls.localize(164, "If the diff editor width is smaller than this value, the inline view is used.")
            },
            'diffEditor.useInlineViewWhenSpaceIsLimited': {
                type: 'boolean',
                default: diffEditor_1.diffEditorDefaultOptions.useInlineViewWhenSpaceIsLimited,
                description: nls.localize(165, "If enabled and the editor width is too small, the inline view is used.")
            },
            'diffEditor.renderMarginRevertIcon': {
                type: 'boolean',
                default: diffEditor_1.diffEditorDefaultOptions.renderMarginRevertIcon,
                description: nls.localize(166, "When enabled, the diff editor shows arrows in its glyph margin to revert changes.")
            },
            'diffEditor.renderGutterMenu': {
                type: 'boolean',
                default: diffEditor_1.diffEditorDefaultOptions.renderGutterMenu,
                description: nls.localize(167, "When enabled, the diff editor shows a special gutter for revert and stage actions.")
            },
            'diffEditor.ignoreTrimWhitespace': {
                type: 'boolean',
                default: diffEditor_1.diffEditorDefaultOptions.ignoreTrimWhitespace,
                description: nls.localize(168, "When enabled, the diff editor ignores changes in leading or trailing whitespace.")
            },
            'diffEditor.renderIndicators': {
                type: 'boolean',
                default: diffEditor_1.diffEditorDefaultOptions.renderIndicators,
                description: nls.localize(169, "Controls whether the diff editor shows +/- indicators for added/removed changes.")
            },
            'diffEditor.codeLens': {
                type: 'boolean',
                default: diffEditor_1.diffEditorDefaultOptions.diffCodeLens,
                description: nls.localize(170, "Controls whether the editor shows CodeLens.")
            },
            'diffEditor.wordWrap': {
                type: 'string',
                enum: ['off', 'on', 'inherit'],
                default: diffEditor_1.diffEditorDefaultOptions.diffWordWrap,
                markdownEnumDescriptions: [
                    nls.localize(171, "Lines will never wrap."),
                    nls.localize(172, "Lines will wrap at the viewport width."),
                    nls.localize(173, "Lines will wrap according to the {0} setting.", '`#editor.wordWrap#`'),
                ]
            },
            'diffEditor.diffAlgorithm': {
                type: 'string',
                enum: ['legacy', 'advanced'],
                default: diffEditor_1.diffEditorDefaultOptions.diffAlgorithm,
                markdownEnumDescriptions: [
                    nls.localize(174, "Uses the legacy diffing algorithm."),
                    nls.localize(175, "Uses the advanced diffing algorithm."),
                ],
                tags: ['experimental'],
            },
            'diffEditor.hideUnchangedRegions.enabled': {
                type: 'boolean',
                default: diffEditor_1.diffEditorDefaultOptions.hideUnchangedRegions.enabled,
                markdownDescription: nls.localize(176, "Controls whether the diff editor shows unchanged regions."),
            },
            'diffEditor.hideUnchangedRegions.revealLineCount': {
                type: 'integer',
                default: diffEditor_1.diffEditorDefaultOptions.hideUnchangedRegions.revealLineCount,
                markdownDescription: nls.localize(177, "Controls how many lines are used for unchanged regions."),
                minimum: 1,
            },
            'diffEditor.hideUnchangedRegions.minimumLineCount': {
                type: 'integer',
                default: diffEditor_1.diffEditorDefaultOptions.hideUnchangedRegions.minimumLineCount,
                markdownDescription: nls.localize(178, "Controls how many lines are used as a minimum for unchanged regions."),
                minimum: 1,
            },
            'diffEditor.hideUnchangedRegions.contextLineCount': {
                type: 'integer',
                default: diffEditor_1.diffEditorDefaultOptions.hideUnchangedRegions.contextLineCount,
                markdownDescription: nls.localize(179, "Controls how many lines are used as context when comparing unchanged regions."),
                minimum: 1,
            },
            'diffEditor.experimental.showMoves': {
                type: 'boolean',
                default: diffEditor_1.diffEditorDefaultOptions.experimental.showMoves,
                markdownDescription: nls.localize(180, "Controls whether the diff editor should show detected code moves.")
            },
            'diffEditor.experimental.showEmptyDecorations': {
                type: 'boolean',
                default: diffEditor_1.diffEditorDefaultOptions.experimental.showEmptyDecorations,
                description: nls.localize(181, "Controls whether the diff editor shows empty decorations to see where characters got inserted or deleted."),
            },
            'diffEditor.experimental.useTrueInlineView': {
                type: 'boolean',
                default: diffEditor_1.diffEditorDefaultOptions.experimental.useTrueInlineView,
                description: nls.localize(182, "If enabled and the editor uses the inline view, word changes are rendered inline."),
            },
        }
    };
    function isConfigurationPropertySchema(x) {
        return (typeof x.type !== 'undefined' || typeof x.anyOf !== 'undefined');
    }
    // Add properties from the Editor Option Registry
    for (const editorOption of editorOptions_1.editorOptionsRegistry) {
        const schema = editorOption.schema;
        if (typeof schema !== 'undefined') {
            if (isConfigurationPropertySchema(schema)) {
                // This is a single schema contribution
                editorConfiguration.properties[`editor.${editorOption.name}`] = schema;
            }
            else {
                for (const key in schema) {
                    if (Object.hasOwnProperty.call(schema, key)) {
                        editorConfiguration.properties[key] = schema[key];
                    }
                }
            }
        }
    }
    let cachedEditorConfigurationKeys = null;
    function getEditorConfigurationKeys() {
        if (cachedEditorConfigurationKeys === null) {
            cachedEditorConfigurationKeys = Object.create(null);
            Object.keys(editorConfiguration.properties).forEach((prop) => {
                cachedEditorConfigurationKeys[prop] = true;
            });
        }
        return cachedEditorConfigurationKeys;
    }
    function isEditorConfigurationKey(key) {
        const editorConfigurationKeys = getEditorConfigurationKeys();
        return (editorConfigurationKeys[`editor.${key}`] || false);
    }
    function isDiffEditorConfigurationKey(key) {
        const editorConfigurationKeys = getEditorConfigurationKeys();
        return (editorConfigurationKeys[`diffEditor.${key}`] || false);
    }
    const configurationRegistry = platform_1.Registry.as(configurationRegistry_1.Extensions.Configuration);
    configurationRegistry.registerConfiguration(editorConfiguration);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[70/*vs/editor/common/languages/modesRegistry*/], __M([1/*require*/,0/*exports*/,3/*vs/nls*/,6/*vs/base/common/event*/,38/*vs/platform/registry/common/platform*/,128/*vs/base/common/mime*/,109/*vs/platform/configuration/common/configurationRegistry*/]), function (require, exports, nls, event_1, platform_1, mime_1, configurationRegistry_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.PLAINTEXT_EXTENSION = exports.PLAINTEXT_LANGUAGE_ID = exports.ModesRegistry = exports.EditorModesRegistry = exports.Extensions = void 0;
    // Define extension point ids
    exports.Extensions = {
        ModesRegistry: 'editor.modesRegistry'
    };
    class EditorModesRegistry {
        constructor() {
            this._onDidChangeLanguages = new event_1.Emitter();
            this.onDidChangeLanguages = this._onDidChangeLanguages.event;
            this._languages = [];
        }
        registerLanguage(def) {
            this._languages.push(def);
            this._onDidChangeLanguages.fire(undefined);
            return {
                dispose: () => {
                    for (let i = 0, len = this._languages.length; i < len; i++) {
                        if (this._languages[i] === def) {
                            this._languages.splice(i, 1);
                            return;
                        }
                    }
                }
            };
        }
        getLanguages() {
            return this._languages;
        }
    }
    exports.EditorModesRegistry = EditorModesRegistry;
    exports.ModesRegistry = new EditorModesRegistry();
    platform_1.Registry.add(exports.Extensions.ModesRegistry, exports.ModesRegistry);
    exports.PLAINTEXT_LANGUAGE_ID = 'plaintext';
    exports.PLAINTEXT_EXTENSION = '.txt';
    exports.ModesRegistry.registerLanguage({
        id: exports.PLAINTEXT_LANGUAGE_ID,
        extensions: [exports.PLAINTEXT_EXTENSION],
        aliases: [nls.localize(696, "Plain Text"), 'text'],
        mimetypes: [mime_1.Mimes.text]
    });
    platform_1.Registry.as(configurationRegistry_1.Extensions.Configuration)
        .registerDefaultConfigurations([{
            overrides: {
                '[plaintext]': {
                    'editor.unicodeHighlight.ambiguousCharacters': false,
                    'editor.unicodeHighlight.invisibleCharacters': false
                }
            }
        }]);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[120/*vs/editor/browser/widget/markdownRenderer/browser/markdownRenderer*/], __M([1/*require*/,0/*exports*/,207/*vs/base/browser/markdownRenderer*/,103/*vs/base/browser/trustedTypes*/,8/*vs/base/common/errors*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,74/*vs/editor/browser/config/domFontInfo*/,43/*vs/editor/common/languages/language*/,70/*vs/editor/common/languages/modesRegistry*/,369/*vs/editor/common/languages/textToHtmlTokenizer*/,59/*vs/platform/opener/common/opener*/,501/*vs/css!vs/editor/browser/widget/markdownRenderer/browser/renderedMarkdown*/]), function (require, exports, markdownRenderer_1, trustedTypes_1, errors_1, event_1, lifecycle_1, domFontInfo_1, language_1, modesRegistry_1, textToHtmlTokenizer_1, opener_1) {
    "use strict";
    var MarkdownRenderer_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MarkdownRenderer = void 0;
    exports.openLinkFromMarkdown = openLinkFromMarkdown;
    /**
     * Markdown renderer that can render codeblocks with the editor mechanics. This
     * renderer should always be preferred.
     */
    let MarkdownRenderer = class MarkdownRenderer {
        static { MarkdownRenderer_1 = this; }
        static { this._ttpTokenizer = (0, trustedTypes_1.createTrustedTypesPolicy)('tokenizeToString', {
            createHTML(html) {
                return html;
            }
        }); }
        constructor(_options, _languageService, _openerService) {
            this._options = _options;
            this._languageService = _languageService;
            this._openerService = _openerService;
            this._onDidRenderAsync = new event_1.Emitter();
            this.onDidRenderAsync = this._onDidRenderAsync.event;
        }
        dispose() {
            this._onDidRenderAsync.dispose();
        }
        render(markdown, options, markedOptions) {
            if (!markdown) {
                const element = document.createElement('span');
                return { element, dispose: () => { } };
            }
            const disposables = new lifecycle_1.DisposableStore();
            const rendered = disposables.add((0, markdownRenderer_1.renderMarkdown)(markdown, { ...this._getRenderOptions(markdown, disposables), ...options }, markedOptions));
            rendered.element.classList.add('rendered-markdown');
            return {
                element: rendered.element,
                dispose: () => disposables.dispose()
            };
        }
        _getRenderOptions(markdown, disposables) {
            return {
                codeBlockRenderer: async (languageAlias, value) => {
                    // In markdown,
                    // it is possible that we stumble upon language aliases (e.g.js instead of javascript)
                    // it is possible no alias is given in which case we fall back to the current editor lang
                    let languageId;
                    if (languageAlias) {
                        languageId = this._languageService.getLanguageIdByLanguageName(languageAlias);
                    }
                    else if (this._options.editor) {
                        languageId = this._options.editor.getModel()?.getLanguageId();
                    }
                    if (!languageId) {
                        languageId = modesRegistry_1.PLAINTEXT_LANGUAGE_ID;
                    }
                    const html = await (0, textToHtmlTokenizer_1.tokenizeToString)(this._languageService, value, languageId);
                    const element = document.createElement('span');
                    element.innerHTML = (MarkdownRenderer_1._ttpTokenizer?.createHTML(html) ?? html);
                    // use "good" font
                    if (this._options.editor) {
                        const fontInfo = this._options.editor.getOption(50 /* EditorOption.fontInfo */);
                        (0, domFontInfo_1.applyFontInfo)(element, fontInfo);
                    }
                    else if (this._options.codeBlockFontFamily) {
                        element.style.fontFamily = this._options.codeBlockFontFamily;
                    }
                    if (this._options.codeBlockFontSize !== undefined) {
                        element.style.fontSize = this._options.codeBlockFontSize;
                    }
                    return element;
                },
                asyncRenderCallback: () => this._onDidRenderAsync.fire(),
                actionHandler: {
                    callback: (link) => openLinkFromMarkdown(this._openerService, link, markdown.isTrusted),
                    disposables: disposables
                }
            };
        }
    };
    exports.MarkdownRenderer = MarkdownRenderer;
    exports.MarkdownRenderer = MarkdownRenderer = MarkdownRenderer_1 = __decorate([
        __param(1, language_1.ILanguageService),
        __param(2, opener_1.IOpenerService)
    ], MarkdownRenderer);
    async function openLinkFromMarkdown(openerService, link, isTrusted) {
        try {
            return await openerService.open(link, {
                fromUserGesture: true,
                allowContributedOpeners: true,
                allowCommands: toAllowCommandsOption(isTrusted),
            });
        }
        catch (e) {
            (0, errors_1.onUnexpectedError)(e);
            return false;
        }
    }
    function toAllowCommandsOption(isTrusted) {
        if (isTrusted === true) {
            return true; // Allow all commands
        }
        if (isTrusted && Array.isArray(isTrusted.enabledCommands)) {
            return isTrusted.enabledCommands; // Allow subset of commands
        }
        return false; // Block commands
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[705/*vs/editor/browser/services/hoverService/hoverWidget*/], __M([1/*require*/,0/*exports*/,2/*vs/base/common/lifecycle*/,6/*vs/base/common/event*/,5/*vs/base/browser/dom*/,31/*vs/platform/keybinding/common/keybinding*/,28/*vs/platform/configuration/common/configuration*/,37/*vs/editor/common/config/editorOptions*/,174/*vs/base/browser/ui/hover/hoverWidget*/,85/*vs/base/browser/ui/widget*/,59/*vs/platform/opener/common/opener*/,7/*vs/platform/instantiation/common/instantiation*/,120/*vs/editor/browser/widget/markdownRenderer/browser/markdownRenderer*/,57/*vs/base/common/htmlContent*/,3/*vs/nls*/,16/*vs/base/common/platform*/,61/*vs/platform/accessibility/common/accessibility*/,46/*vs/base/browser/ui/aria/aria*/,480/*vs/css!vs/editor/browser/services/hoverService/hover*/]), function (require, exports, lifecycle_1, event_1, dom, keybinding_1, configuration_1, editorOptions_1, hoverWidget_1, widget_1, opener_1, instantiation_1, markdownRenderer_1, htmlContent_1, nls_1, platform_1, accessibility_1, aria_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.HoverWidget = void 0;
    const $ = dom.$;
    let HoverWidget = class HoverWidget extends widget_1.Widget {
        get _targetWindow() {
            return dom.getWindow(this._target.targetElements[0]);
        }
        get _targetDocumentElement() {
            return dom.getWindow(this._target.targetElements[0]).document.documentElement;
        }
        get isDisposed() { return this._isDisposed; }
        get isMouseIn() { return this._lockMouseTracker.isMouseIn; }
        get domNode() { return this._hover.containerDomNode; }
        get onDispose() { return this._onDispose.event; }
        get onRequestLayout() { return this._onRequestLayout.event; }
        get anchor() { return this._hoverPosition === 2 /* HoverPosition.BELOW */ ? 0 /* AnchorPosition.BELOW */ : 1 /* AnchorPosition.ABOVE */; }
        get x() { return this._x; }
        get y() { return this._y; }
        /**
         * Whether the hover is "locked" by holding the alt/option key. When locked, the hover will not
         * hide and can be hovered regardless of whether the `hideOnHover` hover option is set.
         */
        get isLocked() { return this._isLocked; }
        set isLocked(value) {
            if (this._isLocked === value) {
                return;
            }
            this._isLocked = value;
            this._hoverContainer.classList.toggle('locked', this._isLocked);
        }
        constructor(options, _keybindingService, _configurationService, _openerService, _instantiationService, _accessibilityService) {
            super();
            this._keybindingService = _keybindingService;
            this._configurationService = _configurationService;
            this._openerService = _openerService;
            this._instantiationService = _instantiationService;
            this._accessibilityService = _accessibilityService;
            this._messageListeners = new lifecycle_1.DisposableStore();
            this._isDisposed = false;
            this._forcePosition = false;
            this._x = 0;
            this._y = 0;
            this._isLocked = false;
            this._enableFocusTraps = false;
            this._addedFocusTrap = false;
            this._onDispose = this._register(new event_1.Emitter());
            this._onRequestLayout = this._register(new event_1.Emitter());
            this._linkHandler = options.linkHandler || (url => {
                return (0, markdownRenderer_1.openLinkFromMarkdown)(this._openerService, url, (0, htmlContent_1.isMarkdownString)(options.content) ? options.content.isTrusted : undefined);
            });
            this._target = 'targetElements' in options.target ? options.target : new ElementHoverTarget(options.target);
            this._hoverPointer = options.appearance?.showPointer ? $('div.workbench-hover-pointer') : undefined;
            this._hover = this._register(new hoverWidget_1.HoverWidget());
            this._hover.containerDomNode.classList.add('workbench-hover', 'fadeIn');
            if (options.appearance?.compact) {
                this._hover.containerDomNode.classList.add('workbench-hover', 'compact');
            }
            if (options.appearance?.skipFadeInAnimation) {
                this._hover.containerDomNode.classList.add('skip-fade-in');
            }
            if (options.additionalClasses) {
                this._hover.containerDomNode.classList.add(...options.additionalClasses);
            }
            if (options.position?.forcePosition) {
                this._forcePosition = true;
            }
            if (options.trapFocus) {
                this._enableFocusTraps = true;
            }
            this._hoverPosition = options.position?.hoverPosition ?? 3 /* HoverPosition.ABOVE */;
            // Don't allow mousedown out of the widget, otherwise preventDefault will call and text will
            // not be selected.
            this.onmousedown(this._hover.containerDomNode, e => e.stopPropagation());
            // Hide hover on escape
            this.onkeydown(this._hover.containerDomNode, e => {
                if (e.equals(9 /* KeyCode.Escape */)) {
                    this.dispose();
                }
            });
            // Hide when the window loses focus
            this._register(dom.addDisposableListener(this._targetWindow, 'blur', () => this.dispose()));
            const rowElement = $('div.hover-row.markdown-hover');
            const contentsElement = $('div.hover-contents');
            if (typeof options.content === 'string') {
                contentsElement.textContent = options.content;
                contentsElement.style.whiteSpace = 'pre-wrap';
            }
            else if (dom.isHTMLElement(options.content)) {
                contentsElement.appendChild(options.content);
                contentsElement.classList.add('html-hover-contents');
            }
            else {
                const markdown = options.content;
                const mdRenderer = this._instantiationService.createInstance(markdownRenderer_1.MarkdownRenderer, { codeBlockFontFamily: this._configurationService.getValue('editor').fontFamily || editorOptions_1.EDITOR_FONT_DEFAULTS.fontFamily });
                const { element } = mdRenderer.render(markdown, {
                    actionHandler: {
                        callback: (content) => this._linkHandler(content),
                        disposables: this._messageListeners
                    },
                    asyncRenderCallback: () => {
                        contentsElement.classList.add('code-hover-contents');
                        this.layout();
                        // This changes the dimensions of the hover so trigger a layout
                        this._onRequestLayout.fire();
                    }
                });
                contentsElement.appendChild(element);
            }
            rowElement.appendChild(contentsElement);
            this._hover.contentsDomNode.appendChild(rowElement);
            if (options.actions && options.actions.length > 0) {
                const statusBarElement = $('div.hover-row.status-bar');
                const actionsElement = $('div.actions');
                options.actions.forEach(action => {
                    const keybinding = this._keybindingService.lookupKeybinding(action.commandId);
                    const keybindingLabel = keybinding ? keybinding.getLabel() : null;
                    hoverWidget_1.HoverAction.render(actionsElement, {
                        label: action.label,
                        commandId: action.commandId,
                        run: e => {
                            action.run(e);
                            this.dispose();
                        },
                        iconClass: action.iconClass
                    }, keybindingLabel);
                });
                statusBarElement.appendChild(actionsElement);
                this._hover.containerDomNode.appendChild(statusBarElement);
            }
            this._hoverContainer = $('div.workbench-hover-container');
            if (this._hoverPointer) {
                this._hoverContainer.appendChild(this._hoverPointer);
            }
            this._hoverContainer.appendChild(this._hover.containerDomNode);
            // Determine whether to hide on hover
            let hideOnHover;
            if (options.actions && options.actions.length > 0) {
                // If there are actions, require hover so they can be accessed
                hideOnHover = false;
            }
            else {
                if (options.persistence?.hideOnHover === undefined) {
                    // When unset, will default to true when it's a string or when it's markdown that
                    // appears to have a link using a naive check for '](' and '</a>'
                    hideOnHover = typeof options.content === 'string' ||
                        (0, htmlContent_1.isMarkdownString)(options.content) && !options.content.value.includes('](') && !options.content.value.includes('</a>');
                }
                else {
                    // It's set explicitly
                    hideOnHover = options.persistence.hideOnHover;
                }
            }
            // Show the hover hint if needed
            if (options.appearance?.showHoverHint) {
                const statusBarElement = $('div.hover-row.status-bar');
                const infoElement = $('div.info');
                infoElement.textContent = (0, nls_1.localize)(68, 'Hold {0} key to mouse over', platform_1.isMacintosh ? 'Option' : 'Alt');
                statusBarElement.appendChild(infoElement);
                this._hover.containerDomNode.appendChild(statusBarElement);
            }
            const mouseTrackerTargets = [...this._target.targetElements];
            if (!hideOnHover) {
                mouseTrackerTargets.push(this._hoverContainer);
            }
            const mouseTracker = this._register(new CompositeMouseTracker(mouseTrackerTargets));
            this._register(mouseTracker.onMouseOut(() => {
                if (!this._isLocked) {
                    this.dispose();
                }
            }));
            // Setup another mouse tracker when hideOnHover is set in order to track the hover as well
            // when it is locked. This ensures the hover will hide on mouseout after alt has been
            // released to unlock the element.
            if (hideOnHover) {
                const mouseTracker2Targets = [...this._target.targetElements, this._hoverContainer];
                this._lockMouseTracker = this._register(new CompositeMouseTracker(mouseTracker2Targets));
                this._register(this._lockMouseTracker.onMouseOut(() => {
                    if (!this._isLocked) {
                        this.dispose();
                    }
                }));
            }
            else {
                this._lockMouseTracker = mouseTracker;
            }
        }
        addFocusTrap() {
            if (!this._enableFocusTraps || this._addedFocusTrap) {
                return;
            }
            this._addedFocusTrap = true;
            // Add a hover tab loop if the hover has at least one element with a valid tabIndex
            const firstContainerFocusElement = this._hover.containerDomNode;
            const lastContainerFocusElement = this.findLastFocusableChild(this._hover.containerDomNode);
            if (lastContainerFocusElement) {
                const beforeContainerFocusElement = dom.prepend(this._hoverContainer, $('div'));
                const afterContainerFocusElement = dom.append(this._hoverContainer, $('div'));
                beforeContainerFocusElement.tabIndex = 0;
                afterContainerFocusElement.tabIndex = 0;
                this._register(dom.addDisposableListener(afterContainerFocusElement, 'focus', (e) => {
                    firstContainerFocusElement.focus();
                    e.preventDefault();
                }));
                this._register(dom.addDisposableListener(beforeContainerFocusElement, 'focus', (e) => {
                    lastContainerFocusElement.focus();
                    e.preventDefault();
                }));
            }
        }
        findLastFocusableChild(root) {
            if (root.hasChildNodes()) {
                for (let i = 0; i < root.childNodes.length; i++) {
                    const node = root.childNodes.item(root.childNodes.length - i - 1);
                    if (node.nodeType === node.ELEMENT_NODE) {
                        const parsedNode = node;
                        if (typeof parsedNode.tabIndex === 'number' && parsedNode.tabIndex >= 0) {
                            return parsedNode;
                        }
                    }
                    const recursivelyFoundElement = this.findLastFocusableChild(node);
                    if (recursivelyFoundElement) {
                        return recursivelyFoundElement;
                    }
                }
            }
            return undefined;
        }
        render(container) {
            container.appendChild(this._hoverContainer);
            const hoverFocused = this._hoverContainer.contains(this._hoverContainer.ownerDocument.activeElement);
            const accessibleViewHint = hoverFocused && (0, hoverWidget_1.getHoverAccessibleViewHint)(this._configurationService.getValue('accessibility.verbosity.hover') === true && this._accessibilityService.isScreenReaderOptimized(), this._keybindingService.lookupKeybinding('editor.action.accessibleView')?.getAriaLabel());
            if (accessibleViewHint) {
                (0, aria_1.status)(accessibleViewHint);
            }
            this.layout();
            this.addFocusTrap();
        }
        layout() {
            this._hover.containerDomNode.classList.remove('right-aligned');
            this._hover.contentsDomNode.style.maxHeight = '';
            const getZoomAccountedBoundingClientRect = (e) => {
                const zoom = dom.getDomNodeZoomLevel(e);
                const boundingRect = e.getBoundingClientRect();
                return {
                    top: boundingRect.top * zoom,
                    bottom: boundingRect.bottom * zoom,
                    right: boundingRect.right * zoom,
                    left: boundingRect.left * zoom,
                };
            };
            const targetBounds = this._target.targetElements.map(e => getZoomAccountedBoundingClientRect(e));
            const { top, right, bottom, left } = targetBounds[0];
            const width = right - left;
            const height = bottom - top;
            const targetRect = {
                top, right, bottom, left, width, height,
                center: {
                    x: left + (width / 2),
                    y: top + (height / 2)
                }
            };
            // These calls adjust the position depending on spacing.
            this.adjustHorizontalHoverPosition(targetRect);
            this.adjustVerticalHoverPosition(targetRect);
            // This call limits the maximum height of the hover.
            this.adjustHoverMaxHeight(targetRect);
            // Offset the hover position if there is a pointer so it aligns with the target element
            this._hoverContainer.style.padding = '';
            this._hoverContainer.style.margin = '';
            if (this._hoverPointer) {
                switch (this._hoverPosition) {
                    case 1 /* HoverPosition.RIGHT */:
                        targetRect.left += 3 /* Constants.PointerSize */;
                        targetRect.right += 3 /* Constants.PointerSize */;
                        this._hoverContainer.style.paddingLeft = `${3 /* Constants.PointerSize */}px`;
                        this._hoverContainer.style.marginLeft = `${-3 /* Constants.PointerSize */}px`;
                        break;
                    case 0 /* HoverPosition.LEFT */:
                        targetRect.left -= 3 /* Constants.PointerSize */;
                        targetRect.right -= 3 /* Constants.PointerSize */;
                        this._hoverContainer.style.paddingRight = `${3 /* Constants.PointerSize */}px`;
                        this._hoverContainer.style.marginRight = `${-3 /* Constants.PointerSize */}px`;
                        break;
                    case 2 /* HoverPosition.BELOW */:
                        targetRect.top += 3 /* Constants.PointerSize */;
                        targetRect.bottom += 3 /* Constants.PointerSize */;
                        this._hoverContainer.style.paddingTop = `${3 /* Constants.PointerSize */}px`;
                        this._hoverContainer.style.marginTop = `${-3 /* Constants.PointerSize */}px`;
                        break;
                    case 3 /* HoverPosition.ABOVE */:
                        targetRect.top -= 3 /* Constants.PointerSize */;
                        targetRect.bottom -= 3 /* Constants.PointerSize */;
                        this._hoverContainer.style.paddingBottom = `${3 /* Constants.PointerSize */}px`;
                        this._hoverContainer.style.marginBottom = `${-3 /* Constants.PointerSize */}px`;
                        break;
                }
                targetRect.center.x = targetRect.left + (width / 2);
                targetRect.center.y = targetRect.top + (height / 2);
            }
            this.computeXCordinate(targetRect);
            this.computeYCordinate(targetRect);
            if (this._hoverPointer) {
                // reset
                this._hoverPointer.classList.remove('top');
                this._hoverPointer.classList.remove('left');
                this._hoverPointer.classList.remove('right');
                this._hoverPointer.classList.remove('bottom');
                this.setHoverPointerPosition(targetRect);
            }
            this._hover.onContentsChanged();
        }
        computeXCordinate(target) {
            const hoverWidth = this._hover.containerDomNode.clientWidth + 2 /* Constants.HoverBorderWidth */;
            if (this._target.x !== undefined) {
                this._x = this._target.x;
            }
            else if (this._hoverPosition === 1 /* HoverPosition.RIGHT */) {
                this._x = target.right;
            }
            else if (this._hoverPosition === 0 /* HoverPosition.LEFT */) {
                this._x = target.left - hoverWidth;
            }
            else {
                if (this._hoverPointer) {
                    this._x = target.center.x - (this._hover.containerDomNode.clientWidth / 2);
                }
                else {
                    this._x = target.left;
                }
                // Hover is going beyond window towards right end
                if (this._x + hoverWidth >= this._targetDocumentElement.clientWidth) {
                    this._hover.containerDomNode.classList.add('right-aligned');
                    this._x = Math.max(this._targetDocumentElement.clientWidth - hoverWidth - 2 /* Constants.HoverWindowEdgeMargin */, this._targetDocumentElement.clientLeft);
                }
            }
            // Hover is going beyond window towards left end
            if (this._x < this._targetDocumentElement.clientLeft) {
                this._x = target.left + 2 /* Constants.HoverWindowEdgeMargin */;
            }
        }
        computeYCordinate(target) {
            if (this._target.y !== undefined) {
                this._y = this._target.y;
            }
            else if (this._hoverPosition === 3 /* HoverPosition.ABOVE */) {
                this._y = target.top;
            }
            else if (this._hoverPosition === 2 /* HoverPosition.BELOW */) {
                this._y = target.bottom - 2;
            }
            else {
                if (this._hoverPointer) {
                    this._y = target.center.y + (this._hover.containerDomNode.clientHeight / 2);
                }
                else {
                    this._y = target.bottom;
                }
            }
            // Hover on bottom is going beyond window
            if (this._y > this._targetWindow.innerHeight) {
                this._y = target.bottom;
            }
        }
        adjustHorizontalHoverPosition(target) {
            // Do not adjust horizontal hover position if x cordiante is provided
            if (this._target.x !== undefined) {
                return;
            }
            const hoverPointerOffset = (this._hoverPointer ? 3 /* Constants.PointerSize */ : 0);
            // When force position is enabled, restrict max width
            if (this._forcePosition) {
                const padding = hoverPointerOffset + 2 /* Constants.HoverBorderWidth */;
                if (this._hoverPosition === 1 /* HoverPosition.RIGHT */) {
                    this._hover.containerDomNode.style.maxWidth = `${this._targetDocumentElement.clientWidth - target.right - padding}px`;
                }
                else if (this._hoverPosition === 0 /* HoverPosition.LEFT */) {
                    this._hover.containerDomNode.style.maxWidth = `${target.left - padding}px`;
                }
                return;
            }
            // Position hover on right to target
            if (this._hoverPosition === 1 /* HoverPosition.RIGHT */) {
                const roomOnRight = this._targetDocumentElement.clientWidth - target.right;
                // Hover on the right is going beyond window.
                if (roomOnRight < this._hover.containerDomNode.clientWidth + hoverPointerOffset) {
                    const roomOnLeft = target.left;
                    // There's enough room on the left, flip the hover position
                    if (roomOnLeft >= this._hover.containerDomNode.clientWidth + hoverPointerOffset) {
                        this._hoverPosition = 0 /* HoverPosition.LEFT */;
                    }
                    // Hover on the left would go beyond window too
                    else {
                        this._hoverPosition = 2 /* HoverPosition.BELOW */;
                    }
                }
            }
            // Position hover on left to target
            else if (this._hoverPosition === 0 /* HoverPosition.LEFT */) {
                const roomOnLeft = target.left;
                // Hover on the left is going beyond window.
                if (roomOnLeft < this._hover.containerDomNode.clientWidth + hoverPointerOffset) {
                    const roomOnRight = this._targetDocumentElement.clientWidth - target.right;
                    // There's enough room on the right, flip the hover position
                    if (roomOnRight >= this._hover.containerDomNode.clientWidth + hoverPointerOffset) {
                        this._hoverPosition = 1 /* HoverPosition.RIGHT */;
                    }
                    // Hover on the right would go beyond window too
                    else {
                        this._hoverPosition = 2 /* HoverPosition.BELOW */;
                    }
                }
                // Hover on the left is going beyond window.
                if (target.left - this._hover.containerDomNode.clientWidth - hoverPointerOffset <= this._targetDocumentElement.clientLeft) {
                    this._hoverPosition = 1 /* HoverPosition.RIGHT */;
                }
            }
        }
        adjustVerticalHoverPosition(target) {
            // Do not adjust vertical hover position if the y coordinate is provided
            // or the position is forced
            if (this._target.y !== undefined || this._forcePosition) {
                return;
            }
            const hoverPointerOffset = (this._hoverPointer ? 3 /* Constants.PointerSize */ : 0);
            // Position hover on top of the target
            if (this._hoverPosition === 3 /* HoverPosition.ABOVE */) {
                // Hover on top is going beyond window
                if (target.top - this._hover.containerDomNode.clientHeight - hoverPointerOffset < 0) {
                    this._hoverPosition = 2 /* HoverPosition.BELOW */;
                }
            }
            // Position hover below the target
            else if (this._hoverPosition === 2 /* HoverPosition.BELOW */) {
                // Hover on bottom is going beyond window
                if (target.bottom + this._hover.containerDomNode.clientHeight + hoverPointerOffset > this._targetWindow.innerHeight) {
                    this._hoverPosition = 3 /* HoverPosition.ABOVE */;
                }
            }
        }
        adjustHoverMaxHeight(target) {
            let maxHeight = this._targetWindow.innerHeight / 2;
            // When force position is enabled, restrict max height
            if (this._forcePosition) {
                const padding = (this._hoverPointer ? 3 /* Constants.PointerSize */ : 0) + 2 /* Constants.HoverBorderWidth */;
                if (this._hoverPosition === 3 /* HoverPosition.ABOVE */) {
                    maxHeight = Math.min(maxHeight, target.top - padding);
                }
                else if (this._hoverPosition === 2 /* HoverPosition.BELOW */) {
                    maxHeight = Math.min(maxHeight, this._targetWindow.innerHeight - target.bottom - padding);
                }
            }
            this._hover.containerDomNode.style.maxHeight = `${maxHeight}px`;
            if (this._hover.contentsDomNode.clientHeight < this._hover.contentsDomNode.scrollHeight) {
                // Add padding for a vertical scrollbar
                const extraRightPadding = `${this._hover.scrollbar.options.verticalScrollbarSize}px`;
                if (this._hover.contentsDomNode.style.paddingRight !== extraRightPadding) {
                    this._hover.contentsDomNode.style.paddingRight = extraRightPadding;
                }
            }
        }
        setHoverPointerPosition(target) {
            if (!this._hoverPointer) {
                return;
            }
            switch (this._hoverPosition) {
                case 0 /* HoverPosition.LEFT */:
                case 1 /* HoverPosition.RIGHT */: {
                    this._hoverPointer.classList.add(this._hoverPosition === 0 /* HoverPosition.LEFT */ ? 'right' : 'left');
                    const hoverHeight = this._hover.containerDomNode.clientHeight;
                    // If hover is taller than target, then show the pointer at the center of target
                    if (hoverHeight > target.height) {
                        this._hoverPointer.style.top = `${target.center.y - (this._y - hoverHeight) - 3 /* Constants.PointerSize */}px`;
                    }
                    // Otherwise show the pointer at the center of hover
                    else {
                        this._hoverPointer.style.top = `${Math.round((hoverHeight / 2)) - 3 /* Constants.PointerSize */}px`;
                    }
                    break;
                }
                case 3 /* HoverPosition.ABOVE */:
                case 2 /* HoverPosition.BELOW */: {
                    this._hoverPointer.classList.add(this._hoverPosition === 3 /* HoverPosition.ABOVE */ ? 'bottom' : 'top');
                    const hoverWidth = this._hover.containerDomNode.clientWidth;
                    // Position pointer at the center of the hover
                    let pointerLeftPosition = Math.round((hoverWidth / 2)) - 3 /* Constants.PointerSize */;
                    // If pointer goes beyond target then position it at the center of the target
                    const pointerX = this._x + pointerLeftPosition;
                    if (pointerX < target.left || pointerX > target.right) {
                        pointerLeftPosition = target.center.x - this._x - 3 /* Constants.PointerSize */;
                    }
                    this._hoverPointer.style.left = `${pointerLeftPosition}px`;
                    break;
                }
            }
        }
        focus() {
            this._hover.containerDomNode.focus();
        }
        dispose() {
            if (!this._isDisposed) {
                this._onDispose.fire();
                this._hoverContainer.remove();
                this._messageListeners.dispose();
                this._target.dispose();
                super.dispose();
            }
            this._isDisposed = true;
        }
    };
    exports.HoverWidget = HoverWidget;
    exports.HoverWidget = HoverWidget = __decorate([
        __param(1, keybinding_1.IKeybindingService),
        __param(2, configuration_1.IConfigurationService),
        __param(3, opener_1.IOpenerService),
        __param(4, instantiation_1.IInstantiationService),
        __param(5, accessibility_1.IAccessibilityService)
    ], HoverWidget);
    class CompositeMouseTracker extends widget_1.Widget {
        get onMouseOut() { return this._onMouseOut.event; }
        get isMouseIn() { return this._isMouseIn; }
        constructor(_elements) {
            super();
            this._elements = _elements;
            this._isMouseIn = true;
            this._onMouseOut = this._register(new event_1.Emitter());
            this._elements.forEach(n => this.onmouseover(n, () => this._onTargetMouseOver(n)));
            this._elements.forEach(n => this.onmouseleave(n, () => this._onTargetMouseLeave(n)));
        }
        _onTargetMouseOver(target) {
            this._isMouseIn = true;
            this._clearEvaluateMouseStateTimeout(target);
        }
        _onTargetMouseLeave(target) {
            this._isMouseIn = false;
            this._evaluateMouseState(target);
        }
        _evaluateMouseState(target) {
            this._clearEvaluateMouseStateTimeout(target);
            // Evaluate whether the mouse is still outside asynchronously such that other mouse targets
            // have the opportunity to first their mouse in event.
            this._mouseTimeout = dom.getWindow(target).setTimeout(() => this._fireIfMouseOutside(), 0);
        }
        _clearEvaluateMouseStateTimeout(target) {
            if (this._mouseTimeout) {
                dom.getWindow(target).clearTimeout(this._mouseTimeout);
                this._mouseTimeout = undefined;
            }
        }
        _fireIfMouseOutside() {
            if (!this._isMouseIn) {
                this._onMouseOut.fire();
            }
        }
    }
    class ElementHoverTarget {
        constructor(_element) {
            this._element = _element;
            this.targetElements = [this._element];
        }
        dispose() {
        }
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[36/*vs/editor/common/languages/languageConfigurationRegistry*/], __M([1/*require*/,0/*exports*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,11/*vs/base/common/strings*/,147/*vs/editor/common/core/wordHelper*/,131/*vs/editor/common/languages/languageConfiguration*/,568/*vs/editor/common/languages/supports/characterPair*/,659/*vs/editor/common/languages/supports/electricCharacter*/,569/*vs/editor/common/languages/supports/indentRules*/,571/*vs/editor/common/languages/supports/onEnter*/,208/*vs/editor/common/languages/supports/richEditBrackets*/,7/*vs/platform/instantiation/common/instantiation*/,28/*vs/platform/configuration/common/configuration*/,43/*vs/editor/common/languages/language*/,49/*vs/platform/instantiation/common/extensions*/,70/*vs/editor/common/languages/modesRegistry*/,660/*vs/editor/common/languages/supports/languageBracketsConfiguration*/]), function (require, exports, event_1, lifecycle_1, strings, wordHelper_1, languageConfiguration_1, characterPair_1, electricCharacter_1, indentRules_1, onEnter_1, richEditBrackets_1, instantiation_1, configuration_1, language_1, extensions_1, modesRegistry_1, languageBracketsConfiguration_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ResolvedLanguageConfiguration = exports.LanguageConfigurationRegistry = exports.LanguageConfigurationChangeEvent = exports.LanguageConfigurationService = exports.ILanguageConfigurationService = exports.LanguageConfigurationServiceChangeEvent = void 0;
    exports.getIndentationAtPosition = getIndentationAtPosition;
    class LanguageConfigurationServiceChangeEvent {
        constructor(languageId) {
            this.languageId = languageId;
        }
        affects(languageId) {
            return !this.languageId ? true : this.languageId === languageId;
        }
    }
    exports.LanguageConfigurationServiceChangeEvent = LanguageConfigurationServiceChangeEvent;
    exports.ILanguageConfigurationService = (0, instantiation_1.createDecorator)('languageConfigurationService');
    let LanguageConfigurationService = class LanguageConfigurationService extends lifecycle_1.Disposable {
        constructor(configurationService, languageService) {
            super();
            this.configurationService = configurationService;
            this.languageService = languageService;
            this._registry = this._register(new LanguageConfigurationRegistry());
            this.onDidChangeEmitter = this._register(new event_1.Emitter());
            this.onDidChange = this.onDidChangeEmitter.event;
            this.configurations = new Map();
            const languageConfigKeys = new Set(Object.values(customizedLanguageConfigKeys));
            this._register(this.configurationService.onDidChangeConfiguration((e) => {
                const globalConfigChanged = e.change.keys.some((k) => languageConfigKeys.has(k));
                const localConfigChanged = e.change.overrides
                    .filter(([overrideLangName, keys]) => keys.some((k) => languageConfigKeys.has(k)))
                    .map(([overrideLangName]) => overrideLangName);
                if (globalConfigChanged) {
                    this.configurations.clear();
                    this.onDidChangeEmitter.fire(new LanguageConfigurationServiceChangeEvent(undefined));
                }
                else {
                    for (const languageId of localConfigChanged) {
                        if (this.languageService.isRegisteredLanguageId(languageId)) {
                            this.configurations.delete(languageId);
                            this.onDidChangeEmitter.fire(new LanguageConfigurationServiceChangeEvent(languageId));
                        }
                    }
                }
            }));
            this._register(this._registry.onDidChange((e) => {
                this.configurations.delete(e.languageId);
                this.onDidChangeEmitter.fire(new LanguageConfigurationServiceChangeEvent(e.languageId));
            }));
        }
        register(languageId, configuration, priority) {
            return this._registry.register(languageId, configuration, priority);
        }
        getLanguageConfiguration(languageId) {
            let result = this.configurations.get(languageId);
            if (!result) {
                result = computeConfig(languageId, this._registry, this.configurationService, this.languageService);
                this.configurations.set(languageId, result);
            }
            return result;
        }
    };
    exports.LanguageConfigurationService = LanguageConfigurationService;
    exports.LanguageConfigurationService = LanguageConfigurationService = __decorate([
        __param(0, configuration_1.IConfigurationService),
        __param(1, language_1.ILanguageService)
    ], LanguageConfigurationService);
    function computeConfig(languageId, registry, configurationService, languageService) {
        let languageConfig = registry.getLanguageConfiguration(languageId);
        if (!languageConfig) {
            if (!languageService.isRegisteredLanguageId(languageId)) {
                // this happens for the null language, which can be returned by monarch.
                // Instead of throwing an error, we just return a default config.
                return new ResolvedLanguageConfiguration(languageId, {});
            }
            languageConfig = new ResolvedLanguageConfiguration(languageId, {});
        }
        const customizedConfig = getCustomizedLanguageConfig(languageConfig.languageId, configurationService);
        const data = combineLanguageConfigurations([languageConfig.underlyingConfig, customizedConfig]);
        const config = new ResolvedLanguageConfiguration(languageConfig.languageId, data);
        return config;
    }
    const customizedLanguageConfigKeys = {
        brackets: 'editor.language.brackets',
        colorizedBracketPairs: 'editor.language.colorizedBracketPairs'
    };
    function getCustomizedLanguageConfig(languageId, configurationService) {
        const brackets = configurationService.getValue(customizedLanguageConfigKeys.brackets, {
            overrideIdentifier: languageId,
        });
        const colorizedBracketPairs = configurationService.getValue(customizedLanguageConfigKeys.colorizedBracketPairs, {
            overrideIdentifier: languageId,
        });
        return {
            brackets: validateBracketPairs(brackets),
            colorizedBracketPairs: validateBracketPairs(colorizedBracketPairs),
        };
    }
    function validateBracketPairs(data) {
        if (!Array.isArray(data)) {
            return undefined;
        }
        return data.map(pair => {
            if (!Array.isArray(pair) || pair.length !== 2) {
                return undefined;
            }
            return [pair[0], pair[1]];
        }).filter((p) => !!p);
    }
    function getIndentationAtPosition(model, lineNumber, column) {
        const lineText = model.getLineContent(lineNumber);
        let indentation = strings.getLeadingWhitespace(lineText);
        if (indentation.length > column - 1) {
            indentation = indentation.substring(0, column - 1);
        }
        return indentation;
    }
    class ComposedLanguageConfiguration {
        constructor(languageId) {
            this.languageId = languageId;
            this._resolved = null;
            this._entries = [];
            this._order = 0;
            this._resolved = null;
        }
        register(configuration, priority) {
            const entry = new LanguageConfigurationContribution(configuration, priority, ++this._order);
            this._entries.push(entry);
            this._resolved = null;
            return (0, lifecycle_1.toDisposable)(() => {
                for (let i = 0; i < this._entries.length; i++) {
                    if (this._entries[i] === entry) {
                        this._entries.splice(i, 1);
                        this._resolved = null;
                        break;
                    }
                }
            });
        }
        getResolvedConfiguration() {
            if (!this._resolved) {
                const config = this._resolve();
                if (config) {
                    this._resolved = new ResolvedLanguageConfiguration(this.languageId, config);
                }
            }
            return this._resolved;
        }
        _resolve() {
            if (this._entries.length === 0) {
                return null;
            }
            this._entries.sort(LanguageConfigurationContribution.cmp);
            return combineLanguageConfigurations(this._entries.map(e => e.configuration));
        }
    }
    function combineLanguageConfigurations(configs) {
        let result = {
            comments: undefined,
            brackets: undefined,
            wordPattern: undefined,
            indentationRules: undefined,
            onEnterRules: undefined,
            autoClosingPairs: undefined,
            surroundingPairs: undefined,
            autoCloseBefore: undefined,
            folding: undefined,
            colorizedBracketPairs: undefined,
            __electricCharacterSupport: undefined,
        };
        for (const entry of configs) {
            result = {
                comments: entry.comments || result.comments,
                brackets: entry.brackets || result.brackets,
                wordPattern: entry.wordPattern || result.wordPattern,
                indentationRules: entry.indentationRules || result.indentationRules,
                onEnterRules: entry.onEnterRules || result.onEnterRules,
                autoClosingPairs: entry.autoClosingPairs || result.autoClosingPairs,
                surroundingPairs: entry.surroundingPairs || result.surroundingPairs,
                autoCloseBefore: entry.autoCloseBefore || result.autoCloseBefore,
                folding: entry.folding || result.folding,
                colorizedBracketPairs: entry.colorizedBracketPairs || result.colorizedBracketPairs,
                __electricCharacterSupport: entry.__electricCharacterSupport || result.__electricCharacterSupport,
            };
        }
        return result;
    }
    class LanguageConfigurationContribution {
        constructor(configuration, priority, order) {
            this.configuration = configuration;
            this.priority = priority;
            this.order = order;
        }
        static cmp(a, b) {
            if (a.priority === b.priority) {
                // higher order last
                return a.order - b.order;
            }
            // higher priority last
            return a.priority - b.priority;
        }
    }
    class LanguageConfigurationChangeEvent {
        constructor(languageId) {
            this.languageId = languageId;
        }
    }
    exports.LanguageConfigurationChangeEvent = LanguageConfigurationChangeEvent;
    class LanguageConfigurationRegistry extends lifecycle_1.Disposable {
        constructor() {
            super();
            this._entries = new Map();
            this._onDidChange = this._register(new event_1.Emitter());
            this.onDidChange = this._onDidChange.event;
            this._register(this.register(modesRegistry_1.PLAINTEXT_LANGUAGE_ID, {
                brackets: [
                    ['(', ')'],
                    ['[', ']'],
                    ['{', '}'],
                ],
                surroundingPairs: [
                    { open: '{', close: '}' },
                    { open: '[', close: ']' },
                    { open: '(', close: ')' },
                    { open: '<', close: '>' },
                    { open: '\"', close: '\"' },
                    { open: '\'', close: '\'' },
                    { open: '`', close: '`' },
                ],
                colorizedBracketPairs: [],
                folding: {
                    offSide: true
                }
            }, 0));
        }
        /**
         * @param priority Use a higher number for higher priority
         */
        register(languageId, configuration, priority = 0) {
            let entries = this._entries.get(languageId);
            if (!entries) {
                entries = new ComposedLanguageConfiguration(languageId);
                this._entries.set(languageId, entries);
            }
            const disposable = entries.register(configuration, priority);
            this._onDidChange.fire(new LanguageConfigurationChangeEvent(languageId));
            return (0, lifecycle_1.toDisposable)(() => {
                disposable.dispose();
                this._onDidChange.fire(new LanguageConfigurationChangeEvent(languageId));
            });
        }
        getLanguageConfiguration(languageId) {
            const entries = this._entries.get(languageId);
            return entries?.getResolvedConfiguration() || null;
        }
    }
    exports.LanguageConfigurationRegistry = LanguageConfigurationRegistry;
    /**
     * Immutable.
    */
    class ResolvedLanguageConfiguration {
        constructor(languageId, underlyingConfig) {
            this.languageId = languageId;
            this.underlyingConfig = underlyingConfig;
            this._brackets = null;
            this._electricCharacter = null;
            this._onEnterSupport =
                this.underlyingConfig.brackets ||
                    this.underlyingConfig.indentationRules ||
                    this.underlyingConfig.onEnterRules
                    ? new onEnter_1.OnEnterSupport(this.underlyingConfig)
                    : null;
            this.comments = ResolvedLanguageConfiguration._handleComments(this.underlyingConfig);
            this.characterPair = new characterPair_1.CharacterPairSupport(this.underlyingConfig);
            this.wordDefinition = this.underlyingConfig.wordPattern || wordHelper_1.DEFAULT_WORD_REGEXP;
            this.indentationRules = this.underlyingConfig.indentationRules;
            if (this.underlyingConfig.indentationRules) {
                this.indentRulesSupport = new indentRules_1.IndentRulesSupport(this.underlyingConfig.indentationRules);
            }
            else {
                this.indentRulesSupport = null;
            }
            this.foldingRules = this.underlyingConfig.folding || {};
            this.bracketsNew = new languageBracketsConfiguration_1.LanguageBracketsConfiguration(languageId, this.underlyingConfig);
        }
        getWordDefinition() {
            return (0, wordHelper_1.ensureValidWordDefinition)(this.wordDefinition);
        }
        get brackets() {
            if (!this._brackets && this.underlyingConfig.brackets) {
                this._brackets = new richEditBrackets_1.RichEditBrackets(this.languageId, this.underlyingConfig.brackets);
            }
            return this._brackets;
        }
        get electricCharacter() {
            if (!this._electricCharacter) {
                this._electricCharacter = new electricCharacter_1.BracketElectricCharacterSupport(this.brackets);
            }
            return this._electricCharacter;
        }
        onEnter(autoIndent, previousLineText, beforeEnterText, afterEnterText) {
            if (!this._onEnterSupport) {
                return null;
            }
            return this._onEnterSupport.onEnter(autoIndent, previousLineText, beforeEnterText, afterEnterText);
        }
        getAutoClosingPairs() {
            return new languageConfiguration_1.AutoClosingPairs(this.characterPair.getAutoClosingPairs());
        }
        getAutoCloseBeforeSet(forQuotes) {
            return this.characterPair.getAutoCloseBeforeSet(forQuotes);
        }
        getSurroundingPairs() {
            return this.characterPair.getSurroundingPairs();
        }
        static _handleComments(conf) {
            const commentRule = conf.comments;
            if (!commentRule) {
                return null;
            }
            // comment configuration
            const comments = {};
            if (commentRule.lineComment) {
                comments.lineCommentToken = commentRule.lineComment;
            }
            if (commentRule.blockComment) {
                const [blockStart, blockEnd] = commentRule.blockComment;
                comments.blockCommentStartToken = blockStart;
                comments.blockCommentEndToken = blockEnd;
            }
            return comments;
        }
    }
    exports.ResolvedLanguageConfiguration = ResolvedLanguageConfiguration;
    (0, extensions_1.registerSingleton)(exports.ILanguageConfigurationService, LanguageConfigurationService, 1 /* InstantiationType.Delayed */);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[401/*vs/editor/browser/services/editorWorkerService*/], __M([1/*require*/,0/*exports*/,14/*vs/base/common/async*/,2/*vs/base/common/lifecycle*/,361/*vs/base/common/worker/simpleWorker*/,646/*vs/base/browser/defaultWorkerFactory*/,4/*vs/editor/common/core/range*/,36/*vs/editor/common/languages/languageConfigurationRegistry*/,666/*vs/editor/common/services/editorSimpleWorker*/,51/*vs/editor/common/services/model*/,211/*vs/editor/common/services/textResourceConfiguration*/,13/*vs/base/common/arrays*/,62/*vs/platform/log/common/log*/,54/*vs/base/common/stopwatch*/,8/*vs/base/common/errors*/,17/*vs/editor/common/services/languageFeatures*/,232/*vs/editor/common/diff/linesDiffComputer*/,105/*vs/editor/common/diff/rangeMapping*/,55/*vs/editor/common/core/lineRange*/,52/*vs/base/browser/window*/,5/*vs/base/browser/dom*/,373/*vs/editor/common/services/textModelSync/textModelSync.impl*/,326/*vs/editor/common/services/editorWorkerHost*/]), function (require, exports, async_1, lifecycle_1, simpleWorker_1, defaultWorkerFactory_1, range_1, languageConfigurationRegistry_1, editorSimpleWorker_1, model_1, textResourceConfiguration_1, arrays_1, log_1, stopwatch_1, errors_1, languageFeatures_1, linesDiffComputer_1, rangeMapping_1, lineRange_1, window_1, dom_1, textModelSync_impl_1, editorWorkerHost_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.EditorWorkerClient = exports.EditorWorkerService = void 0;
    /**
     * Stop the worker if it was not needed for 5 min.
     */
    const STOP_WORKER_DELTA_TIME_MS = 5 * 60 * 1000;
    function canSyncModel(modelService, resource) {
        const model = modelService.getModel(resource);
        if (!model) {
            return false;
        }
        if (model.isTooLargeForSyncing()) {
            return false;
        }
        return true;
    }
    let EditorWorkerService = class EditorWorkerService extends lifecycle_1.Disposable {
        constructor(workerDescriptor, modelService, configurationService, logService, _languageConfigurationService, languageFeaturesService) {
            super();
            this._languageConfigurationService = _languageConfigurationService;
            this._modelService = modelService;
            this._workerManager = this._register(new WorkerManager(workerDescriptor, this._modelService));
            this._logService = logService;
            // register default link-provider and default completions-provider
            this._register(languageFeaturesService.linkProvider.register({ language: '*', hasAccessToAllModels: true }, {
                provideLinks: async (model, token) => {
                    if (!canSyncModel(this._modelService, model.uri)) {
                        return Promise.resolve({ links: [] }); // File too large
                    }
                    const worker = await this._workerWithResources([model.uri]);
                    const links = await worker.$computeLinks(model.uri.toString());
                    return links && { links };
                }
            }));
            this._register(languageFeaturesService.completionProvider.register('*', new WordBasedCompletionItemProvider(this._workerManager, configurationService, this._modelService, this._languageConfigurationService)));
        }
        dispose() {
            super.dispose();
        }
        canComputeUnicodeHighlights(uri) {
            return canSyncModel(this._modelService, uri);
        }
        async computedUnicodeHighlights(uri, options, range) {
            const worker = await this._workerWithResources([uri]);
            return worker.$computeUnicodeHighlights(uri.toString(), options, range);
        }
        async computeDiff(original, modified, options, algorithm) {
            const worker = await this._workerWithResources([original, modified], /* forceLargeModels */ true);
            const result = await worker.$computeDiff(original.toString(), modified.toString(), options, algorithm);
            if (!result) {
                return null;
            }
            // Convert from space efficient JSON data to rich objects.
            const diff = {
                identical: result.identical,
                quitEarly: result.quitEarly,
                changes: toLineRangeMappings(result.changes),
                moves: result.moves.map(m => new linesDiffComputer_1.MovedText(new rangeMapping_1.LineRangeMapping(new lineRange_1.LineRange(m[0], m[1]), new lineRange_1.LineRange(m[2], m[3])), toLineRangeMappings(m[4])))
            };
            return diff;
            function toLineRangeMappings(changes) {
                return changes.map((c) => new rangeMapping_1.DetailedLineRangeMapping(new lineRange_1.LineRange(c[0], c[1]), new lineRange_1.LineRange(c[2], c[3]), c[4]?.map((c) => new rangeMapping_1.RangeMapping(new range_1.Range(c[0], c[1], c[2], c[3]), new range_1.Range(c[4], c[5], c[6], c[7])))));
            }
        }
        async computeMoreMinimalEdits(resource, edits, pretty = false) {
            if ((0, arrays_1.isNonEmptyArray)(edits)) {
                if (!canSyncModel(this._modelService, resource)) {
                    return Promise.resolve(edits); // File too large
                }
                const sw = stopwatch_1.StopWatch.create();
                const result = this._workerWithResources([resource]).then(worker => worker.$computeMoreMinimalEdits(resource.toString(), edits, pretty));
                result.finally(() => this._logService.trace('FORMAT#computeMoreMinimalEdits', resource.toString(true), sw.elapsed()));
                return Promise.race([result, (0, async_1.timeout)(1000).then(() => edits)]);
            }
            else {
                return Promise.resolve(undefined);
            }
        }
        canNavigateValueSet(resource) {
            return (canSyncModel(this._modelService, resource));
        }
        async navigateValueSet(resource, range, up) {
            const model = this._modelService.getModel(resource);
            if (!model) {
                return null;
            }
            const wordDefRegExp = this._languageConfigurationService.getLanguageConfiguration(model.getLanguageId()).getWordDefinition();
            const wordDef = wordDefRegExp.source;
            const wordDefFlags = wordDefRegExp.flags;
            const worker = await this._workerWithResources([resource]);
            return worker.$navigateValueSet(resource.toString(), range, up, wordDef, wordDefFlags);
        }
        canComputeWordRanges(resource) {
            return canSyncModel(this._modelService, resource);
        }
        async computeWordRanges(resource, range) {
            const model = this._modelService.getModel(resource);
            if (!model) {
                return Promise.resolve(null);
            }
            const wordDefRegExp = this._languageConfigurationService.getLanguageConfiguration(model.getLanguageId()).getWordDefinition();
            const wordDef = wordDefRegExp.source;
            const wordDefFlags = wordDefRegExp.flags;
            const worker = await this._workerWithResources([resource]);
            return worker.$computeWordRanges(resource.toString(), range, wordDef, wordDefFlags);
        }
        async findSectionHeaders(uri, options) {
            const worker = await this._workerWithResources([uri]);
            return worker.$findSectionHeaders(uri.toString(), options);
        }
        async computeDefaultDocumentColors(uri) {
            const worker = await this._workerWithResources([uri]);
            return worker.$computeDefaultDocumentColors(uri.toString());
        }
        async _workerWithResources(resources, forceLargeModels = false) {
            const worker = await this._workerManager.withWorker();
            return await worker.workerWithSyncedResources(resources, forceLargeModels);
        }
    };
    exports.EditorWorkerService = EditorWorkerService;
    exports.EditorWorkerService = EditorWorkerService = __decorate([
        __param(1, model_1.IModelService),
        __param(2, textResourceConfiguration_1.ITextResourceConfigurationService),
        __param(3, log_1.ILogService),
        __param(4, languageConfigurationRegistry_1.ILanguageConfigurationService),
        __param(5, languageFeatures_1.ILanguageFeaturesService)
    ], EditorWorkerService);
    class WordBasedCompletionItemProvider {
        constructor(workerManager, configurationService, modelService, languageConfigurationService) {
            this.languageConfigurationService = languageConfigurationService;
            this._debugDisplayName = 'wordbasedCompletions';
            this._workerManager = workerManager;
            this._configurationService = configurationService;
            this._modelService = modelService;
        }
        async provideCompletionItems(model, position) {
            const config = this._configurationService.getValue(model.uri, position, 'editor');
            if (config.wordBasedSuggestions === 'off') {
                return undefined;
            }
            const models = [];
            if (config.wordBasedSuggestions === 'currentDocument') {
                // only current file and only if not too large
                if (canSyncModel(this._modelService, model.uri)) {
                    models.push(model.uri);
                }
            }
            else {
                // either all files or files of same language
                for (const candidate of this._modelService.getModels()) {
                    if (!canSyncModel(this._modelService, candidate.uri)) {
                        continue;
                    }
                    if (candidate === model) {
                        models.unshift(candidate.uri);
                    }
                    else if (config.wordBasedSuggestions === 'allDocuments' || candidate.getLanguageId() === model.getLanguageId()) {
                        models.push(candidate.uri);
                    }
                }
            }
            if (models.length === 0) {
                return undefined; // File too large, no other files
            }
            const wordDefRegExp = this.languageConfigurationService.getLanguageConfiguration(model.getLanguageId()).getWordDefinition();
            const word = model.getWordAtPosition(position);
            const replace = !word ? range_1.Range.fromPositions(position) : new range_1.Range(position.lineNumber, word.startColumn, position.lineNumber, word.endColumn);
            const insert = replace.setEndPosition(position.lineNumber, position.column);
            const client = await this._workerManager.withWorker();
            const data = await client.textualSuggest(models, word?.word, wordDefRegExp);
            if (!data) {
                return undefined;
            }
            return {
                duration: data.duration,
                suggestions: data.words.map((word) => {
                    return {
                        kind: 18 /* languages.CompletionItemKind.Text */,
                        label: word,
                        insertText: word,
                        range: { insert, replace }
                    };
                }),
            };
        }
    }
    let WorkerManager = class WorkerManager extends lifecycle_1.Disposable {
        constructor(_workerDescriptor, modelService) {
            super();
            this._workerDescriptor = _workerDescriptor;
            this._modelService = modelService;
            this._editorWorkerClient = null;
            this._lastWorkerUsedTime = (new Date()).getTime();
            const stopWorkerInterval = this._register(new dom_1.WindowIntervalTimer());
            stopWorkerInterval.cancelAndSet(() => this._checkStopIdleWorker(), Math.round(STOP_WORKER_DELTA_TIME_MS / 2), window_1.mainWindow);
            this._register(this._modelService.onModelRemoved(_ => this._checkStopEmptyWorker()));
        }
        dispose() {
            if (this._editorWorkerClient) {
                this._editorWorkerClient.dispose();
                this._editorWorkerClient = null;
            }
            super.dispose();
        }
        /**
         * Check if the model service has no more models and stop the worker if that is the case.
         */
        _checkStopEmptyWorker() {
            if (!this._editorWorkerClient) {
                return;
            }
            const models = this._modelService.getModels();
            if (models.length === 0) {
                // There are no more models => nothing possible for me to do
                this._editorWorkerClient.dispose();
                this._editorWorkerClient = null;
            }
        }
        /**
         * Check if the worker has been idle for a while and then stop it.
         */
        _checkStopIdleWorker() {
            if (!this._editorWorkerClient) {
                return;
            }
            const timeSinceLastWorkerUsedTime = (new Date()).getTime() - this._lastWorkerUsedTime;
            if (timeSinceLastWorkerUsedTime > STOP_WORKER_DELTA_TIME_MS) {
                this._editorWorkerClient.dispose();
                this._editorWorkerClient = null;
            }
        }
        withWorker() {
            this._lastWorkerUsedTime = (new Date()).getTime();
            if (!this._editorWorkerClient) {
                this._editorWorkerClient = new EditorWorkerClient(this._workerDescriptor, false, this._modelService);
            }
            return Promise.resolve(this._editorWorkerClient);
        }
    };
    WorkerManager = __decorate([
        __param(1, model_1.IModelService)
    ], WorkerManager);
    class SynchronousWorkerClient {
        constructor(instance) {
            this._instance = instance;
            this.proxy = this._instance;
        }
        dispose() {
            this._instance.dispose();
        }
        setChannel(channel, handler) {
            throw new Error(`Not supported`);
        }
    }
    let EditorWorkerClient = class EditorWorkerClient extends lifecycle_1.Disposable {
        constructor(_workerDescriptor, keepIdleModels, modelService) {
            super();
            this._workerDescriptor = _workerDescriptor;
            this._disposed = false;
            this._modelService = modelService;
            this._keepIdleModels = keepIdleModels;
            this._worker = null;
            this._modelManager = null;
        }
        // foreign host request
        fhr(method, args) {
            throw new Error(`Not implemented!`);
        }
        _getOrCreateWorker() {
            if (!this._worker) {
                try {
                    this._worker = this._register((0, defaultWorkerFactory_1.createWebWorker)(this._workerDescriptor));
                    editorWorkerHost_1.EditorWorkerHost.setChannel(this._worker, this._createEditorWorkerHost());
                }
                catch (err) {
                    (0, simpleWorker_1.logOnceWebWorkerWarning)(err);
                    this._worker = this._createFallbackLocalWorker();
                }
            }
            return this._worker;
        }
        async _getProxy() {
            try {
                const proxy = this._getOrCreateWorker().proxy;
                await proxy.$ping();
                return proxy;
            }
            catch (err) {
                (0, simpleWorker_1.logOnceWebWorkerWarning)(err);
                this._worker = this._createFallbackLocalWorker();
                return this._worker.proxy;
            }
        }
        _createFallbackLocalWorker() {
            return new SynchronousWorkerClient(new editorSimpleWorker_1.EditorSimpleWorker(this._createEditorWorkerHost(), null));
        }
        _createEditorWorkerHost() {
            return {
                $fhr: (method, args) => this.fhr(method, args)
            };
        }
        _getOrCreateModelManager(proxy) {
            if (!this._modelManager) {
                this._modelManager = this._register(new textModelSync_impl_1.WorkerTextModelSyncClient(proxy, this._modelService, this._keepIdleModels));
            }
            return this._modelManager;
        }
        async workerWithSyncedResources(resources, forceLargeModels = false) {
            if (this._disposed) {
                return Promise.reject((0, errors_1.canceled)());
            }
            const proxy = await this._getProxy();
            this._getOrCreateModelManager(proxy).ensureSyncedResources(resources, forceLargeModels);
            return proxy;
        }
        async textualSuggest(resources, leadingWord, wordDefRegExp) {
            const proxy = await this.workerWithSyncedResources(resources);
            const wordDef = wordDefRegExp.source;
            const wordDefFlags = wordDefRegExp.flags;
            return proxy.$textualSuggest(resources.map(r => r.toString()), leadingWord, wordDef, wordDefFlags);
        }
        dispose() {
            super.dispose();
            this._disposed = true;
        }
    };
    exports.EditorWorkerClient = EditorWorkerClient;
    exports.EditorWorkerClient = EditorWorkerClient = __decorate([
        __param(2, model_1.IModelService)
    ], EditorWorkerClient);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[275/*vs/editor/common/languages/enterAction*/], __M([1/*require*/,0/*exports*/,131/*vs/editor/common/languages/languageConfiguration*/,36/*vs/editor/common/languages/languageConfigurationRegistry*/,240/*vs/editor/common/languages/supports/indentationLineProcessor*/]), function (require, exports, languageConfiguration_1, languageConfigurationRegistry_1, indentationLineProcessor_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.getEnterAction = getEnterAction;
    function getEnterAction(autoIndent, model, range, languageConfigurationService) {
        model.tokenization.forceTokenization(range.startLineNumber);
        const languageId = model.getLanguageIdAtPosition(range.startLineNumber, range.startColumn);
        const richEditSupport = languageConfigurationService.getLanguageConfiguration(languageId);
        if (!richEditSupport) {
            return null;
        }
        const indentationContextProcessor = new indentationLineProcessor_1.IndentationContextProcessor(model, languageConfigurationService);
        const processedContextTokens = indentationContextProcessor.getProcessedTokenContextAroundRange(range);
        const previousLineText = processedContextTokens.previousLineProcessedTokens.getLineContent();
        const beforeEnterText = processedContextTokens.beforeRangeProcessedTokens.getLineContent();
        const afterEnterText = processedContextTokens.afterRangeProcessedTokens.getLineContent();
        const enterResult = richEditSupport.onEnter(autoIndent, previousLineText, beforeEnterText, afterEnterText);
        if (!enterResult) {
            return null;
        }
        const indentAction = enterResult.indentAction;
        let appendText = enterResult.appendText;
        const removeText = enterResult.removeText || 0;
        // Here we add `\t` to appendText first because enterAction is leveraging appendText and removeText to change indentation.
        if (!appendText) {
            if ((indentAction === languageConfiguration_1.IndentAction.Indent) ||
                (indentAction === languageConfiguration_1.IndentAction.IndentOutdent)) {
                appendText = '\t';
            }
            else {
                appendText = '';
            }
        }
        else if (indentAction === languageConfiguration_1.IndentAction.Indent) {
            appendText = '\t' + appendText;
        }
        let indentation = (0, languageConfigurationRegistry_1.getIndentationAtPosition)(model, range.startLineNumber, range.startColumn);
        if (removeText) {
            indentation = indentation.substring(0, indentation.length - removeText);
        }
        return {
            indentAction: indentAction,
            appendText: appendText,
            removeText: removeText,
            indentation: indentation
        };
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[183/*vs/editor/common/commands/shiftCommand*/], __M([1/*require*/,0/*exports*/,11/*vs/base/common/strings*/,94/*vs/editor/common/core/cursorColumns*/,4/*vs/editor/common/core/range*/,23/*vs/editor/common/core/selection*/,275/*vs/editor/common/languages/enterAction*/,36/*vs/editor/common/languages/languageConfigurationRegistry*/]), function (require, exports, strings, cursorColumns_1, range_1, selection_1, enterAction_1, languageConfigurationRegistry_1) {
    "use strict";
    var ShiftCommand_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ShiftCommand = void 0;
    const repeatCache = Object.create(null);
    function cachedStringRepeat(str, count) {
        if (count <= 0) {
            return '';
        }
        if (!repeatCache[str]) {
            repeatCache[str] = ['', str];
        }
        const cache = repeatCache[str];
        for (let i = cache.length; i <= count; i++) {
            cache[i] = cache[i - 1] + str;
        }
        return cache[count];
    }
    let ShiftCommand = ShiftCommand_1 = class ShiftCommand {
        static unshiftIndent(line, column, tabSize, indentSize, insertSpaces) {
            // Determine the visible column where the content starts
            const contentStartVisibleColumn = cursorColumns_1.CursorColumns.visibleColumnFromColumn(line, column, tabSize);
            if (insertSpaces) {
                const indent = cachedStringRepeat(' ', indentSize);
                const desiredTabStop = cursorColumns_1.CursorColumns.prevIndentTabStop(contentStartVisibleColumn, indentSize);
                const indentCount = desiredTabStop / indentSize; // will be an integer
                return cachedStringRepeat(indent, indentCount);
            }
            else {
                const indent = '\t';
                const desiredTabStop = cursorColumns_1.CursorColumns.prevRenderTabStop(contentStartVisibleColumn, tabSize);
                const indentCount = desiredTabStop / tabSize; // will be an integer
                return cachedStringRepeat(indent, indentCount);
            }
        }
        static shiftIndent(line, column, tabSize, indentSize, insertSpaces) {
            // Determine the visible column where the content starts
            const contentStartVisibleColumn = cursorColumns_1.CursorColumns.visibleColumnFromColumn(line, column, tabSize);
            if (insertSpaces) {
                const indent = cachedStringRepeat(' ', indentSize);
                const desiredTabStop = cursorColumns_1.CursorColumns.nextIndentTabStop(contentStartVisibleColumn, indentSize);
                const indentCount = desiredTabStop / indentSize; // will be an integer
                return cachedStringRepeat(indent, indentCount);
            }
            else {
                const indent = '\t';
                const desiredTabStop = cursorColumns_1.CursorColumns.nextRenderTabStop(contentStartVisibleColumn, tabSize);
                const indentCount = desiredTabStop / tabSize; // will be an integer
                return cachedStringRepeat(indent, indentCount);
            }
        }
        constructor(range, opts, _languageConfigurationService) {
            this._languageConfigurationService = _languageConfigurationService;
            this._opts = opts;
            this._selection = range;
            this._selectionId = null;
            this._useLastEditRangeForCursorEndPosition = false;
            this._selectionStartColumnStaysPut = false;
        }
        _addEditOperation(builder, range, text) {
            if (this._useLastEditRangeForCursorEndPosition) {
                builder.addTrackedEditOperation(range, text);
            }
            else {
                builder.addEditOperation(range, text);
            }
        }
        getEditOperations(model, builder) {
            const startLine = this._selection.startLineNumber;
            let endLine = this._selection.endLineNumber;
            if (this._selection.endColumn === 1 && startLine !== endLine) {
                endLine = endLine - 1;
            }
            const { tabSize, indentSize, insertSpaces } = this._opts;
            const shouldIndentEmptyLines = (startLine === endLine);
            if (this._opts.useTabStops) {
                // if indenting or outdenting on a whitespace only line
                if (this._selection.isEmpty()) {
                    if (/^\s*$/.test(model.getLineContent(startLine))) {
                        this._useLastEditRangeForCursorEndPosition = true;
                    }
                }
                // keep track of previous line's "miss-alignment"
                let previousLineExtraSpaces = 0, extraSpaces = 0;
                for (let lineNumber = startLine; lineNumber <= endLine; lineNumber++, previousLineExtraSpaces = extraSpaces) {
                    extraSpaces = 0;
                    const lineText = model.getLineContent(lineNumber);
                    let indentationEndIndex = strings.firstNonWhitespaceIndex(lineText);
                    if (this._opts.isUnshift && (lineText.length === 0 || indentationEndIndex === 0)) {
                        // empty line or line with no leading whitespace => nothing to do
                        continue;
                    }
                    if (!shouldIndentEmptyLines && !this._opts.isUnshift && lineText.length === 0) {
                        // do not indent empty lines => nothing to do
                        continue;
                    }
                    if (indentationEndIndex === -1) {
                        // the entire line is whitespace
                        indentationEndIndex = lineText.length;
                    }
                    if (lineNumber > 1) {
                        const contentStartVisibleColumn = cursorColumns_1.CursorColumns.visibleColumnFromColumn(lineText, indentationEndIndex + 1, tabSize);
                        if (contentStartVisibleColumn % indentSize !== 0) {
                            // The current line is "miss-aligned", so let's see if this is expected...
                            // This can only happen when it has trailing commas in the indent
                            if (model.tokenization.isCheapToTokenize(lineNumber - 1)) {
                                const enterAction = (0, enterAction_1.getEnterAction)(this._opts.autoIndent, model, new range_1.Range(lineNumber - 1, model.getLineMaxColumn(lineNumber - 1), lineNumber - 1, model.getLineMaxColumn(lineNumber - 1)), this._languageConfigurationService);
                                if (enterAction) {
                                    extraSpaces = previousLineExtraSpaces;
                                    if (enterAction.appendText) {
                                        for (let j = 0, lenJ = enterAction.appendText.length; j < lenJ && extraSpaces < indentSize; j++) {
                                            if (enterAction.appendText.charCodeAt(j) === 32 /* CharCode.Space */) {
                                                extraSpaces++;
                                            }
                                            else {
                                                break;
                                            }
                                        }
                                    }
                                    if (enterAction.removeText) {
                                        extraSpaces = Math.max(0, extraSpaces - enterAction.removeText);
                                    }
                                    // Act as if `prefixSpaces` is not part of the indentation
                                    for (let j = 0; j < extraSpaces; j++) {
                                        if (indentationEndIndex === 0 || lineText.charCodeAt(indentationEndIndex - 1) !== 32 /* CharCode.Space */) {
                                            break;
                                        }
                                        indentationEndIndex--;
                                    }
                                }
                            }
                        }
                    }
                    if (this._opts.isUnshift && indentationEndIndex === 0) {
                        // line with no leading whitespace => nothing to do
                        continue;
                    }
                    let desiredIndent;
                    if (this._opts.isUnshift) {
                        desiredIndent = ShiftCommand_1.unshiftIndent(lineText, indentationEndIndex + 1, tabSize, indentSize, insertSpaces);
                    }
                    else {
                        desiredIndent = ShiftCommand_1.shiftIndent(lineText, indentationEndIndex + 1, tabSize, indentSize, insertSpaces);
                    }
                    this._addEditOperation(builder, new range_1.Range(lineNumber, 1, lineNumber, indentationEndIndex + 1), desiredIndent);
                    if (lineNumber === startLine && !this._selection.isEmpty()) {
                        // Force the startColumn to stay put because we're inserting after it
                        this._selectionStartColumnStaysPut = (this._selection.startColumn <= indentationEndIndex + 1);
                    }
                }
            }
            else {
                // if indenting or outdenting on a whitespace only line
                if (!this._opts.isUnshift && this._selection.isEmpty() && model.getLineLength(startLine) === 0) {
                    this._useLastEditRangeForCursorEndPosition = true;
                }
                const oneIndent = (insertSpaces ? cachedStringRepeat(' ', indentSize) : '\t');
                for (let lineNumber = startLine; lineNumber <= endLine; lineNumber++) {
                    const lineText = model.getLineContent(lineNumber);
                    let indentationEndIndex = strings.firstNonWhitespaceIndex(lineText);
                    if (this._opts.isUnshift && (lineText.length === 0 || indentationEndIndex === 0)) {
                        // empty line or line with no leading whitespace => nothing to do
                        continue;
                    }
                    if (!shouldIndentEmptyLines && !this._opts.isUnshift && lineText.length === 0) {
                        // do not indent empty lines => nothing to do
                        continue;
                    }
                    if (indentationEndIndex === -1) {
                        // the entire line is whitespace
                        indentationEndIndex = lineText.length;
                    }
                    if (this._opts.isUnshift && indentationEndIndex === 0) {
                        // line with no leading whitespace => nothing to do
                        continue;
                    }
                    if (this._opts.isUnshift) {
                        indentationEndIndex = Math.min(indentationEndIndex, indentSize);
                        for (let i = 0; i < indentationEndIndex; i++) {
                            const chr = lineText.charCodeAt(i);
                            if (chr === 9 /* CharCode.Tab */) {
                                indentationEndIndex = i + 1;
                                break;
                            }
                        }
                        this._addEditOperation(builder, new range_1.Range(lineNumber, 1, lineNumber, indentationEndIndex + 1), '');
                    }
                    else {
                        this._addEditOperation(builder, new range_1.Range(lineNumber, 1, lineNumber, 1), oneIndent);
                        if (lineNumber === startLine && !this._selection.isEmpty()) {
                            // Force the startColumn to stay put because we're inserting after it
                            this._selectionStartColumnStaysPut = (this._selection.startColumn === 1);
                        }
                    }
                }
            }
            this._selectionId = builder.trackSelection(this._selection);
        }
        computeCursorState(model, helper) {
            if (this._useLastEditRangeForCursorEndPosition) {
                const lastOp = helper.getInverseEditOperations()[0];
                return new selection_1.Selection(lastOp.range.endLineNumber, lastOp.range.endColumn, lastOp.range.endLineNumber, lastOp.range.endColumn);
            }
            const result = helper.getTrackedSelection(this._selectionId);
            if (this._selectionStartColumnStaysPut) {
                // The selection start should not move
                const initialStartColumn = this._selection.startColumn;
                const resultStartColumn = result.startColumn;
                if (resultStartColumn <= initialStartColumn) {
                    return result;
                }
                if (result.getDirection() === 0 /* SelectionDirection.LTR */) {
                    return new selection_1.Selection(result.startLineNumber, initialStartColumn, result.endLineNumber, result.endColumn);
                }
                return new selection_1.Selection(result.endLineNumber, result.endColumn, result.startLineNumber, initialStartColumn);
            }
            return result;
        }
    };
    exports.ShiftCommand = ShiftCommand;
    exports.ShiftCommand = ShiftCommand = ShiftCommand_1 = __decorate([
        __param(2, languageConfigurationRegistry_1.ILanguageConfigurationService)
    ], ShiftCommand);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[213/*vs/editor/common/cursor/cursorTypeEditOperations*/], __M([1/*require*/,0/*exports*/,8/*vs/base/common/errors*/,11/*vs/base/common/strings*/,146/*vs/editor/common/commands/replaceCommand*/,183/*vs/editor/common/commands/shiftCommand*/,312/*vs/editor/common/commands/surroundSelectionCommand*/,76/*vs/editor/common/cursorCommon*/,166/*vs/editor/common/core/wordCharacterClassifier*/,4/*vs/editor/common/core/range*/,9/*vs/editor/common/core/position*/,131/*vs/editor/common/languages/languageConfiguration*/,36/*vs/editor/common/languages/languageConfigurationRegistry*/,169/*vs/editor/common/languages/supports*/,241/*vs/editor/common/languages/autoIndent*/,275/*vs/editor/common/languages/enterAction*/]), function (require, exports, errors_1, strings, replaceCommand_1, shiftCommand_1, surroundSelectionCommand_1, cursorCommon_1, wordCharacterClassifier_1, range_1, position_1, languageConfiguration_1, languageConfigurationRegistry_1, supports_1, autoIndent_1, enterAction_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.BaseTypeWithAutoClosingCommand = exports.TabOperation = exports.TypeWithoutInterceptorsOperation = exports.CompositionOperation = exports.PasteOperation = exports.EnterOperation = exports.SimpleCharacterTypeOperation = exports.InterceptorElectricCharOperation = exports.SurroundSelectionOperation = exports.AutoClosingOpenCharTypeOperation = exports.AutoClosingOvertypeWithInterceptorsOperation = exports.AutoClosingOvertypeOperation = exports.AutoIndentOperation = void 0;
    exports.shiftIndent = shiftIndent;
    exports.unshiftIndent = unshiftIndent;
    exports.shouldSurroundChar = shouldSurroundChar;
    class AutoIndentOperation {
        static getEdits(config, model, selections, ch, isDoingComposition) {
            if (!isDoingComposition && this._isAutoIndentType(config, model, selections)) {
                const indentationForSelections = [];
                for (const selection of selections) {
                    const indentation = this._findActualIndentationForSelection(config, model, selection, ch);
                    if (indentation === null) {
                        // Auto indentation failed
                        return;
                    }
                    indentationForSelections.push({ selection, indentation });
                }
                const autoClosingPairClose = AutoClosingOpenCharTypeOperation.getAutoClosingPairClose(config, model, selections, ch, false);
                return this._getIndentationAndAutoClosingPairEdits(config, model, indentationForSelections, ch, autoClosingPairClose);
            }
            return;
        }
        static _isAutoIndentType(config, model, selections) {
            if (config.autoIndent < 4 /* EditorAutoIndentStrategy.Full */) {
                return false;
            }
            for (let i = 0, len = selections.length; i < len; i++) {
                if (!model.tokenization.isCheapToTokenize(selections[i].getEndPosition().lineNumber)) {
                    return false;
                }
            }
            return true;
        }
        static _findActualIndentationForSelection(config, model, selection, ch) {
            const actualIndentation = (0, autoIndent_1.getIndentActionForType)(config, model, selection, ch, {
                shiftIndent: (indentation) => {
                    return shiftIndent(config, indentation);
                },
                unshiftIndent: (indentation) => {
                    return unshiftIndent(config, indentation);
                },
            }, config.languageConfigurationService);
            if (actualIndentation === null) {
                return null;
            }
            const currentIndentation = (0, languageConfigurationRegistry_1.getIndentationAtPosition)(model, selection.startLineNumber, selection.startColumn);
            if (actualIndentation === config.normalizeIndentation(currentIndentation)) {
                return null;
            }
            return actualIndentation;
        }
        static _getIndentationAndAutoClosingPairEdits(config, model, indentationForSelections, ch, autoClosingPairClose) {
            const commands = indentationForSelections.map(({ selection, indentation }) => {
                if (autoClosingPairClose !== null) {
                    // Apply both auto closing pair edits and auto indentation edits
                    const indentationEdit = this._getEditFromIndentationAndSelection(config, model, indentation, selection, ch, false);
                    return new TypeWithIndentationAndAutoClosingCommand(indentationEdit, selection, ch, autoClosingPairClose);
                }
                else {
                    // Apply only auto indentation edits
                    const indentationEdit = this._getEditFromIndentationAndSelection(config, model, indentation, selection, ch, true);
                    return typeCommand(indentationEdit.range, indentationEdit.text, false);
                }
            });
            const editOptions = { shouldPushStackElementBefore: true, shouldPushStackElementAfter: false };
            return new cursorCommon_1.EditOperationResult(4 /* EditOperationType.TypingOther */, commands, editOptions);
        }
        static _getEditFromIndentationAndSelection(config, model, indentation, selection, ch, includeChInEdit = true) {
            const startLineNumber = selection.startLineNumber;
            const firstNonWhitespaceColumn = model.getLineFirstNonWhitespaceColumn(startLineNumber);
            let text = config.normalizeIndentation(indentation);
            if (firstNonWhitespaceColumn !== 0) {
                const startLine = model.getLineContent(startLineNumber);
                text += startLine.substring(firstNonWhitespaceColumn - 1, selection.startColumn - 1);
            }
            text += includeChInEdit ? ch : '';
            const range = new range_1.Range(startLineNumber, 1, selection.endLineNumber, selection.endColumn);
            return { range, text };
        }
    }
    exports.AutoIndentOperation = AutoIndentOperation;
    class AutoClosingOvertypeOperation {
        static getEdits(prevEditOperationType, config, model, selections, autoClosedCharacters, ch) {
            if (isAutoClosingOvertype(config, model, selections, autoClosedCharacters, ch)) {
                return this._runAutoClosingOvertype(prevEditOperationType, selections, ch);
            }
            return;
        }
        static _runAutoClosingOvertype(prevEditOperationType, selections, ch) {
            const commands = [];
            for (let i = 0, len = selections.length; i < len; i++) {
                const selection = selections[i];
                const position = selection.getPosition();
                const typeSelection = new range_1.Range(position.lineNumber, position.column, position.lineNumber, position.column + 1);
                commands[i] = new replaceCommand_1.ReplaceCommand(typeSelection, ch);
            }
            return new cursorCommon_1.EditOperationResult(4 /* EditOperationType.TypingOther */, commands, {
                shouldPushStackElementBefore: shouldPushStackElementBetween(prevEditOperationType, 4 /* EditOperationType.TypingOther */),
                shouldPushStackElementAfter: false
            });
        }
    }
    exports.AutoClosingOvertypeOperation = AutoClosingOvertypeOperation;
    class AutoClosingOvertypeWithInterceptorsOperation {
        static getEdits(config, model, selections, autoClosedCharacters, ch) {
            if (isAutoClosingOvertype(config, model, selections, autoClosedCharacters, ch)) {
                // Unfortunately, the close character is at this point "doubled", so we need to delete it...
                const commands = selections.map(s => new replaceCommand_1.ReplaceCommand(new range_1.Range(s.positionLineNumber, s.positionColumn, s.positionLineNumber, s.positionColumn + 1), '', false));
                return new cursorCommon_1.EditOperationResult(4 /* EditOperationType.TypingOther */, commands, {
                    shouldPushStackElementBefore: true,
                    shouldPushStackElementAfter: false
                });
            }
            return;
        }
    }
    exports.AutoClosingOvertypeWithInterceptorsOperation = AutoClosingOvertypeWithInterceptorsOperation;
    class AutoClosingOpenCharTypeOperation {
        static getEdits(config, model, selections, ch, chIsAlreadyTyped, isDoingComposition) {
            if (!isDoingComposition) {
                const autoClosingPairClose = this.getAutoClosingPairClose(config, model, selections, ch, chIsAlreadyTyped);
                if (autoClosingPairClose !== null) {
                    return this._runAutoClosingOpenCharType(selections, ch, chIsAlreadyTyped, autoClosingPairClose);
                }
            }
            return;
        }
        static _runAutoClosingOpenCharType(selections, ch, chIsAlreadyTyped, autoClosingPairClose) {
            const commands = [];
            for (let i = 0, len = selections.length; i < len; i++) {
                const selection = selections[i];
                commands[i] = new TypeWithAutoClosingCommand(selection, ch, !chIsAlreadyTyped, autoClosingPairClose);
            }
            return new cursorCommon_1.EditOperationResult(4 /* EditOperationType.TypingOther */, commands, {
                shouldPushStackElementBefore: true,
                shouldPushStackElementAfter: false
            });
        }
        static getAutoClosingPairClose(config, model, selections, ch, chIsAlreadyTyped) {
            for (const selection of selections) {
                if (!selection.isEmpty()) {
                    return null;
                }
            }
            // This method is called both when typing (regularly) and when composition ends
            // This means that we need to work with a text buffer where sometimes `ch` is not
            // there (it is being typed right now) or with a text buffer where `ch` has already been typed
            //
            // In order to avoid adding checks for `chIsAlreadyTyped` in all places, we will work
            // with two conceptual positions, the position before `ch` and the position after `ch`
            //
            const positions = selections.map((s) => {
                const position = s.getPosition();
                if (chIsAlreadyTyped) {
                    return { lineNumber: position.lineNumber, beforeColumn: position.column - ch.length, afterColumn: position.column };
                }
                else {
                    return { lineNumber: position.lineNumber, beforeColumn: position.column, afterColumn: position.column };
                }
            });
            // Find the longest auto-closing open pair in case of multiple ending in `ch`
            // e.g. when having [f","] and [","], it picks [f","] if the character before is f
            const pair = this._findAutoClosingPairOpen(config, model, positions.map(p => new position_1.Position(p.lineNumber, p.beforeColumn)), ch);
            if (!pair) {
                return null;
            }
            let autoCloseConfig;
            let shouldAutoCloseBefore;
            const chIsQuote = (0, cursorCommon_1.isQuote)(ch);
            if (chIsQuote) {
                autoCloseConfig = config.autoClosingQuotes;
                shouldAutoCloseBefore = config.shouldAutoCloseBefore.quote;
            }
            else {
                const pairIsForComments = config.blockCommentStartToken ? pair.open.includes(config.blockCommentStartToken) : false;
                if (pairIsForComments) {
                    autoCloseConfig = config.autoClosingComments;
                    shouldAutoCloseBefore = config.shouldAutoCloseBefore.comment;
                }
                else {
                    autoCloseConfig = config.autoClosingBrackets;
                    shouldAutoCloseBefore = config.shouldAutoCloseBefore.bracket;
                }
            }
            if (autoCloseConfig === 'never') {
                return null;
            }
            // Sometimes, it is possible to have two auto-closing pairs that have a containment relationship
            // e.g. when having [(,)] and [(*,*)]
            // - when typing (, the resulting state is (|)
            // - when typing *, the desired resulting state is (*|*), not (*|*))
            const containedPair = this._findContainedAutoClosingPair(config, pair);
            const containedPairClose = containedPair ? containedPair.close : '';
            let isContainedPairPresent = true;
            for (const position of positions) {
                const { lineNumber, beforeColumn, afterColumn } = position;
                const lineText = model.getLineContent(lineNumber);
                const lineBefore = lineText.substring(0, beforeColumn - 1);
                const lineAfter = lineText.substring(afterColumn - 1);
                if (!lineAfter.startsWith(containedPairClose)) {
                    isContainedPairPresent = false;
                }
                // Only consider auto closing the pair if an allowed character follows or if another autoclosed pair closing brace follows
                if (lineAfter.length > 0) {
                    const characterAfter = lineAfter.charAt(0);
                    const isBeforeCloseBrace = this._isBeforeClosingBrace(config, lineAfter);
                    if (!isBeforeCloseBrace && !shouldAutoCloseBefore(characterAfter)) {
                        return null;
                    }
                }
                // Do not auto-close ' or " after a word character
                if (pair.open.length === 1 && (ch === '\'' || ch === '"') && autoCloseConfig !== 'always') {
                    const wordSeparators = (0, wordCharacterClassifier_1.getMapForWordSeparators)(config.wordSeparators, []);
                    if (lineBefore.length > 0) {
                        const characterBefore = lineBefore.charCodeAt(lineBefore.length - 1);
                        if (wordSeparators.get(characterBefore) === 0 /* WordCharacterClass.Regular */) {
                            return null;
                        }
                    }
                }
                if (!model.tokenization.isCheapToTokenize(lineNumber)) {
                    // Do not force tokenization
                    return null;
                }
                model.tokenization.forceTokenization(lineNumber);
                const lineTokens = model.tokenization.getLineTokens(lineNumber);
                const scopedLineTokens = (0, supports_1.createScopedLineTokens)(lineTokens, beforeColumn - 1);
                if (!pair.shouldAutoClose(scopedLineTokens, beforeColumn - scopedLineTokens.firstCharOffset)) {
                    return null;
                }
                // Typing for example a quote could either start a new string, in which case auto-closing is desirable
                // or it could end a previously started string, in which case auto-closing is not desirable
                //
                // In certain cases, it is really not possible to look at the previous token to determine
                // what would happen. That's why we do something really unusual, we pretend to type a different
                // character and ask the tokenizer what the outcome of doing that is: after typing a neutral
                // character, are we in a string (i.e. the quote would most likely end a string) or not?
                //
                const neutralCharacter = pair.findNeutralCharacter();
                if (neutralCharacter) {
                    const tokenType = model.tokenization.getTokenTypeIfInsertingCharacter(lineNumber, beforeColumn, neutralCharacter);
                    if (!pair.isOK(tokenType)) {
                        return null;
                    }
                }
            }
            if (isContainedPairPresent) {
                return pair.close.substring(0, pair.close.length - containedPairClose.length);
            }
            else {
                return pair.close;
            }
        }
        /**
         * Find another auto-closing pair that is contained by the one passed in.
         *
         * e.g. when having [(,)] and [(*,*)] as auto-closing pairs
         * this method will find [(,)] as a containment pair for [(*,*)]
         */
        static _findContainedAutoClosingPair(config, pair) {
            if (pair.open.length <= 1) {
                return null;
            }
            const lastChar = pair.close.charAt(pair.close.length - 1);
            // get candidates with the same last character as close
            const candidates = config.autoClosingPairs.autoClosingPairsCloseByEnd.get(lastChar) || [];
            let result = null;
            for (const candidate of candidates) {
                if (candidate.open !== pair.open && pair.open.includes(candidate.open) && pair.close.endsWith(candidate.close)) {
                    if (!result || candidate.open.length > result.open.length) {
                        result = candidate;
                    }
                }
            }
            return result;
        }
        /**
         * Determine if typing `ch` at all `positions` in the `model` results in an
         * auto closing open sequence being typed.
         *
         * Auto closing open sequences can consist of multiple characters, which
         * can lead to ambiguities. In such a case, the longest auto-closing open
         * sequence is returned.
         */
        static _findAutoClosingPairOpen(config, model, positions, ch) {
            const candidates = config.autoClosingPairs.autoClosingPairsOpenByEnd.get(ch);
            if (!candidates) {
                return null;
            }
            // Determine which auto-closing pair it is
            let result = null;
            for (const candidate of candidates) {
                if (result === null || candidate.open.length > result.open.length) {
                    let candidateIsMatch = true;
                    for (const position of positions) {
                        const relevantText = model.getValueInRange(new range_1.Range(position.lineNumber, position.column - candidate.open.length + 1, position.lineNumber, position.column));
                        if (relevantText + ch !== candidate.open) {
                            candidateIsMatch = false;
                            break;
                        }
                    }
                    if (candidateIsMatch) {
                        result = candidate;
                    }
                }
            }
            return result;
        }
        static _isBeforeClosingBrace(config, lineAfter) {
            // If the start of lineAfter can be interpretted as both a starting or ending brace, default to returning false
            const nextChar = lineAfter.charAt(0);
            const potentialStartingBraces = config.autoClosingPairs.autoClosingPairsOpenByStart.get(nextChar) || [];
            const potentialClosingBraces = config.autoClosingPairs.autoClosingPairsCloseByStart.get(nextChar) || [];
            const isBeforeStartingBrace = potentialStartingBraces.some(x => lineAfter.startsWith(x.open));
            const isBeforeClosingBrace = potentialClosingBraces.some(x => lineAfter.startsWith(x.close));
            return !isBeforeStartingBrace && isBeforeClosingBrace;
        }
    }
    exports.AutoClosingOpenCharTypeOperation = AutoClosingOpenCharTypeOperation;
    class SurroundSelectionOperation {
        static getEdits(config, model, selections, ch, isDoingComposition) {
            if (!isDoingComposition && this._isSurroundSelectionType(config, model, selections, ch)) {
                return this._runSurroundSelectionType(config, selections, ch);
            }
            return;
        }
        static _runSurroundSelectionType(config, selections, ch) {
            const commands = [];
            for (let i = 0, len = selections.length; i < len; i++) {
                const selection = selections[i];
                const closeCharacter = config.surroundingPairs[ch];
                commands[i] = new surroundSelectionCommand_1.SurroundSelectionCommand(selection, ch, closeCharacter);
            }
            return new cursorCommon_1.EditOperationResult(0 /* EditOperationType.Other */, commands, {
                shouldPushStackElementBefore: true,
                shouldPushStackElementAfter: true
            });
        }
        static _isSurroundSelectionType(config, model, selections, ch) {
            if (!shouldSurroundChar(config, ch) || !config.surroundingPairs.hasOwnProperty(ch)) {
                return false;
            }
            const isTypingAQuoteCharacter = (0, cursorCommon_1.isQuote)(ch);
            for (const selection of selections) {
                if (selection.isEmpty()) {
                    return false;
                }
                let selectionContainsOnlyWhitespace = true;
                for (let lineNumber = selection.startLineNumber; lineNumber <= selection.endLineNumber; lineNumber++) {
                    const lineText = model.getLineContent(lineNumber);
                    const startIndex = (lineNumber === selection.startLineNumber ? selection.startColumn - 1 : 0);
                    const endIndex = (lineNumber === selection.endLineNumber ? selection.endColumn - 1 : lineText.length);
                    const selectedText = lineText.substring(startIndex, endIndex);
                    if (/[^ \t]/.test(selectedText)) {
                        // this selected text contains something other than whitespace
                        selectionContainsOnlyWhitespace = false;
                        break;
                    }
                }
                if (selectionContainsOnlyWhitespace) {
                    return false;
                }
                if (isTypingAQuoteCharacter && selection.startLineNumber === selection.endLineNumber && selection.startColumn + 1 === selection.endColumn) {
                    const selectionText = model.getValueInRange(selection);
                    if ((0, cursorCommon_1.isQuote)(selectionText)) {
                        // Typing a quote character on top of another quote character
                        // => disable surround selection type
                        return false;
                    }
                }
            }
            return true;
        }
    }
    exports.SurroundSelectionOperation = SurroundSelectionOperation;
    class InterceptorElectricCharOperation {
        static getEdits(prevEditOperationType, config, model, selections, ch, isDoingComposition) {
            // Electric characters make sense only when dealing with a single cursor,
            // as multiple cursors typing brackets for example would interfer with bracket matching
            if (!isDoingComposition && this._isTypeInterceptorElectricChar(config, model, selections)) {
                const r = this._typeInterceptorElectricChar(prevEditOperationType, config, model, selections[0], ch);
                if (r) {
                    return r;
                }
            }
            return;
        }
        static _isTypeInterceptorElectricChar(config, model, selections) {
            if (selections.length === 1 && model.tokenization.isCheapToTokenize(selections[0].getEndPosition().lineNumber)) {
                return true;
            }
            return false;
        }
        static _typeInterceptorElectricChar(prevEditOperationType, config, model, selection, ch) {
            if (!config.electricChars.hasOwnProperty(ch) || !selection.isEmpty()) {
                return null;
            }
            const position = selection.getPosition();
            model.tokenization.forceTokenization(position.lineNumber);
            const lineTokens = model.tokenization.getLineTokens(position.lineNumber);
            let electricAction;
            try {
                electricAction = config.onElectricCharacter(ch, lineTokens, position.column);
            }
            catch (e) {
                (0, errors_1.onUnexpectedError)(e);
                return null;
            }
            if (!electricAction) {
                return null;
            }
            if (electricAction.matchOpenBracket) {
                const endColumn = (lineTokens.getLineContent() + ch).lastIndexOf(electricAction.matchOpenBracket) + 1;
                const match = model.bracketPairs.findMatchingBracketUp(electricAction.matchOpenBracket, {
                    lineNumber: position.lineNumber,
                    column: endColumn
                }, 500 /* give at most 500ms to compute */);
                if (match) {
                    if (match.startLineNumber === position.lineNumber) {
                        // matched something on the same line => no change in indentation
                        return null;
                    }
                    const matchLine = model.getLineContent(match.startLineNumber);
                    const matchLineIndentation = strings.getLeadingWhitespace(matchLine);
                    const newIndentation = config.normalizeIndentation(matchLineIndentation);
                    const lineText = model.getLineContent(position.lineNumber);
                    const lineFirstNonBlankColumn = model.getLineFirstNonWhitespaceColumn(position.lineNumber) || position.column;
                    const prefix = lineText.substring(lineFirstNonBlankColumn - 1, position.column - 1);
                    const typeText = newIndentation + prefix + ch;
                    const typeSelection = new range_1.Range(position.lineNumber, 1, position.lineNumber, position.column);
                    const command = new replaceCommand_1.ReplaceCommand(typeSelection, typeText);
                    return new cursorCommon_1.EditOperationResult(getTypingOperation(typeText, prevEditOperationType), [command], {
                        shouldPushStackElementBefore: false,
                        shouldPushStackElementAfter: true
                    });
                }
            }
            return null;
        }
    }
    exports.InterceptorElectricCharOperation = InterceptorElectricCharOperation;
    class SimpleCharacterTypeOperation {
        static getEdits(prevEditOperationType, selections, ch) {
            // A simple character type
            const commands = [];
            for (let i = 0, len = selections.length; i < len; i++) {
                commands[i] = new replaceCommand_1.ReplaceCommand(selections[i], ch);
            }
            const opType = getTypingOperation(ch, prevEditOperationType);
            return new cursorCommon_1.EditOperationResult(opType, commands, {
                shouldPushStackElementBefore: shouldPushStackElementBetween(prevEditOperationType, opType),
                shouldPushStackElementAfter: false
            });
        }
    }
    exports.SimpleCharacterTypeOperation = SimpleCharacterTypeOperation;
    class EnterOperation {
        static getEdits(config, model, selections, ch, isDoingComposition) {
            if (!isDoingComposition && ch === '\n') {
                const commands = [];
                for (let i = 0, len = selections.length; i < len; i++) {
                    commands[i] = this._enter(config, model, false, selections[i]);
                }
                return new cursorCommon_1.EditOperationResult(4 /* EditOperationType.TypingOther */, commands, {
                    shouldPushStackElementBefore: true,
                    shouldPushStackElementAfter: false,
                });
            }
            return;
        }
        static _enter(config, model, keepPosition, range) {
            if (config.autoIndent === 0 /* EditorAutoIndentStrategy.None */) {
                return typeCommand(range, '\n', keepPosition);
            }
            if (!model.tokenization.isCheapToTokenize(range.getStartPosition().lineNumber) || config.autoIndent === 1 /* EditorAutoIndentStrategy.Keep */) {
                const lineText = model.getLineContent(range.startLineNumber);
                const indentation = strings.getLeadingWhitespace(lineText).substring(0, range.startColumn - 1);
                return typeCommand(range, '\n' + config.normalizeIndentation(indentation), keepPosition);
            }
            const r = (0, enterAction_1.getEnterAction)(config.autoIndent, model, range, config.languageConfigurationService);
            if (r) {
                if (r.indentAction === languageConfiguration_1.IndentAction.None) {
                    // Nothing special
                    return typeCommand(range, '\n' + config.normalizeIndentation(r.indentation + r.appendText), keepPosition);
                }
                else if (r.indentAction === languageConfiguration_1.IndentAction.Indent) {
                    // Indent once
                    return typeCommand(range, '\n' + config.normalizeIndentation(r.indentation + r.appendText), keepPosition);
                }
                else if (r.indentAction === languageConfiguration_1.IndentAction.IndentOutdent) {
                    // Ultra special
                    const normalIndent = config.normalizeIndentation(r.indentation);
                    const increasedIndent = config.normalizeIndentation(r.indentation + r.appendText);
                    const typeText = '\n' + increasedIndent + '\n' + normalIndent;
                    if (keepPosition) {
                        return new replaceCommand_1.ReplaceCommandWithoutChangingPosition(range, typeText, true);
                    }
                    else {
                        return new replaceCommand_1.ReplaceCommandWithOffsetCursorState(range, typeText, -1, increasedIndent.length - normalIndent.length, true);
                    }
                }
                else if (r.indentAction === languageConfiguration_1.IndentAction.Outdent) {
                    const actualIndentation = unshiftIndent(config, r.indentation);
                    return typeCommand(range, '\n' + config.normalizeIndentation(actualIndentation + r.appendText), keepPosition);
                }
            }
            const lineText = model.getLineContent(range.startLineNumber);
            const indentation = strings.getLeadingWhitespace(lineText).substring(0, range.startColumn - 1);
            if (config.autoIndent >= 4 /* EditorAutoIndentStrategy.Full */) {
                const ir = (0, autoIndent_1.getIndentForEnter)(config.autoIndent, model, range, {
                    unshiftIndent: (indent) => {
                        return unshiftIndent(config, indent);
                    },
                    shiftIndent: (indent) => {
                        return shiftIndent(config, indent);
                    },
                    normalizeIndentation: (indent) => {
                        return config.normalizeIndentation(indent);
                    }
                }, config.languageConfigurationService);
                if (ir) {
                    let oldEndViewColumn = config.visibleColumnFromColumn(model, range.getEndPosition());
                    const oldEndColumn = range.endColumn;
                    const newLineContent = model.getLineContent(range.endLineNumber);
                    const firstNonWhitespace = strings.firstNonWhitespaceIndex(newLineContent);
                    if (firstNonWhitespace >= 0) {
                        range = range.setEndPosition(range.endLineNumber, Math.max(range.endColumn, firstNonWhitespace + 1));
                    }
                    else {
                        range = range.setEndPosition(range.endLineNumber, model.getLineMaxColumn(range.endLineNumber));
                    }
                    if (keepPosition) {
                        return new replaceCommand_1.ReplaceCommandWithoutChangingPosition(range, '\n' + config.normalizeIndentation(ir.afterEnter), true);
                    }
                    else {
                        let offset = 0;
                        if (oldEndColumn <= firstNonWhitespace + 1) {
                            if (!config.insertSpaces) {
                                oldEndViewColumn = Math.ceil(oldEndViewColumn / config.indentSize);
                            }
                            offset = Math.min(oldEndViewColumn + 1 - config.normalizeIndentation(ir.afterEnter).length - 1, 0);
                        }
                        return new replaceCommand_1.ReplaceCommandWithOffsetCursorState(range, '\n' + config.normalizeIndentation(ir.afterEnter), 0, offset, true);
                    }
                }
            }
            return typeCommand(range, '\n' + config.normalizeIndentation(indentation), keepPosition);
        }
        static lineInsertBefore(config, model, selections) {
            if (model === null || selections === null) {
                return [];
            }
            const commands = [];
            for (let i = 0, len = selections.length; i < len; i++) {
                let lineNumber = selections[i].positionLineNumber;
                if (lineNumber === 1) {
                    commands[i] = new replaceCommand_1.ReplaceCommandWithoutChangingPosition(new range_1.Range(1, 1, 1, 1), '\n');
                }
                else {
                    lineNumber--;
                    const column = model.getLineMaxColumn(lineNumber);
                    commands[i] = this._enter(config, model, false, new range_1.Range(lineNumber, column, lineNumber, column));
                }
            }
            return commands;
        }
        static lineInsertAfter(config, model, selections) {
            if (model === null || selections === null) {
                return [];
            }
            const commands = [];
            for (let i = 0, len = selections.length; i < len; i++) {
                const lineNumber = selections[i].positionLineNumber;
                const column = model.getLineMaxColumn(lineNumber);
                commands[i] = this._enter(config, model, false, new range_1.Range(lineNumber, column, lineNumber, column));
            }
            return commands;
        }
        static lineBreakInsert(config, model, selections) {
            const commands = [];
            for (let i = 0, len = selections.length; i < len; i++) {
                commands[i] = this._enter(config, model, true, selections[i]);
            }
            return commands;
        }
    }
    exports.EnterOperation = EnterOperation;
    class PasteOperation {
        static getEdits(config, model, selections, text, pasteOnNewLine, multicursorText) {
            const distributedPaste = this._distributePasteToCursors(config, selections, text, pasteOnNewLine, multicursorText);
            if (distributedPaste) {
                selections = selections.sort(range_1.Range.compareRangesUsingStarts);
                return this._distributedPaste(config, model, selections, distributedPaste);
            }
            else {
                return this._simplePaste(config, model, selections, text, pasteOnNewLine);
            }
        }
        static _distributePasteToCursors(config, selections, text, pasteOnNewLine, multicursorText) {
            if (pasteOnNewLine) {
                return null;
            }
            if (selections.length === 1) {
                return null;
            }
            if (multicursorText && multicursorText.length === selections.length) {
                return multicursorText;
            }
            if (config.multiCursorPaste === 'spread') {
                // Try to spread the pasted text in case the line count matches the cursor count
                // Remove trailing \n if present
                if (text.charCodeAt(text.length - 1) === 10 /* CharCode.LineFeed */) {
                    text = text.substring(0, text.length - 1);
                }
                // Remove trailing \r if present
                if (text.charCodeAt(text.length - 1) === 13 /* CharCode.CarriageReturn */) {
                    text = text.substring(0, text.length - 1);
                }
                const lines = strings.splitLines(text);
                if (lines.length === selections.length) {
                    return lines;
                }
            }
            return null;
        }
        static _distributedPaste(config, model, selections, text) {
            const commands = [];
            for (let i = 0, len = selections.length; i < len; i++) {
                commands[i] = new replaceCommand_1.ReplaceCommand(selections[i], text[i]);
            }
            return new cursorCommon_1.EditOperationResult(0 /* EditOperationType.Other */, commands, {
                shouldPushStackElementBefore: true,
                shouldPushStackElementAfter: true
            });
        }
        static _simplePaste(config, model, selections, text, pasteOnNewLine) {
            const commands = [];
            for (let i = 0, len = selections.length; i < len; i++) {
                const selection = selections[i];
                const position = selection.getPosition();
                if (pasteOnNewLine && !selection.isEmpty()) {
                    pasteOnNewLine = false;
                }
                if (pasteOnNewLine && text.indexOf('\n') !== text.length - 1) {
                    pasteOnNewLine = false;
                }
                if (pasteOnNewLine) {
                    // Paste entire line at the beginning of line
                    const typeSelection = new range_1.Range(position.lineNumber, 1, position.lineNumber, 1);
                    commands[i] = new replaceCommand_1.ReplaceCommandThatPreservesSelection(typeSelection, text, selection, true);
                }
                else {
                    commands[i] = new replaceCommand_1.ReplaceCommand(selection, text);
                }
            }
            return new cursorCommon_1.EditOperationResult(0 /* EditOperationType.Other */, commands, {
                shouldPushStackElementBefore: true,
                shouldPushStackElementAfter: true
            });
        }
    }
    exports.PasteOperation = PasteOperation;
    class CompositionOperation {
        static getEdits(prevEditOperationType, config, model, selections, text, replacePrevCharCnt, replaceNextCharCnt, positionDelta) {
            const commands = selections.map(selection => this._compositionType(model, selection, text, replacePrevCharCnt, replaceNextCharCnt, positionDelta));
            return new cursorCommon_1.EditOperationResult(4 /* EditOperationType.TypingOther */, commands, {
                shouldPushStackElementBefore: shouldPushStackElementBetween(prevEditOperationType, 4 /* EditOperationType.TypingOther */),
                shouldPushStackElementAfter: false
            });
        }
        static _compositionType(model, selection, text, replacePrevCharCnt, replaceNextCharCnt, positionDelta) {
            if (!selection.isEmpty()) {
                // looks like https://github.com/microsoft/vscode/issues/2773
                // where a cursor operation occurred before a canceled composition
                // => ignore composition
                return null;
            }
            const pos = selection.getPosition();
            const startColumn = Math.max(1, pos.column - replacePrevCharCnt);
            const endColumn = Math.min(model.getLineMaxColumn(pos.lineNumber), pos.column + replaceNextCharCnt);
            const range = new range_1.Range(pos.lineNumber, startColumn, pos.lineNumber, endColumn);
            const oldText = model.getValueInRange(range);
            if (oldText === text && positionDelta === 0) {
                // => ignore composition that doesn't do anything
                return null;
            }
            return new replaceCommand_1.ReplaceCommandWithOffsetCursorState(range, text, 0, positionDelta);
        }
    }
    exports.CompositionOperation = CompositionOperation;
    class TypeWithoutInterceptorsOperation {
        static getEdits(prevEditOperationType, selections, str) {
            const commands = [];
            for (let i = 0, len = selections.length; i < len; i++) {
                commands[i] = new replaceCommand_1.ReplaceCommand(selections[i], str);
            }
            const opType = getTypingOperation(str, prevEditOperationType);
            return new cursorCommon_1.EditOperationResult(opType, commands, {
                shouldPushStackElementBefore: shouldPushStackElementBetween(prevEditOperationType, opType),
                shouldPushStackElementAfter: false
            });
        }
    }
    exports.TypeWithoutInterceptorsOperation = TypeWithoutInterceptorsOperation;
    class TabOperation {
        static getCommands(config, model, selections) {
            const commands = [];
            for (let i = 0, len = selections.length; i < len; i++) {
                const selection = selections[i];
                if (selection.isEmpty()) {
                    const lineText = model.getLineContent(selection.startLineNumber);
                    if (/^\s*$/.test(lineText) && model.tokenization.isCheapToTokenize(selection.startLineNumber)) {
                        let goodIndent = this._goodIndentForLine(config, model, selection.startLineNumber);
                        goodIndent = goodIndent || '\t';
                        const possibleTypeText = config.normalizeIndentation(goodIndent);
                        if (!lineText.startsWith(possibleTypeText)) {
                            commands[i] = new replaceCommand_1.ReplaceCommand(new range_1.Range(selection.startLineNumber, 1, selection.startLineNumber, lineText.length + 1), possibleTypeText, true);
                            continue;
                        }
                    }
                    commands[i] = this._replaceJumpToNextIndent(config, model, selection, true);
                }
                else {
                    if (selection.startLineNumber === selection.endLineNumber) {
                        const lineMaxColumn = model.getLineMaxColumn(selection.startLineNumber);
                        if (selection.startColumn !== 1 || selection.endColumn !== lineMaxColumn) {
                            // This is a single line selection that is not the entire line
                            commands[i] = this._replaceJumpToNextIndent(config, model, selection, false);
                            continue;
                        }
                    }
                    commands[i] = new shiftCommand_1.ShiftCommand(selection, {
                        isUnshift: false,
                        tabSize: config.tabSize,
                        indentSize: config.indentSize,
                        insertSpaces: config.insertSpaces,
                        useTabStops: config.useTabStops,
                        autoIndent: config.autoIndent
                    }, config.languageConfigurationService);
                }
            }
            return commands;
        }
        static _goodIndentForLine(config, model, lineNumber) {
            let action = null;
            let indentation = '';
            const expectedIndentAction = (0, autoIndent_1.getInheritIndentForLine)(config.autoIndent, model, lineNumber, false, config.languageConfigurationService);
            if (expectedIndentAction) {
                action = expectedIndentAction.action;
                indentation = expectedIndentAction.indentation;
            }
            else if (lineNumber > 1) {
                let lastLineNumber;
                for (lastLineNumber = lineNumber - 1; lastLineNumber >= 1; lastLineNumber--) {
                    const lineText = model.getLineContent(lastLineNumber);
                    const nonWhitespaceIdx = strings.lastNonWhitespaceIndex(lineText);
                    if (nonWhitespaceIdx >= 0) {
                        break;
                    }
                }
                if (lastLineNumber < 1) {
                    // No previous line with content found
                    return null;
                }
                const maxColumn = model.getLineMaxColumn(lastLineNumber);
                const expectedEnterAction = (0, enterAction_1.getEnterAction)(config.autoIndent, model, new range_1.Range(lastLineNumber, maxColumn, lastLineNumber, maxColumn), config.languageConfigurationService);
                if (expectedEnterAction) {
                    indentation = expectedEnterAction.indentation + expectedEnterAction.appendText;
                }
            }
            if (action) {
                if (action === languageConfiguration_1.IndentAction.Indent) {
                    indentation = shiftIndent(config, indentation);
                }
                if (action === languageConfiguration_1.IndentAction.Outdent) {
                    indentation = unshiftIndent(config, indentation);
                }
                indentation = config.normalizeIndentation(indentation);
            }
            if (!indentation) {
                return null;
            }
            return indentation;
        }
        static _replaceJumpToNextIndent(config, model, selection, insertsAutoWhitespace) {
            let typeText = '';
            const position = selection.getStartPosition();
            if (config.insertSpaces) {
                const visibleColumnFromColumn = config.visibleColumnFromColumn(model, position);
                const indentSize = config.indentSize;
                const spacesCnt = indentSize - (visibleColumnFromColumn % indentSize);
                for (let i = 0; i < spacesCnt; i++) {
                    typeText += ' ';
                }
            }
            else {
                typeText = '\t';
            }
            return new replaceCommand_1.ReplaceCommand(selection, typeText, insertsAutoWhitespace);
        }
    }
    exports.TabOperation = TabOperation;
    class BaseTypeWithAutoClosingCommand extends replaceCommand_1.ReplaceCommandWithOffsetCursorState {
        constructor(selection, text, lineNumberDeltaOffset, columnDeltaOffset, openCharacter, closeCharacter) {
            super(selection, text, lineNumberDeltaOffset, columnDeltaOffset);
            this._openCharacter = openCharacter;
            this._closeCharacter = closeCharacter;
            this.closeCharacterRange = null;
            this.enclosingRange = null;
        }
        _computeCursorStateWithRange(model, range, helper) {
            this.closeCharacterRange = new range_1.Range(range.startLineNumber, range.endColumn - this._closeCharacter.length, range.endLineNumber, range.endColumn);
            this.enclosingRange = new range_1.Range(range.startLineNumber, range.endColumn - this._openCharacter.length - this._closeCharacter.length, range.endLineNumber, range.endColumn);
            return super.computeCursorState(model, helper);
        }
    }
    exports.BaseTypeWithAutoClosingCommand = BaseTypeWithAutoClosingCommand;
    class TypeWithAutoClosingCommand extends BaseTypeWithAutoClosingCommand {
        constructor(selection, openCharacter, insertOpenCharacter, closeCharacter) {
            const text = (insertOpenCharacter ? openCharacter : '') + closeCharacter;
            const lineNumberDeltaOffset = 0;
            const columnDeltaOffset = -closeCharacter.length;
            super(selection, text, lineNumberDeltaOffset, columnDeltaOffset, openCharacter, closeCharacter);
        }
        computeCursorState(model, helper) {
            const inverseEditOperations = helper.getInverseEditOperations();
            const range = inverseEditOperations[0].range;
            return this._computeCursorStateWithRange(model, range, helper);
        }
    }
    class TypeWithIndentationAndAutoClosingCommand extends BaseTypeWithAutoClosingCommand {
        constructor(autoIndentationEdit, selection, openCharacter, closeCharacter) {
            const text = openCharacter + closeCharacter;
            const lineNumberDeltaOffset = 0;
            const columnDeltaOffset = openCharacter.length;
            super(selection, text, lineNumberDeltaOffset, columnDeltaOffset, openCharacter, closeCharacter);
            this._autoIndentationEdit = autoIndentationEdit;
            this._autoClosingEdit = { range: selection, text };
        }
        getEditOperations(model, builder) {
            builder.addTrackedEditOperation(this._autoIndentationEdit.range, this._autoIndentationEdit.text);
            builder.addTrackedEditOperation(this._autoClosingEdit.range, this._autoClosingEdit.text);
        }
        computeCursorState(model, helper) {
            const inverseEditOperations = helper.getInverseEditOperations();
            if (inverseEditOperations.length !== 2) {
                throw new Error('There should be two inverse edit operations!');
            }
            const range1 = inverseEditOperations[0].range;
            const range2 = inverseEditOperations[1].range;
            const range = range1.plusRange(range2);
            return this._computeCursorStateWithRange(model, range, helper);
        }
    }
    function getTypingOperation(typedText, previousTypingOperation) {
        if (typedText === ' ') {
            return previousTypingOperation === 5 /* EditOperationType.TypingFirstSpace */
                || previousTypingOperation === 6 /* EditOperationType.TypingConsecutiveSpace */
                ? 6 /* EditOperationType.TypingConsecutiveSpace */
                : 5 /* EditOperationType.TypingFirstSpace */;
        }
        return 4 /* EditOperationType.TypingOther */;
    }
    function shouldPushStackElementBetween(previousTypingOperation, typingOperation) {
        if (isTypingOperation(previousTypingOperation) && !isTypingOperation(typingOperation)) {
            // Always set an undo stop before non-type operations
            return true;
        }
        if (previousTypingOperation === 5 /* EditOperationType.TypingFirstSpace */) {
            // `abc |d`: No undo stop
            // `abc  |d`: Undo stop
            return false;
        }
        // Insert undo stop between different operation types
        return normalizeOperationType(previousTypingOperation) !== normalizeOperationType(typingOperation);
    }
    function normalizeOperationType(type) {
        return (type === 6 /* EditOperationType.TypingConsecutiveSpace */ || type === 5 /* EditOperationType.TypingFirstSpace */)
            ? 'space'
            : type;
    }
    function isTypingOperation(type) {
        return type === 4 /* EditOperationType.TypingOther */
            || type === 5 /* EditOperationType.TypingFirstSpace */
            || type === 6 /* EditOperationType.TypingConsecutiveSpace */;
    }
    function isAutoClosingOvertype(config, model, selections, autoClosedCharacters, ch) {
        if (config.autoClosingOvertype === 'never') {
            return false;
        }
        if (!config.autoClosingPairs.autoClosingPairsCloseSingleChar.has(ch)) {
            return false;
        }
        for (let i = 0, len = selections.length; i < len; i++) {
            const selection = selections[i];
            if (!selection.isEmpty()) {
                return false;
            }
            const position = selection.getPosition();
            const lineText = model.getLineContent(position.lineNumber);
            const afterCharacter = lineText.charAt(position.column - 1);
            if (afterCharacter !== ch) {
                return false;
            }
            // Do not over-type quotes after a backslash
            const chIsQuote = (0, cursorCommon_1.isQuote)(ch);
            const beforeCharacter = position.column > 2 ? lineText.charCodeAt(position.column - 2) : 0 /* CharCode.Null */;
            if (beforeCharacter === 92 /* CharCode.Backslash */ && chIsQuote) {
                return false;
            }
            // Must over-type a closing character typed by the editor
            if (config.autoClosingOvertype === 'auto') {
                let found = false;
                for (let j = 0, lenJ = autoClosedCharacters.length; j < lenJ; j++) {
                    const autoClosedCharacter = autoClosedCharacters[j];
                    if (position.lineNumber === autoClosedCharacter.startLineNumber && position.column === autoClosedCharacter.startColumn) {
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    return false;
                }
            }
        }
        return true;
    }
    function typeCommand(range, text, keepPosition) {
        if (keepPosition) {
            return new replaceCommand_1.ReplaceCommandWithoutChangingPosition(range, text, true);
        }
        else {
            return new replaceCommand_1.ReplaceCommand(range, text, true);
        }
    }
    function shiftIndent(config, indentation, count) {
        count = count || 1;
        return shiftCommand_1.ShiftCommand.shiftIndent(indentation, indentation.length + count, config.tabSize, config.indentSize, config.insertSpaces);
    }
    function unshiftIndent(config, indentation, count) {
        count = count || 1;
        return shiftCommand_1.ShiftCommand.unshiftIndent(indentation, indentation.length + count, config.tabSize, config.indentSize, config.insertSpaces);
    }
    function shouldSurroundChar(config, ch) {
        if ((0, cursorCommon_1.isQuote)(ch)) {
            return (config.autoSurround === 'quotes' || config.autoSurround === 'languageDefined');
        }
        else {
            // Character is a bracket
            return (config.autoSurround === 'brackets' || config.autoSurround === 'languageDefined');
        }
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[276/*vs/editor/common/cursor/cursorTypeOperations*/], __M([1/*require*/,0/*exports*/,183/*vs/editor/common/commands/shiftCommand*/,312/*vs/editor/common/commands/surroundSelectionCommand*/,76/*vs/editor/common/cursorCommon*/,213/*vs/editor/common/cursor/cursorTypeEditOperations*/]), function (require, exports, shiftCommand_1, surroundSelectionCommand_1, cursorCommon_1, cursorTypeEditOperations_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CompositionOutcome = exports.TypeOperations = void 0;
    class TypeOperations {
        static indent(config, model, selections) {
            if (model === null || selections === null) {
                return [];
            }
            const commands = [];
            for (let i = 0, len = selections.length; i < len; i++) {
                commands[i] = new shiftCommand_1.ShiftCommand(selections[i], {
                    isUnshift: false,
                    tabSize: config.tabSize,
                    indentSize: config.indentSize,
                    insertSpaces: config.insertSpaces,
                    useTabStops: config.useTabStops,
                    autoIndent: config.autoIndent
                }, config.languageConfigurationService);
            }
            return commands;
        }
        static outdent(config, model, selections) {
            const commands = [];
            for (let i = 0, len = selections.length; i < len; i++) {
                commands[i] = new shiftCommand_1.ShiftCommand(selections[i], {
                    isUnshift: true,
                    tabSize: config.tabSize,
                    indentSize: config.indentSize,
                    insertSpaces: config.insertSpaces,
                    useTabStops: config.useTabStops,
                    autoIndent: config.autoIndent
                }, config.languageConfigurationService);
            }
            return commands;
        }
        static paste(config, model, selections, text, pasteOnNewLine, multicursorText) {
            return cursorTypeEditOperations_1.PasteOperation.getEdits(config, model, selections, text, pasteOnNewLine, multicursorText);
        }
        static tab(config, model, selections) {
            return cursorTypeEditOperations_1.TabOperation.getCommands(config, model, selections);
        }
        static compositionType(prevEditOperationType, config, model, selections, text, replacePrevCharCnt, replaceNextCharCnt, positionDelta) {
            return cursorTypeEditOperations_1.CompositionOperation.getEdits(prevEditOperationType, config, model, selections, text, replacePrevCharCnt, replaceNextCharCnt, positionDelta);
        }
        /**
         * This is very similar with typing, but the character is already in the text buffer!
         */
        static compositionEndWithInterceptors(prevEditOperationType, config, model, compositions, selections, autoClosedCharacters) {
            if (!compositions) {
                // could not deduce what the composition did
                return null;
            }
            let insertedText = null;
            for (const composition of compositions) {
                if (insertedText === null) {
                    insertedText = composition.insertedText;
                }
                else if (insertedText !== composition.insertedText) {
                    // not all selections agree on what was typed
                    return null;
                }
            }
            if (!insertedText || insertedText.length !== 1) {
                // we're only interested in the case where a single character was inserted
                return null;
            }
            const ch = insertedText;
            let hasDeletion = false;
            for (const composition of compositions) {
                if (composition.deletedText.length !== 0) {
                    hasDeletion = true;
                    break;
                }
            }
            if (hasDeletion) {
                // Check if this could have been a surround selection
                if (!(0, cursorTypeEditOperations_1.shouldSurroundChar)(config, ch) || !config.surroundingPairs.hasOwnProperty(ch)) {
                    return null;
                }
                const isTypingAQuoteCharacter = (0, cursorCommon_1.isQuote)(ch);
                for (const composition of compositions) {
                    if (composition.deletedSelectionStart !== 0 || composition.deletedSelectionEnd !== composition.deletedText.length) {
                        // more text was deleted than was selected, so this could not have been a surround selection
                        return null;
                    }
                    if (/^[ \t]+$/.test(composition.deletedText)) {
                        // deleted text was only whitespace
                        return null;
                    }
                    if (isTypingAQuoteCharacter && (0, cursorCommon_1.isQuote)(composition.deletedText)) {
                        // deleted text was a quote
                        return null;
                    }
                }
                const positions = [];
                for (const selection of selections) {
                    if (!selection.isEmpty()) {
                        return null;
                    }
                    positions.push(selection.getPosition());
                }
                if (positions.length !== compositions.length) {
                    return null;
                }
                const commands = [];
                for (let i = 0, len = positions.length; i < len; i++) {
                    commands.push(new surroundSelectionCommand_1.CompositionSurroundSelectionCommand(positions[i], compositions[i].deletedText, config.surroundingPairs[ch]));
                }
                return new cursorCommon_1.EditOperationResult(4 /* EditOperationType.TypingOther */, commands, {
                    shouldPushStackElementBefore: true,
                    shouldPushStackElementAfter: false
                });
            }
            const autoClosingOvertypeEdits = cursorTypeEditOperations_1.AutoClosingOvertypeWithInterceptorsOperation.getEdits(config, model, selections, autoClosedCharacters, ch);
            if (autoClosingOvertypeEdits !== undefined) {
                return autoClosingOvertypeEdits;
            }
            const autoClosingOpenCharEdits = cursorTypeEditOperations_1.AutoClosingOpenCharTypeOperation.getEdits(config, model, selections, ch, true, false);
            if (autoClosingOpenCharEdits !== undefined) {
                return autoClosingOpenCharEdits;
            }
            return null;
        }
        static typeWithInterceptors(isDoingComposition, prevEditOperationType, config, model, selections, autoClosedCharacters, ch) {
            const enterEdits = cursorTypeEditOperations_1.EnterOperation.getEdits(config, model, selections, ch, isDoingComposition);
            if (enterEdits !== undefined) {
                return enterEdits;
            }
            const autoIndentEdits = cursorTypeEditOperations_1.AutoIndentOperation.getEdits(config, model, selections, ch, isDoingComposition);
            if (autoIndentEdits !== undefined) {
                return autoIndentEdits;
            }
            const autoClosingOverTypeEdits = cursorTypeEditOperations_1.AutoClosingOvertypeOperation.getEdits(prevEditOperationType, config, model, selections, autoClosedCharacters, ch);
            if (autoClosingOverTypeEdits !== undefined) {
                return autoClosingOverTypeEdits;
            }
            const autoClosingOpenCharEdits = cursorTypeEditOperations_1.AutoClosingOpenCharTypeOperation.getEdits(config, model, selections, ch, false, isDoingComposition);
            if (autoClosingOpenCharEdits !== undefined) {
                return autoClosingOpenCharEdits;
            }
            const surroundSelectionEdits = cursorTypeEditOperations_1.SurroundSelectionOperation.getEdits(config, model, selections, ch, isDoingComposition);
            if (surroundSelectionEdits !== undefined) {
                return surroundSelectionEdits;
            }
            const interceptorElectricCharOperation = cursorTypeEditOperations_1.InterceptorElectricCharOperation.getEdits(prevEditOperationType, config, model, selections, ch, isDoingComposition);
            if (interceptorElectricCharOperation !== undefined) {
                return interceptorElectricCharOperation;
            }
            return cursorTypeEditOperations_1.SimpleCharacterTypeOperation.getEdits(prevEditOperationType, selections, ch);
        }
        static typeWithoutInterceptors(prevEditOperationType, config, model, selections, str) {
            return cursorTypeEditOperations_1.TypeWithoutInterceptorsOperation.getEdits(prevEditOperationType, selections, str);
        }
    }
    exports.TypeOperations = TypeOperations;
    class CompositionOutcome {
        constructor(deletedText, deletedSelectionStart, deletedSelectionEnd, insertedText, insertedSelectionStart, insertedSelectionEnd) {
            this.deletedText = deletedText;
            this.deletedSelectionStart = deletedSelectionStart;
            this.deletedSelectionEnd = deletedSelectionEnd;
            this.insertedText = insertedText;
            this.insertedSelectionStart = insertedSelectionStart;
            this.insertedSelectionEnd = insertedSelectionEnd;
        }
    }
    exports.CompositionOutcome = CompositionOutcome;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[706/*vs/editor/common/cursor/cursor*/], __M([1/*require*/,0/*exports*/,8/*vs/base/common/errors*/,11/*vs/base/common/strings*/,567/*vs/editor/common/cursor/cursorCollection*/,76/*vs/editor/common/cursorCommon*/,556/*vs/editor/common/cursor/cursorContext*/,234/*vs/editor/common/cursor/cursorDeleteOperations*/,276/*vs/editor/common/cursor/cursorTypeOperations*/,213/*vs/editor/common/cursor/cursorTypeEditOperations*/,4/*vs/editor/common/core/range*/,23/*vs/editor/common/core/selection*/,132/*vs/editor/common/textModelEvents*/,243/*vs/editor/common/viewEvents*/,2/*vs/base/common/lifecycle*/,244/*vs/editor/common/viewModelEventDispatcher*/]), function (require, exports, errors_1, strings, cursorCollection_1, cursorCommon_1, cursorContext_1, cursorDeleteOperations_1, cursorTypeOperations_1, cursorTypeEditOperations_1, range_1, selection_1, textModelEvents_1, viewEvents_1, lifecycle_1, viewModelEventDispatcher_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CommandExecutor = exports.CursorsController = void 0;
    class CursorsController extends lifecycle_1.Disposable {
        constructor(model, viewModel, coordinatesConverter, cursorConfig) {
            super();
            this._model = model;
            this._knownModelVersionId = this._model.getVersionId();
            this._viewModel = viewModel;
            this._coordinatesConverter = coordinatesConverter;
            this.context = new cursorContext_1.CursorContext(this._model, this._viewModel, this._coordinatesConverter, cursorConfig);
            this._cursors = new cursorCollection_1.CursorCollection(this.context);
            this._hasFocus = false;
            this._isHandling = false;
            this._compositionState = null;
            this._columnSelectData = null;
            this._autoClosedActions = [];
            this._prevEditOperationType = 0 /* EditOperationType.Other */;
        }
        dispose() {
            this._cursors.dispose();
            this._autoClosedActions = (0, lifecycle_1.dispose)(this._autoClosedActions);
            super.dispose();
        }
        updateConfiguration(cursorConfig) {
            this.context = new cursorContext_1.CursorContext(this._model, this._viewModel, this._coordinatesConverter, cursorConfig);
            this._cursors.updateContext(this.context);
        }
        onLineMappingChanged(eventsCollector) {
            if (this._knownModelVersionId !== this._model.getVersionId()) {
                // There are model change events that I didn't yet receive.
                //
                // This can happen when editing the model, and the view model receives the change events first,
                // and the view model emits line mapping changed events, all before the cursor gets a chance to
                // recover from markers.
                //
                // The model change listener above will be called soon and we'll ensure a valid cursor state there.
                return;
            }
            // Ensure valid state
            this.setStates(eventsCollector, 'viewModel', 0 /* CursorChangeReason.NotSet */, this.getCursorStates());
        }
        setHasFocus(hasFocus) {
            this._hasFocus = hasFocus;
        }
        _validateAutoClosedActions() {
            if (this._autoClosedActions.length > 0) {
                const selections = this._cursors.getSelections();
                for (let i = 0; i < this._autoClosedActions.length; i++) {
                    const autoClosedAction = this._autoClosedActions[i];
                    if (!autoClosedAction.isValid(selections)) {
                        autoClosedAction.dispose();
                        this._autoClosedActions.splice(i, 1);
                        i--;
                    }
                }
            }
        }
        // ------ some getters/setters
        getPrimaryCursorState() {
            return this._cursors.getPrimaryCursor();
        }
        getLastAddedCursorIndex() {
            return this._cursors.getLastAddedCursorIndex();
        }
        getCursorStates() {
            return this._cursors.getAll();
        }
        setStates(eventsCollector, source, reason, states) {
            let reachedMaxCursorCount = false;
            const multiCursorLimit = this.context.cursorConfig.multiCursorLimit;
            if (states !== null && states.length > multiCursorLimit) {
                states = states.slice(0, multiCursorLimit);
                reachedMaxCursorCount = true;
            }
            const oldState = CursorModelState.from(this._model, this);
            this._cursors.setStates(states);
            this._cursors.normalize();
            this._columnSelectData = null;
            this._validateAutoClosedActions();
            return this._emitStateChangedIfNecessary(eventsCollector, source, reason, oldState, reachedMaxCursorCount);
        }
        setCursorColumnSelectData(columnSelectData) {
            this._columnSelectData = columnSelectData;
        }
        revealAll(eventsCollector, source, minimalReveal, verticalType, revealHorizontal, scrollType) {
            const viewPositions = this._cursors.getViewPositions();
            let revealViewRange = null;
            let revealViewSelections = null;
            if (viewPositions.length > 1) {
                revealViewSelections = this._cursors.getViewSelections();
            }
            else {
                revealViewRange = range_1.Range.fromPositions(viewPositions[0], viewPositions[0]);
            }
            eventsCollector.emitViewEvent(new viewEvents_1.ViewRevealRangeRequestEvent(source, minimalReveal, revealViewRange, revealViewSelections, verticalType, revealHorizontal, scrollType));
        }
        revealPrimary(eventsCollector, source, minimalReveal, verticalType, revealHorizontal, scrollType) {
            const primaryCursor = this._cursors.getPrimaryCursor();
            const revealViewSelections = [primaryCursor.viewState.selection];
            eventsCollector.emitViewEvent(new viewEvents_1.ViewRevealRangeRequestEvent(source, minimalReveal, null, revealViewSelections, verticalType, revealHorizontal, scrollType));
        }
        saveState() {
            const result = [];
            const selections = this._cursors.getSelections();
            for (let i = 0, len = selections.length; i < len; i++) {
                const selection = selections[i];
                result.push({
                    inSelectionMode: !selection.isEmpty(),
                    selectionStart: {
                        lineNumber: selection.selectionStartLineNumber,
                        column: selection.selectionStartColumn,
                    },
                    position: {
                        lineNumber: selection.positionLineNumber,
                        column: selection.positionColumn,
                    }
                });
            }
            return result;
        }
        restoreState(eventsCollector, states) {
            const desiredSelections = [];
            for (let i = 0, len = states.length; i < len; i++) {
                const state = states[i];
                let positionLineNumber = 1;
                let positionColumn = 1;
                // Avoid missing properties on the literal
                if (state.position && state.position.lineNumber) {
                    positionLineNumber = state.position.lineNumber;
                }
                if (state.position && state.position.column) {
                    positionColumn = state.position.column;
                }
                let selectionStartLineNumber = positionLineNumber;
                let selectionStartColumn = positionColumn;
                // Avoid missing properties on the literal
                if (state.selectionStart && state.selectionStart.lineNumber) {
                    selectionStartLineNumber = state.selectionStart.lineNumber;
                }
                if (state.selectionStart && state.selectionStart.column) {
                    selectionStartColumn = state.selectionStart.column;
                }
                desiredSelections.push({
                    selectionStartLineNumber: selectionStartLineNumber,
                    selectionStartColumn: selectionStartColumn,
                    positionLineNumber: positionLineNumber,
                    positionColumn: positionColumn
                });
            }
            this.setStates(eventsCollector, 'restoreState', 0 /* CursorChangeReason.NotSet */, cursorCommon_1.CursorState.fromModelSelections(desiredSelections));
            this.revealAll(eventsCollector, 'restoreState', false, 0 /* VerticalRevealType.Simple */, true, 1 /* editorCommon.ScrollType.Immediate */);
        }
        onModelContentChanged(eventsCollector, event) {
            if (event instanceof textModelEvents_1.ModelInjectedTextChangedEvent) {
                // If injected texts change, the view positions of all cursors need to be updated.
                if (this._isHandling) {
                    // The view positions will be updated when handling finishes
                    return;
                }
                // setStates might remove markers, which could trigger a decoration change.
                // If there are injected text decorations for that line, `onModelContentChanged` is emitted again
                // and an endless recursion happens.
                // _isHandling prevents that.
                this._isHandling = true;
                try {
                    this.setStates(eventsCollector, 'modelChange', 0 /* CursorChangeReason.NotSet */, this.getCursorStates());
                }
                finally {
                    this._isHandling = false;
                }
            }
            else {
                const e = event.rawContentChangedEvent;
                this._knownModelVersionId = e.versionId;
                if (this._isHandling) {
                    return;
                }
                const hadFlushEvent = e.containsEvent(1 /* RawContentChangedType.Flush */);
                this._prevEditOperationType = 0 /* EditOperationType.Other */;
                if (hadFlushEvent) {
                    // a model.setValue() was called
                    this._cursors.dispose();
                    this._cursors = new cursorCollection_1.CursorCollection(this.context);
                    this._validateAutoClosedActions();
                    this._emitStateChangedIfNecessary(eventsCollector, 'model', 1 /* CursorChangeReason.ContentFlush */, null, false);
                }
                else {
                    if (this._hasFocus && e.resultingSelection && e.resultingSelection.length > 0) {
                        const cursorState = cursorCommon_1.CursorState.fromModelSelections(e.resultingSelection);
                        if (this.setStates(eventsCollector, 'modelChange', e.isUndoing ? 5 /* CursorChangeReason.Undo */ : e.isRedoing ? 6 /* CursorChangeReason.Redo */ : 2 /* CursorChangeReason.RecoverFromMarkers */, cursorState)) {
                            this.revealAll(eventsCollector, 'modelChange', false, 0 /* VerticalRevealType.Simple */, true, 0 /* editorCommon.ScrollType.Smooth */);
                        }
                    }
                    else {
                        const selectionsFromMarkers = this._cursors.readSelectionFromMarkers();
                        this.setStates(eventsCollector, 'modelChange', 2 /* CursorChangeReason.RecoverFromMarkers */, cursorCommon_1.CursorState.fromModelSelections(selectionsFromMarkers));
                    }
                }
            }
        }
        getSelection() {
            return this._cursors.getPrimaryCursor().modelState.selection;
        }
        getTopMostViewPosition() {
            return this._cursors.getTopMostViewPosition();
        }
        getBottomMostViewPosition() {
            return this._cursors.getBottomMostViewPosition();
        }
        getCursorColumnSelectData() {
            if (this._columnSelectData) {
                return this._columnSelectData;
            }
            const primaryCursor = this._cursors.getPrimaryCursor();
            const viewSelectionStart = primaryCursor.viewState.selectionStart.getStartPosition();
            const viewPosition = primaryCursor.viewState.position;
            return {
                isReal: false,
                fromViewLineNumber: viewSelectionStart.lineNumber,
                fromViewVisualColumn: this.context.cursorConfig.visibleColumnFromColumn(this._viewModel, viewSelectionStart),
                toViewLineNumber: viewPosition.lineNumber,
                toViewVisualColumn: this.context.cursorConfig.visibleColumnFromColumn(this._viewModel, viewPosition),
            };
        }
        getSelections() {
            return this._cursors.getSelections();
        }
        setSelections(eventsCollector, source, selections, reason) {
            this.setStates(eventsCollector, source, reason, cursorCommon_1.CursorState.fromModelSelections(selections));
        }
        getPrevEditOperationType() {
            return this._prevEditOperationType;
        }
        setPrevEditOperationType(type) {
            this._prevEditOperationType = type;
        }
        // ------ auxiliary handling logic
        _pushAutoClosedAction(autoClosedCharactersRanges, autoClosedEnclosingRanges) {
            const autoClosedCharactersDeltaDecorations = [];
            const autoClosedEnclosingDeltaDecorations = [];
            for (let i = 0, len = autoClosedCharactersRanges.length; i < len; i++) {
                autoClosedCharactersDeltaDecorations.push({
                    range: autoClosedCharactersRanges[i],
                    options: {
                        description: 'auto-closed-character',
                        inlineClassName: 'auto-closed-character',
                        stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */
                    }
                });
                autoClosedEnclosingDeltaDecorations.push({
                    range: autoClosedEnclosingRanges[i],
                    options: {
                        description: 'auto-closed-enclosing',
                        stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */
                    }
                });
            }
            const autoClosedCharactersDecorations = this._model.deltaDecorations([], autoClosedCharactersDeltaDecorations);
            const autoClosedEnclosingDecorations = this._model.deltaDecorations([], autoClosedEnclosingDeltaDecorations);
            this._autoClosedActions.push(new AutoClosedAction(this._model, autoClosedCharactersDecorations, autoClosedEnclosingDecorations));
        }
        _executeEditOperation(opResult) {
            if (!opResult) {
                // Nothing to execute
                return;
            }
            if (opResult.shouldPushStackElementBefore) {
                this._model.pushStackElement();
            }
            const result = CommandExecutor.executeCommands(this._model, this._cursors.getSelections(), opResult.commands);
            if (result) {
                // The commands were applied correctly
                this._interpretCommandResult(result);
                // Check for auto-closing closed characters
                const autoClosedCharactersRanges = [];
                const autoClosedEnclosingRanges = [];
                for (let i = 0; i < opResult.commands.length; i++) {
                    const command = opResult.commands[i];
                    if (command instanceof cursorTypeEditOperations_1.BaseTypeWithAutoClosingCommand && command.enclosingRange && command.closeCharacterRange) {
                        autoClosedCharactersRanges.push(command.closeCharacterRange);
                        autoClosedEnclosingRanges.push(command.enclosingRange);
                    }
                }
                if (autoClosedCharactersRanges.length > 0) {
                    this._pushAutoClosedAction(autoClosedCharactersRanges, autoClosedEnclosingRanges);
                }
                this._prevEditOperationType = opResult.type;
            }
            if (opResult.shouldPushStackElementAfter) {
                this._model.pushStackElement();
            }
        }
        _interpretCommandResult(cursorState) {
            if (!cursorState || cursorState.length === 0) {
                cursorState = this._cursors.readSelectionFromMarkers();
            }
            this._columnSelectData = null;
            this._cursors.setSelections(cursorState);
            this._cursors.normalize();
        }
        // -----------------------------------------------------------------------------------------------------------
        // ----- emitting events
        _emitStateChangedIfNecessary(eventsCollector, source, reason, oldState, reachedMaxCursorCount) {
            const newState = CursorModelState.from(this._model, this);
            if (newState.equals(oldState)) {
                return false;
            }
            const selections = this._cursors.getSelections();
            const viewSelections = this._cursors.getViewSelections();
            // Let the view get the event first.
            eventsCollector.emitViewEvent(new viewEvents_1.ViewCursorStateChangedEvent(viewSelections, selections, reason));
            // Only after the view has been notified, let the rest of the world know...
            if (!oldState
                || oldState.cursorState.length !== newState.cursorState.length
                || newState.cursorState.some((newCursorState, i) => !newCursorState.modelState.equals(oldState.cursorState[i].modelState))) {
                const oldSelections = oldState ? oldState.cursorState.map(s => s.modelState.selection) : null;
                const oldModelVersionId = oldState ? oldState.modelVersionId : 0;
                eventsCollector.emitOutgoingEvent(new viewModelEventDispatcher_1.CursorStateChangedEvent(oldSelections, selections, oldModelVersionId, newState.modelVersionId, source || 'keyboard', reason, reachedMaxCursorCount));
            }
            return true;
        }
        // -----------------------------------------------------------------------------------------------------------
        // ----- handlers beyond this point
        _findAutoClosingPairs(edits) {
            if (!edits.length) {
                return null;
            }
            const indices = [];
            for (let i = 0, len = edits.length; i < len; i++) {
                const edit = edits[i];
                if (!edit.text || edit.text.indexOf('\n') >= 0) {
                    return null;
                }
                const m = edit.text.match(/([)\]}>'"`])([^)\]}>'"`]*)$/);
                if (!m) {
                    return null;
                }
                const closeChar = m[1];
                const autoClosingPairsCandidates = this.context.cursorConfig.autoClosingPairs.autoClosingPairsCloseSingleChar.get(closeChar);
                if (!autoClosingPairsCandidates || autoClosingPairsCandidates.length !== 1) {
                    return null;
                }
                const openChar = autoClosingPairsCandidates[0].open;
                const closeCharIndex = edit.text.length - m[2].length - 1;
                const openCharIndex = edit.text.lastIndexOf(openChar, closeCharIndex - 1);
                if (openCharIndex === -1) {
                    return null;
                }
                indices.push([openCharIndex, closeCharIndex]);
            }
            return indices;
        }
        executeEdits(eventsCollector, source, edits, cursorStateComputer) {
            let autoClosingIndices = null;
            if (source === 'snippet') {
                autoClosingIndices = this._findAutoClosingPairs(edits);
            }
            if (autoClosingIndices) {
                edits[0]._isTracked = true;
            }
            const autoClosedCharactersRanges = [];
            const autoClosedEnclosingRanges = [];
            const selections = this._model.pushEditOperations(this.getSelections(), edits, (undoEdits) => {
                if (autoClosingIndices) {
                    for (let i = 0, len = autoClosingIndices.length; i < len; i++) {
                        const [openCharInnerIndex, closeCharInnerIndex] = autoClosingIndices[i];
                        const undoEdit = undoEdits[i];
                        const lineNumber = undoEdit.range.startLineNumber;
                        const openCharIndex = undoEdit.range.startColumn - 1 + openCharInnerIndex;
                        const closeCharIndex = undoEdit.range.startColumn - 1 + closeCharInnerIndex;
                        autoClosedCharactersRanges.push(new range_1.Range(lineNumber, closeCharIndex + 1, lineNumber, closeCharIndex + 2));
                        autoClosedEnclosingRanges.push(new range_1.Range(lineNumber, openCharIndex + 1, lineNumber, closeCharIndex + 2));
                    }
                }
                const selections = cursorStateComputer(undoEdits);
                if (selections) {
                    // Don't recover the selection from markers because
                    // we know what it should be.
                    this._isHandling = true;
                }
                return selections;
            });
            if (selections) {
                this._isHandling = false;
                this.setSelections(eventsCollector, source, selections, 0 /* CursorChangeReason.NotSet */);
            }
            if (autoClosedCharactersRanges.length > 0) {
                this._pushAutoClosedAction(autoClosedCharactersRanges, autoClosedEnclosingRanges);
            }
        }
        _executeEdit(callback, eventsCollector, source, cursorChangeReason = 0 /* CursorChangeReason.NotSet */) {
            if (this.context.cursorConfig.readOnly) {
                // we cannot edit when read only...
                return;
            }
            const oldState = CursorModelState.from(this._model, this);
            this._cursors.stopTrackingSelections();
            this._isHandling = true;
            try {
                this._cursors.ensureValidState();
                callback();
            }
            catch (err) {
                (0, errors_1.onUnexpectedError)(err);
            }
            this._isHandling = false;
            this._cursors.startTrackingSelections();
            this._validateAutoClosedActions();
            if (this._emitStateChangedIfNecessary(eventsCollector, source, cursorChangeReason, oldState, false)) {
                this.revealAll(eventsCollector, source, false, 0 /* VerticalRevealType.Simple */, true, 0 /* editorCommon.ScrollType.Smooth */);
            }
        }
        getAutoClosedCharacters() {
            return AutoClosedAction.getAllAutoClosedCharacters(this._autoClosedActions);
        }
        startComposition(eventsCollector) {
            this._compositionState = new CompositionState(this._model, this.getSelections());
        }
        endComposition(eventsCollector, source) {
            const compositionOutcome = this._compositionState ? this._compositionState.deduceOutcome(this._model, this.getSelections()) : null;
            this._compositionState = null;
            this._executeEdit(() => {
                if (source === 'keyboard') {
                    // composition finishes, let's check if we need to auto complete if necessary.
                    this._executeEditOperation(cursorTypeOperations_1.TypeOperations.compositionEndWithInterceptors(this._prevEditOperationType, this.context.cursorConfig, this._model, compositionOutcome, this.getSelections(), this.getAutoClosedCharacters()));
                }
            }, eventsCollector, source);
        }
        type(eventsCollector, text, source) {
            this._executeEdit(() => {
                if (source === 'keyboard') {
                    // If this event is coming straight from the keyboard, look for electric characters and enter
                    const len = text.length;
                    let offset = 0;
                    while (offset < len) {
                        const charLength = strings.nextCharLength(text, offset);
                        const chr = text.substr(offset, charLength);
                        // Here we must interpret each typed character individually
                        this._executeEditOperation(cursorTypeOperations_1.TypeOperations.typeWithInterceptors(!!this._compositionState, this._prevEditOperationType, this.context.cursorConfig, this._model, this.getSelections(), this.getAutoClosedCharacters(), chr));
                        offset += charLength;
                    }
                }
                else {
                    this._executeEditOperation(cursorTypeOperations_1.TypeOperations.typeWithoutInterceptors(this._prevEditOperationType, this.context.cursorConfig, this._model, this.getSelections(), text));
                }
            }, eventsCollector, source);
        }
        compositionType(eventsCollector, text, replacePrevCharCnt, replaceNextCharCnt, positionDelta, source) {
            if (text.length === 0 && replacePrevCharCnt === 0 && replaceNextCharCnt === 0) {
                // this edit is a no-op
                if (positionDelta !== 0) {
                    // but it still wants to move the cursor
                    const newSelections = this.getSelections().map(selection => {
                        const position = selection.getPosition();
                        return new selection_1.Selection(position.lineNumber, position.column + positionDelta, position.lineNumber, position.column + positionDelta);
                    });
                    this.setSelections(eventsCollector, source, newSelections, 0 /* CursorChangeReason.NotSet */);
                }
                return;
            }
            this._executeEdit(() => {
                this._executeEditOperation(cursorTypeOperations_1.TypeOperations.compositionType(this._prevEditOperationType, this.context.cursorConfig, this._model, this.getSelections(), text, replacePrevCharCnt, replaceNextCharCnt, positionDelta));
            }, eventsCollector, source);
        }
        paste(eventsCollector, text, pasteOnNewLine, multicursorText, source) {
            this._executeEdit(() => {
                this._executeEditOperation(cursorTypeOperations_1.TypeOperations.paste(this.context.cursorConfig, this._model, this.getSelections(), text, pasteOnNewLine, multicursorText || []));
            }, eventsCollector, source, 4 /* CursorChangeReason.Paste */);
        }
        cut(eventsCollector, source) {
            this._executeEdit(() => {
                this._executeEditOperation(cursorDeleteOperations_1.DeleteOperations.cut(this.context.cursorConfig, this._model, this.getSelections()));
            }, eventsCollector, source);
        }
        executeCommand(eventsCollector, command, source) {
            this._executeEdit(() => {
                this._cursors.killSecondaryCursors();
                this._executeEditOperation(new cursorCommon_1.EditOperationResult(0 /* EditOperationType.Other */, [command], {
                    shouldPushStackElementBefore: false,
                    shouldPushStackElementAfter: false
                }));
            }, eventsCollector, source);
        }
        executeCommands(eventsCollector, commands, source) {
            this._executeEdit(() => {
                this._executeEditOperation(new cursorCommon_1.EditOperationResult(0 /* EditOperationType.Other */, commands, {
                    shouldPushStackElementBefore: false,
                    shouldPushStackElementAfter: false
                }));
            }, eventsCollector, source);
        }
    }
    exports.CursorsController = CursorsController;
    /**
     * A snapshot of the cursor and the model state
     */
    class CursorModelState {
        static from(model, cursor) {
            return new CursorModelState(model.getVersionId(), cursor.getCursorStates());
        }
        constructor(modelVersionId, cursorState) {
            this.modelVersionId = modelVersionId;
            this.cursorState = cursorState;
        }
        equals(other) {
            if (!other) {
                return false;
            }
            if (this.modelVersionId !== other.modelVersionId) {
                return false;
            }
            if (this.cursorState.length !== other.cursorState.length) {
                return false;
            }
            for (let i = 0, len = this.cursorState.length; i < len; i++) {
                if (!this.cursorState[i].equals(other.cursorState[i])) {
                    return false;
                }
            }
            return true;
        }
    }
    class AutoClosedAction {
        static getAllAutoClosedCharacters(autoClosedActions) {
            let autoClosedCharacters = [];
            for (const autoClosedAction of autoClosedActions) {
                autoClosedCharacters = autoClosedCharacters.concat(autoClosedAction.getAutoClosedCharactersRanges());
            }
            return autoClosedCharacters;
        }
        constructor(model, autoClosedCharactersDecorations, autoClosedEnclosingDecorations) {
            this._model = model;
            this._autoClosedCharactersDecorations = autoClosedCharactersDecorations;
            this._autoClosedEnclosingDecorations = autoClosedEnclosingDecorations;
        }
        dispose() {
            this._autoClosedCharactersDecorations = this._model.deltaDecorations(this._autoClosedCharactersDecorations, []);
            this._autoClosedEnclosingDecorations = this._model.deltaDecorations(this._autoClosedEnclosingDecorations, []);
        }
        getAutoClosedCharactersRanges() {
            const result = [];
            for (let i = 0; i < this._autoClosedCharactersDecorations.length; i++) {
                const decorationRange = this._model.getDecorationRange(this._autoClosedCharactersDecorations[i]);
                if (decorationRange) {
                    result.push(decorationRange);
                }
            }
            return result;
        }
        isValid(selections) {
            const enclosingRanges = [];
            for (let i = 0; i < this._autoClosedEnclosingDecorations.length; i++) {
                const decorationRange = this._model.getDecorationRange(this._autoClosedEnclosingDecorations[i]);
                if (decorationRange) {
                    enclosingRanges.push(decorationRange);
                    if (decorationRange.startLineNumber !== decorationRange.endLineNumber) {
                        // Stop tracking if the range becomes multiline...
                        return false;
                    }
                }
            }
            enclosingRanges.sort(range_1.Range.compareRangesUsingStarts);
            selections.sort(range_1.Range.compareRangesUsingStarts);
            for (let i = 0; i < selections.length; i++) {
                if (i >= enclosingRanges.length) {
                    return false;
                }
                if (!enclosingRanges[i].strictContainsRange(selections[i])) {
                    return false;
                }
            }
            return true;
        }
    }
    class CommandExecutor {
        static executeCommands(model, selectionsBefore, commands) {
            const ctx = {
                model: model,
                selectionsBefore: selectionsBefore,
                trackedRanges: [],
                trackedRangesDirection: []
            };
            const result = this._innerExecuteCommands(ctx, commands);
            for (let i = 0, len = ctx.trackedRanges.length; i < len; i++) {
                ctx.model._setTrackedRange(ctx.trackedRanges[i], null, 0 /* TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges */);
            }
            return result;
        }
        static _innerExecuteCommands(ctx, commands) {
            if (this._arrayIsEmpty(commands)) {
                return null;
            }
            const commandsData = this._getEditOperations(ctx, commands);
            if (commandsData.operations.length === 0) {
                return null;
            }
            const rawOperations = commandsData.operations;
            const loserCursorsMap = this._getLoserCursorMap(rawOperations);
            if (loserCursorsMap.hasOwnProperty('0')) {
                // These commands are very messed up
                console.warn('Ignoring commands');
                return null;
            }
            // Remove operations belonging to losing cursors
            const filteredOperations = [];
            for (let i = 0, len = rawOperations.length; i < len; i++) {
                if (!loserCursorsMap.hasOwnProperty(rawOperations[i].identifier.major.toString())) {
                    filteredOperations.push(rawOperations[i]);
                }
            }
            // TODO@Alex: find a better way to do this.
            // give the hint that edit operations are tracked to the model
            if (commandsData.hadTrackedEditOperation && filteredOperations.length > 0) {
                filteredOperations[0]._isTracked = true;
            }
            let selectionsAfter = ctx.model.pushEditOperations(ctx.selectionsBefore, filteredOperations, (inverseEditOperations) => {
                const groupedInverseEditOperations = [];
                for (let i = 0; i < ctx.selectionsBefore.length; i++) {
                    groupedInverseEditOperations[i] = [];
                }
                for (const op of inverseEditOperations) {
                    if (!op.identifier) {
                        // perhaps auto whitespace trim edits
                        continue;
                    }
                    groupedInverseEditOperations[op.identifier.major].push(op);
                }
                const minorBasedSorter = (a, b) => {
                    return a.identifier.minor - b.identifier.minor;
                };
                const cursorSelections = [];
                for (let i = 0; i < ctx.selectionsBefore.length; i++) {
                    if (groupedInverseEditOperations[i].length > 0) {
                        groupedInverseEditOperations[i].sort(minorBasedSorter);
                        cursorSelections[i] = commands[i].computeCursorState(ctx.model, {
                            getInverseEditOperations: () => {
                                return groupedInverseEditOperations[i];
                            },
                            getTrackedSelection: (id) => {
                                const idx = parseInt(id, 10);
                                const range = ctx.model._getTrackedRange(ctx.trackedRanges[idx]);
                                if (ctx.trackedRangesDirection[idx] === 0 /* SelectionDirection.LTR */) {
                                    return new selection_1.Selection(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn);
                                }
                                return new selection_1.Selection(range.endLineNumber, range.endColumn, range.startLineNumber, range.startColumn);
                            }
                        });
                    }
                    else {
                        cursorSelections[i] = ctx.selectionsBefore[i];
                    }
                }
                return cursorSelections;
            });
            if (!selectionsAfter) {
                selectionsAfter = ctx.selectionsBefore;
            }
            // Extract losing cursors
            const losingCursors = [];
            for (const losingCursorIndex in loserCursorsMap) {
                if (loserCursorsMap.hasOwnProperty(losingCursorIndex)) {
                    losingCursors.push(parseInt(losingCursorIndex, 10));
                }
            }
            // Sort losing cursors descending
            losingCursors.sort((a, b) => {
                return b - a;
            });
            // Remove losing cursors
            for (const losingCursor of losingCursors) {
                selectionsAfter.splice(losingCursor, 1);
            }
            return selectionsAfter;
        }
        static _arrayIsEmpty(commands) {
            for (let i = 0, len = commands.length; i < len; i++) {
                if (commands[i]) {
                    return false;
                }
            }
            return true;
        }
        static _getEditOperations(ctx, commands) {
            let operations = [];
            let hadTrackedEditOperation = false;
            for (let i = 0, len = commands.length; i < len; i++) {
                const command = commands[i];
                if (command) {
                    const r = this._getEditOperationsFromCommand(ctx, i, command);
                    operations = operations.concat(r.operations);
                    hadTrackedEditOperation = hadTrackedEditOperation || r.hadTrackedEditOperation;
                }
            }
            return {
                operations: operations,
                hadTrackedEditOperation: hadTrackedEditOperation
            };
        }
        static _getEditOperationsFromCommand(ctx, majorIdentifier, command) {
            // This method acts as a transaction, if the command fails
            // everything it has done is ignored
            const operations = [];
            let operationMinor = 0;
            const addEditOperation = (range, text, forceMoveMarkers = false) => {
                if (range_1.Range.isEmpty(range) && text === '') {
                    // This command wants to add a no-op => no thank you
                    return;
                }
                operations.push({
                    identifier: {
                        major: majorIdentifier,
                        minor: operationMinor++
                    },
                    range: range,
                    text: text,
                    forceMoveMarkers: forceMoveMarkers,
                    isAutoWhitespaceEdit: command.insertsAutoWhitespace
                });
            };
            let hadTrackedEditOperation = false;
            const addTrackedEditOperation = (selection, text, forceMoveMarkers) => {
                hadTrackedEditOperation = true;
                addEditOperation(selection, text, forceMoveMarkers);
            };
            const trackSelection = (_selection, trackPreviousOnEmpty) => {
                const selection = selection_1.Selection.liftSelection(_selection);
                let stickiness;
                if (selection.isEmpty()) {
                    if (typeof trackPreviousOnEmpty === 'boolean') {
                        if (trackPreviousOnEmpty) {
                            stickiness = 2 /* TrackedRangeStickiness.GrowsOnlyWhenTypingBefore */;
                        }
                        else {
                            stickiness = 3 /* TrackedRangeStickiness.GrowsOnlyWhenTypingAfter */;
                        }
                    }
                    else {
                        // Try to lock it with surrounding text
                        const maxLineColumn = ctx.model.getLineMaxColumn(selection.startLineNumber);
                        if (selection.startColumn === maxLineColumn) {
                            stickiness = 2 /* TrackedRangeStickiness.GrowsOnlyWhenTypingBefore */;
                        }
                        else {
                            stickiness = 3 /* TrackedRangeStickiness.GrowsOnlyWhenTypingAfter */;
                        }
                    }
                }
                else {
                    stickiness = 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */;
                }
                const l = ctx.trackedRanges.length;
                const id = ctx.model._setTrackedRange(null, selection, stickiness);
                ctx.trackedRanges[l] = id;
                ctx.trackedRangesDirection[l] = selection.getDirection();
                return l.toString();
            };
            const editOperationBuilder = {
                addEditOperation: addEditOperation,
                addTrackedEditOperation: addTrackedEditOperation,
                trackSelection: trackSelection
            };
            try {
                command.getEditOperations(ctx.model, editOperationBuilder);
            }
            catch (e) {
                // TODO@Alex use notification service if this should be user facing
                // e.friendlyMessage = nls.localize('corrupt.commands', "Unexpected exception while executing command.");
                (0, errors_1.onUnexpectedError)(e);
                return {
                    operations: [],
                    hadTrackedEditOperation: false
                };
            }
            return {
                operations: operations,
                hadTrackedEditOperation: hadTrackedEditOperation
            };
        }
        static _getLoserCursorMap(operations) {
            // This is destructive on the array
            operations = operations.slice(0);
            // Sort operations with last one first
            operations.sort((a, b) => {
                // Note the minus!
                return -(range_1.Range.compareRangesUsingEnds(a.range, b.range));
            });
            // Operations can not overlap!
            const loserCursorsMap = {};
            for (let i = 1; i < operations.length; i++) {
                const previousOp = operations[i - 1];
                const currentOp = operations[i];
                if (range_1.Range.getStartPosition(previousOp.range).isBefore(range_1.Range.getEndPosition(currentOp.range))) {
                    let loserMajor;
                    if (previousOp.identifier.major > currentOp.identifier.major) {
                        // previousOp loses the battle
                        loserMajor = previousOp.identifier.major;
                    }
                    else {
                        loserMajor = currentOp.identifier.major;
                    }
                    loserCursorsMap[loserMajor.toString()] = true;
                    for (let j = 0; j < operations.length; j++) {
                        if (operations[j].identifier.major === loserMajor) {
                            operations.splice(j, 1);
                            if (j < i) {
                                i--;
                            }
                            j--;
                        }
                    }
                    if (i > 0) {
                        i--;
                    }
                }
            }
            return loserCursorsMap;
        }
    }
    exports.CommandExecutor = CommandExecutor;
    class CompositionLineState {
        constructor(text, startSelection, endSelection) {
            this.text = text;
            this.startSelection = startSelection;
            this.endSelection = endSelection;
        }
    }
    class CompositionState {
        static _capture(textModel, selections) {
            const result = [];
            for (const selection of selections) {
                if (selection.startLineNumber !== selection.endLineNumber) {
                    return null;
                }
                result.push(new CompositionLineState(textModel.getLineContent(selection.startLineNumber), selection.startColumn - 1, selection.endColumn - 1));
            }
            return result;
        }
        constructor(textModel, selections) {
            this._original = CompositionState._capture(textModel, selections);
        }
        /**
         * Returns the inserted text during this composition.
         * If the composition resulted in existing text being changed (i.e. not a pure insertion) it returns null.
         */
        deduceOutcome(textModel, selections) {
            if (!this._original) {
                return null;
            }
            const current = CompositionState._capture(textModel, selections);
            if (!current) {
                return null;
            }
            if (this._original.length !== current.length) {
                return null;
            }
            const result = [];
            for (let i = 0, len = this._original.length; i < len; i++) {
                result.push(CompositionState._deduceOutcome(this._original[i], current[i]));
            }
            return result;
        }
        static _deduceOutcome(original, current) {
            const commonPrefix = Math.min(original.startSelection, current.startSelection, strings.commonPrefixLength(original.text, current.text));
            const commonSuffix = Math.min(original.text.length - original.endSelection, current.text.length - current.endSelection, strings.commonSuffixLength(original.text, current.text));
            const deletedText = original.text.substring(commonPrefix, original.text.length - commonSuffix);
            const insertedText = current.text.substring(commonPrefix, current.text.length - commonSuffix);
            return new cursorTypeOperations_1.CompositionOutcome(deletedText, original.startSelection - commonPrefix, original.endSelection - commonPrefix, insertedText, current.startSelection - commonPrefix, current.endSelection - commonPrefix);
        }
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[707/*vs/editor/common/model/tokenizationTextModelPart*/], __M([1/*require*/,0/*exports*/,8/*vs/base/common/errors*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,145/*vs/editor/common/core/eolCounter*/,55/*vs/editor/common/core/lineRange*/,9/*vs/editor/common/core/position*/,147/*vs/editor/common/core/wordHelper*/,27/*vs/editor/common/languages*/,43/*vs/editor/common/languages/language*/,36/*vs/editor/common/languages/languageConfigurationRegistry*/,323/*vs/editor/common/model/textModelPart*/,663/*vs/editor/common/model/textModelTokens*/,263/*vs/editor/common/model/tokens*/,664/*vs/editor/common/model/treeSitterTokens*/,384/*vs/editor/common/services/treeSitterParserService*/,330/*vs/editor/common/tokens/contiguousMultilineTokensBuilder*/,588/*vs/editor/common/tokens/contiguousTokensStore*/,590/*vs/editor/common/tokens/sparseTokensStore*/]), function (require, exports, errors_1, event_1, lifecycle_1, eolCounter_1, lineRange_1, position_1, wordHelper_1, languages_1, language_1, languageConfigurationRegistry_1, textModelPart_1, textModelTokens_1, tokens_1, treeSitterTokens_1, treeSitterParserService_1, contiguousMultilineTokensBuilder_1, contiguousTokensStore_1, sparseTokensStore_1) {
    "use strict";
    var TokenizationTextModelPart_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.TokenizationTextModelPart = void 0;
    let TokenizationTextModelPart = TokenizationTextModelPart_1 = class TokenizationTextModelPart extends textModelPart_1.TextModelPart {
        constructor(_textModel, _bracketPairsTextModelPart, _languageId, _attachedViews, _languageService, _languageConfigurationService, _treeSitterService) {
            super();
            this._textModel = _textModel;
            this._bracketPairsTextModelPart = _bracketPairsTextModelPart;
            this._languageId = _languageId;
            this._attachedViews = _attachedViews;
            this._languageService = _languageService;
            this._languageConfigurationService = _languageConfigurationService;
            this._treeSitterService = _treeSitterService;
            this._semanticTokens = new sparseTokensStore_1.SparseTokensStore(this._languageService.languageIdCodec);
            this._onDidChangeLanguage = this._register(new event_1.Emitter());
            this.onDidChangeLanguage = this._onDidChangeLanguage.event;
            this._onDidChangeLanguageConfiguration = this._register(new event_1.Emitter());
            this.onDidChangeLanguageConfiguration = this._onDidChangeLanguageConfiguration.event;
            this._onDidChangeTokens = this._register(new event_1.Emitter());
            this.onDidChangeTokens = this._onDidChangeTokens.event;
            this._tokensDisposables = this._register(new lifecycle_1.DisposableStore());
            this._register(this._languageConfigurationService.onDidChange(e => {
                if (e.affects(this._languageId)) {
                    this._onDidChangeLanguageConfiguration.fire({});
                }
            }));
            // We just look at registry changes to determine whether to use tree sitter.
            // This means that removing a language from the setting will not cause a switch to textmate and will require a reload.
            // Adding a language to the setting will not need a reload, however.
            this._register(event_1.Event.filter(languages_1.TreeSitterTokenizationRegistry.onDidChange, (e) => e.changedLanguages.includes(this._languageId))(() => {
                this.createPreferredTokenProvider();
            }));
            this.createPreferredTokenProvider();
        }
        createGrammarTokens() {
            return this._register(new GrammarTokens(this._languageService.languageIdCodec, this._textModel, () => this._languageId, this._attachedViews));
        }
        createTreeSitterTokens() {
            return this._register(new treeSitterTokens_1.TreeSitterTokens(this._treeSitterService, this._languageService.languageIdCodec, this._textModel, () => this._languageId));
        }
        createTokens(useTreeSitter) {
            const needsReset = this._tokens !== undefined;
            this._tokens?.dispose();
            this._tokens = useTreeSitter ? this.createTreeSitterTokens() : this.createGrammarTokens();
            this._tokensDisposables.clear();
            this._tokensDisposables.add(this._tokens.onDidChangeTokens(e => {
                this._emitModelTokensChangedEvent(e);
            }));
            this._tokensDisposables.add(this._tokens.onDidChangeBackgroundTokenizationState(e => {
                this._bracketPairsTextModelPart.handleDidChangeBackgroundTokenizationState();
            }));
            if (needsReset) {
                // We need to reset the tokenization, as the new token provider otherwise won't have a chance to provide tokens until some action happens in the editor.
                this._tokens.resetTokenization();
            }
        }
        createPreferredTokenProvider() {
            if (languages_1.TreeSitterTokenizationRegistry.get(this._languageId)) {
                if (!(this._tokens instanceof treeSitterTokens_1.TreeSitterTokens)) {
                    this.createTokens(true);
                }
            }
            else {
                if (!(this._tokens instanceof GrammarTokens)) {
                    this.createTokens(false);
                }
            }
        }
        handleLanguageConfigurationServiceChange(e) {
            if (e.affects(this._languageId)) {
                this._onDidChangeLanguageConfiguration.fire({});
            }
        }
        handleDidChangeContent(e) {
            if (e.isFlush) {
                this._semanticTokens.flush();
            }
            else if (!e.isEolChange) { // We don't have to do anything on an EOL change
                for (const c of e.changes) {
                    const [eolCount, firstLineLength, lastLineLength] = (0, eolCounter_1.countEOL)(c.text);
                    this._semanticTokens.acceptEdit(c.range, eolCount, firstLineLength, lastLineLength, c.text.length > 0 ? c.text.charCodeAt(0) : 0 /* CharCode.Null */);
                }
            }
            this._tokens.handleDidChangeContent(e);
        }
        handleDidChangeAttached() {
            this._tokens.handleDidChangeAttached();
        }
        /**
         * Includes grammar and semantic tokens.
         */
        getLineTokens(lineNumber) {
            this.validateLineNumber(lineNumber);
            const syntacticTokens = this._tokens.getLineTokens(lineNumber);
            return this._semanticTokens.addSparseTokens(lineNumber, syntacticTokens);
        }
        _emitModelTokensChangedEvent(e) {
            if (!this._textModel._isDisposing()) {
                this._bracketPairsTextModelPart.handleDidChangeTokens(e);
                this._onDidChangeTokens.fire(e);
            }
        }
        // #region Grammar Tokens
        validateLineNumber(lineNumber) {
            if (lineNumber < 1 || lineNumber > this._textModel.getLineCount()) {
                throw new errors_1.BugIndicatingError('Illegal value for lineNumber');
            }
        }
        get hasTokens() {
            return this._tokens.hasTokens;
        }
        resetTokenization() {
            this._tokens.resetTokenization();
        }
        get backgroundTokenizationState() {
            return this._tokens.backgroundTokenizationState;
        }
        forceTokenization(lineNumber) {
            this.validateLineNumber(lineNumber);
            this._tokens.forceTokenization(lineNumber);
        }
        hasAccurateTokensForLine(lineNumber) {
            this.validateLineNumber(lineNumber);
            return this._tokens.hasAccurateTokensForLine(lineNumber);
        }
        isCheapToTokenize(lineNumber) {
            this.validateLineNumber(lineNumber);
            return this._tokens.isCheapToTokenize(lineNumber);
        }
        tokenizeIfCheap(lineNumber) {
            this.validateLineNumber(lineNumber);
            this._tokens.tokenizeIfCheap(lineNumber);
        }
        getTokenTypeIfInsertingCharacter(lineNumber, column, character) {
            return this._tokens.getTokenTypeIfInsertingCharacter(lineNumber, column, character);
        }
        tokenizeLineWithEdit(position, length, newText) {
            return this._tokens.tokenizeLineWithEdit(position, length, newText);
        }
        // #endregion
        // #region Semantic Tokens
        setSemanticTokens(tokens, isComplete) {
            this._semanticTokens.set(tokens, isComplete);
            this._emitModelTokensChangedEvent({
                semanticTokensApplied: tokens !== null,
                ranges: [{ fromLineNumber: 1, toLineNumber: this._textModel.getLineCount() }],
            });
        }
        hasCompleteSemanticTokens() {
            return this._semanticTokens.isComplete();
        }
        hasSomeSemanticTokens() {
            return !this._semanticTokens.isEmpty();
        }
        setPartialSemanticTokens(range, tokens) {
            if (this.hasCompleteSemanticTokens()) {
                return;
            }
            const changedRange = this._textModel.validateRange(this._semanticTokens.setPartial(range, tokens));
            this._emitModelTokensChangedEvent({
                semanticTokensApplied: true,
                ranges: [
                    {
                        fromLineNumber: changedRange.startLineNumber,
                        toLineNumber: changedRange.endLineNumber,
                    },
                ],
            });
        }
        // #endregion
        // #region Utility Methods
        getWordAtPosition(_position) {
            this.assertNotDisposed();
            const position = this._textModel.validatePosition(_position);
            const lineContent = this._textModel.getLineContent(position.lineNumber);
            const lineTokens = this.getLineTokens(position.lineNumber);
            const tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
            // (1). First try checking right biased word
            const [rbStartOffset, rbEndOffset] = TokenizationTextModelPart_1._findLanguageBoundaries(lineTokens, tokenIndex);
            const rightBiasedWord = (0, wordHelper_1.getWordAtText)(position.column, this.getLanguageConfiguration(lineTokens.getLanguageId(tokenIndex)).getWordDefinition(), lineContent.substring(rbStartOffset, rbEndOffset), rbStartOffset);
            // Make sure the result touches the original passed in position
            if (rightBiasedWord &&
                rightBiasedWord.startColumn <= _position.column &&
                _position.column <= rightBiasedWord.endColumn) {
                return rightBiasedWord;
            }
            // (2). Else, if we were at a language boundary, check the left biased word
            if (tokenIndex > 0 && rbStartOffset === position.column - 1) {
                // edge case, where `position` sits between two tokens belonging to two different languages
                const [lbStartOffset, lbEndOffset] = TokenizationTextModelPart_1._findLanguageBoundaries(lineTokens, tokenIndex - 1);
                const leftBiasedWord = (0, wordHelper_1.getWordAtText)(position.column, this.getLanguageConfiguration(lineTokens.getLanguageId(tokenIndex - 1)).getWordDefinition(), lineContent.substring(lbStartOffset, lbEndOffset), lbStartOffset);
                // Make sure the result touches the original passed in position
                if (leftBiasedWord &&
                    leftBiasedWord.startColumn <= _position.column &&
                    _position.column <= leftBiasedWord.endColumn) {
                    return leftBiasedWord;
                }
            }
            return null;
        }
        getLanguageConfiguration(languageId) {
            return this._languageConfigurationService.getLanguageConfiguration(languageId);
        }
        static _findLanguageBoundaries(lineTokens, tokenIndex) {
            const languageId = lineTokens.getLanguageId(tokenIndex);
            // go left until a different language is hit
            let startOffset = 0;
            for (let i = tokenIndex; i >= 0 && lineTokens.getLanguageId(i) === languageId; i--) {
                startOffset = lineTokens.getStartOffset(i);
            }
            // go right until a different language is hit
            let endOffset = lineTokens.getLineContent().length;
            for (let i = tokenIndex, tokenCount = lineTokens.getCount(); i < tokenCount && lineTokens.getLanguageId(i) === languageId; i++) {
                endOffset = lineTokens.getEndOffset(i);
            }
            return [startOffset, endOffset];
        }
        getWordUntilPosition(position) {
            const wordAtPosition = this.getWordAtPosition(position);
            if (!wordAtPosition) {
                return { word: '', startColumn: position.column, endColumn: position.column, };
            }
            return {
                word: wordAtPosition.word.substr(0, position.column - wordAtPosition.startColumn),
                startColumn: wordAtPosition.startColumn,
                endColumn: position.column,
            };
        }
        // #endregion
        // #region Language Id handling
        getLanguageId() {
            return this._languageId;
        }
        getLanguageIdAtPosition(lineNumber, column) {
            const position = this._textModel.validatePosition(new position_1.Position(lineNumber, column));
            const lineTokens = this.getLineTokens(position.lineNumber);
            return lineTokens.getLanguageId(lineTokens.findTokenIndexAtOffset(position.column - 1));
        }
        setLanguageId(languageId, source = 'api') {
            if (this._languageId === languageId) {
                // There's nothing to do
                return;
            }
            const e = {
                oldLanguage: this._languageId,
                newLanguage: languageId,
                source
            };
            this._languageId = languageId;
            this._bracketPairsTextModelPart.handleDidChangeLanguage(e);
            this._tokens.resetTokenization();
            this.createPreferredTokenProvider();
            this._onDidChangeLanguage.fire(e);
            this._onDidChangeLanguageConfiguration.fire({});
        }
    };
    exports.TokenizationTextModelPart = TokenizationTextModelPart;
    exports.TokenizationTextModelPart = TokenizationTextModelPart = TokenizationTextModelPart_1 = __decorate([
        __param(4, language_1.ILanguageService),
        __param(5, languageConfigurationRegistry_1.ILanguageConfigurationService),
        __param(6, treeSitterParserService_1.ITreeSitterParserService)
    ], TokenizationTextModelPart);
    class GrammarTokens extends tokens_1.AbstractTokens {
        constructor(languageIdCodec, textModel, getLanguageId, attachedViews) {
            super(languageIdCodec, textModel, getLanguageId);
            this._tokenizer = null;
            this._defaultBackgroundTokenizer = null;
            this._backgroundTokenizer = this._register(new lifecycle_1.MutableDisposable());
            this._tokens = new contiguousTokensStore_1.ContiguousTokensStore(this._languageIdCodec);
            this._debugBackgroundTokenizer = this._register(new lifecycle_1.MutableDisposable());
            this._attachedViewStates = this._register(new lifecycle_1.DisposableMap());
            this._register(languages_1.TokenizationRegistry.onDidChange((e) => {
                const languageId = this.getLanguageId();
                if (e.changedLanguages.indexOf(languageId) === -1) {
                    return;
                }
                this.resetTokenization();
            }));
            this.resetTokenization();
            this._register(attachedViews.onDidChangeVisibleRanges(({ view, state }) => {
                if (state) {
                    let existing = this._attachedViewStates.get(view);
                    if (!existing) {
                        existing = new tokens_1.AttachedViewHandler(() => this.refreshRanges(existing.lineRanges));
                        this._attachedViewStates.set(view, existing);
                    }
                    existing.handleStateChange(state);
                }
                else {
                    this._attachedViewStates.deleteAndDispose(view);
                }
            }));
        }
        resetTokenization(fireTokenChangeEvent = true) {
            this._tokens.flush();
            this._debugBackgroundTokens?.flush();
            if (this._debugBackgroundStates) {
                this._debugBackgroundStates = new textModelTokens_1.TrackingTokenizationStateStore(this._textModel.getLineCount());
            }
            if (fireTokenChangeEvent) {
                this._onDidChangeTokens.fire({
                    semanticTokensApplied: false,
                    ranges: [
                        {
                            fromLineNumber: 1,
                            toLineNumber: this._textModel.getLineCount(),
                        },
                    ],
                });
            }
            const initializeTokenization = () => {
                if (this._textModel.isTooLargeForTokenization()) {
                    return [null, null];
                }
                const tokenizationSupport = languages_1.TokenizationRegistry.get(this.getLanguageId());
                if (!tokenizationSupport) {
                    return [null, null];
                }
                let initialState;
                try {
                    initialState = tokenizationSupport.getInitialState();
                }
                catch (e) {
                    (0, errors_1.onUnexpectedError)(e);
                    return [null, null];
                }
                return [tokenizationSupport, initialState];
            };
            const [tokenizationSupport, initialState] = initializeTokenization();
            if (tokenizationSupport && initialState) {
                this._tokenizer = new textModelTokens_1.TokenizerWithStateStoreAndTextModel(this._textModel.getLineCount(), tokenizationSupport, this._textModel, this._languageIdCodec);
            }
            else {
                this._tokenizer = null;
            }
            this._backgroundTokenizer.clear();
            this._defaultBackgroundTokenizer = null;
            if (this._tokenizer) {
                const b = {
                    setTokens: (tokens) => {
                        this.setTokens(tokens);
                    },
                    backgroundTokenizationFinished: () => {
                        if (this._backgroundTokenizationState === 2 /* BackgroundTokenizationState.Completed */) {
                            // We already did a full tokenization and don't go back to progressing.
                            return;
                        }
                        const newState = 2 /* BackgroundTokenizationState.Completed */;
                        this._backgroundTokenizationState = newState;
                        this._onDidChangeBackgroundTokenizationState.fire();
                    },
                    setEndState: (lineNumber, state) => {
                        if (!this._tokenizer) {
                            return;
                        }
                        const firstInvalidEndStateLineNumber = this._tokenizer.store.getFirstInvalidEndStateLineNumber();
                        // Don't accept states for definitely valid states, the renderer is ahead of the worker!
                        if (firstInvalidEndStateLineNumber !== null && lineNumber >= firstInvalidEndStateLineNumber) {
                            this._tokenizer?.store.setEndState(lineNumber, state);
                        }
                    },
                };
                if (tokenizationSupport && tokenizationSupport.createBackgroundTokenizer && !tokenizationSupport.backgroundTokenizerShouldOnlyVerifyTokens) {
                    this._backgroundTokenizer.value = tokenizationSupport.createBackgroundTokenizer(this._textModel, b);
                }
                if (!this._backgroundTokenizer.value && !this._textModel.isTooLargeForTokenization()) {
                    this._backgroundTokenizer.value = this._defaultBackgroundTokenizer =
                        new textModelTokens_1.DefaultBackgroundTokenizer(this._tokenizer, b);
                    this._defaultBackgroundTokenizer.handleChanges();
                }
                if (tokenizationSupport?.backgroundTokenizerShouldOnlyVerifyTokens && tokenizationSupport.createBackgroundTokenizer) {
                    this._debugBackgroundTokens = new contiguousTokensStore_1.ContiguousTokensStore(this._languageIdCodec);
                    this._debugBackgroundStates = new textModelTokens_1.TrackingTokenizationStateStore(this._textModel.getLineCount());
                    this._debugBackgroundTokenizer.clear();
                    this._debugBackgroundTokenizer.value = tokenizationSupport.createBackgroundTokenizer(this._textModel, {
                        setTokens: (tokens) => {
                            this._debugBackgroundTokens?.setMultilineTokens(tokens, this._textModel);
                        },
                        backgroundTokenizationFinished() {
                            // NO OP
                        },
                        setEndState: (lineNumber, state) => {
                            this._debugBackgroundStates?.setEndState(lineNumber, state);
                        },
                    });
                }
                else {
                    this._debugBackgroundTokens = undefined;
                    this._debugBackgroundStates = undefined;
                    this._debugBackgroundTokenizer.value = undefined;
                }
            }
            this.refreshAllVisibleLineTokens();
        }
        handleDidChangeAttached() {
            this._defaultBackgroundTokenizer?.handleChanges();
        }
        handleDidChangeContent(e) {
            if (e.isFlush) {
                // Don't fire the event, as the view might not have got the text change event yet
                this.resetTokenization(false);
            }
            else if (!e.isEolChange) { // We don't have to do anything on an EOL change
                for (const c of e.changes) {
                    const [eolCount, firstLineLength] = (0, eolCounter_1.countEOL)(c.text);
                    this._tokens.acceptEdit(c.range, eolCount, firstLineLength);
                    this._debugBackgroundTokens?.acceptEdit(c.range, eolCount, firstLineLength);
                }
                this._debugBackgroundStates?.acceptChanges(e.changes);
                if (this._tokenizer) {
                    this._tokenizer.store.acceptChanges(e.changes);
                }
                this._defaultBackgroundTokenizer?.handleChanges();
            }
        }
        setTokens(tokens) {
            const { changes } = this._tokens.setMultilineTokens(tokens, this._textModel);
            if (changes.length > 0) {
                this._onDidChangeTokens.fire({ semanticTokensApplied: false, ranges: changes, });
            }
            return { changes: changes };
        }
        refreshAllVisibleLineTokens() {
            const ranges = lineRange_1.LineRange.joinMany([...this._attachedViewStates].map(([_, s]) => s.lineRanges));
            this.refreshRanges(ranges);
        }
        refreshRanges(ranges) {
            for (const range of ranges) {
                this.refreshRange(range.startLineNumber, range.endLineNumberExclusive - 1);
            }
        }
        refreshRange(startLineNumber, endLineNumber) {
            if (!this._tokenizer) {
                return;
            }
            startLineNumber = Math.max(1, Math.min(this._textModel.getLineCount(), startLineNumber));
            endLineNumber = Math.min(this._textModel.getLineCount(), endLineNumber);
            const builder = new contiguousMultilineTokensBuilder_1.ContiguousMultilineTokensBuilder();
            const { heuristicTokens } = this._tokenizer.tokenizeHeuristically(builder, startLineNumber, endLineNumber);
            const changedTokens = this.setTokens(builder.finalize());
            if (heuristicTokens) {
                // We overrode tokens with heuristically computed ones.
                // Because old states might get reused (thus stopping invalidation),
                // we have to explicitly request the tokens for the changed ranges again.
                for (const c of changedTokens.changes) {
                    this._backgroundTokenizer.value?.requestTokens(c.fromLineNumber, c.toLineNumber + 1);
                }
            }
            this._defaultBackgroundTokenizer?.checkFinished();
        }
        forceTokenization(lineNumber) {
            const builder = new contiguousMultilineTokensBuilder_1.ContiguousMultilineTokensBuilder();
            this._tokenizer?.updateTokensUntilLine(builder, lineNumber);
            this.setTokens(builder.finalize());
            this._defaultBackgroundTokenizer?.checkFinished();
        }
        hasAccurateTokensForLine(lineNumber) {
            if (!this._tokenizer) {
                return true;
            }
            return this._tokenizer.hasAccurateTokensForLine(lineNumber);
        }
        isCheapToTokenize(lineNumber) {
            if (!this._tokenizer) {
                return true;
            }
            return this._tokenizer.isCheapToTokenize(lineNumber);
        }
        getLineTokens(lineNumber) {
            const lineText = this._textModel.getLineContent(lineNumber);
            const result = this._tokens.getTokens(this._textModel.getLanguageId(), lineNumber - 1, lineText);
            if (this._debugBackgroundTokens && this._debugBackgroundStates && this._tokenizer) {
                if (this._debugBackgroundStates.getFirstInvalidEndStateLineNumberOrMax() > lineNumber && this._tokenizer.store.getFirstInvalidEndStateLineNumberOrMax() > lineNumber) {
                    const backgroundResult = this._debugBackgroundTokens.getTokens(this._textModel.getLanguageId(), lineNumber - 1, lineText);
                    if (!result.equals(backgroundResult) && this._debugBackgroundTokenizer.value?.reportMismatchingTokens) {
                        this._debugBackgroundTokenizer.value.reportMismatchingTokens(lineNumber);
                    }
                }
            }
            return result;
        }
        getTokenTypeIfInsertingCharacter(lineNumber, column, character) {
            if (!this._tokenizer) {
                return 0 /* StandardTokenType.Other */;
            }
            const position = this._textModel.validatePosition(new position_1.Position(lineNumber, column));
            this.forceTokenization(position.lineNumber);
            return this._tokenizer.getTokenTypeIfInsertingCharacter(position, character);
        }
        tokenizeLineWithEdit(position, length, newText) {
            if (!this._tokenizer) {
                return null;
            }
            const validatedPosition = this._textModel.validatePosition(position);
            this.forceTokenization(validatedPosition.lineNumber);
            return this._tokenizer.tokenizeLineWithEdit(validatedPosition, length, newText);
        }
        get hasTokens() {
            return this._tokens.hasTokens;
        }
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[708/*vs/editor/common/services/getIconClasses*/], __M([1/*require*/,0/*exports*/,42/*vs/base/common/network*/,48/*vs/base/common/resources*/,22/*vs/base/common/uri*/,70/*vs/editor/common/languages/modesRegistry*/,382/*vs/platform/files/common/files*/,30/*vs/base/common/themables*/]), function (require, exports, network_1, resources_1, uri_1, modesRegistry_1, files_1, themables_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.getIconClasses = getIconClasses;
    const fileIconDirectoryRegex = /(?:\/|^)(?:([^\/]+)\/)?([^\/]+)$/;
    function getIconClasses(modelService, languageService, resource, fileKind, icon) {
        if (themables_1.ThemeIcon.isThemeIcon(icon)) {
            return [`codicon-${icon.id}`, 'predefined-file-icon'];
        }
        if (uri_1.URI.isUri(icon)) {
            return [];
        }
        // we always set these base classes even if we do not have a path
        const classes = fileKind === files_1.FileKind.ROOT_FOLDER ? ['rootfolder-icon'] : fileKind === files_1.FileKind.FOLDER ? ['folder-icon'] : ['file-icon'];
        if (resource) {
            // Get the path and name of the resource. For data-URIs, we need to parse specially
            let name;
            if (resource.scheme === network_1.Schemas.data) {
                const metadata = resources_1.DataUri.parseMetaData(resource);
                name = metadata.get(resources_1.DataUri.META_DATA_LABEL);
            }
            else {
                const match = resource.path.match(fileIconDirectoryRegex);
                if (match) {
                    name = cssEscape(match[2].toLowerCase());
                    if (match[1]) {
                        classes.push(`${cssEscape(match[1].toLowerCase())}-name-dir-icon`); // parent directory
                    }
                }
                else {
                    name = cssEscape(resource.authority.toLowerCase());
                }
            }
            // Root Folders
            if (fileKind === files_1.FileKind.ROOT_FOLDER) {
                classes.push(`${name}-root-name-folder-icon`);
            }
            // Folders
            else if (fileKind === files_1.FileKind.FOLDER) {
                classes.push(`${name}-name-folder-icon`);
            }
            // Files
            else {
                // Name & Extension(s)
                if (name) {
                    classes.push(`${name}-name-file-icon`);
                    classes.push(`name-file-icon`); // extra segment to increase file-name score
                    // Avoid doing an explosive combination of extensions for very long filenames
                    // (most file systems do not allow files > 255 length) with lots of `.` characters
                    // https://github.com/microsoft/vscode/issues/116199
                    if (name.length <= 255) {
                        const dotSegments = name.split('.');
                        for (let i = 1; i < dotSegments.length; i++) {
                            classes.push(`${dotSegments.slice(i).join('.')}-ext-file-icon`); // add each combination of all found extensions if more than one
                        }
                    }
                    classes.push(`ext-file-icon`); // extra segment to increase file-ext score
                }
                // Detected Mode
                const detectedLanguageId = detectLanguageId(modelService, languageService, resource);
                if (detectedLanguageId) {
                    classes.push(`${cssEscape(detectedLanguageId)}-lang-file-icon`);
                }
            }
        }
        return classes;
    }
    function detectLanguageId(modelService, languageService, resource) {
        if (!resource) {
            return null; // we need a resource at least
        }
        let languageId = null;
        // Data URI: check for encoded metadata
        if (resource.scheme === network_1.Schemas.data) {
            const metadata = resources_1.DataUri.parseMetaData(resource);
            const mime = metadata.get(resources_1.DataUri.META_DATA_MIME);
            if (mime) {
                languageId = languageService.getLanguageIdByMimeType(mime);
            }
        }
        // Any other URI: check for model if existing
        else {
            const model = modelService.getModel(resource);
            if (model) {
                languageId = model.getLanguageId();
            }
        }
        // only take if the language id is specific (aka no just plain text)
        if (languageId && languageId !== modesRegistry_1.PLAINTEXT_LANGUAGE_ID) {
            return languageId;
        }
        // otherwise fallback to path based detection
        return languageService.guessLanguageIdByFilepathOrFirstLine(resource);
    }
    function cssEscape(str) {
        return str.replace(/[\s]/g, '/'); // HTML class names can not contain certain whitespace characters (https://dom.spec.whatwg.org/#interface-domtokenlist), use / instead, which doesn't exist in file names.
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[709/*vs/editor/common/services/languagesAssociations*/], __M([1/*require*/,0/*exports*/,350/*vs/base/common/glob*/,128/*vs/base/common/mime*/,42/*vs/base/common/network*/,99/*vs/base/common/path*/,48/*vs/base/common/resources*/,11/*vs/base/common/strings*/,70/*vs/editor/common/languages/modesRegistry*/]), function (require, exports, glob_1, mime_1, network_1, path_1, resources_1, strings_1, modesRegistry_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.registerPlatformLanguageAssociation = registerPlatformLanguageAssociation;
    exports.clearPlatformLanguageAssociations = clearPlatformLanguageAssociations;
    exports.getLanguageIds = getLanguageIds;
    let registeredAssociations = [];
    let nonUserRegisteredAssociations = [];
    let userRegisteredAssociations = [];
    /**
     * Associate a language to the registry (platform).
     * * **NOTE**: This association will lose over associations registered using `registerConfiguredLanguageAssociation`.
     * * **NOTE**: Use `clearPlatformLanguageAssociations` to remove all associations registered using this function.
     */
    function registerPlatformLanguageAssociation(association, warnOnOverwrite = false) {
        _registerLanguageAssociation(association, false, warnOnOverwrite);
    }
    function _registerLanguageAssociation(association, userConfigured, warnOnOverwrite) {
        // Register
        const associationItem = toLanguageAssociationItem(association, userConfigured);
        registeredAssociations.push(associationItem);
        if (!associationItem.userConfigured) {
            nonUserRegisteredAssociations.push(associationItem);
        }
        else {
            userRegisteredAssociations.push(associationItem);
        }
        // Check for conflicts unless this is a user configured association
        if (warnOnOverwrite && !associationItem.userConfigured) {
            registeredAssociations.forEach(a => {
                if (a.mime === associationItem.mime || a.userConfigured) {
                    return; // same mime or userConfigured is ok
                }
                if (associationItem.extension && a.extension === associationItem.extension) {
                    console.warn(`Overwriting extension <<${associationItem.extension}>> to now point to mime <<${associationItem.mime}>>`);
                }
                if (associationItem.filename && a.filename === associationItem.filename) {
                    console.warn(`Overwriting filename <<${associationItem.filename}>> to now point to mime <<${associationItem.mime}>>`);
                }
                if (associationItem.filepattern && a.filepattern === associationItem.filepattern) {
                    console.warn(`Overwriting filepattern <<${associationItem.filepattern}>> to now point to mime <<${associationItem.mime}>>`);
                }
                if (associationItem.firstline && a.firstline === associationItem.firstline) {
                    console.warn(`Overwriting firstline <<${associationItem.firstline}>> to now point to mime <<${associationItem.mime}>>`);
                }
            });
        }
    }
    function toLanguageAssociationItem(association, userConfigured) {
        return {
            id: association.id,
            mime: association.mime,
            filename: association.filename,
            extension: association.extension,
            filepattern: association.filepattern,
            firstline: association.firstline,
            userConfigured: userConfigured,
            filenameLowercase: association.filename ? association.filename.toLowerCase() : undefined,
            extensionLowercase: association.extension ? association.extension.toLowerCase() : undefined,
            filepatternLowercase: association.filepattern ? (0, glob_1.parse)(association.filepattern.toLowerCase()) : undefined,
            filepatternOnPath: association.filepattern ? association.filepattern.indexOf(path_1.posix.sep) >= 0 : false
        };
    }
    /**
     * Clear language associations from the registry (platform).
     */
    function clearPlatformLanguageAssociations() {
        registeredAssociations = registeredAssociations.filter(a => a.userConfigured);
        nonUserRegisteredAssociations = [];
    }
    /**
     * @see `getMimeTypes`
     */
    function getLanguageIds(resource, firstLine) {
        return getAssociations(resource, firstLine).map(item => item.id);
    }
    function getAssociations(resource, firstLine) {
        let path;
        if (resource) {
            switch (resource.scheme) {
                case network_1.Schemas.file:
                    path = resource.fsPath;
                    break;
                case network_1.Schemas.data: {
                    const metadata = resources_1.DataUri.parseMetaData(resource);
                    path = metadata.get(resources_1.DataUri.META_DATA_LABEL);
                    break;
                }
                case network_1.Schemas.vscodeNotebookCell:
                    // File path not relevant for language detection of cell
                    path = undefined;
                    break;
                default:
                    path = resource.path;
            }
        }
        if (!path) {
            return [{ id: 'unknown', mime: mime_1.Mimes.unknown }];
        }
        path = path.toLowerCase();
        const filename = (0, path_1.basename)(path);
        // 1.) User configured mappings have highest priority
        const configuredLanguage = getAssociationByPath(path, filename, userRegisteredAssociations);
        if (configuredLanguage) {
            return [configuredLanguage, { id: modesRegistry_1.PLAINTEXT_LANGUAGE_ID, mime: mime_1.Mimes.text }];
        }
        // 2.) Registered mappings have middle priority
        const registeredLanguage = getAssociationByPath(path, filename, nonUserRegisteredAssociations);
        if (registeredLanguage) {
            return [registeredLanguage, { id: modesRegistry_1.PLAINTEXT_LANGUAGE_ID, mime: mime_1.Mimes.text }];
        }
        // 3.) Firstline has lowest priority
        if (firstLine) {
            const firstlineLanguage = getAssociationByFirstline(firstLine);
            if (firstlineLanguage) {
                return [firstlineLanguage, { id: modesRegistry_1.PLAINTEXT_LANGUAGE_ID, mime: mime_1.Mimes.text }];
            }
        }
        return [{ id: 'unknown', mime: mime_1.Mimes.unknown }];
    }
    function getAssociationByPath(path, filename, associations) {
        let filenameMatch = undefined;
        let patternMatch = undefined;
        let extensionMatch = undefined;
        // We want to prioritize associations based on the order they are registered so that the last registered
        // association wins over all other. This is for https://github.com/microsoft/vscode/issues/20074
        for (let i = associations.length - 1; i >= 0; i--) {
            const association = associations[i];
            // First exact name match
            if (filename === association.filenameLowercase) {
                filenameMatch = association;
                break; // take it!
            }
            // Longest pattern match
            if (association.filepattern) {
                if (!patternMatch || association.filepattern.length > patternMatch.filepattern.length) {
                    const target = association.filepatternOnPath ? path : filename; // match on full path if pattern contains path separator
                    if (association.filepatternLowercase?.(target)) {
                        patternMatch = association;
                    }
                }
            }
            // Longest extension match
            if (association.extension) {
                if (!extensionMatch || association.extension.length > extensionMatch.extension.length) {
                    if (filename.endsWith(association.extensionLowercase)) {
                        extensionMatch = association;
                    }
                }
            }
        }
        // 1.) Exact name match has second highest priority
        if (filenameMatch) {
            return filenameMatch;
        }
        // 2.) Match on pattern
        if (patternMatch) {
            return patternMatch;
        }
        // 3.) Match on extension comes next
        if (extensionMatch) {
            return extensionMatch;
        }
        return undefined;
    }
    function getAssociationByFirstline(firstLine) {
        if ((0, strings_1.startsWithUTF8BOM)(firstLine)) {
            firstLine = firstLine.substr(1);
        }
        if (firstLine.length > 0) {
            // We want to prioritize associations based on the order they are registered so that the last registered
            // association wins over all other. This is for https://github.com/microsoft/vscode/issues/20074
            for (let i = registeredAssociations.length - 1; i >= 0; i--) {
                const association = registeredAssociations[i];
                if (!association.firstline) {
                    continue;
                }
                const matches = firstLine.match(association.firstline);
                if (matches && matches.length > 0) {
                    return association;
                }
            }
        }
        return undefined;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[710/*vs/editor/common/services/languagesRegistry*/], __M([1/*require*/,0/*exports*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,11/*vs/base/common/strings*/,709/*vs/editor/common/services/languagesAssociations*/,70/*vs/editor/common/languages/modesRegistry*/,109/*vs/platform/configuration/common/configurationRegistry*/,38/*vs/platform/registry/common/platform*/]), function (require, exports, event_1, lifecycle_1, strings_1, languagesAssociations_1, modesRegistry_1, configurationRegistry_1, platform_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.LanguagesRegistry = exports.LanguageIdCodec = void 0;
    const hasOwnProperty = Object.prototype.hasOwnProperty;
    const NULL_LANGUAGE_ID = 'vs.editor.nullLanguage';
    class LanguageIdCodec {
        constructor() {
            this._languageIdToLanguage = [];
            this._languageToLanguageId = new Map();
            this._register(NULL_LANGUAGE_ID, 0 /* LanguageId.Null */);
            this._register(modesRegistry_1.PLAINTEXT_LANGUAGE_ID, 1 /* LanguageId.PlainText */);
            this._nextLanguageId = 2;
        }
        _register(language, languageId) {
            this._languageIdToLanguage[languageId] = language;
            this._languageToLanguageId.set(language, languageId);
        }
        register(language) {
            if (this._languageToLanguageId.has(language)) {
                return;
            }
            const languageId = this._nextLanguageId++;
            this._register(language, languageId);
        }
        encodeLanguageId(languageId) {
            return this._languageToLanguageId.get(languageId) || 0 /* LanguageId.Null */;
        }
        decodeLanguageId(languageId) {
            return this._languageIdToLanguage[languageId] || NULL_LANGUAGE_ID;
        }
    }
    exports.LanguageIdCodec = LanguageIdCodec;
    class LanguagesRegistry extends lifecycle_1.Disposable {
        static { this.instanceCount = 0; }
        constructor(useModesRegistry = true, warnOnOverwrite = false) {
            super();
            this._onDidChange = this._register(new event_1.Emitter());
            this.onDidChange = this._onDidChange.event;
            LanguagesRegistry.instanceCount++;
            this._warnOnOverwrite = warnOnOverwrite;
            this.languageIdCodec = new LanguageIdCodec();
            this._dynamicLanguages = [];
            this._languages = {};
            this._mimeTypesMap = {};
            this._nameMap = {};
            this._lowercaseNameMap = {};
            if (useModesRegistry) {
                this._initializeFromRegistry();
                this._register(modesRegistry_1.ModesRegistry.onDidChangeLanguages((m) => {
                    this._initializeFromRegistry();
                }));
            }
        }
        dispose() {
            LanguagesRegistry.instanceCount--;
            super.dispose();
        }
        _initializeFromRegistry() {
            this._languages = {};
            this._mimeTypesMap = {};
            this._nameMap = {};
            this._lowercaseNameMap = {};
            (0, languagesAssociations_1.clearPlatformLanguageAssociations)();
            const desc = [].concat(modesRegistry_1.ModesRegistry.getLanguages()).concat(this._dynamicLanguages);
            this._registerLanguages(desc);
        }
        _registerLanguages(desc) {
            for (const d of desc) {
                this._registerLanguage(d);
            }
            // Rebuild fast path maps
            this._mimeTypesMap = {};
            this._nameMap = {};
            this._lowercaseNameMap = {};
            Object.keys(this._languages).forEach((langId) => {
                const language = this._languages[langId];
                if (language.name) {
                    this._nameMap[language.name] = language.identifier;
                }
                language.aliases.forEach((alias) => {
                    this._lowercaseNameMap[alias.toLowerCase()] = language.identifier;
                });
                language.mimetypes.forEach((mimetype) => {
                    this._mimeTypesMap[mimetype] = language.identifier;
                });
            });
            platform_1.Registry.as(configurationRegistry_1.Extensions.Configuration).registerOverrideIdentifiers(this.getRegisteredLanguageIds());
            this._onDidChange.fire();
        }
        _registerLanguage(lang) {
            const langId = lang.id;
            let resolvedLanguage;
            if (hasOwnProperty.call(this._languages, langId)) {
                resolvedLanguage = this._languages[langId];
            }
            else {
                this.languageIdCodec.register(langId);
                resolvedLanguage = {
                    identifier: langId,
                    name: null,
                    mimetypes: [],
                    aliases: [],
                    extensions: [],
                    filenames: [],
                    configurationFiles: [],
                    icons: []
                };
                this._languages[langId] = resolvedLanguage;
            }
            this._mergeLanguage(resolvedLanguage, lang);
        }
        _mergeLanguage(resolvedLanguage, lang) {
            const langId = lang.id;
            let primaryMime = null;
            if (Array.isArray(lang.mimetypes) && lang.mimetypes.length > 0) {
                resolvedLanguage.mimetypes.push(...lang.mimetypes);
                primaryMime = lang.mimetypes[0];
            }
            if (!primaryMime) {
                primaryMime = `text/x-${langId}`;
                resolvedLanguage.mimetypes.push(primaryMime);
            }
            if (Array.isArray(lang.extensions)) {
                if (lang.configuration) {
                    // insert first as this appears to be the 'primary' language definition
                    resolvedLanguage.extensions = lang.extensions.concat(resolvedLanguage.extensions);
                }
                else {
                    resolvedLanguage.extensions = resolvedLanguage.extensions.concat(lang.extensions);
                }
                for (const extension of lang.extensions) {
                    (0, languagesAssociations_1.registerPlatformLanguageAssociation)({ id: langId, mime: primaryMime, extension: extension }, this._warnOnOverwrite);
                }
            }
            if (Array.isArray(lang.filenames)) {
                for (const filename of lang.filenames) {
                    (0, languagesAssociations_1.registerPlatformLanguageAssociation)({ id: langId, mime: primaryMime, filename: filename }, this._warnOnOverwrite);
                    resolvedLanguage.filenames.push(filename);
                }
            }
            if (Array.isArray(lang.filenamePatterns)) {
                for (const filenamePattern of lang.filenamePatterns) {
                    (0, languagesAssociations_1.registerPlatformLanguageAssociation)({ id: langId, mime: primaryMime, filepattern: filenamePattern }, this._warnOnOverwrite);
                }
            }
            if (typeof lang.firstLine === 'string' && lang.firstLine.length > 0) {
                let firstLineRegexStr = lang.firstLine;
                if (firstLineRegexStr.charAt(0) !== '^') {
                    firstLineRegexStr = '^' + firstLineRegexStr;
                }
                try {
                    const firstLineRegex = new RegExp(firstLineRegexStr);
                    if (!(0, strings_1.regExpLeadsToEndlessLoop)(firstLineRegex)) {
                        (0, languagesAssociations_1.registerPlatformLanguageAssociation)({ id: langId, mime: primaryMime, firstline: firstLineRegex }, this._warnOnOverwrite);
                    }
                }
                catch (err) {
                    // Most likely, the regex was bad
                    console.warn(`[${lang.id}]: Invalid regular expression \`${firstLineRegexStr}\`: `, err);
                }
            }
            resolvedLanguage.aliases.push(langId);
            let langAliases = null;
            if (typeof lang.aliases !== 'undefined' && Array.isArray(lang.aliases)) {
                if (lang.aliases.length === 0) {
                    // signal that this language should not get a name
                    langAliases = [null];
                }
                else {
                    langAliases = lang.aliases;
                }
            }
            if (langAliases !== null) {
                for (const langAlias of langAliases) {
                    if (!langAlias || langAlias.length === 0) {
                        continue;
                    }
                    resolvedLanguage.aliases.push(langAlias);
                }
            }
            const containsAliases = (langAliases !== null && langAliases.length > 0);
            if (containsAliases && langAliases[0] === null) {
                // signal that this language should not get a name
            }
            else {
                const bestName = (containsAliases ? langAliases[0] : null) || langId;
                if (containsAliases || !resolvedLanguage.name) {
                    resolvedLanguage.name = bestName;
                }
            }
            if (lang.configuration) {
                resolvedLanguage.configurationFiles.push(lang.configuration);
            }
            if (lang.icon) {
                resolvedLanguage.icons.push(lang.icon);
            }
        }
        isRegisteredLanguageId(languageId) {
            if (!languageId) {
                return false;
            }
            return hasOwnProperty.call(this._languages, languageId);
        }
        getRegisteredLanguageIds() {
            return Object.keys(this._languages);
        }
        getLanguageIdByLanguageName(languageName) {
            const languageNameLower = languageName.toLowerCase();
            if (!hasOwnProperty.call(this._lowercaseNameMap, languageNameLower)) {
                return null;
            }
            return this._lowercaseNameMap[languageNameLower];
        }
        getLanguageIdByMimeType(mimeType) {
            if (!mimeType) {
                return null;
            }
            if (hasOwnProperty.call(this._mimeTypesMap, mimeType)) {
                return this._mimeTypesMap[mimeType];
            }
            return null;
        }
        guessLanguageIdByFilepathOrFirstLine(resource, firstLine) {
            if (!resource && !firstLine) {
                return [];
            }
            return (0, languagesAssociations_1.getLanguageIds)(resource, firstLine);
        }
    }
    exports.LanguagesRegistry = LanguagesRegistry;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[711/*vs/editor/common/services/languageService*/], __M([1/*require*/,0/*exports*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,710/*vs/editor/common/services/languagesRegistry*/,13/*vs/base/common/arrays*/,27/*vs/editor/common/languages*/,70/*vs/editor/common/languages/modesRegistry*/,21/*vs/base/common/observable*/]), function (require, exports, event_1, lifecycle_1, languagesRegistry_1, arrays_1, languages_1, modesRegistry_1, observable_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.LanguageService = void 0;
    class LanguageService extends lifecycle_1.Disposable {
        static { this.instanceCount = 0; }
        constructor(warnOnOverwrite = false) {
            super();
            this._onDidRequestBasicLanguageFeatures = this._register(new event_1.Emitter());
            this.onDidRequestBasicLanguageFeatures = this._onDidRequestBasicLanguageFeatures.event;
            this._onDidRequestRichLanguageFeatures = this._register(new event_1.Emitter());
            this.onDidRequestRichLanguageFeatures = this._onDidRequestRichLanguageFeatures.event;
            this._onDidChange = this._register(new event_1.Emitter({ leakWarningThreshold: 200 /* https://github.com/microsoft/vscode/issues/119968 */ }));
            this.onDidChange = this._onDidChange.event;
            this._requestedBasicLanguages = new Set();
            this._requestedRichLanguages = new Set();
            LanguageService.instanceCount++;
            this._registry = this._register(new languagesRegistry_1.LanguagesRegistry(true, warnOnOverwrite));
            this.languageIdCodec = this._registry.languageIdCodec;
            this._register(this._registry.onDidChange(() => this._onDidChange.fire()));
        }
        dispose() {
            LanguageService.instanceCount--;
            super.dispose();
        }
        isRegisteredLanguageId(languageId) {
            return this._registry.isRegisteredLanguageId(languageId);
        }
        getLanguageIdByLanguageName(languageName) {
            return this._registry.getLanguageIdByLanguageName(languageName);
        }
        getLanguageIdByMimeType(mimeType) {
            return this._registry.getLanguageIdByMimeType(mimeType);
        }
        guessLanguageIdByFilepathOrFirstLine(resource, firstLine) {
            const languageIds = this._registry.guessLanguageIdByFilepathOrFirstLine(resource, firstLine);
            return (0, arrays_1.firstOrDefault)(languageIds, null);
        }
        createById(languageId) {
            return new LanguageSelection(this.onDidChange, () => {
                return this._createAndGetLanguageIdentifier(languageId);
            });
        }
        createByFilepathOrFirstLine(resource, firstLine) {
            return new LanguageSelection(this.onDidChange, () => {
                const languageId = this.guessLanguageIdByFilepathOrFirstLine(resource, firstLine);
                return this._createAndGetLanguageIdentifier(languageId);
            });
        }
        _createAndGetLanguageIdentifier(languageId) {
            if (!languageId || !this.isRegisteredLanguageId(languageId)) {
                // Fall back to plain text if language is unknown
                languageId = modesRegistry_1.PLAINTEXT_LANGUAGE_ID;
            }
            return languageId;
        }
        requestBasicLanguageFeatures(languageId) {
            if (!this._requestedBasicLanguages.has(languageId)) {
                this._requestedBasicLanguages.add(languageId);
                this._onDidRequestBasicLanguageFeatures.fire(languageId);
            }
        }
        requestRichLanguageFeatures(languageId) {
            if (!this._requestedRichLanguages.has(languageId)) {
                this._requestedRichLanguages.add(languageId);
                // Ensure basic features are requested
                this.requestBasicLanguageFeatures(languageId);
                // Ensure tokenizers are created
                languages_1.TokenizationRegistry.getOrCreate(languageId);
                this._onDidRequestRichLanguageFeatures.fire(languageId);
            }
        }
    }
    exports.LanguageService = LanguageService;
    class LanguageSelection {
        constructor(onDidChangeLanguages, selector) {
            this._value = (0, observable_1.observableFromEvent)(this, onDidChangeLanguages, () => selector());
            this.onDidChange = event_1.Event.fromObservable(this._value);
        }
        get languageId() {
            return this._value.get();
        }
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[712/*vs/editor/contrib/hover/browser/marginHoverWidget*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,2/*vs/base/common/lifecycle*/,120/*vs/editor/browser/widget/markdownRenderer/browser/markdownRenderer*/,43/*vs/editor/common/languages/language*/,376/*vs/editor/contrib/hover/browser/hoverOperation*/,59/*vs/platform/opener/common/opener*/,174/*vs/base/browser/ui/hover/hoverWidget*/,669/*vs/editor/contrib/hover/browser/marginHoverComputer*/,210/*vs/editor/contrib/hover/browser/hoverUtils*/]), function (require, exports, dom, lifecycle_1, markdownRenderer_1, language_1, hoverOperation_1, opener_1, hoverWidget_1, marginHoverComputer_1, hoverUtils_1) {
    "use strict";
    var MarginHoverWidget_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MarginHoverWidget = void 0;
    const $ = dom.$;
    let MarginHoverWidget = class MarginHoverWidget extends lifecycle_1.Disposable {
        static { MarginHoverWidget_1 = this; }
        static { this.ID = 'editor.contrib.modesGlyphHoverWidget'; }
        constructor(editor, languageService, openerService) {
            super();
            this._renderDisposeables = this._register(new lifecycle_1.DisposableStore());
            this._editor = editor;
            this._isVisible = false;
            this._messages = [];
            this._hover = this._register(new hoverWidget_1.HoverWidget());
            this._hover.containerDomNode.classList.toggle('hidden', !this._isVisible);
            this._markdownRenderer = this._register(new markdownRenderer_1.MarkdownRenderer({ editor: this._editor }, languageService, openerService));
            this._computer = new marginHoverComputer_1.MarginHoverComputer(this._editor);
            this._hoverOperation = this._register(new hoverOperation_1.HoverOperation(this._editor, this._computer));
            this._register(this._hoverOperation.onResult((result) => {
                this._withResult(result.value);
            }));
            this._register(this._editor.onDidChangeModelDecorations(() => this._onModelDecorationsChanged()));
            this._register(this._editor.onDidChangeConfiguration((e) => {
                if (e.hasChanged(50 /* EditorOption.fontInfo */)) {
                    this._updateFont();
                }
            }));
            this._register(dom.addStandardDisposableListener(this._hover.containerDomNode, 'mouseleave', (e) => {
                this._onMouseLeave(e);
            }));
            this._editor.addOverlayWidget(this);
        }
        dispose() {
            this._editor.removeOverlayWidget(this);
            super.dispose();
        }
        getId() {
            return MarginHoverWidget_1.ID;
        }
        getDomNode() {
            return this._hover.containerDomNode;
        }
        getPosition() {
            return null;
        }
        _updateFont() {
            const codeClasses = Array.prototype.slice.call(this._hover.contentsDomNode.getElementsByClassName('code'));
            codeClasses.forEach(node => this._editor.applyFontInfo(node));
        }
        _onModelDecorationsChanged() {
            if (this._isVisible) {
                // The decorations have changed and the hover is visible,
                // we need to recompute the displayed text
                this._hoverOperation.cancel();
                this._hoverOperation.start(0 /* HoverStartMode.Delayed */);
            }
        }
        showsOrWillShow(mouseEvent) {
            const target = mouseEvent.target;
            if (target.type === 2 /* MouseTargetType.GUTTER_GLYPH_MARGIN */ && target.detail.glyphMarginLane) {
                this._startShowingAt(target.position.lineNumber, target.detail.glyphMarginLane);
                return true;
            }
            if (target.type === 3 /* MouseTargetType.GUTTER_LINE_NUMBERS */) {
                this._startShowingAt(target.position.lineNumber, 'lineNo');
                return true;
            }
            return false;
        }
        _startShowingAt(lineNumber, laneOrLine) {
            if (this._computer.lineNumber === lineNumber && this._computer.lane === laneOrLine) {
                // We have to show the widget at the exact same line number as before, so no work is needed
                return;
            }
            this._hoverOperation.cancel();
            this.hide();
            this._computer.lineNumber = lineNumber;
            this._computer.lane = laneOrLine;
            this._hoverOperation.start(0 /* HoverStartMode.Delayed */);
        }
        hide() {
            this._computer.lineNumber = -1;
            this._hoverOperation.cancel();
            if (!this._isVisible) {
                return;
            }
            this._isVisible = false;
            this._hover.containerDomNode.classList.toggle('hidden', !this._isVisible);
        }
        _withResult(result) {
            this._messages = result;
            if (this._messages.length > 0) {
                this._renderMessages(this._computer.lineNumber, this._messages);
            }
            else {
                this.hide();
            }
        }
        _renderMessages(lineNumber, messages) {
            this._renderDisposeables.clear();
            const fragment = document.createDocumentFragment();
            for (const msg of messages) {
                const markdownHoverElement = $('div.hover-row.markdown-hover');
                const hoverContentsElement = dom.append(markdownHoverElement, $('div.hover-contents'));
                const renderedContents = this._renderDisposeables.add(this._markdownRenderer.render(msg.value));
                hoverContentsElement.appendChild(renderedContents.element);
                fragment.appendChild(markdownHoverElement);
            }
            this._updateContents(fragment);
            this._showAt(lineNumber);
        }
        _updateContents(node) {
            this._hover.contentsDomNode.textContent = '';
            this._hover.contentsDomNode.appendChild(node);
            this._updateFont();
        }
        _showAt(lineNumber) {
            if (!this._isVisible) {
                this._isVisible = true;
                this._hover.containerDomNode.classList.toggle('hidden', !this._isVisible);
            }
            const editorLayout = this._editor.getLayoutInfo();
            const topForLineNumber = this._editor.getTopForLineNumber(lineNumber);
            const editorScrollTop = this._editor.getScrollTop();
            const lineHeight = this._editor.getOption(67 /* EditorOption.lineHeight */);
            const nodeHeight = this._hover.containerDomNode.clientHeight;
            const top = topForLineNumber - editorScrollTop - ((nodeHeight - lineHeight) / 2);
            const left = editorLayout.glyphMarginLeft + editorLayout.glyphMarginWidth + (this._computer.lane === 'lineNo' ? editorLayout.lineNumbersWidth : 0);
            this._hover.containerDomNode.style.left = `${left}px`;
            this._hover.containerDomNode.style.top = `${Math.max(Math.round(top), 0)}px`;
        }
        _onMouseLeave(e) {
            const editorDomNode = this._editor.getDomNode();
            const isMousePositionOutsideOfEditor = !editorDomNode || !(0, hoverUtils_1.isMousePositionWithinElement)(editorDomNode, e.x, e.y);
            if (isMousePositionOutsideOfEditor) {
                this.hide();
            }
        }
    };
    exports.MarginHoverWidget = MarginHoverWidget;
    exports.MarginHoverWidget = MarginHoverWidget = MarginHoverWidget_1 = __decorate([
        __param(1, language_1.ILanguageService),
        __param(2, opener_1.IOpenerService)
    ], MarginHoverWidget);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[713/*vs/editor/contrib/hover/browser/marginHoverController*/], __M([1/*require*/,0/*exports*/,2/*vs/base/common/lifecycle*/,7/*vs/platform/instantiation/common/instantiation*/,14/*vs/base/common/async*/,210/*vs/editor/contrib/hover/browser/hoverUtils*/,712/*vs/editor/contrib/hover/browser/marginHoverWidget*/,196/*vs/css!vs/editor/contrib/hover/browser/hover*/]), function (require, exports, lifecycle_1, instantiation_1, async_1, hoverUtils_1, marginHoverWidget_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MarginHoverController = void 0;
    // sticky hover widget which doesn't disappear on focus out and such
    const _sticky = false;
    let MarginHoverController = class MarginHoverController extends lifecycle_1.Disposable {
        static { this.ID = 'editor.contrib.marginHover'; }
        constructor(_editor, _instantiationService) {
            super();
            this._editor = _editor;
            this._instantiationService = _instantiationService;
            this.shouldKeepOpenOnEditorMouseMoveOrLeave = false;
            this._listenersStore = new lifecycle_1.DisposableStore();
            this._hoverState = {
                mouseDown: false
            };
            this._reactToEditorMouseMoveRunner = this._register(new async_1.RunOnceScheduler(() => this._reactToEditorMouseMove(this._mouseMoveEvent), 0));
            this._hookListeners();
            this._register(this._editor.onDidChangeConfiguration((e) => {
                if (e.hasChanged(60 /* EditorOption.hover */)) {
                    this._unhookListeners();
                    this._hookListeners();
                }
            }));
        }
        _hookListeners() {
            const hoverOpts = this._editor.getOption(60 /* EditorOption.hover */);
            this._hoverSettings = {
                enabled: hoverOpts.enabled,
                sticky: hoverOpts.sticky,
                hidingDelay: hoverOpts.hidingDelay
            };
            if (hoverOpts.enabled) {
                this._listenersStore.add(this._editor.onMouseDown((e) => this._onEditorMouseDown(e)));
                this._listenersStore.add(this._editor.onMouseUp(() => this._onEditorMouseUp()));
                this._listenersStore.add(this._editor.onMouseMove((e) => this._onEditorMouseMove(e)));
                this._listenersStore.add(this._editor.onKeyDown((e) => this._onKeyDown(e)));
            }
            else {
                this._listenersStore.add(this._editor.onMouseMove((e) => this._onEditorMouseMove(e)));
                this._listenersStore.add(this._editor.onKeyDown((e) => this._onKeyDown(e)));
            }
            this._listenersStore.add(this._editor.onMouseLeave((e) => this._onEditorMouseLeave(e)));
            this._listenersStore.add(this._editor.onDidChangeModel(() => {
                this._cancelScheduler();
                this._hideWidgets();
            }));
            this._listenersStore.add(this._editor.onDidChangeModelContent(() => this._cancelScheduler()));
            this._listenersStore.add(this._editor.onDidScrollChange((e) => this._onEditorScrollChanged(e)));
        }
        _unhookListeners() {
            this._listenersStore.clear();
        }
        _cancelScheduler() {
            this._mouseMoveEvent = undefined;
            this._reactToEditorMouseMoveRunner.cancel();
        }
        _onEditorScrollChanged(e) {
            if (e.scrollTopChanged || e.scrollLeftChanged) {
                this._hideWidgets();
            }
        }
        _onEditorMouseDown(mouseEvent) {
            this._hoverState.mouseDown = true;
            const shouldNotHideCurrentHoverWidget = this._isMouseOnMarginHoverWidget(mouseEvent);
            if (shouldNotHideCurrentHoverWidget) {
                return;
            }
            this._hideWidgets();
        }
        _isMouseOnMarginHoverWidget(mouseEvent) {
            const marginHoverWidgetNode = this._glyphWidget?.getDomNode();
            if (marginHoverWidgetNode) {
                return (0, hoverUtils_1.isMousePositionWithinElement)(marginHoverWidgetNode, mouseEvent.event.posx, mouseEvent.event.posy);
            }
            return false;
        }
        _onEditorMouseUp() {
            this._hoverState.mouseDown = false;
        }
        _onEditorMouseLeave(mouseEvent) {
            if (this.shouldKeepOpenOnEditorMouseMoveOrLeave) {
                return;
            }
            this._cancelScheduler();
            const shouldNotHideCurrentHoverWidget = this._isMouseOnMarginHoverWidget(mouseEvent);
            if (shouldNotHideCurrentHoverWidget) {
                return;
            }
            if (_sticky) {
                return;
            }
            this._hideWidgets();
        }
        _shouldNotRecomputeCurrentHoverWidget(mouseEvent) {
            const isHoverSticky = this._hoverSettings.sticky;
            const isMouseOnMarginHoverWidget = this._isMouseOnMarginHoverWidget(mouseEvent);
            return isHoverSticky && isMouseOnMarginHoverWidget;
        }
        _onEditorMouseMove(mouseEvent) {
            if (this.shouldKeepOpenOnEditorMouseMoveOrLeave) {
                return;
            }
            this._mouseMoveEvent = mouseEvent;
            const shouldNotRecomputeCurrentHoverWidget = this._shouldNotRecomputeCurrentHoverWidget(mouseEvent);
            if (shouldNotRecomputeCurrentHoverWidget) {
                this._reactToEditorMouseMoveRunner.cancel();
                return;
            }
            this._reactToEditorMouseMove(mouseEvent);
        }
        _reactToEditorMouseMove(mouseEvent) {
            if (!mouseEvent) {
                return;
            }
            const glyphWidgetShowsOrWillShow = this._tryShowHoverWidget(mouseEvent);
            if (glyphWidgetShowsOrWillShow) {
                return;
            }
            if (_sticky) {
                return;
            }
            this._hideWidgets();
        }
        _tryShowHoverWidget(mouseEvent) {
            const glyphWidget = this._getOrCreateGlyphWidget();
            return glyphWidget.showsOrWillShow(mouseEvent);
        }
        _onKeyDown(e) {
            if (!this._editor.hasModel()) {
                return;
            }
            if (e.keyCode === 5 /* KeyCode.Ctrl */
                || e.keyCode === 6 /* KeyCode.Alt */
                || e.keyCode === 57 /* KeyCode.Meta */
                || e.keyCode === 4 /* KeyCode.Shift */) {
                // Do not hide hover when a modifier key is pressed
                return;
            }
            this._hideWidgets();
        }
        _hideWidgets() {
            if (_sticky) {
                return;
            }
            this._glyphWidget?.hide();
        }
        _getOrCreateGlyphWidget() {
            if (!this._glyphWidget) {
                this._glyphWidget = this._instantiationService.createInstance(marginHoverWidget_1.MarginHoverWidget, this._editor);
            }
            return this._glyphWidget;
        }
        dispose() {
            super.dispose();
            this._unhookListeners();
            this._listenersStore.dispose();
            this._glyphWidget?.dispose();
        }
    };
    exports.MarginHoverController = MarginHoverController;
    exports.MarginHoverController = MarginHoverController = __decorate([
        __param(1, instantiation_1.IInstantiationService)
    ], MarginHoverController);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[714/*vs/editor/contrib/indentation/common/indentation*/], __M([1/*require*/,0/*exports*/,11/*vs/base/common/strings*/,183/*vs/editor/common/commands/shiftCommand*/,75/*vs/editor/common/core/editOperation*/,230/*vs/editor/common/core/indentation*/,23/*vs/editor/common/core/selection*/,240/*vs/editor/common/languages/supports/indentationLineProcessor*/]), function (require, exports, strings, shiftCommand_1, editOperation_1, indentation_1, selection_1, indentationLineProcessor_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.getReindentEditOperations = getReindentEditOperations;
    function getReindentEditOperations(model, languageConfigurationService, startLineNumber, endLineNumber) {
        if (model.getLineCount() === 1 && model.getLineMaxColumn(1) === 1) {
            // Model is empty
            return [];
        }
        const indentationRulesSupport = languageConfigurationService.getLanguageConfiguration(model.getLanguageId()).indentRulesSupport;
        if (!indentationRulesSupport) {
            return [];
        }
        const processedIndentRulesSupport = new indentationLineProcessor_1.ProcessedIndentRulesSupport(model, indentationRulesSupport, languageConfigurationService);
        endLineNumber = Math.min(endLineNumber, model.getLineCount());
        // Skip `unIndentedLinePattern` lines
        while (startLineNumber <= endLineNumber) {
            if (!processedIndentRulesSupport.shouldIgnore(startLineNumber)) {
                break;
            }
            startLineNumber++;
        }
        if (startLineNumber > endLineNumber - 1) {
            return [];
        }
        const { tabSize, indentSize, insertSpaces } = model.getOptions();
        const shiftIndent = (indentation, count) => {
            count = count || 1;
            return shiftCommand_1.ShiftCommand.shiftIndent(indentation, indentation.length + count, tabSize, indentSize, insertSpaces);
        };
        const unshiftIndent = (indentation, count) => {
            count = count || 1;
            return shiftCommand_1.ShiftCommand.unshiftIndent(indentation, indentation.length + count, tabSize, indentSize, insertSpaces);
        };
        const indentEdits = [];
        // indentation being passed to lines below
        // Calculate indentation for the first line
        // If there is no passed-in indentation, we use the indentation of the first line as base.
        const currentLineText = model.getLineContent(startLineNumber);
        let globalIndent = strings.getLeadingWhitespace(currentLineText);
        // idealIndentForNextLine doesn't equal globalIndent when there is a line matching `indentNextLinePattern`.
        let idealIndentForNextLine = globalIndent;
        if (processedIndentRulesSupport.shouldIncrease(startLineNumber)) {
            idealIndentForNextLine = shiftIndent(idealIndentForNextLine);
            globalIndent = shiftIndent(globalIndent);
        }
        else if (processedIndentRulesSupport.shouldIndentNextLine(startLineNumber)) {
            idealIndentForNextLine = shiftIndent(idealIndentForNextLine);
        }
        startLineNumber++;
        // Calculate indentation adjustment for all following lines
        for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
            if (doesLineStartWithString(model, lineNumber)) {
                continue;
            }
            const text = model.getLineContent(lineNumber);
            const oldIndentation = strings.getLeadingWhitespace(text);
            const currentIdealIndent = idealIndentForNextLine;
            if (processedIndentRulesSupport.shouldDecrease(lineNumber, currentIdealIndent)) {
                idealIndentForNextLine = unshiftIndent(idealIndentForNextLine);
                globalIndent = unshiftIndent(globalIndent);
            }
            if (oldIndentation !== idealIndentForNextLine) {
                indentEdits.push(editOperation_1.EditOperation.replaceMove(new selection_1.Selection(lineNumber, 1, lineNumber, oldIndentation.length + 1), (0, indentation_1.normalizeIndentation)(idealIndentForNextLine, indentSize, insertSpaces)));
            }
            // calculate idealIndentForNextLine
            if (processedIndentRulesSupport.shouldIgnore(lineNumber)) {
                // In reindent phase, if the line matches `unIndentedLinePattern` we inherit indentation from above lines
                // but don't change globalIndent and idealIndentForNextLine.
                continue;
            }
            else if (processedIndentRulesSupport.shouldIncrease(lineNumber, currentIdealIndent)) {
                globalIndent = shiftIndent(globalIndent);
                idealIndentForNextLine = globalIndent;
            }
            else if (processedIndentRulesSupport.shouldIndentNextLine(lineNumber, currentIdealIndent)) {
                idealIndentForNextLine = shiftIndent(idealIndentForNextLine);
            }
            else {
                idealIndentForNextLine = globalIndent;
            }
        }
        return indentEdits;
    }
    function doesLineStartWithString(model, lineNumber) {
        if (!model.tokenization.isCheapToTokenize(lineNumber)) {
            return false;
        }
        const lineTokens = model.tokenization.getLineTokens(lineNumber);
        return lineTokens.getStandardTokenType(0) === 2 /* StandardTokenType.String */;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[715/*vs/editor/contrib/inlineCompletions/browser/model/inlineCompletionsSource*/], __M([1/*require*/,0/*exports*/,18/*vs/base/common/cancellation*/,102/*vs/base/common/equals*/,82/*vs/base/common/filters*/,2/*vs/base/common/lifecycle*/,21/*vs/base/common/observable*/,4/*vs/editor/common/core/range*/,104/*vs/editor/common/core/textEdit*/,113/*vs/editor/common/core/textLength*/,27/*vs/editor/common/languages*/,36/*vs/editor/common/languages/languageConfigurationRegistry*/,17/*vs/editor/common/services/languageFeatures*/,378/*vs/editor/contrib/inlineCompletions/browser/model/provideInlineCompletions*/,246/*vs/editor/contrib/inlineCompletions/browser/model/singleTextEdit*/]), function (require, exports, cancellation_1, equals_1, filters_1, lifecycle_1, observable_1, range_1, textEdit_1, textLength_1, languages_1, languageConfigurationRegistry_1, languageFeatures_1, provideInlineCompletions_1, singleTextEdit_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.InlineCompletionWithUpdatedRange = exports.UpToDateInlineCompletions = exports.InlineCompletionsSource = void 0;
    let InlineCompletionsSource = class InlineCompletionsSource extends lifecycle_1.Disposable {
        constructor(textModel, versionId, _debounceValue, languageFeaturesService, languageConfigurationService) {
            super();
            this.textModel = textModel;
            this.versionId = versionId;
            this._debounceValue = _debounceValue;
            this.languageFeaturesService = languageFeaturesService;
            this.languageConfigurationService = languageConfigurationService;
            this._updateOperation = this._register(new lifecycle_1.MutableDisposable());
            this.inlineCompletions = (0, observable_1.disposableObservableValue)('inlineCompletions', undefined);
            this.suggestWidgetInlineCompletions = (0, observable_1.disposableObservableValue)('suggestWidgetInlineCompletions', undefined);
            this._register(this.textModel.onDidChangeContent(() => {
                this._updateOperation.clear();
            }));
        }
        fetch(position, context, activeInlineCompletion) {
            const request = new UpdateRequest(position, context, this.textModel.getVersionId());
            const target = context.selectedSuggestionInfo ? this.suggestWidgetInlineCompletions : this.inlineCompletions;
            if (this._updateOperation.value?.request.satisfies(request)) {
                return this._updateOperation.value.promise;
            }
            else if (target.get()?.request.satisfies(request)) {
                return Promise.resolve(true);
            }
            const updateOngoing = !!this._updateOperation.value;
            this._updateOperation.clear();
            const source = new cancellation_1.CancellationTokenSource();
            const promise = (async () => {
                const shouldDebounce = updateOngoing || context.triggerKind === languages_1.InlineCompletionTriggerKind.Automatic;
                if (shouldDebounce) {
                    // This debounces the operation
                    await wait(this._debounceValue.get(this.textModel), source.token);
                }
                if (source.token.isCancellationRequested || this._store.isDisposed || this.textModel.getVersionId() !== request.versionId) {
                    return false;
                }
                const startTime = new Date();
                const updatedCompletions = await (0, provideInlineCompletions_1.provideInlineCompletions)(this.languageFeaturesService.inlineCompletionsProvider, position, this.textModel, context, source.token, this.languageConfigurationService);
                if (source.token.isCancellationRequested || this._store.isDisposed || this.textModel.getVersionId() !== request.versionId) {
                    return false;
                }
                const endTime = new Date();
                this._debounceValue.update(this.textModel, endTime.getTime() - startTime.getTime());
                const completions = new UpToDateInlineCompletions(updatedCompletions, request, this.textModel, this.versionId);
                if (activeInlineCompletion) {
                    const asInlineCompletion = activeInlineCompletion.toInlineCompletion(undefined);
                    if (activeInlineCompletion.canBeReused(this.textModel, position) && !updatedCompletions.has(asInlineCompletion)) {
                        completions.prepend(activeInlineCompletion.inlineCompletion, asInlineCompletion.range, true);
                    }
                }
                this._updateOperation.clear();
                (0, observable_1.transaction)(tx => {
                    /** @description Update completions with provider result */
                    target.set(completions, tx);
                });
                return true;
            })();
            const updateOperation = new UpdateOperation(request, source, promise);
            this._updateOperation.value = updateOperation;
            return promise;
        }
        clear(tx) {
            this._updateOperation.clear();
            this.inlineCompletions.set(undefined, tx);
            this.suggestWidgetInlineCompletions.set(undefined, tx);
        }
        clearSuggestWidgetInlineCompletions(tx) {
            if (this._updateOperation.value?.request.context.selectedSuggestionInfo) {
                this._updateOperation.clear();
            }
            this.suggestWidgetInlineCompletions.set(undefined, tx);
        }
        cancelUpdate() {
            this._updateOperation.clear();
        }
    };
    exports.InlineCompletionsSource = InlineCompletionsSource;
    exports.InlineCompletionsSource = InlineCompletionsSource = __decorate([
        __param(3, languageFeatures_1.ILanguageFeaturesService),
        __param(4, languageConfigurationRegistry_1.ILanguageConfigurationService)
    ], InlineCompletionsSource);
    function wait(ms, cancellationToken) {
        return new Promise(resolve => {
            let d = undefined;
            const handle = setTimeout(() => {
                if (d) {
                    d.dispose();
                }
                resolve();
            }, ms);
            if (cancellationToken) {
                d = cancellationToken.onCancellationRequested(() => {
                    clearTimeout(handle);
                    if (d) {
                        d.dispose();
                    }
                    resolve();
                });
            }
        });
    }
    class UpdateRequest {
        constructor(position, context, versionId) {
            this.position = position;
            this.context = context;
            this.versionId = versionId;
        }
        satisfies(other) {
            return this.position.equals(other.position)
                && (0, equals_1.equalsIfDefined)(this.context.selectedSuggestionInfo, other.context.selectedSuggestionInfo, (0, equals_1.itemEquals)())
                && (other.context.triggerKind === languages_1.InlineCompletionTriggerKind.Automatic
                    || this.context.triggerKind === languages_1.InlineCompletionTriggerKind.Explicit)
                && this.versionId === other.versionId;
        }
    }
    class UpdateOperation {
        constructor(request, cancellationTokenSource, promise) {
            this.request = request;
            this.cancellationTokenSource = cancellationTokenSource;
            this.promise = promise;
        }
        dispose() {
            this.cancellationTokenSource.cancel();
        }
    }
    class UpToDateInlineCompletions {
        get inlineCompletions() { return this._inlineCompletions; }
        constructor(inlineCompletionProviderResult, request, _textModel, _versionId) {
            this.inlineCompletionProviderResult = inlineCompletionProviderResult;
            this.request = request;
            this._textModel = _textModel;
            this._versionId = _versionId;
            this._refCount = 1;
            this._prependedInlineCompletionItems = [];
            const ids = _textModel.deltaDecorations([], inlineCompletionProviderResult.completions.map(i => ({
                range: i.range,
                options: {
                    description: 'inline-completion-tracking-range'
                },
            })));
            this._inlineCompletions = inlineCompletionProviderResult.completions.map((i, index) => new InlineCompletionWithUpdatedRange(i, ids[index], this._textModel, this._versionId));
        }
        clone() {
            this._refCount++;
            return this;
        }
        dispose() {
            this._refCount--;
            if (this._refCount === 0) {
                setTimeout(() => {
                    // To fix https://github.com/microsoft/vscode/issues/188348
                    if (!this._textModel.isDisposed()) {
                        // This is just cleanup. It's ok if it happens with a delay.
                        this._textModel.deltaDecorations(this._inlineCompletions.map(i => i.decorationId), []);
                    }
                }, 0);
                this.inlineCompletionProviderResult.dispose();
                for (const i of this._prependedInlineCompletionItems) {
                    i.source.removeRef();
                }
            }
        }
        prepend(inlineCompletion, range, addRefToSource) {
            if (addRefToSource) {
                inlineCompletion.source.addRef();
            }
            const id = this._textModel.deltaDecorations([], [{
                    range,
                    options: {
                        description: 'inline-completion-tracking-range'
                    },
                }])[0];
            this._inlineCompletions.unshift(new InlineCompletionWithUpdatedRange(inlineCompletion, id, this._textModel, this._versionId));
            this._prependedInlineCompletionItems.push(inlineCompletion);
        }
    }
    exports.UpToDateInlineCompletions = UpToDateInlineCompletions;
    class InlineCompletionWithUpdatedRange {
        get forwardStable() {
            return this.inlineCompletion.source.inlineCompletions.enableForwardStability ?? false;
        }
        constructor(inlineCompletion, decorationId, _textModel, _modelVersion) {
            this.inlineCompletion = inlineCompletion;
            this.decorationId = decorationId;
            this._textModel = _textModel;
            this._modelVersion = _modelVersion;
            this.semanticId = JSON.stringify([
                this.inlineCompletion.filterText,
                this.inlineCompletion.insertText,
                this.inlineCompletion.range.getStartPosition().toString()
            ]);
            this._updatedRange = (0, observable_1.derivedOpts)({ owner: this, equalsFn: range_1.Range.equalsRange }, reader => {
                this._modelVersion.read(reader);
                return this._textModel.getDecorationRange(this.decorationId);
            });
        }
        toInlineCompletion(reader) {
            return this.inlineCompletion.withRange(this._updatedRange.read(reader) ?? emptyRange);
        }
        toSingleTextEdit(reader) {
            return new textEdit_1.SingleTextEdit(this._updatedRange.read(reader) ?? emptyRange, this.inlineCompletion.insertText);
        }
        isVisible(model, cursorPosition, reader) {
            const minimizedReplacement = (0, singleTextEdit_1.singleTextRemoveCommonPrefix)(this._toFilterTextReplacement(reader), model);
            const updatedRange = this._updatedRange.read(reader);
            if (!updatedRange
                || !this.inlineCompletion.range.getStartPosition().equals(updatedRange.getStartPosition())
                || cursorPosition.lineNumber !== minimizedReplacement.range.startLineNumber) {
                return false;
            }
            // We might consider comparing by .toLowerText, but this requires GhostTextReplacement
            const originalValue = model.getValueInRange(minimizedReplacement.range, 1 /* EndOfLinePreference.LF */);
            const filterText = minimizedReplacement.text;
            const cursorPosIndex = Math.max(0, cursorPosition.column - minimizedReplacement.range.startColumn);
            let filterTextBefore = filterText.substring(0, cursorPosIndex);
            let filterTextAfter = filterText.substring(cursorPosIndex);
            let originalValueBefore = originalValue.substring(0, cursorPosIndex);
            let originalValueAfter = originalValue.substring(cursorPosIndex);
            const originalValueIndent = model.getLineIndentColumn(minimizedReplacement.range.startLineNumber);
            if (minimizedReplacement.range.startColumn <= originalValueIndent) {
                // Remove indentation
                originalValueBefore = originalValueBefore.trimStart();
                if (originalValueBefore.length === 0) {
                    originalValueAfter = originalValueAfter.trimStart();
                }
                filterTextBefore = filterTextBefore.trimStart();
                if (filterTextBefore.length === 0) {
                    filterTextAfter = filterTextAfter.trimStart();
                }
            }
            return filterTextBefore.startsWith(originalValueBefore)
                && !!(0, filters_1.matchesSubString)(originalValueAfter, filterTextAfter);
        }
        canBeReused(model, position) {
            const updatedRange = this._updatedRange.read(undefined);
            const result = !!updatedRange
                && updatedRange.containsPosition(position)
                && this.isVisible(model, position, undefined)
                && textLength_1.TextLength.ofRange(updatedRange).isGreaterThanOrEqualTo(textLength_1.TextLength.ofRange(this.inlineCompletion.range));
            return result;
        }
        _toFilterTextReplacement(reader) {
            return new textEdit_1.SingleTextEdit(this._updatedRange.read(reader) ?? emptyRange, this.inlineCompletion.filterText);
        }
    }
    exports.InlineCompletionWithUpdatedRange = InlineCompletionWithUpdatedRange;
    const emptyRange = new range_1.Range(1, 1, 1, 1);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[716/*vs/editor/contrib/linesOperations/browser/moveLinesCommand*/], __M([1/*require*/,0/*exports*/,11/*vs/base/common/strings*/,183/*vs/editor/common/commands/shiftCommand*/,4/*vs/editor/common/core/range*/,23/*vs/editor/common/core/selection*/,131/*vs/editor/common/languages/languageConfiguration*/,36/*vs/editor/common/languages/languageConfigurationRegistry*/,338/*vs/editor/contrib/indentation/common/indentUtils*/,241/*vs/editor/common/languages/autoIndent*/,275/*vs/editor/common/languages/enterAction*/]), function (require, exports, strings, shiftCommand_1, range_1, selection_1, languageConfiguration_1, languageConfigurationRegistry_1, indentUtils, autoIndent_1, enterAction_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MoveLinesCommand = void 0;
    let MoveLinesCommand = class MoveLinesCommand {
        constructor(selection, isMovingDown, autoIndent, _languageConfigurationService) {
            this._languageConfigurationService = _languageConfigurationService;
            this._selection = selection;
            this._isMovingDown = isMovingDown;
            this._autoIndent = autoIndent;
            this._selectionId = null;
            this._moveEndLineSelectionShrink = false;
        }
        getEditOperations(model, builder) {
            const getLanguageId = () => {
                return model.getLanguageId();
            };
            const getLanguageIdAtPosition = (lineNumber, column) => {
                return model.getLanguageIdAtPosition(lineNumber, column);
            };
            const modelLineCount = model.getLineCount();
            if (this._isMovingDown && this._selection.endLineNumber === modelLineCount) {
                this._selectionId = builder.trackSelection(this._selection);
                return;
            }
            if (!this._isMovingDown && this._selection.startLineNumber === 1) {
                this._selectionId = builder.trackSelection(this._selection);
                return;
            }
            this._moveEndPositionDown = false;
            let s = this._selection;
            if (s.startLineNumber < s.endLineNumber && s.endColumn === 1) {
                this._moveEndPositionDown = true;
                s = s.setEndPosition(s.endLineNumber - 1, model.getLineMaxColumn(s.endLineNumber - 1));
            }
            const { tabSize, indentSize, insertSpaces } = model.getOptions();
            const indentConverter = this.buildIndentConverter(tabSize, indentSize, insertSpaces);
            if (s.startLineNumber === s.endLineNumber && model.getLineMaxColumn(s.startLineNumber) === 1) {
                // Current line is empty
                const lineNumber = s.startLineNumber;
                const otherLineNumber = (this._isMovingDown ? lineNumber + 1 : lineNumber - 1);
                if (model.getLineMaxColumn(otherLineNumber) === 1) {
                    // Other line number is empty too, so no editing is needed
                    // Add a no-op to force running by the model
                    builder.addEditOperation(new range_1.Range(1, 1, 1, 1), null);
                }
                else {
                    // Type content from other line number on line number
                    builder.addEditOperation(new range_1.Range(lineNumber, 1, lineNumber, 1), model.getLineContent(otherLineNumber));
                    // Remove content from other line number
                    builder.addEditOperation(new range_1.Range(otherLineNumber, 1, otherLineNumber, model.getLineMaxColumn(otherLineNumber)), null);
                }
                // Track selection at the other line number
                s = new selection_1.Selection(otherLineNumber, 1, otherLineNumber, 1);
            }
            else {
                let movingLineNumber;
                let movingLineText;
                if (this._isMovingDown) {
                    movingLineNumber = s.endLineNumber + 1;
                    movingLineText = model.getLineContent(movingLineNumber);
                    // Delete line that needs to be moved
                    builder.addEditOperation(new range_1.Range(movingLineNumber - 1, model.getLineMaxColumn(movingLineNumber - 1), movingLineNumber, model.getLineMaxColumn(movingLineNumber)), null);
                    let insertingText = movingLineText;
                    if (this.shouldAutoIndent(model, s)) {
                        const movingLineMatchResult = this.matchEnterRule(model, indentConverter, tabSize, movingLineNumber, s.startLineNumber - 1);
                        // if s.startLineNumber - 1 matches onEnter rule, we still honor that.
                        if (movingLineMatchResult !== null) {
                            const oldIndentation = strings.getLeadingWhitespace(model.getLineContent(movingLineNumber));
                            const newSpaceCnt = movingLineMatchResult + indentUtils.getSpaceCnt(oldIndentation, tabSize);
                            const newIndentation = indentUtils.generateIndent(newSpaceCnt, tabSize, insertSpaces);
                            insertingText = newIndentation + this.trimStart(movingLineText);
                        }
                        else {
                            // no enter rule matches, let's check indentatin rules then.
                            const virtualModel = {
                                tokenization: {
                                    getLineTokens: (lineNumber) => {
                                        if (lineNumber === s.startLineNumber) {
                                            return model.tokenization.getLineTokens(movingLineNumber);
                                        }
                                        else {
                                            return model.tokenization.getLineTokens(lineNumber);
                                        }
                                    },
                                    getLanguageId,
                                    getLanguageIdAtPosition,
                                },
                                getLineContent: (lineNumber) => {
                                    if (lineNumber === s.startLineNumber) {
                                        return model.getLineContent(movingLineNumber);
                                    }
                                    else {
                                        return model.getLineContent(lineNumber);
                                    }
                                },
                            };
                            const indentOfMovingLine = (0, autoIndent_1.getGoodIndentForLine)(this._autoIndent, virtualModel, model.getLanguageIdAtPosition(movingLineNumber, 1), s.startLineNumber, indentConverter, this._languageConfigurationService);
                            if (indentOfMovingLine !== null) {
                                const oldIndentation = strings.getLeadingWhitespace(model.getLineContent(movingLineNumber));
                                const newSpaceCnt = indentUtils.getSpaceCnt(indentOfMovingLine, tabSize);
                                const oldSpaceCnt = indentUtils.getSpaceCnt(oldIndentation, tabSize);
                                if (newSpaceCnt !== oldSpaceCnt) {
                                    const newIndentation = indentUtils.generateIndent(newSpaceCnt, tabSize, insertSpaces);
                                    insertingText = newIndentation + this.trimStart(movingLineText);
                                }
                            }
                        }
                        // add edit operations for moving line first to make sure it's executed after we make indentation change
                        // to s.startLineNumber
                        builder.addEditOperation(new range_1.Range(s.startLineNumber, 1, s.startLineNumber, 1), insertingText + '\n');
                        const ret = this.matchEnterRuleMovingDown(model, indentConverter, tabSize, s.startLineNumber, movingLineNumber, insertingText);
                        // check if the line being moved before matches onEnter rules, if so let's adjust the indentation by onEnter rules.
                        if (ret !== null) {
                            if (ret !== 0) {
                                this.getIndentEditsOfMovingBlock(model, builder, s, tabSize, insertSpaces, ret);
                            }
                        }
                        else {
                            // it doesn't match onEnter rules, let's check indentation rules then.
                            const virtualModel = {
                                tokenization: {
                                    getLineTokens: (lineNumber) => {
                                        if (lineNumber === s.startLineNumber) {
                                            // TODO@aiday-mar: the tokens here don't correspond exactly to the corresponding content (after indentation adjustment), have to fix this.
                                            return model.tokenization.getLineTokens(movingLineNumber);
                                        }
                                        else if (lineNumber >= s.startLineNumber + 1 && lineNumber <= s.endLineNumber + 1) {
                                            return model.tokenization.getLineTokens(lineNumber - 1);
                                        }
                                        else {
                                            return model.tokenization.getLineTokens(lineNumber);
                                        }
                                    },
                                    getLanguageId,
                                    getLanguageIdAtPosition,
                                },
                                getLineContent: (lineNumber) => {
                                    if (lineNumber === s.startLineNumber) {
                                        return insertingText;
                                    }
                                    else if (lineNumber >= s.startLineNumber + 1 && lineNumber <= s.endLineNumber + 1) {
                                        return model.getLineContent(lineNumber - 1);
                                    }
                                    else {
                                        return model.getLineContent(lineNumber);
                                    }
                                },
                            };
                            const newIndentatOfMovingBlock = (0, autoIndent_1.getGoodIndentForLine)(this._autoIndent, virtualModel, model.getLanguageIdAtPosition(movingLineNumber, 1), s.startLineNumber + 1, indentConverter, this._languageConfigurationService);
                            if (newIndentatOfMovingBlock !== null) {
                                const oldIndentation = strings.getLeadingWhitespace(model.getLineContent(s.startLineNumber));
                                const newSpaceCnt = indentUtils.getSpaceCnt(newIndentatOfMovingBlock, tabSize);
                                const oldSpaceCnt = indentUtils.getSpaceCnt(oldIndentation, tabSize);
                                if (newSpaceCnt !== oldSpaceCnt) {
                                    const spaceCntOffset = newSpaceCnt - oldSpaceCnt;
                                    this.getIndentEditsOfMovingBlock(model, builder, s, tabSize, insertSpaces, spaceCntOffset);
                                }
                            }
                        }
                    }
                    else {
                        // Insert line that needs to be moved before
                        builder.addEditOperation(new range_1.Range(s.startLineNumber, 1, s.startLineNumber, 1), insertingText + '\n');
                    }
                }
                else {
                    movingLineNumber = s.startLineNumber - 1;
                    movingLineText = model.getLineContent(movingLineNumber);
                    // Delete line that needs to be moved
                    builder.addEditOperation(new range_1.Range(movingLineNumber, 1, movingLineNumber + 1, 1), null);
                    // Insert line that needs to be moved after
                    builder.addEditOperation(new range_1.Range(s.endLineNumber, model.getLineMaxColumn(s.endLineNumber), s.endLineNumber, model.getLineMaxColumn(s.endLineNumber)), '\n' + movingLineText);
                    if (this.shouldAutoIndent(model, s)) {
                        const virtualModel = {
                            tokenization: {
                                getLineTokens: (lineNumber) => {
                                    if (lineNumber === movingLineNumber) {
                                        return model.tokenization.getLineTokens(s.startLineNumber);
                                    }
                                    else {
                                        return model.tokenization.getLineTokens(lineNumber);
                                    }
                                },
                                getLanguageId,
                                getLanguageIdAtPosition,
                            },
                            getLineContent: (lineNumber) => {
                                if (lineNumber === movingLineNumber) {
                                    return model.getLineContent(s.startLineNumber);
                                }
                                else {
                                    return model.getLineContent(lineNumber);
                                }
                            },
                        };
                        const ret = this.matchEnterRule(model, indentConverter, tabSize, s.startLineNumber, s.startLineNumber - 2);
                        // check if s.startLineNumber - 2 matches onEnter rules, if so adjust the moving block by onEnter rules.
                        if (ret !== null) {
                            if (ret !== 0) {
                                this.getIndentEditsOfMovingBlock(model, builder, s, tabSize, insertSpaces, ret);
                            }
                        }
                        else {
                            // it doesn't match any onEnter rule, let's check indentation rules then.
                            const indentOfFirstLine = (0, autoIndent_1.getGoodIndentForLine)(this._autoIndent, virtualModel, model.getLanguageIdAtPosition(s.startLineNumber, 1), movingLineNumber, indentConverter, this._languageConfigurationService);
                            if (indentOfFirstLine !== null) {
                                // adjust the indentation of the moving block
                                const oldIndent = strings.getLeadingWhitespace(model.getLineContent(s.startLineNumber));
                                const newSpaceCnt = indentUtils.getSpaceCnt(indentOfFirstLine, tabSize);
                                const oldSpaceCnt = indentUtils.getSpaceCnt(oldIndent, tabSize);
                                if (newSpaceCnt !== oldSpaceCnt) {
                                    const spaceCntOffset = newSpaceCnt - oldSpaceCnt;
                                    this.getIndentEditsOfMovingBlock(model, builder, s, tabSize, insertSpaces, spaceCntOffset);
                                }
                            }
                        }
                    }
                }
            }
            this._selectionId = builder.trackSelection(s);
        }
        buildIndentConverter(tabSize, indentSize, insertSpaces) {
            return {
                shiftIndent: (indentation) => {
                    return shiftCommand_1.ShiftCommand.shiftIndent(indentation, indentation.length + 1, tabSize, indentSize, insertSpaces);
                },
                unshiftIndent: (indentation) => {
                    return shiftCommand_1.ShiftCommand.unshiftIndent(indentation, indentation.length + 1, tabSize, indentSize, insertSpaces);
                }
            };
        }
        parseEnterResult(model, indentConverter, tabSize, line, enter) {
            if (enter) {
                let enterPrefix = enter.indentation;
                if (enter.indentAction === languageConfiguration_1.IndentAction.None) {
                    enterPrefix = enter.indentation + enter.appendText;
                }
                else if (enter.indentAction === languageConfiguration_1.IndentAction.Indent) {
                    enterPrefix = enter.indentation + enter.appendText;
                }
                else if (enter.indentAction === languageConfiguration_1.IndentAction.IndentOutdent) {
                    enterPrefix = enter.indentation;
                }
                else if (enter.indentAction === languageConfiguration_1.IndentAction.Outdent) {
                    enterPrefix = indentConverter.unshiftIndent(enter.indentation) + enter.appendText;
                }
                const movingLineText = model.getLineContent(line);
                if (this.trimStart(movingLineText).indexOf(this.trimStart(enterPrefix)) >= 0) {
                    const oldIndentation = strings.getLeadingWhitespace(model.getLineContent(line));
                    let newIndentation = strings.getLeadingWhitespace(enterPrefix);
                    const indentMetadataOfMovelingLine = (0, autoIndent_1.getIndentMetadata)(model, line, this._languageConfigurationService);
                    if (indentMetadataOfMovelingLine !== null && indentMetadataOfMovelingLine & 2 /* IndentConsts.DECREASE_MASK */) {
                        newIndentation = indentConverter.unshiftIndent(newIndentation);
                    }
                    const newSpaceCnt = indentUtils.getSpaceCnt(newIndentation, tabSize);
                    const oldSpaceCnt = indentUtils.getSpaceCnt(oldIndentation, tabSize);
                    return newSpaceCnt - oldSpaceCnt;
                }
            }
            return null;
        }
        /**
         *
         * @param model
         * @param indentConverter
         * @param tabSize
         * @param line the line moving down
         * @param futureAboveLineNumber the line which will be at the `line` position
         * @param futureAboveLineText
         */
        matchEnterRuleMovingDown(model, indentConverter, tabSize, line, futureAboveLineNumber, futureAboveLineText) {
            if (strings.lastNonWhitespaceIndex(futureAboveLineText) >= 0) {
                // break
                const maxColumn = model.getLineMaxColumn(futureAboveLineNumber);
                const enter = (0, enterAction_1.getEnterAction)(this._autoIndent, model, new range_1.Range(futureAboveLineNumber, maxColumn, futureAboveLineNumber, maxColumn), this._languageConfigurationService);
                return this.parseEnterResult(model, indentConverter, tabSize, line, enter);
            }
            else {
                // go upwards, starting from `line - 1`
                let validPrecedingLine = line - 1;
                while (validPrecedingLine >= 1) {
                    const lineContent = model.getLineContent(validPrecedingLine);
                    const nonWhitespaceIdx = strings.lastNonWhitespaceIndex(lineContent);
                    if (nonWhitespaceIdx >= 0) {
                        break;
                    }
                    validPrecedingLine--;
                }
                if (validPrecedingLine < 1 || line > model.getLineCount()) {
                    return null;
                }
                const maxColumn = model.getLineMaxColumn(validPrecedingLine);
                const enter = (0, enterAction_1.getEnterAction)(this._autoIndent, model, new range_1.Range(validPrecedingLine, maxColumn, validPrecedingLine, maxColumn), this._languageConfigurationService);
                return this.parseEnterResult(model, indentConverter, tabSize, line, enter);
            }
        }
        matchEnterRule(model, indentConverter, tabSize, line, oneLineAbove, previousLineText) {
            let validPrecedingLine = oneLineAbove;
            while (validPrecedingLine >= 1) {
                // ship empty lines as empty lines just inherit indentation
                let lineContent;
                if (validPrecedingLine === oneLineAbove && previousLineText !== undefined) {
                    lineContent = previousLineText;
                }
                else {
                    lineContent = model.getLineContent(validPrecedingLine);
                }
                const nonWhitespaceIdx = strings.lastNonWhitespaceIndex(lineContent);
                if (nonWhitespaceIdx >= 0) {
                    break;
                }
                validPrecedingLine--;
            }
            if (validPrecedingLine < 1 || line > model.getLineCount()) {
                return null;
            }
            const maxColumn = model.getLineMaxColumn(validPrecedingLine);
            const enter = (0, enterAction_1.getEnterAction)(this._autoIndent, model, new range_1.Range(validPrecedingLine, maxColumn, validPrecedingLine, maxColumn), this._languageConfigurationService);
            return this.parseEnterResult(model, indentConverter, tabSize, line, enter);
        }
        trimStart(str) {
            return str.replace(/^\s+/, '');
        }
        shouldAutoIndent(model, selection) {
            if (this._autoIndent < 4 /* EditorAutoIndentStrategy.Full */) {
                return false;
            }
            // if it's not easy to tokenize, we stop auto indent.
            if (!model.tokenization.isCheapToTokenize(selection.startLineNumber)) {
                return false;
            }
            const languageAtSelectionStart = model.getLanguageIdAtPosition(selection.startLineNumber, 1);
            const languageAtSelectionEnd = model.getLanguageIdAtPosition(selection.endLineNumber, 1);
            if (languageAtSelectionStart !== languageAtSelectionEnd) {
                return false;
            }
            if (this._languageConfigurationService.getLanguageConfiguration(languageAtSelectionStart).indentRulesSupport === null) {
                return false;
            }
            return true;
        }
        getIndentEditsOfMovingBlock(model, builder, s, tabSize, insertSpaces, offset) {
            for (let i = s.startLineNumber; i <= s.endLineNumber; i++) {
                const lineContent = model.getLineContent(i);
                const originalIndent = strings.getLeadingWhitespace(lineContent);
                const originalSpacesCnt = indentUtils.getSpaceCnt(originalIndent, tabSize);
                const newSpacesCnt = originalSpacesCnt + offset;
                const newIndent = indentUtils.generateIndent(newSpacesCnt, tabSize, insertSpaces);
                if (newIndent !== originalIndent) {
                    builder.addEditOperation(new range_1.Range(i, 1, i, originalIndent.length + 1), newIndent);
                    if (i === s.endLineNumber && s.endColumn <= originalIndent.length + 1 && newIndent === '') {
                        // as users select part of the original indent white spaces
                        // when we adjust the indentation of endLine, we should adjust the cursor position as well.
                        this._moveEndLineSelectionShrink = true;
                    }
                }
            }
        }
        computeCursorState(model, helper) {
            let result = helper.getTrackedSelection(this._selectionId);
            if (this._moveEndPositionDown) {
                result = result.setEndPosition(result.endLineNumber + 1, 1);
            }
            if (this._moveEndLineSelectionShrink && result.startLineNumber < result.endLineNumber) {
                result = result.setEndPosition(result.endLineNumber, 2);
            }
            return result;
        }
    };
    exports.MoveLinesCommand = MoveLinesCommand;
    exports.MoveLinesCommand = MoveLinesCommand = __decorate([
        __param(3, languageConfigurationRegistry_1.ILanguageConfigurationService)
    ], MoveLinesCommand);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[402/*vs/editor/contrib/suggest/browser/suggestWidgetDetails*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,86/*vs/base/browser/ui/scrollbar/scrollableElement*/,26/*vs/base/common/codicons*/,30/*vs/base/common/themables*/,6/*vs/base/common/event*/,57/*vs/base/common/htmlContent*/,2/*vs/base/common/lifecycle*/,120/*vs/editor/browser/widget/markdownRenderer/browser/markdownRenderer*/,255/*vs/base/browser/ui/resizable/resizable*/,3/*vs/nls*/,7/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, dom, scrollableElement_1, codicons_1, themables_1, event_1, htmlContent_1, lifecycle_1, markdownRenderer_1, resizable_1, nls, instantiation_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SuggestDetailsOverlay = exports.SuggestDetailsWidget = void 0;
    exports.canExpandCompletionItem = canExpandCompletionItem;
    function canExpandCompletionItem(item) {
        return !!item && Boolean(item.completion.documentation || item.completion.detail && item.completion.detail !== item.completion.label);
    }
    let SuggestDetailsWidget = class SuggestDetailsWidget {
        constructor(_editor, instaService) {
            this._editor = _editor;
            this._onDidClose = new event_1.Emitter();
            this.onDidClose = this._onDidClose.event;
            this._onDidChangeContents = new event_1.Emitter();
            this.onDidChangeContents = this._onDidChangeContents.event;
            this._disposables = new lifecycle_1.DisposableStore();
            this._renderDisposeable = new lifecycle_1.DisposableStore();
            this._borderWidth = 1;
            this._size = new dom.Dimension(330, 0);
            this.domNode = dom.$('.suggest-details');
            this.domNode.classList.add('no-docs');
            this._markdownRenderer = instaService.createInstance(markdownRenderer_1.MarkdownRenderer, { editor: _editor });
            this._body = dom.$('.body');
            this._scrollbar = new scrollableElement_1.DomScrollableElement(this._body, {
                alwaysConsumeMouseWheel: true,
            });
            dom.append(this.domNode, this._scrollbar.getDomNode());
            this._disposables.add(this._scrollbar);
            this._header = dom.append(this._body, dom.$('.header'));
            this._close = dom.append(this._header, dom.$('span' + themables_1.ThemeIcon.asCSSSelector(codicons_1.Codicon.close)));
            this._close.title = nls.localize(1344, "Close");
            this._type = dom.append(this._header, dom.$('p.type'));
            this._docs = dom.append(this._body, dom.$('p.docs'));
            this._configureFont();
            this._disposables.add(this._editor.onDidChangeConfiguration(e => {
                if (e.hasChanged(50 /* EditorOption.fontInfo */)) {
                    this._configureFont();
                }
            }));
        }
        dispose() {
            this._disposables.dispose();
            this._renderDisposeable.dispose();
        }
        _configureFont() {
            const options = this._editor.getOptions();
            const fontInfo = options.get(50 /* EditorOption.fontInfo */);
            const fontFamily = fontInfo.getMassagedFontFamily();
            const fontSize = options.get(120 /* EditorOption.suggestFontSize */) || fontInfo.fontSize;
            const lineHeight = options.get(121 /* EditorOption.suggestLineHeight */) || fontInfo.lineHeight;
            const fontWeight = fontInfo.fontWeight;
            const fontSizePx = `${fontSize}px`;
            const lineHeightPx = `${lineHeight}px`;
            this.domNode.style.fontSize = fontSizePx;
            this.domNode.style.lineHeight = `${lineHeight / fontSize}`;
            this.domNode.style.fontWeight = fontWeight;
            this.domNode.style.fontFeatureSettings = fontInfo.fontFeatureSettings;
            this._type.style.fontFamily = fontFamily;
            this._close.style.height = lineHeightPx;
            this._close.style.width = lineHeightPx;
        }
        getLayoutInfo() {
            const lineHeight = this._editor.getOption(121 /* EditorOption.suggestLineHeight */) || this._editor.getOption(50 /* EditorOption.fontInfo */).lineHeight;
            const borderWidth = this._borderWidth;
            const borderHeight = borderWidth * 2;
            return {
                lineHeight,
                borderWidth,
                borderHeight,
                verticalPadding: 22,
                horizontalPadding: 14
            };
        }
        renderLoading() {
            this._type.textContent = nls.localize(1345, "Loading...");
            this._docs.textContent = '';
            this.domNode.classList.remove('no-docs', 'no-type');
            this.layout(this.size.width, this.getLayoutInfo().lineHeight * 2);
            this._onDidChangeContents.fire(this);
        }
        renderItem(item, explainMode) {
            this._renderDisposeable.clear();
            let { detail, documentation } = item.completion;
            if (explainMode) {
                let md = '';
                md += `score: ${item.score[0]}\n`;
                md += `prefix: ${item.word ?? '(no prefix)'}\n`;
                md += `word: ${item.completion.filterText ? item.completion.filterText + ' (filterText)' : item.textLabel}\n`;
                md += `distance: ${item.distance} (localityBonus-setting)\n`;
                md += `index: ${item.idx}, based on ${item.completion.sortText && `sortText: "${item.completion.sortText}"` || 'label'}\n`;
                md += `commit_chars: ${item.completion.commitCharacters?.join('')}\n`;
                documentation = new htmlContent_1.MarkdownString().appendCodeblock('empty', md);
                detail = `Provider: ${item.provider._debugDisplayName}`;
            }
            if (!explainMode && !canExpandCompletionItem(item)) {
                this.clearContents();
                return;
            }
            this.domNode.classList.remove('no-docs', 'no-type');
            // --- details
            if (detail) {
                const cappedDetail = detail.length > 100000 ? `${detail.substr(0, 100000)}…` : detail;
                this._type.textContent = cappedDetail;
                this._type.title = cappedDetail;
                dom.show(this._type);
                this._type.classList.toggle('auto-wrap', !/\r?\n^\s+/gmi.test(cappedDetail));
            }
            else {
                dom.clearNode(this._type);
                this._type.title = '';
                dom.hide(this._type);
                this.domNode.classList.add('no-type');
            }
            // --- documentation
            dom.clearNode(this._docs);
            if (typeof documentation === 'string') {
                this._docs.classList.remove('markdown-docs');
                this._docs.textContent = documentation;
            }
            else if (documentation) {
                this._docs.classList.add('markdown-docs');
                dom.clearNode(this._docs);
                const renderedContents = this._markdownRenderer.render(documentation);
                this._docs.appendChild(renderedContents.element);
                this._renderDisposeable.add(renderedContents);
                this._renderDisposeable.add(this._markdownRenderer.onDidRenderAsync(() => {
                    this.layout(this._size.width, this._type.clientHeight + this._docs.clientHeight);
                    this._onDidChangeContents.fire(this);
                }));
            }
            this.domNode.style.userSelect = 'text';
            this.domNode.tabIndex = -1;
            this._close.onmousedown = e => {
                e.preventDefault();
                e.stopPropagation();
            };
            this._close.onclick = e => {
                e.preventDefault();
                e.stopPropagation();
                this._onDidClose.fire();
            };
            this._body.scrollTop = 0;
            this.layout(this._size.width, this._type.clientHeight + this._docs.clientHeight);
            this._onDidChangeContents.fire(this);
        }
        clearContents() {
            this.domNode.classList.add('no-docs');
            this._type.textContent = '';
            this._docs.textContent = '';
        }
        get isEmpty() {
            return this.domNode.classList.contains('no-docs');
        }
        get size() {
            return this._size;
        }
        layout(width, height) {
            const newSize = new dom.Dimension(width, height);
            if (!dom.Dimension.equals(newSize, this._size)) {
                this._size = newSize;
                dom.size(this.domNode, width, height);
            }
            this._scrollbar.scanDomNode();
        }
        scrollDown(much = 8) {
            this._body.scrollTop += much;
        }
        scrollUp(much = 8) {
            this._body.scrollTop -= much;
        }
        scrollTop() {
            this._body.scrollTop = 0;
        }
        scrollBottom() {
            this._body.scrollTop = this._body.scrollHeight;
        }
        pageDown() {
            this.scrollDown(80);
        }
        pageUp() {
            this.scrollUp(80);
        }
        set borderWidth(width) {
            this._borderWidth = width;
        }
        get borderWidth() {
            return this._borderWidth;
        }
    };
    exports.SuggestDetailsWidget = SuggestDetailsWidget;
    exports.SuggestDetailsWidget = SuggestDetailsWidget = __decorate([
        __param(1, instantiation_1.IInstantiationService)
    ], SuggestDetailsWidget);
    class SuggestDetailsOverlay {
        constructor(widget, _editor) {
            this.widget = widget;
            this._editor = _editor;
            this.allowEditorOverflow = true;
            this._disposables = new lifecycle_1.DisposableStore();
            this._added = false;
            this._preferAlignAtTop = true;
            this._resizable = new resizable_1.ResizableHTMLElement();
            this._resizable.domNode.classList.add('suggest-details-container');
            this._resizable.domNode.appendChild(widget.domNode);
            this._resizable.enableSashes(false, true, true, false);
            let topLeftNow;
            let sizeNow;
            let deltaTop = 0;
            let deltaLeft = 0;
            this._disposables.add(this._resizable.onDidWillResize(() => {
                topLeftNow = this._topLeft;
                sizeNow = this._resizable.size;
            }));
            this._disposables.add(this._resizable.onDidResize(e => {
                if (topLeftNow && sizeNow) {
                    this.widget.layout(e.dimension.width, e.dimension.height);
                    let updateTopLeft = false;
                    if (e.west) {
                        deltaLeft = sizeNow.width - e.dimension.width;
                        updateTopLeft = true;
                    }
                    if (e.north) {
                        deltaTop = sizeNow.height - e.dimension.height;
                        updateTopLeft = true;
                    }
                    if (updateTopLeft) {
                        this._applyTopLeft({
                            top: topLeftNow.top + deltaTop,
                            left: topLeftNow.left + deltaLeft,
                        });
                    }
                }
                if (e.done) {
                    topLeftNow = undefined;
                    sizeNow = undefined;
                    deltaTop = 0;
                    deltaLeft = 0;
                    this._userSize = e.dimension;
                }
            }));
            this._disposables.add(this.widget.onDidChangeContents(() => {
                if (this._anchorBox) {
                    this._placeAtAnchor(this._anchorBox, this._userSize ?? this.widget.size, this._preferAlignAtTop);
                }
            }));
        }
        dispose() {
            this._resizable.dispose();
            this._disposables.dispose();
            this.hide();
        }
        getId() {
            return 'suggest.details';
        }
        getDomNode() {
            return this._resizable.domNode;
        }
        getPosition() {
            return this._topLeft ? { preference: this._topLeft } : null;
        }
        show() {
            if (!this._added) {
                this._editor.addOverlayWidget(this);
                this._added = true;
            }
        }
        hide(sessionEnded = false) {
            this._resizable.clearSashHoverState();
            if (this._added) {
                this._editor.removeOverlayWidget(this);
                this._added = false;
                this._anchorBox = undefined;
                this._topLeft = undefined;
            }
            if (sessionEnded) {
                this._userSize = undefined;
                this.widget.clearContents();
            }
        }
        placeAtAnchor(anchor, preferAlignAtTop) {
            const anchorBox = anchor.getBoundingClientRect();
            this._anchorBox = anchorBox;
            this._preferAlignAtTop = preferAlignAtTop;
            this._placeAtAnchor(this._anchorBox, this._userSize ?? this.widget.size, preferAlignAtTop);
        }
        _placeAtAnchor(anchorBox, size, preferAlignAtTop) {
            const bodyBox = dom.getClientArea(this.getDomNode().ownerDocument.body);
            const info = this.widget.getLayoutInfo();
            const defaultMinSize = new dom.Dimension(220, 2 * info.lineHeight);
            const defaultTop = anchorBox.top;
            // EAST
            const eastPlacement = (function () {
                const width = bodyBox.width - (anchorBox.left + anchorBox.width + info.borderWidth + info.horizontalPadding);
                const left = -info.borderWidth + anchorBox.left + anchorBox.width;
                const maxSizeTop = new dom.Dimension(width, bodyBox.height - anchorBox.top - info.borderHeight - info.verticalPadding);
                const maxSizeBottom = maxSizeTop.with(undefined, anchorBox.top + anchorBox.height - info.borderHeight - info.verticalPadding);
                return { top: defaultTop, left, fit: width - size.width, maxSizeTop, maxSizeBottom, minSize: defaultMinSize.with(Math.min(width, defaultMinSize.width)) };
            })();
            // WEST
            const westPlacement = (function () {
                const width = anchorBox.left - info.borderWidth - info.horizontalPadding;
                const left = Math.max(info.horizontalPadding, anchorBox.left - size.width - info.borderWidth);
                const maxSizeTop = new dom.Dimension(width, bodyBox.height - anchorBox.top - info.borderHeight - info.verticalPadding);
                const maxSizeBottom = maxSizeTop.with(undefined, anchorBox.top + anchorBox.height - info.borderHeight - info.verticalPadding);
                return { top: defaultTop, left, fit: width - size.width, maxSizeTop, maxSizeBottom, minSize: defaultMinSize.with(Math.min(width, defaultMinSize.width)) };
            })();
            // SOUTH
            const southPacement = (function () {
                const left = anchorBox.left;
                const top = -info.borderWidth + anchorBox.top + anchorBox.height;
                const maxSizeBottom = new dom.Dimension(anchorBox.width - info.borderHeight, bodyBox.height - anchorBox.top - anchorBox.height - info.verticalPadding);
                return { top, left, fit: maxSizeBottom.height - size.height, maxSizeBottom, maxSizeTop: maxSizeBottom, minSize: defaultMinSize.with(maxSizeBottom.width) };
            })();
            // take first placement that fits or the first with "least bad" fit
            const placements = [eastPlacement, westPlacement, southPacement];
            const placement = placements.find(p => p.fit >= 0) ?? placements.sort((a, b) => b.fit - a.fit)[0];
            // top/bottom placement
            const bottom = anchorBox.top + anchorBox.height - info.borderHeight;
            let alignAtTop;
            let height = size.height;
            const maxHeight = Math.max(placement.maxSizeTop.height, placement.maxSizeBottom.height);
            if (height > maxHeight) {
                height = maxHeight;
            }
            let maxSize;
            if (preferAlignAtTop) {
                if (height <= placement.maxSizeTop.height) {
                    alignAtTop = true;
                    maxSize = placement.maxSizeTop;
                }
                else {
                    alignAtTop = false;
                    maxSize = placement.maxSizeBottom;
                }
            }
            else {
                if (height <= placement.maxSizeBottom.height) {
                    alignAtTop = false;
                    maxSize = placement.maxSizeBottom;
                }
                else {
                    alignAtTop = true;
                    maxSize = placement.maxSizeTop;
                }
            }
            let { top, left } = placement;
            if (!alignAtTop && height > anchorBox.height) {
                top = bottom - height;
            }
            const editorDomNode = this._editor.getDomNode();
            if (editorDomNode) {
                // get bounding rectangle of the suggest widget relative to the editor
                const editorBoundingBox = editorDomNode.getBoundingClientRect();
                top -= editorBoundingBox.top;
                left -= editorBoundingBox.left;
            }
            this._applyTopLeft({ left, top });
            this._resizable.enableSashes(!alignAtTop, placement === eastPlacement, alignAtTop, placement !== eastPlacement);
            this._resizable.minSize = placement.minSize;
            this._resizable.maxSize = maxSize;
            this._resizable.layout(height, Math.min(maxSize.width, size.width));
            this.widget.layout(this._resizable.size.width, this._resizable.size.height);
        }
        _applyTopLeft(topLeft) {
            this._topLeft = topLeft;
            this._editor.layoutOverlayWidget(this);
        }
    }
    exports.SuggestDetailsOverlay = SuggestDetailsOverlay;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[403/*vs/platform/configuration/common/configurationModels*/], __M([1/*require*/,0/*exports*/,13/*vs/base/common/arrays*/,45/*vs/base/common/map*/,60/*vs/base/common/objects*/,19/*vs/base/common/types*/,22/*vs/base/common/uri*/,28/*vs/platform/configuration/common/configuration*/,109/*vs/platform/configuration/common/configurationRegistry*/,38/*vs/platform/registry/common/platform*/]), function (require, exports, arrays, map_1, objects, types, uri_1, configuration_1, configurationRegistry_1, platform_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ConfigurationChangeEvent = exports.Configuration = exports.ConfigurationModelParser = exports.ConfigurationModel = void 0;
    function freeze(data) {
        return Object.isFrozen(data) ? data : objects.deepFreeze(data);
    }
    class ConfigurationModel {
        static createEmptyModel(logService) {
            return new ConfigurationModel({}, [], [], undefined, logService);
        }
        constructor(_contents, _keys, _overrides, raw, logService) {
            this._contents = _contents;
            this._keys = _keys;
            this._overrides = _overrides;
            this.raw = raw;
            this.logService = logService;
            this.overrideConfigurations = new Map();
        }
        get rawConfiguration() {
            if (!this._rawConfiguration) {
                if (this.raw?.length) {
                    const rawConfigurationModels = this.raw.map(raw => {
                        if (raw instanceof ConfigurationModel) {
                            return raw;
                        }
                        const parser = new ConfigurationModelParser('', this.logService);
                        parser.parseRaw(raw);
                        return parser.configurationModel;
                    });
                    this._rawConfiguration = rawConfigurationModels.reduce((previous, current) => current === previous ? current : previous.merge(current), rawConfigurationModels[0]);
                }
                else {
                    // raw is same as current
                    this._rawConfiguration = this;
                }
            }
            return this._rawConfiguration;
        }
        get contents() {
            return this._contents;
        }
        get overrides() {
            return this._overrides;
        }
        get keys() {
            return this._keys;
        }
        isEmpty() {
            return this._keys.length === 0 && Object.keys(this._contents).length === 0 && this._overrides.length === 0;
        }
        getValue(section) {
            return section ? (0, configuration_1.getConfigurationValue)(this.contents, section) : this.contents;
        }
        inspect(section, overrideIdentifier) {
            const that = this;
            return {
                get value() {
                    return freeze(that.rawConfiguration.getValue(section));
                },
                get override() {
                    return overrideIdentifier ? freeze(that.rawConfiguration.getOverrideValue(section, overrideIdentifier)) : undefined;
                },
                get merged() {
                    return freeze(overrideIdentifier ? that.rawConfiguration.override(overrideIdentifier).getValue(section) : that.rawConfiguration.getValue(section));
                },
                get overrides() {
                    const overrides = [];
                    for (const { contents, identifiers, keys } of that.rawConfiguration.overrides) {
                        const value = new ConfigurationModel(contents, keys, [], undefined, that.logService).getValue(section);
                        if (value !== undefined) {
                            overrides.push({ identifiers, value });
                        }
                    }
                    return overrides.length ? freeze(overrides) : undefined;
                }
            };
        }
        getOverrideValue(section, overrideIdentifier) {
            const overrideContents = this.getContentsForOverrideIdentifer(overrideIdentifier);
            return overrideContents
                ? section ? (0, configuration_1.getConfigurationValue)(overrideContents, section) : overrideContents
                : undefined;
        }
        override(identifier) {
            let overrideConfigurationModel = this.overrideConfigurations.get(identifier);
            if (!overrideConfigurationModel) {
                overrideConfigurationModel = this.createOverrideConfigurationModel(identifier);
                this.overrideConfigurations.set(identifier, overrideConfigurationModel);
            }
            return overrideConfigurationModel;
        }
        merge(...others) {
            const contents = objects.deepClone(this.contents);
            const overrides = objects.deepClone(this.overrides);
            const keys = [...this.keys];
            const raws = this.raw?.length ? [...this.raw] : [this];
            for (const other of others) {
                raws.push(...(other.raw?.length ? other.raw : [other]));
                if (other.isEmpty()) {
                    continue;
                }
                this.mergeContents(contents, other.contents);
                for (const otherOverride of other.overrides) {
                    const [override] = overrides.filter(o => arrays.equals(o.identifiers, otherOverride.identifiers));
                    if (override) {
                        this.mergeContents(override.contents, otherOverride.contents);
                        override.keys.push(...otherOverride.keys);
                        override.keys = arrays.distinct(override.keys);
                    }
                    else {
                        overrides.push(objects.deepClone(otherOverride));
                    }
                }
                for (const key of other.keys) {
                    if (keys.indexOf(key) === -1) {
                        keys.push(key);
                    }
                }
            }
            return new ConfigurationModel(contents, keys, overrides, raws.every(raw => raw instanceof ConfigurationModel) ? undefined : raws, this.logService);
        }
        createOverrideConfigurationModel(identifier) {
            const overrideContents = this.getContentsForOverrideIdentifer(identifier);
            if (!overrideContents || typeof overrideContents !== 'object' || !Object.keys(overrideContents).length) {
                // If there are no valid overrides, return self
                return this;
            }
            const contents = {};
            for (const key of arrays.distinct([...Object.keys(this.contents), ...Object.keys(overrideContents)])) {
                let contentsForKey = this.contents[key];
                const overrideContentsForKey = overrideContents[key];
                // If there are override contents for the key, clone and merge otherwise use base contents
                if (overrideContentsForKey) {
                    // Clone and merge only if base contents and override contents are of type object otherwise just override
                    if (typeof contentsForKey === 'object' && typeof overrideContentsForKey === 'object') {
                        contentsForKey = objects.deepClone(contentsForKey);
                        this.mergeContents(contentsForKey, overrideContentsForKey);
                    }
                    else {
                        contentsForKey = overrideContentsForKey;
                    }
                }
                contents[key] = contentsForKey;
            }
            return new ConfigurationModel(contents, this.keys, this.overrides, undefined, this.logService);
        }
        mergeContents(source, target) {
            for (const key of Object.keys(target)) {
                if (key in source) {
                    if (types.isObject(source[key]) && types.isObject(target[key])) {
                        this.mergeContents(source[key], target[key]);
                        continue;
                    }
                }
                source[key] = objects.deepClone(target[key]);
            }
        }
        getContentsForOverrideIdentifer(identifier) {
            let contentsForIdentifierOnly = null;
            let contents = null;
            const mergeContents = (contentsToMerge) => {
                if (contentsToMerge) {
                    if (contents) {
                        this.mergeContents(contents, contentsToMerge);
                    }
                    else {
                        contents = objects.deepClone(contentsToMerge);
                    }
                }
            };
            for (const override of this.overrides) {
                if (override.identifiers.length === 1 && override.identifiers[0] === identifier) {
                    contentsForIdentifierOnly = override.contents;
                }
                else if (override.identifiers.includes(identifier)) {
                    mergeContents(override.contents);
                }
            }
            // Merge contents of the identifier only at the end to take precedence.
            mergeContents(contentsForIdentifierOnly);
            return contents;
        }
        toJSON() {
            return {
                contents: this.contents,
                overrides: this.overrides,
                keys: this.keys
            };
        }
        setValue(key, value) {
            this.updateValue(key, value, false);
        }
        removeValue(key) {
            const index = this.keys.indexOf(key);
            if (index === -1) {
                return;
            }
            this.keys.splice(index, 1);
            (0, configuration_1.removeFromValueTree)(this.contents, key);
            if (configurationRegistry_1.OVERRIDE_PROPERTY_REGEX.test(key)) {
                this.overrides.splice(this.overrides.findIndex(o => arrays.equals(o.identifiers, (0, configurationRegistry_1.overrideIdentifiersFromKey)(key))), 1);
            }
        }
        updateValue(key, value, add) {
            (0, configuration_1.addToValueTree)(this.contents, key, value, e => this.logService.error(e));
            add = add || this.keys.indexOf(key) === -1;
            if (add) {
                this.keys.push(key);
            }
            if (configurationRegistry_1.OVERRIDE_PROPERTY_REGEX.test(key)) {
                const identifiers = (0, configurationRegistry_1.overrideIdentifiersFromKey)(key);
                const override = {
                    identifiers,
                    keys: Object.keys(this.contents[key]),
                    contents: (0, configuration_1.toValuesTree)(this.contents[key], message => this.logService.error(message)),
                };
                const index = this.overrides.findIndex(o => arrays.equals(o.identifiers, identifiers));
                if (index !== -1) {
                    this.overrides[index] = override;
                }
                else {
                    this.overrides.push(override);
                }
            }
        }
    }
    exports.ConfigurationModel = ConfigurationModel;
    class ConfigurationModelParser {
        constructor(_name, logService) {
            this._name = _name;
            this.logService = logService;
            this._raw = null;
            this._configurationModel = null;
            this._restrictedConfigurations = [];
        }
        get configurationModel() {
            return this._configurationModel || ConfigurationModel.createEmptyModel(this.logService);
        }
        parseRaw(raw, options) {
            this._raw = raw;
            const { contents, keys, overrides, restricted, hasExcludedProperties } = this.doParseRaw(raw, options);
            this._configurationModel = new ConfigurationModel(contents, keys, overrides, hasExcludedProperties ? [raw] : undefined /* raw has not changed */, this.logService);
            this._restrictedConfigurations = restricted || [];
        }
        doParseRaw(raw, options) {
            const configurationProperties = platform_1.Registry.as(configurationRegistry_1.Extensions.Configuration).getConfigurationProperties();
            const filtered = this.filter(raw, configurationProperties, true, options);
            raw = filtered.raw;
            const contents = (0, configuration_1.toValuesTree)(raw, message => this.logService.error(`Conflict in settings file ${this._name}: ${message}`));
            const keys = Object.keys(raw);
            const overrides = this.toOverrides(raw, message => this.logService.error(`Conflict in settings file ${this._name}: ${message}`));
            return { contents, keys, overrides, restricted: filtered.restricted, hasExcludedProperties: filtered.hasExcludedProperties };
        }
        filter(properties, configurationProperties, filterOverriddenProperties, options) {
            let hasExcludedProperties = false;
            if (!options?.scopes && !options?.skipRestricted && !options?.exclude?.length) {
                return { raw: properties, restricted: [], hasExcludedProperties };
            }
            const raw = {};
            const restricted = [];
            for (const key in properties) {
                if (configurationRegistry_1.OVERRIDE_PROPERTY_REGEX.test(key) && filterOverriddenProperties) {
                    const result = this.filter(properties[key], configurationProperties, false, options);
                    raw[key] = result.raw;
                    hasExcludedProperties = hasExcludedProperties || result.hasExcludedProperties;
                    restricted.push(...result.restricted);
                }
                else {
                    const propertySchema = configurationProperties[key];
                    const scope = propertySchema ? typeof propertySchema.scope !== 'undefined' ? propertySchema.scope : 3 /* ConfigurationScope.WINDOW */ : undefined;
                    if (propertySchema?.restricted) {
                        restricted.push(key);
                    }
                    if (!options.exclude?.includes(key) /* Check exclude */
                        && (options.include?.includes(key) /* Check include */
                            || ((scope === undefined || options.scopes === undefined || options.scopes.includes(scope)) /* Check scopes */
                                && !(options.skipRestricted && propertySchema?.restricted)))) /* Check restricted */ {
                        raw[key] = properties[key];
                    }
                    else {
                        hasExcludedProperties = true;
                    }
                }
            }
            return { raw, restricted, hasExcludedProperties };
        }
        toOverrides(raw, conflictReporter) {
            const overrides = [];
            for (const key of Object.keys(raw)) {
                if (configurationRegistry_1.OVERRIDE_PROPERTY_REGEX.test(key)) {
                    const overrideRaw = {};
                    for (const keyInOverrideRaw in raw[key]) {
                        overrideRaw[keyInOverrideRaw] = raw[key][keyInOverrideRaw];
                    }
                    overrides.push({
                        identifiers: (0, configurationRegistry_1.overrideIdentifiersFromKey)(key),
                        keys: Object.keys(overrideRaw),
                        contents: (0, configuration_1.toValuesTree)(overrideRaw, conflictReporter)
                    });
                }
            }
            return overrides;
        }
    }
    exports.ConfigurationModelParser = ConfigurationModelParser;
    class ConfigurationInspectValue {
        constructor(key, overrides, _value, overrideIdentifiers, defaultConfiguration, policyConfiguration, applicationConfiguration, userConfiguration, localUserConfiguration, remoteUserConfiguration, workspaceConfiguration, folderConfigurationModel, memoryConfigurationModel) {
            this.key = key;
            this.overrides = overrides;
            this._value = _value;
            this.overrideIdentifiers = overrideIdentifiers;
            this.defaultConfiguration = defaultConfiguration;
            this.policyConfiguration = policyConfiguration;
            this.applicationConfiguration = applicationConfiguration;
            this.userConfiguration = userConfiguration;
            this.localUserConfiguration = localUserConfiguration;
            this.remoteUserConfiguration = remoteUserConfiguration;
            this.workspaceConfiguration = workspaceConfiguration;
            this.folderConfigurationModel = folderConfigurationModel;
            this.memoryConfigurationModel = memoryConfigurationModel;
        }
        toInspectValue(inspectValue) {
            return inspectValue?.value !== undefined || inspectValue?.override !== undefined || inspectValue?.overrides !== undefined ? inspectValue : undefined;
        }
        get userInspectValue() {
            if (!this._userInspectValue) {
                this._userInspectValue = this.userConfiguration.inspect(this.key, this.overrides.overrideIdentifier);
            }
            return this._userInspectValue;
        }
        get user() {
            return this.toInspectValue(this.userInspectValue);
        }
    }
    class Configuration {
        constructor(_defaultConfiguration, _policyConfiguration, _applicationConfiguration, _localUserConfiguration, _remoteUserConfiguration, _workspaceConfiguration, _folderConfigurations, _memoryConfiguration, _memoryConfigurationByResource, logService) {
            this._defaultConfiguration = _defaultConfiguration;
            this._policyConfiguration = _policyConfiguration;
            this._applicationConfiguration = _applicationConfiguration;
            this._localUserConfiguration = _localUserConfiguration;
            this._remoteUserConfiguration = _remoteUserConfiguration;
            this._workspaceConfiguration = _workspaceConfiguration;
            this._folderConfigurations = _folderConfigurations;
            this._memoryConfiguration = _memoryConfiguration;
            this._memoryConfigurationByResource = _memoryConfigurationByResource;
            this.logService = logService;
            this._workspaceConsolidatedConfiguration = null;
            this._foldersConsolidatedConfigurations = new map_1.ResourceMap();
            this._userConfiguration = null;
        }
        getValue(section, overrides, workspace) {
            const consolidateConfigurationModel = this.getConsolidatedConfigurationModel(section, overrides, workspace);
            return consolidateConfigurationModel.getValue(section);
        }
        updateValue(key, value, overrides = {}) {
            let memoryConfiguration;
            if (overrides.resource) {
                memoryConfiguration = this._memoryConfigurationByResource.get(overrides.resource);
                if (!memoryConfiguration) {
                    memoryConfiguration = ConfigurationModel.createEmptyModel(this.logService);
                    this._memoryConfigurationByResource.set(overrides.resource, memoryConfiguration);
                }
            }
            else {
                memoryConfiguration = this._memoryConfiguration;
            }
            if (value === undefined) {
                memoryConfiguration.removeValue(key);
            }
            else {
                memoryConfiguration.setValue(key, value);
            }
            if (!overrides.resource) {
                this._workspaceConsolidatedConfiguration = null;
            }
        }
        inspect(key, overrides, workspace) {
            const consolidateConfigurationModel = this.getConsolidatedConfigurationModel(key, overrides, workspace);
            const folderConfigurationModel = this.getFolderConfigurationModelForResource(overrides.resource, workspace);
            const memoryConfigurationModel = overrides.resource ? this._memoryConfigurationByResource.get(overrides.resource) || this._memoryConfiguration : this._memoryConfiguration;
            const overrideIdentifiers = new Set();
            for (const override of consolidateConfigurationModel.overrides) {
                for (const overrideIdentifier of override.identifiers) {
                    if (consolidateConfigurationModel.getOverrideValue(key, overrideIdentifier) !== undefined) {
                        overrideIdentifiers.add(overrideIdentifier);
                    }
                }
            }
            return new ConfigurationInspectValue(key, overrides, consolidateConfigurationModel.getValue(key), overrideIdentifiers.size ? [...overrideIdentifiers] : undefined, this._defaultConfiguration, this._policyConfiguration.isEmpty() ? undefined : this._policyConfiguration, this.applicationConfiguration.isEmpty() ? undefined : this.applicationConfiguration, this.userConfiguration, this.localUserConfiguration, this.remoteUserConfiguration, workspace ? this._workspaceConfiguration : undefined, folderConfigurationModel ? folderConfigurationModel : undefined, memoryConfigurationModel);
        }
        get applicationConfiguration() {
            return this._applicationConfiguration;
        }
        get userConfiguration() {
            if (!this._userConfiguration) {
                this._userConfiguration = this._remoteUserConfiguration.isEmpty() ? this._localUserConfiguration : this._localUserConfiguration.merge(this._remoteUserConfiguration);
            }
            return this._userConfiguration;
        }
        get localUserConfiguration() {
            return this._localUserConfiguration;
        }
        get remoteUserConfiguration() {
            return this._remoteUserConfiguration;
        }
        getConsolidatedConfigurationModel(section, overrides, workspace) {
            let configurationModel = this.getConsolidatedConfigurationModelForResource(overrides, workspace);
            if (overrides.overrideIdentifier) {
                configurationModel = configurationModel.override(overrides.overrideIdentifier);
            }
            if (!this._policyConfiguration.isEmpty() && this._policyConfiguration.getValue(section) !== undefined) {
                configurationModel = configurationModel.merge(this._policyConfiguration);
            }
            return configurationModel;
        }
        getConsolidatedConfigurationModelForResource({ resource }, workspace) {
            let consolidateConfiguration = this.getWorkspaceConsolidatedConfiguration();
            if (workspace && resource) {
                const root = workspace.getFolder(resource);
                if (root) {
                    consolidateConfiguration = this.getFolderConsolidatedConfiguration(root.uri) || consolidateConfiguration;
                }
                const memoryConfigurationForResource = this._memoryConfigurationByResource.get(resource);
                if (memoryConfigurationForResource) {
                    consolidateConfiguration = consolidateConfiguration.merge(memoryConfigurationForResource);
                }
            }
            return consolidateConfiguration;
        }
        getWorkspaceConsolidatedConfiguration() {
            if (!this._workspaceConsolidatedConfiguration) {
                this._workspaceConsolidatedConfiguration = this._defaultConfiguration.merge(this.applicationConfiguration, this.userConfiguration, this._workspaceConfiguration, this._memoryConfiguration);
            }
            return this._workspaceConsolidatedConfiguration;
        }
        getFolderConsolidatedConfiguration(folder) {
            let folderConsolidatedConfiguration = this._foldersConsolidatedConfigurations.get(folder);
            if (!folderConsolidatedConfiguration) {
                const workspaceConsolidateConfiguration = this.getWorkspaceConsolidatedConfiguration();
                const folderConfiguration = this._folderConfigurations.get(folder);
                if (folderConfiguration) {
                    folderConsolidatedConfiguration = workspaceConsolidateConfiguration.merge(folderConfiguration);
                    this._foldersConsolidatedConfigurations.set(folder, folderConsolidatedConfiguration);
                }
                else {
                    folderConsolidatedConfiguration = workspaceConsolidateConfiguration;
                }
            }
            return folderConsolidatedConfiguration;
        }
        getFolderConfigurationModelForResource(resource, workspace) {
            if (workspace && resource) {
                const root = workspace.getFolder(resource);
                if (root) {
                    return this._folderConfigurations.get(root.uri);
                }
            }
            return undefined;
        }
        toData() {
            return {
                defaults: {
                    contents: this._defaultConfiguration.contents,
                    overrides: this._defaultConfiguration.overrides,
                    keys: this._defaultConfiguration.keys
                },
                policy: {
                    contents: this._policyConfiguration.contents,
                    overrides: this._policyConfiguration.overrides,
                    keys: this._policyConfiguration.keys
                },
                application: {
                    contents: this.applicationConfiguration.contents,
                    overrides: this.applicationConfiguration.overrides,
                    keys: this.applicationConfiguration.keys
                },
                user: {
                    contents: this.userConfiguration.contents,
                    overrides: this.userConfiguration.overrides,
                    keys: this.userConfiguration.keys
                },
                workspace: {
                    contents: this._workspaceConfiguration.contents,
                    overrides: this._workspaceConfiguration.overrides,
                    keys: this._workspaceConfiguration.keys
                },
                folders: [...this._folderConfigurations.keys()].reduce((result, folder) => {
                    const { contents, overrides, keys } = this._folderConfigurations.get(folder);
                    result.push([folder, { contents, overrides, keys }]);
                    return result;
                }, [])
            };
        }
        static parse(data, logService) {
            const defaultConfiguration = this.parseConfigurationModel(data.defaults, logService);
            const policyConfiguration = this.parseConfigurationModel(data.policy, logService);
            const applicationConfiguration = this.parseConfigurationModel(data.application, logService);
            const userConfiguration = this.parseConfigurationModel(data.user, logService);
            const workspaceConfiguration = this.parseConfigurationModel(data.workspace, logService);
            const folders = data.folders.reduce((result, value) => {
                result.set(uri_1.URI.revive(value[0]), this.parseConfigurationModel(value[1], logService));
                return result;
            }, new map_1.ResourceMap());
            return new Configuration(defaultConfiguration, policyConfiguration, applicationConfiguration, userConfiguration, ConfigurationModel.createEmptyModel(logService), workspaceConfiguration, folders, ConfigurationModel.createEmptyModel(logService), new map_1.ResourceMap(), logService);
        }
        static parseConfigurationModel(model, logService) {
            return new ConfigurationModel(model.contents, model.keys, model.overrides, undefined, logService);
        }
    }
    exports.Configuration = Configuration;
    class ConfigurationChangeEvent {
        constructor(change, previous, currentConfiguraiton, currentWorkspace, logService) {
            this.change = change;
            this.previous = previous;
            this.currentConfiguraiton = currentConfiguraiton;
            this.currentWorkspace = currentWorkspace;
            this.logService = logService;
            this._marker = '\n';
            this._markerCode1 = this._marker.charCodeAt(0);
            this._markerCode2 = '.'.charCodeAt(0);
            this.affectedKeys = new Set();
            this._previousConfiguration = undefined;
            for (const key of change.keys) {
                this.affectedKeys.add(key);
            }
            for (const [, keys] of change.overrides) {
                for (const key of keys) {
                    this.affectedKeys.add(key);
                }
            }
            // Example: '\nfoo.bar\nabc.def\n'
            this._affectsConfigStr = this._marker;
            for (const key of this.affectedKeys) {
                this._affectsConfigStr += key + this._marker;
            }
        }
        get previousConfiguration() {
            if (!this._previousConfiguration && this.previous) {
                this._previousConfiguration = Configuration.parse(this.previous.data, this.logService);
            }
            return this._previousConfiguration;
        }
        affectsConfiguration(section, overrides) {
            // we have one large string with all keys that have changed. we pad (marker) the section
            // and check that either find it padded or before a segment character
            const needle = this._marker + section;
            const idx = this._affectsConfigStr.indexOf(needle);
            if (idx < 0) {
                // NOT: (marker + section)
                return false;
            }
            const pos = idx + needle.length;
            if (pos >= this._affectsConfigStr.length) {
                return false;
            }
            const code = this._affectsConfigStr.charCodeAt(pos);
            if (code !== this._markerCode1 && code !== this._markerCode2) {
                // NOT: section + (marker | segment)
                return false;
            }
            if (overrides) {
                const value1 = this.previousConfiguration ? this.previousConfiguration.getValue(section, overrides, this.previous?.workspace) : undefined;
                const value2 = this.currentConfiguraiton.getValue(section, overrides, this.currentWorkspace);
                return !objects.equals(value1, value2);
            }
            return true;
        }
    }
    exports.ConfigurationChangeEvent = ConfigurationChangeEvent;
});

define(__m[717/*vs/platform/configuration/common/configurations*/], __M([1/*require*/,0/*exports*/,2/*vs/base/common/lifecycle*/,403/*vs/platform/configuration/common/configurationModels*/,109/*vs/platform/configuration/common/configurationRegistry*/,38/*vs/platform/registry/common/platform*/]), function (require, exports, lifecycle_1, configurationModels_1, configurationRegistry_1, platform_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DefaultConfiguration = void 0;
    class DefaultConfiguration extends lifecycle_1.Disposable {
        get configurationModel() {
            return this._configurationModel;
        }
        constructor(logService) {
            super();
            this.logService = logService;
            this._configurationModel = configurationModels_1.ConfigurationModel.createEmptyModel(this.logService);
        }
        reload() {
            this.resetConfigurationModel();
            return this.configurationModel;
        }
        getConfigurationDefaultOverrides() {
            return {};
        }
        resetConfigurationModel() {
            this._configurationModel = configurationModels_1.ConfigurationModel.createEmptyModel(this.logService);
            const properties = platform_1.Registry.as(configurationRegistry_1.Extensions.Configuration).getConfigurationProperties();
            this.updateConfigurationModel(Object.keys(properties), properties);
        }
        updateConfigurationModel(properties, configurationProperties) {
            const configurationDefaultsOverrides = this.getConfigurationDefaultOverrides();
            for (const key of properties) {
                const defaultOverrideValue = configurationDefaultsOverrides[key];
                const propertySchema = configurationProperties[key];
                if (defaultOverrideValue !== undefined) {
                    this._configurationModel.setValue(key, defaultOverrideValue);
                }
                else if (propertySchema) {
                    this._configurationModel.setValue(key, propertySchema.default);
                }
                else {
                    this._configurationModel.removeValue(key);
                }
            }
        }
    }
    exports.DefaultConfiguration = DefaultConfiguration;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[121/*vs/platform/keybinding/common/keybindingsRegistry*/], __M([1/*require*/,0/*exports*/,140/*vs/base/common/keybindings*/,16/*vs/base/common/platform*/,24/*vs/platform/commands/common/commands*/,38/*vs/platform/registry/common/platform*/,2/*vs/base/common/lifecycle*/,73/*vs/base/common/linkedList*/]), function (require, exports, keybindings_1, platform_1, commands_1, platform_2, lifecycle_1, linkedList_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Extensions = exports.KeybindingsRegistry = void 0;
    /**
     * Stores all built-in and extension-provided keybindings (but not ones that user defines themselves)
     */
    class KeybindingsRegistryImpl {
        constructor() {
            this._coreKeybindings = new linkedList_1.LinkedList();
            this._extensionKeybindings = [];
            this._cachedMergedKeybindings = null;
        }
        /**
         * Take current platform into account and reduce to primary & secondary.
         */
        static bindToCurrentPlatform(kb) {
            if (platform_1.OS === 1 /* OperatingSystem.Windows */) {
                if (kb && kb.win) {
                    return kb.win;
                }
            }
            else if (platform_1.OS === 2 /* OperatingSystem.Macintosh */) {
                if (kb && kb.mac) {
                    return kb.mac;
                }
            }
            else {
                if (kb && kb.linux) {
                    return kb.linux;
                }
            }
            return kb;
        }
        registerKeybindingRule(rule) {
            const actualKb = KeybindingsRegistryImpl.bindToCurrentPlatform(rule);
            const result = new lifecycle_1.DisposableStore();
            if (actualKb && actualKb.primary) {
                const kk = (0, keybindings_1.decodeKeybinding)(actualKb.primary, platform_1.OS);
                if (kk) {
                    result.add(this._registerDefaultKeybinding(kk, rule.id, rule.args, rule.weight, 0, rule.when));
                }
            }
            if (actualKb && Array.isArray(actualKb.secondary)) {
                for (let i = 0, len = actualKb.secondary.length; i < len; i++) {
                    const k = actualKb.secondary[i];
                    const kk = (0, keybindings_1.decodeKeybinding)(k, platform_1.OS);
                    if (kk) {
                        result.add(this._registerDefaultKeybinding(kk, rule.id, rule.args, rule.weight, -i - 1, rule.when));
                    }
                }
            }
            return result;
        }
        registerCommandAndKeybindingRule(desc) {
            return (0, lifecycle_1.combinedDisposable)(this.registerKeybindingRule(desc), commands_1.CommandsRegistry.registerCommand(desc));
        }
        _registerDefaultKeybinding(keybinding, commandId, commandArgs, weight1, weight2, when) {
            const remove = this._coreKeybindings.push({
                keybinding: keybinding,
                command: commandId,
                commandArgs: commandArgs,
                when: when,
                weight1: weight1,
                weight2: weight2,
                extensionId: null,
                isBuiltinExtension: false
            });
            this._cachedMergedKeybindings = null;
            return (0, lifecycle_1.toDisposable)(() => {
                remove();
                this._cachedMergedKeybindings = null;
            });
        }
        getDefaultKeybindings() {
            if (!this._cachedMergedKeybindings) {
                this._cachedMergedKeybindings = Array.from(this._coreKeybindings).concat(this._extensionKeybindings);
                this._cachedMergedKeybindings.sort(sorter);
            }
            return this._cachedMergedKeybindings.slice(0);
        }
    }
    exports.KeybindingsRegistry = new KeybindingsRegistryImpl();
    // Define extension point ids
    exports.Extensions = {
        EditorModes: 'platform.keybindingsRegistry'
    };
    platform_2.Registry.add(exports.Extensions.EditorModes, exports.KeybindingsRegistry);
    function sorter(a, b) {
        if (a.weight1 !== b.weight1) {
            return a.weight1 - b.weight1;
        }
        if (a.command && b.command) {
            if (a.command < b.command) {
                return -1;
            }
            if (a.command > b.command) {
                return 1;
            }
        }
        return a.weight2 - b.weight2;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[29/*vs/platform/actions/common/actions*/], __M([1/*require*/,0/*exports*/,41/*vs/base/common/actions*/,30/*vs/base/common/themables*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,73/*vs/base/common/linkedList*/,24/*vs/platform/commands/common/commands*/,12/*vs/platform/contextkey/common/contextkey*/,7/*vs/platform/instantiation/common/instantiation*/,121/*vs/platform/keybinding/common/keybindingsRegistry*/]), function (require, exports, actions_1, themables_1, event_1, lifecycle_1, linkedList_1, commands_1, contextkey_1, instantiation_1, keybindingsRegistry_1) {
    "use strict";
    var MenuItemAction_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Action2 = exports.MenuItemAction = exports.SubmenuItemAction = exports.MenuRegistry = exports.IMenuService = exports.MenuId = void 0;
    exports.isIMenuItem = isIMenuItem;
    exports.isISubmenuItem = isISubmenuItem;
    exports.registerAction2 = registerAction2;
    function isIMenuItem(item) {
        return item.command !== undefined;
    }
    function isISubmenuItem(item) {
        return item.submenu !== undefined;
    }
    class MenuId {
        static { this._instances = new Map(); }
        static { this.CommandPalette = new MenuId('CommandPalette'); }
        static { this.DebugBreakpointsContext = new MenuId('DebugBreakpointsContext'); }
        static { this.DebugCallStackContext = new MenuId('DebugCallStackContext'); }
        static { this.DebugConsoleContext = new MenuId('DebugConsoleContext'); }
        static { this.DebugVariablesContext = new MenuId('DebugVariablesContext'); }
        static { this.NotebookVariablesContext = new MenuId('NotebookVariablesContext'); }
        static { this.DebugHoverContext = new MenuId('DebugHoverContext'); }
        static { this.DebugWatchContext = new MenuId('DebugWatchContext'); }
        static { this.DebugToolBar = new MenuId('DebugToolBar'); }
        static { this.DebugToolBarStop = new MenuId('DebugToolBarStop'); }
        static { this.DebugCallStackToolbar = new MenuId('DebugCallStackToolbar'); }
        static { this.DebugCreateConfiguration = new MenuId('DebugCreateConfiguration'); }
        static { this.EditorContext = new MenuId('EditorContext'); }
        static { this.SimpleEditorContext = new MenuId('SimpleEditorContext'); }
        static { this.EditorContent = new MenuId('EditorContent'); }
        static { this.EditorLineNumberContext = new MenuId('EditorLineNumberContext'); }
        static { this.EditorContextCopy = new MenuId('EditorContextCopy'); }
        static { this.EditorContextPeek = new MenuId('EditorContextPeek'); }
        static { this.EditorContextShare = new MenuId('EditorContextShare'); }
        static { this.EditorTitle = new MenuId('EditorTitle'); }
        static { this.EditorTitleRun = new MenuId('EditorTitleRun'); }
        static { this.EditorTitleContext = new MenuId('EditorTitleContext'); }
        static { this.EditorTitleContextShare = new MenuId('EditorTitleContextShare'); }
        static { this.EmptyEditorGroup = new MenuId('EmptyEditorGroup'); }
        static { this.EmptyEditorGroupContext = new MenuId('EmptyEditorGroupContext'); }
        static { this.EditorTabsBarContext = new MenuId('EditorTabsBarContext'); }
        static { this.EditorTabsBarShowTabsSubmenu = new MenuId('EditorTabsBarShowTabsSubmenu'); }
        static { this.EditorTabsBarShowTabsZenModeSubmenu = new MenuId('EditorTabsBarShowTabsZenModeSubmenu'); }
        static { this.EditorActionsPositionSubmenu = new MenuId('EditorActionsPositionSubmenu'); }
        static { this.ExplorerContext = new MenuId('ExplorerContext'); }
        static { this.ExplorerContextShare = new MenuId('ExplorerContextShare'); }
        static { this.ExtensionContext = new MenuId('ExtensionContext'); }
        static { this.GlobalActivity = new MenuId('GlobalActivity'); }
        static { this.CommandCenter = new MenuId('CommandCenter'); }
        static { this.CommandCenterCenter = new MenuId('CommandCenterCenter'); }
        static { this.LayoutControlMenuSubmenu = new MenuId('LayoutControlMenuSubmenu'); }
        static { this.LayoutControlMenu = new MenuId('LayoutControlMenu'); }
        static { this.MenubarMainMenu = new MenuId('MenubarMainMenu'); }
        static { this.MenubarAppearanceMenu = new MenuId('MenubarAppearanceMenu'); }
        static { this.MenubarDebugMenu = new MenuId('MenubarDebugMenu'); }
        static { this.MenubarEditMenu = new MenuId('MenubarEditMenu'); }
        static { this.MenubarCopy = new MenuId('MenubarCopy'); }
        static { this.MenubarFileMenu = new MenuId('MenubarFileMenu'); }
        static { this.MenubarGoMenu = new MenuId('MenubarGoMenu'); }
        static { this.MenubarHelpMenu = new MenuId('MenubarHelpMenu'); }
        static { this.MenubarLayoutMenu = new MenuId('MenubarLayoutMenu'); }
        static { this.MenubarNewBreakpointMenu = new MenuId('MenubarNewBreakpointMenu'); }
        static { this.PanelAlignmentMenu = new MenuId('PanelAlignmentMenu'); }
        static { this.PanelPositionMenu = new MenuId('PanelPositionMenu'); }
        static { this.ActivityBarPositionMenu = new MenuId('ActivityBarPositionMenu'); }
        static { this.MenubarPreferencesMenu = new MenuId('MenubarPreferencesMenu'); }
        static { this.MenubarRecentMenu = new MenuId('MenubarRecentMenu'); }
        static { this.MenubarSelectionMenu = new MenuId('MenubarSelectionMenu'); }
        static { this.MenubarShare = new MenuId('MenubarShare'); }
        static { this.MenubarSwitchEditorMenu = new MenuId('MenubarSwitchEditorMenu'); }
        static { this.MenubarSwitchGroupMenu = new MenuId('MenubarSwitchGroupMenu'); }
        static { this.MenubarTerminalMenu = new MenuId('MenubarTerminalMenu'); }
        static { this.MenubarViewMenu = new MenuId('MenubarViewMenu'); }
        static { this.MenubarHomeMenu = new MenuId('MenubarHomeMenu'); }
        static { this.OpenEditorsContext = new MenuId('OpenEditorsContext'); }
        static { this.OpenEditorsContextShare = new MenuId('OpenEditorsContextShare'); }
        static { this.ProblemsPanelContext = new MenuId('ProblemsPanelContext'); }
        static { this.SCMInputBox = new MenuId('SCMInputBox'); }
        static { this.SCMChangesSeparator = new MenuId('SCMChangesSeparator'); }
        static { this.SCMChangesContext = new MenuId('SCMChangesContext'); }
        static { this.SCMIncomingChanges = new MenuId('SCMIncomingChanges'); }
        static { this.SCMIncomingChangesContext = new MenuId('SCMIncomingChangesContext'); }
        static { this.SCMIncomingChangesSetting = new MenuId('SCMIncomingChangesSetting'); }
        static { this.SCMOutgoingChanges = new MenuId('SCMOutgoingChanges'); }
        static { this.SCMOutgoingChangesContext = new MenuId('SCMOutgoingChangesContext'); }
        static { this.SCMOutgoingChangesSetting = new MenuId('SCMOutgoingChangesSetting'); }
        static { this.SCMIncomingChangesAllChangesContext = new MenuId('SCMIncomingChangesAllChangesContext'); }
        static { this.SCMIncomingChangesHistoryItemContext = new MenuId('SCMIncomingChangesHistoryItemContext'); }
        static { this.SCMOutgoingChangesAllChangesContext = new MenuId('SCMOutgoingChangesAllChangesContext'); }
        static { this.SCMOutgoingChangesHistoryItemContext = new MenuId('SCMOutgoingChangesHistoryItemContext'); }
        static { this.SCMChangeContext = new MenuId('SCMChangeContext'); }
        static { this.SCMResourceContext = new MenuId('SCMResourceContext'); }
        static { this.SCMResourceContextShare = new MenuId('SCMResourceContextShare'); }
        static { this.SCMResourceFolderContext = new MenuId('SCMResourceFolderContext'); }
        static { this.SCMResourceGroupContext = new MenuId('SCMResourceGroupContext'); }
        static { this.SCMSourceControl = new MenuId('SCMSourceControl'); }
        static { this.SCMSourceControlInline = new MenuId('SCMSourceControlInline'); }
        static { this.SCMSourceControlTitle = new MenuId('SCMSourceControlTitle'); }
        static { this.SCMHistoryTitle = new MenuId('SCMHistoryTitle'); }
        static { this.SCMTitle = new MenuId('SCMTitle'); }
        static { this.SearchContext = new MenuId('SearchContext'); }
        static { this.SearchActionMenu = new MenuId('SearchActionContext'); }
        static { this.StatusBarWindowIndicatorMenu = new MenuId('StatusBarWindowIndicatorMenu'); }
        static { this.StatusBarRemoteIndicatorMenu = new MenuId('StatusBarRemoteIndicatorMenu'); }
        static { this.StickyScrollContext = new MenuId('StickyScrollContext'); }
        static { this.TestItem = new MenuId('TestItem'); }
        static { this.TestItemGutter = new MenuId('TestItemGutter'); }
        static { this.TestProfilesContext = new MenuId('TestProfilesContext'); }
        static { this.TestMessageContext = new MenuId('TestMessageContext'); }
        static { this.TestMessageContent = new MenuId('TestMessageContent'); }
        static { this.TestPeekElement = new MenuId('TestPeekElement'); }
        static { this.TestPeekTitle = new MenuId('TestPeekTitle'); }
        static { this.TestCallStack = new MenuId('TestCallStack'); }
        static { this.TouchBarContext = new MenuId('TouchBarContext'); }
        static { this.TitleBarContext = new MenuId('TitleBarContext'); }
        static { this.TitleBarTitleContext = new MenuId('TitleBarTitleContext'); }
        static { this.TunnelContext = new MenuId('TunnelContext'); }
        static { this.TunnelPrivacy = new MenuId('TunnelPrivacy'); }
        static { this.TunnelProtocol = new MenuId('TunnelProtocol'); }
        static { this.TunnelPortInline = new MenuId('TunnelInline'); }
        static { this.TunnelTitle = new MenuId('TunnelTitle'); }
        static { this.TunnelLocalAddressInline = new MenuId('TunnelLocalAddressInline'); }
        static { this.TunnelOriginInline = new MenuId('TunnelOriginInline'); }
        static { this.ViewItemContext = new MenuId('ViewItemContext'); }
        static { this.ViewContainerTitle = new MenuId('ViewContainerTitle'); }
        static { this.ViewContainerTitleContext = new MenuId('ViewContainerTitleContext'); }
        static { this.ViewTitle = new MenuId('ViewTitle'); }
        static { this.ViewTitleContext = new MenuId('ViewTitleContext'); }
        static { this.CommentEditorActions = new MenuId('CommentEditorActions'); }
        static { this.CommentThreadTitle = new MenuId('CommentThreadTitle'); }
        static { this.CommentThreadActions = new MenuId('CommentThreadActions'); }
        static { this.CommentThreadAdditionalActions = new MenuId('CommentThreadAdditionalActions'); }
        static { this.CommentThreadTitleContext = new MenuId('CommentThreadTitleContext'); }
        static { this.CommentThreadCommentContext = new MenuId('CommentThreadCommentContext'); }
        static { this.CommentTitle = new MenuId('CommentTitle'); }
        static { this.CommentActions = new MenuId('CommentActions'); }
        static { this.CommentsViewThreadActions = new MenuId('CommentsViewThreadActions'); }
        static { this.InteractiveToolbar = new MenuId('InteractiveToolbar'); }
        static { this.InteractiveCellTitle = new MenuId('InteractiveCellTitle'); }
        static { this.InteractiveCellDelete = new MenuId('InteractiveCellDelete'); }
        static { this.InteractiveCellExecute = new MenuId('InteractiveCellExecute'); }
        static { this.InteractiveInputExecute = new MenuId('InteractiveInputExecute'); }
        static { this.InteractiveInputConfig = new MenuId('InteractiveInputConfig'); }
        static { this.ReplInputExecute = new MenuId('ReplInputExecute'); }
        static { this.IssueReporter = new MenuId('IssueReporter'); }
        static { this.NotebookToolbar = new MenuId('NotebookToolbar'); }
        static { this.NotebookStickyScrollContext = new MenuId('NotebookStickyScrollContext'); }
        static { this.NotebookCellTitle = new MenuId('NotebookCellTitle'); }
        static { this.NotebookCellDelete = new MenuId('NotebookCellDelete'); }
        static { this.NotebookCellInsert = new MenuId('NotebookCellInsert'); }
        static { this.NotebookCellBetween = new MenuId('NotebookCellBetween'); }
        static { this.NotebookCellListTop = new MenuId('NotebookCellTop'); }
        static { this.NotebookCellExecute = new MenuId('NotebookCellExecute'); }
        static { this.NotebookCellExecuteGoTo = new MenuId('NotebookCellExecuteGoTo'); }
        static { this.NotebookCellExecutePrimary = new MenuId('NotebookCellExecutePrimary'); }
        static { this.NotebookDiffCellInputTitle = new MenuId('NotebookDiffCellInputTitle'); }
        static { this.NotebookDiffCellMetadataTitle = new MenuId('NotebookDiffCellMetadataTitle'); }
        static { this.NotebookDiffCellOutputsTitle = new MenuId('NotebookDiffCellOutputsTitle'); }
        static { this.NotebookOutputToolbar = new MenuId('NotebookOutputToolbar'); }
        static { this.NotebookOutlineFilter = new MenuId('NotebookOutlineFilter'); }
        static { this.NotebookOutlineActionMenu = new MenuId('NotebookOutlineActionMenu'); }
        static { this.NotebookEditorLayoutConfigure = new MenuId('NotebookEditorLayoutConfigure'); }
        static { this.NotebookKernelSource = new MenuId('NotebookKernelSource'); }
        static { this.BulkEditTitle = new MenuId('BulkEditTitle'); }
        static { this.BulkEditContext = new MenuId('BulkEditContext'); }
        static { this.TimelineItemContext = new MenuId('TimelineItemContext'); }
        static { this.TimelineTitle = new MenuId('TimelineTitle'); }
        static { this.TimelineTitleContext = new MenuId('TimelineTitleContext'); }
        static { this.TimelineFilterSubMenu = new MenuId('TimelineFilterSubMenu'); }
        static { this.AccountsContext = new MenuId('AccountsContext'); }
        static { this.SidebarTitle = new MenuId('SidebarTitle'); }
        static { this.PanelTitle = new MenuId('PanelTitle'); }
        static { this.AuxiliaryBarTitle = new MenuId('AuxiliaryBarTitle'); }
        static { this.AuxiliaryBarHeader = new MenuId('AuxiliaryBarHeader'); }
        static { this.TerminalInstanceContext = new MenuId('TerminalInstanceContext'); }
        static { this.TerminalEditorInstanceContext = new MenuId('TerminalEditorInstanceContext'); }
        static { this.TerminalNewDropdownContext = new MenuId('TerminalNewDropdownContext'); }
        static { this.TerminalTabContext = new MenuId('TerminalTabContext'); }
        static { this.TerminalTabEmptyAreaContext = new MenuId('TerminalTabEmptyAreaContext'); }
        static { this.TerminalStickyScrollContext = new MenuId('TerminalStickyScrollContext'); }
        static { this.WebviewContext = new MenuId('WebviewContext'); }
        static { this.InlineCompletionsActions = new MenuId('InlineCompletionsActions'); }
        static { this.InlineEditsActions = new MenuId('InlineEditsActions'); }
        static { this.InlineEditActions = new MenuId('InlineEditActions'); }
        static { this.NewFile = new MenuId('NewFile'); }
        static { this.MergeInput1Toolbar = new MenuId('MergeToolbar1Toolbar'); }
        static { this.MergeInput2Toolbar = new MenuId('MergeToolbar2Toolbar'); }
        static { this.MergeBaseToolbar = new MenuId('MergeBaseToolbar'); }
        static { this.MergeInputResultToolbar = new MenuId('MergeToolbarResultToolbar'); }
        static { this.InlineSuggestionToolbar = new MenuId('InlineSuggestionToolbar'); }
        static { this.InlineEditToolbar = new MenuId('InlineEditToolbar'); }
        static { this.ChatContext = new MenuId('ChatContext'); }
        static { this.ChatCodeBlock = new MenuId('ChatCodeblock'); }
        static { this.ChatCompareBlock = new MenuId('ChatCompareBlock'); }
        static { this.ChatMessageTitle = new MenuId('ChatMessageTitle'); }
        static { this.ChatExecute = new MenuId('ChatExecute'); }
        static { this.ChatExecuteSecondary = new MenuId('ChatExecuteSecondary'); }
        static { this.ChatInputSide = new MenuId('ChatInputSide'); }
        static { this.AccessibleView = new MenuId('AccessibleView'); }
        static { this.MultiDiffEditorFileToolbar = new MenuId('MultiDiffEditorFileToolbar'); }
        static { this.DiffEditorHunkToolbar = new MenuId('DiffEditorHunkToolbar'); }
        static { this.DiffEditorSelectionToolbar = new MenuId('DiffEditorSelectionToolbar'); }
        /**
         * Create a new `MenuId` with the unique identifier. Will throw if a menu
         * with the identifier already exists, use `MenuId.for(ident)` or a unique
         * identifier
         */
        constructor(identifier) {
            if (MenuId._instances.has(identifier)) {
                throw new TypeError(`MenuId with identifier '${identifier}' already exists. Use MenuId.for(ident) or a unique identifier`);
            }
            MenuId._instances.set(identifier, this);
            this.id = identifier;
        }
    }
    exports.MenuId = MenuId;
    exports.IMenuService = (0, instantiation_1.createDecorator)('menuService');
    class MenuRegistryChangeEvent {
        static { this._all = new Map(); }
        static for(id) {
            let value = this._all.get(id);
            if (!value) {
                value = new MenuRegistryChangeEvent(id);
                this._all.set(id, value);
            }
            return value;
        }
        static merge(events) {
            const ids = new Set();
            for (const item of events) {
                if (item instanceof MenuRegistryChangeEvent) {
                    ids.add(item.id);
                }
            }
            return ids;
        }
        constructor(id) {
            this.id = id;
            this.has = candidate => candidate === id;
        }
    }
    exports.MenuRegistry = new class {
        constructor() {
            this._commands = new Map();
            this._menuItems = new Map();
            this._onDidChangeMenu = new event_1.MicrotaskEmitter({
                merge: MenuRegistryChangeEvent.merge
            });
            this.onDidChangeMenu = this._onDidChangeMenu.event;
        }
        addCommand(command) {
            this._commands.set(command.id, command);
            this._onDidChangeMenu.fire(MenuRegistryChangeEvent.for(MenuId.CommandPalette));
            return (0, lifecycle_1.toDisposable)(() => {
                if (this._commands.delete(command.id)) {
                    this._onDidChangeMenu.fire(MenuRegistryChangeEvent.for(MenuId.CommandPalette));
                }
            });
        }
        getCommand(id) {
            return this._commands.get(id);
        }
        getCommands() {
            const map = new Map();
            this._commands.forEach((value, key) => map.set(key, value));
            return map;
        }
        appendMenuItem(id, item) {
            let list = this._menuItems.get(id);
            if (!list) {
                list = new linkedList_1.LinkedList();
                this._menuItems.set(id, list);
            }
            const rm = list.push(item);
            this._onDidChangeMenu.fire(MenuRegistryChangeEvent.for(id));
            return (0, lifecycle_1.toDisposable)(() => {
                rm();
                this._onDidChangeMenu.fire(MenuRegistryChangeEvent.for(id));
            });
        }
        appendMenuItems(items) {
            const result = new lifecycle_1.DisposableStore();
            for (const { id, item } of items) {
                result.add(this.appendMenuItem(id, item));
            }
            return result;
        }
        getMenuItems(id) {
            let result;
            if (this._menuItems.has(id)) {
                result = [...this._menuItems.get(id)];
            }
            else {
                result = [];
            }
            if (id === MenuId.CommandPalette) {
                // CommandPalette is special because it shows
                // all commands by default
                this._appendImplicitItems(result);
            }
            return result;
        }
        _appendImplicitItems(result) {
            const set = new Set();
            for (const item of result) {
                if (isIMenuItem(item)) {
                    set.add(item.command.id);
                    if (item.alt) {
                        set.add(item.alt.id);
                    }
                }
            }
            this._commands.forEach((command, id) => {
                if (!set.has(id)) {
                    result.push({ command });
                }
            });
        }
    };
    class SubmenuItemAction extends actions_1.SubmenuAction {
        constructor(item, hideActions, actions) {
            super(`submenuitem.${item.submenu.id}`, typeof item.title === 'string' ? item.title : item.title.value, actions, 'submenu');
            this.item = item;
            this.hideActions = hideActions;
        }
    }
    exports.SubmenuItemAction = SubmenuItemAction;
    // implements IAction, does NOT extend Action, so that no one
    // subscribes to events of Action or modified properties
    let MenuItemAction = MenuItemAction_1 = class MenuItemAction {
        static label(action, options) {
            return options?.renderShortTitle && action.shortTitle
                ? (typeof action.shortTitle === 'string' ? action.shortTitle : action.shortTitle.value)
                : (typeof action.title === 'string' ? action.title : action.title.value);
        }
        constructor(item, alt, options, hideActions, menuKeybinding, contextKeyService, _commandService) {
            this.hideActions = hideActions;
            this.menuKeybinding = menuKeybinding;
            this._commandService = _commandService;
            this.id = item.id;
            this.label = MenuItemAction_1.label(item, options);
            this.tooltip = (typeof item.tooltip === 'string' ? item.tooltip : item.tooltip?.value) ?? '';
            this.enabled = !item.precondition || contextKeyService.contextMatchesRules(item.precondition);
            this.checked = undefined;
            let icon;
            if (item.toggled) {
                const toggled = (item.toggled.condition ? item.toggled : { condition: item.toggled });
                this.checked = contextKeyService.contextMatchesRules(toggled.condition);
                if (this.checked && toggled.tooltip) {
                    this.tooltip = typeof toggled.tooltip === 'string' ? toggled.tooltip : toggled.tooltip.value;
                }
                if (this.checked && themables_1.ThemeIcon.isThemeIcon(toggled.icon)) {
                    icon = toggled.icon;
                }
                if (this.checked && toggled.title) {
                    this.label = typeof toggled.title === 'string' ? toggled.title : toggled.title.value;
                }
            }
            if (!icon) {
                icon = themables_1.ThemeIcon.isThemeIcon(item.icon) ? item.icon : undefined;
            }
            this.item = item;
            this.alt = alt ? new MenuItemAction_1(alt, undefined, options, hideActions, undefined, contextKeyService, _commandService) : undefined;
            this._options = options;
            this.class = icon && themables_1.ThemeIcon.asClassName(icon);
        }
        run(...args) {
            let runArgs = [];
            if (this._options?.arg) {
                runArgs = [...runArgs, this._options.arg];
            }
            if (this._options?.shouldForwardArgs) {
                runArgs = [...runArgs, ...args];
            }
            return this._commandService.executeCommand(this.id, ...runArgs);
        }
    };
    exports.MenuItemAction = MenuItemAction;
    exports.MenuItemAction = MenuItemAction = MenuItemAction_1 = __decorate([
        __param(5, contextkey_1.IContextKeyService),
        __param(6, commands_1.ICommandService)
    ], MenuItemAction);
    class Action2 {
        constructor(desc) {
            this.desc = desc;
        }
    }
    exports.Action2 = Action2;
    function registerAction2(ctor) {
        const disposables = []; // not using `DisposableStore` to reduce startup perf cost
        const action = new ctor();
        const { f1, menu, keybinding, ...command } = action.desc;
        if (commands_1.CommandsRegistry.getCommand(command.id)) {
            throw new Error(`Cannot register two commands with the same id: ${command.id}`);
        }
        // command
        disposables.push(commands_1.CommandsRegistry.registerCommand({
            id: command.id,
            handler: (accessor, ...args) => action.run(accessor, ...args),
            metadata: command.metadata,
        }));
        // menu
        if (Array.isArray(menu)) {
            for (const item of menu) {
                disposables.push(exports.MenuRegistry.appendMenuItem(item.id, { command: { ...command, precondition: item.precondition === null ? undefined : command.precondition }, ...item }));
            }
        }
        else if (menu) {
            disposables.push(exports.MenuRegistry.appendMenuItem(menu.id, { command: { ...command, precondition: menu.precondition === null ? undefined : command.precondition }, ...menu }));
        }
        if (f1) {
            disposables.push(exports.MenuRegistry.appendMenuItem(MenuId.CommandPalette, { command, when: command.precondition }));
            disposables.push(exports.MenuRegistry.addCommand(command));
        }
        // keybinding
        if (Array.isArray(keybinding)) {
            for (const item of keybinding) {
                disposables.push(keybindingsRegistry_1.KeybindingsRegistry.registerKeybindingRule({
                    ...item,
                    id: command.id,
                    when: command.precondition ? contextkey_1.ContextKeyExpr.and(command.precondition, item.when) : item.when
                }));
            }
        }
        else if (keybinding) {
            disposables.push(keybindingsRegistry_1.KeybindingsRegistry.registerKeybindingRule({
                ...keybinding,
                id: command.id,
                when: command.precondition ? contextkey_1.ContextKeyExpr.and(command.precondition, keybinding.when) : keybinding.when
            }));
        }
        return {
            dispose() {
                (0, lifecycle_1.dispose)(disposables);
            }
        };
    }
});
//#endregion

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[718/*vs/editor/contrib/toggleTabFocusMode/browser/toggleTabFocusMode*/], __M([1/*require*/,0/*exports*/,46/*vs/base/browser/ui/aria/aria*/,229/*vs/editor/browser/config/tabFocus*/,3/*vs/nls*/,29/*vs/platform/actions/common/actions*/]), function (require, exports, aria_1, tabFocus_1, nls, actions_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ToggleTabFocusModeAction = void 0;
    class ToggleTabFocusModeAction extends actions_1.Action2 {
        static { this.ID = 'editor.action.toggleTabFocusMode'; }
        constructor() {
            super({
                id: ToggleTabFocusModeAction.ID,
                title: nls.localize2(1383, 'Toggle Tab Key Moves Focus'),
                precondition: undefined,
                keybinding: {
                    primary: 2048 /* KeyMod.CtrlCmd */ | 43 /* KeyCode.KeyM */,
                    mac: { primary: 256 /* KeyMod.WinCtrl */ | 1024 /* KeyMod.Shift */ | 43 /* KeyCode.KeyM */ },
                    weight: 100 /* KeybindingWeight.EditorContrib */
                },
                metadata: {
                    description: nls.localize2(1384, "Determines whether the tab key moves focus around the workbench or inserts the tab character in the current editor. This is also called tab trapping, tab navigation, or tab focus mode."),
                },
                f1: true
            });
        }
        run() {
            const oldValue = tabFocus_1.TabFocus.getTabFocusMode();
            const newValue = !oldValue;
            tabFocus_1.TabFocus.setTabFocusMode(newValue);
            if (newValue) {
                (0, aria_1.alert)(nls.localize(1381, "Pressing Tab will now move focus to the next focusable element"));
            }
            else {
                (0, aria_1.alert)(nls.localize(1382, "Pressing Tab will now insert the tab character"));
            }
        }
    }
    exports.ToggleTabFocusModeAction = ToggleTabFocusModeAction;
    (0, actions_1.registerAction2)(ToggleTabFocusModeAction);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[404/*vs/platform/history/browser/contextScopedHistoryWidget*/], __M([1/*require*/,0/*exports*/,260/*vs/base/browser/ui/findinput/findInput*/,641/*vs/base/browser/ui/findinput/replaceInput*/,12/*vs/platform/contextkey/common/contextkey*/,121/*vs/platform/keybinding/common/keybindingsRegistry*/,3/*vs/nls*/,2/*vs/base/common/lifecycle*/,5/*vs/base/browser/dom*/]), function (require, exports, findInput_1, replaceInput_1, contextkey_1, keybindingsRegistry_1, nls_1, lifecycle_1, dom_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ContextScopedReplaceInput = exports.ContextScopedFindInput = exports.historyNavigationVisible = void 0;
    exports.registerAndCreateHistoryNavigationContext = registerAndCreateHistoryNavigationContext;
    exports.historyNavigationVisible = new contextkey_1.RawContextKey('suggestWidgetVisible', false, (0, nls_1.localize)(1537, "Whether suggestion are visible"));
    const HistoryNavigationWidgetFocusContext = 'historyNavigationWidgetFocus';
    const HistoryNavigationForwardsEnablementContext = 'historyNavigationForwardsEnabled';
    const HistoryNavigationBackwardsEnablementContext = 'historyNavigationBackwardsEnabled';
    let lastFocusedWidget = undefined;
    const widgets = [];
    function registerAndCreateHistoryNavigationContext(scopedContextKeyService, widget) {
        if (widgets.includes(widget)) {
            throw new Error('Cannot register the same widget multiple times');
        }
        widgets.push(widget);
        const disposableStore = new lifecycle_1.DisposableStore();
        const historyNavigationWidgetFocus = new contextkey_1.RawContextKey(HistoryNavigationWidgetFocusContext, false).bindTo(scopedContextKeyService);
        const historyNavigationForwardsEnablement = new contextkey_1.RawContextKey(HistoryNavigationForwardsEnablementContext, true).bindTo(scopedContextKeyService);
        const historyNavigationBackwardsEnablement = new contextkey_1.RawContextKey(HistoryNavigationBackwardsEnablementContext, true).bindTo(scopedContextKeyService);
        const onDidFocus = () => {
            historyNavigationWidgetFocus.set(true);
            lastFocusedWidget = widget;
        };
        const onDidBlur = () => {
            historyNavigationWidgetFocus.set(false);
            if (lastFocusedWidget === widget) {
                lastFocusedWidget = undefined;
            }
        };
        // Check for currently being focused
        if ((0, dom_1.isActiveElement)(widget.element)) {
            onDidFocus();
        }
        disposableStore.add(widget.onDidFocus(() => onDidFocus()));
        disposableStore.add(widget.onDidBlur(() => onDidBlur()));
        disposableStore.add((0, lifecycle_1.toDisposable)(() => {
            widgets.splice(widgets.indexOf(widget), 1);
            onDidBlur();
        }));
        return {
            historyNavigationForwardsEnablement,
            historyNavigationBackwardsEnablement,
            dispose() {
                disposableStore.dispose();
            }
        };
    }
    let ContextScopedFindInput = class ContextScopedFindInput extends findInput_1.FindInput {
        constructor(container, contextViewProvider, options, contextKeyService) {
            super(container, contextViewProvider, options);
            const scopedContextKeyService = this._register(contextKeyService.createScoped(this.inputBox.element));
            this._register(registerAndCreateHistoryNavigationContext(scopedContextKeyService, this.inputBox));
        }
    };
    exports.ContextScopedFindInput = ContextScopedFindInput;
    exports.ContextScopedFindInput = ContextScopedFindInput = __decorate([
        __param(3, contextkey_1.IContextKeyService)
    ], ContextScopedFindInput);
    let ContextScopedReplaceInput = class ContextScopedReplaceInput extends replaceInput_1.ReplaceInput {
        constructor(container, contextViewProvider, options, contextKeyService, showReplaceOptions = false) {
            super(container, contextViewProvider, showReplaceOptions, options);
            const scopedContextKeyService = this._register(contextKeyService.createScoped(this.inputBox.element));
            this._register(registerAndCreateHistoryNavigationContext(scopedContextKeyService, this.inputBox));
        }
    };
    exports.ContextScopedReplaceInput = ContextScopedReplaceInput;
    exports.ContextScopedReplaceInput = ContextScopedReplaceInput = __decorate([
        __param(3, contextkey_1.IContextKeyService)
    ], ContextScopedReplaceInput);
    keybindingsRegistry_1.KeybindingsRegistry.registerCommandAndKeybindingRule({
        id: 'history.showPrevious',
        weight: 200 /* KeybindingWeight.WorkbenchContrib */,
        when: contextkey_1.ContextKeyExpr.and(contextkey_1.ContextKeyExpr.has(HistoryNavigationWidgetFocusContext), contextkey_1.ContextKeyExpr.equals(HistoryNavigationBackwardsEnablementContext, true), contextkey_1.ContextKeyExpr.not('isComposing'), exports.historyNavigationVisible.isEqualTo(false)),
        primary: 16 /* KeyCode.UpArrow */,
        secondary: [512 /* KeyMod.Alt */ | 16 /* KeyCode.UpArrow */],
        handler: (accessor) => {
            lastFocusedWidget?.showPreviousValue();
        }
    });
    keybindingsRegistry_1.KeybindingsRegistry.registerCommandAndKeybindingRule({
        id: 'history.showNext',
        weight: 200 /* KeybindingWeight.WorkbenchContrib */,
        when: contextkey_1.ContextKeyExpr.and(contextkey_1.ContextKeyExpr.has(HistoryNavigationWidgetFocusContext), contextkey_1.ContextKeyExpr.equals(HistoryNavigationForwardsEnablementContext, true), contextkey_1.ContextKeyExpr.not('isComposing'), exports.historyNavigationVisible.isEqualTo(false)),
        primary: 18 /* KeyCode.DownArrow */,
        secondary: [512 /* KeyMod.Alt */ | 18 /* KeyCode.DownArrow */],
        handler: (accessor) => {
            lastFocusedWidget?.showNextValue();
        }
    });
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[155/*vs/editor/contrib/suggest/browser/suggest*/], __M([1/*require*/,0/*exports*/,18/*vs/base/common/cancellation*/,8/*vs/base/common/errors*/,82/*vs/base/common/filters*/,2/*vs/base/common/lifecycle*/,54/*vs/base/common/stopwatch*/,19/*vs/base/common/types*/,22/*vs/base/common/uri*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/,78/*vs/editor/common/services/resolverService*/,135/*vs/editor/contrib/snippet/browser/snippetParser*/,3/*vs/nls*/,29/*vs/platform/actions/common/actions*/,24/*vs/platform/commands/common/commands*/,12/*vs/platform/contextkey/common/contextkey*/,17/*vs/editor/common/services/languageFeatures*/,404/*vs/platform/history/browser/contextScopedHistoryWidget*/]), function (require, exports, cancellation_1, errors_1, filters_1, lifecycle_1, stopwatch_1, types_1, uri_1, position_1, range_1, resolverService_1, snippetParser_1, nls_1, actions_1, commands_1, contextkey_1, languageFeatures_1, contextScopedHistoryWidget_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.QuickSuggestionsOptions = exports.CompletionItemModel = exports.CompletionOptions = exports.CompletionItem = exports.suggestWidgetStatusbarMenu = exports.Context = void 0;
    exports.getSnippetSuggestSupport = getSnippetSuggestSupport;
    exports.provideSuggestionItems = provideSuggestionItems;
    exports.getSuggestionComparator = getSuggestionComparator;
    exports.showSimpleSuggestions = showSimpleSuggestions;
    exports.Context = {
        Visible: contextScopedHistoryWidget_1.historyNavigationVisible,
        HasFocusedSuggestion: new contextkey_1.RawContextKey('suggestWidgetHasFocusedSuggestion', false, (0, nls_1.localize)(1310, "Whether any suggestion is focused")),
        DetailsVisible: new contextkey_1.RawContextKey('suggestWidgetDetailsVisible', false, (0, nls_1.localize)(1311, "Whether suggestion details are visible")),
        MultipleSuggestions: new contextkey_1.RawContextKey('suggestWidgetMultipleSuggestions', false, (0, nls_1.localize)(1312, "Whether there are multiple suggestions to pick from")),
        MakesTextEdit: new contextkey_1.RawContextKey('suggestionMakesTextEdit', true, (0, nls_1.localize)(1313, "Whether inserting the current suggestion yields in a change or has everything already been typed")),
        AcceptSuggestionsOnEnter: new contextkey_1.RawContextKey('acceptSuggestionOnEnter', true, (0, nls_1.localize)(1314, "Whether suggestions are inserted when pressing Enter")),
        HasInsertAndReplaceRange: new contextkey_1.RawContextKey('suggestionHasInsertAndReplaceRange', false, (0, nls_1.localize)(1315, "Whether the current suggestion has insert and replace behaviour")),
        InsertMode: new contextkey_1.RawContextKey('suggestionInsertMode', undefined, { type: 'string', description: (0, nls_1.localize)(1316, "Whether the default behaviour is to insert or replace") }),
        CanResolve: new contextkey_1.RawContextKey('suggestionCanResolve', false, (0, nls_1.localize)(1317, "Whether the current suggestion supports to resolve further details")),
    };
    exports.suggestWidgetStatusbarMenu = new actions_1.MenuId('suggestWidgetStatusBar');
    class CompletionItem {
        constructor(position, completion, container, provider) {
            this.position = position;
            this.completion = completion;
            this.container = container;
            this.provider = provider;
            // validation
            this.isInvalid = false;
            // sorting, filtering
            this.score = filters_1.FuzzyScore.Default;
            this.distance = 0;
            this.textLabel = typeof completion.label === 'string'
                ? completion.label
                : completion.label?.label;
            // ensure lower-variants (perf)
            this.labelLow = this.textLabel.toLowerCase();
            // validate label
            this.isInvalid = !this.textLabel;
            this.sortTextLow = completion.sortText && completion.sortText.toLowerCase();
            this.filterTextLow = completion.filterText && completion.filterText.toLowerCase();
            this.extensionId = completion.extensionId;
            // normalize ranges
            if (range_1.Range.isIRange(completion.range)) {
                this.editStart = new position_1.Position(completion.range.startLineNumber, completion.range.startColumn);
                this.editInsertEnd = new position_1.Position(completion.range.endLineNumber, completion.range.endColumn);
                this.editReplaceEnd = new position_1.Position(completion.range.endLineNumber, completion.range.endColumn);
                // validate range
                this.isInvalid = this.isInvalid
                    || range_1.Range.spansMultipleLines(completion.range) || completion.range.startLineNumber !== position.lineNumber;
            }
            else {
                this.editStart = new position_1.Position(completion.range.insert.startLineNumber, completion.range.insert.startColumn);
                this.editInsertEnd = new position_1.Position(completion.range.insert.endLineNumber, completion.range.insert.endColumn);
                this.editReplaceEnd = new position_1.Position(completion.range.replace.endLineNumber, completion.range.replace.endColumn);
                // validate ranges
                this.isInvalid = this.isInvalid
                    || range_1.Range.spansMultipleLines(completion.range.insert) || range_1.Range.spansMultipleLines(completion.range.replace)
                    || completion.range.insert.startLineNumber !== position.lineNumber || completion.range.replace.startLineNumber !== position.lineNumber
                    || completion.range.insert.startColumn !== completion.range.replace.startColumn;
            }
            // create the suggestion resolver
            if (typeof provider.resolveCompletionItem !== 'function') {
                this._resolveCache = Promise.resolve();
                this._resolveDuration = 0;
            }
        }
        // ---- resolving
        get isResolved() {
            return this._resolveDuration !== undefined;
        }
        get resolveDuration() {
            return this._resolveDuration !== undefined ? this._resolveDuration : -1;
        }
        async resolve(token) {
            if (!this._resolveCache) {
                const sub = token.onCancellationRequested(() => {
                    this._resolveCache = undefined;
                    this._resolveDuration = undefined;
                });
                const sw = new stopwatch_1.StopWatch(true);
                this._resolveCache = Promise.resolve(this.provider.resolveCompletionItem(this.completion, token)).then(value => {
                    Object.assign(this.completion, value);
                    this._resolveDuration = sw.elapsed();
                }, err => {
                    if ((0, errors_1.isCancellationError)(err)) {
                        // the IPC queue will reject the request with the
                        // cancellation error -> reset cached
                        this._resolveCache = undefined;
                        this._resolveDuration = undefined;
                    }
                }).finally(() => {
                    sub.dispose();
                });
            }
            return this._resolveCache;
        }
    }
    exports.CompletionItem = CompletionItem;
    class CompletionOptions {
        static { this.default = new CompletionOptions(); }
        constructor(snippetSortOrder = 2 /* SnippetSortOrder.Bottom */, kindFilter = new Set(), providerFilter = new Set(), providerItemsToReuse = new Map(), showDeprecated = true) {
            this.snippetSortOrder = snippetSortOrder;
            this.kindFilter = kindFilter;
            this.providerFilter = providerFilter;
            this.providerItemsToReuse = providerItemsToReuse;
            this.showDeprecated = showDeprecated;
        }
    }
    exports.CompletionOptions = CompletionOptions;
    let _snippetSuggestSupport;
    function getSnippetSuggestSupport() {
        return _snippetSuggestSupport;
    }
    class CompletionItemModel {
        constructor(items, needsClipboard, durations, disposable) {
            this.items = items;
            this.needsClipboard = needsClipboard;
            this.durations = durations;
            this.disposable = disposable;
        }
    }
    exports.CompletionItemModel = CompletionItemModel;
    async function provideSuggestionItems(registry, model, position, options = CompletionOptions.default, context = { triggerKind: 0 /* languages.CompletionTriggerKind.Invoke */ }, token = cancellation_1.CancellationToken.None) {
        const sw = new stopwatch_1.StopWatch();
        position = position.clone();
        const word = model.getWordAtPosition(position);
        const defaultReplaceRange = word ? new range_1.Range(position.lineNumber, word.startColumn, position.lineNumber, word.endColumn) : range_1.Range.fromPositions(position);
        const defaultRange = { replace: defaultReplaceRange, insert: defaultReplaceRange.setEndPosition(position.lineNumber, position.column) };
        const result = [];
        const disposables = new lifecycle_1.DisposableStore();
        const durations = [];
        let needsClipboard = false;
        const onCompletionList = (provider, container, sw) => {
            let didAddResult = false;
            if (!container) {
                return didAddResult;
            }
            for (const suggestion of container.suggestions) {
                if (!options.kindFilter.has(suggestion.kind)) {
                    // skip if not showing deprecated suggestions
                    if (!options.showDeprecated && suggestion?.tags?.includes(1 /* languages.CompletionItemTag.Deprecated */)) {
                        continue;
                    }
                    // fill in default range when missing
                    if (!suggestion.range) {
                        suggestion.range = defaultRange;
                    }
                    // fill in default sortText when missing
                    if (!suggestion.sortText) {
                        suggestion.sortText = typeof suggestion.label === 'string' ? suggestion.label : suggestion.label.label;
                    }
                    if (!needsClipboard && suggestion.insertTextRules && suggestion.insertTextRules & 4 /* languages.CompletionItemInsertTextRule.InsertAsSnippet */) {
                        needsClipboard = snippetParser_1.SnippetParser.guessNeedsClipboard(suggestion.insertText);
                    }
                    result.push(new CompletionItem(position, suggestion, container, provider));
                    didAddResult = true;
                }
            }
            if ((0, lifecycle_1.isDisposable)(container)) {
                disposables.add(container);
            }
            durations.push({
                providerName: provider._debugDisplayName ?? 'unknown_provider', elapsedProvider: container.duration ?? -1, elapsedOverall: sw.elapsed()
            });
            return didAddResult;
        };
        // ask for snippets in parallel to asking "real" providers. Only do something if configured to
        // do so - no snippet filter, no special-providers-only request
        const snippetCompletions = (async () => {
            if (!_snippetSuggestSupport || options.kindFilter.has(27 /* languages.CompletionItemKind.Snippet */)) {
                return;
            }
            // we have items from a previous session that we can reuse
            const reuseItems = options.providerItemsToReuse.get(_snippetSuggestSupport);
            if (reuseItems) {
                reuseItems.forEach(item => result.push(item));
                return;
            }
            if (options.providerFilter.size > 0 && !options.providerFilter.has(_snippetSuggestSupport)) {
                return;
            }
            const sw = new stopwatch_1.StopWatch();
            const list = await _snippetSuggestSupport.provideCompletionItems(model, position, context, token);
            onCompletionList(_snippetSuggestSupport, list, sw);
        })();
        // add suggestions from contributed providers - providers are ordered in groups of
        // equal score and once a group produces a result the process stops
        // get provider groups, always add snippet suggestion provider
        for (const providerGroup of registry.orderedGroups(model)) {
            // for each support in the group ask for suggestions
            let didAddResult = false;
            await Promise.all(providerGroup.map(async (provider) => {
                // we have items from a previous session that we can reuse
                if (options.providerItemsToReuse.has(provider)) {
                    const items = options.providerItemsToReuse.get(provider);
                    items.forEach(item => result.push(item));
                    didAddResult = didAddResult || items.length > 0;
                    return;
                }
                // check if this provider is filtered out
                if (options.providerFilter.size > 0 && !options.providerFilter.has(provider)) {
                    return;
                }
                try {
                    const sw = new stopwatch_1.StopWatch();
                    const list = await provider.provideCompletionItems(model, position, context, token);
                    didAddResult = onCompletionList(provider, list, sw) || didAddResult;
                }
                catch (err) {
                    (0, errors_1.onUnexpectedExternalError)(err);
                }
            }));
            if (didAddResult || token.isCancellationRequested) {
                break;
            }
        }
        await snippetCompletions;
        if (token.isCancellationRequested) {
            disposables.dispose();
            return Promise.reject(new errors_1.CancellationError());
        }
        return new CompletionItemModel(result.sort(getSuggestionComparator(options.snippetSortOrder)), needsClipboard, { entries: durations, elapsed: sw.elapsed() }, disposables);
    }
    function defaultComparator(a, b) {
        // check with 'sortText'
        if (a.sortTextLow && b.sortTextLow) {
            if (a.sortTextLow < b.sortTextLow) {
                return -1;
            }
            else if (a.sortTextLow > b.sortTextLow) {
                return 1;
            }
        }
        // check with 'label'
        if (a.textLabel < b.textLabel) {
            return -1;
        }
        else if (a.textLabel > b.textLabel) {
            return 1;
        }
        // check with 'type'
        return a.completion.kind - b.completion.kind;
    }
    function snippetUpComparator(a, b) {
        if (a.completion.kind !== b.completion.kind) {
            if (a.completion.kind === 27 /* languages.CompletionItemKind.Snippet */) {
                return -1;
            }
            else if (b.completion.kind === 27 /* languages.CompletionItemKind.Snippet */) {
                return 1;
            }
        }
        return defaultComparator(a, b);
    }
    function snippetDownComparator(a, b) {
        if (a.completion.kind !== b.completion.kind) {
            if (a.completion.kind === 27 /* languages.CompletionItemKind.Snippet */) {
                return 1;
            }
            else if (b.completion.kind === 27 /* languages.CompletionItemKind.Snippet */) {
                return -1;
            }
        }
        return defaultComparator(a, b);
    }
    const _snippetComparators = new Map();
    _snippetComparators.set(0 /* SnippetSortOrder.Top */, snippetUpComparator);
    _snippetComparators.set(2 /* SnippetSortOrder.Bottom */, snippetDownComparator);
    _snippetComparators.set(1 /* SnippetSortOrder.Inline */, defaultComparator);
    function getSuggestionComparator(snippetConfig) {
        return _snippetComparators.get(snippetConfig);
    }
    commands_1.CommandsRegistry.registerCommand('_executeCompletionItemProvider', async (accessor, ...args) => {
        const [uri, position, triggerCharacter, maxItemsToResolve] = args;
        (0, types_1.assertType)(uri_1.URI.isUri(uri));
        (0, types_1.assertType)(position_1.Position.isIPosition(position));
        (0, types_1.assertType)(typeof triggerCharacter === 'string' || !triggerCharacter);
        (0, types_1.assertType)(typeof maxItemsToResolve === 'number' || !maxItemsToResolve);
        const { completionProvider } = accessor.get(languageFeatures_1.ILanguageFeaturesService);
        const ref = await accessor.get(resolverService_1.ITextModelService).createModelReference(uri);
        try {
            const result = {
                incomplete: false,
                suggestions: []
            };
            const resolving = [];
            const actualPosition = ref.object.textEditorModel.validatePosition(position);
            const completions = await provideSuggestionItems(completionProvider, ref.object.textEditorModel, actualPosition, undefined, { triggerCharacter: triggerCharacter ?? undefined, triggerKind: triggerCharacter ? 1 /* languages.CompletionTriggerKind.TriggerCharacter */ : 0 /* languages.CompletionTriggerKind.Invoke */ });
            for (const item of completions.items) {
                if (resolving.length < (maxItemsToResolve ?? 0)) {
                    resolving.push(item.resolve(cancellation_1.CancellationToken.None));
                }
                result.incomplete = result.incomplete || item.container.incomplete;
                result.suggestions.push(item.completion);
            }
            try {
                await Promise.all(resolving);
                return result;
            }
            finally {
                setTimeout(() => completions.disposable.dispose(), 100);
            }
        }
        finally {
            ref.dispose();
        }
    });
    function showSimpleSuggestions(editor, provider) {
        editor.getContribution('editor.contrib.suggestController')?.triggerSuggest(new Set().add(provider), undefined, true);
    }
    class QuickSuggestionsOptions {
        static isAllOff(config) {
            return config.other === 'off' && config.comments === 'off' && config.strings === 'off';
        }
        static isAllOn(config) {
            return config.other === 'on' && config.comments === 'on' && config.strings === 'on';
        }
        static valueFor(config, tokenType) {
            switch (tokenType) {
                case 1 /* StandardTokenType.Comment */: return config.comments;
                case 2 /* StandardTokenType.String */: return config.strings;
                default: return config.other;
            }
        }
    }
    exports.QuickSuggestionsOptions = QuickSuggestionsOptions;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[719/*vs/platform/quickinput/browser/quickInputActions*/], __M([1/*require*/,0/*exports*/,16/*vs/base/common/platform*/,3/*vs/nls*/,12/*vs/platform/contextkey/common/contextkey*/,179/*vs/platform/contextkey/common/contextkeys*/,121/*vs/platform/keybinding/common/keybindingsRegistry*/,272/*vs/platform/quickinput/browser/quickInput*/,66/*vs/platform/quickinput/common/quickInput*/]), function (require, exports, platform_1, nls_1, contextkey_1, contextkeys_1, keybindingsRegistry_1, quickInput_1, quickInput_2) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    const defaultCommandAndKeybindingRule = {
        weight: 200 /* KeybindingWeight.WorkbenchContrib */,
        when: contextkey_1.ContextKeyExpr.and(contextkey_1.ContextKeyExpr.equals(quickInput_1.quickInputTypeContextKeyValue, "quickPick" /* QuickInputType.QuickPick */), quickInput_1.inQuickInputContext),
        metadata: { description: (0, nls_1.localize)(1587, "Used while in the context of the quick pick. If you change one keybinding for this command, you should change all of the other keybindings (modifier variants) of this command as well.") }
    };
    function registerQuickPickCommandAndKeybindingRule(rule, options = {}) {
        keybindingsRegistry_1.KeybindingsRegistry.registerCommandAndKeybindingRule({
            ...defaultCommandAndKeybindingRule,
            ...rule,
            secondary: getSecondary(rule.primary, rule.secondary ?? [], options)
        });
    }
    const ctrlKeyMod = platform_1.isMacintosh ? 256 /* KeyMod.WinCtrl */ : 2048 /* KeyMod.CtrlCmd */;
    // This function will generate all the combinations of keybindings for the given primary keybinding
    function getSecondary(primary, secondary, options = {}) {
        if (options.withAltMod) {
            secondary.push(512 /* KeyMod.Alt */ + primary);
        }
        if (options.withCtrlMod) {
            secondary.push(ctrlKeyMod + primary);
            if (options.withAltMod) {
                secondary.push(512 /* KeyMod.Alt */ + ctrlKeyMod + primary);
            }
        }
        if (options.withCmdMod && platform_1.isMacintosh) {
            secondary.push(2048 /* KeyMod.CtrlCmd */ + primary);
            if (options.withCtrlMod) {
                secondary.push(2048 /* KeyMod.CtrlCmd */ + 256 /* KeyMod.WinCtrl */ + primary);
            }
            if (options.withAltMod) {
                secondary.push(2048 /* KeyMod.CtrlCmd */ + 512 /* KeyMod.Alt */ + primary);
                if (options.withCtrlMod) {
                    secondary.push(2048 /* KeyMod.CtrlCmd */ + 512 /* KeyMod.Alt */ + 256 /* KeyMod.WinCtrl */ + primary);
                }
            }
        }
        return secondary;
    }
    //#region Navigation
    function focusHandler(focus, focusOnQuickNatigate) {
        return accessor => {
            // Assuming this is a quick pick due to above when clause
            const currentQuickPick = accessor.get(quickInput_2.IQuickInputService).currentQuickInput;
            if (!currentQuickPick) {
                return;
            }
            if (focusOnQuickNatigate && currentQuickPick.quickNavigate) {
                return currentQuickPick.focus(focusOnQuickNatigate);
            }
            return currentQuickPick.focus(focus);
        };
    }
    registerQuickPickCommandAndKeybindingRule({ id: 'quickInput.pageNext', primary: 12 /* KeyCode.PageDown */, handler: focusHandler(quickInput_2.QuickPickFocus.NextPage) }, { withAltMod: true, withCtrlMod: true, withCmdMod: true });
    registerQuickPickCommandAndKeybindingRule({ id: 'quickInput.pagePrevious', primary: 11 /* KeyCode.PageUp */, handler: focusHandler(quickInput_2.QuickPickFocus.PreviousPage) }, { withAltMod: true, withCtrlMod: true, withCmdMod: true });
    registerQuickPickCommandAndKeybindingRule({ id: 'quickInput.first', primary: ctrlKeyMod + 14 /* KeyCode.Home */, handler: focusHandler(quickInput_2.QuickPickFocus.First) }, { withAltMod: true, withCmdMod: true });
    registerQuickPickCommandAndKeybindingRule({ id: 'quickInput.last', primary: ctrlKeyMod + 13 /* KeyCode.End */, handler: focusHandler(quickInput_2.QuickPickFocus.Last) }, { withAltMod: true, withCmdMod: true });
    registerQuickPickCommandAndKeybindingRule({ id: 'quickInput.next', primary: 18 /* KeyCode.DownArrow */, handler: focusHandler(quickInput_2.QuickPickFocus.Next) }, { withCtrlMod: true });
    registerQuickPickCommandAndKeybindingRule({ id: 'quickInput.previous', primary: 16 /* KeyCode.UpArrow */, handler: focusHandler(quickInput_2.QuickPickFocus.Previous) }, { withCtrlMod: true });
    // The next & previous separator commands are interesting because if we are in quick access mode, we are already holding a modifier key down.
    // In this case, we want that modifier key+up/down to navigate to the next/previous item, not the next/previous separator.
    // To handle this, we have a separate command for navigating to the next/previous separator when we are not in quick access mode.
    // If, however, we are in quick access mode, and you hold down an additional modifier key, we will navigate to the next/previous separator.
    const nextSeparatorFallbackDesc = (0, nls_1.localize)(1588, "If we're in quick access mode, this will navigate to the next item. If we are not in quick access mode, this will navigate to the next separator.");
    const prevSeparatorFallbackDesc = (0, nls_1.localize)(1589, "If we're in quick access mode, this will navigate to the previous item. If we are not in quick access mode, this will navigate to the previous separator.");
    if (platform_1.isMacintosh) {
        registerQuickPickCommandAndKeybindingRule({
            id: 'quickInput.nextSeparatorWithQuickAccessFallback',
            primary: 2048 /* KeyMod.CtrlCmd */ + 18 /* KeyCode.DownArrow */,
            handler: focusHandler(quickInput_2.QuickPickFocus.NextSeparator, quickInput_2.QuickPickFocus.Next),
            metadata: { description: nextSeparatorFallbackDesc }
        });
        registerQuickPickCommandAndKeybindingRule({
            id: 'quickInput.nextSeparator',
            primary: 2048 /* KeyMod.CtrlCmd */ + 512 /* KeyMod.Alt */ + 18 /* KeyCode.DownArrow */,
            // Since macOS has the cmd key as the primary modifier, we need to add this additional
            // keybinding to capture cmd+ctrl+upArrow
            secondary: [2048 /* KeyMod.CtrlCmd */ + 256 /* KeyMod.WinCtrl */ + 18 /* KeyCode.DownArrow */],
            handler: focusHandler(quickInput_2.QuickPickFocus.NextSeparator)
        }, { withCtrlMod: true });
        registerQuickPickCommandAndKeybindingRule({
            id: 'quickInput.previousSeparatorWithQuickAccessFallback',
            primary: 2048 /* KeyMod.CtrlCmd */ + 16 /* KeyCode.UpArrow */,
            handler: focusHandler(quickInput_2.QuickPickFocus.PreviousSeparator, quickInput_2.QuickPickFocus.Previous),
            metadata: { description: prevSeparatorFallbackDesc }
        });
        registerQuickPickCommandAndKeybindingRule({
            id: 'quickInput.previousSeparator',
            primary: 2048 /* KeyMod.CtrlCmd */ + 512 /* KeyMod.Alt */ + 16 /* KeyCode.UpArrow */,
            // Since macOS has the cmd key as the primary modifier, we need to add this additional
            // keybinding to capture cmd+ctrl+upArrow
            secondary: [2048 /* KeyMod.CtrlCmd */ + 256 /* KeyMod.WinCtrl */ + 16 /* KeyCode.UpArrow */],
            handler: focusHandler(quickInput_2.QuickPickFocus.PreviousSeparator)
        }, { withCtrlMod: true });
    }
    else {
        registerQuickPickCommandAndKeybindingRule({
            id: 'quickInput.nextSeparatorWithQuickAccessFallback',
            primary: 512 /* KeyMod.Alt */ + 18 /* KeyCode.DownArrow */,
            handler: focusHandler(quickInput_2.QuickPickFocus.NextSeparator, quickInput_2.QuickPickFocus.Next),
            metadata: { description: nextSeparatorFallbackDesc }
        });
        registerQuickPickCommandAndKeybindingRule({
            id: 'quickInput.nextSeparator',
            primary: 2048 /* KeyMod.CtrlCmd */ + 512 /* KeyMod.Alt */ + 18 /* KeyCode.DownArrow */,
            handler: focusHandler(quickInput_2.QuickPickFocus.NextSeparator)
        });
        registerQuickPickCommandAndKeybindingRule({
            id: 'quickInput.previousSeparatorWithQuickAccessFallback',
            primary: 512 /* KeyMod.Alt */ + 16 /* KeyCode.UpArrow */,
            handler: focusHandler(quickInput_2.QuickPickFocus.PreviousSeparator, quickInput_2.QuickPickFocus.Previous),
            metadata: { description: prevSeparatorFallbackDesc }
        });
        registerQuickPickCommandAndKeybindingRule({
            id: 'quickInput.previousSeparator',
            primary: 2048 /* KeyMod.CtrlCmd */ + 512 /* KeyMod.Alt */ + 16 /* KeyCode.UpArrow */,
            handler: focusHandler(quickInput_2.QuickPickFocus.PreviousSeparator)
        });
    }
    //#endregion
    //#region Accept
    registerQuickPickCommandAndKeybindingRule({
        id: 'quickInput.acceptInBackground',
        // If we are in the quick pick but the input box is not focused or our cursor is at the end of the input box
        when: contextkey_1.ContextKeyExpr.and(defaultCommandAndKeybindingRule.when, contextkey_1.ContextKeyExpr.or(contextkeys_1.InputFocusedContext.negate(), quickInput_1.endOfQuickInputBoxContext)),
        primary: 17 /* KeyCode.RightArrow */,
        // Need a little extra weight to ensure this keybinding is preferred over the default cmd+alt+right arrow keybinding
        // https://github.com/microsoft/vscode/blob/1451e4fbbbf074a4355cc537c35b547b80ce1c52/src/vs/workbench/browser/parts/editor/editorActions.ts#L1178-L1195
        weight: 200 /* KeybindingWeight.WorkbenchContrib */ + 50,
        handler: (accessor) => {
            const currentQuickPick = accessor.get(quickInput_2.IQuickInputService).currentQuickInput;
            currentQuickPick?.accept(true);
        },
    }, { withAltMod: true, withCtrlMod: true, withCmdMod: true });
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[156/*vs/platform/quickinput/common/quickAccess*/], __M([1/*require*/,0/*exports*/,13/*vs/base/common/arrays*/,2/*vs/base/common/lifecycle*/,38/*vs/platform/registry/common/platform*/]), function (require, exports, arrays_1, lifecycle_1, platform_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.QuickAccessRegistry = exports.Extensions = exports.DefaultQuickAccessFilterValue = void 0;
    var DefaultQuickAccessFilterValue;
    (function (DefaultQuickAccessFilterValue) {
        /**
         * Keep the value as it is given to quick access.
         */
        DefaultQuickAccessFilterValue[DefaultQuickAccessFilterValue["PRESERVE"] = 0] = "PRESERVE";
        /**
         * Use the value that was used last time something was accepted from the picker.
         */
        DefaultQuickAccessFilterValue[DefaultQuickAccessFilterValue["LAST"] = 1] = "LAST";
    })(DefaultQuickAccessFilterValue || (exports.DefaultQuickAccessFilterValue = DefaultQuickAccessFilterValue = {}));
    exports.Extensions = {
        Quickaccess: 'workbench.contributions.quickaccess'
    };
    class QuickAccessRegistry {
        constructor() {
            this.providers = [];
            this.defaultProvider = undefined;
        }
        registerQuickAccessProvider(provider) {
            // Extract the default provider when no prefix is present
            if (provider.prefix.length === 0) {
                this.defaultProvider = provider;
            }
            else {
                this.providers.push(provider);
            }
            // sort the providers by decreasing prefix length, such that longer
            // prefixes take priority: 'ext' vs 'ext install' - the latter should win
            this.providers.sort((providerA, providerB) => providerB.prefix.length - providerA.prefix.length);
            return (0, lifecycle_1.toDisposable)(() => {
                this.providers.splice(this.providers.indexOf(provider), 1);
                if (this.defaultProvider === provider) {
                    this.defaultProvider = undefined;
                }
            });
        }
        getQuickAccessProviders() {
            return (0, arrays_1.coalesce)([this.defaultProvider, ...this.providers]);
        }
        getQuickAccessProvider(prefix) {
            const result = prefix ? (this.providers.find(provider => prefix.startsWith(provider.prefix)) || undefined) : undefined;
            return result || this.defaultProvider;
        }
    }
    exports.QuickAccessRegistry = QuickAccessRegistry;
    platform_1.Registry.add(exports.Extensions.Quickaccess, new QuickAccessRegistry());
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[720/*vs/platform/quickinput/browser/helpQuickAccess*/], __M([1/*require*/,0/*exports*/,3/*vs/nls*/,38/*vs/platform/registry/common/platform*/,2/*vs/base/common/lifecycle*/,31/*vs/platform/keybinding/common/keybinding*/,156/*vs/platform/quickinput/common/quickAccess*/,66/*vs/platform/quickinput/common/quickInput*/]), function (require, exports, nls_1, platform_1, lifecycle_1, keybinding_1, quickAccess_1, quickInput_1) {
    "use strict";
    var HelpQuickAccessProvider_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.HelpQuickAccessProvider = void 0;
    let HelpQuickAccessProvider = class HelpQuickAccessProvider {
        static { HelpQuickAccessProvider_1 = this; }
        static { this.PREFIX = '?'; }
        constructor(quickInputService, keybindingService) {
            this.quickInputService = quickInputService;
            this.keybindingService = keybindingService;
            this.registry = platform_1.Registry.as(quickAccess_1.Extensions.Quickaccess);
        }
        provide(picker) {
            const disposables = new lifecycle_1.DisposableStore();
            // Open a picker with the selected value if picked
            disposables.add(picker.onDidAccept(() => {
                const [item] = picker.selectedItems;
                if (item) {
                    this.quickInputService.quickAccess.show(item.prefix, { preserveValue: true });
                }
            }));
            // Also open a picker when we detect the user typed the exact
            // name of a provider (e.g. `?term` for terminals)
            disposables.add(picker.onDidChangeValue(value => {
                const providerDescriptor = this.registry.getQuickAccessProvider(value.substr(HelpQuickAccessProvider_1.PREFIX.length));
                if (providerDescriptor && providerDescriptor.prefix && providerDescriptor.prefix !== HelpQuickAccessProvider_1.PREFIX) {
                    this.quickInputService.quickAccess.show(providerDescriptor.prefix, { preserveValue: true });
                }
            }));
            // Fill in all providers
            picker.items = this.getQuickAccessProviders().filter(p => p.prefix !== HelpQuickAccessProvider_1.PREFIX);
            return disposables;
        }
        getQuickAccessProviders() {
            const providers = this.registry
                .getQuickAccessProviders()
                .sort((providerA, providerB) => providerA.prefix.localeCompare(providerB.prefix))
                .flatMap(provider => this.createPicks(provider));
            return providers;
        }
        createPicks(provider) {
            return provider.helpEntries.map(helpEntry => {
                const prefix = helpEntry.prefix || provider.prefix;
                const label = prefix || '\u2026' /* ... */;
                return {
                    prefix,
                    label,
                    keybinding: helpEntry.commandId ? this.keybindingService.lookupKeybinding(helpEntry.commandId) : undefined,
                    ariaLabel: (0, nls_1.localize)(1579, "{0}, {1}", label, helpEntry.description),
                    description: helpEntry.description
                };
            });
        }
    };
    exports.HelpQuickAccessProvider = HelpQuickAccessProvider;
    exports.HelpQuickAccessProvider = HelpQuickAccessProvider = HelpQuickAccessProvider_1 = __decorate([
        __param(0, quickInput_1.IQuickInputService),
        __param(1, keybinding_1.IKeybindingService)
    ], HelpQuickAccessProvider);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[721/*vs/editor/standalone/browser/quickAccess/standaloneHelpQuickAccess*/], __M([1/*require*/,0/*exports*/,38/*vs/platform/registry/common/platform*/,156/*vs/platform/quickinput/common/quickAccess*/,107/*vs/editor/common/standaloneStrings*/,720/*vs/platform/quickinput/browser/helpQuickAccess*/]), function (require, exports, platform_1, quickAccess_1, standaloneStrings_1, helpQuickAccess_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    platform_1.Registry.as(quickAccess_1.Extensions.Quickaccess).registerQuickAccessProvider({
        ctor: helpQuickAccess_1.HelpQuickAccessProvider,
        prefix: '',
        helpEntries: [{ description: standaloneStrings_1.QuickHelpNLS.helpQuickAccessActionLabel }]
    });
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[722/*vs/platform/quickinput/browser/quickAccess*/], __M([1/*require*/,0/*exports*/,14/*vs/base/common/async*/,18/*vs/base/common/cancellation*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,7/*vs/platform/instantiation/common/instantiation*/,156/*vs/platform/quickinput/common/quickAccess*/,66/*vs/platform/quickinput/common/quickInput*/,38/*vs/platform/registry/common/platform*/]), function (require, exports, async_1, cancellation_1, event_1, lifecycle_1, instantiation_1, quickAccess_1, quickInput_1, platform_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.QuickAccessController = void 0;
    let QuickAccessController = class QuickAccessController extends lifecycle_1.Disposable {
        constructor(quickInputService, instantiationService) {
            super();
            this.quickInputService = quickInputService;
            this.instantiationService = instantiationService;
            this.registry = platform_1.Registry.as(quickAccess_1.Extensions.Quickaccess);
            this.mapProviderToDescriptor = new Map();
            this.lastAcceptedPickerValues = new Map();
            this.visibleQuickAccess = undefined;
        }
        show(value = '', options) {
            this.doShowOrPick(value, false, options);
        }
        doShowOrPick(value, pick, options) {
            // Find provider for the value to show
            const [provider, descriptor] = this.getOrInstantiateProvider(value, options?.enabledProviderPrefixes);
            // Return early if quick access is already showing on that same prefix
            const visibleQuickAccess = this.visibleQuickAccess;
            const visibleDescriptor = visibleQuickAccess?.descriptor;
            if (visibleQuickAccess && descriptor && visibleDescriptor === descriptor) {
                // Apply value only if it is more specific than the prefix
                // from the provider and we are not instructed to preserve
                if (value !== descriptor.prefix && !options?.preserveValue) {
                    visibleQuickAccess.picker.value = value;
                }
                // Always adjust selection
                this.adjustValueSelection(visibleQuickAccess.picker, descriptor, options);
                return;
            }
            // Rewrite the filter value based on certain rules unless disabled
            if (descriptor && !options?.preserveValue) {
                let newValue = undefined;
                // If we have a visible provider with a value, take it's filter value but
                // rewrite to new provider prefix in case they differ
                if (visibleQuickAccess && visibleDescriptor && visibleDescriptor !== descriptor) {
                    const newValueCandidateWithoutPrefix = visibleQuickAccess.value.substr(visibleDescriptor.prefix.length);
                    if (newValueCandidateWithoutPrefix) {
                        newValue = `${descriptor.prefix}${newValueCandidateWithoutPrefix}`;
                    }
                }
                // Otherwise, take a default value as instructed
                if (!newValue) {
                    const defaultFilterValue = provider?.defaultFilterValue;
                    if (defaultFilterValue === quickAccess_1.DefaultQuickAccessFilterValue.LAST) {
                        newValue = this.lastAcceptedPickerValues.get(descriptor);
                    }
                    else if (typeof defaultFilterValue === 'string') {
                        newValue = `${descriptor.prefix}${defaultFilterValue}`;
                    }
                }
                if (typeof newValue === 'string') {
                    value = newValue;
                }
            }
            // Store the existing selection if there was one.
            const visibleSelection = visibleQuickAccess?.picker?.valueSelection;
            const visibleValue = visibleQuickAccess?.picker?.value;
            // Create a picker for the provider to use with the initial value
            // and adjust the filtering to exclude the prefix from filtering
            const disposables = new lifecycle_1.DisposableStore();
            const picker = disposables.add(this.quickInputService.createQuickPick({ useSeparators: true }));
            picker.value = value;
            this.adjustValueSelection(picker, descriptor, options);
            picker.placeholder = options?.placeholder ?? descriptor?.placeholder;
            picker.quickNavigate = options?.quickNavigateConfiguration;
            picker.hideInput = !!picker.quickNavigate && !visibleQuickAccess; // only hide input if there was no picker opened already
            if (typeof options?.itemActivation === 'number' || options?.quickNavigateConfiguration) {
                picker.itemActivation = options?.itemActivation ?? quickInput_1.ItemActivation.SECOND /* quick nav is always second */;
            }
            picker.contextKey = descriptor?.contextKey;
            picker.filterValue = (value) => value.substring(descriptor ? descriptor.prefix.length : 0);
            // Pick mode: setup a promise that can be resolved
            // with the selected items and prevent execution
            let pickPromise = undefined;
            if (pick) {
                pickPromise = new async_1.DeferredPromise();
                disposables.add(event_1.Event.once(picker.onWillAccept)(e => {
                    e.veto();
                    picker.hide();
                }));
            }
            // Register listeners
            disposables.add(this.registerPickerListeners(picker, provider, descriptor, value, options));
            // Ask provider to fill the picker as needed if we have one
            // and pass over a cancellation token that will indicate when
            // the picker is hiding without a pick being made.
            const cts = disposables.add(new cancellation_1.CancellationTokenSource());
            if (provider) {
                disposables.add(provider.provide(picker, cts.token, options?.providerOptions));
            }
            // Finally, trigger disposal and cancellation when the picker
            // hides depending on items selected or not.
            event_1.Event.once(picker.onDidHide)(() => {
                if (picker.selectedItems.length === 0) {
                    cts.cancel();
                }
                // Start to dispose once picker hides
                disposables.dispose();
                // Resolve pick promise with selected items
                pickPromise?.complete(picker.selectedItems.slice(0));
            });
            // Finally, show the picker. This is important because a provider
            // may not call this and then our disposables would leak that rely
            // on the onDidHide event.
            picker.show();
            // If the previous picker had a selection and the value is unchanged, we should set that in the new picker.
            if (visibleSelection && visibleValue === value) {
                picker.valueSelection = visibleSelection;
            }
            // Pick mode: return with promise
            if (pick) {
                return pickPromise?.p;
            }
        }
        adjustValueSelection(picker, descriptor, options) {
            let valueSelection;
            // Preserve: just always put the cursor at the end
            if (options?.preserveValue) {
                valueSelection = [picker.value.length, picker.value.length];
            }
            // Otherwise: select the value up until the prefix
            else {
                valueSelection = [descriptor?.prefix.length ?? 0, picker.value.length];
            }
            picker.valueSelection = valueSelection;
        }
        registerPickerListeners(picker, provider, descriptor, value, options) {
            const disposables = new lifecycle_1.DisposableStore();
            // Remember as last visible picker and clean up once picker get's disposed
            const visibleQuickAccess = this.visibleQuickAccess = { picker, descriptor, value };
            disposables.add((0, lifecycle_1.toDisposable)(() => {
                if (visibleQuickAccess === this.visibleQuickAccess) {
                    this.visibleQuickAccess = undefined;
                }
            }));
            // Whenever the value changes, check if the provider has
            // changed and if so - re-create the picker from the beginning
            disposables.add(picker.onDidChangeValue(value => {
                const [providerForValue] = this.getOrInstantiateProvider(value, options?.enabledProviderPrefixes);
                if (providerForValue !== provider) {
                    this.show(value, {
                        enabledProviderPrefixes: options?.enabledProviderPrefixes,
                        // do not rewrite value from user typing!
                        preserveValue: true,
                        // persist the value of the providerOptions from the original showing
                        providerOptions: options?.providerOptions
                    });
                }
                else {
                    visibleQuickAccess.value = value; // remember the value in our visible one
                }
            }));
            // Remember picker input for future use when accepting
            if (descriptor) {
                disposables.add(picker.onDidAccept(() => {
                    this.lastAcceptedPickerValues.set(descriptor, picker.value);
                }));
            }
            return disposables;
        }
        getOrInstantiateProvider(value, enabledProviderPrefixes) {
            const providerDescriptor = this.registry.getQuickAccessProvider(value);
            if (!providerDescriptor || enabledProviderPrefixes && !enabledProviderPrefixes?.includes(providerDescriptor.prefix)) {
                return [undefined, undefined];
            }
            let provider = this.mapProviderToDescriptor.get(providerDescriptor);
            if (!provider) {
                provider = this.instantiationService.createInstance(providerDescriptor.ctor);
                this.mapProviderToDescriptor.set(providerDescriptor, provider);
            }
            return [provider, providerDescriptor];
        }
    };
    exports.QuickAccessController = QuickAccessController;
    exports.QuickAccessController = QuickAccessController = __decorate([
        __param(0, quickInput_1.IQuickInputService),
        __param(1, instantiation_1.IInstantiationService)
    ], QuickAccessController);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[723/*vs/platform/severityIcon/browser/severityIcon*/], __M([1/*require*/,0/*exports*/,26/*vs/base/common/codicons*/,30/*vs/base/common/themables*/,111/*vs/base/common/severity*/,544/*vs/css!vs/platform/severityIcon/browser/media/severityIcon*/]), function (require, exports, codicons_1, themables_1, severity_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SeverityIcon = void 0;
    var SeverityIcon;
    (function (SeverityIcon) {
        function className(severity) {
            switch (severity) {
                case severity_1.default.Ignore:
                    return 'severity-ignore ' + themables_1.ThemeIcon.asClassName(codicons_1.Codicon.info);
                case severity_1.default.Info:
                    return themables_1.ThemeIcon.asClassName(codicons_1.Codicon.info);
                case severity_1.default.Warning:
                    return themables_1.ThemeIcon.asClassName(codicons_1.Codicon.warning);
                case severity_1.default.Error:
                    return themables_1.ThemeIcon.asClassName(codicons_1.Codicon.error);
                default:
                    return '';
            }
        }
        SeverityIcon.className = className;
    })(SeverityIcon || (exports.SeverityIcon = SeverityIcon = {}));
});

define(__m[101/*vs/platform/storage/common/storage*/], __M([1/*require*/,0/*exports*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,19/*vs/base/common/types*/,647/*vs/base/parts/storage/common/storage*/,7/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, event_1, lifecycle_1, types_1, storage_1, instantiation_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.InMemoryStorageService = exports.AbstractStorageService = exports.WillSaveStateReason = exports.IStorageService = exports.TARGET_KEY = void 0;
    exports.loadKeyTargets = loadKeyTargets;
    exports.TARGET_KEY = '__$__targetStorageMarker';
    exports.IStorageService = (0, instantiation_1.createDecorator)('storageService');
    var WillSaveStateReason;
    (function (WillSaveStateReason) {
        /**
         * No specific reason to save state.
         */
        WillSaveStateReason[WillSaveStateReason["NONE"] = 0] = "NONE";
        /**
         * A hint that the workbench is about to shutdown.
         */
        WillSaveStateReason[WillSaveStateReason["SHUTDOWN"] = 1] = "SHUTDOWN";
    })(WillSaveStateReason || (exports.WillSaveStateReason = WillSaveStateReason = {}));
    function loadKeyTargets(storage) {
        const keysRaw = storage.get(exports.TARGET_KEY);
        if (keysRaw) {
            try {
                return JSON.parse(keysRaw);
            }
            catch (error) {
                // Fail gracefully
            }
        }
        return Object.create(null);
    }
    class AbstractStorageService extends lifecycle_1.Disposable {
        static { this.DEFAULT_FLUSH_INTERVAL = 60 * 1000; } // every minute
        constructor(options = { flushInterval: AbstractStorageService.DEFAULT_FLUSH_INTERVAL }) {
            super();
            this.options = options;
            this._onDidChangeValue = this._register(new event_1.PauseableEmitter());
            this._onDidChangeTarget = this._register(new event_1.PauseableEmitter());
            this._onWillSaveState = this._register(new event_1.Emitter());
            this.onWillSaveState = this._onWillSaveState.event;
            this._workspaceKeyTargets = undefined;
            this._profileKeyTargets = undefined;
            this._applicationKeyTargets = undefined;
        }
        onDidChangeValue(scope, key, disposable) {
            return event_1.Event.filter(this._onDidChangeValue.event, e => e.scope === scope && (key === undefined || e.key === key), disposable);
        }
        emitDidChangeValue(scope, event) {
            const { key, external } = event;
            // Specially handle `TARGET_KEY`
            if (key === exports.TARGET_KEY) {
                // Clear our cached version which is now out of date
                switch (scope) {
                    case -1 /* StorageScope.APPLICATION */:
                        this._applicationKeyTargets = undefined;
                        break;
                    case 0 /* StorageScope.PROFILE */:
                        this._profileKeyTargets = undefined;
                        break;
                    case 1 /* StorageScope.WORKSPACE */:
                        this._workspaceKeyTargets = undefined;
                        break;
                }
                // Emit as `didChangeTarget` event
                this._onDidChangeTarget.fire({ scope });
            }
            // Emit any other key to outside
            else {
                this._onDidChangeValue.fire({ scope, key, target: this.getKeyTargets(scope)[key], external });
            }
        }
        get(key, scope, fallbackValue) {
            return this.getStorage(scope)?.get(key, fallbackValue);
        }
        getBoolean(key, scope, fallbackValue) {
            return this.getStorage(scope)?.getBoolean(key, fallbackValue);
        }
        getNumber(key, scope, fallbackValue) {
            return this.getStorage(scope)?.getNumber(key, fallbackValue);
        }
        store(key, value, scope, target, external = false) {
            // We remove the key for undefined/null values
            if ((0, types_1.isUndefinedOrNull)(value)) {
                this.remove(key, scope, external);
                return;
            }
            // Update our datastructures but send events only after
            this.withPausedEmitters(() => {
                // Update key-target map
                this.updateKeyTarget(key, scope, target);
                // Store actual value
                this.getStorage(scope)?.set(key, value, external);
            });
        }
        remove(key, scope, external = false) {
            // Update our datastructures but send events only after
            this.withPausedEmitters(() => {
                // Update key-target map
                this.updateKeyTarget(key, scope, undefined);
                // Remove actual key
                this.getStorage(scope)?.delete(key, external);
            });
        }
        withPausedEmitters(fn) {
            // Pause emitters
            this._onDidChangeValue.pause();
            this._onDidChangeTarget.pause();
            try {
                fn();
            }
            finally {
                // Resume emitters
                this._onDidChangeValue.resume();
                this._onDidChangeTarget.resume();
            }
        }
        updateKeyTarget(key, scope, target, external = false) {
            // Add
            const keyTargets = this.getKeyTargets(scope);
            if (typeof target === 'number') {
                if (keyTargets[key] !== target) {
                    keyTargets[key] = target;
                    this.getStorage(scope)?.set(exports.TARGET_KEY, JSON.stringify(keyTargets), external);
                }
            }
            // Remove
            else {
                if (typeof keyTargets[key] === 'number') {
                    delete keyTargets[key];
                    this.getStorage(scope)?.set(exports.TARGET_KEY, JSON.stringify(keyTargets), external);
                }
            }
        }
        get workspaceKeyTargets() {
            if (!this._workspaceKeyTargets) {
                this._workspaceKeyTargets = this.loadKeyTargets(1 /* StorageScope.WORKSPACE */);
            }
            return this._workspaceKeyTargets;
        }
        get profileKeyTargets() {
            if (!this._profileKeyTargets) {
                this._profileKeyTargets = this.loadKeyTargets(0 /* StorageScope.PROFILE */);
            }
            return this._profileKeyTargets;
        }
        get applicationKeyTargets() {
            if (!this._applicationKeyTargets) {
                this._applicationKeyTargets = this.loadKeyTargets(-1 /* StorageScope.APPLICATION */);
            }
            return this._applicationKeyTargets;
        }
        getKeyTargets(scope) {
            switch (scope) {
                case -1 /* StorageScope.APPLICATION */:
                    return this.applicationKeyTargets;
                case 0 /* StorageScope.PROFILE */:
                    return this.profileKeyTargets;
                default:
                    return this.workspaceKeyTargets;
            }
        }
        loadKeyTargets(scope) {
            const storage = this.getStorage(scope);
            return storage ? loadKeyTargets(storage) : Object.create(null);
        }
    }
    exports.AbstractStorageService = AbstractStorageService;
    class InMemoryStorageService extends AbstractStorageService {
        constructor() {
            super();
            this.applicationStorage = this._register(new storage_1.Storage(new storage_1.InMemoryStorageDatabase(), { hint: storage_1.StorageHint.STORAGE_IN_MEMORY }));
            this.profileStorage = this._register(new storage_1.Storage(new storage_1.InMemoryStorageDatabase(), { hint: storage_1.StorageHint.STORAGE_IN_MEMORY }));
            this.workspaceStorage = this._register(new storage_1.Storage(new storage_1.InMemoryStorageDatabase(), { hint: storage_1.StorageHint.STORAGE_IN_MEMORY }));
            this._register(this.workspaceStorage.onDidChangeStorage(e => this.emitDidChangeValue(1 /* StorageScope.WORKSPACE */, e)));
            this._register(this.profileStorage.onDidChangeStorage(e => this.emitDidChangeValue(0 /* StorageScope.PROFILE */, e)));
            this._register(this.applicationStorage.onDidChangeStorage(e => this.emitDidChangeValue(-1 /* StorageScope.APPLICATION */, e)));
        }
        getStorage(scope) {
            switch (scope) {
                case -1 /* StorageScope.APPLICATION */:
                    return this.applicationStorage;
                case 0 /* StorageScope.PROFILE */:
                    return this.profileStorage;
                default:
                    return this.workspaceStorage;
            }
        }
    }
    exports.InMemoryStorageService = InMemoryStorageService;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[724/*vs/editor/contrib/codelens/browser/codeLensCache*/], __M([1/*require*/,0/*exports*/,6/*vs/base/common/event*/,45/*vs/base/common/map*/,4/*vs/editor/common/core/range*/,386/*vs/editor/contrib/codelens/browser/codelens*/,49/*vs/platform/instantiation/common/extensions*/,7/*vs/platform/instantiation/common/instantiation*/,101/*vs/platform/storage/common/storage*/,52/*vs/base/browser/window*/,5/*vs/base/browser/dom*/]), function (require, exports, event_1, map_1, range_1, codelens_1, extensions_1, instantiation_1, storage_1, window_1, dom_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CodeLensCache = exports.ICodeLensCache = void 0;
    exports.ICodeLensCache = (0, instantiation_1.createDecorator)('ICodeLensCache');
    class CacheItem {
        constructor(lineCount, data) {
            this.lineCount = lineCount;
            this.data = data;
        }
    }
    let CodeLensCache = class CodeLensCache {
        constructor(storageService) {
            this._fakeProvider = new class {
                provideCodeLenses() {
                    throw new Error('not supported');
                }
            };
            this._cache = new map_1.LRUCache(20, 0.75);
            // remove old data
            const oldkey = 'codelens/cache';
            (0, dom_1.runWhenWindowIdle)(window_1.mainWindow, () => storageService.remove(oldkey, 1 /* StorageScope.WORKSPACE */));
            // restore lens data on start
            const key = 'codelens/cache2';
            const raw = storageService.get(key, 1 /* StorageScope.WORKSPACE */, '{}');
            this._deserialize(raw);
            // store lens data on shutdown
            const onWillSaveStateBecauseOfShutdown = event_1.Event.filter(storageService.onWillSaveState, e => e.reason === storage_1.WillSaveStateReason.SHUTDOWN);
            event_1.Event.once(onWillSaveStateBecauseOfShutdown)(e => {
                storageService.store(key, this._serialize(), 1 /* StorageScope.WORKSPACE */, 1 /* StorageTarget.MACHINE */);
            });
        }
        put(model, data) {
            // create a copy of the model that is without command-ids
            // but with comand-labels
            const copyItems = data.lenses.map((item) => {
                return {
                    range: item.symbol.range,
                    command: item.symbol.command && { id: '', title: item.symbol.command?.title },
                };
            });
            const copyModel = new codelens_1.CodeLensModel();
            copyModel.add({ lenses: copyItems, dispose: () => { } }, this._fakeProvider);
            const item = new CacheItem(model.getLineCount(), copyModel);
            this._cache.set(model.uri.toString(), item);
        }
        get(model) {
            const item = this._cache.get(model.uri.toString());
            return item && item.lineCount === model.getLineCount() ? item.data : undefined;
        }
        delete(model) {
            this._cache.delete(model.uri.toString());
        }
        // --- persistence
        _serialize() {
            const data = Object.create(null);
            for (const [key, value] of this._cache) {
                const lines = new Set();
                for (const d of value.data.lenses) {
                    lines.add(d.symbol.range.startLineNumber);
                }
                data[key] = {
                    lineCount: value.lineCount,
                    lines: [...lines.values()]
                };
            }
            return JSON.stringify(data);
        }
        _deserialize(raw) {
            try {
                const data = JSON.parse(raw);
                for (const key in data) {
                    const element = data[key];
                    const lenses = [];
                    for (const line of element.lines) {
                        lenses.push({ range: new range_1.Range(line, 1, line, 11) });
                    }
                    const model = new codelens_1.CodeLensModel();
                    model.add({ lenses, dispose() { } }, this._fakeProvider);
                    this._cache.set(key, new CacheItem(element.lineCount, model));
                }
            }
            catch {
                // ignore...
            }
        }
    };
    exports.CodeLensCache = CodeLensCache;
    exports.CodeLensCache = CodeLensCache = __decorate([
        __param(0, storage_1.IStorageService)
    ], CodeLensCache);
    (0, extensions_1.registerSingleton)(exports.ICodeLensCache, CodeLensCache, 1 /* InstantiationType.Delayed */);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[405/*vs/editor/contrib/suggest/browser/suggestMemory*/], __M([1/*require*/,0/*exports*/,14/*vs/base/common/async*/,2/*vs/base/common/lifecycle*/,45/*vs/base/common/map*/,225/*vs/base/common/ternarySearchTree*/,27/*vs/editor/common/languages*/,28/*vs/platform/configuration/common/configuration*/,49/*vs/platform/instantiation/common/extensions*/,7/*vs/platform/instantiation/common/instantiation*/,101/*vs/platform/storage/common/storage*/]), function (require, exports, async_1, lifecycle_1, map_1, ternarySearchTree_1, languages_1, configuration_1, extensions_1, instantiation_1, storage_1) {
    "use strict";
    var SuggestMemoryService_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ISuggestMemoryService = exports.SuggestMemoryService = exports.PrefixMemory = exports.LRUMemory = exports.NoMemory = exports.Memory = void 0;
    class Memory {
        constructor(name) {
            this.name = name;
        }
        select(model, pos, items) {
            if (items.length === 0) {
                return 0;
            }
            const topScore = items[0].score[0];
            for (let i = 0; i < items.length; i++) {
                const { score, completion: suggestion } = items[i];
                if (score[0] !== topScore) {
                    // stop when leaving the group of top matches
                    break;
                }
                if (suggestion.preselect) {
                    // stop when seeing an auto-select-item
                    return i;
                }
            }
            return 0;
        }
    }
    exports.Memory = Memory;
    class NoMemory extends Memory {
        constructor() {
            super('first');
        }
        memorize(model, pos, item) {
            // no-op
        }
        toJSON() {
            return undefined;
        }
        fromJSON() {
            //
        }
    }
    exports.NoMemory = NoMemory;
    class LRUMemory extends Memory {
        constructor() {
            super('recentlyUsed');
            this._cache = new map_1.LRUCache(300, 0.66);
            this._seq = 0;
        }
        memorize(model, pos, item) {
            const key = `${model.getLanguageId()}/${item.textLabel}`;
            this._cache.set(key, {
                touch: this._seq++,
                type: item.completion.kind,
                insertText: item.completion.insertText
            });
        }
        select(model, pos, items) {
            if (items.length === 0) {
                return 0;
            }
            const lineSuffix = model.getLineContent(pos.lineNumber).substr(pos.column - 10, pos.column - 1);
            if (/\s$/.test(lineSuffix)) {
                return super.select(model, pos, items);
            }
            const topScore = items[0].score[0];
            let indexPreselect = -1;
            let indexRecency = -1;
            let seq = -1;
            for (let i = 0; i < items.length; i++) {
                if (items[i].score[0] !== topScore) {
                    // consider only top items
                    break;
                }
                const key = `${model.getLanguageId()}/${items[i].textLabel}`;
                const item = this._cache.peek(key);
                if (item && item.touch > seq && item.type === items[i].completion.kind && item.insertText === items[i].completion.insertText) {
                    seq = item.touch;
                    indexRecency = i;
                }
                if (items[i].completion.preselect && indexPreselect === -1) {
                    // stop when seeing an auto-select-item
                    return indexPreselect = i;
                }
            }
            if (indexRecency !== -1) {
                return indexRecency;
            }
            else if (indexPreselect !== -1) {
                return indexPreselect;
            }
            else {
                return 0;
            }
        }
        toJSON() {
            return this._cache.toJSON();
        }
        fromJSON(data) {
            this._cache.clear();
            const seq = 0;
            for (const [key, value] of data) {
                value.touch = seq;
                value.type = typeof value.type === 'number' ? value.type : languages_1.CompletionItemKinds.fromString(value.type);
                this._cache.set(key, value);
            }
            this._seq = this._cache.size;
        }
    }
    exports.LRUMemory = LRUMemory;
    class PrefixMemory extends Memory {
        constructor() {
            super('recentlyUsedByPrefix');
            this._trie = ternarySearchTree_1.TernarySearchTree.forStrings();
            this._seq = 0;
        }
        memorize(model, pos, item) {
            const { word } = model.getWordUntilPosition(pos);
            const key = `${model.getLanguageId()}/${word}`;
            this._trie.set(key, {
                type: item.completion.kind,
                insertText: item.completion.insertText,
                touch: this._seq++
            });
        }
        select(model, pos, items) {
            const { word } = model.getWordUntilPosition(pos);
            if (!word) {
                return super.select(model, pos, items);
            }
            const key = `${model.getLanguageId()}/${word}`;
            let item = this._trie.get(key);
            if (!item) {
                item = this._trie.findSubstr(key);
            }
            if (item) {
                for (let i = 0; i < items.length; i++) {
                    const { kind, insertText } = items[i].completion;
                    if (kind === item.type && insertText === item.insertText) {
                        return i;
                    }
                }
            }
            return super.select(model, pos, items);
        }
        toJSON() {
            const entries = [];
            this._trie.forEach((value, key) => entries.push([key, value]));
            // sort by last recently used (touch), then
            // take the top 200 item and normalize their
            // touch
            entries
                .sort((a, b) => -(a[1].touch - b[1].touch))
                .forEach((value, i) => value[1].touch = i);
            return entries.slice(0, 200);
        }
        fromJSON(data) {
            this._trie.clear();
            if (data.length > 0) {
                this._seq = data[0][1].touch + 1;
                for (const [key, value] of data) {
                    value.type = typeof value.type === 'number' ? value.type : languages_1.CompletionItemKinds.fromString(value.type);
                    this._trie.set(key, value);
                }
            }
        }
    }
    exports.PrefixMemory = PrefixMemory;
    let SuggestMemoryService = class SuggestMemoryService {
        static { SuggestMemoryService_1 = this; }
        static { this._strategyCtors = new Map([
            ['recentlyUsedByPrefix', PrefixMemory],
            ['recentlyUsed', LRUMemory],
            ['first', NoMemory]
        ]); }
        static { this._storagePrefix = 'suggest/memories'; }
        constructor(_storageService, _configService) {
            this._storageService = _storageService;
            this._configService = _configService;
            this._disposables = new lifecycle_1.DisposableStore();
            this._persistSoon = new async_1.RunOnceScheduler(() => this._saveState(), 500);
            this._disposables.add(_storageService.onWillSaveState(e => {
                if (e.reason === storage_1.WillSaveStateReason.SHUTDOWN) {
                    this._saveState();
                }
            }));
        }
        dispose() {
            this._disposables.dispose();
            this._persistSoon.dispose();
        }
        memorize(model, pos, item) {
            this._withStrategy(model, pos).memorize(model, pos, item);
            this._persistSoon.schedule();
        }
        select(model, pos, items) {
            return this._withStrategy(model, pos).select(model, pos, items);
        }
        _withStrategy(model, pos) {
            const mode = this._configService.getValue('editor.suggestSelection', {
                overrideIdentifier: model.getLanguageIdAtPosition(pos.lineNumber, pos.column),
                resource: model.uri
            });
            if (this._strategy?.name !== mode) {
                this._saveState();
                const ctor = SuggestMemoryService_1._strategyCtors.get(mode) || NoMemory;
                this._strategy = new ctor();
                try {
                    const share = this._configService.getValue('editor.suggest.shareSuggestSelections');
                    const scope = share ? 0 /* StorageScope.PROFILE */ : 1 /* StorageScope.WORKSPACE */;
                    const raw = this._storageService.get(`${SuggestMemoryService_1._storagePrefix}/${mode}`, scope);
                    if (raw) {
                        this._strategy.fromJSON(JSON.parse(raw));
                    }
                }
                catch (e) {
                    // things can go wrong with JSON...
                }
            }
            return this._strategy;
        }
        _saveState() {
            if (this._strategy) {
                const share = this._configService.getValue('editor.suggest.shareSuggestSelections');
                const scope = share ? 0 /* StorageScope.PROFILE */ : 1 /* StorageScope.WORKSPACE */;
                const raw = JSON.stringify(this._strategy);
                this._storageService.store(`${SuggestMemoryService_1._storagePrefix}/${this._strategy.name}`, raw, scope, 1 /* StorageTarget.MACHINE */);
            }
        }
    };
    exports.SuggestMemoryService = SuggestMemoryService;
    exports.SuggestMemoryService = SuggestMemoryService = SuggestMemoryService_1 = __decorate([
        __param(0, storage_1.IStorageService),
        __param(1, configuration_1.IConfigurationService)
    ], SuggestMemoryService);
    exports.ISuggestMemoryService = (0, instantiation_1.createDecorator)('ISuggestMemories');
    (0, extensions_1.registerSingleton)(exports.ISuggestMemoryService, SuggestMemoryService, 1 /* InstantiationType.Delayed */);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[406/*vs/platform/actions/common/menuService*/], __M([1/*require*/,0/*exports*/,14/*vs/base/common/async*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,29/*vs/platform/actions/common/actions*/,24/*vs/platform/commands/common/commands*/,12/*vs/platform/contextkey/common/contextkey*/,41/*vs/base/common/actions*/,101/*vs/platform/storage/common/storage*/,13/*vs/base/common/arrays*/,3/*vs/nls*/,31/*vs/platform/keybinding/common/keybinding*/]), function (require, exports, async_1, event_1, lifecycle_1, actions_1, commands_1, contextkey_1, actions_2, storage_1, arrays_1, nls_1, keybinding_1) {
    "use strict";
    var PersistedMenuHideState_1, MenuInfo_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MenuService = void 0;
    exports.createConfigureKeybindingAction = createConfigureKeybindingAction;
    let MenuService = class MenuService {
        constructor(_commandService, _keybindingService, storageService) {
            this._commandService = _commandService;
            this._keybindingService = _keybindingService;
            this._hiddenStates = new PersistedMenuHideState(storageService);
        }
        createMenu(id, contextKeyService, options) {
            return new MenuImpl(id, this._hiddenStates, { emitEventsForSubmenuChanges: false, eventDebounceDelay: 50, ...options }, this._commandService, this._keybindingService, contextKeyService);
        }
        getMenuActions(id, contextKeyService, options) {
            const menu = new MenuImpl(id, this._hiddenStates, { emitEventsForSubmenuChanges: false, eventDebounceDelay: 50, ...options }, this._commandService, this._keybindingService, contextKeyService);
            const actions = menu.getActions(options);
            menu.dispose();
            return actions;
        }
        resetHiddenStates(ids) {
            this._hiddenStates.reset(ids);
        }
    };
    exports.MenuService = MenuService;
    exports.MenuService = MenuService = __decorate([
        __param(0, commands_1.ICommandService),
        __param(1, keybinding_1.IKeybindingService),
        __param(2, storage_1.IStorageService)
    ], MenuService);
    let PersistedMenuHideState = class PersistedMenuHideState {
        static { PersistedMenuHideState_1 = this; }
        static { this._key = 'menu.hiddenCommands'; }
        constructor(_storageService) {
            this._storageService = _storageService;
            this._disposables = new lifecycle_1.DisposableStore();
            this._onDidChange = new event_1.Emitter();
            this.onDidChange = this._onDidChange.event;
            this._ignoreChangeEvent = false;
            this._hiddenByDefaultCache = new Map();
            try {
                const raw = _storageService.get(PersistedMenuHideState_1._key, 0 /* StorageScope.PROFILE */, '{}');
                this._data = JSON.parse(raw);
            }
            catch (err) {
                this._data = Object.create(null);
            }
            this._disposables.add(_storageService.onDidChangeValue(0 /* StorageScope.PROFILE */, PersistedMenuHideState_1._key, this._disposables)(() => {
                if (!this._ignoreChangeEvent) {
                    try {
                        const raw = _storageService.get(PersistedMenuHideState_1._key, 0 /* StorageScope.PROFILE */, '{}');
                        this._data = JSON.parse(raw);
                    }
                    catch (err) {
                        console.log('FAILED to read storage after UPDATE', err);
                    }
                }
                this._onDidChange.fire();
            }));
        }
        dispose() {
            this._onDidChange.dispose();
            this._disposables.dispose();
        }
        _isHiddenByDefault(menu, commandId) {
            return this._hiddenByDefaultCache.get(`${menu.id}/${commandId}`) ?? false;
        }
        setDefaultState(menu, commandId, hidden) {
            this._hiddenByDefaultCache.set(`${menu.id}/${commandId}`, hidden);
        }
        isHidden(menu, commandId) {
            const hiddenByDefault = this._isHiddenByDefault(menu, commandId);
            const state = this._data[menu.id]?.includes(commandId) ?? false;
            return hiddenByDefault ? !state : state;
        }
        updateHidden(menu, commandId, hidden) {
            const hiddenByDefault = this._isHiddenByDefault(menu, commandId);
            if (hiddenByDefault) {
                hidden = !hidden;
            }
            const entries = this._data[menu.id];
            if (!hidden) {
                // remove and cleanup
                if (entries) {
                    const idx = entries.indexOf(commandId);
                    if (idx >= 0) {
                        (0, arrays_1.removeFastWithoutKeepingOrder)(entries, idx);
                    }
                    if (entries.length === 0) {
                        delete this._data[menu.id];
                    }
                }
            }
            else {
                // add unless already added
                if (!entries) {
                    this._data[menu.id] = [commandId];
                }
                else {
                    const idx = entries.indexOf(commandId);
                    if (idx < 0) {
                        entries.push(commandId);
                    }
                }
            }
            this._persist();
        }
        reset(menus) {
            if (menus === undefined) {
                // reset all
                this._data = Object.create(null);
                this._persist();
            }
            else {
                // reset only for a specific menu
                for (const { id } of menus) {
                    if (this._data[id]) {
                        delete this._data[id];
                    }
                }
                this._persist();
            }
        }
        _persist() {
            try {
                this._ignoreChangeEvent = true;
                const raw = JSON.stringify(this._data);
                this._storageService.store(PersistedMenuHideState_1._key, raw, 0 /* StorageScope.PROFILE */, 0 /* StorageTarget.USER */);
            }
            finally {
                this._ignoreChangeEvent = false;
            }
        }
    };
    PersistedMenuHideState = PersistedMenuHideState_1 = __decorate([
        __param(0, storage_1.IStorageService)
    ], PersistedMenuHideState);
    class MenuInfoSnapshot {
        constructor(_id, _collectContextKeysForSubmenus) {
            this._id = _id;
            this._collectContextKeysForSubmenus = _collectContextKeysForSubmenus;
            this._menuGroups = [];
            this._allMenuIds = new Set();
            this._structureContextKeys = new Set();
            this._preconditionContextKeys = new Set();
            this._toggledContextKeys = new Set();
            this.refresh();
        }
        get allMenuIds() {
            return this._allMenuIds;
        }
        get structureContextKeys() {
            return this._structureContextKeys;
        }
        get preconditionContextKeys() {
            return this._preconditionContextKeys;
        }
        get toggledContextKeys() {
            return this._toggledContextKeys;
        }
        refresh() {
            // reset
            this._menuGroups.length = 0;
            this._allMenuIds.clear();
            this._structureContextKeys.clear();
            this._preconditionContextKeys.clear();
            this._toggledContextKeys.clear();
            const menuItems = this._sort(actions_1.MenuRegistry.getMenuItems(this._id));
            let group;
            for (const item of menuItems) {
                // group by groupId
                const groupName = item.group || '';
                if (!group || group[0] !== groupName) {
                    group = [groupName, []];
                    this._menuGroups.push(group);
                }
                group[1].push(item);
                // keep keys and submenu ids for eventing
                this._collectContextKeysAndSubmenuIds(item);
            }
            this._allMenuIds.add(this._id);
        }
        _sort(menuItems) {
            // no sorting needed in snapshot
            return menuItems;
        }
        _collectContextKeysAndSubmenuIds(item) {
            MenuInfoSnapshot._fillInKbExprKeys(item.when, this._structureContextKeys);
            if ((0, actions_1.isIMenuItem)(item)) {
                // keep precondition keys for event if applicable
                if (item.command.precondition) {
                    MenuInfoSnapshot._fillInKbExprKeys(item.command.precondition, this._preconditionContextKeys);
                }
                // keep toggled keys for event if applicable
                if (item.command.toggled) {
                    const toggledExpression = item.command.toggled.condition || item.command.toggled;
                    MenuInfoSnapshot._fillInKbExprKeys(toggledExpression, this._toggledContextKeys);
                }
            }
            else if (this._collectContextKeysForSubmenus) {
                // recursively collect context keys from submenus so that this
                // menu fires events when context key changes affect submenus
                actions_1.MenuRegistry.getMenuItems(item.submenu).forEach(this._collectContextKeysAndSubmenuIds, this);
                this._allMenuIds.add(item.submenu);
            }
        }
        static _fillInKbExprKeys(exp, set) {
            if (exp) {
                for (const key of exp.keys()) {
                    set.add(key);
                }
            }
        }
    }
    let MenuInfo = MenuInfo_1 = class MenuInfo extends MenuInfoSnapshot {
        constructor(_id, _hiddenStates, _collectContextKeysForSubmenus, _commandService, _keybindingService, _contextKeyService) {
            super(_id, _collectContextKeysForSubmenus);
            this._hiddenStates = _hiddenStates;
            this._commandService = _commandService;
            this._keybindingService = _keybindingService;
            this._contextKeyService = _contextKeyService;
            this.refresh();
        }
        createActionGroups(options) {
            const result = [];
            for (const group of this._menuGroups) {
                const [id, items] = group;
                let activeActions;
                for (const item of items) {
                    if (this._contextKeyService.contextMatchesRules(item.when)) {
                        const isMenuItem = (0, actions_1.isIMenuItem)(item);
                        if (isMenuItem) {
                            this._hiddenStates.setDefaultState(this._id, item.command.id, !!item.isHiddenByDefault);
                        }
                        const menuHide = createMenuHide(this._id, isMenuItem ? item.command : item, this._hiddenStates);
                        if (isMenuItem) {
                            // MenuItemAction
                            const menuKeybinding = createConfigureKeybindingAction(this._commandService, this._keybindingService, item.command.id, item.when);
                            (activeActions ??= []).push(new actions_1.MenuItemAction(item.command, item.alt, options, menuHide, menuKeybinding, this._contextKeyService, this._commandService));
                        }
                        else {
                            // SubmenuItemAction
                            const groups = new MenuInfo_1(item.submenu, this._hiddenStates, this._collectContextKeysForSubmenus, this._commandService, this._keybindingService, this._contextKeyService).createActionGroups(options);
                            const submenuActions = actions_2.Separator.join(...groups.map(g => g[1]));
                            if (submenuActions.length > 0) {
                                (activeActions ??= []).push(new actions_1.SubmenuItemAction(item, menuHide, submenuActions));
                            }
                        }
                    }
                }
                if (activeActions && activeActions.length > 0) {
                    result.push([id, activeActions]);
                }
            }
            return result;
        }
        _sort(menuItems) {
            return menuItems.sort(MenuInfo_1._compareMenuItems);
        }
        static _compareMenuItems(a, b) {
            const aGroup = a.group;
            const bGroup = b.group;
            if (aGroup !== bGroup) {
                // Falsy groups come last
                if (!aGroup) {
                    return 1;
                }
                else if (!bGroup) {
                    return -1;
                }
                // 'navigation' group comes first
                if (aGroup === 'navigation') {
                    return -1;
                }
                else if (bGroup === 'navigation') {
                    return 1;
                }
                // lexical sort for groups
                const value = aGroup.localeCompare(bGroup);
                if (value !== 0) {
                    return value;
                }
            }
            // sort on priority - default is 0
            const aPrio = a.order || 0;
            const bPrio = b.order || 0;
            if (aPrio < bPrio) {
                return -1;
            }
            else if (aPrio > bPrio) {
                return 1;
            }
            // sort on titles
            return MenuInfo_1._compareTitles((0, actions_1.isIMenuItem)(a) ? a.command.title : a.title, (0, actions_1.isIMenuItem)(b) ? b.command.title : b.title);
        }
        static _compareTitles(a, b) {
            const aStr = typeof a === 'string' ? a : a.original;
            const bStr = typeof b === 'string' ? b : b.original;
            return aStr.localeCompare(bStr);
        }
    };
    MenuInfo = MenuInfo_1 = __decorate([
        __param(3, commands_1.ICommandService),
        __param(4, keybinding_1.IKeybindingService),
        __param(5, contextkey_1.IContextKeyService)
    ], MenuInfo);
    let MenuImpl = class MenuImpl {
        constructor(id, hiddenStates, options, commandService, keybindingService, contextKeyService) {
            this._disposables = new lifecycle_1.DisposableStore();
            this._menuInfo = new MenuInfo(id, hiddenStates, options.emitEventsForSubmenuChanges, commandService, keybindingService, contextKeyService);
            // Rebuild this menu whenever the menu registry reports an event for this MenuId.
            // This usually happen while code and extensions are loaded and affects the over
            // structure of the menu
            const rebuildMenuSoon = new async_1.RunOnceScheduler(() => {
                this._menuInfo.refresh();
                this._onDidChange.fire({ menu: this, isStructuralChange: true, isEnablementChange: true, isToggleChange: true });
            }, options.eventDebounceDelay);
            this._disposables.add(rebuildMenuSoon);
            this._disposables.add(actions_1.MenuRegistry.onDidChangeMenu(e => {
                for (const id of this._menuInfo.allMenuIds) {
                    if (e.has(id)) {
                        rebuildMenuSoon.schedule();
                        break;
                    }
                }
            }));
            // When context keys or storage state changes we need to check if the menu also has changed. However,
            // we only do that when someone listens on this menu because (1) these events are
            // firing often and (2) menu are often leaked
            const lazyListener = this._disposables.add(new lifecycle_1.DisposableStore());
            const merge = (events) => {
                let isStructuralChange = false;
                let isEnablementChange = false;
                let isToggleChange = false;
                for (const item of events) {
                    isStructuralChange = isStructuralChange || item.isStructuralChange;
                    isEnablementChange = isEnablementChange || item.isEnablementChange;
                    isToggleChange = isToggleChange || item.isToggleChange;
                    if (isStructuralChange && isEnablementChange && isToggleChange) {
                        // everything is TRUE, no need to continue iterating
                        break;
                    }
                }
                return { menu: this, isStructuralChange, isEnablementChange, isToggleChange };
            };
            const startLazyListener = () => {
                lazyListener.add(contextKeyService.onDidChangeContext(e => {
                    const isStructuralChange = e.affectsSome(this._menuInfo.structureContextKeys);
                    const isEnablementChange = e.affectsSome(this._menuInfo.preconditionContextKeys);
                    const isToggleChange = e.affectsSome(this._menuInfo.toggledContextKeys);
                    if (isStructuralChange || isEnablementChange || isToggleChange) {
                        this._onDidChange.fire({ menu: this, isStructuralChange, isEnablementChange, isToggleChange });
                    }
                }));
                lazyListener.add(hiddenStates.onDidChange(e => {
                    this._onDidChange.fire({ menu: this, isStructuralChange: true, isEnablementChange: false, isToggleChange: false });
                }));
            };
            this._onDidChange = new event_1.DebounceEmitter({
                // start/stop context key listener
                onWillAddFirstListener: startLazyListener,
                onDidRemoveLastListener: lazyListener.clear.bind(lazyListener),
                delay: options.eventDebounceDelay,
                merge
            });
            this.onDidChange = this._onDidChange.event;
        }
        getActions(options) {
            return this._menuInfo.createActionGroups(options);
        }
        dispose() {
            this._disposables.dispose();
            this._onDidChange.dispose();
        }
    };
    MenuImpl = __decorate([
        __param(3, commands_1.ICommandService),
        __param(4, keybinding_1.IKeybindingService),
        __param(5, contextkey_1.IContextKeyService)
    ], MenuImpl);
    function createMenuHide(menu, command, states) {
        const id = (0, actions_1.isISubmenuItem)(command) ? command.submenu.id : command.id;
        const title = typeof command.title === 'string' ? command.title : command.title.value;
        const hide = (0, actions_2.toAction)({
            id: `hide/${menu.id}/${id}`,
            label: (0, nls_1.localize)(1490, 'Hide \'{0}\'', title),
            run() { states.updateHidden(menu, id, true); }
        });
        const toggle = (0, actions_2.toAction)({
            id: `toggle/${menu.id}/${id}`,
            label: title,
            get checked() { return !states.isHidden(menu, id); },
            run() { states.updateHidden(menu, id, !!this.checked); }
        });
        return {
            hide,
            toggle,
            get isHidden() { return !toggle.checked; },
        };
    }
    function createConfigureKeybindingAction(commandService, keybindingService, commandId, when = undefined, enabled = true) {
        return (0, actions_2.toAction)({
            id: `configureKeybinding/${commandId}`,
            label: (0, nls_1.localize)(1491, "Configure Keybinding"),
            enabled,
            run() {
                // Only set the when clause when there is no keybinding
                // It is possible that the action and the keybinding have different when clauses
                const hasKeybinding = !!keybindingService.lookupKeybinding(commandId); // This may only be called inside the `run()` method as it can be expensive on startup. #210529
                const whenValue = !hasKeybinding && when ? when.serialize() : undefined;
                commandService.executeCommand('workbench.action.openGlobalKeybindings', `@command:${commandId}` + (whenValue ? ` +when:${whenValue}` : ''));
            }
        });
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[63/*vs/platform/telemetry/common/telemetry*/], __M([1/*require*/,0/*exports*/,7/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ITelemetryService = void 0;
    exports.ITelemetryService = (0, instantiation_1.createDecorator)('telemetryService');
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[15/*vs/editor/browser/editorExtensions*/], __M([1/*require*/,0/*exports*/,3/*vs/nls*/,22/*vs/base/common/uri*/,34/*vs/editor/browser/services/codeEditorService*/,9/*vs/editor/common/core/position*/,51/*vs/editor/common/services/model*/,78/*vs/editor/common/services/resolverService*/,29/*vs/platform/actions/common/actions*/,24/*vs/platform/commands/common/commands*/,12/*vs/platform/contextkey/common/contextkey*/,7/*vs/platform/instantiation/common/instantiation*/,121/*vs/platform/keybinding/common/keybindingsRegistry*/,38/*vs/platform/registry/common/platform*/,63/*vs/platform/telemetry/common/telemetry*/,19/*vs/base/common/types*/,62/*vs/platform/log/common/log*/,5/*vs/base/browser/dom*/]), function (require, exports, nls, uri_1, codeEditorService_1, position_1, model_1, resolverService_1, actions_1, commands_1, contextkey_1, instantiation_1, keybindingsRegistry_1, platform_1, telemetry_1, types_1, log_1, dom_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SelectAllCommand = exports.RedoCommand = exports.UndoCommand = exports.EditorExtensionsRegistry = exports.EditorAction2 = exports.MultiEditorAction = exports.EditorAction = exports.EditorCommand = exports.ProxyCommand = exports.MultiCommand = exports.Command = void 0;
    exports.registerModelAndPositionCommand = registerModelAndPositionCommand;
    exports.registerEditorCommand = registerEditorCommand;
    exports.registerEditorAction = registerEditorAction;
    exports.registerMultiEditorAction = registerMultiEditorAction;
    exports.registerInstantiatedEditorAction = registerInstantiatedEditorAction;
    exports.registerEditorContribution = registerEditorContribution;
    class Command {
        constructor(opts) {
            this.id = opts.id;
            this.precondition = opts.precondition;
            this._kbOpts = opts.kbOpts;
            this._menuOpts = opts.menuOpts;
            this.metadata = opts.metadata;
        }
        register() {
            if (Array.isArray(this._menuOpts)) {
                this._menuOpts.forEach(this._registerMenuItem, this);
            }
            else if (this._menuOpts) {
                this._registerMenuItem(this._menuOpts);
            }
            if (this._kbOpts) {
                const kbOptsArr = Array.isArray(this._kbOpts) ? this._kbOpts : [this._kbOpts];
                for (const kbOpts of kbOptsArr) {
                    let kbWhen = kbOpts.kbExpr;
                    if (this.precondition) {
                        if (kbWhen) {
                            kbWhen = contextkey_1.ContextKeyExpr.and(kbWhen, this.precondition);
                        }
                        else {
                            kbWhen = this.precondition;
                        }
                    }
                    const desc = {
                        id: this.id,
                        weight: kbOpts.weight,
                        args: kbOpts.args,
                        when: kbWhen,
                        primary: kbOpts.primary,
                        secondary: kbOpts.secondary,
                        win: kbOpts.win,
                        linux: kbOpts.linux,
                        mac: kbOpts.mac,
                    };
                    keybindingsRegistry_1.KeybindingsRegistry.registerKeybindingRule(desc);
                }
            }
            commands_1.CommandsRegistry.registerCommand({
                id: this.id,
                handler: (accessor, args) => this.runCommand(accessor, args),
                metadata: this.metadata
            });
        }
        _registerMenuItem(item) {
            actions_1.MenuRegistry.appendMenuItem(item.menuId, {
                group: item.group,
                command: {
                    id: this.id,
                    title: item.title,
                    icon: item.icon,
                    precondition: this.precondition
                },
                when: item.when,
                order: item.order
            });
        }
    }
    exports.Command = Command;
    class MultiCommand extends Command {
        constructor() {
            super(...arguments);
            this._implementations = [];
        }
        /**
         * A higher priority gets to be looked at first
         */
        addImplementation(priority, name, implementation, when) {
            this._implementations.push({ priority, name, implementation, when });
            this._implementations.sort((a, b) => b.priority - a.priority);
            return {
                dispose: () => {
                    for (let i = 0; i < this._implementations.length; i++) {
                        if (this._implementations[i].implementation === implementation) {
                            this._implementations.splice(i, 1);
                            return;
                        }
                    }
                }
            };
        }
        runCommand(accessor, args) {
            const logService = accessor.get(log_1.ILogService);
            const contextKeyService = accessor.get(contextkey_1.IContextKeyService);
            logService.trace(`Executing Command '${this.id}' which has ${this._implementations.length} bound.`);
            for (const impl of this._implementations) {
                if (impl.when) {
                    const context = contextKeyService.getContext((0, dom_1.getActiveElement)());
                    const value = impl.when.evaluate(context);
                    if (!value) {
                        continue;
                    }
                }
                const result = impl.implementation(accessor, args);
                if (result) {
                    logService.trace(`Command '${this.id}' was handled by '${impl.name}'.`);
                    if (typeof result === 'boolean') {
                        return;
                    }
                    return result;
                }
            }
            logService.trace(`The Command '${this.id}' was not handled by any implementation.`);
        }
    }
    exports.MultiCommand = MultiCommand;
    //#endregion
    /**
     * A command that delegates to another command's implementation.
     *
     * This lets different commands be registered but share the same implementation
     */
    class ProxyCommand extends Command {
        constructor(command, opts) {
            super(opts);
            this.command = command;
        }
        runCommand(accessor, args) {
            return this.command.runCommand(accessor, args);
        }
    }
    exports.ProxyCommand = ProxyCommand;
    class EditorCommand extends Command {
        /**
         * Create a command class that is bound to a certain editor contribution.
         */
        static bindToContribution(controllerGetter) {
            return class EditorControllerCommandImpl extends EditorCommand {
                constructor(opts) {
                    super(opts);
                    this._callback = opts.handler;
                }
                runEditorCommand(accessor, editor, args) {
                    const controller = controllerGetter(editor);
                    if (controller) {
                        this._callback(controller, args);
                    }
                }
            };
        }
        static runEditorCommand(accessor, args, precondition, runner) {
            const codeEditorService = accessor.get(codeEditorService_1.ICodeEditorService);
            // Find the editor with text focus or active
            const editor = codeEditorService.getFocusedCodeEditor() || codeEditorService.getActiveCodeEditor();
            if (!editor) {
                // well, at least we tried...
                return;
            }
            return editor.invokeWithinContext((editorAccessor) => {
                const kbService = editorAccessor.get(contextkey_1.IContextKeyService);
                if (!kbService.contextMatchesRules(precondition ?? undefined)) {
                    // precondition does not hold
                    return;
                }
                return runner(editorAccessor, editor, args);
            });
        }
        runCommand(accessor, args) {
            return EditorCommand.runEditorCommand(accessor, args, this.precondition, (accessor, editor, args) => this.runEditorCommand(accessor, editor, args));
        }
    }
    exports.EditorCommand = EditorCommand;
    class EditorAction extends EditorCommand {
        static convertOptions(opts) {
            let menuOpts;
            if (Array.isArray(opts.menuOpts)) {
                menuOpts = opts.menuOpts;
            }
            else if (opts.menuOpts) {
                menuOpts = [opts.menuOpts];
            }
            else {
                menuOpts = [];
            }
            function withDefaults(item) {
                if (!item.menuId) {
                    item.menuId = actions_1.MenuId.EditorContext;
                }
                if (!item.title) {
                    item.title = opts.label;
                }
                item.when = contextkey_1.ContextKeyExpr.and(opts.precondition, item.when);
                return item;
            }
            if (Array.isArray(opts.contextMenuOpts)) {
                menuOpts.push(...opts.contextMenuOpts.map(withDefaults));
            }
            else if (opts.contextMenuOpts) {
                menuOpts.push(withDefaults(opts.contextMenuOpts));
            }
            opts.menuOpts = menuOpts;
            return opts;
        }
        constructor(opts) {
            super(EditorAction.convertOptions(opts));
            this.label = opts.label;
            this.alias = opts.alias;
        }
        runEditorCommand(accessor, editor, args) {
            this.reportTelemetry(accessor, editor);
            return this.run(accessor, editor, args || {});
        }
        reportTelemetry(accessor, editor) {
            accessor.get(telemetry_1.ITelemetryService).publicLog2('editorActionInvoked', { name: this.label, id: this.id });
        }
    }
    exports.EditorAction = EditorAction;
    class MultiEditorAction extends EditorAction {
        constructor() {
            super(...arguments);
            this._implementations = [];
        }
        /**
         * A higher priority gets to be looked at first
         */
        addImplementation(priority, implementation) {
            this._implementations.push([priority, implementation]);
            this._implementations.sort((a, b) => b[0] - a[0]);
            return {
                dispose: () => {
                    for (let i = 0; i < this._implementations.length; i++) {
                        if (this._implementations[i][1] === implementation) {
                            this._implementations.splice(i, 1);
                            return;
                        }
                    }
                }
            };
        }
        run(accessor, editor, args) {
            for (const impl of this._implementations) {
                const result = impl[1](accessor, editor, args);
                if (result) {
                    if (typeof result === 'boolean') {
                        return;
                    }
                    return result;
                }
            }
        }
    }
    exports.MultiEditorAction = MultiEditorAction;
    //#endregion EditorAction
    //#region EditorAction2
    class EditorAction2 extends actions_1.Action2 {
        run(accessor, ...args) {
            // Find the editor with text focus or active
            const codeEditorService = accessor.get(codeEditorService_1.ICodeEditorService);
            const editor = codeEditorService.getFocusedCodeEditor() || codeEditorService.getActiveCodeEditor();
            if (!editor) {
                // well, at least we tried...
                return;
            }
            // precondition does hold
            return editor.invokeWithinContext((editorAccessor) => {
                const kbService = editorAccessor.get(contextkey_1.IContextKeyService);
                const logService = editorAccessor.get(log_1.ILogService);
                const enabled = kbService.contextMatchesRules(this.desc.precondition ?? undefined);
                if (!enabled) {
                    logService.debug(`[EditorAction2] NOT running command because its precondition is FALSE`, this.desc.id, this.desc.precondition?.serialize());
                    return;
                }
                return this.runEditorCommand(editorAccessor, editor, ...args);
            });
        }
    }
    exports.EditorAction2 = EditorAction2;
    //#endregion
    // --- Registration of commands and actions
    function registerModelAndPositionCommand(id, handler) {
        commands_1.CommandsRegistry.registerCommand(id, function (accessor, ...args) {
            const instaService = accessor.get(instantiation_1.IInstantiationService);
            const [resource, position] = args;
            (0, types_1.assertType)(uri_1.URI.isUri(resource));
            (0, types_1.assertType)(position_1.Position.isIPosition(position));
            const model = accessor.get(model_1.IModelService).getModel(resource);
            if (model) {
                const editorPosition = position_1.Position.lift(position);
                return instaService.invokeFunction(handler, model, editorPosition, ...args.slice(2));
            }
            return accessor.get(resolverService_1.ITextModelService).createModelReference(resource).then(reference => {
                return new Promise((resolve, reject) => {
                    try {
                        const result = instaService.invokeFunction(handler, reference.object.textEditorModel, position_1.Position.lift(position), args.slice(2));
                        resolve(result);
                    }
                    catch (err) {
                        reject(err);
                    }
                }).finally(() => {
                    reference.dispose();
                });
            });
        });
    }
    function registerEditorCommand(editorCommand) {
        EditorContributionRegistry.INSTANCE.registerEditorCommand(editorCommand);
        return editorCommand;
    }
    function registerEditorAction(ctor) {
        const action = new ctor();
        EditorContributionRegistry.INSTANCE.registerEditorAction(action);
        return action;
    }
    function registerMultiEditorAction(action) {
        EditorContributionRegistry.INSTANCE.registerEditorAction(action);
        return action;
    }
    function registerInstantiatedEditorAction(editorAction) {
        EditorContributionRegistry.INSTANCE.registerEditorAction(editorAction);
    }
    /**
     * Registers an editor contribution. Editor contributions have a lifecycle which is bound
     * to a specific code editor instance.
     */
    function registerEditorContribution(id, ctor, instantiation) {
        EditorContributionRegistry.INSTANCE.registerEditorContribution(id, ctor, instantiation);
    }
    var EditorExtensionsRegistry;
    (function (EditorExtensionsRegistry) {
        function getEditorCommand(commandId) {
            return EditorContributionRegistry.INSTANCE.getEditorCommand(commandId);
        }
        EditorExtensionsRegistry.getEditorCommand = getEditorCommand;
        function getEditorActions() {
            return EditorContributionRegistry.INSTANCE.getEditorActions();
        }
        EditorExtensionsRegistry.getEditorActions = getEditorActions;
        function getEditorContributions() {
            return EditorContributionRegistry.INSTANCE.getEditorContributions();
        }
        EditorExtensionsRegistry.getEditorContributions = getEditorContributions;
        function getSomeEditorContributions(ids) {
            return EditorContributionRegistry.INSTANCE.getEditorContributions().filter(c => ids.indexOf(c.id) >= 0);
        }
        EditorExtensionsRegistry.getSomeEditorContributions = getSomeEditorContributions;
        function getDiffEditorContributions() {
            return EditorContributionRegistry.INSTANCE.getDiffEditorContributions();
        }
        EditorExtensionsRegistry.getDiffEditorContributions = getDiffEditorContributions;
    })(EditorExtensionsRegistry || (exports.EditorExtensionsRegistry = EditorExtensionsRegistry = {}));
    // Editor extension points
    const Extensions = {
        EditorCommonContributions: 'editor.contributions'
    };
    class EditorContributionRegistry {
        static { this.INSTANCE = new EditorContributionRegistry(); }
        constructor() {
            this.editorContributions = [];
            this.diffEditorContributions = [];
            this.editorActions = [];
            this.editorCommands = Object.create(null);
        }
        registerEditorContribution(id, ctor, instantiation) {
            this.editorContributions.push({ id, ctor: ctor, instantiation });
        }
        getEditorContributions() {
            return this.editorContributions.slice(0);
        }
        getDiffEditorContributions() {
            return this.diffEditorContributions.slice(0);
        }
        registerEditorAction(action) {
            action.register();
            this.editorActions.push(action);
        }
        getEditorActions() {
            return this.editorActions;
        }
        registerEditorCommand(editorCommand) {
            editorCommand.register();
            this.editorCommands[editorCommand.id] = editorCommand;
        }
        getEditorCommand(commandId) {
            return (this.editorCommands[commandId] || null);
        }
    }
    platform_1.Registry.add(Extensions.EditorCommonContributions, EditorContributionRegistry.INSTANCE);
    function registerCommand(command) {
        command.register();
        return command;
    }
    exports.UndoCommand = registerCommand(new MultiCommand({
        id: 'undo',
        precondition: undefined,
        kbOpts: {
            weight: 0 /* KeybindingWeight.EditorCore */,
            primary: 2048 /* KeyMod.CtrlCmd */ | 56 /* KeyCode.KeyZ */
        },
        menuOpts: [{
                menuId: actions_1.MenuId.MenubarEditMenu,
                group: '1_do',
                title: nls.localize(62, "&&Undo"),
                order: 1
            }, {
                menuId: actions_1.MenuId.CommandPalette,
                group: '',
                title: nls.localize(63, "Undo"),
                order: 1
            }]
    }));
    registerCommand(new ProxyCommand(exports.UndoCommand, { id: 'default:undo', precondition: undefined }));
    exports.RedoCommand = registerCommand(new MultiCommand({
        id: 'redo',
        precondition: undefined,
        kbOpts: {
            weight: 0 /* KeybindingWeight.EditorCore */,
            primary: 2048 /* KeyMod.CtrlCmd */ | 55 /* KeyCode.KeyY */,
            secondary: [2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 56 /* KeyCode.KeyZ */],
            mac: { primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 56 /* KeyCode.KeyZ */ }
        },
        menuOpts: [{
                menuId: actions_1.MenuId.MenubarEditMenu,
                group: '1_do',
                title: nls.localize(64, "&&Redo"),
                order: 2
            }, {
                menuId: actions_1.MenuId.CommandPalette,
                group: '',
                title: nls.localize(65, "Redo"),
                order: 1
            }]
    }));
    registerCommand(new ProxyCommand(exports.RedoCommand, { id: 'default:redo', precondition: undefined }));
    exports.SelectAllCommand = registerCommand(new MultiCommand({
        id: 'editor.action.selectAll',
        precondition: undefined,
        kbOpts: {
            weight: 0 /* KeybindingWeight.EditorCore */,
            kbExpr: null,
            primary: 2048 /* KeyMod.CtrlCmd */ | 31 /* KeyCode.KeyA */
        },
        menuOpts: [{
                menuId: actions_1.MenuId.MenubarSelectionMenu,
                group: '1_basic',
                title: nls.localize(66, "&&Select All"),
                order: 1
            }, {
                menuId: actions_1.MenuId.CommandPalette,
                group: '',
                title: nls.localize(67, "Select All"),
                order: 1
            }]
    }));
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[214/*vs/editor/browser/coreCommands*/], __M([1/*require*/,0/*exports*/,3/*vs/nls*/,64/*vs/base/browser/browser*/,19/*vs/base/common/types*/,46/*vs/base/browser/ui/aria/aria*/,15/*vs/editor/browser/editorExtensions*/,34/*vs/editor/browser/services/codeEditorService*/,565/*vs/editor/common/cursor/cursorColumnSelection*/,76/*vs/editor/common/cursorCommon*/,234/*vs/editor/common/cursor/cursorDeleteOperations*/,235/*vs/editor/common/cursor/cursorMoveCommands*/,276/*vs/editor/common/cursor/cursorTypeOperations*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/,20/*vs/editor/common/editorContextKeys*/,12/*vs/platform/contextkey/common/contextkey*/,121/*vs/platform/keybinding/common/keybindingsRegistry*/,5/*vs/base/browser/dom*/,213/*vs/editor/common/cursor/cursorTypeEditOperations*/]), function (require, exports, nls, browser_1, types, aria_1, editorExtensions_1, codeEditorService_1, cursorColumnSelection_1, cursorCommon_1, cursorDeleteOperations_1, cursorMoveCommands_1, cursorTypeOperations_1, position_1, range_1, editorContextKeys_1, contextkey_1, keybindingsRegistry_1, dom_1, cursorTypeEditOperations_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CoreEditingCommands = exports.CoreNavigationCommands = exports.RevealLine_ = exports.EditorScroll_ = exports.CoreEditorCommand = void 0;
    const CORE_WEIGHT = 0 /* KeybindingWeight.EditorCore */;
    class CoreEditorCommand extends editorExtensions_1.EditorCommand {
        runEditorCommand(accessor, editor, args) {
            const viewModel = editor._getViewModel();
            if (!viewModel) {
                // the editor has no view => has no cursors
                return;
            }
            this.runCoreEditorCommand(viewModel, args || {});
        }
    }
    exports.CoreEditorCommand = CoreEditorCommand;
    var EditorScroll_;
    (function (EditorScroll_) {
        const isEditorScrollArgs = function (arg) {
            if (!types.isObject(arg)) {
                return false;
            }
            const scrollArg = arg;
            if (!types.isString(scrollArg.to)) {
                return false;
            }
            if (!types.isUndefined(scrollArg.by) && !types.isString(scrollArg.by)) {
                return false;
            }
            if (!types.isUndefined(scrollArg.value) && !types.isNumber(scrollArg.value)) {
                return false;
            }
            if (!types.isUndefined(scrollArg.revealCursor) && !types.isBoolean(scrollArg.revealCursor)) {
                return false;
            }
            return true;
        };
        EditorScroll_.metadata = {
            description: 'Scroll editor in the given direction',
            args: [
                {
                    name: 'Editor scroll argument object',
                    description: `Property-value pairs that can be passed through this argument:
					* 'to': A mandatory direction value.
						\`\`\`
						'up', 'down'
						\`\`\`
					* 'by': Unit to move. Default is computed based on 'to' value.
						\`\`\`
						'line', 'wrappedLine', 'page', 'halfPage', 'editor'
						\`\`\`
					* 'value': Number of units to move. Default is '1'.
					* 'revealCursor': If 'true' reveals the cursor if it is outside view port.
				`,
                    constraint: isEditorScrollArgs,
                    schema: {
                        'type': 'object',
                        'required': ['to'],
                        'properties': {
                            'to': {
                                'type': 'string',
                                'enum': ['up', 'down']
                            },
                            'by': {
                                'type': 'string',
                                'enum': ['line', 'wrappedLine', 'page', 'halfPage', 'editor']
                            },
                            'value': {
                                'type': 'number',
                                'default': 1
                            },
                            'revealCursor': {
                                'type': 'boolean',
                            }
                        }
                    }
                }
            ]
        };
        /**
         * Directions in the view for editor scroll command.
         */
        EditorScroll_.RawDirection = {
            Up: 'up',
            Right: 'right',
            Down: 'down',
            Left: 'left'
        };
        /**
         * Units for editor scroll 'by' argument
         */
        EditorScroll_.RawUnit = {
            Line: 'line',
            WrappedLine: 'wrappedLine',
            Page: 'page',
            HalfPage: 'halfPage',
            Editor: 'editor',
            Column: 'column'
        };
        function parse(args) {
            let direction;
            switch (args.to) {
                case EditorScroll_.RawDirection.Up:
                    direction = 1 /* Direction.Up */;
                    break;
                case EditorScroll_.RawDirection.Right:
                    direction = 2 /* Direction.Right */;
                    break;
                case EditorScroll_.RawDirection.Down:
                    direction = 3 /* Direction.Down */;
                    break;
                case EditorScroll_.RawDirection.Left:
                    direction = 4 /* Direction.Left */;
                    break;
                default:
                    // Illegal arguments
                    return null;
            }
            let unit;
            switch (args.by) {
                case EditorScroll_.RawUnit.Line:
                    unit = 1 /* Unit.Line */;
                    break;
                case EditorScroll_.RawUnit.WrappedLine:
                    unit = 2 /* Unit.WrappedLine */;
                    break;
                case EditorScroll_.RawUnit.Page:
                    unit = 3 /* Unit.Page */;
                    break;
                case EditorScroll_.RawUnit.HalfPage:
                    unit = 4 /* Unit.HalfPage */;
                    break;
                case EditorScroll_.RawUnit.Editor:
                    unit = 5 /* Unit.Editor */;
                    break;
                case EditorScroll_.RawUnit.Column:
                    unit = 6 /* Unit.Column */;
                    break;
                default:
                    unit = 2 /* Unit.WrappedLine */;
            }
            const value = Math.floor(args.value || 1);
            const revealCursor = !!args.revealCursor;
            return {
                direction: direction,
                unit: unit,
                value: value,
                revealCursor: revealCursor,
                select: (!!args.select)
            };
        }
        EditorScroll_.parse = parse;
    })(EditorScroll_ || (exports.EditorScroll_ = EditorScroll_ = {}));
    var RevealLine_;
    (function (RevealLine_) {
        const isRevealLineArgs = function (arg) {
            if (!types.isObject(arg)) {
                return false;
            }
            const reveaLineArg = arg;
            if (!types.isNumber(reveaLineArg.lineNumber) && !types.isString(reveaLineArg.lineNumber)) {
                return false;
            }
            if (!types.isUndefined(reveaLineArg.at) && !types.isString(reveaLineArg.at)) {
                return false;
            }
            return true;
        };
        RevealLine_.metadata = {
            description: 'Reveal the given line at the given logical position',
            args: [
                {
                    name: 'Reveal line argument object',
                    description: `Property-value pairs that can be passed through this argument:
					* 'lineNumber': A mandatory line number value.
					* 'at': Logical position at which line has to be revealed.
						\`\`\`
						'top', 'center', 'bottom'
						\`\`\`
				`,
                    constraint: isRevealLineArgs,
                    schema: {
                        'type': 'object',
                        'required': ['lineNumber'],
                        'properties': {
                            'lineNumber': {
                                'type': ['number', 'string'],
                            },
                            'at': {
                                'type': 'string',
                                'enum': ['top', 'center', 'bottom']
                            }
                        }
                    }
                }
            ]
        };
        /**
         * Values for reveal line 'at' argument
         */
        RevealLine_.RawAtArgument = {
            Top: 'top',
            Center: 'center',
            Bottom: 'bottom'
        };
    })(RevealLine_ || (exports.RevealLine_ = RevealLine_ = {}));
    class EditorOrNativeTextInputCommand {
        constructor(target) {
            // 1. handle case when focus is in editor.
            target.addImplementation(10000, 'code-editor', (accessor, args) => {
                // Only if editor text focus (i.e. not if editor has widget focus).
                const focusedEditor = accessor.get(codeEditorService_1.ICodeEditorService).getFocusedCodeEditor();
                if (focusedEditor && focusedEditor.hasTextFocus()) {
                    return this._runEditorCommand(accessor, focusedEditor, args);
                }
                return false;
            });
            // 2. handle case when focus is in some other `input` / `textarea`.
            target.addImplementation(1000, 'generic-dom-input-textarea', (accessor, args) => {
                // Only if focused on an element that allows for entering text
                const activeElement = (0, dom_1.getActiveElement)();
                if (activeElement && ['input', 'textarea'].indexOf(activeElement.tagName.toLowerCase()) >= 0) {
                    this.runDOMCommand(activeElement);
                    return true;
                }
                return false;
            });
            // 3. (default) handle case when focus is somewhere else.
            target.addImplementation(0, 'generic-dom', (accessor, args) => {
                // Redirecting to active editor
                const activeEditor = accessor.get(codeEditorService_1.ICodeEditorService).getActiveCodeEditor();
                if (activeEditor) {
                    activeEditor.focus();
                    return this._runEditorCommand(accessor, activeEditor, args);
                }
                return false;
            });
        }
        _runEditorCommand(accessor, editor, args) {
            const result = this.runEditorCommand(accessor, editor, args);
            if (result) {
                return result;
            }
            return true;
        }
    }
    var CoreNavigationCommands;
    (function (CoreNavigationCommands) {
        class BaseMoveToCommand extends CoreEditorCommand {
            constructor(opts) {
                super(opts);
                this._inSelectionMode = opts.inSelectionMode;
            }
            runCoreEditorCommand(viewModel, args) {
                if (!args.position) {
                    return;
                }
                viewModel.model.pushStackElement();
                const cursorStateChanged = viewModel.setCursorStates(args.source, 3 /* CursorChangeReason.Explicit */, [
                    cursorMoveCommands_1.CursorMoveCommands.moveTo(viewModel, viewModel.getPrimaryCursorState(), this._inSelectionMode, args.position, args.viewPosition)
                ]);
                if (cursorStateChanged && args.revealType !== 2 /* NavigationCommandRevealType.None */) {
                    viewModel.revealAllCursors(args.source, true, true);
                }
            }
        }
        CoreNavigationCommands.MoveTo = (0, editorExtensions_1.registerEditorCommand)(new BaseMoveToCommand({
            id: '_moveTo',
            inSelectionMode: false,
            precondition: undefined
        }));
        CoreNavigationCommands.MoveToSelect = (0, editorExtensions_1.registerEditorCommand)(new BaseMoveToCommand({
            id: '_moveToSelect',
            inSelectionMode: true,
            precondition: undefined
        }));
        class ColumnSelectCommand extends CoreEditorCommand {
            runCoreEditorCommand(viewModel, args) {
                viewModel.model.pushStackElement();
                const result = this._getColumnSelectResult(viewModel, viewModel.getPrimaryCursorState(), viewModel.getCursorColumnSelectData(), args);
                if (result === null) {
                    // invalid arguments
                    return;
                }
                viewModel.setCursorStates(args.source, 3 /* CursorChangeReason.Explicit */, result.viewStates.map((viewState) => cursorCommon_1.CursorState.fromViewState(viewState)));
                viewModel.setCursorColumnSelectData({
                    isReal: true,
                    fromViewLineNumber: result.fromLineNumber,
                    fromViewVisualColumn: result.fromVisualColumn,
                    toViewLineNumber: result.toLineNumber,
                    toViewVisualColumn: result.toVisualColumn
                });
                if (result.reversed) {
                    viewModel.revealTopMostCursor(args.source);
                }
                else {
                    viewModel.revealBottomMostCursor(args.source);
                }
            }
        }
        CoreNavigationCommands.ColumnSelect = (0, editorExtensions_1.registerEditorCommand)(new class extends ColumnSelectCommand {
            constructor() {
                super({
                    id: 'columnSelect',
                    precondition: undefined
                });
            }
            _getColumnSelectResult(viewModel, primary, prevColumnSelectData, args) {
                if (typeof args.position === 'undefined' || typeof args.viewPosition === 'undefined' || typeof args.mouseColumn === 'undefined') {
                    return null;
                }
                // validate `args`
                const validatedPosition = viewModel.model.validatePosition(args.position);
                const validatedViewPosition = viewModel.coordinatesConverter.validateViewPosition(new position_1.Position(args.viewPosition.lineNumber, args.viewPosition.column), validatedPosition);
                const fromViewLineNumber = args.doColumnSelect ? prevColumnSelectData.fromViewLineNumber : validatedViewPosition.lineNumber;
                const fromViewVisualColumn = args.doColumnSelect ? prevColumnSelectData.fromViewVisualColumn : args.mouseColumn - 1;
                return cursorColumnSelection_1.ColumnSelection.columnSelect(viewModel.cursorConfig, viewModel, fromViewLineNumber, fromViewVisualColumn, validatedViewPosition.lineNumber, args.mouseColumn - 1);
            }
        });
        CoreNavigationCommands.CursorColumnSelectLeft = (0, editorExtensions_1.registerEditorCommand)(new class extends ColumnSelectCommand {
            constructor() {
                super({
                    id: 'cursorColumnSelectLeft',
                    precondition: undefined,
                    kbOpts: {
                        weight: CORE_WEIGHT,
                        kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                        primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 512 /* KeyMod.Alt */ | 15 /* KeyCode.LeftArrow */,
                        linux: { primary: 0 }
                    }
                });
            }
            _getColumnSelectResult(viewModel, primary, prevColumnSelectData, args) {
                return cursorColumnSelection_1.ColumnSelection.columnSelectLeft(viewModel.cursorConfig, viewModel, prevColumnSelectData);
            }
        });
        CoreNavigationCommands.CursorColumnSelectRight = (0, editorExtensions_1.registerEditorCommand)(new class extends ColumnSelectCommand {
            constructor() {
                super({
                    id: 'cursorColumnSelectRight',
                    precondition: undefined,
                    kbOpts: {
                        weight: CORE_WEIGHT,
                        kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                        primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 512 /* KeyMod.Alt */ | 17 /* KeyCode.RightArrow */,
                        linux: { primary: 0 }
                    }
                });
            }
            _getColumnSelectResult(viewModel, primary, prevColumnSelectData, args) {
                return cursorColumnSelection_1.ColumnSelection.columnSelectRight(viewModel.cursorConfig, viewModel, prevColumnSelectData);
            }
        });
        class ColumnSelectUpCommand extends ColumnSelectCommand {
            constructor(opts) {
                super(opts);
                this._isPaged = opts.isPaged;
            }
            _getColumnSelectResult(viewModel, primary, prevColumnSelectData, args) {
                return cursorColumnSelection_1.ColumnSelection.columnSelectUp(viewModel.cursorConfig, viewModel, prevColumnSelectData, this._isPaged);
            }
        }
        CoreNavigationCommands.CursorColumnSelectUp = (0, editorExtensions_1.registerEditorCommand)(new ColumnSelectUpCommand({
            isPaged: false,
            id: 'cursorColumnSelectUp',
            precondition: undefined,
            kbOpts: {
                weight: CORE_WEIGHT,
                kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 512 /* KeyMod.Alt */ | 16 /* KeyCode.UpArrow */,
                linux: { primary: 0 }
            }
        }));
        CoreNavigationCommands.CursorColumnSelectPageUp = (0, editorExtensions_1.registerEditorCommand)(new ColumnSelectUpCommand({
            isPaged: true,
            id: 'cursorColumnSelectPageUp',
            precondition: undefined,
            kbOpts: {
                weight: CORE_WEIGHT,
                kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 512 /* KeyMod.Alt */ | 11 /* KeyCode.PageUp */,
                linux: { primary: 0 }
            }
        }));
        class ColumnSelectDownCommand extends ColumnSelectCommand {
            constructor(opts) {
                super(opts);
                this._isPaged = opts.isPaged;
            }
            _getColumnSelectResult(viewModel, primary, prevColumnSelectData, args) {
                return cursorColumnSelection_1.ColumnSelection.columnSelectDown(viewModel.cursorConfig, viewModel, prevColumnSelectData, this._isPaged);
            }
        }
        CoreNavigationCommands.CursorColumnSelectDown = (0, editorExtensions_1.registerEditorCommand)(new ColumnSelectDownCommand({
            isPaged: false,
            id: 'cursorColumnSelectDown',
            precondition: undefined,
            kbOpts: {
                weight: CORE_WEIGHT,
                kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 512 /* KeyMod.Alt */ | 18 /* KeyCode.DownArrow */,
                linux: { primary: 0 }
            }
        }));
        CoreNavigationCommands.CursorColumnSelectPageDown = (0, editorExtensions_1.registerEditorCommand)(new ColumnSelectDownCommand({
            isPaged: true,
            id: 'cursorColumnSelectPageDown',
            precondition: undefined,
            kbOpts: {
                weight: CORE_WEIGHT,
                kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 512 /* KeyMod.Alt */ | 12 /* KeyCode.PageDown */,
                linux: { primary: 0 }
            }
        }));
        class CursorMoveImpl extends CoreEditorCommand {
            constructor() {
                super({
                    id: 'cursorMove',
                    precondition: undefined,
                    metadata: cursorMoveCommands_1.CursorMove.metadata
                });
            }
            runCoreEditorCommand(viewModel, args) {
                const parsed = cursorMoveCommands_1.CursorMove.parse(args);
                if (!parsed) {
                    // illegal arguments
                    return;
                }
                this._runCursorMove(viewModel, args.source, parsed);
            }
            _runCursorMove(viewModel, source, args) {
                viewModel.model.pushStackElement();
                viewModel.setCursorStates(source, 3 /* CursorChangeReason.Explicit */, CursorMoveImpl._move(viewModel, viewModel.getCursorStates(), args));
                viewModel.revealAllCursors(source, true);
            }
            static _move(viewModel, cursors, args) {
                const inSelectionMode = args.select;
                const value = args.value;
                switch (args.direction) {
                    case 0 /* CursorMove_.Direction.Left */:
                    case 1 /* CursorMove_.Direction.Right */:
                    case 2 /* CursorMove_.Direction.Up */:
                    case 3 /* CursorMove_.Direction.Down */:
                    case 4 /* CursorMove_.Direction.PrevBlankLine */:
                    case 5 /* CursorMove_.Direction.NextBlankLine */:
                    case 6 /* CursorMove_.Direction.WrappedLineStart */:
                    case 7 /* CursorMove_.Direction.WrappedLineFirstNonWhitespaceCharacter */:
                    case 8 /* CursorMove_.Direction.WrappedLineColumnCenter */:
                    case 9 /* CursorMove_.Direction.WrappedLineEnd */:
                    case 10 /* CursorMove_.Direction.WrappedLineLastNonWhitespaceCharacter */:
                        return cursorMoveCommands_1.CursorMoveCommands.simpleMove(viewModel, cursors, args.direction, inSelectionMode, value, args.unit);
                    case 11 /* CursorMove_.Direction.ViewPortTop */:
                    case 13 /* CursorMove_.Direction.ViewPortBottom */:
                    case 12 /* CursorMove_.Direction.ViewPortCenter */:
                    case 14 /* CursorMove_.Direction.ViewPortIfOutside */:
                        return cursorMoveCommands_1.CursorMoveCommands.viewportMove(viewModel, cursors, args.direction, inSelectionMode, value);
                    default:
                        return null;
                }
            }
        }
        CoreNavigationCommands.CursorMoveImpl = CursorMoveImpl;
        CoreNavigationCommands.CursorMove = (0, editorExtensions_1.registerEditorCommand)(new CursorMoveImpl());
        class CursorMoveBasedCommand extends CoreEditorCommand {
            constructor(opts) {
                super(opts);
                this._staticArgs = opts.args;
            }
            runCoreEditorCommand(viewModel, dynamicArgs) {
                let args = this._staticArgs;
                if (this._staticArgs.value === -1 /* Constants.PAGE_SIZE_MARKER */) {
                    // -1 is a marker for page size
                    args = {
                        direction: this._staticArgs.direction,
                        unit: this._staticArgs.unit,
                        select: this._staticArgs.select,
                        value: dynamicArgs.pageSize || viewModel.cursorConfig.pageSize
                    };
                }
                viewModel.model.pushStackElement();
                viewModel.setCursorStates(dynamicArgs.source, 3 /* CursorChangeReason.Explicit */, cursorMoveCommands_1.CursorMoveCommands.simpleMove(viewModel, viewModel.getCursorStates(), args.direction, args.select, args.value, args.unit));
                viewModel.revealAllCursors(dynamicArgs.source, true);
            }
        }
        CoreNavigationCommands.CursorLeft = (0, editorExtensions_1.registerEditorCommand)(new CursorMoveBasedCommand({
            args: {
                direction: 0 /* CursorMove_.Direction.Left */,
                unit: 0 /* CursorMove_.Unit.None */,
                select: false,
                value: 1
            },
            id: 'cursorLeft',
            precondition: undefined,
            kbOpts: {
                weight: CORE_WEIGHT,
                kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                primary: 15 /* KeyCode.LeftArrow */,
                mac: { primary: 15 /* KeyCode.LeftArrow */, secondary: [256 /* KeyMod.WinCtrl */ | 32 /* KeyCode.KeyB */] }
            }
        }));
        CoreNavigationCommands.CursorLeftSelect = (0, editorExtensions_1.registerEditorCommand)(new CursorMoveBasedCommand({
            args: {
                direction: 0 /* CursorMove_.Direction.Left */,
                unit: 0 /* CursorMove_.Unit.None */,
                select: true,
                value: 1
            },
            id: 'cursorLeftSelect',
            precondition: undefined,
            kbOpts: {
                weight: CORE_WEIGHT,
                kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                primary: 1024 /* KeyMod.Shift */ | 15 /* KeyCode.LeftArrow */
            }
        }));
        CoreNavigationCommands.CursorRight = (0, editorExtensions_1.registerEditorCommand)(new CursorMoveBasedCommand({
            args: {
                direction: 1 /* CursorMove_.Direction.Right */,
                unit: 0 /* CursorMove_.Unit.None */,
                select: false,
                value: 1
            },
            id: 'cursorRight',
            precondition: undefined,
            kbOpts: {
                weight: CORE_WEIGHT,
                kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                primary: 17 /* KeyCode.RightArrow */,
                mac: { primary: 17 /* KeyCode.RightArrow */, secondary: [256 /* KeyMod.WinCtrl */ | 36 /* KeyCode.KeyF */] }
            }
        }));
        CoreNavigationCommands.CursorRightSelect = (0, editorExtensions_1.registerEditorCommand)(new CursorMoveBasedCommand({
            args: {
                direction: 1 /* CursorMove_.Direction.Right */,
                unit: 0 /* CursorMove_.Unit.None */,
                select: true,
                value: 1
            },
            id: 'cursorRightSelect',
            precondition: undefined,
            kbOpts: {
                weight: CORE_WEIGHT,
                kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                primary: 1024 /* KeyMod.Shift */ | 17 /* KeyCode.RightArrow */
            }
        }));
        CoreNavigationCommands.CursorUp = (0, editorExtensions_1.registerEditorCommand)(new CursorMoveBasedCommand({
            args: {
                direction: 2 /* CursorMove_.Direction.Up */,
                unit: 2 /* CursorMove_.Unit.WrappedLine */,
                select: false,
                value: 1
            },
            id: 'cursorUp',
            precondition: undefined,
            kbOpts: {
                weight: CORE_WEIGHT,
                kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                primary: 16 /* KeyCode.UpArrow */,
                mac: { primary: 16 /* KeyCode.UpArrow */, secondary: [256 /* KeyMod.WinCtrl */ | 46 /* KeyCode.KeyP */] }
            }
        }));
        CoreNavigationCommands.CursorUpSelect = (0, editorExtensions_1.registerEditorCommand)(new CursorMoveBasedCommand({
            args: {
                direction: 2 /* CursorMove_.Direction.Up */,
                unit: 2 /* CursorMove_.Unit.WrappedLine */,
                select: true,
                value: 1
            },
            id: 'cursorUpSelect',
            precondition: undefined,
            kbOpts: {
                weight: CORE_WEIGHT,
                kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                primary: 1024 /* KeyMod.Shift */ | 16 /* KeyCode.UpArrow */,
                secondary: [2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 16 /* KeyCode.UpArrow */],
                mac: { primary: 1024 /* KeyMod.Shift */ | 16 /* KeyCode.UpArrow */ },
                linux: { primary: 1024 /* KeyMod.Shift */ | 16 /* KeyCode.UpArrow */ }
            }
        }));
        CoreNavigationCommands.CursorPageUp = (0, editorExtensions_1.registerEditorCommand)(new CursorMoveBasedCommand({
            args: {
                direction: 2 /* CursorMove_.Direction.Up */,
                unit: 2 /* CursorMove_.Unit.WrappedLine */,
                select: false,
                value: -1 /* Constants.PAGE_SIZE_MARKER */
            },
            id: 'cursorPageUp',
            precondition: undefined,
            kbOpts: {
                weight: CORE_WEIGHT,
                kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                primary: 11 /* KeyCode.PageUp */
            }
        }));
        CoreNavigationCommands.CursorPageUpSelect = (0, editorExtensions_1.registerEditorCommand)(new CursorMoveBasedCommand({
            args: {
                direction: 2 /* CursorMove_.Direction.Up */,
                unit: 2 /* CursorMove_.Unit.WrappedLine */,
                select: true,
                value: -1 /* Constants.PAGE_SIZE_MARKER */
            },
            id: 'cursorPageUpSelect',
            precondition: undefined,
            kbOpts: {
                weight: CORE_WEIGHT,
                kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                primary: 1024 /* KeyMod.Shift */ | 11 /* KeyCode.PageUp */
            }
        }));
        CoreNavigationCommands.CursorDown = (0, editorExtensions_1.registerEditorCommand)(new CursorMoveBasedCommand({
            args: {
                direction: 3 /* CursorMove_.Direction.Down */,
                unit: 2 /* CursorMove_.Unit.WrappedLine */,
                select: false,
                value: 1
            },
            id: 'cursorDown',
            precondition: undefined,
            kbOpts: {
                weight: CORE_WEIGHT,
                kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                primary: 18 /* KeyCode.DownArrow */,
                mac: { primary: 18 /* KeyCode.DownArrow */, secondary: [256 /* KeyMod.WinCtrl */ | 44 /* KeyCode.KeyN */] }
            }
        }));
        CoreNavigationCommands.CursorDownSelect = (0, editorExtensions_1.registerEditorCommand)(new CursorMoveBasedCommand({
            args: {
                direction: 3 /* CursorMove_.Direction.Down */,
                unit: 2 /* CursorMove_.Unit.WrappedLine */,
                select: true,
                value: 1
            },
            id: 'cursorDownSelect',
            precondition: undefined,
            kbOpts: {
                weight: CORE_WEIGHT,
                kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                primary: 1024 /* KeyMod.Shift */ | 18 /* KeyCode.DownArrow */,
                secondary: [2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 18 /* KeyCode.DownArrow */],
                mac: { primary: 1024 /* KeyMod.Shift */ | 18 /* KeyCode.DownArrow */ },
                linux: { primary: 1024 /* KeyMod.Shift */ | 18 /* KeyCode.DownArrow */ }
            }
        }));
        CoreNavigationCommands.CursorPageDown = (0, editorExtensions_1.registerEditorCommand)(new CursorMoveBasedCommand({
            args: {
                direction: 3 /* CursorMove_.Direction.Down */,
                unit: 2 /* CursorMove_.Unit.WrappedLine */,
                select: false,
                value: -1 /* Constants.PAGE_SIZE_MARKER */
            },
            id: 'cursorPageDown',
            precondition: undefined,
            kbOpts: {
                weight: CORE_WEIGHT,
                kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                primary: 12 /* KeyCode.PageDown */
            }
        }));
        CoreNavigationCommands.CursorPageDownSelect = (0, editorExtensions_1.registerEditorCommand)(new CursorMoveBasedCommand({
            args: {
                direction: 3 /* CursorMove_.Direction.Down */,
                unit: 2 /* CursorMove_.Unit.WrappedLine */,
                select: true,
                value: -1 /* Constants.PAGE_SIZE_MARKER */
            },
            id: 'cursorPageDownSelect',
            precondition: undefined,
            kbOpts: {
                weight: CORE_WEIGHT,
                kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                primary: 1024 /* KeyMod.Shift */ | 12 /* KeyCode.PageDown */
            }
        }));
        CoreNavigationCommands.CreateCursor = (0, editorExtensions_1.registerEditorCommand)(new class extends CoreEditorCommand {
            constructor() {
                super({
                    id: 'createCursor',
                    precondition: undefined
                });
            }
            runCoreEditorCommand(viewModel, args) {
                if (!args.position) {
                    return;
                }
                let newState;
                if (args.wholeLine) {
                    newState = cursorMoveCommands_1.CursorMoveCommands.line(viewModel, viewModel.getPrimaryCursorState(), false, args.position, args.viewPosition);
                }
                else {
                    newState = cursorMoveCommands_1.CursorMoveCommands.moveTo(viewModel, viewModel.getPrimaryCursorState(), false, args.position, args.viewPosition);
                }
                const states = viewModel.getCursorStates();
                // Check if we should remove a cursor (sort of like a toggle)
                if (states.length > 1) {
                    const newModelPosition = (newState.modelState ? newState.modelState.position : null);
                    const newViewPosition = (newState.viewState ? newState.viewState.position : null);
                    for (let i = 0, len = states.length; i < len; i++) {
                        const state = states[i];
                        if (newModelPosition && !state.modelState.selection.containsPosition(newModelPosition)) {
                            continue;
                        }
                        if (newViewPosition && !state.viewState.selection.containsPosition(newViewPosition)) {
                            continue;
                        }
                        // => Remove the cursor
                        states.splice(i, 1);
                        viewModel.model.pushStackElement();
                        viewModel.setCursorStates(args.source, 3 /* CursorChangeReason.Explicit */, states);
                        return;
                    }
                }
                // => Add the new cursor
                states.push(newState);
                viewModel.model.pushStackElement();
                viewModel.setCursorStates(args.source, 3 /* CursorChangeReason.Explicit */, states);
            }
        });
        CoreNavigationCommands.LastCursorMoveToSelect = (0, editorExtensions_1.registerEditorCommand)(new class extends CoreEditorCommand {
            constructor() {
                super({
                    id: '_lastCursorMoveToSelect',
                    precondition: undefined
                });
            }
            runCoreEditorCommand(viewModel, args) {
                if (!args.position) {
                    return;
                }
                const lastAddedCursorIndex = viewModel.getLastAddedCursorIndex();
                const states = viewModel.getCursorStates();
                const newStates = states.slice(0);
                newStates[lastAddedCursorIndex] = cursorMoveCommands_1.CursorMoveCommands.moveTo(viewModel, states[lastAddedCursorIndex], true, args.position, args.viewPosition);
                viewModel.model.pushStackElement();
                viewModel.setCursorStates(args.source, 3 /* CursorChangeReason.Explicit */, newStates);
            }
        });
        class HomeCommand extends CoreEditorCommand {
            constructor(opts) {
                super(opts);
                this._inSelectionMode = opts.inSelectionMode;
            }
            runCoreEditorCommand(viewModel, args) {
                viewModel.model.pushStackElement();
                viewModel.setCursorStates(args.source, 3 /* CursorChangeReason.Explicit */, cursorMoveCommands_1.CursorMoveCommands.moveToBeginningOfLine(viewModel, viewModel.getCursorStates(), this._inSelectionMode));
                viewModel.revealAllCursors(args.source, true);
            }
        }
        CoreNavigationCommands.CursorHome = (0, editorExtensions_1.registerEditorCommand)(new HomeCommand({
            inSelectionMode: false,
            id: 'cursorHome',
            precondition: undefined,
            kbOpts: {
                weight: CORE_WEIGHT,
                kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                primary: 14 /* KeyCode.Home */,
                mac: { primary: 14 /* KeyCode.Home */, secondary: [2048 /* KeyMod.CtrlCmd */ | 15 /* KeyCode.LeftArrow */] }
            }
        }));
        CoreNavigationCommands.CursorHomeSelect = (0, editorExtensions_1.registerEditorCommand)(new HomeCommand({
            inSelectionMode: true,
            id: 'cursorHomeSelect',
            precondition: undefined,
            kbOpts: {
                weight: CORE_WEIGHT,
                kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                primary: 1024 /* KeyMod.Shift */ | 14 /* KeyCode.Home */,
                mac: { primary: 1024 /* KeyMod.Shift */ | 14 /* KeyCode.Home */, secondary: [2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 15 /* KeyCode.LeftArrow */] }
            }
        }));
        class LineStartCommand extends CoreEditorCommand {
            constructor(opts) {
                super(opts);
                this._inSelectionMode = opts.inSelectionMode;
            }
            runCoreEditorCommand(viewModel, args) {
                viewModel.model.pushStackElement();
                viewModel.setCursorStates(args.source, 3 /* CursorChangeReason.Explicit */, this._exec(viewModel.getCursorStates()));
                viewModel.revealAllCursors(args.source, true);
            }
            _exec(cursors) {
                const result = [];
                for (let i = 0, len = cursors.length; i < len; i++) {
                    const cursor = cursors[i];
                    const lineNumber = cursor.modelState.position.lineNumber;
                    result[i] = cursorCommon_1.CursorState.fromModelState(cursor.modelState.move(this._inSelectionMode, lineNumber, 1, 0));
                }
                return result;
            }
        }
        CoreNavigationCommands.CursorLineStart = (0, editorExtensions_1.registerEditorCommand)(new LineStartCommand({
            inSelectionMode: false,
            id: 'cursorLineStart',
            precondition: undefined,
            kbOpts: {
                weight: CORE_WEIGHT,
                kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                primary: 0,
                mac: { primary: 256 /* KeyMod.WinCtrl */ | 31 /* KeyCode.KeyA */ }
            }
        }));
        CoreNavigationCommands.CursorLineStartSelect = (0, editorExtensions_1.registerEditorCommand)(new LineStartCommand({
            inSelectionMode: true,
            id: 'cursorLineStartSelect',
            precondition: undefined,
            kbOpts: {
                weight: CORE_WEIGHT,
                kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                primary: 0,
                mac: { primary: 256 /* KeyMod.WinCtrl */ | 1024 /* KeyMod.Shift */ | 31 /* KeyCode.KeyA */ }
            }
        }));
        class EndCommand extends CoreEditorCommand {
            constructor(opts) {
                super(opts);
                this._inSelectionMode = opts.inSelectionMode;
            }
            runCoreEditorCommand(viewModel, args) {
                viewModel.model.pushStackElement();
                viewModel.setCursorStates(args.source, 3 /* CursorChangeReason.Explicit */, cursorMoveCommands_1.CursorMoveCommands.moveToEndOfLine(viewModel, viewModel.getCursorStates(), this._inSelectionMode, args.sticky || false));
                viewModel.revealAllCursors(args.source, true);
            }
        }
        CoreNavigationCommands.CursorEnd = (0, editorExtensions_1.registerEditorCommand)(new EndCommand({
            inSelectionMode: false,
            id: 'cursorEnd',
            precondition: undefined,
            kbOpts: {
                args: { sticky: false },
                weight: CORE_WEIGHT,
                kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                primary: 13 /* KeyCode.End */,
                mac: { primary: 13 /* KeyCode.End */, secondary: [2048 /* KeyMod.CtrlCmd */ | 17 /* KeyCode.RightArrow */] }
            },
            metadata: {
                description: `Go to End`,
                args: [{
                        name: 'args',
                        schema: {
                            type: 'object',
                            properties: {
                                'sticky': {
                                    description: nls.localize(59, "Stick to the end even when going to longer lines"),
                                    type: 'boolean',
                                    default: false
                                }
                            }
                        }
                    }]
            }
        }));
        CoreNavigationCommands.CursorEndSelect = (0, editorExtensions_1.registerEditorCommand)(new EndCommand({
            inSelectionMode: true,
            id: 'cursorEndSelect',
            precondition: undefined,
            kbOpts: {
                args: { sticky: false },
                weight: CORE_WEIGHT,
                kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                primary: 1024 /* KeyMod.Shift */ | 13 /* KeyCode.End */,
                mac: { primary: 1024 /* KeyMod.Shift */ | 13 /* KeyCode.End */, secondary: [2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 17 /* KeyCode.RightArrow */] }
            },
            metadata: {
                description: `Select to End`,
                args: [{
                        name: 'args',
                        schema: {
                            type: 'object',
                            properties: {
                                'sticky': {
                                    description: nls.localize(60, "Stick to the end even when going to longer lines"),
                                    type: 'boolean',
                                    default: false
                                }
                            }
                        }
                    }]
            }
        }));
        class LineEndCommand extends CoreEditorCommand {
            constructor(opts) {
                super(opts);
                this._inSelectionMode = opts.inSelectionMode;
            }
            runCoreEditorCommand(viewModel, args) {
                viewModel.model.pushStackElement();
                viewModel.setCursorStates(args.source, 3 /* CursorChangeReason.Explicit */, this._exec(viewModel, viewModel.getCursorStates()));
                viewModel.revealAllCursors(args.source, true);
            }
            _exec(viewModel, cursors) {
                const result = [];
                for (let i = 0, len = cursors.length; i < len; i++) {
                    const cursor = cursors[i];
                    const lineNumber = cursor.modelState.position.lineNumber;
                    const maxColumn = viewModel.model.getLineMaxColumn(lineNumber);
                    result[i] = cursorCommon_1.CursorState.fromModelState(cursor.modelState.move(this._inSelectionMode, lineNumber, maxColumn, 0));
                }
                return result;
            }
        }
        CoreNavigationCommands.CursorLineEnd = (0, editorExtensions_1.registerEditorCommand)(new LineEndCommand({
            inSelectionMode: false,
            id: 'cursorLineEnd',
            precondition: undefined,
            kbOpts: {
                weight: CORE_WEIGHT,
                kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                primary: 0,
                mac: { primary: 256 /* KeyMod.WinCtrl */ | 35 /* KeyCode.KeyE */ }
            }
        }));
        CoreNavigationCommands.CursorLineEndSelect = (0, editorExtensions_1.registerEditorCommand)(new LineEndCommand({
            inSelectionMode: true,
            id: 'cursorLineEndSelect',
            precondition: undefined,
            kbOpts: {
                weight: CORE_WEIGHT,
                kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                primary: 0,
                mac: { primary: 256 /* KeyMod.WinCtrl */ | 1024 /* KeyMod.Shift */ | 35 /* KeyCode.KeyE */ }
            }
        }));
        class TopCommand extends CoreEditorCommand {
            constructor(opts) {
                super(opts);
                this._inSelectionMode = opts.inSelectionMode;
            }
            runCoreEditorCommand(viewModel, args) {
                viewModel.model.pushStackElement();
                viewModel.setCursorStates(args.source, 3 /* CursorChangeReason.Explicit */, cursorMoveCommands_1.CursorMoveCommands.moveToBeginningOfBuffer(viewModel, viewModel.getCursorStates(), this._inSelectionMode));
                viewModel.revealAllCursors(args.source, true);
            }
        }
        CoreNavigationCommands.CursorTop = (0, editorExtensions_1.registerEditorCommand)(new TopCommand({
            inSelectionMode: false,
            id: 'cursorTop',
            precondition: undefined,
            kbOpts: {
                weight: CORE_WEIGHT,
                kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                primary: 2048 /* KeyMod.CtrlCmd */ | 14 /* KeyCode.Home */,
                mac: { primary: 2048 /* KeyMod.CtrlCmd */ | 16 /* KeyCode.UpArrow */ }
            }
        }));
        CoreNavigationCommands.CursorTopSelect = (0, editorExtensions_1.registerEditorCommand)(new TopCommand({
            inSelectionMode: true,
            id: 'cursorTopSelect',
            precondition: undefined,
            kbOpts: {
                weight: CORE_WEIGHT,
                kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 14 /* KeyCode.Home */,
                mac: { primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 16 /* KeyCode.UpArrow */ }
            }
        }));
        class BottomCommand extends CoreEditorCommand {
            constructor(opts) {
                super(opts);
                this._inSelectionMode = opts.inSelectionMode;
            }
            runCoreEditorCommand(viewModel, args) {
                viewModel.model.pushStackElement();
                viewModel.setCursorStates(args.source, 3 /* CursorChangeReason.Explicit */, cursorMoveCommands_1.CursorMoveCommands.moveToEndOfBuffer(viewModel, viewModel.getCursorStates(), this._inSelectionMode));
                viewModel.revealAllCursors(args.source, true);
            }
        }
        CoreNavigationCommands.CursorBottom = (0, editorExtensions_1.registerEditorCommand)(new BottomCommand({
            inSelectionMode: false,
            id: 'cursorBottom',
            precondition: undefined,
            kbOpts: {
                weight: CORE_WEIGHT,
                kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                primary: 2048 /* KeyMod.CtrlCmd */ | 13 /* KeyCode.End */,
                mac: { primary: 2048 /* KeyMod.CtrlCmd */ | 18 /* KeyCode.DownArrow */ }
            }
        }));
        CoreNavigationCommands.CursorBottomSelect = (0, editorExtensions_1.registerEditorCommand)(new BottomCommand({
            inSelectionMode: true,
            id: 'cursorBottomSelect',
            precondition: undefined,
            kbOpts: {
                weight: CORE_WEIGHT,
                kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 13 /* KeyCode.End */,
                mac: { primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 18 /* KeyCode.DownArrow */ }
            }
        }));
        class EditorScrollImpl extends CoreEditorCommand {
            constructor() {
                super({
                    id: 'editorScroll',
                    precondition: undefined,
                    metadata: EditorScroll_.metadata
                });
            }
            determineScrollMethod(args) {
                const horizontalUnits = [6 /* EditorScroll_.Unit.Column */];
                const verticalUnits = [
                    1 /* EditorScroll_.Unit.Line */,
                    2 /* EditorScroll_.Unit.WrappedLine */,
                    3 /* EditorScroll_.Unit.Page */,
                    4 /* EditorScroll_.Unit.HalfPage */,
                    5 /* EditorScroll_.Unit.Editor */,
                    6 /* EditorScroll_.Unit.Column */
                ];
                const horizontalDirections = [4 /* EditorScroll_.Direction.Left */, 2 /* EditorScroll_.Direction.Right */];
                const verticalDirections = [1 /* EditorScroll_.Direction.Up */, 3 /* EditorScroll_.Direction.Down */];
                if (horizontalUnits.includes(args.unit) && horizontalDirections.includes(args.direction)) {
                    return this._runHorizontalEditorScroll.bind(this);
                }
                if (verticalUnits.includes(args.unit) && verticalDirections.includes(args.direction)) {
                    return this._runVerticalEditorScroll.bind(this);
                }
                return null;
            }
            runCoreEditorCommand(viewModel, args) {
                const parsed = EditorScroll_.parse(args);
                if (!parsed) {
                    // illegal arguments
                    return;
                }
                const runEditorScroll = this.determineScrollMethod(parsed);
                if (!runEditorScroll) {
                    // Incompatible unit and direction
                    return;
                }
                runEditorScroll(viewModel, args.source, parsed);
            }
            _runVerticalEditorScroll(viewModel, source, args) {
                const desiredScrollTop = this._computeDesiredScrollTop(viewModel, args);
                if (args.revealCursor) {
                    // must ensure cursor is in new visible range
                    const desiredVisibleViewRange = viewModel.getCompletelyVisibleViewRangeAtScrollTop(desiredScrollTop);
                    viewModel.setCursorStates(source, 3 /* CursorChangeReason.Explicit */, [
                        cursorMoveCommands_1.CursorMoveCommands.findPositionInViewportIfOutside(viewModel, viewModel.getPrimaryCursorState(), desiredVisibleViewRange, args.select)
                    ]);
                }
                viewModel.viewLayout.setScrollPosition({ scrollTop: desiredScrollTop }, 0 /* ScrollType.Smooth */);
            }
            _computeDesiredScrollTop(viewModel, args) {
                if (args.unit === 1 /* EditorScroll_.Unit.Line */) {
                    // scrolling by model lines
                    const futureViewport = viewModel.viewLayout.getFutureViewport();
                    const visibleViewRange = viewModel.getCompletelyVisibleViewRangeAtScrollTop(futureViewport.top);
                    const visibleModelRange = viewModel.coordinatesConverter.convertViewRangeToModelRange(visibleViewRange);
                    let desiredTopModelLineNumber;
                    if (args.direction === 1 /* EditorScroll_.Direction.Up */) {
                        // must go x model lines up
                        desiredTopModelLineNumber = Math.max(1, visibleModelRange.startLineNumber - args.value);
                    }
                    else {
                        // must go x model lines down
                        desiredTopModelLineNumber = Math.min(viewModel.model.getLineCount(), visibleModelRange.startLineNumber + args.value);
                    }
                    const viewPosition = viewModel.coordinatesConverter.convertModelPositionToViewPosition(new position_1.Position(desiredTopModelLineNumber, 1));
                    return viewModel.viewLayout.getVerticalOffsetForLineNumber(viewPosition.lineNumber);
                }
                if (args.unit === 5 /* EditorScroll_.Unit.Editor */) {
                    let desiredTopModelLineNumber = 0;
                    if (args.direction === 3 /* EditorScroll_.Direction.Down */) {
                        desiredTopModelLineNumber = viewModel.model.getLineCount() - viewModel.cursorConfig.pageSize;
                    }
                    return viewModel.viewLayout.getVerticalOffsetForLineNumber(desiredTopModelLineNumber);
                }
                let noOfLines;
                if (args.unit === 3 /* EditorScroll_.Unit.Page */) {
                    noOfLines = viewModel.cursorConfig.pageSize * args.value;
                }
                else if (args.unit === 4 /* EditorScroll_.Unit.HalfPage */) {
                    noOfLines = Math.round(viewModel.cursorConfig.pageSize / 2) * args.value;
                }
                else {
                    noOfLines = args.value;
                }
                const deltaLines = (args.direction === 1 /* EditorScroll_.Direction.Up */ ? -1 : 1) * noOfLines;
                return viewModel.viewLayout.getCurrentScrollTop() + deltaLines * viewModel.cursorConfig.lineHeight;
            }
            _runHorizontalEditorScroll(viewModel, source, args) {
                const desiredScrollLeft = this._computeDesiredScrollLeft(viewModel, args);
                viewModel.viewLayout.setScrollPosition({ scrollLeft: desiredScrollLeft }, 0 /* ScrollType.Smooth */);
            }
            _computeDesiredScrollLeft(viewModel, args) {
                const deltaColumns = (args.direction === 4 /* EditorScroll_.Direction.Left */ ? -1 : 1) * args.value;
                return viewModel.viewLayout.getCurrentScrollLeft() + deltaColumns * viewModel.cursorConfig.typicalHalfwidthCharacterWidth;
            }
        }
        CoreNavigationCommands.EditorScrollImpl = EditorScrollImpl;
        CoreNavigationCommands.EditorScroll = (0, editorExtensions_1.registerEditorCommand)(new EditorScrollImpl());
        CoreNavigationCommands.ScrollLineUp = (0, editorExtensions_1.registerEditorCommand)(new class extends CoreEditorCommand {
            constructor() {
                super({
                    id: 'scrollLineUp',
                    precondition: undefined,
                    kbOpts: {
                        weight: CORE_WEIGHT,
                        kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                        primary: 2048 /* KeyMod.CtrlCmd */ | 16 /* KeyCode.UpArrow */,
                        mac: { primary: 256 /* KeyMod.WinCtrl */ | 11 /* KeyCode.PageUp */ }
                    }
                });
            }
            runCoreEditorCommand(viewModel, args) {
                CoreNavigationCommands.EditorScroll.runCoreEditorCommand(viewModel, {
                    to: EditorScroll_.RawDirection.Up,
                    by: EditorScroll_.RawUnit.WrappedLine,
                    value: 1,
                    revealCursor: false,
                    select: false,
                    source: args.source
                });
            }
        });
        CoreNavigationCommands.ScrollPageUp = (0, editorExtensions_1.registerEditorCommand)(new class extends CoreEditorCommand {
            constructor() {
                super({
                    id: 'scrollPageUp',
                    precondition: undefined,
                    kbOpts: {
                        weight: CORE_WEIGHT,
                        kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                        primary: 2048 /* KeyMod.CtrlCmd */ | 11 /* KeyCode.PageUp */,
                        win: { primary: 512 /* KeyMod.Alt */ | 11 /* KeyCode.PageUp */ },
                        linux: { primary: 512 /* KeyMod.Alt */ | 11 /* KeyCode.PageUp */ }
                    }
                });
            }
            runCoreEditorCommand(viewModel, args) {
                CoreNavigationCommands.EditorScroll.runCoreEditorCommand(viewModel, {
                    to: EditorScroll_.RawDirection.Up,
                    by: EditorScroll_.RawUnit.Page,
                    value: 1,
                    revealCursor: false,
                    select: false,
                    source: args.source
                });
            }
        });
        CoreNavigationCommands.ScrollEditorTop = (0, editorExtensions_1.registerEditorCommand)(new class extends CoreEditorCommand {
            constructor() {
                super({
                    id: 'scrollEditorTop',
                    precondition: undefined,
                    kbOpts: {
                        weight: CORE_WEIGHT,
                        kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                    }
                });
            }
            runCoreEditorCommand(viewModel, args) {
                CoreNavigationCommands.EditorScroll.runCoreEditorCommand(viewModel, {
                    to: EditorScroll_.RawDirection.Up,
                    by: EditorScroll_.RawUnit.Editor,
                    value: 1,
                    revealCursor: false,
                    select: false,
                    source: args.source
                });
            }
        });
        CoreNavigationCommands.ScrollLineDown = (0, editorExtensions_1.registerEditorCommand)(new class extends CoreEditorCommand {
            constructor() {
                super({
                    id: 'scrollLineDown',
                    precondition: undefined,
                    kbOpts: {
                        weight: CORE_WEIGHT,
                        kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                        primary: 2048 /* KeyMod.CtrlCmd */ | 18 /* KeyCode.DownArrow */,
                        mac: { primary: 256 /* KeyMod.WinCtrl */ | 12 /* KeyCode.PageDown */ }
                    }
                });
            }
            runCoreEditorCommand(viewModel, args) {
                CoreNavigationCommands.EditorScroll.runCoreEditorCommand(viewModel, {
                    to: EditorScroll_.RawDirection.Down,
                    by: EditorScroll_.RawUnit.WrappedLine,
                    value: 1,
                    revealCursor: false,
                    select: false,
                    source: args.source
                });
            }
        });
        CoreNavigationCommands.ScrollPageDown = (0, editorExtensions_1.registerEditorCommand)(new class extends CoreEditorCommand {
            constructor() {
                super({
                    id: 'scrollPageDown',
                    precondition: undefined,
                    kbOpts: {
                        weight: CORE_WEIGHT,
                        kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                        primary: 2048 /* KeyMod.CtrlCmd */ | 12 /* KeyCode.PageDown */,
                        win: { primary: 512 /* KeyMod.Alt */ | 12 /* KeyCode.PageDown */ },
                        linux: { primary: 512 /* KeyMod.Alt */ | 12 /* KeyCode.PageDown */ }
                    }
                });
            }
            runCoreEditorCommand(viewModel, args) {
                CoreNavigationCommands.EditorScroll.runCoreEditorCommand(viewModel, {
                    to: EditorScroll_.RawDirection.Down,
                    by: EditorScroll_.RawUnit.Page,
                    value: 1,
                    revealCursor: false,
                    select: false,
                    source: args.source
                });
            }
        });
        CoreNavigationCommands.ScrollEditorBottom = (0, editorExtensions_1.registerEditorCommand)(new class extends CoreEditorCommand {
            constructor() {
                super({
                    id: 'scrollEditorBottom',
                    precondition: undefined,
                    kbOpts: {
                        weight: CORE_WEIGHT,
                        kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                    }
                });
            }
            runCoreEditorCommand(viewModel, args) {
                CoreNavigationCommands.EditorScroll.runCoreEditorCommand(viewModel, {
                    to: EditorScroll_.RawDirection.Down,
                    by: EditorScroll_.RawUnit.Editor,
                    value: 1,
                    revealCursor: false,
                    select: false,
                    source: args.source
                });
            }
        });
        CoreNavigationCommands.ScrollLeft = (0, editorExtensions_1.registerEditorCommand)(new class extends CoreEditorCommand {
            constructor() {
                super({
                    id: 'scrollLeft',
                    precondition: undefined,
                    kbOpts: {
                        weight: CORE_WEIGHT,
                        kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                    }
                });
            }
            runCoreEditorCommand(viewModel, args) {
                CoreNavigationCommands.EditorScroll.runCoreEditorCommand(viewModel, {
                    to: EditorScroll_.RawDirection.Left,
                    by: EditorScroll_.RawUnit.Column,
                    value: 2,
                    revealCursor: false,
                    select: false,
                    source: args.source
                });
            }
        });
        CoreNavigationCommands.ScrollRight = (0, editorExtensions_1.registerEditorCommand)(new class extends CoreEditorCommand {
            constructor() {
                super({
                    id: 'scrollRight',
                    precondition: undefined,
                    kbOpts: {
                        weight: CORE_WEIGHT,
                        kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                    }
                });
            }
            runCoreEditorCommand(viewModel, args) {
                CoreNavigationCommands.EditorScroll.runCoreEditorCommand(viewModel, {
                    to: EditorScroll_.RawDirection.Right,
                    by: EditorScroll_.RawUnit.Column,
                    value: 2,
                    revealCursor: false,
                    select: false,
                    source: args.source
                });
            }
        });
        class WordCommand extends CoreEditorCommand {
            constructor(opts) {
                super(opts);
                this._inSelectionMode = opts.inSelectionMode;
            }
            runCoreEditorCommand(viewModel, args) {
                if (!args.position) {
                    return;
                }
                viewModel.model.pushStackElement();
                viewModel.setCursorStates(args.source, 3 /* CursorChangeReason.Explicit */, [
                    cursorMoveCommands_1.CursorMoveCommands.word(viewModel, viewModel.getPrimaryCursorState(), this._inSelectionMode, args.position)
                ]);
                if (args.revealType !== 2 /* NavigationCommandRevealType.None */) {
                    viewModel.revealAllCursors(args.source, true, true);
                }
            }
        }
        CoreNavigationCommands.WordSelect = (0, editorExtensions_1.registerEditorCommand)(new WordCommand({
            inSelectionMode: false,
            id: '_wordSelect',
            precondition: undefined
        }));
        CoreNavigationCommands.WordSelectDrag = (0, editorExtensions_1.registerEditorCommand)(new WordCommand({
            inSelectionMode: true,
            id: '_wordSelectDrag',
            precondition: undefined
        }));
        CoreNavigationCommands.LastCursorWordSelect = (0, editorExtensions_1.registerEditorCommand)(new class extends CoreEditorCommand {
            constructor() {
                super({
                    id: 'lastCursorWordSelect',
                    precondition: undefined
                });
            }
            runCoreEditorCommand(viewModel, args) {
                if (!args.position) {
                    return;
                }
                const lastAddedCursorIndex = viewModel.getLastAddedCursorIndex();
                const states = viewModel.getCursorStates();
                const newStates = states.slice(0);
                const lastAddedState = states[lastAddedCursorIndex];
                newStates[lastAddedCursorIndex] = cursorMoveCommands_1.CursorMoveCommands.word(viewModel, lastAddedState, lastAddedState.modelState.hasSelection(), args.position);
                viewModel.model.pushStackElement();
                viewModel.setCursorStates(args.source, 3 /* CursorChangeReason.Explicit */, newStates);
            }
        });
        class LineCommand extends CoreEditorCommand {
            constructor(opts) {
                super(opts);
                this._inSelectionMode = opts.inSelectionMode;
            }
            runCoreEditorCommand(viewModel, args) {
                if (!args.position) {
                    return;
                }
                viewModel.model.pushStackElement();
                viewModel.setCursorStates(args.source, 3 /* CursorChangeReason.Explicit */, [
                    cursorMoveCommands_1.CursorMoveCommands.line(viewModel, viewModel.getPrimaryCursorState(), this._inSelectionMode, args.position, args.viewPosition)
                ]);
                if (args.revealType !== 2 /* NavigationCommandRevealType.None */) {
                    viewModel.revealAllCursors(args.source, false, true);
                }
            }
        }
        CoreNavigationCommands.LineSelect = (0, editorExtensions_1.registerEditorCommand)(new LineCommand({
            inSelectionMode: false,
            id: '_lineSelect',
            precondition: undefined
        }));
        CoreNavigationCommands.LineSelectDrag = (0, editorExtensions_1.registerEditorCommand)(new LineCommand({
            inSelectionMode: true,
            id: '_lineSelectDrag',
            precondition: undefined
        }));
        class LastCursorLineCommand extends CoreEditorCommand {
            constructor(opts) {
                super(opts);
                this._inSelectionMode = opts.inSelectionMode;
            }
            runCoreEditorCommand(viewModel, args) {
                if (!args.position) {
                    return;
                }
                const lastAddedCursorIndex = viewModel.getLastAddedCursorIndex();
                const states = viewModel.getCursorStates();
                const newStates = states.slice(0);
                newStates[lastAddedCursorIndex] = cursorMoveCommands_1.CursorMoveCommands.line(viewModel, states[lastAddedCursorIndex], this._inSelectionMode, args.position, args.viewPosition);
                viewModel.model.pushStackElement();
                viewModel.setCursorStates(args.source, 3 /* CursorChangeReason.Explicit */, newStates);
            }
        }
        CoreNavigationCommands.LastCursorLineSelect = (0, editorExtensions_1.registerEditorCommand)(new LastCursorLineCommand({
            inSelectionMode: false,
            id: 'lastCursorLineSelect',
            precondition: undefined
        }));
        CoreNavigationCommands.LastCursorLineSelectDrag = (0, editorExtensions_1.registerEditorCommand)(new LastCursorLineCommand({
            inSelectionMode: true,
            id: 'lastCursorLineSelectDrag',
            precondition: undefined
        }));
        CoreNavigationCommands.CancelSelection = (0, editorExtensions_1.registerEditorCommand)(new class extends CoreEditorCommand {
            constructor() {
                super({
                    id: 'cancelSelection',
                    precondition: editorContextKeys_1.EditorContextKeys.hasNonEmptySelection,
                    kbOpts: {
                        weight: CORE_WEIGHT,
                        kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                        primary: 9 /* KeyCode.Escape */,
                        secondary: [1024 /* KeyMod.Shift */ | 9 /* KeyCode.Escape */]
                    }
                });
            }
            runCoreEditorCommand(viewModel, args) {
                viewModel.model.pushStackElement();
                viewModel.setCursorStates(args.source, 3 /* CursorChangeReason.Explicit */, [
                    cursorMoveCommands_1.CursorMoveCommands.cancelSelection(viewModel, viewModel.getPrimaryCursorState())
                ]);
                viewModel.revealAllCursors(args.source, true);
            }
        });
        CoreNavigationCommands.RemoveSecondaryCursors = (0, editorExtensions_1.registerEditorCommand)(new class extends CoreEditorCommand {
            constructor() {
                super({
                    id: 'removeSecondaryCursors',
                    precondition: editorContextKeys_1.EditorContextKeys.hasMultipleSelections,
                    kbOpts: {
                        weight: CORE_WEIGHT + 1,
                        kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                        primary: 9 /* KeyCode.Escape */,
                        secondary: [1024 /* KeyMod.Shift */ | 9 /* KeyCode.Escape */]
                    }
                });
            }
            runCoreEditorCommand(viewModel, args) {
                viewModel.model.pushStackElement();
                viewModel.setCursorStates(args.source, 3 /* CursorChangeReason.Explicit */, [
                    viewModel.getPrimaryCursorState()
                ]);
                viewModel.revealAllCursors(args.source, true);
                (0, aria_1.status)(nls.localize(61, "Removed secondary cursors"));
            }
        });
        CoreNavigationCommands.RevealLine = (0, editorExtensions_1.registerEditorCommand)(new class extends CoreEditorCommand {
            constructor() {
                super({
                    id: 'revealLine',
                    precondition: undefined,
                    metadata: RevealLine_.metadata
                });
            }
            runCoreEditorCommand(viewModel, args) {
                const revealLineArg = args;
                const lineNumberArg = revealLineArg.lineNumber || 0;
                let lineNumber = typeof lineNumberArg === 'number' ? (lineNumberArg + 1) : (parseInt(lineNumberArg) + 1);
                if (lineNumber < 1) {
                    lineNumber = 1;
                }
                const lineCount = viewModel.model.getLineCount();
                if (lineNumber > lineCount) {
                    lineNumber = lineCount;
                }
                const range = new range_1.Range(lineNumber, 1, lineNumber, viewModel.model.getLineMaxColumn(lineNumber));
                let revealAt = 0 /* VerticalRevealType.Simple */;
                if (revealLineArg.at) {
                    switch (revealLineArg.at) {
                        case RevealLine_.RawAtArgument.Top:
                            revealAt = 3 /* VerticalRevealType.Top */;
                            break;
                        case RevealLine_.RawAtArgument.Center:
                            revealAt = 1 /* VerticalRevealType.Center */;
                            break;
                        case RevealLine_.RawAtArgument.Bottom:
                            revealAt = 4 /* VerticalRevealType.Bottom */;
                            break;
                        default:
                            break;
                    }
                }
                const viewRange = viewModel.coordinatesConverter.convertModelRangeToViewRange(range);
                viewModel.revealRange(args.source, false, viewRange, revealAt, 0 /* ScrollType.Smooth */);
            }
        });
        CoreNavigationCommands.SelectAll = new class extends EditorOrNativeTextInputCommand {
            constructor() {
                super(editorExtensions_1.SelectAllCommand);
            }
            runDOMCommand(activeElement) {
                if (browser_1.isFirefox) {
                    activeElement.focus();
                    activeElement.select();
                }
                activeElement.ownerDocument.execCommand('selectAll');
            }
            runEditorCommand(accessor, editor, args) {
                const viewModel = editor._getViewModel();
                if (!viewModel) {
                    // the editor has no view => has no cursors
                    return;
                }
                this.runCoreEditorCommand(viewModel, args);
            }
            runCoreEditorCommand(viewModel, args) {
                viewModel.model.pushStackElement();
                viewModel.setCursorStates('keyboard', 3 /* CursorChangeReason.Explicit */, [
                    cursorMoveCommands_1.CursorMoveCommands.selectAll(viewModel, viewModel.getPrimaryCursorState())
                ]);
            }
        }();
        CoreNavigationCommands.SetSelection = (0, editorExtensions_1.registerEditorCommand)(new class extends CoreEditorCommand {
            constructor() {
                super({
                    id: 'setSelection',
                    precondition: undefined
                });
            }
            runCoreEditorCommand(viewModel, args) {
                if (!args.selection) {
                    return;
                }
                viewModel.model.pushStackElement();
                viewModel.setCursorStates(args.source, 3 /* CursorChangeReason.Explicit */, [
                    cursorCommon_1.CursorState.fromModelSelection(args.selection)
                ]);
            }
        });
    })(CoreNavigationCommands || (exports.CoreNavigationCommands = CoreNavigationCommands = {}));
    const columnSelectionCondition = contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.textInputFocus, editorContextKeys_1.EditorContextKeys.columnSelection);
    function registerColumnSelection(id, keybinding) {
        keybindingsRegistry_1.KeybindingsRegistry.registerKeybindingRule({
            id: id,
            primary: keybinding,
            when: columnSelectionCondition,
            weight: CORE_WEIGHT + 1
        });
    }
    registerColumnSelection(CoreNavigationCommands.CursorColumnSelectLeft.id, 1024 /* KeyMod.Shift */ | 15 /* KeyCode.LeftArrow */);
    registerColumnSelection(CoreNavigationCommands.CursorColumnSelectRight.id, 1024 /* KeyMod.Shift */ | 17 /* KeyCode.RightArrow */);
    registerColumnSelection(CoreNavigationCommands.CursorColumnSelectUp.id, 1024 /* KeyMod.Shift */ | 16 /* KeyCode.UpArrow */);
    registerColumnSelection(CoreNavigationCommands.CursorColumnSelectPageUp.id, 1024 /* KeyMod.Shift */ | 11 /* KeyCode.PageUp */);
    registerColumnSelection(CoreNavigationCommands.CursorColumnSelectDown.id, 1024 /* KeyMod.Shift */ | 18 /* KeyCode.DownArrow */);
    registerColumnSelection(CoreNavigationCommands.CursorColumnSelectPageDown.id, 1024 /* KeyMod.Shift */ | 12 /* KeyCode.PageDown */);
    function registerCommand(command) {
        command.register();
        return command;
    }
    var CoreEditingCommands;
    (function (CoreEditingCommands) {
        class CoreEditingCommand extends editorExtensions_1.EditorCommand {
            runEditorCommand(accessor, editor, args) {
                const viewModel = editor._getViewModel();
                if (!viewModel) {
                    // the editor has no view => has no cursors
                    return;
                }
                this.runCoreEditingCommand(editor, viewModel, args || {});
            }
        }
        CoreEditingCommands.CoreEditingCommand = CoreEditingCommand;
        CoreEditingCommands.LineBreakInsert = (0, editorExtensions_1.registerEditorCommand)(new class extends CoreEditingCommand {
            constructor() {
                super({
                    id: 'lineBreakInsert',
                    precondition: editorContextKeys_1.EditorContextKeys.writable,
                    kbOpts: {
                        weight: CORE_WEIGHT,
                        kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                        primary: 0,
                        mac: { primary: 256 /* KeyMod.WinCtrl */ | 45 /* KeyCode.KeyO */ }
                    }
                });
            }
            runCoreEditingCommand(editor, viewModel, args) {
                editor.pushUndoStop();
                editor.executeCommands(this.id, cursorTypeEditOperations_1.EnterOperation.lineBreakInsert(viewModel.cursorConfig, viewModel.model, viewModel.getCursorStates().map(s => s.modelState.selection)));
            }
        });
        CoreEditingCommands.Outdent = (0, editorExtensions_1.registerEditorCommand)(new class extends CoreEditingCommand {
            constructor() {
                super({
                    id: 'outdent',
                    precondition: editorContextKeys_1.EditorContextKeys.writable,
                    kbOpts: {
                        weight: CORE_WEIGHT,
                        kbExpr: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.editorTextFocus, editorContextKeys_1.EditorContextKeys.tabDoesNotMoveFocus),
                        primary: 1024 /* KeyMod.Shift */ | 2 /* KeyCode.Tab */
                    }
                });
            }
            runCoreEditingCommand(editor, viewModel, args) {
                editor.pushUndoStop();
                editor.executeCommands(this.id, cursorTypeOperations_1.TypeOperations.outdent(viewModel.cursorConfig, viewModel.model, viewModel.getCursorStates().map(s => s.modelState.selection)));
                editor.pushUndoStop();
            }
        });
        CoreEditingCommands.Tab = (0, editorExtensions_1.registerEditorCommand)(new class extends CoreEditingCommand {
            constructor() {
                super({
                    id: 'tab',
                    precondition: editorContextKeys_1.EditorContextKeys.writable,
                    kbOpts: {
                        weight: CORE_WEIGHT,
                        kbExpr: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.editorTextFocus, editorContextKeys_1.EditorContextKeys.tabDoesNotMoveFocus),
                        primary: 2 /* KeyCode.Tab */
                    }
                });
            }
            runCoreEditingCommand(editor, viewModel, args) {
                editor.pushUndoStop();
                editor.executeCommands(this.id, cursorTypeOperations_1.TypeOperations.tab(viewModel.cursorConfig, viewModel.model, viewModel.getCursorStates().map(s => s.modelState.selection)));
                editor.pushUndoStop();
            }
        });
        CoreEditingCommands.DeleteLeft = (0, editorExtensions_1.registerEditorCommand)(new class extends CoreEditingCommand {
            constructor() {
                super({
                    id: 'deleteLeft',
                    precondition: undefined,
                    kbOpts: {
                        weight: CORE_WEIGHT,
                        kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                        primary: 1 /* KeyCode.Backspace */,
                        secondary: [1024 /* KeyMod.Shift */ | 1 /* KeyCode.Backspace */],
                        mac: { primary: 1 /* KeyCode.Backspace */, secondary: [1024 /* KeyMod.Shift */ | 1 /* KeyCode.Backspace */, 256 /* KeyMod.WinCtrl */ | 38 /* KeyCode.KeyH */, 256 /* KeyMod.WinCtrl */ | 1 /* KeyCode.Backspace */] }
                    }
                });
            }
            runCoreEditingCommand(editor, viewModel, args) {
                const [shouldPushStackElementBefore, commands] = cursorDeleteOperations_1.DeleteOperations.deleteLeft(viewModel.getPrevEditOperationType(), viewModel.cursorConfig, viewModel.model, viewModel.getCursorStates().map(s => s.modelState.selection), viewModel.getCursorAutoClosedCharacters());
                if (shouldPushStackElementBefore) {
                    editor.pushUndoStop();
                }
                editor.executeCommands(this.id, commands);
                viewModel.setPrevEditOperationType(2 /* EditOperationType.DeletingLeft */);
            }
        });
        CoreEditingCommands.DeleteRight = (0, editorExtensions_1.registerEditorCommand)(new class extends CoreEditingCommand {
            constructor() {
                super({
                    id: 'deleteRight',
                    precondition: undefined,
                    kbOpts: {
                        weight: CORE_WEIGHT,
                        kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                        primary: 20 /* KeyCode.Delete */,
                        mac: { primary: 20 /* KeyCode.Delete */, secondary: [256 /* KeyMod.WinCtrl */ | 34 /* KeyCode.KeyD */, 256 /* KeyMod.WinCtrl */ | 20 /* KeyCode.Delete */] }
                    }
                });
            }
            runCoreEditingCommand(editor, viewModel, args) {
                const [shouldPushStackElementBefore, commands] = cursorDeleteOperations_1.DeleteOperations.deleteRight(viewModel.getPrevEditOperationType(), viewModel.cursorConfig, viewModel.model, viewModel.getCursorStates().map(s => s.modelState.selection));
                if (shouldPushStackElementBefore) {
                    editor.pushUndoStop();
                }
                editor.executeCommands(this.id, commands);
                viewModel.setPrevEditOperationType(3 /* EditOperationType.DeletingRight */);
            }
        });
        CoreEditingCommands.Undo = new class extends EditorOrNativeTextInputCommand {
            constructor() {
                super(editorExtensions_1.UndoCommand);
            }
            runDOMCommand(activeElement) {
                activeElement.ownerDocument.execCommand('undo');
            }
            runEditorCommand(accessor, editor, args) {
                if (!editor.hasModel() || editor.getOption(92 /* EditorOption.readOnly */) === true) {
                    return;
                }
                return editor.getModel().undo();
            }
        }();
        CoreEditingCommands.Redo = new class extends EditorOrNativeTextInputCommand {
            constructor() {
                super(editorExtensions_1.RedoCommand);
            }
            runDOMCommand(activeElement) {
                activeElement.ownerDocument.execCommand('redo');
            }
            runEditorCommand(accessor, editor, args) {
                if (!editor.hasModel() || editor.getOption(92 /* EditorOption.readOnly */) === true) {
                    return;
                }
                return editor.getModel().redo();
            }
        }();
    })(CoreEditingCommands || (exports.CoreEditingCommands = CoreEditingCommands = {}));
    /**
     * A command that will invoke a command on the focused editor.
     */
    class EditorHandlerCommand extends editorExtensions_1.Command {
        constructor(id, handlerId, metadata) {
            super({
                id: id,
                precondition: undefined,
                metadata
            });
            this._handlerId = handlerId;
        }
        runCommand(accessor, args) {
            const editor = accessor.get(codeEditorService_1.ICodeEditorService).getFocusedCodeEditor();
            if (!editor) {
                return;
            }
            editor.trigger('keyboard', this._handlerId, args);
        }
    }
    function registerOverwritableCommand(handlerId, metadata) {
        registerCommand(new EditorHandlerCommand('default:' + handlerId, handlerId));
        registerCommand(new EditorHandlerCommand(handlerId, handlerId, metadata));
    }
    registerOverwritableCommand("type" /* Handler.Type */, {
        description: `Type`,
        args: [{
                name: 'args',
                schema: {
                    'type': 'object',
                    'required': ['text'],
                    'properties': {
                        'text': {
                            'type': 'string'
                        }
                    },
                }
            }]
    });
    registerOverwritableCommand("replacePreviousChar" /* Handler.ReplacePreviousChar */);
    registerOverwritableCommand("compositionType" /* Handler.CompositionType */);
    registerOverwritableCommand("compositionStart" /* Handler.CompositionStart */);
    registerOverwritableCommand("compositionEnd" /* Handler.CompositionEnd */);
    registerOverwritableCommand("paste" /* Handler.Paste */);
    registerOverwritableCommand("cut" /* Handler.Cut */);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[725/*vs/editor/browser/services/markerDecorations*/], __M([1/*require*/,0/*exports*/,266/*vs/editor/common/services/markerDecorations*/,15/*vs/editor/browser/editorExtensions*/]), function (require, exports, markerDecorations_1, editorExtensions_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MarkerDecorationsContribution = void 0;
    let MarkerDecorationsContribution = class MarkerDecorationsContribution {
        static { this.ID = 'editor.contrib.markerDecorations'; }
        constructor(_editor, _markerDecorationsService) {
            // Doesn't do anything, just requires `IMarkerDecorationsService` to make sure it gets instantiated
        }
        dispose() {
        }
    };
    exports.MarkerDecorationsContribution = MarkerDecorationsContribution;
    exports.MarkerDecorationsContribution = MarkerDecorationsContribution = __decorate([
        __param(1, markerDecorations_1.IMarkerDecorationsService)
    ], MarkerDecorationsContribution);
    (0, editorExtensions_1.registerEditorContribution)(MarkerDecorationsContribution.ID, MarkerDecorationsContribution, 0 /* EditorContributionInstantiation.Eager */); // eager because it instantiates IMarkerDecorationsService which is responsible for rendering squiggles
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[726/*vs/editor/browser/view/viewController*/], __M([1/*require*/,0/*exports*/,214/*vs/editor/browser/coreCommands*/,9/*vs/editor/common/core/position*/,16/*vs/base/common/platform*/]), function (require, exports, coreCommands_1, position_1, platform) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ViewController = void 0;
    class ViewController {
        constructor(configuration, viewModel, userInputEvents, commandDelegate) {
            this.configuration = configuration;
            this.viewModel = viewModel;
            this.userInputEvents = userInputEvents;
            this.commandDelegate = commandDelegate;
        }
        paste(text, pasteOnNewLine, multicursorText, mode) {
            this.commandDelegate.paste(text, pasteOnNewLine, multicursorText, mode);
        }
        type(text) {
            this.commandDelegate.type(text);
        }
        compositionType(text, replacePrevCharCnt, replaceNextCharCnt, positionDelta) {
            this.commandDelegate.compositionType(text, replacePrevCharCnt, replaceNextCharCnt, positionDelta);
        }
        compositionStart() {
            this.commandDelegate.startComposition();
        }
        compositionEnd() {
            this.commandDelegate.endComposition();
        }
        cut() {
            this.commandDelegate.cut();
        }
        setSelection(modelSelection) {
            coreCommands_1.CoreNavigationCommands.SetSelection.runCoreEditorCommand(this.viewModel, {
                source: 'keyboard',
                selection: modelSelection
            });
        }
        _validateViewColumn(viewPosition) {
            const minColumn = this.viewModel.getLineMinColumn(viewPosition.lineNumber);
            if (viewPosition.column < minColumn) {
                return new position_1.Position(viewPosition.lineNumber, minColumn);
            }
            return viewPosition;
        }
        _hasMulticursorModifier(data) {
            switch (this.configuration.options.get(78 /* EditorOption.multiCursorModifier */)) {
                case 'altKey':
                    return data.altKey;
                case 'ctrlKey':
                    return data.ctrlKey;
                case 'metaKey':
                    return data.metaKey;
                default:
                    return false;
            }
        }
        _hasNonMulticursorModifier(data) {
            switch (this.configuration.options.get(78 /* EditorOption.multiCursorModifier */)) {
                case 'altKey':
                    return data.ctrlKey || data.metaKey;
                case 'ctrlKey':
                    return data.altKey || data.metaKey;
                case 'metaKey':
                    return data.ctrlKey || data.altKey;
                default:
                    return false;
            }
        }
        dispatchMouse(data) {
            const options = this.configuration.options;
            const selectionClipboardIsOn = (platform.isLinux && options.get(108 /* EditorOption.selectionClipboard */));
            const columnSelection = options.get(22 /* EditorOption.columnSelection */);
            if (data.middleButton && !selectionClipboardIsOn) {
                this._columnSelect(data.position, data.mouseColumn, data.inSelectionMode);
            }
            else if (data.startedOnLineNumbers) {
                // If the dragging started on the gutter, then have operations work on the entire line
                if (this._hasMulticursorModifier(data)) {
                    if (data.inSelectionMode) {
                        this._lastCursorLineSelect(data.position, data.revealType);
                    }
                    else {
                        this._createCursor(data.position, true);
                    }
                }
                else {
                    if (data.inSelectionMode) {
                        this._lineSelectDrag(data.position, data.revealType);
                    }
                    else {
                        this._lineSelect(data.position, data.revealType);
                    }
                }
            }
            else if (data.mouseDownCount >= 4) {
                this._selectAll();
            }
            else if (data.mouseDownCount === 3) {
                if (this._hasMulticursorModifier(data)) {
                    if (data.inSelectionMode) {
                        this._lastCursorLineSelectDrag(data.position, data.revealType);
                    }
                    else {
                        this._lastCursorLineSelect(data.position, data.revealType);
                    }
                }
                else {
                    if (data.inSelectionMode) {
                        this._lineSelectDrag(data.position, data.revealType);
                    }
                    else {
                        this._lineSelect(data.position, data.revealType);
                    }
                }
            }
            else if (data.mouseDownCount === 2) {
                if (!data.onInjectedText) {
                    if (this._hasMulticursorModifier(data)) {
                        this._lastCursorWordSelect(data.position, data.revealType);
                    }
                    else {
                        if (data.inSelectionMode) {
                            this._wordSelectDrag(data.position, data.revealType);
                        }
                        else {
                            this._wordSelect(data.position, data.revealType);
                        }
                    }
                }
            }
            else {
                if (this._hasMulticursorModifier(data)) {
                    if (!this._hasNonMulticursorModifier(data)) {
                        if (data.shiftKey) {
                            this._columnSelect(data.position, data.mouseColumn, true);
                        }
                        else {
                            // Do multi-cursor operations only when purely alt is pressed
                            if (data.inSelectionMode) {
                                this._lastCursorMoveToSelect(data.position, data.revealType);
                            }
                            else {
                                this._createCursor(data.position, false);
                            }
                        }
                    }
                }
                else {
                    if (data.inSelectionMode) {
                        if (data.altKey) {
                            this._columnSelect(data.position, data.mouseColumn, true);
                        }
                        else {
                            if (columnSelection) {
                                this._columnSelect(data.position, data.mouseColumn, true);
                            }
                            else {
                                this._moveToSelect(data.position, data.revealType);
                            }
                        }
                    }
                    else {
                        this.moveTo(data.position, data.revealType);
                    }
                }
            }
        }
        _usualArgs(viewPosition, revealType) {
            viewPosition = this._validateViewColumn(viewPosition);
            return {
                source: 'mouse',
                position: this._convertViewToModelPosition(viewPosition),
                viewPosition,
                revealType
            };
        }
        moveTo(viewPosition, revealType) {
            coreCommands_1.CoreNavigationCommands.MoveTo.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition, revealType));
        }
        _moveToSelect(viewPosition, revealType) {
            coreCommands_1.CoreNavigationCommands.MoveToSelect.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition, revealType));
        }
        _columnSelect(viewPosition, mouseColumn, doColumnSelect) {
            viewPosition = this._validateViewColumn(viewPosition);
            coreCommands_1.CoreNavigationCommands.ColumnSelect.runCoreEditorCommand(this.viewModel, {
                source: 'mouse',
                position: this._convertViewToModelPosition(viewPosition),
                viewPosition: viewPosition,
                mouseColumn: mouseColumn,
                doColumnSelect: doColumnSelect
            });
        }
        _createCursor(viewPosition, wholeLine) {
            viewPosition = this._validateViewColumn(viewPosition);
            coreCommands_1.CoreNavigationCommands.CreateCursor.runCoreEditorCommand(this.viewModel, {
                source: 'mouse',
                position: this._convertViewToModelPosition(viewPosition),
                viewPosition: viewPosition,
                wholeLine: wholeLine
            });
        }
        _lastCursorMoveToSelect(viewPosition, revealType) {
            coreCommands_1.CoreNavigationCommands.LastCursorMoveToSelect.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition, revealType));
        }
        _wordSelect(viewPosition, revealType) {
            coreCommands_1.CoreNavigationCommands.WordSelect.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition, revealType));
        }
        _wordSelectDrag(viewPosition, revealType) {
            coreCommands_1.CoreNavigationCommands.WordSelectDrag.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition, revealType));
        }
        _lastCursorWordSelect(viewPosition, revealType) {
            coreCommands_1.CoreNavigationCommands.LastCursorWordSelect.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition, revealType));
        }
        _lineSelect(viewPosition, revealType) {
            coreCommands_1.CoreNavigationCommands.LineSelect.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition, revealType));
        }
        _lineSelectDrag(viewPosition, revealType) {
            coreCommands_1.CoreNavigationCommands.LineSelectDrag.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition, revealType));
        }
        _lastCursorLineSelect(viewPosition, revealType) {
            coreCommands_1.CoreNavigationCommands.LastCursorLineSelect.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition, revealType));
        }
        _lastCursorLineSelectDrag(viewPosition, revealType) {
            coreCommands_1.CoreNavigationCommands.LastCursorLineSelectDrag.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition, revealType));
        }
        _selectAll() {
            coreCommands_1.CoreNavigationCommands.SelectAll.runCoreEditorCommand(this.viewModel, { source: 'mouse' });
        }
        // ----------------------
        _convertViewToModelPosition(viewPosition) {
            return this.viewModel.coordinatesConverter.convertViewPositionToModelPosition(viewPosition);
        }
        emitKeyDown(e) {
            this.userInputEvents.emitKeyDown(e);
        }
        emitKeyUp(e) {
            this.userInputEvents.emitKeyUp(e);
        }
        emitContextMenu(e) {
            this.userInputEvents.emitContextMenu(e);
        }
        emitMouseMove(e) {
            this.userInputEvents.emitMouseMove(e);
        }
        emitMouseLeave(e) {
            this.userInputEvents.emitMouseLeave(e);
        }
        emitMouseUp(e) {
            this.userInputEvents.emitMouseUp(e);
        }
        emitMouseDown(e) {
            this.userInputEvents.emitMouseDown(e);
        }
        emitMouseDrag(e) {
            this.userInputEvents.emitMouseDrag(e);
        }
        emitMouseDrop(e) {
            this.userInputEvents.emitMouseDrop(e);
        }
        emitMouseDropCanceled() {
            this.userInputEvents.emitMouseDropCanceled();
        }
        emitMouseWheel(e) {
            this.userInputEvents.emitMouseWheel(e);
        }
    }
    exports.ViewController = ViewController;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[215/*vs/editor/browser/widget/diffEditor/diffProviderFactoryService*/], __M([1/*require*/,0/*exports*/,49/*vs/platform/instantiation/common/extensions*/,7/*vs/platform/instantiation/common/instantiation*/,6/*vs/base/common/event*/,54/*vs/base/common/stopwatch*/,55/*vs/editor/common/core/lineRange*/,105/*vs/editor/common/diff/rangeMapping*/,100/*vs/editor/common/services/editorWorker*/,63/*vs/platform/telemetry/common/telemetry*/]), function (require, exports, extensions_1, instantiation_1, event_1, stopwatch_1, lineRange_1, rangeMapping_1, editorWorker_1, telemetry_1) {
    "use strict";
    var WorkerBasedDocumentDiffProvider_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.WorkerBasedDocumentDiffProvider = exports.WorkerBasedDiffProviderFactoryService = exports.IDiffProviderFactoryService = void 0;
    exports.IDiffProviderFactoryService = (0, instantiation_1.createDecorator)('diffProviderFactoryService');
    let WorkerBasedDiffProviderFactoryService = class WorkerBasedDiffProviderFactoryService {
        constructor(instantiationService) {
            this.instantiationService = instantiationService;
        }
        createDiffProvider(options) {
            return this.instantiationService.createInstance(WorkerBasedDocumentDiffProvider, options);
        }
    };
    exports.WorkerBasedDiffProviderFactoryService = WorkerBasedDiffProviderFactoryService;
    exports.WorkerBasedDiffProviderFactoryService = WorkerBasedDiffProviderFactoryService = __decorate([
        __param(0, instantiation_1.IInstantiationService)
    ], WorkerBasedDiffProviderFactoryService);
    (0, extensions_1.registerSingleton)(exports.IDiffProviderFactoryService, WorkerBasedDiffProviderFactoryService, 1 /* InstantiationType.Delayed */);
    let WorkerBasedDocumentDiffProvider = class WorkerBasedDocumentDiffProvider {
        static { WorkerBasedDocumentDiffProvider_1 = this; }
        static { this.diffCache = new Map(); }
        constructor(options, editorWorkerService, telemetryService) {
            this.editorWorkerService = editorWorkerService;
            this.telemetryService = telemetryService;
            this.onDidChangeEventEmitter = new event_1.Emitter();
            this.onDidChange = this.onDidChangeEventEmitter.event;
            this.diffAlgorithm = 'advanced';
            this.diffAlgorithmOnDidChangeSubscription = undefined;
            this.setOptions(options);
        }
        dispose() {
            this.diffAlgorithmOnDidChangeSubscription?.dispose();
        }
        async computeDiff(original, modified, options, cancellationToken) {
            if (typeof this.diffAlgorithm !== 'string') {
                return this.diffAlgorithm.computeDiff(original, modified, options, cancellationToken);
            }
            if (original.isDisposed() || modified.isDisposed()) {
                // TODO@hediet
                return {
                    changes: [],
                    identical: true,
                    quitEarly: false,
                    moves: [],
                };
            }
            // This significantly speeds up the case when the original file is empty
            if (original.getLineCount() === 1 && original.getLineMaxColumn(1) === 1) {
                if (modified.getLineCount() === 1 && modified.getLineMaxColumn(1) === 1) {
                    return {
                        changes: [],
                        identical: true,
                        quitEarly: false,
                        moves: [],
                    };
                }
                return {
                    changes: [
                        new rangeMapping_1.DetailedLineRangeMapping(new lineRange_1.LineRange(1, 2), new lineRange_1.LineRange(1, modified.getLineCount() + 1), [
                            new rangeMapping_1.RangeMapping(original.getFullModelRange(), modified.getFullModelRange())
                        ])
                    ],
                    identical: false,
                    quitEarly: false,
                    moves: [],
                };
            }
            const uriKey = JSON.stringify([original.uri.toString(), modified.uri.toString()]);
            const context = JSON.stringify([original.id, modified.id, original.getAlternativeVersionId(), modified.getAlternativeVersionId(), JSON.stringify(options)]);
            const c = WorkerBasedDocumentDiffProvider_1.diffCache.get(uriKey);
            if (c && c.context === context) {
                return c.result;
            }
            const sw = stopwatch_1.StopWatch.create();
            const result = await this.editorWorkerService.computeDiff(original.uri, modified.uri, options, this.diffAlgorithm);
            const timeMs = sw.elapsed();
            this.telemetryService.publicLog2('diffEditor.computeDiff', {
                timeMs,
                timedOut: result?.quitEarly ?? true,
                detectedMoves: options.computeMoves ? (result?.moves.length ?? 0) : -1,
            });
            if (cancellationToken.isCancellationRequested) {
                // Text models might be disposed!
                return {
                    changes: [],
                    identical: false,
                    quitEarly: true,
                    moves: [],
                };
            }
            if (!result) {
                throw new Error('no diff result available');
            }
            // max 10 items in cache
            if (WorkerBasedDocumentDiffProvider_1.diffCache.size > 10) {
                WorkerBasedDocumentDiffProvider_1.diffCache.delete(WorkerBasedDocumentDiffProvider_1.diffCache.keys().next().value);
            }
            WorkerBasedDocumentDiffProvider_1.diffCache.set(uriKey, { result, context });
            return result;
        }
        setOptions(newOptions) {
            let didChange = false;
            if (newOptions.diffAlgorithm) {
                if (this.diffAlgorithm !== newOptions.diffAlgorithm) {
                    this.diffAlgorithmOnDidChangeSubscription?.dispose();
                    this.diffAlgorithmOnDidChangeSubscription = undefined;
                    this.diffAlgorithm = newOptions.diffAlgorithm;
                    if (typeof newOptions.diffAlgorithm !== 'string') {
                        this.diffAlgorithmOnDidChangeSubscription = newOptions.diffAlgorithm.onDidChange(() => this.onDidChangeEventEmitter.fire());
                    }
                    didChange = true;
                }
            }
            if (didChange) {
                this.onDidChangeEventEmitter.fire();
            }
        }
    };
    exports.WorkerBasedDocumentDiffProvider = WorkerBasedDocumentDiffProvider;
    exports.WorkerBasedDocumentDiffProvider = WorkerBasedDocumentDiffProvider = WorkerBasedDocumentDiffProvider_1 = __decorate([
        __param(1, editorWorker_1.IEditorWorkerService),
        __param(2, telemetry_1.ITelemetryService)
    ], WorkerBasedDocumentDiffProvider);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[407/*vs/editor/browser/widget/diffEditor/diffEditorViewModel*/], __M([1/*require*/,0/*exports*/,14/*vs/base/common/async*/,18/*vs/base/common/cancellation*/,2/*vs/base/common/lifecycle*/,21/*vs/base/common/observable*/,215/*vs/editor/browser/widget/diffEditor/diffProviderFactoryService*/,88/*vs/editor/browser/widget/diffEditor/utils*/,171/*vs/base/common/hotReloadHelpers*/,55/*vs/editor/common/core/lineRange*/,317/*vs/editor/common/diff/defaultLinesDiffComputer/defaultLinesDiffComputer*/,105/*vs/editor/common/diff/rangeMapping*/,200/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/beforeEditPositionMapper*/,319/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/combineTextEditInfos*/,315/*vs/editor/common/diff/defaultLinesDiffComputer/heuristicSequenceOptimizations*/,19/*vs/base/common/types*/,13/*vs/base/common/arrays*/,90/*vs/base/common/assert*/]), function (require, exports, async_1, cancellation_1, lifecycle_1, observable_1, diffProviderFactoryService_1, utils_1, hotReloadHelpers_1, lineRange_1, defaultLinesDiffComputer_1, rangeMapping_1, beforeEditPositionMapper_1, combineTextEditInfos_1, heuristicSequenceOptimizations_1, types_1, arrays_1, assert_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.UnchangedRegion = exports.DiffMapping = exports.DiffState = exports.DiffEditorViewModel = void 0;
    let DiffEditorViewModel = class DiffEditorViewModel extends lifecycle_1.Disposable {
        setActiveMovedText(movedText) {
            this._activeMovedText.set(movedText, undefined);
        }
        constructor(model, _options, _diffProviderFactoryService) {
            super();
            this.model = model;
            this._options = _options;
            this._diffProviderFactoryService = _diffProviderFactoryService;
            this._isDiffUpToDate = (0, observable_1.observableValue)(this, false);
            this.isDiffUpToDate = this._isDiffUpToDate;
            this._diff = (0, observable_1.observableValue)(this, undefined);
            this.diff = this._diff;
            this._unchangedRegions = (0, observable_1.observableValue)(this, undefined);
            this.unchangedRegions = (0, observable_1.derived)(this, r => {
                if (this._options.hideUnchangedRegions.read(r)) {
                    return this._unchangedRegions.read(r)?.regions ?? [];
                }
                else {
                    // Reset state
                    (0, observable_1.transaction)(tx => {
                        for (const r of this._unchangedRegions.get()?.regions || []) {
                            r.collapseAll(tx);
                        }
                    });
                    return [];
                }
            });
            this.movedTextToCompare = (0, observable_1.observableValue)(this, undefined);
            this._activeMovedText = (0, observable_1.observableValue)(this, undefined);
            this._hoveredMovedText = (0, observable_1.observableValue)(this, undefined);
            this.activeMovedText = (0, observable_1.derived)(this, r => this.movedTextToCompare.read(r) ?? this._hoveredMovedText.read(r) ?? this._activeMovedText.read(r));
            this._cancellationTokenSource = new cancellation_1.CancellationTokenSource();
            this._diffProvider = (0, observable_1.derived)(this, reader => {
                const diffProvider = this._diffProviderFactoryService.createDiffProvider({
                    diffAlgorithm: this._options.diffAlgorithm.read(reader)
                });
                const onChangeSignal = (0, observable_1.observableSignalFromEvent)('onDidChange', diffProvider.onDidChange);
                return {
                    diffProvider,
                    onChangeSignal,
                };
            });
            this._register((0, lifecycle_1.toDisposable)(() => this._cancellationTokenSource.cancel()));
            const contentChangedSignal = (0, observable_1.observableSignal)('contentChangedSignal');
            const debouncer = this._register(new async_1.RunOnceScheduler(() => contentChangedSignal.trigger(undefined), 200));
            this._register((0, observable_1.autorun)(reader => {
                /** @description collapse touching unchanged ranges */
                const lastUnchangedRegions = this._unchangedRegions.read(reader);
                if (!lastUnchangedRegions || lastUnchangedRegions.regions.some(r => r.isDragged.read(reader))) {
                    return;
                }
                const lastUnchangedRegionsOrigRanges = lastUnchangedRegions.originalDecorationIds
                    .map(id => model.original.getDecorationRange(id))
                    .map(r => r ? lineRange_1.LineRange.fromRangeInclusive(r) : undefined);
                const lastUnchangedRegionsModRanges = lastUnchangedRegions.modifiedDecorationIds
                    .map(id => model.modified.getDecorationRange(id))
                    .map(r => r ? lineRange_1.LineRange.fromRangeInclusive(r) : undefined);
                const updatedLastUnchangedRegions = lastUnchangedRegions.regions.map((r, idx) => (!lastUnchangedRegionsOrigRanges[idx] || !lastUnchangedRegionsModRanges[idx]) ? undefined :
                    new UnchangedRegion(lastUnchangedRegionsOrigRanges[idx].startLineNumber, lastUnchangedRegionsModRanges[idx].startLineNumber, lastUnchangedRegionsOrigRanges[idx].length, r.visibleLineCountTop.read(reader), r.visibleLineCountBottom.read(reader))).filter(types_1.isDefined);
                const newRanges = [];
                let didChange = false;
                for (const touching of (0, arrays_1.groupAdjacentBy)(updatedLastUnchangedRegions, (a, b) => a.getHiddenModifiedRange(reader).endLineNumberExclusive === b.getHiddenModifiedRange(reader).startLineNumber)) {
                    if (touching.length > 1) {
                        didChange = true;
                        const sumLineCount = touching.reduce((sum, r) => sum + r.lineCount, 0);
                        const r = new UnchangedRegion(touching[0].originalLineNumber, touching[0].modifiedLineNumber, sumLineCount, touching[0].visibleLineCountTop.get(), touching[touching.length - 1].visibleLineCountBottom.get());
                        newRanges.push(r);
                    }
                    else {
                        newRanges.push(touching[0]);
                    }
                }
                if (didChange) {
                    const originalDecorationIds = model.original.deltaDecorations(lastUnchangedRegions.originalDecorationIds, newRanges.map(r => ({ range: r.originalUnchangedRange.toInclusiveRange(), options: { description: 'unchanged' } })));
                    const modifiedDecorationIds = model.modified.deltaDecorations(lastUnchangedRegions.modifiedDecorationIds, newRanges.map(r => ({ range: r.modifiedUnchangedRange.toInclusiveRange(), options: { description: 'unchanged' } })));
                    (0, observable_1.transaction)(tx => {
                        this._unchangedRegions.set({
                            regions: newRanges,
                            originalDecorationIds,
                            modifiedDecorationIds
                        }, tx);
                    });
                }
            }));
            const updateUnchangedRegions = (result, tx, reader) => {
                const newUnchangedRegions = UnchangedRegion.fromDiffs(result.changes, model.original.getLineCount(), model.modified.getLineCount(), this._options.hideUnchangedRegionsMinimumLineCount.read(reader), this._options.hideUnchangedRegionsContextLineCount.read(reader));
                // Transfer state from cur state
                let visibleRegions = undefined;
                const lastUnchangedRegions = this._unchangedRegions.get();
                if (lastUnchangedRegions) {
                    const lastUnchangedRegionsOrigRanges = lastUnchangedRegions.originalDecorationIds
                        .map(id => model.original.getDecorationRange(id))
                        .map(r => r ? lineRange_1.LineRange.fromRangeInclusive(r) : undefined);
                    const lastUnchangedRegionsModRanges = lastUnchangedRegions.modifiedDecorationIds
                        .map(id => model.modified.getDecorationRange(id))
                        .map(r => r ? lineRange_1.LineRange.fromRangeInclusive(r) : undefined);
                    const updatedLastUnchangedRegions = (0, utils_1.filterWithPrevious)(lastUnchangedRegions.regions
                        .map((r, idx) => {
                        if (!lastUnchangedRegionsOrigRanges[idx] || !lastUnchangedRegionsModRanges[idx]) {
                            return undefined;
                        }
                        const length = lastUnchangedRegionsOrigRanges[idx].length;
                        return new UnchangedRegion(lastUnchangedRegionsOrigRanges[idx].startLineNumber, lastUnchangedRegionsModRanges[idx].startLineNumber, length, 
                        // The visible area can shrink by edits -> we have to account for this
                        Math.min(r.visibleLineCountTop.get(), length), Math.min(r.visibleLineCountBottom.get(), length - r.visibleLineCountTop.get()));
                    }).filter(types_1.isDefined), (cur, prev) => !prev || (cur.modifiedLineNumber >= prev.modifiedLineNumber + prev.lineCount && cur.originalLineNumber >= prev.originalLineNumber + prev.lineCount));
                    let hiddenRegions = updatedLastUnchangedRegions.map(r => new rangeMapping_1.LineRangeMapping(r.getHiddenOriginalRange(reader), r.getHiddenModifiedRange(reader)));
                    hiddenRegions = rangeMapping_1.LineRangeMapping.clip(hiddenRegions, lineRange_1.LineRange.ofLength(1, model.original.getLineCount()), lineRange_1.LineRange.ofLength(1, model.modified.getLineCount()));
                    visibleRegions = rangeMapping_1.LineRangeMapping.inverse(hiddenRegions, model.original.getLineCount(), model.modified.getLineCount());
                }
                const newUnchangedRegions2 = [];
                if (visibleRegions) {
                    for (const r of newUnchangedRegions) {
                        const intersecting = visibleRegions.filter(f => f.original.intersectsStrict(r.originalUnchangedRange) && f.modified.intersectsStrict(r.modifiedUnchangedRange));
                        newUnchangedRegions2.push(...r.setVisibleRanges(intersecting, tx));
                    }
                }
                else {
                    newUnchangedRegions2.push(...newUnchangedRegions);
                }
                const originalDecorationIds = model.original.deltaDecorations(lastUnchangedRegions?.originalDecorationIds || [], newUnchangedRegions2.map(r => ({ range: r.originalUnchangedRange.toInclusiveRange(), options: { description: 'unchanged' } })));
                const modifiedDecorationIds = model.modified.deltaDecorations(lastUnchangedRegions?.modifiedDecorationIds || [], newUnchangedRegions2.map(r => ({ range: r.modifiedUnchangedRange.toInclusiveRange(), options: { description: 'unchanged' } })));
                this._unchangedRegions.set({
                    regions: newUnchangedRegions2,
                    originalDecorationIds,
                    modifiedDecorationIds
                }, tx);
            };
            this._register(model.modified.onDidChangeContent((e) => {
                const diff = this._diff.get();
                if (diff) {
                    const textEdits = beforeEditPositionMapper_1.TextEditInfo.fromModelContentChanges(e.changes);
                    const result = applyModifiedEdits(this._lastDiff, textEdits, model.original, model.modified);
                    if (result) {
                        this._lastDiff = result;
                        (0, observable_1.transaction)(tx => {
                            this._diff.set(DiffState.fromDiffResult(this._lastDiff), tx);
                            updateUnchangedRegions(result, tx);
                            const currentSyncedMovedText = this.movedTextToCompare.get();
                            this.movedTextToCompare.set(currentSyncedMovedText ? this._lastDiff.moves.find(m => m.lineRangeMapping.modified.intersect(currentSyncedMovedText.lineRangeMapping.modified)) : undefined, tx);
                        });
                    }
                }
                this._isDiffUpToDate.set(false, undefined);
                debouncer.schedule();
            }));
            this._register(model.original.onDidChangeContent((e) => {
                const diff = this._diff.get();
                if (diff) {
                    const textEdits = beforeEditPositionMapper_1.TextEditInfo.fromModelContentChanges(e.changes);
                    const result = applyOriginalEdits(this._lastDiff, textEdits, model.original, model.modified);
                    if (result) {
                        this._lastDiff = result;
                        (0, observable_1.transaction)(tx => {
                            this._diff.set(DiffState.fromDiffResult(this._lastDiff), tx);
                            updateUnchangedRegions(result, tx);
                            const currentSyncedMovedText = this.movedTextToCompare.get();
                            this.movedTextToCompare.set(currentSyncedMovedText ? this._lastDiff.moves.find(m => m.lineRangeMapping.modified.intersect(currentSyncedMovedText.lineRangeMapping.modified)) : undefined, tx);
                        });
                    }
                }
                this._isDiffUpToDate.set(false, undefined);
                debouncer.schedule();
            }));
            this._register((0, observable_1.autorunWithStore)(async (reader, store) => {
                /** @description compute diff */
                // So that they get recomputed when these settings change
                this._options.hideUnchangedRegionsMinimumLineCount.read(reader);
                this._options.hideUnchangedRegionsContextLineCount.read(reader);
                debouncer.cancel();
                contentChangedSignal.read(reader);
                const documentDiffProvider = this._diffProvider.read(reader);
                documentDiffProvider.onChangeSignal.read(reader);
                (0, hotReloadHelpers_1.readHotReloadableExport)(defaultLinesDiffComputer_1.DefaultLinesDiffComputer, reader);
                (0, hotReloadHelpers_1.readHotReloadableExport)(heuristicSequenceOptimizations_1.optimizeSequenceDiffs, reader);
                this._isDiffUpToDate.set(false, undefined);
                let originalTextEditInfos = [];
                store.add(model.original.onDidChangeContent((e) => {
                    const edits = beforeEditPositionMapper_1.TextEditInfo.fromModelContentChanges(e.changes);
                    originalTextEditInfos = (0, combineTextEditInfos_1.combineTextEditInfos)(originalTextEditInfos, edits);
                }));
                let modifiedTextEditInfos = [];
                store.add(model.modified.onDidChangeContent((e) => {
                    const edits = beforeEditPositionMapper_1.TextEditInfo.fromModelContentChanges(e.changes);
                    modifiedTextEditInfos = (0, combineTextEditInfos_1.combineTextEditInfos)(modifiedTextEditInfos, edits);
                }));
                let result = await documentDiffProvider.diffProvider.computeDiff(model.original, model.modified, {
                    ignoreTrimWhitespace: this._options.ignoreTrimWhitespace.read(reader),
                    maxComputationTimeMs: this._options.maxComputationTimeMs.read(reader),
                    computeMoves: this._options.showMoves.read(reader),
                }, this._cancellationTokenSource.token);
                if (this._cancellationTokenSource.token.isCancellationRequested) {
                    return;
                }
                if (model.original.isDisposed() || model.modified.isDisposed()) {
                    // TODO@hediet fishy?
                    return;
                }
                result = normalizeDocumentDiff(result, model.original, model.modified);
                result = applyOriginalEdits(result, originalTextEditInfos, model.original, model.modified) ?? result;
                result = applyModifiedEdits(result, modifiedTextEditInfos, model.original, model.modified) ?? result;
                (0, observable_1.transaction)(tx => {
                    /** @description write diff result */
                    updateUnchangedRegions(result, tx);
                    this._lastDiff = result;
                    const state = DiffState.fromDiffResult(result);
                    this._diff.set(state, tx);
                    this._isDiffUpToDate.set(true, tx);
                    const currentSyncedMovedText = this.movedTextToCompare.get();
                    this.movedTextToCompare.set(currentSyncedMovedText ? this._lastDiff.moves.find(m => m.lineRangeMapping.modified.intersect(currentSyncedMovedText.lineRangeMapping.modified)) : undefined, tx);
                });
            }));
        }
        ensureModifiedLineIsVisible(lineNumber, preference, tx) {
            if (this.diff.get()?.mappings.length === 0) {
                return;
            }
            const unchangedRegions = this._unchangedRegions.get()?.regions || [];
            for (const r of unchangedRegions) {
                if (r.getHiddenModifiedRange(undefined).contains(lineNumber)) {
                    r.showModifiedLine(lineNumber, preference, tx);
                    return;
                }
            }
        }
        ensureOriginalLineIsVisible(lineNumber, preference, tx) {
            if (this.diff.get()?.mappings.length === 0) {
                return;
            }
            const unchangedRegions = this._unchangedRegions.get()?.regions || [];
            for (const r of unchangedRegions) {
                if (r.getHiddenOriginalRange(undefined).contains(lineNumber)) {
                    r.showOriginalLine(lineNumber, preference, tx);
                    return;
                }
            }
        }
        async waitForDiff() {
            await (0, observable_1.waitForState)(this.isDiffUpToDate, s => s);
        }
        serializeState() {
            const regions = this._unchangedRegions.get();
            return {
                collapsedRegions: regions?.regions.map(r => ({ range: r.getHiddenModifiedRange(undefined).serialize() }))
            };
        }
        restoreSerializedState(state) {
            const ranges = state.collapsedRegions?.map(r => lineRange_1.LineRange.deserialize(r.range));
            const regions = this._unchangedRegions.get();
            if (!regions || !ranges) {
                return;
            }
            (0, observable_1.transaction)(tx => {
                for (const r of regions.regions) {
                    for (const range of ranges) {
                        if (r.modifiedUnchangedRange.intersect(range)) {
                            r.setHiddenModifiedRange(range, tx);
                            break;
                        }
                    }
                }
            });
        }
    };
    exports.DiffEditorViewModel = DiffEditorViewModel;
    exports.DiffEditorViewModel = DiffEditorViewModel = __decorate([
        __param(2, diffProviderFactoryService_1.IDiffProviderFactoryService)
    ], DiffEditorViewModel);
    function normalizeDocumentDiff(diff, original, modified) {
        return {
            changes: diff.changes.map(c => new rangeMapping_1.DetailedLineRangeMapping(c.original, c.modified, c.innerChanges ? c.innerChanges.map(i => normalizeRangeMapping(i, original, modified)) : undefined)),
            moves: diff.moves,
            identical: diff.identical,
            quitEarly: diff.quitEarly,
        };
    }
    function normalizeRangeMapping(rangeMapping, original, modified) {
        let originalRange = rangeMapping.originalRange;
        let modifiedRange = rangeMapping.modifiedRange;
        if (originalRange.startColumn === 1 && modifiedRange.startColumn === 1 &&
            (originalRange.endColumn !== 1 || modifiedRange.endColumn !== 1) &&
            originalRange.endColumn === original.getLineMaxColumn(originalRange.endLineNumber)
            && modifiedRange.endColumn === modified.getLineMaxColumn(modifiedRange.endLineNumber)
            && originalRange.endLineNumber < original.getLineCount()
            && modifiedRange.endLineNumber < modified.getLineCount()) {
            originalRange = originalRange.setEndPosition(originalRange.endLineNumber + 1, 1);
            modifiedRange = modifiedRange.setEndPosition(modifiedRange.endLineNumber + 1, 1);
        }
        return new rangeMapping_1.RangeMapping(originalRange, modifiedRange);
    }
    class DiffState {
        static fromDiffResult(result) {
            return new DiffState(result.changes.map(c => new DiffMapping(c)), result.moves || [], result.identical, result.quitEarly);
        }
        constructor(mappings, movedTexts, identical, quitEarly) {
            this.mappings = mappings;
            this.movedTexts = movedTexts;
            this.identical = identical;
            this.quitEarly = quitEarly;
        }
    }
    exports.DiffState = DiffState;
    class DiffMapping {
        constructor(lineRangeMapping) {
            this.lineRangeMapping = lineRangeMapping;
            /*
            readonly movedTo: MovedText | undefined,
            readonly movedFrom: MovedText | undefined,
    
            if (movedTo) {
                assertFn(() =>
                    movedTo.lineRangeMapping.modifiedRange.equals(lineRangeMapping.modifiedRange)
                    && lineRangeMapping.originalRange.isEmpty
                    && !movedFrom
                );
            } else if (movedFrom) {
                assertFn(() =>
                    movedFrom.lineRangeMapping.originalRange.equals(lineRangeMapping.originalRange)
                    && lineRangeMapping.modifiedRange.isEmpty
                    && !movedTo
                );
            }
            */
        }
    }
    exports.DiffMapping = DiffMapping;
    class UnchangedRegion {
        static fromDiffs(changes, originalLineCount, modifiedLineCount, minHiddenLineCount, minContext) {
            const inversedMappings = rangeMapping_1.DetailedLineRangeMapping.inverse(changes, originalLineCount, modifiedLineCount);
            const result = [];
            for (const mapping of inversedMappings) {
                let origStart = mapping.original.startLineNumber;
                let modStart = mapping.modified.startLineNumber;
                let length = mapping.original.length;
                const atStart = origStart === 1 && modStart === 1;
                const atEnd = origStart + length === originalLineCount + 1 && modStart + length === modifiedLineCount + 1;
                if ((atStart || atEnd) && length >= minContext + minHiddenLineCount) {
                    if (atStart && !atEnd) {
                        length -= minContext;
                    }
                    if (atEnd && !atStart) {
                        origStart += minContext;
                        modStart += minContext;
                        length -= minContext;
                    }
                    result.push(new UnchangedRegion(origStart, modStart, length, 0, 0));
                }
                else if (length >= minContext * 2 + minHiddenLineCount) {
                    origStart += minContext;
                    modStart += minContext;
                    length -= minContext * 2;
                    result.push(new UnchangedRegion(origStart, modStart, length, 0, 0));
                }
            }
            return result;
        }
        get originalUnchangedRange() {
            return lineRange_1.LineRange.ofLength(this.originalLineNumber, this.lineCount);
        }
        get modifiedUnchangedRange() {
            return lineRange_1.LineRange.ofLength(this.modifiedLineNumber, this.lineCount);
        }
        constructor(originalLineNumber, modifiedLineNumber, lineCount, visibleLineCountTop, visibleLineCountBottom) {
            this.originalLineNumber = originalLineNumber;
            this.modifiedLineNumber = modifiedLineNumber;
            this.lineCount = lineCount;
            this._visibleLineCountTop = (0, observable_1.observableValue)(this, 0);
            this.visibleLineCountTop = this._visibleLineCountTop;
            this._visibleLineCountBottom = (0, observable_1.observableValue)(this, 0);
            this.visibleLineCountBottom = this._visibleLineCountBottom;
            this._shouldHideControls = (0, observable_1.derived)(this, reader => /** @description isVisible */ this.visibleLineCountTop.read(reader) + this.visibleLineCountBottom.read(reader) === this.lineCount && !this.isDragged.read(reader));
            this.isDragged = (0, observable_1.observableValue)(this, undefined);
            const visibleLineCountTop2 = Math.max(Math.min(visibleLineCountTop, this.lineCount), 0);
            const visibleLineCountBottom2 = Math.max(Math.min(visibleLineCountBottom, this.lineCount - visibleLineCountTop), 0);
            (0, assert_1.softAssert)(visibleLineCountTop === visibleLineCountTop2);
            (0, assert_1.softAssert)(visibleLineCountBottom === visibleLineCountBottom2);
            this._visibleLineCountTop.set(visibleLineCountTop2, undefined);
            this._visibleLineCountBottom.set(visibleLineCountBottom2, undefined);
        }
        setVisibleRanges(visibleRanges, tx) {
            const result = [];
            const hiddenModified = new lineRange_1.LineRangeSet(visibleRanges.map(r => r.modified)).subtractFrom(this.modifiedUnchangedRange);
            let originalStartLineNumber = this.originalLineNumber;
            let modifiedStartLineNumber = this.modifiedLineNumber;
            const modifiedEndLineNumberEx = this.modifiedLineNumber + this.lineCount;
            if (hiddenModified.ranges.length === 0) {
                this.showAll(tx);
                result.push(this);
            }
            else {
                let i = 0;
                for (const r of hiddenModified.ranges) {
                    const isLast = i === hiddenModified.ranges.length - 1;
                    i++;
                    const length = (isLast ? modifiedEndLineNumberEx : r.endLineNumberExclusive) - modifiedStartLineNumber;
                    const newR = new UnchangedRegion(originalStartLineNumber, modifiedStartLineNumber, length, 0, 0);
                    newR.setHiddenModifiedRange(r, tx);
                    result.push(newR);
                    originalStartLineNumber = newR.originalUnchangedRange.endLineNumberExclusive;
                    modifiedStartLineNumber = newR.modifiedUnchangedRange.endLineNumberExclusive;
                }
            }
            return result;
        }
        shouldHideControls(reader) {
            return this._shouldHideControls.read(reader);
        }
        getHiddenOriginalRange(reader) {
            return lineRange_1.LineRange.ofLength(this.originalLineNumber + this._visibleLineCountTop.read(reader), this.lineCount - this._visibleLineCountTop.read(reader) - this._visibleLineCountBottom.read(reader));
        }
        getHiddenModifiedRange(reader) {
            return lineRange_1.LineRange.ofLength(this.modifiedLineNumber + this._visibleLineCountTop.read(reader), this.lineCount - this._visibleLineCountTop.read(reader) - this._visibleLineCountBottom.read(reader));
        }
        setHiddenModifiedRange(range, tx) {
            const visibleLineCountTop = range.startLineNumber - this.modifiedLineNumber;
            const visibleLineCountBottom = (this.modifiedLineNumber + this.lineCount) - range.endLineNumberExclusive;
            this.setState(visibleLineCountTop, visibleLineCountBottom, tx);
        }
        getMaxVisibleLineCountTop() {
            return this.lineCount - this._visibleLineCountBottom.get();
        }
        getMaxVisibleLineCountBottom() {
            return this.lineCount - this._visibleLineCountTop.get();
        }
        showMoreAbove(count = 10, tx) {
            const maxVisibleLineCountTop = this.getMaxVisibleLineCountTop();
            this._visibleLineCountTop.set(Math.min(this._visibleLineCountTop.get() + count, maxVisibleLineCountTop), tx);
        }
        showMoreBelow(count = 10, tx) {
            const maxVisibleLineCountBottom = this.lineCount - this._visibleLineCountTop.get();
            this._visibleLineCountBottom.set(Math.min(this._visibleLineCountBottom.get() + count, maxVisibleLineCountBottom), tx);
        }
        showAll(tx) {
            this._visibleLineCountBottom.set(this.lineCount - this._visibleLineCountTop.get(), tx);
        }
        showModifiedLine(lineNumber, preference, tx) {
            const top = lineNumber + 1 - (this.modifiedLineNumber + this._visibleLineCountTop.get());
            const bottom = (this.modifiedLineNumber - this._visibleLineCountBottom.get() + this.lineCount) - lineNumber;
            if (preference === 0 /* RevealPreference.FromCloserSide */ && top < bottom || preference === 1 /* RevealPreference.FromTop */) {
                this._visibleLineCountTop.set(this._visibleLineCountTop.get() + top, tx);
            }
            else {
                this._visibleLineCountBottom.set(this._visibleLineCountBottom.get() + bottom, tx);
            }
        }
        showOriginalLine(lineNumber, preference, tx) {
            const top = lineNumber - this.originalLineNumber;
            const bottom = (this.originalLineNumber + this.lineCount) - lineNumber;
            if (preference === 0 /* RevealPreference.FromCloserSide */ && top < bottom || preference === 1 /* RevealPreference.FromTop */) {
                this._visibleLineCountTop.set(Math.min(this._visibleLineCountTop.get() + bottom - top, this.getMaxVisibleLineCountTop()), tx);
            }
            else {
                this._visibleLineCountBottom.set(Math.min(this._visibleLineCountBottom.get() + top - bottom, this.getMaxVisibleLineCountBottom()), tx);
            }
        }
        collapseAll(tx) {
            this._visibleLineCountTop.set(0, tx);
            this._visibleLineCountBottom.set(0, tx);
        }
        setState(visibleLineCountTop, visibleLineCountBottom, tx) {
            visibleLineCountTop = Math.max(Math.min(visibleLineCountTop, this.lineCount), 0);
            visibleLineCountBottom = Math.max(Math.min(visibleLineCountBottom, this.lineCount - visibleLineCountTop), 0);
            this._visibleLineCountTop.set(visibleLineCountTop, tx);
            this._visibleLineCountBottom.set(visibleLineCountBottom, tx);
        }
    }
    exports.UnchangedRegion = UnchangedRegion;
    function applyOriginalEdits(diff, textEdits, originalTextModel, modifiedTextModel) {
        return undefined;
        /*
        TODO@hediet
        if (textEdits.length === 0) {
            return diff;
        }
    
        const diff2 = flip(diff);
        const diff3 = applyModifiedEdits(diff2, textEdits, modifiedTextModel, originalTextModel);
        if (!diff3) {
            return undefined;
        }
        return flip(diff3);*/
    }
    /*
    function flip(diff: IDocumentDiff): IDocumentDiff {
        return {
            changes: diff.changes.map(c => c.flip()),
            moves: diff.moves.map(m => m.flip()),
            identical: diff.identical,
            quitEarly: diff.quitEarly,
        };
    }
    */
    function applyModifiedEdits(diff, textEdits, originalTextModel, modifiedTextModel) {
        return undefined;
        /*
        TODO@hediet
        if (textEdits.length === 0) {
            return diff;
        }
        if (diff.changes.some(c => !c.innerChanges) || diff.moves.length > 0) {
            // TODO support these cases
            return undefined;
        }
    
        const changes = applyModifiedEditsToLineRangeMappings(diff.changes, textEdits, originalTextModel, modifiedTextModel);
    
        const moves = diff.moves.map(m => {
            const newModifiedRange = applyEditToLineRange(m.lineRangeMapping.modified, textEdits);
            return newModifiedRange ? new MovedText(
                new SimpleLineRangeMapping(m.lineRangeMapping.original, newModifiedRange),
                applyModifiedEditsToLineRangeMappings(m.changes, textEdits, originalTextModel, modifiedTextModel),
            ) : undefined;
        }).filter(isDefined);
    
        return {
            identical: false,
            quitEarly: false,
            changes,
            moves,
        };*/
    }
});
/*
function applyEditToLineRange(range: LineRange, textEdits: TextEditInfo[]): LineRange | undefined {
    let rangeStartLineNumber = range.startLineNumber;
    let rangeEndLineNumberEx = range.endLineNumberExclusive;

    for (let i = textEdits.length - 1; i >= 0; i--) {
        const textEdit = textEdits[i];
        const textEditStartLineNumber = lengthGetLineCount(textEdit.startOffset) + 1;
        const textEditEndLineNumber = lengthGetLineCount(textEdit.endOffset) + 1;
        const newLengthLineCount = lengthGetLineCount(textEdit.newLength);
        const delta = newLengthLineCount - (textEditEndLineNumber - textEditStartLineNumber);

        if (textEditEndLineNumber < rangeStartLineNumber) {
            // the text edit is before us
            rangeStartLineNumber += delta;
            rangeEndLineNumberEx += delta;
        } else if (textEditStartLineNumber > rangeEndLineNumberEx) {
            // the text edit is after us
            // NOOP
        } else if (textEditStartLineNumber < rangeStartLineNumber && rangeEndLineNumberEx < textEditEndLineNumber) {
            // the range is fully contained in the text edit
            return undefined;
        } else if (textEditStartLineNumber < rangeStartLineNumber && textEditEndLineNumber <= rangeEndLineNumberEx) {
            // the text edit ends inside our range
            rangeStartLineNumber = textEditEndLineNumber + 1;
            rangeStartLineNumber += delta;
            rangeEndLineNumberEx += delta;
        } else if (rangeStartLineNumber <= textEditStartLineNumber && textEditEndLineNumber < rangeStartLineNumber) {
            // the text edit starts inside our range
            rangeEndLineNumberEx = textEditStartLineNumber;
        } else {
            rangeEndLineNumberEx += delta;
        }
    }

    return new LineRange(rangeStartLineNumber, rangeEndLineNumberEx);
}

function applyModifiedEditsToLineRangeMappings(changes: readonly LineRangeMapping[], textEdits: TextEditInfo[], originalTextModel: ITextModel, modifiedTextModel: ITextModel): LineRangeMapping[] {
    const diffTextEdits = changes.flatMap(c => c.innerChanges!.map(c => new TextEditInfo(
        positionToLength(c.originalRange.getStartPosition()),
        positionToLength(c.originalRange.getEndPosition()),
        lengthOfRange(c.modifiedRange).toLength(),
    )));

    const combined = combineTextEditInfos(diffTextEdits, textEdits);

    let lastOriginalEndOffset = lengthZero;
    let lastModifiedEndOffset = lengthZero;
    const rangeMappings = combined.map(c => {
        const modifiedStartOffset = lengthAdd(lastModifiedEndOffset, lengthDiffNonNegative(lastOriginalEndOffset, c.startOffset));
        lastOriginalEndOffset = c.endOffset;
        lastModifiedEndOffset = lengthAdd(modifiedStartOffset, c.newLength);

        return new RangeMapping(
            Range.fromPositions(lengthToPosition(c.startOffset), lengthToPosition(c.endOffset)),
            Range.fromPositions(lengthToPosition(modifiedStartOffset), lengthToPosition(lastModifiedEndOffset)),
        );
    });

    const newChanges = lineRangeMappingFromRangeMappings(
        rangeMappings,
        originalTextModel.getLinesContent(),
        modifiedTextModel.getLinesContent(),
    );
    return newChanges;
}
*/

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[727/*vs/editor/contrib/anchorSelect/browser/anchorSelect*/], __M([1/*require*/,0/*exports*/,46/*vs/base/browser/ui/aria/aria*/,57/*vs/base/common/htmlContent*/,72/*vs/base/common/keyCodes*/,15/*vs/editor/browser/editorExtensions*/,23/*vs/editor/common/core/selection*/,20/*vs/editor/common/editorContextKeys*/,3/*vs/nls*/,12/*vs/platform/contextkey/common/contextkey*/,503/*vs/css!vs/editor/contrib/anchorSelect/browser/anchorSelect*/]), function (require, exports, aria_1, htmlContent_1, keyCodes_1, editorExtensions_1, selection_1, editorContextKeys_1, nls_1, contextkey_1) {
    "use strict";
    var SelectionAnchorController_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SelectionAnchorSet = void 0;
    exports.SelectionAnchorSet = new contextkey_1.RawContextKey('selectionAnchorSet', false);
    let SelectionAnchorController = class SelectionAnchorController {
        static { SelectionAnchorController_1 = this; }
        static { this.ID = 'editor.contrib.selectionAnchorController'; }
        static get(editor) {
            return editor.getContribution(SelectionAnchorController_1.ID);
        }
        constructor(editor, contextKeyService) {
            this.editor = editor;
            this.selectionAnchorSetContextKey = exports.SelectionAnchorSet.bindTo(contextKeyService);
            this.modelChangeListener = editor.onDidChangeModel(() => this.selectionAnchorSetContextKey.reset());
        }
        setSelectionAnchor() {
            if (this.editor.hasModel()) {
                const position = this.editor.getPosition();
                this.editor.changeDecorations((accessor) => {
                    if (this.decorationId) {
                        accessor.removeDecoration(this.decorationId);
                    }
                    this.decorationId = accessor.addDecoration(selection_1.Selection.fromPositions(position, position), {
                        description: 'selection-anchor',
                        stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */,
                        hoverMessage: new htmlContent_1.MarkdownString().appendText((0, nls_1.localize)(710, "Selection Anchor")),
                        className: 'selection-anchor'
                    });
                });
                this.selectionAnchorSetContextKey.set(!!this.decorationId);
                (0, aria_1.alert)((0, nls_1.localize)(711, "Anchor set at {0}:{1}", position.lineNumber, position.column));
            }
        }
        goToSelectionAnchor() {
            if (this.editor.hasModel() && this.decorationId) {
                const anchorPosition = this.editor.getModel().getDecorationRange(this.decorationId);
                if (anchorPosition) {
                    this.editor.setPosition(anchorPosition.getStartPosition());
                }
            }
        }
        selectFromAnchorToCursor() {
            if (this.editor.hasModel() && this.decorationId) {
                const start = this.editor.getModel().getDecorationRange(this.decorationId);
                if (start) {
                    const end = this.editor.getPosition();
                    this.editor.setSelection(selection_1.Selection.fromPositions(start.getStartPosition(), end));
                    this.cancelSelectionAnchor();
                }
            }
        }
        cancelSelectionAnchor() {
            if (this.decorationId) {
                const decorationId = this.decorationId;
                this.editor.changeDecorations((accessor) => {
                    accessor.removeDecoration(decorationId);
                    this.decorationId = undefined;
                });
                this.selectionAnchorSetContextKey.set(false);
            }
        }
        dispose() {
            this.cancelSelectionAnchor();
            this.modelChangeListener.dispose();
        }
    };
    SelectionAnchorController = SelectionAnchorController_1 = __decorate([
        __param(1, contextkey_1.IContextKeyService)
    ], SelectionAnchorController);
    class SetSelectionAnchor extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: 'editor.action.setSelectionAnchor',
                label: (0, nls_1.localize)(712, "Set Selection Anchor"),
                alias: 'Set Selection Anchor',
                precondition: undefined,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    primary: (0, keyCodes_1.KeyChord)(2048 /* KeyMod.CtrlCmd */ | 41 /* KeyCode.KeyK */, 2048 /* KeyMod.CtrlCmd */ | 32 /* KeyCode.KeyB */),
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
        async run(_accessor, editor) {
            SelectionAnchorController.get(editor)?.setSelectionAnchor();
        }
    }
    class GoToSelectionAnchor extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: 'editor.action.goToSelectionAnchor',
                label: (0, nls_1.localize)(713, "Go to Selection Anchor"),
                alias: 'Go to Selection Anchor',
                precondition: exports.SelectionAnchorSet,
            });
        }
        async run(_accessor, editor) {
            SelectionAnchorController.get(editor)?.goToSelectionAnchor();
        }
    }
    class SelectFromAnchorToCursor extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: 'editor.action.selectFromAnchorToCursor',
                label: (0, nls_1.localize)(714, "Select from Anchor to Cursor"),
                alias: 'Select from Anchor to Cursor',
                precondition: exports.SelectionAnchorSet,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    primary: (0, keyCodes_1.KeyChord)(2048 /* KeyMod.CtrlCmd */ | 41 /* KeyCode.KeyK */, 2048 /* KeyMod.CtrlCmd */ | 41 /* KeyCode.KeyK */),
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
        async run(_accessor, editor) {
            SelectionAnchorController.get(editor)?.selectFromAnchorToCursor();
        }
    }
    class CancelSelectionAnchor extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: 'editor.action.cancelSelectionAnchor',
                label: (0, nls_1.localize)(715, "Cancel Selection Anchor"),
                alias: 'Cancel Selection Anchor',
                precondition: exports.SelectionAnchorSet,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    primary: 9 /* KeyCode.Escape */,
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
        async run(_accessor, editor) {
            SelectionAnchorController.get(editor)?.cancelSelectionAnchor();
        }
    }
    (0, editorExtensions_1.registerEditorContribution)(SelectionAnchorController.ID, SelectionAnchorController, 4 /* EditorContributionInstantiation.Lazy */);
    (0, editorExtensions_1.registerEditorAction)(SetSelectionAnchor);
    (0, editorExtensions_1.registerEditorAction)(GoToSelectionAnchor);
    (0, editorExtensions_1.registerEditorAction)(SelectFromAnchorToCursor);
    (0, editorExtensions_1.registerEditorAction)(CancelSelectionAnchor);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[728/*vs/editor/contrib/caretOperations/browser/caretOperations*/], __M([1/*require*/,0/*exports*/,15/*vs/editor/browser/editorExtensions*/,20/*vs/editor/common/editorContextKeys*/,607/*vs/editor/contrib/caretOperations/browser/moveCaretCommand*/,3/*vs/nls*/]), function (require, exports, editorExtensions_1, editorContextKeys_1, moveCaretCommand_1, nls) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    class MoveCaretAction extends editorExtensions_1.EditorAction {
        constructor(left, opts) {
            super(opts);
            this.left = left;
        }
        run(accessor, editor) {
            if (!editor.hasModel()) {
                return;
            }
            const commands = [];
            const selections = editor.getSelections();
            for (const selection of selections) {
                commands.push(new moveCaretCommand_1.MoveCaretCommand(selection, this.left));
            }
            editor.pushUndoStop();
            editor.executeCommands(this.id, commands);
            editor.pushUndoStop();
        }
    }
    class MoveCaretLeftAction extends MoveCaretAction {
        constructor() {
            super(true, {
                id: 'editor.action.moveCarretLeftAction',
                label: nls.localize(722, "Move Selected Text Left"),
                alias: 'Move Selected Text Left',
                precondition: editorContextKeys_1.EditorContextKeys.writable
            });
        }
    }
    class MoveCaretRightAction extends MoveCaretAction {
        constructor() {
            super(false, {
                id: 'editor.action.moveCarretRightAction',
                label: nls.localize(723, "Move Selected Text Right"),
                alias: 'Move Selected Text Right',
                precondition: editorContextKeys_1.EditorContextKeys.writable
            });
        }
    }
    (0, editorExtensions_1.registerEditorAction)(MoveCaretLeftAction);
    (0, editorExtensions_1.registerEditorAction)(MoveCaretRightAction);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[729/*vs/editor/contrib/caretOperations/browser/transpose*/], __M([1/*require*/,0/*exports*/,15/*vs/editor/browser/editorExtensions*/,146/*vs/editor/common/commands/replaceCommand*/,233/*vs/editor/common/cursor/cursorMoveOperations*/,4/*vs/editor/common/core/range*/,20/*vs/editor/common/editorContextKeys*/,3/*vs/nls*/]), function (require, exports, editorExtensions_1, replaceCommand_1, cursorMoveOperations_1, range_1, editorContextKeys_1, nls) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    class TransposeLettersAction extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: 'editor.action.transposeLetters',
                label: nls.localize(724, "Transpose Letters"),
                alias: 'Transpose Letters',
                precondition: editorContextKeys_1.EditorContextKeys.writable,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                    primary: 0,
                    mac: {
                        primary: 256 /* KeyMod.WinCtrl */ | 50 /* KeyCode.KeyT */
                    },
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
        run(accessor, editor) {
            if (!editor.hasModel()) {
                return;
            }
            const model = editor.getModel();
            const commands = [];
            const selections = editor.getSelections();
            for (const selection of selections) {
                if (!selection.isEmpty()) {
                    continue;
                }
                const lineNumber = selection.startLineNumber;
                const column = selection.startColumn;
                const lastColumn = model.getLineMaxColumn(lineNumber);
                if (lineNumber === 1 && (column === 1 || (column === 2 && lastColumn === 2))) {
                    // at beginning of file, nothing to do
                    continue;
                }
                // handle special case: when at end of line, transpose left two chars
                // otherwise, transpose left and right chars
                const endPosition = (column === lastColumn) ?
                    selection.getPosition() :
                    cursorMoveOperations_1.MoveOperations.rightPosition(model, selection.getPosition().lineNumber, selection.getPosition().column);
                const middlePosition = cursorMoveOperations_1.MoveOperations.leftPosition(model, endPosition);
                const beginPosition = cursorMoveOperations_1.MoveOperations.leftPosition(model, middlePosition);
                const leftChar = model.getValueInRange(range_1.Range.fromPositions(beginPosition, middlePosition));
                const rightChar = model.getValueInRange(range_1.Range.fromPositions(middlePosition, endPosition));
                const replaceRange = range_1.Range.fromPositions(beginPosition, endPosition);
                commands.push(new replaceCommand_1.ReplaceCommand(replaceRange, rightChar + leftChar));
            }
            if (commands.length > 0) {
                editor.pushUndoStop();
                editor.executeCommands(this.id, commands);
                editor.pushUndoStop();
            }
        }
    }
    (0, editorExtensions_1.registerEditorAction)(TransposeLettersAction);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[730/*vs/editor/contrib/comment/browser/comment*/], __M([1/*require*/,0/*exports*/,72/*vs/base/common/keyCodes*/,15/*vs/editor/browser/editorExtensions*/,4/*vs/editor/common/core/range*/,20/*vs/editor/common/editorContextKeys*/,36/*vs/editor/common/languages/languageConfigurationRegistry*/,333/*vs/editor/contrib/comment/browser/blockCommentCommand*/,609/*vs/editor/contrib/comment/browser/lineCommentCommand*/,3/*vs/nls*/,29/*vs/platform/actions/common/actions*/]), function (require, exports, keyCodes_1, editorExtensions_1, range_1, editorContextKeys_1, languageConfigurationRegistry_1, blockCommentCommand_1, lineCommentCommand_1, nls, actions_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    class CommentLineAction extends editorExtensions_1.EditorAction {
        constructor(type, opts) {
            super(opts);
            this._type = type;
        }
        run(accessor, editor) {
            const languageConfigurationService = accessor.get(languageConfigurationRegistry_1.ILanguageConfigurationService);
            if (!editor.hasModel()) {
                return;
            }
            const model = editor.getModel();
            const commands = [];
            const modelOptions = model.getOptions();
            const commentsOptions = editor.getOption(23 /* EditorOption.comments */);
            const selections = editor.getSelections().map((selection, index) => ({ selection, index, ignoreFirstLine: false }));
            selections.sort((a, b) => range_1.Range.compareRangesUsingStarts(a.selection, b.selection));
            // Remove selections that would result in copying the same line
            let prev = selections[0];
            for (let i = 1; i < selections.length; i++) {
                const curr = selections[i];
                if (prev.selection.endLineNumber === curr.selection.startLineNumber) {
                    // these two selections would copy the same line
                    if (prev.index < curr.index) {
                        // prev wins
                        curr.ignoreFirstLine = true;
                    }
                    else {
                        // curr wins
                        prev.ignoreFirstLine = true;
                        prev = curr;
                    }
                }
            }
            for (const selection of selections) {
                commands.push(new lineCommentCommand_1.LineCommentCommand(languageConfigurationService, selection.selection, modelOptions.indentSize, this._type, commentsOptions.insertSpace, commentsOptions.ignoreEmptyLines, selection.ignoreFirstLine));
            }
            editor.pushUndoStop();
            editor.executeCommands(this.id, commands);
            editor.pushUndoStop();
        }
    }
    class ToggleCommentLineAction extends CommentLineAction {
        constructor() {
            super(0 /* Type.Toggle */, {
                id: 'editor.action.commentLine',
                label: nls.localize(805, "Toggle Line Comment"),
                alias: 'Toggle Line Comment',
                precondition: editorContextKeys_1.EditorContextKeys.writable,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    primary: 2048 /* KeyMod.CtrlCmd */ | 90 /* KeyCode.Slash */,
                    weight: 100 /* KeybindingWeight.EditorContrib */
                },
                menuOpts: {
                    menuId: actions_1.MenuId.MenubarEditMenu,
                    group: '5_insert',
                    title: nls.localize(806, "&&Toggle Line Comment"),
                    order: 1
                }
            });
        }
    }
    class AddLineCommentAction extends CommentLineAction {
        constructor() {
            super(1 /* Type.ForceAdd */, {
                id: 'editor.action.addCommentLine',
                label: nls.localize(807, "Add Line Comment"),
                alias: 'Add Line Comment',
                precondition: editorContextKeys_1.EditorContextKeys.writable,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    primary: (0, keyCodes_1.KeyChord)(2048 /* KeyMod.CtrlCmd */ | 41 /* KeyCode.KeyK */, 2048 /* KeyMod.CtrlCmd */ | 33 /* KeyCode.KeyC */),
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
    }
    class RemoveLineCommentAction extends CommentLineAction {
        constructor() {
            super(2 /* Type.ForceRemove */, {
                id: 'editor.action.removeCommentLine',
                label: nls.localize(808, "Remove Line Comment"),
                alias: 'Remove Line Comment',
                precondition: editorContextKeys_1.EditorContextKeys.writable,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    primary: (0, keyCodes_1.KeyChord)(2048 /* KeyMod.CtrlCmd */ | 41 /* KeyCode.KeyK */, 2048 /* KeyMod.CtrlCmd */ | 51 /* KeyCode.KeyU */),
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
    }
    class BlockCommentAction extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: 'editor.action.blockComment',
                label: nls.localize(809, "Toggle Block Comment"),
                alias: 'Toggle Block Comment',
                precondition: editorContextKeys_1.EditorContextKeys.writable,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    primary: 1024 /* KeyMod.Shift */ | 512 /* KeyMod.Alt */ | 31 /* KeyCode.KeyA */,
                    linux: { primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 31 /* KeyCode.KeyA */ },
                    weight: 100 /* KeybindingWeight.EditorContrib */
                },
                menuOpts: {
                    menuId: actions_1.MenuId.MenubarEditMenu,
                    group: '5_insert',
                    title: nls.localize(810, "Toggle &&Block Comment"),
                    order: 2
                }
            });
        }
        run(accessor, editor) {
            const languageConfigurationService = accessor.get(languageConfigurationRegistry_1.ILanguageConfigurationService);
            if (!editor.hasModel()) {
                return;
            }
            const commentsOptions = editor.getOption(23 /* EditorOption.comments */);
            const commands = [];
            const selections = editor.getSelections();
            for (const selection of selections) {
                commands.push(new blockCommentCommand_1.BlockCommentCommand(selection, commentsOptions.insertSpace, languageConfigurationService));
            }
            editor.pushUndoStop();
            editor.executeCommands(this.id, commands);
            editor.pushUndoStop();
        }
    }
    (0, editorExtensions_1.registerEditorAction)(ToggleCommentLineAction);
    (0, editorExtensions_1.registerEditorAction)(AddLineCommentAction);
    (0, editorExtensions_1.registerEditorAction)(RemoveLineCommentAction);
    (0, editorExtensions_1.registerEditorAction)(BlockCommentAction);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[731/*vs/editor/contrib/cursorUndo/browser/cursorUndo*/], __M([1/*require*/,0/*exports*/,2/*vs/base/common/lifecycle*/,15/*vs/editor/browser/editorExtensions*/,20/*vs/editor/common/editorContextKeys*/,3/*vs/nls*/]), function (require, exports, lifecycle_1, editorExtensions_1, editorContextKeys_1, nls) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CursorRedo = exports.CursorUndo = exports.CursorUndoRedoController = void 0;
    class CursorState {
        constructor(selections) {
            this.selections = selections;
        }
        equals(other) {
            const thisLen = this.selections.length;
            const otherLen = other.selections.length;
            if (thisLen !== otherLen) {
                return false;
            }
            for (let i = 0; i < thisLen; i++) {
                if (!this.selections[i].equalsSelection(other.selections[i])) {
                    return false;
                }
            }
            return true;
        }
    }
    class StackElement {
        constructor(cursorState, scrollTop, scrollLeft) {
            this.cursorState = cursorState;
            this.scrollTop = scrollTop;
            this.scrollLeft = scrollLeft;
        }
    }
    class CursorUndoRedoController extends lifecycle_1.Disposable {
        static { this.ID = 'editor.contrib.cursorUndoRedoController'; }
        static get(editor) {
            return editor.getContribution(CursorUndoRedoController.ID);
        }
        constructor(editor) {
            super();
            this._editor = editor;
            this._isCursorUndoRedo = false;
            this._undoStack = [];
            this._redoStack = [];
            this._register(editor.onDidChangeModel((e) => {
                this._undoStack = [];
                this._redoStack = [];
            }));
            this._register(editor.onDidChangeModelContent((e) => {
                this._undoStack = [];
                this._redoStack = [];
            }));
            this._register(editor.onDidChangeCursorSelection((e) => {
                if (this._isCursorUndoRedo) {
                    return;
                }
                if (!e.oldSelections) {
                    return;
                }
                if (e.oldModelVersionId !== e.modelVersionId) {
                    return;
                }
                const prevState = new CursorState(e.oldSelections);
                const isEqualToLastUndoStack = (this._undoStack.length > 0 && this._undoStack[this._undoStack.length - 1].cursorState.equals(prevState));
                if (!isEqualToLastUndoStack) {
                    this._undoStack.push(new StackElement(prevState, editor.getScrollTop(), editor.getScrollLeft()));
                    this._redoStack = [];
                    if (this._undoStack.length > 50) {
                        // keep the cursor undo stack bounded
                        this._undoStack.shift();
                    }
                }
            }));
        }
        cursorUndo() {
            if (!this._editor.hasModel() || this._undoStack.length === 0) {
                return;
            }
            this._redoStack.push(new StackElement(new CursorState(this._editor.getSelections()), this._editor.getScrollTop(), this._editor.getScrollLeft()));
            this._applyState(this._undoStack.pop());
        }
        cursorRedo() {
            if (!this._editor.hasModel() || this._redoStack.length === 0) {
                return;
            }
            this._undoStack.push(new StackElement(new CursorState(this._editor.getSelections()), this._editor.getScrollTop(), this._editor.getScrollLeft()));
            this._applyState(this._redoStack.pop());
        }
        _applyState(stackElement) {
            this._isCursorUndoRedo = true;
            this._editor.setSelections(stackElement.cursorState.selections);
            this._editor.setScrollPosition({
                scrollTop: stackElement.scrollTop,
                scrollLeft: stackElement.scrollLeft
            });
            this._isCursorUndoRedo = false;
        }
    }
    exports.CursorUndoRedoController = CursorUndoRedoController;
    class CursorUndo extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: 'cursorUndo',
                label: nls.localize(821, "Cursor Undo"),
                alias: 'Cursor Undo',
                precondition: undefined,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                    primary: 2048 /* KeyMod.CtrlCmd */ | 51 /* KeyCode.KeyU */,
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
        run(accessor, editor, args) {
            CursorUndoRedoController.get(editor)?.cursorUndo();
        }
    }
    exports.CursorUndo = CursorUndo;
    class CursorRedo extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: 'cursorRedo',
                label: nls.localize(822, "Cursor Redo"),
                alias: 'Cursor Redo',
                precondition: undefined
            });
        }
        run(accessor, editor, args) {
            CursorUndoRedoController.get(editor)?.cursorRedo();
        }
    }
    exports.CursorRedo = CursorRedo;
    (0, editorExtensions_1.registerEditorContribution)(CursorUndoRedoController.ID, CursorUndoRedoController, 0 /* EditorContributionInstantiation.Eager */); // eager because it needs to listen to record cursor state ASAP
    (0, editorExtensions_1.registerEditorAction)(CursorUndo);
    (0, editorExtensions_1.registerEditorAction)(CursorRedo);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[732/*vs/editor/contrib/editorState/browser/keybindingCancellation*/], __M([1/*require*/,0/*exports*/,15/*vs/editor/browser/editorExtensions*/,12/*vs/platform/contextkey/common/contextkey*/,18/*vs/base/common/cancellation*/,73/*vs/base/common/linkedList*/,7/*vs/platform/instantiation/common/instantiation*/,49/*vs/platform/instantiation/common/extensions*/,3/*vs/nls*/]), function (require, exports, editorExtensions_1, contextkey_1, cancellation_1, linkedList_1, instantiation_1, extensions_1, nls_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.EditorKeybindingCancellationTokenSource = void 0;
    const IEditorCancellationTokens = (0, instantiation_1.createDecorator)('IEditorCancelService');
    const ctxCancellableOperation = new contextkey_1.RawContextKey('cancellableOperation', false, (0, nls_1.localize)(847, 'Whether the editor runs a cancellable operation, e.g. like \'Peek References\''));
    (0, extensions_1.registerSingleton)(IEditorCancellationTokens, class {
        constructor() {
            this._tokens = new WeakMap();
        }
        add(editor, cts) {
            let data = this._tokens.get(editor);
            if (!data) {
                data = editor.invokeWithinContext(accessor => {
                    const key = ctxCancellableOperation.bindTo(accessor.get(contextkey_1.IContextKeyService));
                    const tokens = new linkedList_1.LinkedList();
                    return { key, tokens };
                });
                this._tokens.set(editor, data);
            }
            let removeFn;
            data.key.set(true);
            removeFn = data.tokens.push(cts);
            return () => {
                // remove w/o cancellation
                if (removeFn) {
                    removeFn();
                    data.key.set(!data.tokens.isEmpty());
                    removeFn = undefined;
                }
            };
        }
        cancel(editor) {
            const data = this._tokens.get(editor);
            if (!data) {
                return;
            }
            // remove with cancellation
            const cts = data.tokens.pop();
            if (cts) {
                cts.cancel();
                data.key.set(!data.tokens.isEmpty());
            }
        }
    }, 1 /* InstantiationType.Delayed */);
    class EditorKeybindingCancellationTokenSource extends cancellation_1.CancellationTokenSource {
        constructor(editor, parent) {
            super(parent);
            this.editor = editor;
            this._unregister = editor.invokeWithinContext(accessor => accessor.get(IEditorCancellationTokens).add(editor, this));
        }
        dispose() {
            this._unregister();
            super.dispose();
        }
    }
    exports.EditorKeybindingCancellationTokenSource = EditorKeybindingCancellationTokenSource;
    (0, editorExtensions_1.registerEditorCommand)(new class extends editorExtensions_1.EditorCommand {
        constructor() {
            super({
                id: 'editor.cancelOperation',
                kbOpts: {
                    weight: 100 /* KeybindingWeight.EditorContrib */,
                    primary: 9 /* KeyCode.Escape */
                },
                precondition: ctxCancellableOperation
            });
        }
        runEditorCommand(accessor, editor) {
            accessor.get(IEditorCancellationTokens).cancel(editor);
        }
    });
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[122/*vs/editor/contrib/editorState/browser/editorState*/], __M([1/*require*/,0/*exports*/,11/*vs/base/common/strings*/,4/*vs/editor/common/core/range*/,18/*vs/base/common/cancellation*/,2/*vs/base/common/lifecycle*/,732/*vs/editor/contrib/editorState/browser/keybindingCancellation*/]), function (require, exports, strings, range_1, cancellation_1, lifecycle_1, keybindingCancellation_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.TextModelCancellationTokenSource = exports.EditorStateCancellationTokenSource = exports.EditorState = void 0;
    class EditorState {
        constructor(editor, flags) {
            this.flags = flags;
            if ((this.flags & 1 /* CodeEditorStateFlag.Value */) !== 0) {
                const model = editor.getModel();
                this.modelVersionId = model ? strings.format('{0}#{1}', model.uri.toString(), model.getVersionId()) : null;
            }
            else {
                this.modelVersionId = null;
            }
            if ((this.flags & 4 /* CodeEditorStateFlag.Position */) !== 0) {
                this.position = editor.getPosition();
            }
            else {
                this.position = null;
            }
            if ((this.flags & 2 /* CodeEditorStateFlag.Selection */) !== 0) {
                this.selection = editor.getSelection();
            }
            else {
                this.selection = null;
            }
            if ((this.flags & 8 /* CodeEditorStateFlag.Scroll */) !== 0) {
                this.scrollLeft = editor.getScrollLeft();
                this.scrollTop = editor.getScrollTop();
            }
            else {
                this.scrollLeft = -1;
                this.scrollTop = -1;
            }
        }
        _equals(other) {
            if (!(other instanceof EditorState)) {
                return false;
            }
            const state = other;
            if (this.modelVersionId !== state.modelVersionId) {
                return false;
            }
            if (this.scrollLeft !== state.scrollLeft || this.scrollTop !== state.scrollTop) {
                return false;
            }
            if (!this.position && state.position || this.position && !state.position || this.position && state.position && !this.position.equals(state.position)) {
                return false;
            }
            if (!this.selection && state.selection || this.selection && !state.selection || this.selection && state.selection && !this.selection.equalsRange(state.selection)) {
                return false;
            }
            return true;
        }
        validate(editor) {
            return this._equals(new EditorState(editor, this.flags));
        }
    }
    exports.EditorState = EditorState;
    /**
     * A cancellation token source that cancels when the editor changes as expressed
     * by the provided flags
     * @param range If provided, changes in position and selection within this range will not trigger cancellation
     */
    class EditorStateCancellationTokenSource extends keybindingCancellation_1.EditorKeybindingCancellationTokenSource {
        constructor(editor, flags, range, parent) {
            super(editor, parent);
            this._listener = new lifecycle_1.DisposableStore();
            if (flags & 4 /* CodeEditorStateFlag.Position */) {
                this._listener.add(editor.onDidChangeCursorPosition(e => {
                    if (!range || !range_1.Range.containsPosition(range, e.position)) {
                        this.cancel();
                    }
                }));
            }
            if (flags & 2 /* CodeEditorStateFlag.Selection */) {
                this._listener.add(editor.onDidChangeCursorSelection(e => {
                    if (!range || !range_1.Range.containsRange(range, e.selection)) {
                        this.cancel();
                    }
                }));
            }
            if (flags & 8 /* CodeEditorStateFlag.Scroll */) {
                this._listener.add(editor.onDidScrollChange(_ => this.cancel()));
            }
            if (flags & 1 /* CodeEditorStateFlag.Value */) {
                this._listener.add(editor.onDidChangeModel(_ => this.cancel()));
                this._listener.add(editor.onDidChangeModelContent(_ => this.cancel()));
            }
        }
        dispose() {
            this._listener.dispose();
            super.dispose();
        }
    }
    exports.EditorStateCancellationTokenSource = EditorStateCancellationTokenSource;
    /**
     * A cancellation token source that cancels when the provided model changes
     */
    class TextModelCancellationTokenSource extends cancellation_1.CancellationTokenSource {
        constructor(model, parent) {
            super(parent);
            this._listener = model.onDidChangeContent(() => this.cancel());
        }
        dispose() {
            this._listener.dispose();
            super.dispose();
        }
    }
    exports.TextModelCancellationTokenSource = TextModelCancellationTokenSource;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[157/*vs/editor/contrib/codeAction/browser/codeAction*/], __M([1/*require*/,0/*exports*/,13/*vs/base/common/arrays*/,18/*vs/base/common/cancellation*/,8/*vs/base/common/errors*/,2/*vs/base/common/lifecycle*/,22/*vs/base/common/uri*/,152/*vs/editor/browser/services/bulkEditService*/,4/*vs/editor/common/core/range*/,23/*vs/editor/common/core/selection*/,17/*vs/editor/common/services/languageFeatures*/,51/*vs/editor/common/services/model*/,122/*vs/editor/contrib/editorState/browser/editorState*/,3/*vs/nls*/,24/*vs/platform/commands/common/commands*/,50/*vs/platform/notification/common/notification*/,96/*vs/platform/progress/common/progress*/,63/*vs/platform/telemetry/common/telemetry*/,134/*vs/editor/contrib/codeAction/common/types*/,91/*vs/base/common/hierarchicalKind*/]), function (require, exports, arrays_1, cancellation_1, errors_1, lifecycle_1, uri_1, bulkEditService_1, range_1, selection_1, languageFeatures_1, model_1, editorState_1, nls, commands_1, notification_1, progress_1, telemetry_1, types_1, hierarchicalKind_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ApplyCodeActionReason = exports.fixAllCommandId = exports.organizeImportsCommandId = exports.sourceActionCommandId = exports.refactorCommandId = exports.autoFixCommandId = exports.quickFixCommandId = exports.codeActionCommandId = void 0;
    exports.getCodeActions = getCodeActions;
    exports.applyCodeAction = applyCodeAction;
    exports.codeActionCommandId = 'editor.action.codeAction';
    exports.quickFixCommandId = 'editor.action.quickFix';
    exports.autoFixCommandId = 'editor.action.autoFix';
    exports.refactorCommandId = 'editor.action.refactor';
    exports.sourceActionCommandId = 'editor.action.sourceAction';
    exports.organizeImportsCommandId = 'editor.action.organizeImports';
    exports.fixAllCommandId = 'editor.action.fixAll';
    class ManagedCodeActionSet extends lifecycle_1.Disposable {
        static codeActionsPreferredComparator(a, b) {
            if (a.isPreferred && !b.isPreferred) {
                return -1;
            }
            else if (!a.isPreferred && b.isPreferred) {
                return 1;
            }
            else {
                return 0;
            }
        }
        static codeActionsComparator({ action: a }, { action: b }) {
            if (a.isAI && !b.isAI) {
                return 1;
            }
            else if (!a.isAI && b.isAI) {
                return -1;
            }
            if ((0, arrays_1.isNonEmptyArray)(a.diagnostics)) {
                return (0, arrays_1.isNonEmptyArray)(b.diagnostics) ? ManagedCodeActionSet.codeActionsPreferredComparator(a, b) : -1;
            }
            else if ((0, arrays_1.isNonEmptyArray)(b.diagnostics)) {
                return 1;
            }
            else {
                return ManagedCodeActionSet.codeActionsPreferredComparator(a, b); // both have no diagnostics
            }
        }
        constructor(actions, documentation, disposables) {
            super();
            this.documentation = documentation;
            this._register(disposables);
            this.allActions = [...actions].sort(ManagedCodeActionSet.codeActionsComparator);
            this.validActions = this.allActions.filter(({ action }) => !action.disabled);
        }
        get hasAutoFix() {
            return this.validActions.some(({ action: fix }) => !!fix.kind && types_1.CodeActionKind.QuickFix.contains(new hierarchicalKind_1.HierarchicalKind(fix.kind)) && !!fix.isPreferred);
        }
        get hasAIFix() {
            return this.validActions.some(({ action: fix }) => !!fix.isAI);
        }
        get allAIFixes() {
            return this.validActions.every(({ action: fix }) => !!fix.isAI);
        }
    }
    const emptyCodeActionsResponse = { actions: [], documentation: undefined };
    async function getCodeActions(registry, model, rangeOrSelection, trigger, progress, token) {
        const filter = trigger.filter || {};
        const notebookFilter = {
            ...filter,
            excludes: [...(filter.excludes || []), types_1.CodeActionKind.Notebook],
        };
        const codeActionContext = {
            only: filter.include?.value,
            trigger: trigger.type,
        };
        const cts = new editorState_1.TextModelCancellationTokenSource(model, token);
        // if the trigger is auto (autosave, lightbulb, etc), we should exclude notebook codeActions
        const excludeNotebookCodeActions = (trigger.type === 2 /* languages.CodeActionTriggerType.Auto */);
        const providers = getCodeActionProviders(registry, model, (excludeNotebookCodeActions) ? notebookFilter : filter);
        const disposables = new lifecycle_1.DisposableStore();
        const promises = providers.map(async (provider) => {
            try {
                progress.report(provider);
                const providedCodeActions = await provider.provideCodeActions(model, rangeOrSelection, codeActionContext, cts.token);
                if (providedCodeActions) {
                    disposables.add(providedCodeActions);
                }
                if (cts.token.isCancellationRequested) {
                    return emptyCodeActionsResponse;
                }
                const filteredActions = (providedCodeActions?.actions || []).filter(action => action && (0, types_1.filtersAction)(filter, action));
                const documentation = getDocumentationFromProvider(provider, filteredActions, filter.include);
                return {
                    actions: filteredActions.map(action => new types_1.CodeActionItem(action, provider)),
                    documentation
                };
            }
            catch (err) {
                if ((0, errors_1.isCancellationError)(err)) {
                    throw err;
                }
                (0, errors_1.onUnexpectedExternalError)(err);
                return emptyCodeActionsResponse;
            }
        });
        const listener = registry.onDidChange(() => {
            const newProviders = registry.all(model);
            if (!(0, arrays_1.equals)(newProviders, providers)) {
                cts.cancel();
            }
        });
        try {
            const actions = await Promise.all(promises);
            const allActions = actions.map(x => x.actions).flat();
            const allDocumentation = [
                ...(0, arrays_1.coalesce)(actions.map(x => x.documentation)),
                ...getAdditionalDocumentationForShowingActions(registry, model, trigger, allActions)
            ];
            return new ManagedCodeActionSet(allActions, allDocumentation, disposables);
        }
        finally {
            listener.dispose();
            cts.dispose();
        }
    }
    function getCodeActionProviders(registry, model, filter) {
        return registry.all(model)
            // Don't include providers that we know will not return code actions of interest
            .filter(provider => {
            if (!provider.providedCodeActionKinds) {
                // We don't know what type of actions this provider will return.
                return true;
            }
            return provider.providedCodeActionKinds.some(kind => (0, types_1.mayIncludeActionsOfKind)(filter, new hierarchicalKind_1.HierarchicalKind(kind)));
        });
    }
    function* getAdditionalDocumentationForShowingActions(registry, model, trigger, actionsToShow) {
        if (model && actionsToShow.length) {
            for (const provider of registry.all(model)) {
                if (provider._getAdditionalMenuItems) {
                    yield* provider._getAdditionalMenuItems?.({ trigger: trigger.type, only: trigger.filter?.include?.value }, actionsToShow.map(item => item.action));
                }
            }
        }
    }
    function getDocumentationFromProvider(provider, providedCodeActions, only) {
        if (!provider.documentation) {
            return undefined;
        }
        const documentation = provider.documentation.map(entry => ({ kind: new hierarchicalKind_1.HierarchicalKind(entry.kind), command: entry.command }));
        if (only) {
            let currentBest;
            for (const entry of documentation) {
                if (entry.kind.contains(only)) {
                    if (!currentBest) {
                        currentBest = entry;
                    }
                    else {
                        // Take best match
                        if (currentBest.kind.contains(entry.kind)) {
                            currentBest = entry;
                        }
                    }
                }
            }
            if (currentBest) {
                return currentBest?.command;
            }
        }
        // Otherwise, check to see if any of the provided actions match.
        for (const action of providedCodeActions) {
            if (!action.kind) {
                continue;
            }
            for (const entry of documentation) {
                if (entry.kind.contains(new hierarchicalKind_1.HierarchicalKind(action.kind))) {
                    return entry.command;
                }
            }
        }
        return undefined;
    }
    var ApplyCodeActionReason;
    (function (ApplyCodeActionReason) {
        ApplyCodeActionReason["OnSave"] = "onSave";
        ApplyCodeActionReason["FromProblemsView"] = "fromProblemsView";
        ApplyCodeActionReason["FromCodeActions"] = "fromCodeActions";
        ApplyCodeActionReason["FromAILightbulb"] = "fromAILightbulb"; // direct invocation when clicking on the AI lightbulb
    })(ApplyCodeActionReason || (exports.ApplyCodeActionReason = ApplyCodeActionReason = {}));
    async function applyCodeAction(accessor, item, codeActionReason, options, token = cancellation_1.CancellationToken.None) {
        const bulkEditService = accessor.get(bulkEditService_1.IBulkEditService);
        const commandService = accessor.get(commands_1.ICommandService);
        const telemetryService = accessor.get(telemetry_1.ITelemetryService);
        const notificationService = accessor.get(notification_1.INotificationService);
        telemetryService.publicLog2('codeAction.applyCodeAction', {
            codeActionTitle: item.action.title,
            codeActionKind: item.action.kind,
            codeActionIsPreferred: !!item.action.isPreferred,
            reason: codeActionReason,
        });
        await item.resolve(token);
        if (token.isCancellationRequested) {
            return;
        }
        if (item.action.edit?.edits.length) {
            const result = await bulkEditService.apply(item.action.edit, {
                editor: options?.editor,
                label: item.action.title,
                quotableLabel: item.action.title,
                code: 'undoredo.codeAction',
                respectAutoSaveConfig: codeActionReason !== ApplyCodeActionReason.OnSave,
                showPreview: options?.preview,
            });
            if (!result.isApplied) {
                return;
            }
        }
        if (item.action.command) {
            try {
                await commandService.executeCommand(item.action.command.id, ...(item.action.command.arguments || []));
            }
            catch (err) {
                const message = asMessage(err);
                notificationService.error(typeof message === 'string'
                    ? message
                    : nls.localize(742, "An unknown error occurred while applying the code action"));
            }
        }
    }
    function asMessage(err) {
        if (typeof err === 'string') {
            return err;
        }
        else if (err instanceof Error && typeof err.message === 'string') {
            return err.message;
        }
        else {
            return undefined;
        }
    }
    commands_1.CommandsRegistry.registerCommand('_executeCodeActionProvider', async function (accessor, resource, rangeOrSelection, kind, itemResolveCount) {
        if (!(resource instanceof uri_1.URI)) {
            throw (0, errors_1.illegalArgument)();
        }
        const { codeActionProvider } = accessor.get(languageFeatures_1.ILanguageFeaturesService);
        const model = accessor.get(model_1.IModelService).getModel(resource);
        if (!model) {
            throw (0, errors_1.illegalArgument)();
        }
        const validatedRangeOrSelection = selection_1.Selection.isISelection(rangeOrSelection)
            ? selection_1.Selection.liftSelection(rangeOrSelection)
            : range_1.Range.isIRange(rangeOrSelection)
                ? model.validateRange(rangeOrSelection)
                : undefined;
        if (!validatedRangeOrSelection) {
            throw (0, errors_1.illegalArgument)();
        }
        const include = typeof kind === 'string' ? new hierarchicalKind_1.HierarchicalKind(kind) : undefined;
        const codeActionSet = await getCodeActions(codeActionProvider, model, validatedRangeOrSelection, { type: 1 /* languages.CodeActionTriggerType.Invoke */, triggerAction: types_1.CodeActionTriggerSource.Default, filter: { includeSourceActions: true, include } }, progress_1.Progress.None, cancellation_1.CancellationToken.None);
        const resolving = [];
        const resolveCount = Math.min(codeActionSet.validActions.length, typeof itemResolveCount === 'number' ? itemResolveCount : 0);
        for (let i = 0; i < resolveCount; i++) {
            resolving.push(codeActionSet.validActions[i].resolve(cancellation_1.CancellationToken.None));
        }
        try {
            await Promise.all(resolving);
            return codeActionSet.validActions.map(item => item.action);
        }
        finally {
            setTimeout(() => codeActionSet.dispose(), 100);
        }
    });
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[733/*vs/editor/contrib/codeAction/browser/codeActionKeybindingResolver*/], __M([1/*require*/,0/*exports*/,91/*vs/base/common/hierarchicalKind*/,98/*vs/base/common/lazy*/,157/*vs/editor/contrib/codeAction/browser/codeAction*/,134/*vs/editor/contrib/codeAction/common/types*/,31/*vs/platform/keybinding/common/keybinding*/]), function (require, exports, hierarchicalKind_1, lazy_1, codeAction_1, types_1, keybinding_1) {
    "use strict";
    var CodeActionKeybindingResolver_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CodeActionKeybindingResolver = void 0;
    let CodeActionKeybindingResolver = class CodeActionKeybindingResolver {
        static { CodeActionKeybindingResolver_1 = this; }
        static { this.codeActionCommands = [
            codeAction_1.refactorCommandId,
            codeAction_1.codeActionCommandId,
            codeAction_1.sourceActionCommandId,
            codeAction_1.organizeImportsCommandId,
            codeAction_1.fixAllCommandId
        ]; }
        constructor(keybindingService) {
            this.keybindingService = keybindingService;
        }
        getResolver() {
            // Lazy since we may not actually ever read the value
            const allCodeActionBindings = new lazy_1.Lazy(() => this.keybindingService.getKeybindings()
                .filter(item => CodeActionKeybindingResolver_1.codeActionCommands.indexOf(item.command) >= 0)
                .filter(item => item.resolvedKeybinding)
                .map((item) => {
                // Special case these commands since they come built-in with VS Code and don't use 'commandArgs'
                let commandArgs = item.commandArgs;
                if (item.command === codeAction_1.organizeImportsCommandId) {
                    commandArgs = { kind: types_1.CodeActionKind.SourceOrganizeImports.value };
                }
                else if (item.command === codeAction_1.fixAllCommandId) {
                    commandArgs = { kind: types_1.CodeActionKind.SourceFixAll.value };
                }
                return {
                    resolvedKeybinding: item.resolvedKeybinding,
                    ...types_1.CodeActionCommandArgs.fromUser(commandArgs, {
                        kind: hierarchicalKind_1.HierarchicalKind.None,
                        apply: "never" /* CodeActionAutoApply.Never */
                    })
                };
            }));
            return (action) => {
                if (action.kind) {
                    const binding = this.bestKeybindingForCodeAction(action, allCodeActionBindings.value);
                    return binding?.resolvedKeybinding;
                }
                return undefined;
            };
        }
        bestKeybindingForCodeAction(action, candidates) {
            if (!action.kind) {
                return undefined;
            }
            const kind = new hierarchicalKind_1.HierarchicalKind(action.kind);
            return candidates
                .filter(candidate => candidate.kind.contains(kind))
                .filter(candidate => {
                if (candidate.preferred) {
                    // If the candidate keybinding only applies to preferred actions, the this action must also be preferred
                    return action.isPreferred;
                }
                return true;
            })
                .reduceRight((currentBest, candidate) => {
                if (!currentBest) {
                    return candidate;
                }
                // Select the more specific binding
                return currentBest.kind.contains(candidate.kind) ? candidate : currentBest;
            }, undefined);
        }
    };
    exports.CodeActionKeybindingResolver = CodeActionKeybindingResolver;
    exports.CodeActionKeybindingResolver = CodeActionKeybindingResolver = CodeActionKeybindingResolver_1 = __decorate([
        __param(0, keybinding_1.IKeybindingService)
    ], CodeActionKeybindingResolver);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[408/*vs/editor/contrib/codeAction/browser/codeActionModel*/], __M([1/*require*/,0/*exports*/,14/*vs/base/common/async*/,8/*vs/base/common/errors*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,48/*vs/base/common/resources*/,37/*vs/editor/common/config/editorOptions*/,9/*vs/editor/common/core/position*/,23/*vs/editor/common/core/selection*/,12/*vs/platform/contextkey/common/contextkey*/,96/*vs/platform/progress/common/progress*/,134/*vs/editor/contrib/codeAction/common/types*/,157/*vs/editor/contrib/codeAction/browser/codeAction*/,91/*vs/base/common/hierarchicalKind*/,54/*vs/base/common/stopwatch*/]), function (require, exports, async_1, errors_1, event_1, lifecycle_1, resources_1, editorOptions_1, position_1, selection_1, contextkey_1, progress_1, types_1, codeAction_1, hierarchicalKind_1, stopwatch_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CodeActionModel = exports.CodeActionsState = exports.APPLY_FIX_ALL_COMMAND_ID = exports.SUPPORTED_CODE_ACTIONS = void 0;
    exports.SUPPORTED_CODE_ACTIONS = new contextkey_1.RawContextKey('supportedCodeAction', '');
    exports.APPLY_FIX_ALL_COMMAND_ID = '_typescript.applyFixAllCodeAction';
    class CodeActionOracle extends lifecycle_1.Disposable {
        constructor(_editor, _markerService, _signalChange, _delay = 250) {
            super();
            this._editor = _editor;
            this._markerService = _markerService;
            this._signalChange = _signalChange;
            this._delay = _delay;
            this._autoTriggerTimer = this._register(new async_1.TimeoutTimer());
            this._register(this._markerService.onMarkerChanged(e => this._onMarkerChanges(e)));
            this._register(this._editor.onDidChangeCursorPosition(() => this._tryAutoTrigger()));
        }
        trigger(trigger) {
            const selection = this._getRangeOfSelectionUnlessWhitespaceEnclosed(trigger);
            this._signalChange(selection ? { trigger, selection } : undefined);
        }
        _onMarkerChanges(resources) {
            const model = this._editor.getModel();
            if (model && resources.some(resource => (0, resources_1.isEqual)(resource, model.uri))) {
                this._tryAutoTrigger();
            }
        }
        _tryAutoTrigger() {
            this._autoTriggerTimer.cancelAndSet(() => {
                this.trigger({ type: 2 /* CodeActionTriggerType.Auto */, triggerAction: types_1.CodeActionTriggerSource.Default });
            }, this._delay);
        }
        _getRangeOfSelectionUnlessWhitespaceEnclosed(trigger) {
            if (!this._editor.hasModel()) {
                return undefined;
            }
            const selection = this._editor.getSelection();
            if (trigger.type === 1 /* CodeActionTriggerType.Invoke */) {
                return selection;
            }
            const enabled = this._editor.getOption(65 /* EditorOption.lightbulb */).enabled;
            if (enabled === editorOptions_1.ShowLightbulbIconMode.Off) {
                return undefined;
            }
            else if (enabled === editorOptions_1.ShowLightbulbIconMode.On) {
                return selection;
            }
            else if (enabled === editorOptions_1.ShowLightbulbIconMode.OnCode) {
                const isSelectionEmpty = selection.isEmpty();
                if (!isSelectionEmpty) {
                    return selection;
                }
                const model = this._editor.getModel();
                const { lineNumber, column } = selection.getPosition();
                const line = model.getLineContent(lineNumber);
                if (line.length === 0) {
                    // empty line
                    return undefined;
                }
                else if (column === 1) {
                    // look only right
                    if (/\s/.test(line[0])) {
                        return undefined;
                    }
                }
                else if (column === model.getLineMaxColumn(lineNumber)) {
                    // look only left
                    if (/\s/.test(line[line.length - 1])) {
                        return undefined;
                    }
                }
                else {
                    // look left and right
                    if (/\s/.test(line[column - 2]) && /\s/.test(line[column - 1])) {
                        return undefined;
                    }
                }
            }
            return selection;
        }
    }
    var CodeActionsState;
    (function (CodeActionsState) {
        CodeActionsState.Empty = { type: 0 /* Type.Empty */ };
        class Triggered {
            constructor(trigger, position, _cancellablePromise) {
                this.trigger = trigger;
                this.position = position;
                this._cancellablePromise = _cancellablePromise;
                this.type = 1 /* Type.Triggered */;
                this.actions = _cancellablePromise.catch((e) => {
                    if ((0, errors_1.isCancellationError)(e)) {
                        return emptyCodeActionSet;
                    }
                    throw e;
                });
            }
            cancel() {
                this._cancellablePromise.cancel();
            }
        }
        CodeActionsState.Triggered = Triggered;
    })(CodeActionsState || (exports.CodeActionsState = CodeActionsState = {}));
    const emptyCodeActionSet = Object.freeze({
        allActions: [],
        validActions: [],
        dispose: () => { },
        documentation: [],
        hasAutoFix: false,
        hasAIFix: false,
        allAIFixes: false,
    });
    class CodeActionModel extends lifecycle_1.Disposable {
        constructor(_editor, _registry, _markerService, contextKeyService, _progressService, _configurationService, _telemetryService) {
            super();
            this._editor = _editor;
            this._registry = _registry;
            this._markerService = _markerService;
            this._progressService = _progressService;
            this._configurationService = _configurationService;
            this._telemetryService = _telemetryService;
            this._codeActionOracle = this._register(new lifecycle_1.MutableDisposable());
            this._state = CodeActionsState.Empty;
            this._onDidChangeState = this._register(new event_1.Emitter());
            this.onDidChangeState = this._onDidChangeState.event;
            this._disposed = false;
            this._supportedCodeActions = exports.SUPPORTED_CODE_ACTIONS.bindTo(contextKeyService);
            this._register(this._editor.onDidChangeModel(() => this._update()));
            this._register(this._editor.onDidChangeModelLanguage(() => this._update()));
            this._register(this._registry.onDidChange(() => this._update()));
            this._register(this._editor.onDidChangeConfiguration((e) => {
                if (e.hasChanged(65 /* EditorOption.lightbulb */)) {
                    this._update();
                }
            }));
            this._update();
        }
        dispose() {
            if (this._disposed) {
                return;
            }
            this._disposed = true;
            super.dispose();
            this.setState(CodeActionsState.Empty, true);
        }
        _settingEnabledNearbyQuickfixes() {
            const model = this._editor?.getModel();
            return this._configurationService ? this._configurationService.getValue('editor.codeActionWidget.includeNearbyQuickFixes', { resource: model?.uri }) : false;
        }
        _update() {
            if (this._disposed) {
                return;
            }
            this._codeActionOracle.value = undefined;
            this.setState(CodeActionsState.Empty);
            const model = this._editor.getModel();
            if (model
                && this._registry.has(model)
                && !this._editor.getOption(92 /* EditorOption.readOnly */)) {
                const supportedActions = this._registry.all(model).flatMap(provider => provider.providedCodeActionKinds ?? []);
                this._supportedCodeActions.set(supportedActions.join(' '));
                this._codeActionOracle.value = new CodeActionOracle(this._editor, this._markerService, trigger => {
                    if (!trigger) {
                        this.setState(CodeActionsState.Empty);
                        return;
                    }
                    const startPosition = trigger.selection.getStartPosition();
                    const actions = (0, async_1.createCancelablePromise)(async (token) => {
                        if (this._settingEnabledNearbyQuickfixes() && trigger.trigger.type === 1 /* CodeActionTriggerType.Invoke */ && (trigger.trigger.triggerAction === types_1.CodeActionTriggerSource.QuickFix || trigger.trigger.filter?.include?.contains(types_1.CodeActionKind.QuickFix))) {
                            const codeActionSet = await (0, codeAction_1.getCodeActions)(this._registry, model, trigger.selection, trigger.trigger, progress_1.Progress.None, token);
                            const allCodeActions = [...codeActionSet.allActions];
                            if (token.isCancellationRequested) {
                                return emptyCodeActionSet;
                            }
                            // Search for quickfixes in the curret code action set.
                            const foundQuickfix = codeActionSet.validActions?.some(action => action.action.kind ? types_1.CodeActionKind.QuickFix.contains(new hierarchicalKind_1.HierarchicalKind(action.action.kind)) : false);
                            const allMarkers = this._markerService.read({ resource: model.uri });
                            if (foundQuickfix) {
                                for (const action of codeActionSet.validActions) {
                                    if (action.action.command?.arguments?.some(arg => typeof arg === 'string' && arg.includes(exports.APPLY_FIX_ALL_COMMAND_ID))) {
                                        action.action.diagnostics = [...allMarkers.filter(marker => marker.relatedInformation)];
                                    }
                                }
                                return { validActions: codeActionSet.validActions, allActions: allCodeActions, documentation: codeActionSet.documentation, hasAutoFix: codeActionSet.hasAutoFix, hasAIFix: codeActionSet.hasAIFix, allAIFixes: codeActionSet.allAIFixes, dispose: () => { codeActionSet.dispose(); } };
                            }
                            else if (!foundQuickfix) {
                                // If markers exists, and there are no quickfixes found or length is zero, check for quickfixes on that line.
                                if (allMarkers.length > 0) {
                                    const currPosition = trigger.selection.getPosition();
                                    let trackedPosition = currPosition;
                                    let distance = Number.MAX_VALUE;
                                    const currentActions = [...codeActionSet.validActions];
                                    for (const marker of allMarkers) {
                                        const col = marker.endColumn;
                                        const row = marker.endLineNumber;
                                        const startRow = marker.startLineNumber;
                                        // Found quickfix on the same line and check relative distance to other markers
                                        if ((row === currPosition.lineNumber || startRow === currPosition.lineNumber)) {
                                            trackedPosition = new position_1.Position(row, col);
                                            const newCodeActionTrigger = {
                                                type: trigger.trigger.type,
                                                triggerAction: trigger.trigger.triggerAction,
                                                filter: { include: trigger.trigger.filter?.include ? trigger.trigger.filter?.include : types_1.CodeActionKind.QuickFix },
                                                autoApply: trigger.trigger.autoApply,
                                                context: { notAvailableMessage: trigger.trigger.context?.notAvailableMessage || '', position: trackedPosition }
                                            };
                                            const selectionAsPosition = new selection_1.Selection(trackedPosition.lineNumber, trackedPosition.column, trackedPosition.lineNumber, trackedPosition.column);
                                            const actionsAtMarker = await (0, codeAction_1.getCodeActions)(this._registry, model, selectionAsPosition, newCodeActionTrigger, progress_1.Progress.None, token);
                                            if (actionsAtMarker.validActions.length !== 0) {
                                                for (const action of actionsAtMarker.validActions) {
                                                    if (action.action.command?.arguments?.some(arg => typeof arg === 'string' && arg.includes(exports.APPLY_FIX_ALL_COMMAND_ID))) {
                                                        action.action.diagnostics = [...allMarkers.filter(marker => marker.relatedInformation)];
                                                    }
                                                }
                                                if (codeActionSet.allActions.length === 0) {
                                                    allCodeActions.push(...actionsAtMarker.allActions);
                                                }
                                                // Already filtered through to only get quickfixes, so no need to filter again.
                                                if (Math.abs(currPosition.column - col) < distance) {
                                                    currentActions.unshift(...actionsAtMarker.validActions);
                                                }
                                                else {
                                                    currentActions.push(...actionsAtMarker.validActions);
                                                }
                                            }
                                            distance = Math.abs(currPosition.column - col);
                                        }
                                    }
                                    const filteredActions = currentActions.filter((action, index, self) => self.findIndex((a) => a.action.title === action.action.title) === index);
                                    filteredActions.sort((a, b) => {
                                        if (a.action.isPreferred && !b.action.isPreferred) {
                                            return -1;
                                        }
                                        else if (!a.action.isPreferred && b.action.isPreferred) {
                                            return 1;
                                        }
                                        else if (a.action.isAI && !b.action.isAI) {
                                            return 1;
                                        }
                                        else if (!a.action.isAI && b.action.isAI) {
                                            return -1;
                                        }
                                        else {
                                            return 0;
                                        }
                                    });
                                    // Only retriggers if actually found quickfix on the same line as cursor
                                    return { validActions: filteredActions, allActions: allCodeActions, documentation: codeActionSet.documentation, hasAutoFix: codeActionSet.hasAutoFix, hasAIFix: codeActionSet.hasAIFix, allAIFixes: codeActionSet.allAIFixes, dispose: () => { codeActionSet.dispose(); } };
                                }
                            }
                        }
                        // Case for manual triggers - specifically Source Actions and Refactors
                        if (trigger.trigger.type === 1 /* CodeActionTriggerType.Invoke */) {
                            const sw = new stopwatch_1.StopWatch();
                            const codeActions = await (0, codeAction_1.getCodeActions)(this._registry, model, trigger.selection, trigger.trigger, progress_1.Progress.None, token);
                            // Telemetry for duration of each code action on save.
                            if (this._telemetryService) {
                                this._telemetryService.publicLog2('codeAction.invokedDurations', {
                                    codeActions: codeActions.validActions.length,
                                    duration: sw.elapsed()
                                });
                            }
                            return codeActions;
                        }
                        return (0, codeAction_1.getCodeActions)(this._registry, model, trigger.selection, trigger.trigger, progress_1.Progress.None, token);
                    });
                    if (trigger.trigger.type === 1 /* CodeActionTriggerType.Invoke */) {
                        this._progressService?.showWhile(actions, 250);
                    }
                    const newState = new CodeActionsState.Triggered(trigger.trigger, startPosition, actions);
                    let isManualToAutoTransition = false;
                    if (this._state.type === 1 /* CodeActionsState.Type.Triggered */) {
                        // Check if the current state is manual and the new state is automatic
                        isManualToAutoTransition = this._state.trigger.type === 1 /* CodeActionTriggerType.Invoke */ &&
                            newState.type === 1 /* CodeActionsState.Type.Triggered */ &&
                            newState.trigger.type === 2 /* CodeActionTriggerType.Auto */ &&
                            this._state.position !== newState.position;
                    }
                    // Do not trigger state if current state is manual and incoming state is automatic
                    if (!isManualToAutoTransition) {
                        this.setState(newState);
                    }
                    else {
                        // Reset the new state after getting code actions back.
                        setTimeout(() => {
                            this.setState(newState);
                        }, 500);
                    }
                }, undefined);
                this._codeActionOracle.value.trigger({ type: 2 /* CodeActionTriggerType.Auto */, triggerAction: types_1.CodeActionTriggerSource.Default });
            }
            else {
                this._supportedCodeActions.reset();
            }
        }
        trigger(trigger) {
            this._codeActionOracle.value?.trigger(trigger);
        }
        setState(newState, skipNotify) {
            if (newState === this._state) {
                return;
            }
            // Cancel old request
            if (this._state.type === 1 /* CodeActionsState.Type.Triggered */) {
                this._state.cancel();
            }
            this._state = newState;
            if (!skipNotify && !this._disposed) {
                this._onDidChangeState.fire(newState);
            }
        }
    }
    exports.CodeActionModel = CodeActionModel;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[734/*vs/editor/contrib/fontZoom/browser/fontZoom*/], __M([1/*require*/,0/*exports*/,15/*vs/editor/browser/editorExtensions*/,165/*vs/editor/common/config/editorZoom*/,3/*vs/nls*/]), function (require, exports, editorExtensions_1, editorZoom_1, nls) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    class EditorFontZoomIn extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: 'editor.action.fontZoomIn',
                label: nls.localize(919, "Increase Editor Font Size"),
                alias: 'Increase Editor Font Size',
                precondition: undefined
            });
        }
        run(accessor, editor) {
            editorZoom_1.EditorZoom.setZoomLevel(editorZoom_1.EditorZoom.getZoomLevel() + 1);
        }
    }
    class EditorFontZoomOut extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: 'editor.action.fontZoomOut',
                label: nls.localize(920, "Decrease Editor Font Size"),
                alias: 'Decrease Editor Font Size',
                precondition: undefined
            });
        }
        run(accessor, editor) {
            editorZoom_1.EditorZoom.setZoomLevel(editorZoom_1.EditorZoom.getZoomLevel() - 1);
        }
    }
    class EditorFontZoomReset extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: 'editor.action.fontZoomReset',
                label: nls.localize(921, "Reset Editor Font Size"),
                alias: 'Reset Editor Font Size',
                precondition: undefined
            });
        }
        run(accessor, editor) {
            editorZoom_1.EditorZoom.setZoomLevel(0);
        }
    }
    (0, editorExtensions_1.registerEditorAction)(EditorFontZoomIn);
    (0, editorExtensions_1.registerEditorAction)(EditorFontZoomOut);
    (0, editorExtensions_1.registerEditorAction)(EditorFontZoomReset);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[409/*vs/editor/contrib/format/browser/format*/], __M([1/*require*/,0/*exports*/,13/*vs/base/common/arrays*/,18/*vs/base/common/cancellation*/,8/*vs/base/common/errors*/,53/*vs/base/common/iterator*/,73/*vs/base/common/linkedList*/,19/*vs/base/common/types*/,22/*vs/base/common/uri*/,122/*vs/editor/contrib/editorState/browser/editorState*/,168/*vs/editor/browser/editorBrowser*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/,23/*vs/editor/common/core/selection*/,100/*vs/editor/common/services/editorWorker*/,78/*vs/editor/common/services/resolverService*/,337/*vs/editor/contrib/format/browser/formattingEdit*/,24/*vs/platform/commands/common/commands*/,674/*vs/platform/extensions/common/extensions*/,7/*vs/platform/instantiation/common/instantiation*/,17/*vs/editor/common/services/languageFeatures*/,62/*vs/platform/log/common/log*/,137/*vs/platform/accessibilitySignal/browser/accessibilitySignalService*/]), function (require, exports, arrays_1, cancellation_1, errors_1, iterator_1, linkedList_1, types_1, uri_1, editorState_1, editorBrowser_1, position_1, range_1, selection_1, editorWorker_1, resolverService_1, formattingEdit_1, commands_1, extensions_1, instantiation_1, languageFeatures_1, log_1, accessibilitySignalService_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.FormattingConflicts = void 0;
    exports.getRealAndSyntheticDocumentFormattersOrdered = getRealAndSyntheticDocumentFormattersOrdered;
    exports.formatDocumentRangesWithSelectedProvider = formatDocumentRangesWithSelectedProvider;
    exports.formatDocumentRangesWithProvider = formatDocumentRangesWithProvider;
    exports.formatDocumentWithSelectedProvider = formatDocumentWithSelectedProvider;
    exports.formatDocumentWithProvider = formatDocumentWithProvider;
    exports.getDocumentRangeFormattingEditsUntilResult = getDocumentRangeFormattingEditsUntilResult;
    exports.getDocumentFormattingEditsUntilResult = getDocumentFormattingEditsUntilResult;
    exports.getOnTypeFormattingEdits = getOnTypeFormattingEdits;
    function getRealAndSyntheticDocumentFormattersOrdered(documentFormattingEditProvider, documentRangeFormattingEditProvider, model) {
        const result = [];
        const seen = new extensions_1.ExtensionIdentifierSet();
        // (1) add all document formatter
        const docFormatter = documentFormattingEditProvider.ordered(model);
        for (const formatter of docFormatter) {
            result.push(formatter);
            if (formatter.extensionId) {
                seen.add(formatter.extensionId);
            }
        }
        // (2) add all range formatter as document formatter (unless the same extension already did that)
        const rangeFormatter = documentRangeFormattingEditProvider.ordered(model);
        for (const formatter of rangeFormatter) {
            if (formatter.extensionId) {
                if (seen.has(formatter.extensionId)) {
                    continue;
                }
                seen.add(formatter.extensionId);
            }
            result.push({
                displayName: formatter.displayName,
                extensionId: formatter.extensionId,
                provideDocumentFormattingEdits(model, options, token) {
                    return formatter.provideDocumentRangeFormattingEdits(model, model.getFullModelRange(), options, token);
                }
            });
        }
        return result;
    }
    class FormattingConflicts {
        static { this._selectors = new linkedList_1.LinkedList(); }
        static setFormatterSelector(selector) {
            const remove = FormattingConflicts._selectors.unshift(selector);
            return { dispose: remove };
        }
        static async select(formatter, document, mode, kind) {
            if (formatter.length === 0) {
                return undefined;
            }
            const selector = iterator_1.Iterable.first(FormattingConflicts._selectors);
            if (selector) {
                return await selector(formatter, document, mode, kind);
            }
            return undefined;
        }
    }
    exports.FormattingConflicts = FormattingConflicts;
    async function formatDocumentRangesWithSelectedProvider(accessor, editorOrModel, rangeOrRanges, mode, progress, token, userGesture) {
        const instaService = accessor.get(instantiation_1.IInstantiationService);
        const { documentRangeFormattingEditProvider: documentRangeFormattingEditProviderRegistry } = accessor.get(languageFeatures_1.ILanguageFeaturesService);
        const model = (0, editorBrowser_1.isCodeEditor)(editorOrModel) ? editorOrModel.getModel() : editorOrModel;
        const provider = documentRangeFormattingEditProviderRegistry.ordered(model);
        const selected = await FormattingConflicts.select(provider, model, mode, 2 /* FormattingKind.Selection */);
        if (selected) {
            progress.report(selected);
            await instaService.invokeFunction(formatDocumentRangesWithProvider, selected, editorOrModel, rangeOrRanges, token, userGesture);
        }
    }
    async function formatDocumentRangesWithProvider(accessor, provider, editorOrModel, rangeOrRanges, token, userGesture) {
        const workerService = accessor.get(editorWorker_1.IEditorWorkerService);
        const logService = accessor.get(log_1.ILogService);
        const accessibilitySignalService = accessor.get(accessibilitySignalService_1.IAccessibilitySignalService);
        let model;
        let cts;
        if ((0, editorBrowser_1.isCodeEditor)(editorOrModel)) {
            model = editorOrModel.getModel();
            cts = new editorState_1.EditorStateCancellationTokenSource(editorOrModel, 1 /* CodeEditorStateFlag.Value */ | 4 /* CodeEditorStateFlag.Position */, undefined, token);
        }
        else {
            model = editorOrModel;
            cts = new editorState_1.TextModelCancellationTokenSource(editorOrModel, token);
        }
        // make sure that ranges don't overlap nor touch each other
        const ranges = [];
        let len = 0;
        for (const range of (0, arrays_1.asArray)(rangeOrRanges).sort(range_1.Range.compareRangesUsingStarts)) {
            if (len > 0 && range_1.Range.areIntersectingOrTouching(ranges[len - 1], range)) {
                ranges[len - 1] = range_1.Range.fromPositions(ranges[len - 1].getStartPosition(), range.getEndPosition());
            }
            else {
                len = ranges.push(range);
            }
        }
        const computeEdits = async (range) => {
            logService.trace(`[format][provideDocumentRangeFormattingEdits] (request)`, provider.extensionId?.value, range);
            const result = (await provider.provideDocumentRangeFormattingEdits(model, range, model.getFormattingOptions(), cts.token)) || [];
            logService.trace(`[format][provideDocumentRangeFormattingEdits] (response)`, provider.extensionId?.value, result);
            return result;
        };
        const hasIntersectingEdit = (a, b) => {
            if (!a.length || !b.length) {
                return false;
            }
            // quick exit if the list of ranges are completely unrelated [O(n)]
            const mergedA = a.reduce((acc, val) => { return range_1.Range.plusRange(acc, val.range); }, a[0].range);
            if (!b.some(x => { return range_1.Range.intersectRanges(mergedA, x.range); })) {
                return false;
            }
            // fallback to a complete check [O(n^2)]
            for (const edit of a) {
                for (const otherEdit of b) {
                    if (range_1.Range.intersectRanges(edit.range, otherEdit.range)) {
                        return true;
                    }
                }
            }
            return false;
        };
        const allEdits = [];
        const rawEditsList = [];
        try {
            if (typeof provider.provideDocumentRangesFormattingEdits === 'function') {
                logService.trace(`[format][provideDocumentRangeFormattingEdits] (request)`, provider.extensionId?.value, ranges);
                const result = (await provider.provideDocumentRangesFormattingEdits(model, ranges, model.getFormattingOptions(), cts.token)) || [];
                logService.trace(`[format][provideDocumentRangeFormattingEdits] (response)`, provider.extensionId?.value, result);
                rawEditsList.push(result);
            }
            else {
                for (const range of ranges) {
                    if (cts.token.isCancellationRequested) {
                        return true;
                    }
                    rawEditsList.push(await computeEdits(range));
                }
                for (let i = 0; i < ranges.length; ++i) {
                    for (let j = i + 1; j < ranges.length; ++j) {
                        if (cts.token.isCancellationRequested) {
                            return true;
                        }
                        if (hasIntersectingEdit(rawEditsList[i], rawEditsList[j])) {
                            // Merge ranges i and j into a single range, recompute the associated edits
                            const mergedRange = range_1.Range.plusRange(ranges[i], ranges[j]);
                            const edits = await computeEdits(mergedRange);
                            ranges.splice(j, 1);
                            ranges.splice(i, 1);
                            ranges.push(mergedRange);
                            rawEditsList.splice(j, 1);
                            rawEditsList.splice(i, 1);
                            rawEditsList.push(edits);
                            // Restart scanning
                            i = 0;
                            j = 0;
                        }
                    }
                }
            }
            for (const rawEdits of rawEditsList) {
                if (cts.token.isCancellationRequested) {
                    return true;
                }
                const minimalEdits = await workerService.computeMoreMinimalEdits(model.uri, rawEdits);
                if (minimalEdits) {
                    allEdits.push(...minimalEdits);
                }
            }
        }
        finally {
            cts.dispose();
        }
        if (allEdits.length === 0) {
            return false;
        }
        if ((0, editorBrowser_1.isCodeEditor)(editorOrModel)) {
            // use editor to apply edits
            formattingEdit_1.FormattingEdit.execute(editorOrModel, allEdits, true);
            editorOrModel.revealPositionInCenterIfOutsideViewport(editorOrModel.getPosition(), 1 /* ScrollType.Immediate */);
        }
        else {
            // use model to apply edits
            const [{ range }] = allEdits;
            const initialSelection = new selection_1.Selection(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn);
            model.pushEditOperations([initialSelection], allEdits.map(edit => {
                return {
                    text: edit.text,
                    range: range_1.Range.lift(edit.range),
                    forceMoveMarkers: true
                };
            }), undoEdits => {
                for (const { range } of undoEdits) {
                    if (range_1.Range.areIntersectingOrTouching(range, initialSelection)) {
                        return [new selection_1.Selection(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn)];
                    }
                }
                return null;
            });
        }
        accessibilitySignalService.playSignal(accessibilitySignalService_1.AccessibilitySignal.format, { userGesture });
        return true;
    }
    async function formatDocumentWithSelectedProvider(accessor, editorOrModel, mode, progress, token, userGesture) {
        const instaService = accessor.get(instantiation_1.IInstantiationService);
        const languageFeaturesService = accessor.get(languageFeatures_1.ILanguageFeaturesService);
        const model = (0, editorBrowser_1.isCodeEditor)(editorOrModel) ? editorOrModel.getModel() : editorOrModel;
        const provider = getRealAndSyntheticDocumentFormattersOrdered(languageFeaturesService.documentFormattingEditProvider, languageFeaturesService.documentRangeFormattingEditProvider, model);
        const selected = await FormattingConflicts.select(provider, model, mode, 1 /* FormattingKind.File */);
        if (selected) {
            progress.report(selected);
            await instaService.invokeFunction(formatDocumentWithProvider, selected, editorOrModel, mode, token, userGesture);
        }
    }
    async function formatDocumentWithProvider(accessor, provider, editorOrModel, mode, token, userGesture) {
        const workerService = accessor.get(editorWorker_1.IEditorWorkerService);
        const accessibilitySignalService = accessor.get(accessibilitySignalService_1.IAccessibilitySignalService);
        let model;
        let cts;
        if ((0, editorBrowser_1.isCodeEditor)(editorOrModel)) {
            model = editorOrModel.getModel();
            cts = new editorState_1.EditorStateCancellationTokenSource(editorOrModel, 1 /* CodeEditorStateFlag.Value */ | 4 /* CodeEditorStateFlag.Position */, undefined, token);
        }
        else {
            model = editorOrModel;
            cts = new editorState_1.TextModelCancellationTokenSource(editorOrModel, token);
        }
        let edits;
        try {
            const rawEdits = await provider.provideDocumentFormattingEdits(model, model.getFormattingOptions(), cts.token);
            edits = await workerService.computeMoreMinimalEdits(model.uri, rawEdits);
            if (cts.token.isCancellationRequested) {
                return true;
            }
        }
        finally {
            cts.dispose();
        }
        if (!edits || edits.length === 0) {
            return false;
        }
        if ((0, editorBrowser_1.isCodeEditor)(editorOrModel)) {
            // use editor to apply edits
            formattingEdit_1.FormattingEdit.execute(editorOrModel, edits, mode !== 2 /* FormattingMode.Silent */);
            if (mode !== 2 /* FormattingMode.Silent */) {
                editorOrModel.revealPositionInCenterIfOutsideViewport(editorOrModel.getPosition(), 1 /* ScrollType.Immediate */);
            }
        }
        else {
            // use model to apply edits
            const [{ range }] = edits;
            const initialSelection = new selection_1.Selection(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn);
            model.pushEditOperations([initialSelection], edits.map(edit => {
                return {
                    text: edit.text,
                    range: range_1.Range.lift(edit.range),
                    forceMoveMarkers: true
                };
            }), undoEdits => {
                for (const { range } of undoEdits) {
                    if (range_1.Range.areIntersectingOrTouching(range, initialSelection)) {
                        return [new selection_1.Selection(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn)];
                    }
                }
                return null;
            });
        }
        accessibilitySignalService.playSignal(accessibilitySignalService_1.AccessibilitySignal.format, { userGesture });
        return true;
    }
    async function getDocumentRangeFormattingEditsUntilResult(workerService, languageFeaturesService, model, range, options, token) {
        const providers = languageFeaturesService.documentRangeFormattingEditProvider.ordered(model);
        for (const provider of providers) {
            const rawEdits = await Promise.resolve(provider.provideDocumentRangeFormattingEdits(model, range, options, token)).catch(errors_1.onUnexpectedExternalError);
            if ((0, arrays_1.isNonEmptyArray)(rawEdits)) {
                return await workerService.computeMoreMinimalEdits(model.uri, rawEdits);
            }
        }
        return undefined;
    }
    async function getDocumentFormattingEditsUntilResult(workerService, languageFeaturesService, model, options, token) {
        const providers = getRealAndSyntheticDocumentFormattersOrdered(languageFeaturesService.documentFormattingEditProvider, languageFeaturesService.documentRangeFormattingEditProvider, model);
        for (const provider of providers) {
            const rawEdits = await Promise.resolve(provider.provideDocumentFormattingEdits(model, options, token)).catch(errors_1.onUnexpectedExternalError);
            if ((0, arrays_1.isNonEmptyArray)(rawEdits)) {
                return await workerService.computeMoreMinimalEdits(model.uri, rawEdits);
            }
        }
        return undefined;
    }
    function getOnTypeFormattingEdits(workerService, languageFeaturesService, model, position, ch, options, token) {
        const providers = languageFeaturesService.onTypeFormattingEditProvider.ordered(model);
        if (providers.length === 0) {
            return Promise.resolve(undefined);
        }
        if (providers[0].autoFormatTriggerCharacters.indexOf(ch) < 0) {
            return Promise.resolve(undefined);
        }
        return Promise.resolve(providers[0].provideOnTypeFormattingEdits(model, position, ch, options, token)).catch(errors_1.onUnexpectedExternalError).then(edits => {
            return workerService.computeMoreMinimalEdits(model.uri, edits);
        });
    }
    commands_1.CommandsRegistry.registerCommand('_executeFormatRangeProvider', async function (accessor, ...args) {
        const [resource, range, options] = args;
        (0, types_1.assertType)(uri_1.URI.isUri(resource));
        (0, types_1.assertType)(range_1.Range.isIRange(range));
        const resolverService = accessor.get(resolverService_1.ITextModelService);
        const workerService = accessor.get(editorWorker_1.IEditorWorkerService);
        const languageFeaturesService = accessor.get(languageFeatures_1.ILanguageFeaturesService);
        const reference = await resolverService.createModelReference(resource);
        try {
            return getDocumentRangeFormattingEditsUntilResult(workerService, languageFeaturesService, reference.object.textEditorModel, range_1.Range.lift(range), options, cancellation_1.CancellationToken.None);
        }
        finally {
            reference.dispose();
        }
    });
    commands_1.CommandsRegistry.registerCommand('_executeFormatDocumentProvider', async function (accessor, ...args) {
        const [resource, options] = args;
        (0, types_1.assertType)(uri_1.URI.isUri(resource));
        const resolverService = accessor.get(resolverService_1.ITextModelService);
        const workerService = accessor.get(editorWorker_1.IEditorWorkerService);
        const languageFeaturesService = accessor.get(languageFeatures_1.ILanguageFeaturesService);
        const reference = await resolverService.createModelReference(resource);
        try {
            return getDocumentFormattingEditsUntilResult(workerService, languageFeaturesService, reference.object.textEditorModel, options, cancellation_1.CancellationToken.None);
        }
        finally {
            reference.dispose();
        }
    });
    commands_1.CommandsRegistry.registerCommand('_executeFormatOnTypeProvider', async function (accessor, ...args) {
        const [resource, position, ch, options] = args;
        (0, types_1.assertType)(uri_1.URI.isUri(resource));
        (0, types_1.assertType)(position_1.Position.isIPosition(position));
        (0, types_1.assertType)(typeof ch === 'string');
        const resolverService = accessor.get(resolverService_1.ITextModelService);
        const workerService = accessor.get(editorWorker_1.IEditorWorkerService);
        const languageFeaturesService = accessor.get(languageFeatures_1.ILanguageFeaturesService);
        const reference = await resolverService.createModelReference(resource);
        try {
            return getOnTypeFormattingEdits(workerService, languageFeaturesService, reference.object.textEditorModel, position_1.Position.lift(position), ch, options, cancellation_1.CancellationToken.None);
        }
        finally {
            reference.dispose();
        }
    });
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[735/*vs/editor/contrib/format/browser/formatActions*/], __M([1/*require*/,0/*exports*/,13/*vs/base/common/arrays*/,18/*vs/base/common/cancellation*/,8/*vs/base/common/errors*/,72/*vs/base/common/keyCodes*/,2/*vs/base/common/lifecycle*/,15/*vs/editor/browser/editorExtensions*/,34/*vs/editor/browser/services/codeEditorService*/,144/*vs/editor/common/core/characterClassifier*/,4/*vs/editor/common/core/range*/,20/*vs/editor/common/editorContextKeys*/,100/*vs/editor/common/services/editorWorker*/,17/*vs/editor/common/services/languageFeatures*/,409/*vs/editor/contrib/format/browser/format*/,337/*vs/editor/contrib/format/browser/formattingEdit*/,3/*vs/nls*/,137/*vs/platform/accessibilitySignal/browser/accessibilitySignalService*/,24/*vs/platform/commands/common/commands*/,12/*vs/platform/contextkey/common/contextkey*/,7/*vs/platform/instantiation/common/instantiation*/,96/*vs/platform/progress/common/progress*/]), function (require, exports, arrays_1, cancellation_1, errors_1, keyCodes_1, lifecycle_1, editorExtensions_1, codeEditorService_1, characterClassifier_1, range_1, editorContextKeys_1, editorWorker_1, languageFeatures_1, format_1, formattingEdit_1, nls, accessibilitySignalService_1, commands_1, contextkey_1, instantiation_1, progress_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.FormatOnType = void 0;
    let FormatOnType = class FormatOnType {
        static { this.ID = 'editor.contrib.autoFormat'; }
        constructor(_editor, _languageFeaturesService, _workerService, _accessibilitySignalService) {
            this._editor = _editor;
            this._languageFeaturesService = _languageFeaturesService;
            this._workerService = _workerService;
            this._accessibilitySignalService = _accessibilitySignalService;
            this._disposables = new lifecycle_1.DisposableStore();
            this._sessionDisposables = new lifecycle_1.DisposableStore();
            this._disposables.add(_languageFeaturesService.onTypeFormattingEditProvider.onDidChange(this._update, this));
            this._disposables.add(_editor.onDidChangeModel(() => this._update()));
            this._disposables.add(_editor.onDidChangeModelLanguage(() => this._update()));
            this._disposables.add(_editor.onDidChangeConfiguration(e => {
                if (e.hasChanged(56 /* EditorOption.formatOnType */)) {
                    this._update();
                }
            }));
            this._update();
        }
        dispose() {
            this._disposables.dispose();
            this._sessionDisposables.dispose();
        }
        _update() {
            // clean up
            this._sessionDisposables.clear();
            // we are disabled
            if (!this._editor.getOption(56 /* EditorOption.formatOnType */)) {
                return;
            }
            // no model
            if (!this._editor.hasModel()) {
                return;
            }
            const model = this._editor.getModel();
            // no support
            const [support] = this._languageFeaturesService.onTypeFormattingEditProvider.ordered(model);
            if (!support || !support.autoFormatTriggerCharacters) {
                return;
            }
            // register typing listeners that will trigger the format
            const triggerChars = new characterClassifier_1.CharacterSet();
            for (const ch of support.autoFormatTriggerCharacters) {
                triggerChars.add(ch.charCodeAt(0));
            }
            this._sessionDisposables.add(this._editor.onDidType((text) => {
                const lastCharCode = text.charCodeAt(text.length - 1);
                if (triggerChars.has(lastCharCode)) {
                    this._trigger(String.fromCharCode(lastCharCode));
                }
            }));
        }
        _trigger(ch) {
            if (!this._editor.hasModel()) {
                return;
            }
            if (this._editor.getSelections().length > 1 || !this._editor.getSelection().isEmpty()) {
                return;
            }
            const model = this._editor.getModel();
            const position = this._editor.getPosition();
            const cts = new cancellation_1.CancellationTokenSource();
            // install a listener that checks if edits happens before the
            // position on which we format right now. If so, we won't
            // apply the format edits
            const unbind = this._editor.onDidChangeModelContent((e) => {
                if (e.isFlush) {
                    // a model.setValue() was called
                    // cancel only once
                    cts.cancel();
                    unbind.dispose();
                    return;
                }
                for (let i = 0, len = e.changes.length; i < len; i++) {
                    const change = e.changes[i];
                    if (change.range.endLineNumber <= position.lineNumber) {
                        // cancel only once
                        cts.cancel();
                        unbind.dispose();
                        return;
                    }
                }
            });
            (0, format_1.getOnTypeFormattingEdits)(this._workerService, this._languageFeaturesService, model, position, ch, model.getFormattingOptions(), cts.token).then(edits => {
                if (cts.token.isCancellationRequested) {
                    return;
                }
                if ((0, arrays_1.isNonEmptyArray)(edits)) {
                    this._accessibilitySignalService.playSignal(accessibilitySignalService_1.AccessibilitySignal.format, { userGesture: false });
                    formattingEdit_1.FormattingEdit.execute(this._editor, edits, true);
                }
            }).finally(() => {
                unbind.dispose();
            });
        }
    };
    exports.FormatOnType = FormatOnType;
    exports.FormatOnType = FormatOnType = __decorate([
        __param(1, languageFeatures_1.ILanguageFeaturesService),
        __param(2, editorWorker_1.IEditorWorkerService),
        __param(3, accessibilitySignalService_1.IAccessibilitySignalService)
    ], FormatOnType);
    let FormatOnPaste = class FormatOnPaste {
        static { this.ID = 'editor.contrib.formatOnPaste'; }
        constructor(editor, _languageFeaturesService, _instantiationService) {
            this.editor = editor;
            this._languageFeaturesService = _languageFeaturesService;
            this._instantiationService = _instantiationService;
            this._callOnDispose = new lifecycle_1.DisposableStore();
            this._callOnModel = new lifecycle_1.DisposableStore();
            this._callOnDispose.add(editor.onDidChangeConfiguration(() => this._update()));
            this._callOnDispose.add(editor.onDidChangeModel(() => this._update()));
            this._callOnDispose.add(editor.onDidChangeModelLanguage(() => this._update()));
            this._callOnDispose.add(_languageFeaturesService.documentRangeFormattingEditProvider.onDidChange(this._update, this));
        }
        dispose() {
            this._callOnDispose.dispose();
            this._callOnModel.dispose();
        }
        _update() {
            // clean up
            this._callOnModel.clear();
            // we are disabled
            if (!this.editor.getOption(55 /* EditorOption.formatOnPaste */)) {
                return;
            }
            // no model
            if (!this.editor.hasModel()) {
                return;
            }
            // no formatter
            if (!this._languageFeaturesService.documentRangeFormattingEditProvider.has(this.editor.getModel())) {
                return;
            }
            this._callOnModel.add(this.editor.onDidPaste(({ range }) => this._trigger(range)));
        }
        _trigger(range) {
            if (!this.editor.hasModel()) {
                return;
            }
            if (this.editor.getSelections().length > 1) {
                return;
            }
            this._instantiationService.invokeFunction(format_1.formatDocumentRangesWithSelectedProvider, this.editor, range, 2 /* FormattingMode.Silent */, progress_1.Progress.None, cancellation_1.CancellationToken.None, false).catch(errors_1.onUnexpectedError);
        }
    };
    FormatOnPaste = __decorate([
        __param(1, languageFeatures_1.ILanguageFeaturesService),
        __param(2, instantiation_1.IInstantiationService)
    ], FormatOnPaste);
    class FormatDocumentAction extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: 'editor.action.formatDocument',
                label: nls.localize(922, "Format Document"),
                alias: 'Format Document',
                precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.notInCompositeEditor, editorContextKeys_1.EditorContextKeys.writable, editorContextKeys_1.EditorContextKeys.hasDocumentFormattingProvider),
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    primary: 1024 /* KeyMod.Shift */ | 512 /* KeyMod.Alt */ | 36 /* KeyCode.KeyF */,
                    linux: { primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 39 /* KeyCode.KeyI */ },
                    weight: 100 /* KeybindingWeight.EditorContrib */
                },
                contextMenuOpts: {
                    group: '1_modification',
                    order: 1.3
                }
            });
        }
        async run(accessor, editor) {
            if (editor.hasModel()) {
                const instaService = accessor.get(instantiation_1.IInstantiationService);
                const progressService = accessor.get(progress_1.IEditorProgressService);
                await progressService.showWhile(instaService.invokeFunction(format_1.formatDocumentWithSelectedProvider, editor, 1 /* FormattingMode.Explicit */, progress_1.Progress.None, cancellation_1.CancellationToken.None, true), 250);
            }
        }
    }
    class FormatSelectionAction extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: 'editor.action.formatSelection',
                label: nls.localize(923, "Format Selection"),
                alias: 'Format Selection',
                precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, editorContextKeys_1.EditorContextKeys.hasDocumentSelectionFormattingProvider),
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    primary: (0, keyCodes_1.KeyChord)(2048 /* KeyMod.CtrlCmd */ | 41 /* KeyCode.KeyK */, 2048 /* KeyMod.CtrlCmd */ | 36 /* KeyCode.KeyF */),
                    weight: 100 /* KeybindingWeight.EditorContrib */
                },
                contextMenuOpts: {
                    when: editorContextKeys_1.EditorContextKeys.hasNonEmptySelection,
                    group: '1_modification',
                    order: 1.31
                }
            });
        }
        async run(accessor, editor) {
            if (!editor.hasModel()) {
                return;
            }
            const instaService = accessor.get(instantiation_1.IInstantiationService);
            const model = editor.getModel();
            const ranges = editor.getSelections().map(range => {
                return range.isEmpty()
                    ? new range_1.Range(range.startLineNumber, 1, range.startLineNumber, model.getLineMaxColumn(range.startLineNumber))
                    : range;
            });
            const progressService = accessor.get(progress_1.IEditorProgressService);
            await progressService.showWhile(instaService.invokeFunction(format_1.formatDocumentRangesWithSelectedProvider, editor, ranges, 1 /* FormattingMode.Explicit */, progress_1.Progress.None, cancellation_1.CancellationToken.None, true), 250);
        }
    }
    (0, editorExtensions_1.registerEditorContribution)(FormatOnType.ID, FormatOnType, 2 /* EditorContributionInstantiation.BeforeFirstInteraction */);
    (0, editorExtensions_1.registerEditorContribution)(FormatOnPaste.ID, FormatOnPaste, 2 /* EditorContributionInstantiation.BeforeFirstInteraction */);
    (0, editorExtensions_1.registerEditorAction)(FormatDocumentAction);
    (0, editorExtensions_1.registerEditorAction)(FormatSelectionAction);
    // this is the old format action that does both (format document OR format selection)
    // and we keep it here such that existing keybinding configurations etc will still work
    commands_1.CommandsRegistry.registerCommand('editor.action.format', async (accessor) => {
        const editor = accessor.get(codeEditorService_1.ICodeEditorService).getFocusedCodeEditor();
        if (!editor || !editor.hasModel()) {
            return;
        }
        const commandService = accessor.get(commands_1.ICommandService);
        if (editor.getSelection().isEmpty()) {
            await commandService.executeCommand('editor.action.formatDocument');
        }
        else {
            await commandService.executeCommand('editor.action.formatSelection');
        }
    });
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[277/*vs/editor/contrib/gotoSymbol/browser/goToSymbol*/], __M([1/*require*/,0/*exports*/,13/*vs/base/common/arrays*/,18/*vs/base/common/cancellation*/,8/*vs/base/common/errors*/,42/*vs/base/common/network*/,15/*vs/editor/browser/editorExtensions*/,17/*vs/editor/common/services/languageFeatures*/,178/*vs/editor/contrib/gotoSymbol/browser/referencesModel*/]), function (require, exports, arrays_1, cancellation_1, errors_1, network_1, editorExtensions_1, languageFeatures_1, referencesModel_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.getDefinitionsAtPosition = getDefinitionsAtPosition;
    exports.getDeclarationsAtPosition = getDeclarationsAtPosition;
    exports.getImplementationsAtPosition = getImplementationsAtPosition;
    exports.getTypeDefinitionsAtPosition = getTypeDefinitionsAtPosition;
    exports.getReferencesAtPosition = getReferencesAtPosition;
    function shouldIncludeLocationLink(sourceModel, loc) {
        // Always allow the location if the request comes from a document with the same scheme.
        if (loc.uri.scheme === sourceModel.uri.scheme) {
            return true;
        }
        // Otherwise filter out locations from internal schemes
        if ((0, network_1.matchesSomeScheme)(loc.uri, network_1.Schemas.walkThroughSnippet, network_1.Schemas.vscodeChatCodeBlock, network_1.Schemas.vscodeChatCodeCompareBlock)) {
            return false;
        }
        return true;
    }
    async function getLocationLinks(model, position, registry, recursive, provide) {
        const provider = registry.ordered(model, recursive);
        // get results
        const promises = provider.map((provider) => {
            return Promise.resolve(provide(provider, model, position)).then(undefined, err => {
                (0, errors_1.onUnexpectedExternalError)(err);
                return undefined;
            });
        });
        const values = await Promise.all(promises);
        return (0, arrays_1.coalesce)(values.flat()).filter(loc => shouldIncludeLocationLink(model, loc));
    }
    function getDefinitionsAtPosition(registry, model, position, recursive, token) {
        return getLocationLinks(model, position, registry, recursive, (provider, model, position) => {
            return provider.provideDefinition(model, position, token);
        });
    }
    function getDeclarationsAtPosition(registry, model, position, recursive, token) {
        return getLocationLinks(model, position, registry, recursive, (provider, model, position) => {
            return provider.provideDeclaration(model, position, token);
        });
    }
    function getImplementationsAtPosition(registry, model, position, recursive, token) {
        return getLocationLinks(model, position, registry, recursive, (provider, model, position) => {
            return provider.provideImplementation(model, position, token);
        });
    }
    function getTypeDefinitionsAtPosition(registry, model, position, recursive, token) {
        return getLocationLinks(model, position, registry, recursive, (provider, model, position) => {
            return provider.provideTypeDefinition(model, position, token);
        });
    }
    function getReferencesAtPosition(registry, model, position, compact, recursive, token) {
        return getLocationLinks(model, position, registry, recursive, async (provider, model, position) => {
            const result = (await provider.provideReferences(model, position, { includeDeclaration: true }, token))?.filter(ref => shouldIncludeLocationLink(model, ref));
            if (!compact || !result || result.length !== 2) {
                return result;
            }
            const resultWithoutDeclaration = (await provider.provideReferences(model, position, { includeDeclaration: false }, token))?.filter(ref => shouldIncludeLocationLink(model, ref));
            if (resultWithoutDeclaration && resultWithoutDeclaration.length === 1) {
                return resultWithoutDeclaration;
            }
            return result;
        });
    }
    // -- API commands ----
    async function _sortedAndDeduped(callback) {
        const rawLinks = await callback();
        const model = new referencesModel_1.ReferencesModel(rawLinks, '');
        const modelLinks = model.references.map(ref => ref.link);
        model.dispose();
        return modelLinks;
    }
    (0, editorExtensions_1.registerModelAndPositionCommand)('_executeDefinitionProvider', (accessor, model, position) => {
        const languageFeaturesService = accessor.get(languageFeatures_1.ILanguageFeaturesService);
        const promise = getDefinitionsAtPosition(languageFeaturesService.definitionProvider, model, position, false, cancellation_1.CancellationToken.None);
        return _sortedAndDeduped(() => promise);
    });
    (0, editorExtensions_1.registerModelAndPositionCommand)('_executeDefinitionProvider_recursive', (accessor, model, position) => {
        const languageFeaturesService = accessor.get(languageFeatures_1.ILanguageFeaturesService);
        const promise = getDefinitionsAtPosition(languageFeaturesService.definitionProvider, model, position, true, cancellation_1.CancellationToken.None);
        return _sortedAndDeduped(() => promise);
    });
    (0, editorExtensions_1.registerModelAndPositionCommand)('_executeTypeDefinitionProvider', (accessor, model, position) => {
        const languageFeaturesService = accessor.get(languageFeatures_1.ILanguageFeaturesService);
        const promise = getTypeDefinitionsAtPosition(languageFeaturesService.typeDefinitionProvider, model, position, false, cancellation_1.CancellationToken.None);
        return _sortedAndDeduped(() => promise);
    });
    (0, editorExtensions_1.registerModelAndPositionCommand)('_executeTypeDefinitionProvider_recursive', (accessor, model, position) => {
        const languageFeaturesService = accessor.get(languageFeatures_1.ILanguageFeaturesService);
        const promise = getTypeDefinitionsAtPosition(languageFeaturesService.typeDefinitionProvider, model, position, true, cancellation_1.CancellationToken.None);
        return _sortedAndDeduped(() => promise);
    });
    (0, editorExtensions_1.registerModelAndPositionCommand)('_executeDeclarationProvider', (accessor, model, position) => {
        const languageFeaturesService = accessor.get(languageFeatures_1.ILanguageFeaturesService);
        const promise = getDeclarationsAtPosition(languageFeaturesService.declarationProvider, model, position, false, cancellation_1.CancellationToken.None);
        return _sortedAndDeduped(() => promise);
    });
    (0, editorExtensions_1.registerModelAndPositionCommand)('_executeDeclarationProvider_recursive', (accessor, model, position) => {
        const languageFeaturesService = accessor.get(languageFeatures_1.ILanguageFeaturesService);
        const promise = getDeclarationsAtPosition(languageFeaturesService.declarationProvider, model, position, true, cancellation_1.CancellationToken.None);
        return _sortedAndDeduped(() => promise);
    });
    (0, editorExtensions_1.registerModelAndPositionCommand)('_executeReferenceProvider', (accessor, model, position) => {
        const languageFeaturesService = accessor.get(languageFeatures_1.ILanguageFeaturesService);
        const promise = getReferencesAtPosition(languageFeaturesService.referenceProvider, model, position, false, false, cancellation_1.CancellationToken.None);
        return _sortedAndDeduped(() => promise);
    });
    (0, editorExtensions_1.registerModelAndPositionCommand)('_executeReferenceProvider_recursive', (accessor, model, position) => {
        const languageFeaturesService = accessor.get(languageFeatures_1.ILanguageFeaturesService);
        const promise = getReferencesAtPosition(languageFeaturesService.referenceProvider, model, position, false, true, cancellation_1.CancellationToken.None);
        return _sortedAndDeduped(() => promise);
    });
    (0, editorExtensions_1.registerModelAndPositionCommand)('_executeImplementationProvider', (accessor, model, position) => {
        const languageFeaturesService = accessor.get(languageFeatures_1.ILanguageFeaturesService);
        const promise = getImplementationsAtPosition(languageFeaturesService.implementationProvider, model, position, false, cancellation_1.CancellationToken.None);
        return _sortedAndDeduped(() => promise);
    });
    (0, editorExtensions_1.registerModelAndPositionCommand)('_executeImplementationProvider_recursive', (accessor, model, position) => {
        const languageFeaturesService = accessor.get(languageFeatures_1.ILanguageFeaturesService);
        const promise = getImplementationsAtPosition(languageFeaturesService.implementationProvider, model, position, true, cancellation_1.CancellationToken.None);
        return _sortedAndDeduped(() => promise);
    });
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[736/*vs/editor/contrib/gotoSymbol/browser/symbolNavigation*/], __M([1/*require*/,0/*exports*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,48/*vs/base/common/resources*/,15/*vs/editor/browser/editorExtensions*/,34/*vs/editor/browser/services/codeEditorService*/,4/*vs/editor/common/core/range*/,3/*vs/nls*/,12/*vs/platform/contextkey/common/contextkey*/,49/*vs/platform/instantiation/common/extensions*/,7/*vs/platform/instantiation/common/instantiation*/,31/*vs/platform/keybinding/common/keybinding*/,121/*vs/platform/keybinding/common/keybindingsRegistry*/,50/*vs/platform/notification/common/notification*/]), function (require, exports, event_1, lifecycle_1, resources_1, editorExtensions_1, codeEditorService_1, range_1, nls_1, contextkey_1, extensions_1, instantiation_1, keybinding_1, keybindingsRegistry_1, notification_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ISymbolNavigationService = exports.ctxHasSymbols = void 0;
    exports.ctxHasSymbols = new contextkey_1.RawContextKey('hasSymbols', false, (0, nls_1.localize)(1003, "Whether there are symbol locations that can be navigated via keyboard-only."));
    exports.ISymbolNavigationService = (0, instantiation_1.createDecorator)('ISymbolNavigationService');
    let SymbolNavigationService = class SymbolNavigationService {
        constructor(contextKeyService, _editorService, _notificationService, _keybindingService) {
            this._editorService = _editorService;
            this._notificationService = _notificationService;
            this._keybindingService = _keybindingService;
            this._currentModel = undefined;
            this._currentIdx = -1;
            this._ignoreEditorChange = false;
            this._ctxHasSymbols = exports.ctxHasSymbols.bindTo(contextKeyService);
        }
        reset() {
            this._ctxHasSymbols.reset();
            this._currentState?.dispose();
            this._currentMessage?.dispose();
            this._currentModel = undefined;
            this._currentIdx = -1;
        }
        put(anchor) {
            const refModel = anchor.parent.parent;
            if (refModel.references.length <= 1) {
                this.reset();
                return;
            }
            this._currentModel = refModel;
            this._currentIdx = refModel.references.indexOf(anchor);
            this._ctxHasSymbols.set(true);
            this._showMessage();
            const editorState = new EditorState(this._editorService);
            const listener = editorState.onDidChange(_ => {
                if (this._ignoreEditorChange) {
                    return;
                }
                const editor = this._editorService.getActiveCodeEditor();
                if (!editor) {
                    return;
                }
                const model = editor.getModel();
                const position = editor.getPosition();
                if (!model || !position) {
                    return;
                }
                let seenUri = false;
                let seenPosition = false;
                for (const reference of refModel.references) {
                    if ((0, resources_1.isEqual)(reference.uri, model.uri)) {
                        seenUri = true;
                        seenPosition = seenPosition || range_1.Range.containsPosition(reference.range, position);
                    }
                    else if (seenUri) {
                        break;
                    }
                }
                if (!seenUri || !seenPosition) {
                    this.reset();
                }
            });
            this._currentState = (0, lifecycle_1.combinedDisposable)(editorState, listener);
        }
        revealNext(source) {
            if (!this._currentModel) {
                return Promise.resolve();
            }
            // get next result and advance
            this._currentIdx += 1;
            this._currentIdx %= this._currentModel.references.length;
            const reference = this._currentModel.references[this._currentIdx];
            // status
            this._showMessage();
            // open editor, ignore events while that happens
            this._ignoreEditorChange = true;
            return this._editorService.openCodeEditor({
                resource: reference.uri,
                options: {
                    selection: range_1.Range.collapseToStart(reference.range),
                    selectionRevealType: 3 /* TextEditorSelectionRevealType.NearTopIfOutsideViewport */
                }
            }, source).finally(() => {
                this._ignoreEditorChange = false;
            });
        }
        _showMessage() {
            this._currentMessage?.dispose();
            const kb = this._keybindingService.lookupKeybinding('editor.gotoNextSymbolFromResult');
            const message = kb
                ? (0, nls_1.localize)(1004, "Symbol {0} of {1}, {2} for next", this._currentIdx + 1, this._currentModel.references.length, kb.getLabel())
                : (0, nls_1.localize)(1005, "Symbol {0} of {1}", this._currentIdx + 1, this._currentModel.references.length);
            this._currentMessage = this._notificationService.status(message);
        }
    };
    SymbolNavigationService = __decorate([
        __param(0, contextkey_1.IContextKeyService),
        __param(1, codeEditorService_1.ICodeEditorService),
        __param(2, notification_1.INotificationService),
        __param(3, keybinding_1.IKeybindingService)
    ], SymbolNavigationService);
    (0, extensions_1.registerSingleton)(exports.ISymbolNavigationService, SymbolNavigationService, 1 /* InstantiationType.Delayed */);
    (0, editorExtensions_1.registerEditorCommand)(new class extends editorExtensions_1.EditorCommand {
        constructor() {
            super({
                id: 'editor.gotoNextSymbolFromResult',
                precondition: exports.ctxHasSymbols,
                kbOpts: {
                    weight: 100 /* KeybindingWeight.EditorContrib */,
                    primary: 70 /* KeyCode.F12 */
                }
            });
        }
        runEditorCommand(accessor, editor) {
            return accessor.get(exports.ISymbolNavigationService).revealNext(editor);
        }
    });
    keybindingsRegistry_1.KeybindingsRegistry.registerCommandAndKeybindingRule({
        id: 'editor.gotoNextSymbolFromResult.cancel',
        weight: 100 /* KeybindingWeight.EditorContrib */,
        when: exports.ctxHasSymbols,
        primary: 9 /* KeyCode.Escape */,
        handler(accessor) {
            accessor.get(exports.ISymbolNavigationService).reset();
        }
    });
    //
    let EditorState = class EditorState {
        constructor(editorService) {
            this._listener = new Map();
            this._disposables = new lifecycle_1.DisposableStore();
            this._onDidChange = new event_1.Emitter();
            this.onDidChange = this._onDidChange.event;
            this._disposables.add(editorService.onCodeEditorRemove(this._onDidRemoveEditor, this));
            this._disposables.add(editorService.onCodeEditorAdd(this._onDidAddEditor, this));
            editorService.listCodeEditors().forEach(this._onDidAddEditor, this);
        }
        dispose() {
            this._disposables.dispose();
            this._onDidChange.dispose();
            (0, lifecycle_1.dispose)(this._listener.values());
        }
        _onDidAddEditor(editor) {
            this._listener.set(editor, (0, lifecycle_1.combinedDisposable)(editor.onDidChangeCursorPosition(_ => this._onDidChange.fire({ editor })), editor.onDidChangeModelContent(_ => this._onDidChange.fire({ editor }))));
        }
        _onDidRemoveEditor(editor) {
            this._listener.get(editor)?.dispose();
            this._listener.delete(editor);
        }
    };
    EditorState = __decorate([
        __param(0, codeEditorService_1.ICodeEditorService)
    ], EditorState);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[410/*vs/editor/contrib/hover/browser/getHover*/], __M([1/*require*/,0/*exports*/,14/*vs/base/common/async*/,18/*vs/base/common/cancellation*/,8/*vs/base/common/errors*/,15/*vs/editor/browser/editorExtensions*/,17/*vs/editor/common/services/languageFeatures*/]), function (require, exports, async_1, cancellation_1, errors_1, editorExtensions_1, languageFeatures_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.HoverProviderResult = void 0;
    exports.getHoverProviderResultsAsAsyncIterable = getHoverProviderResultsAsAsyncIterable;
    exports.getHoversPromise = getHoversPromise;
    class HoverProviderResult {
        constructor(provider, hover, ordinal) {
            this.provider = provider;
            this.hover = hover;
            this.ordinal = ordinal;
        }
    }
    exports.HoverProviderResult = HoverProviderResult;
    /**
     * Does not throw or return a rejected promise (returns undefined instead).
     */
    async function executeProvider(provider, ordinal, model, position, token) {
        const result = await Promise
            .resolve(provider.provideHover(model, position, token))
            .catch(errors_1.onUnexpectedExternalError);
        if (!result || !isValid(result)) {
            return undefined;
        }
        return new HoverProviderResult(provider, result, ordinal);
    }
    function getHoverProviderResultsAsAsyncIterable(registry, model, position, token, recursive = false) {
        const providers = registry.ordered(model, recursive);
        const promises = providers.map((provider, index) => executeProvider(provider, index, model, position, token));
        return async_1.AsyncIterableObject.fromPromises(promises).coalesce();
    }
    function getHoversPromise(registry, model, position, token, recursive = false) {
        return getHoverProviderResultsAsAsyncIterable(registry, model, position, token, recursive).map(item => item.hover).toPromise();
    }
    (0, editorExtensions_1.registerModelAndPositionCommand)('_executeHoverProvider', (accessor, model, position) => {
        const languageFeaturesService = accessor.get(languageFeatures_1.ILanguageFeaturesService);
        return getHoversPromise(languageFeaturesService.hoverProvider, model, position, cancellation_1.CancellationToken.None);
    });
    (0, editorExtensions_1.registerModelAndPositionCommand)('_executeHoverProvider_recursive', (accessor, model, position) => {
        const languageFeaturesService = accessor.get(languageFeatures_1.ILanguageFeaturesService);
        return getHoversPromise(languageFeaturesService.hoverProvider, model, position, cancellation_1.CancellationToken.None, true);
    });
    function isValid(result) {
        const hasRange = (typeof result.range !== 'undefined');
        const hasHtmlContent = typeof result.contents !== 'undefined' && result.contents && result.contents.length > 0;
        return hasRange && hasHtmlContent;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[737/*vs/editor/contrib/indentation/browser/indentation*/], __M([1/*require*/,0/*exports*/,2/*vs/base/common/lifecycle*/,11/*vs/base/common/strings*/,15/*vs/editor/browser/editorExtensions*/,183/*vs/editor/common/commands/shiftCommand*/,4/*vs/editor/common/core/range*/,20/*vs/editor/common/editorContextKeys*/,36/*vs/editor/common/languages/languageConfigurationRegistry*/,51/*vs/editor/common/services/model*/,338/*vs/editor/contrib/indentation/common/indentUtils*/,3/*vs/nls*/,66/*vs/platform/quickinput/common/quickInput*/,241/*vs/editor/common/languages/autoIndent*/,714/*vs/editor/contrib/indentation/common/indentation*/,83/*vs/editor/common/tokens/lineTokens*/]), function (require, exports, lifecycle_1, strings, editorExtensions_1, shiftCommand_1, range_1, editorContextKeys_1, languageConfigurationRegistry_1, model_1, indentUtils, nls, quickInput_1, autoIndent_1, indentation_1, lineTokens_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.IndentationToTabsCommand = exports.IndentationToSpacesCommand = exports.AutoIndentOnPaste = exports.AutoIndentOnPasteCommand = exports.ReindentSelectedLinesAction = exports.ReindentLinesAction = exports.DetectIndentation = exports.ChangeTabDisplaySize = exports.IndentUsingSpaces = exports.IndentUsingTabs = exports.ChangeIndentationSizeAction = exports.IndentationToTabsAction = exports.IndentationToSpacesAction = void 0;
    class IndentationToSpacesAction extends editorExtensions_1.EditorAction {
        static { this.ID = 'editor.action.indentationToSpaces'; }
        constructor() {
            super({
                id: IndentationToSpacesAction.ID,
                label: nls.localize(1045, "Convert Indentation to Spaces"),
                alias: 'Convert Indentation to Spaces',
                precondition: editorContextKeys_1.EditorContextKeys.writable,
                metadata: {
                    description: nls.localize2(1057, "Convert the tab indentation to spaces."),
                }
            });
        }
        run(accessor, editor) {
            const model = editor.getModel();
            if (!model) {
                return;
            }
            const modelOpts = model.getOptions();
            const selection = editor.getSelection();
            if (!selection) {
                return;
            }
            const command = new IndentationToSpacesCommand(selection, modelOpts.tabSize);
            editor.pushUndoStop();
            editor.executeCommands(this.id, [command]);
            editor.pushUndoStop();
            model.updateOptions({
                insertSpaces: true
            });
        }
    }
    exports.IndentationToSpacesAction = IndentationToSpacesAction;
    class IndentationToTabsAction extends editorExtensions_1.EditorAction {
        static { this.ID = 'editor.action.indentationToTabs'; }
        constructor() {
            super({
                id: IndentationToTabsAction.ID,
                label: nls.localize(1046, "Convert Indentation to Tabs"),
                alias: 'Convert Indentation to Tabs',
                precondition: editorContextKeys_1.EditorContextKeys.writable,
                metadata: {
                    description: nls.localize2(1058, "Convert the spaces indentation to tabs."),
                }
            });
        }
        run(accessor, editor) {
            const model = editor.getModel();
            if (!model) {
                return;
            }
            const modelOpts = model.getOptions();
            const selection = editor.getSelection();
            if (!selection) {
                return;
            }
            const command = new IndentationToTabsCommand(selection, modelOpts.tabSize);
            editor.pushUndoStop();
            editor.executeCommands(this.id, [command]);
            editor.pushUndoStop();
            model.updateOptions({
                insertSpaces: false
            });
        }
    }
    exports.IndentationToTabsAction = IndentationToTabsAction;
    class ChangeIndentationSizeAction extends editorExtensions_1.EditorAction {
        constructor(insertSpaces, displaySizeOnly, opts) {
            super(opts);
            this.insertSpaces = insertSpaces;
            this.displaySizeOnly = displaySizeOnly;
        }
        run(accessor, editor) {
            const quickInputService = accessor.get(quickInput_1.IQuickInputService);
            const modelService = accessor.get(model_1.IModelService);
            const model = editor.getModel();
            if (!model) {
                return;
            }
            const creationOpts = modelService.getCreationOptions(model.getLanguageId(), model.uri, model.isForSimpleWidget);
            const modelOpts = model.getOptions();
            const picks = [1, 2, 3, 4, 5, 6, 7, 8].map(n => ({
                id: n.toString(),
                label: n.toString(),
                // add description for tabSize value set in the configuration
                description: (n === creationOpts.tabSize && n === modelOpts.tabSize
                    ? nls.localize(1047, "Configured Tab Size")
                    : n === creationOpts.tabSize
                        ? nls.localize(1048, "Default Tab Size")
                        : n === modelOpts.tabSize
                            ? nls.localize(1049, "Current Tab Size")
                            : undefined)
            }));
            // auto focus the tabSize set for the current editor
            const autoFocusIndex = Math.min(model.getOptions().tabSize - 1, 7);
            setTimeout(() => {
                quickInputService.pick(picks, { placeHolder: nls.localize(1050, "Select Tab Size for Current File"), activeItem: picks[autoFocusIndex] }).then(pick => {
                    if (pick) {
                        if (model && !model.isDisposed()) {
                            const pickedVal = parseInt(pick.label, 10);
                            if (this.displaySizeOnly) {
                                model.updateOptions({
                                    tabSize: pickedVal
                                });
                            }
                            else {
                                model.updateOptions({
                                    tabSize: pickedVal,
                                    indentSize: pickedVal,
                                    insertSpaces: this.insertSpaces
                                });
                            }
                        }
                    }
                });
            }, 50 /* quick input is sensitive to being opened so soon after another */);
        }
    }
    exports.ChangeIndentationSizeAction = ChangeIndentationSizeAction;
    class IndentUsingTabs extends ChangeIndentationSizeAction {
        static { this.ID = 'editor.action.indentUsingTabs'; }
        constructor() {
            super(false, false, {
                id: IndentUsingTabs.ID,
                label: nls.localize(1051, "Indent Using Tabs"),
                alias: 'Indent Using Tabs',
                precondition: undefined,
                metadata: {
                    description: nls.localize2(1059, "Use indentation with tabs."),
                }
            });
        }
    }
    exports.IndentUsingTabs = IndentUsingTabs;
    class IndentUsingSpaces extends ChangeIndentationSizeAction {
        static { this.ID = 'editor.action.indentUsingSpaces'; }
        constructor() {
            super(true, false, {
                id: IndentUsingSpaces.ID,
                label: nls.localize(1052, "Indent Using Spaces"),
                alias: 'Indent Using Spaces',
                precondition: undefined,
                metadata: {
                    description: nls.localize2(1060, "Use indentation with spaces."),
                }
            });
        }
    }
    exports.IndentUsingSpaces = IndentUsingSpaces;
    class ChangeTabDisplaySize extends ChangeIndentationSizeAction {
        static { this.ID = 'editor.action.changeTabDisplaySize'; }
        constructor() {
            super(true, true, {
                id: ChangeTabDisplaySize.ID,
                label: nls.localize(1053, "Change Tab Display Size"),
                alias: 'Change Tab Display Size',
                precondition: undefined,
                metadata: {
                    description: nls.localize2(1061, "Change the space size equivalent of the tab."),
                }
            });
        }
    }
    exports.ChangeTabDisplaySize = ChangeTabDisplaySize;
    class DetectIndentation extends editorExtensions_1.EditorAction {
        static { this.ID = 'editor.action.detectIndentation'; }
        constructor() {
            super({
                id: DetectIndentation.ID,
                label: nls.localize(1054, "Detect Indentation from Content"),
                alias: 'Detect Indentation from Content',
                precondition: undefined,
                metadata: {
                    description: nls.localize2(1062, "Detect the indentation from content."),
                }
            });
        }
        run(accessor, editor) {
            const modelService = accessor.get(model_1.IModelService);
            const model = editor.getModel();
            if (!model) {
                return;
            }
            const creationOpts = modelService.getCreationOptions(model.getLanguageId(), model.uri, model.isForSimpleWidget);
            model.detectIndentation(creationOpts.insertSpaces, creationOpts.tabSize);
        }
    }
    exports.DetectIndentation = DetectIndentation;
    class ReindentLinesAction extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: 'editor.action.reindentlines',
                label: nls.localize(1055, "Reindent Lines"),
                alias: 'Reindent Lines',
                precondition: editorContextKeys_1.EditorContextKeys.writable,
                metadata: {
                    description: nls.localize2(1063, "Reindent the lines of the editor."),
                }
            });
        }
        run(accessor, editor) {
            const languageConfigurationService = accessor.get(languageConfigurationRegistry_1.ILanguageConfigurationService);
            const model = editor.getModel();
            if (!model) {
                return;
            }
            const edits = (0, indentation_1.getReindentEditOperations)(model, languageConfigurationService, 1, model.getLineCount());
            if (edits.length > 0) {
                editor.pushUndoStop();
                editor.executeEdits(this.id, edits);
                editor.pushUndoStop();
            }
        }
    }
    exports.ReindentLinesAction = ReindentLinesAction;
    class ReindentSelectedLinesAction extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: 'editor.action.reindentselectedlines',
                label: nls.localize(1056, "Reindent Selected Lines"),
                alias: 'Reindent Selected Lines',
                precondition: editorContextKeys_1.EditorContextKeys.writable,
                metadata: {
                    description: nls.localize2(1064, "Reindent the selected lines of the editor."),
                }
            });
        }
        run(accessor, editor) {
            const languageConfigurationService = accessor.get(languageConfigurationRegistry_1.ILanguageConfigurationService);
            const model = editor.getModel();
            if (!model) {
                return;
            }
            const selections = editor.getSelections();
            if (selections === null) {
                return;
            }
            const edits = [];
            for (const selection of selections) {
                let startLineNumber = selection.startLineNumber;
                let endLineNumber = selection.endLineNumber;
                if (startLineNumber !== endLineNumber && selection.endColumn === 1) {
                    endLineNumber--;
                }
                if (startLineNumber === 1) {
                    if (startLineNumber === endLineNumber) {
                        continue;
                    }
                }
                else {
                    startLineNumber--;
                }
                const editOperations = (0, indentation_1.getReindentEditOperations)(model, languageConfigurationService, startLineNumber, endLineNumber);
                edits.push(...editOperations);
            }
            if (edits.length > 0) {
                editor.pushUndoStop();
                editor.executeEdits(this.id, edits);
                editor.pushUndoStop();
            }
        }
    }
    exports.ReindentSelectedLinesAction = ReindentSelectedLinesAction;
    class AutoIndentOnPasteCommand {
        constructor(edits, initialSelection) {
            this._initialSelection = initialSelection;
            this._edits = [];
            this._selectionId = null;
            for (const edit of edits) {
                if (edit.range && typeof edit.text === 'string') {
                    this._edits.push(edit);
                }
            }
        }
        getEditOperations(model, builder) {
            for (const edit of this._edits) {
                builder.addEditOperation(range_1.Range.lift(edit.range), edit.text);
            }
            let selectionIsSet = false;
            if (Array.isArray(this._edits) && this._edits.length === 1 && this._initialSelection.isEmpty()) {
                if (this._edits[0].range.startColumn === this._initialSelection.endColumn &&
                    this._edits[0].range.startLineNumber === this._initialSelection.endLineNumber) {
                    selectionIsSet = true;
                    this._selectionId = builder.trackSelection(this._initialSelection, true);
                }
                else if (this._edits[0].range.endColumn === this._initialSelection.startColumn &&
                    this._edits[0].range.endLineNumber === this._initialSelection.startLineNumber) {
                    selectionIsSet = true;
                    this._selectionId = builder.trackSelection(this._initialSelection, false);
                }
            }
            if (!selectionIsSet) {
                this._selectionId = builder.trackSelection(this._initialSelection);
            }
        }
        computeCursorState(model, helper) {
            return helper.getTrackedSelection(this._selectionId);
        }
    }
    exports.AutoIndentOnPasteCommand = AutoIndentOnPasteCommand;
    let AutoIndentOnPaste = class AutoIndentOnPaste {
        static { this.ID = 'editor.contrib.autoIndentOnPaste'; }
        constructor(editor, _languageConfigurationService) {
            this.editor = editor;
            this._languageConfigurationService = _languageConfigurationService;
            this.callOnDispose = new lifecycle_1.DisposableStore();
            this.callOnModel = new lifecycle_1.DisposableStore();
            this.callOnDispose.add(editor.onDidChangeConfiguration(() => this.update()));
            this.callOnDispose.add(editor.onDidChangeModel(() => this.update()));
            this.callOnDispose.add(editor.onDidChangeModelLanguage(() => this.update()));
        }
        update() {
            // clean up
            this.callOnModel.clear();
            // we are disabled
            if (this.editor.getOption(12 /* EditorOption.autoIndent */) < 4 /* EditorAutoIndentStrategy.Full */ || this.editor.getOption(55 /* EditorOption.formatOnPaste */)) {
                return;
            }
            // no model
            if (!this.editor.hasModel()) {
                return;
            }
            this.callOnModel.add(this.editor.onDidPaste(({ range }) => {
                this.trigger(range);
            }));
        }
        trigger(range) {
            const selections = this.editor.getSelections();
            if (selections === null || selections.length > 1) {
                return;
            }
            const model = this.editor.getModel();
            if (!model) {
                return;
            }
            const containsOnlyWhitespace = this.rangeContainsOnlyWhitespaceCharacters(model, range);
            if (containsOnlyWhitespace) {
                return;
            }
            if (isStartOrEndInString(model, range)) {
                return;
            }
            if (!model.tokenization.isCheapToTokenize(range.getStartPosition().lineNumber)) {
                return;
            }
            const autoIndent = this.editor.getOption(12 /* EditorOption.autoIndent */);
            const { tabSize, indentSize, insertSpaces } = model.getOptions();
            const textEdits = [];
            const indentConverter = {
                shiftIndent: (indentation) => {
                    return shiftCommand_1.ShiftCommand.shiftIndent(indentation, indentation.length + 1, tabSize, indentSize, insertSpaces);
                },
                unshiftIndent: (indentation) => {
                    return shiftCommand_1.ShiftCommand.unshiftIndent(indentation, indentation.length + 1, tabSize, indentSize, insertSpaces);
                }
            };
            let startLineNumber = range.startLineNumber;
            while (startLineNumber <= range.endLineNumber) {
                if (this.shouldIgnoreLine(model, startLineNumber)) {
                    startLineNumber++;
                    continue;
                }
                break;
            }
            if (startLineNumber > range.endLineNumber) {
                return;
            }
            let firstLineText = model.getLineContent(startLineNumber);
            if (!/\S/.test(firstLineText.substring(0, range.startColumn - 1))) {
                const indentOfFirstLine = (0, autoIndent_1.getGoodIndentForLine)(autoIndent, model, model.getLanguageId(), startLineNumber, indentConverter, this._languageConfigurationService);
                if (indentOfFirstLine !== null) {
                    const oldIndentation = strings.getLeadingWhitespace(firstLineText);
                    const newSpaceCnt = indentUtils.getSpaceCnt(indentOfFirstLine, tabSize);
                    const oldSpaceCnt = indentUtils.getSpaceCnt(oldIndentation, tabSize);
                    if (newSpaceCnt !== oldSpaceCnt) {
                        const newIndent = indentUtils.generateIndent(newSpaceCnt, tabSize, insertSpaces);
                        textEdits.push({
                            range: new range_1.Range(startLineNumber, 1, startLineNumber, oldIndentation.length + 1),
                            text: newIndent
                        });
                        firstLineText = newIndent + firstLineText.substring(oldIndentation.length);
                    }
                    else {
                        const indentMetadata = (0, autoIndent_1.getIndentMetadata)(model, startLineNumber, this._languageConfigurationService);
                        if (indentMetadata === 0 || indentMetadata === 8 /* IndentConsts.UNINDENT_MASK */) {
                            // we paste content into a line where only contains whitespaces
                            // after pasting, the indentation of the first line is already correct
                            // the first line doesn't match any indentation rule
                            // then no-op.
                            return;
                        }
                    }
                }
            }
            const firstLineNumber = startLineNumber;
            // ignore empty or ignored lines
            while (startLineNumber < range.endLineNumber) {
                if (!/\S/.test(model.getLineContent(startLineNumber + 1))) {
                    startLineNumber++;
                    continue;
                }
                break;
            }
            if (startLineNumber !== range.endLineNumber) {
                const virtualModel = {
                    tokenization: {
                        getLineTokens: (lineNumber) => {
                            return model.tokenization.getLineTokens(lineNumber);
                        },
                        getLanguageId: () => {
                            return model.getLanguageId();
                        },
                        getLanguageIdAtPosition: (lineNumber, column) => {
                            return model.getLanguageIdAtPosition(lineNumber, column);
                        },
                    },
                    getLineContent: (lineNumber) => {
                        if (lineNumber === firstLineNumber) {
                            return firstLineText;
                        }
                        else {
                            return model.getLineContent(lineNumber);
                        }
                    }
                };
                const indentOfSecondLine = (0, autoIndent_1.getGoodIndentForLine)(autoIndent, virtualModel, model.getLanguageId(), startLineNumber + 1, indentConverter, this._languageConfigurationService);
                if (indentOfSecondLine !== null) {
                    const newSpaceCntOfSecondLine = indentUtils.getSpaceCnt(indentOfSecondLine, tabSize);
                    const oldSpaceCntOfSecondLine = indentUtils.getSpaceCnt(strings.getLeadingWhitespace(model.getLineContent(startLineNumber + 1)), tabSize);
                    if (newSpaceCntOfSecondLine !== oldSpaceCntOfSecondLine) {
                        const spaceCntOffset = newSpaceCntOfSecondLine - oldSpaceCntOfSecondLine;
                        for (let i = startLineNumber + 1; i <= range.endLineNumber; i++) {
                            const lineContent = model.getLineContent(i);
                            const originalIndent = strings.getLeadingWhitespace(lineContent);
                            const originalSpacesCnt = indentUtils.getSpaceCnt(originalIndent, tabSize);
                            const newSpacesCnt = originalSpacesCnt + spaceCntOffset;
                            const newIndent = indentUtils.generateIndent(newSpacesCnt, tabSize, insertSpaces);
                            if (newIndent !== originalIndent) {
                                textEdits.push({
                                    range: new range_1.Range(i, 1, i, originalIndent.length + 1),
                                    text: newIndent
                                });
                            }
                        }
                    }
                }
            }
            if (textEdits.length > 0) {
                this.editor.pushUndoStop();
                const cmd = new AutoIndentOnPasteCommand(textEdits, this.editor.getSelection());
                this.editor.executeCommand('autoIndentOnPaste', cmd);
                this.editor.pushUndoStop();
            }
        }
        rangeContainsOnlyWhitespaceCharacters(model, range) {
            const lineContainsOnlyWhitespace = (content) => {
                return content.trim().length === 0;
            };
            let containsOnlyWhitespace = true;
            if (range.startLineNumber === range.endLineNumber) {
                const lineContent = model.getLineContent(range.startLineNumber);
                const linePart = lineContent.substring(range.startColumn - 1, range.endColumn - 1);
                containsOnlyWhitespace = lineContainsOnlyWhitespace(linePart);
            }
            else {
                for (let i = range.startLineNumber; i <= range.endLineNumber; i++) {
                    const lineContent = model.getLineContent(i);
                    if (i === range.startLineNumber) {
                        const linePart = lineContent.substring(range.startColumn - 1);
                        containsOnlyWhitespace = lineContainsOnlyWhitespace(linePart);
                    }
                    else if (i === range.endLineNumber) {
                        const linePart = lineContent.substring(0, range.endColumn - 1);
                        containsOnlyWhitespace = lineContainsOnlyWhitespace(linePart);
                    }
                    else {
                        containsOnlyWhitespace = model.getLineFirstNonWhitespaceColumn(i) === 0;
                    }
                    if (!containsOnlyWhitespace) {
                        break;
                    }
                }
            }
            return containsOnlyWhitespace;
        }
        shouldIgnoreLine(model, lineNumber) {
            model.tokenization.forceTokenization(lineNumber);
            const nonWhitespaceColumn = model.getLineFirstNonWhitespaceColumn(lineNumber);
            if (nonWhitespaceColumn === 0) {
                return true;
            }
            const tokens = model.tokenization.getLineTokens(lineNumber);
            if (tokens.getCount() > 0) {
                const firstNonWhitespaceTokenIndex = tokens.findTokenIndexAtOffset(nonWhitespaceColumn);
                if (firstNonWhitespaceTokenIndex >= 0 && tokens.getStandardTokenType(firstNonWhitespaceTokenIndex) === 1 /* StandardTokenType.Comment */) {
                    return true;
                }
            }
            return false;
        }
        dispose() {
            this.callOnDispose.dispose();
            this.callOnModel.dispose();
        }
    };
    exports.AutoIndentOnPaste = AutoIndentOnPaste;
    exports.AutoIndentOnPaste = AutoIndentOnPaste = __decorate([
        __param(1, languageConfigurationRegistry_1.ILanguageConfigurationService)
    ], AutoIndentOnPaste);
    function isStartOrEndInString(model, range) {
        const isPositionInString = (position) => {
            const tokenType = (0, lineTokens_1.getStandardTokenTypeAtPosition)(model, position);
            return tokenType === 2 /* StandardTokenType.String */;
        };
        return isPositionInString(range.getStartPosition()) || isPositionInString(range.getEndPosition());
    }
    function getIndentationEditOperations(model, builder, tabSize, tabsToSpaces) {
        if (model.getLineCount() === 1 && model.getLineMaxColumn(1) === 1) {
            // Model is empty
            return;
        }
        let spaces = '';
        for (let i = 0; i < tabSize; i++) {
            spaces += ' ';
        }
        const spacesRegExp = new RegExp(spaces, 'gi');
        for (let lineNumber = 1, lineCount = model.getLineCount(); lineNumber <= lineCount; lineNumber++) {
            let lastIndentationColumn = model.getLineFirstNonWhitespaceColumn(lineNumber);
            if (lastIndentationColumn === 0) {
                lastIndentationColumn = model.getLineMaxColumn(lineNumber);
            }
            if (lastIndentationColumn === 1) {
                continue;
            }
            const originalIndentationRange = new range_1.Range(lineNumber, 1, lineNumber, lastIndentationColumn);
            const originalIndentation = model.getValueInRange(originalIndentationRange);
            const newIndentation = (tabsToSpaces
                ? originalIndentation.replace(/\t/ig, spaces)
                : originalIndentation.replace(spacesRegExp, '\t'));
            builder.addEditOperation(originalIndentationRange, newIndentation);
        }
    }
    class IndentationToSpacesCommand {
        constructor(selection, tabSize) {
            this.selection = selection;
            this.tabSize = tabSize;
            this.selectionId = null;
        }
        getEditOperations(model, builder) {
            this.selectionId = builder.trackSelection(this.selection);
            getIndentationEditOperations(model, builder, this.tabSize, true);
        }
        computeCursorState(model, helper) {
            return helper.getTrackedSelection(this.selectionId);
        }
    }
    exports.IndentationToSpacesCommand = IndentationToSpacesCommand;
    class IndentationToTabsCommand {
        constructor(selection, tabSize) {
            this.selection = selection;
            this.tabSize = tabSize;
            this.selectionId = null;
        }
        getEditOperations(model, builder) {
            this.selectionId = builder.trackSelection(this.selection);
            getIndentationEditOperations(model, builder, this.tabSize, false);
        }
        computeCursorState(model, helper) {
            return helper.getTrackedSelection(this.selectionId);
        }
    }
    exports.IndentationToTabsCommand = IndentationToTabsCommand;
    (0, editorExtensions_1.registerEditorContribution)(AutoIndentOnPaste.ID, AutoIndentOnPaste, 2 /* EditorContributionInstantiation.BeforeFirstInteraction */);
    (0, editorExtensions_1.registerEditorAction)(IndentationToSpacesAction);
    (0, editorExtensions_1.registerEditorAction)(IndentationToTabsAction);
    (0, editorExtensions_1.registerEditorAction)(IndentUsingTabs);
    (0, editorExtensions_1.registerEditorAction)(IndentUsingSpaces);
    (0, editorExtensions_1.registerEditorAction)(ChangeTabDisplaySize);
    (0, editorExtensions_1.registerEditorAction)(DetectIndentation);
    (0, editorExtensions_1.registerEditorAction)(ReindentLinesAction);
    (0, editorExtensions_1.registerEditorAction)(ReindentSelectedLinesAction);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[738/*vs/editor/contrib/lineSelection/browser/lineSelection*/], __M([1/*require*/,0/*exports*/,15/*vs/editor/browser/editorExtensions*/,235/*vs/editor/common/cursor/cursorMoveCommands*/,20/*vs/editor/common/editorContextKeys*/,3/*vs/nls*/]), function (require, exports, editorExtensions_1, cursorMoveCommands_1, editorContextKeys_1, nls) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ExpandLineSelectionAction = void 0;
    class ExpandLineSelectionAction extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: 'expandLineSelection',
                label: nls.localize(1105, "Expand Line Selection"),
                alias: 'Expand Line Selection',
                precondition: undefined,
                kbOpts: {
                    weight: 0 /* KeybindingWeight.EditorCore */,
                    kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                    primary: 2048 /* KeyMod.CtrlCmd */ | 42 /* KeyCode.KeyL */
                },
            });
        }
        run(_accessor, editor, args) {
            args = args || {};
            if (!editor.hasModel()) {
                return;
            }
            const viewModel = editor._getViewModel();
            viewModel.model.pushStackElement();
            viewModel.setCursorStates(args.source, 3 /* CursorChangeReason.Explicit */, cursorMoveCommands_1.CursorMoveCommands.expandLineSelection(viewModel, viewModel.getCursorStates()));
            viewModel.revealAllCursors(args.source, true);
        }
    }
    exports.ExpandLineSelectionAction = ExpandLineSelectionAction;
    (0, editorExtensions_1.registerEditorAction)(ExpandLineSelectionAction);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[739/*vs/editor/contrib/linesOperations/browser/linesOperations*/], __M([1/*require*/,0/*exports*/,72/*vs/base/common/keyCodes*/,214/*vs/editor/browser/coreCommands*/,15/*vs/editor/browser/editorExtensions*/,146/*vs/editor/common/commands/replaceCommand*/,554/*vs/editor/common/commands/trimTrailingWhitespaceCommand*/,276/*vs/editor/common/cursor/cursorTypeOperations*/,213/*vs/editor/common/cursor/cursorTypeEditOperations*/,75/*vs/editor/common/core/editOperation*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/,23/*vs/editor/common/core/selection*/,20/*vs/editor/common/editorContextKeys*/,619/*vs/editor/contrib/linesOperations/browser/copyLinesCommand*/,716/*vs/editor/contrib/linesOperations/browser/moveLinesCommand*/,620/*vs/editor/contrib/linesOperations/browser/sortLinesCommand*/,3/*vs/nls*/,29/*vs/platform/actions/common/actions*/,36/*vs/editor/common/languages/languageConfigurationRegistry*/,28/*vs/platform/configuration/common/configuration*/]), function (require, exports, keyCodes_1, coreCommands_1, editorExtensions_1, replaceCommand_1, trimTrailingWhitespaceCommand_1, cursorTypeOperations_1, cursorTypeEditOperations_1, editOperation_1, position_1, range_1, selection_1, editorContextKeys_1, copyLinesCommand_1, moveLinesCommand_1, sortLinesCommand_1, nls, actions_1, languageConfigurationRegistry_1, configuration_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.KebabCaseAction = exports.PascalCaseAction = exports.CamelCaseAction = exports.SnakeCaseAction = exports.TitleCaseAction = exports.LowerCaseAction = exports.UpperCaseAction = exports.AbstractCaseAction = exports.TransposeAction = exports.JoinLinesAction = exports.DeleteAllRightAction = exports.DeleteAllLeftAction = exports.AbstractDeleteAllToBoundaryAction = exports.InsertLineAfterAction = exports.InsertLineBeforeAction = exports.IndentLinesAction = exports.DeleteLinesAction = exports.TrimTrailingWhitespaceAction = exports.DeleteDuplicateLinesAction = exports.SortLinesDescendingAction = exports.SortLinesAscendingAction = exports.AbstractSortLinesAction = exports.DuplicateSelectionAction = void 0;
    // copy lines
    class AbstractCopyLinesAction extends editorExtensions_1.EditorAction {
        constructor(down, opts) {
            super(opts);
            this.down = down;
        }
        run(_accessor, editor) {
            if (!editor.hasModel()) {
                return;
            }
            const selections = editor.getSelections().map((selection, index) => ({ selection, index, ignore: false }));
            selections.sort((a, b) => range_1.Range.compareRangesUsingStarts(a.selection, b.selection));
            // Remove selections that would result in copying the same line
            let prev = selections[0];
            for (let i = 1; i < selections.length; i++) {
                const curr = selections[i];
                if (prev.selection.endLineNumber === curr.selection.startLineNumber) {
                    // these two selections would copy the same line
                    if (prev.index < curr.index) {
                        // prev wins
                        curr.ignore = true;
                    }
                    else {
                        // curr wins
                        prev.ignore = true;
                        prev = curr;
                    }
                }
            }
            const commands = [];
            for (const selection of selections) {
                commands.push(new copyLinesCommand_1.CopyLinesCommand(selection.selection, this.down, selection.ignore));
            }
            editor.pushUndoStop();
            editor.executeCommands(this.id, commands);
            editor.pushUndoStop();
        }
    }
    class CopyLinesUpAction extends AbstractCopyLinesAction {
        constructor() {
            super(false, {
                id: 'editor.action.copyLinesUpAction',
                label: nls.localize(1106, "Copy Line Up"),
                alias: 'Copy Line Up',
                precondition: editorContextKeys_1.EditorContextKeys.writable,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    primary: 512 /* KeyMod.Alt */ | 1024 /* KeyMod.Shift */ | 16 /* KeyCode.UpArrow */,
                    linux: { primary: 2048 /* KeyMod.CtrlCmd */ | 512 /* KeyMod.Alt */ | 1024 /* KeyMod.Shift */ | 16 /* KeyCode.UpArrow */ },
                    weight: 100 /* KeybindingWeight.EditorContrib */
                },
                menuOpts: {
                    menuId: actions_1.MenuId.MenubarSelectionMenu,
                    group: '2_line',
                    title: nls.localize(1107, "&&Copy Line Up"),
                    order: 1
                }
            });
        }
    }
    class CopyLinesDownAction extends AbstractCopyLinesAction {
        constructor() {
            super(true, {
                id: 'editor.action.copyLinesDownAction',
                label: nls.localize(1108, "Copy Line Down"),
                alias: 'Copy Line Down',
                precondition: editorContextKeys_1.EditorContextKeys.writable,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    primary: 512 /* KeyMod.Alt */ | 1024 /* KeyMod.Shift */ | 18 /* KeyCode.DownArrow */,
                    linux: { primary: 2048 /* KeyMod.CtrlCmd */ | 512 /* KeyMod.Alt */ | 1024 /* KeyMod.Shift */ | 18 /* KeyCode.DownArrow */ },
                    weight: 100 /* KeybindingWeight.EditorContrib */
                },
                menuOpts: {
                    menuId: actions_1.MenuId.MenubarSelectionMenu,
                    group: '2_line',
                    title: nls.localize(1109, "Co&&py Line Down"),
                    order: 2
                }
            });
        }
    }
    class DuplicateSelectionAction extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: 'editor.action.duplicateSelection',
                label: nls.localize(1110, "Duplicate Selection"),
                alias: 'Duplicate Selection',
                precondition: editorContextKeys_1.EditorContextKeys.writable,
                menuOpts: {
                    menuId: actions_1.MenuId.MenubarSelectionMenu,
                    group: '2_line',
                    title: nls.localize(1111, "&&Duplicate Selection"),
                    order: 5
                }
            });
        }
        run(accessor, editor, args) {
            if (!editor.hasModel()) {
                return;
            }
            const commands = [];
            const selections = editor.getSelections();
            const model = editor.getModel();
            for (const selection of selections) {
                if (selection.isEmpty()) {
                    commands.push(new copyLinesCommand_1.CopyLinesCommand(selection, true));
                }
                else {
                    const insertSelection = new selection_1.Selection(selection.endLineNumber, selection.endColumn, selection.endLineNumber, selection.endColumn);
                    commands.push(new replaceCommand_1.ReplaceCommandThatSelectsText(insertSelection, model.getValueInRange(selection)));
                }
            }
            editor.pushUndoStop();
            editor.executeCommands(this.id, commands);
            editor.pushUndoStop();
        }
    }
    exports.DuplicateSelectionAction = DuplicateSelectionAction;
    // move lines
    class AbstractMoveLinesAction extends editorExtensions_1.EditorAction {
        constructor(down, opts) {
            super(opts);
            this.down = down;
        }
        run(accessor, editor) {
            const languageConfigurationService = accessor.get(languageConfigurationRegistry_1.ILanguageConfigurationService);
            const commands = [];
            const selections = editor.getSelections() || [];
            const autoIndent = editor.getOption(12 /* EditorOption.autoIndent */);
            for (const selection of selections) {
                commands.push(new moveLinesCommand_1.MoveLinesCommand(selection, this.down, autoIndent, languageConfigurationService));
            }
            editor.pushUndoStop();
            editor.executeCommands(this.id, commands);
            editor.pushUndoStop();
        }
    }
    class MoveLinesUpAction extends AbstractMoveLinesAction {
        constructor() {
            super(false, {
                id: 'editor.action.moveLinesUpAction',
                label: nls.localize(1112, "Move Line Up"),
                alias: 'Move Line Up',
                precondition: editorContextKeys_1.EditorContextKeys.writable,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    primary: 512 /* KeyMod.Alt */ | 16 /* KeyCode.UpArrow */,
                    linux: { primary: 512 /* KeyMod.Alt */ | 16 /* KeyCode.UpArrow */ },
                    weight: 100 /* KeybindingWeight.EditorContrib */
                },
                menuOpts: {
                    menuId: actions_1.MenuId.MenubarSelectionMenu,
                    group: '2_line',
                    title: nls.localize(1113, "Mo&&ve Line Up"),
                    order: 3
                }
            });
        }
    }
    class MoveLinesDownAction extends AbstractMoveLinesAction {
        constructor() {
            super(true, {
                id: 'editor.action.moveLinesDownAction',
                label: nls.localize(1114, "Move Line Down"),
                alias: 'Move Line Down',
                precondition: editorContextKeys_1.EditorContextKeys.writable,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    primary: 512 /* KeyMod.Alt */ | 18 /* KeyCode.DownArrow */,
                    linux: { primary: 512 /* KeyMod.Alt */ | 18 /* KeyCode.DownArrow */ },
                    weight: 100 /* KeybindingWeight.EditorContrib */
                },
                menuOpts: {
                    menuId: actions_1.MenuId.MenubarSelectionMenu,
                    group: '2_line',
                    title: nls.localize(1115, "Move &&Line Down"),
                    order: 4
                }
            });
        }
    }
    class AbstractSortLinesAction extends editorExtensions_1.EditorAction {
        constructor(descending, opts) {
            super(opts);
            this.descending = descending;
        }
        run(_accessor, editor) {
            if (!editor.hasModel()) {
                return;
            }
            const model = editor.getModel();
            let selections = editor.getSelections();
            if (selections.length === 1 && selections[0].isEmpty()) {
                // Apply to whole document.
                selections = [new selection_1.Selection(1, 1, model.getLineCount(), model.getLineMaxColumn(model.getLineCount()))];
            }
            for (const selection of selections) {
                if (!sortLinesCommand_1.SortLinesCommand.canRun(editor.getModel(), selection, this.descending)) {
                    return;
                }
            }
            const commands = [];
            for (let i = 0, len = selections.length; i < len; i++) {
                commands[i] = new sortLinesCommand_1.SortLinesCommand(selections[i], this.descending);
            }
            editor.pushUndoStop();
            editor.executeCommands(this.id, commands);
            editor.pushUndoStop();
        }
    }
    exports.AbstractSortLinesAction = AbstractSortLinesAction;
    class SortLinesAscendingAction extends AbstractSortLinesAction {
        constructor() {
            super(false, {
                id: 'editor.action.sortLinesAscending',
                label: nls.localize(1116, "Sort Lines Ascending"),
                alias: 'Sort Lines Ascending',
                precondition: editorContextKeys_1.EditorContextKeys.writable
            });
        }
    }
    exports.SortLinesAscendingAction = SortLinesAscendingAction;
    class SortLinesDescendingAction extends AbstractSortLinesAction {
        constructor() {
            super(true, {
                id: 'editor.action.sortLinesDescending',
                label: nls.localize(1117, "Sort Lines Descending"),
                alias: 'Sort Lines Descending',
                precondition: editorContextKeys_1.EditorContextKeys.writable
            });
        }
    }
    exports.SortLinesDescendingAction = SortLinesDescendingAction;
    class DeleteDuplicateLinesAction extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: 'editor.action.removeDuplicateLines',
                label: nls.localize(1118, "Delete Duplicate Lines"),
                alias: 'Delete Duplicate Lines',
                precondition: editorContextKeys_1.EditorContextKeys.writable
            });
        }
        run(_accessor, editor) {
            if (!editor.hasModel()) {
                return;
            }
            const model = editor.getModel();
            if (model.getLineCount() === 1 && model.getLineMaxColumn(1) === 1) {
                return;
            }
            const edits = [];
            const endCursorState = [];
            let linesDeleted = 0;
            let updateSelection = true;
            let selections = editor.getSelections();
            if (selections.length === 1 && selections[0].isEmpty()) {
                // Apply to whole document.
                selections = [new selection_1.Selection(1, 1, model.getLineCount(), model.getLineMaxColumn(model.getLineCount()))];
                updateSelection = false;
            }
            for (const selection of selections) {
                const uniqueLines = new Set();
                const lines = [];
                for (let i = selection.startLineNumber; i <= selection.endLineNumber; i++) {
                    const line = model.getLineContent(i);
                    if (uniqueLines.has(line)) {
                        continue;
                    }
                    lines.push(line);
                    uniqueLines.add(line);
                }
                const selectionToReplace = new selection_1.Selection(selection.startLineNumber, 1, selection.endLineNumber, model.getLineMaxColumn(selection.endLineNumber));
                const adjustedSelectionStart = selection.startLineNumber - linesDeleted;
                const finalSelection = new selection_1.Selection(adjustedSelectionStart, 1, adjustedSelectionStart + lines.length - 1, lines[lines.length - 1].length);
                edits.push(editOperation_1.EditOperation.replace(selectionToReplace, lines.join('\n')));
                endCursorState.push(finalSelection);
                linesDeleted += (selection.endLineNumber - selection.startLineNumber + 1) - lines.length;
            }
            editor.pushUndoStop();
            editor.executeEdits(this.id, edits, updateSelection ? endCursorState : undefined);
            editor.pushUndoStop();
        }
    }
    exports.DeleteDuplicateLinesAction = DeleteDuplicateLinesAction;
    class TrimTrailingWhitespaceAction extends editorExtensions_1.EditorAction {
        static { this.ID = 'editor.action.trimTrailingWhitespace'; }
        constructor() {
            super({
                id: TrimTrailingWhitespaceAction.ID,
                label: nls.localize(1119, "Trim Trailing Whitespace"),
                alias: 'Trim Trailing Whitespace',
                precondition: editorContextKeys_1.EditorContextKeys.writable,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    primary: (0, keyCodes_1.KeyChord)(2048 /* KeyMod.CtrlCmd */ | 41 /* KeyCode.KeyK */, 2048 /* KeyMod.CtrlCmd */ | 54 /* KeyCode.KeyX */),
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
        run(_accessor, editor, args) {
            let cursors = [];
            if (args.reason === 'auto-save') {
                // See https://github.com/editorconfig/editorconfig-vscode/issues/47
                // It is very convenient for the editor config extension to invoke this action.
                // So, if we get a reason:'auto-save' passed in, let's preserve cursor positions.
                cursors = (editor.getSelections() || []).map(s => new position_1.Position(s.positionLineNumber, s.positionColumn));
            }
            const selection = editor.getSelection();
            if (selection === null) {
                return;
            }
            const config = _accessor.get(configuration_1.IConfigurationService);
            const model = editor.getModel();
            const trimInRegexAndStrings = config.getValue('files.trimTrailingWhitespaceInRegexAndStrings', { overrideIdentifier: model?.getLanguageId(), resource: model?.uri });
            const command = new trimTrailingWhitespaceCommand_1.TrimTrailingWhitespaceCommand(selection, cursors, trimInRegexAndStrings);
            editor.pushUndoStop();
            editor.executeCommands(this.id, [command]);
            editor.pushUndoStop();
        }
    }
    exports.TrimTrailingWhitespaceAction = TrimTrailingWhitespaceAction;
    class DeleteLinesAction extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: 'editor.action.deleteLines',
                label: nls.localize(1120, "Delete Line"),
                alias: 'Delete Line',
                precondition: editorContextKeys_1.EditorContextKeys.writable,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                    primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 41 /* KeyCode.KeyK */,
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
        run(_accessor, editor) {
            if (!editor.hasModel()) {
                return;
            }
            const ops = this._getLinesToRemove(editor);
            const model = editor.getModel();
            if (model.getLineCount() === 1 && model.getLineMaxColumn(1) === 1) {
                // Model is empty
                return;
            }
            let linesDeleted = 0;
            const edits = [];
            const cursorState = [];
            for (let i = 0, len = ops.length; i < len; i++) {
                const op = ops[i];
                let startLineNumber = op.startLineNumber;
                let endLineNumber = op.endLineNumber;
                let startColumn = 1;
                let endColumn = model.getLineMaxColumn(endLineNumber);
                if (endLineNumber < model.getLineCount()) {
                    endLineNumber += 1;
                    endColumn = 1;
                }
                else if (startLineNumber > 1) {
                    startLineNumber -= 1;
                    startColumn = model.getLineMaxColumn(startLineNumber);
                }
                edits.push(editOperation_1.EditOperation.replace(new selection_1.Selection(startLineNumber, startColumn, endLineNumber, endColumn), ''));
                cursorState.push(new selection_1.Selection(startLineNumber - linesDeleted, op.positionColumn, startLineNumber - linesDeleted, op.positionColumn));
                linesDeleted += (op.endLineNumber - op.startLineNumber + 1);
            }
            editor.pushUndoStop();
            editor.executeEdits(this.id, edits, cursorState);
            editor.pushUndoStop();
        }
        _getLinesToRemove(editor) {
            // Construct delete operations
            const operations = editor.getSelections().map((s) => {
                let endLineNumber = s.endLineNumber;
                if (s.startLineNumber < s.endLineNumber && s.endColumn === 1) {
                    endLineNumber -= 1;
                }
                return {
                    startLineNumber: s.startLineNumber,
                    selectionStartColumn: s.selectionStartColumn,
                    endLineNumber: endLineNumber,
                    positionColumn: s.positionColumn
                };
            });
            // Sort delete operations
            operations.sort((a, b) => {
                if (a.startLineNumber === b.startLineNumber) {
                    return a.endLineNumber - b.endLineNumber;
                }
                return a.startLineNumber - b.startLineNumber;
            });
            // Merge delete operations which are adjacent or overlapping
            const mergedOperations = [];
            let previousOperation = operations[0];
            for (let i = 1; i < operations.length; i++) {
                if (previousOperation.endLineNumber + 1 >= operations[i].startLineNumber) {
                    // Merge current operations into the previous one
                    previousOperation.endLineNumber = operations[i].endLineNumber;
                }
                else {
                    // Push previous operation
                    mergedOperations.push(previousOperation);
                    previousOperation = operations[i];
                }
            }
            // Push the last operation
            mergedOperations.push(previousOperation);
            return mergedOperations;
        }
    }
    exports.DeleteLinesAction = DeleteLinesAction;
    class IndentLinesAction extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: 'editor.action.indentLines',
                label: nls.localize(1121, "Indent Line"),
                alias: 'Indent Line',
                precondition: editorContextKeys_1.EditorContextKeys.writable,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    primary: 2048 /* KeyMod.CtrlCmd */ | 94 /* KeyCode.BracketRight */,
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
        run(_accessor, editor) {
            const viewModel = editor._getViewModel();
            if (!viewModel) {
                return;
            }
            editor.pushUndoStop();
            editor.executeCommands(this.id, cursorTypeOperations_1.TypeOperations.indent(viewModel.cursorConfig, editor.getModel(), editor.getSelections()));
            editor.pushUndoStop();
        }
    }
    exports.IndentLinesAction = IndentLinesAction;
    class OutdentLinesAction extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: 'editor.action.outdentLines',
                label: nls.localize(1122, "Outdent Line"),
                alias: 'Outdent Line',
                precondition: editorContextKeys_1.EditorContextKeys.writable,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    primary: 2048 /* KeyMod.CtrlCmd */ | 92 /* KeyCode.BracketLeft */,
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
        run(_accessor, editor) {
            coreCommands_1.CoreEditingCommands.Outdent.runEditorCommand(_accessor, editor, null);
        }
    }
    class InsertLineBeforeAction extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: 'editor.action.insertLineBefore',
                label: nls.localize(1123, "Insert Line Above"),
                alias: 'Insert Line Above',
                precondition: editorContextKeys_1.EditorContextKeys.writable,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 3 /* KeyCode.Enter */,
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
        run(_accessor, editor) {
            const viewModel = editor._getViewModel();
            if (!viewModel) {
                return;
            }
            editor.pushUndoStop();
            editor.executeCommands(this.id, cursorTypeEditOperations_1.EnterOperation.lineInsertBefore(viewModel.cursorConfig, editor.getModel(), editor.getSelections()));
        }
    }
    exports.InsertLineBeforeAction = InsertLineBeforeAction;
    class InsertLineAfterAction extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: 'editor.action.insertLineAfter',
                label: nls.localize(1124, "Insert Line Below"),
                alias: 'Insert Line Below',
                precondition: editorContextKeys_1.EditorContextKeys.writable,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    primary: 2048 /* KeyMod.CtrlCmd */ | 3 /* KeyCode.Enter */,
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
        run(_accessor, editor) {
            const viewModel = editor._getViewModel();
            if (!viewModel) {
                return;
            }
            editor.pushUndoStop();
            editor.executeCommands(this.id, cursorTypeEditOperations_1.EnterOperation.lineInsertAfter(viewModel.cursorConfig, editor.getModel(), editor.getSelections()));
        }
    }
    exports.InsertLineAfterAction = InsertLineAfterAction;
    class AbstractDeleteAllToBoundaryAction extends editorExtensions_1.EditorAction {
        run(_accessor, editor) {
            if (!editor.hasModel()) {
                return;
            }
            const primaryCursor = editor.getSelection();
            const rangesToDelete = this._getRangesToDelete(editor);
            // merge overlapping selections
            const effectiveRanges = [];
            for (let i = 0, count = rangesToDelete.length - 1; i < count; i++) {
                const range = rangesToDelete[i];
                const nextRange = rangesToDelete[i + 1];
                if (range_1.Range.intersectRanges(range, nextRange) === null) {
                    effectiveRanges.push(range);
                }
                else {
                    rangesToDelete[i + 1] = range_1.Range.plusRange(range, nextRange);
                }
            }
            effectiveRanges.push(rangesToDelete[rangesToDelete.length - 1]);
            const endCursorState = this._getEndCursorState(primaryCursor, effectiveRanges);
            const edits = effectiveRanges.map(range => {
                return editOperation_1.EditOperation.replace(range, '');
            });
            editor.pushUndoStop();
            editor.executeEdits(this.id, edits, endCursorState);
            editor.pushUndoStop();
        }
    }
    exports.AbstractDeleteAllToBoundaryAction = AbstractDeleteAllToBoundaryAction;
    class DeleteAllLeftAction extends AbstractDeleteAllToBoundaryAction {
        constructor() {
            super({
                id: 'deleteAllLeft',
                label: nls.localize(1125, "Delete All Left"),
                alias: 'Delete All Left',
                precondition: editorContextKeys_1.EditorContextKeys.writable,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                    primary: 0,
                    mac: { primary: 2048 /* KeyMod.CtrlCmd */ | 1 /* KeyCode.Backspace */ },
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
        _getEndCursorState(primaryCursor, rangesToDelete) {
            let endPrimaryCursor = null;
            const endCursorState = [];
            let deletedLines = 0;
            rangesToDelete.forEach(range => {
                let endCursor;
                if (range.endColumn === 1 && deletedLines > 0) {
                    const newStartLine = range.startLineNumber - deletedLines;
                    endCursor = new selection_1.Selection(newStartLine, range.startColumn, newStartLine, range.startColumn);
                }
                else {
                    endCursor = new selection_1.Selection(range.startLineNumber, range.startColumn, range.startLineNumber, range.startColumn);
                }
                deletedLines += range.endLineNumber - range.startLineNumber;
                if (range.intersectRanges(primaryCursor)) {
                    endPrimaryCursor = endCursor;
                }
                else {
                    endCursorState.push(endCursor);
                }
            });
            if (endPrimaryCursor) {
                endCursorState.unshift(endPrimaryCursor);
            }
            return endCursorState;
        }
        _getRangesToDelete(editor) {
            const selections = editor.getSelections();
            if (selections === null) {
                return [];
            }
            let rangesToDelete = selections;
            const model = editor.getModel();
            if (model === null) {
                return [];
            }
            rangesToDelete.sort(range_1.Range.compareRangesUsingStarts);
            rangesToDelete = rangesToDelete.map(selection => {
                if (selection.isEmpty()) {
                    if (selection.startColumn === 1) {
                        const deleteFromLine = Math.max(1, selection.startLineNumber - 1);
                        const deleteFromColumn = selection.startLineNumber === 1 ? 1 : model.getLineLength(deleteFromLine) + 1;
                        return new range_1.Range(deleteFromLine, deleteFromColumn, selection.startLineNumber, 1);
                    }
                    else {
                        return new range_1.Range(selection.startLineNumber, 1, selection.startLineNumber, selection.startColumn);
                    }
                }
                else {
                    return new range_1.Range(selection.startLineNumber, 1, selection.endLineNumber, selection.endColumn);
                }
            });
            return rangesToDelete;
        }
    }
    exports.DeleteAllLeftAction = DeleteAllLeftAction;
    class DeleteAllRightAction extends AbstractDeleteAllToBoundaryAction {
        constructor() {
            super({
                id: 'deleteAllRight',
                label: nls.localize(1126, "Delete All Right"),
                alias: 'Delete All Right',
                precondition: editorContextKeys_1.EditorContextKeys.writable,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                    primary: 0,
                    mac: { primary: 256 /* KeyMod.WinCtrl */ | 41 /* KeyCode.KeyK */, secondary: [2048 /* KeyMod.CtrlCmd */ | 20 /* KeyCode.Delete */] },
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
        _getEndCursorState(primaryCursor, rangesToDelete) {
            let endPrimaryCursor = null;
            const endCursorState = [];
            for (let i = 0, len = rangesToDelete.length, offset = 0; i < len; i++) {
                const range = rangesToDelete[i];
                const endCursor = new selection_1.Selection(range.startLineNumber - offset, range.startColumn, range.startLineNumber - offset, range.startColumn);
                if (range.intersectRanges(primaryCursor)) {
                    endPrimaryCursor = endCursor;
                }
                else {
                    endCursorState.push(endCursor);
                }
            }
            if (endPrimaryCursor) {
                endCursorState.unshift(endPrimaryCursor);
            }
            return endCursorState;
        }
        _getRangesToDelete(editor) {
            const model = editor.getModel();
            if (model === null) {
                return [];
            }
            const selections = editor.getSelections();
            if (selections === null) {
                return [];
            }
            const rangesToDelete = selections.map((sel) => {
                if (sel.isEmpty()) {
                    const maxColumn = model.getLineMaxColumn(sel.startLineNumber);
                    if (sel.startColumn === maxColumn) {
                        return new range_1.Range(sel.startLineNumber, sel.startColumn, sel.startLineNumber + 1, 1);
                    }
                    else {
                        return new range_1.Range(sel.startLineNumber, sel.startColumn, sel.startLineNumber, maxColumn);
                    }
                }
                return sel;
            });
            rangesToDelete.sort(range_1.Range.compareRangesUsingStarts);
            return rangesToDelete;
        }
    }
    exports.DeleteAllRightAction = DeleteAllRightAction;
    class JoinLinesAction extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: 'editor.action.joinLines',
                label: nls.localize(1127, "Join Lines"),
                alias: 'Join Lines',
                precondition: editorContextKeys_1.EditorContextKeys.writable,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    primary: 0,
                    mac: { primary: 256 /* KeyMod.WinCtrl */ | 40 /* KeyCode.KeyJ */ },
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
        run(_accessor, editor) {
            const selections = editor.getSelections();
            if (selections === null) {
                return;
            }
            let primaryCursor = editor.getSelection();
            if (primaryCursor === null) {
                return;
            }
            selections.sort(range_1.Range.compareRangesUsingStarts);
            const reducedSelections = [];
            const lastSelection = selections.reduce((previousValue, currentValue) => {
                if (previousValue.isEmpty()) {
                    if (previousValue.endLineNumber === currentValue.startLineNumber) {
                        if (primaryCursor.equalsSelection(previousValue)) {
                            primaryCursor = currentValue;
                        }
                        return currentValue;
                    }
                    if (currentValue.startLineNumber > previousValue.endLineNumber + 1) {
                        reducedSelections.push(previousValue);
                        return currentValue;
                    }
                    else {
                        return new selection_1.Selection(previousValue.startLineNumber, previousValue.startColumn, currentValue.endLineNumber, currentValue.endColumn);
                    }
                }
                else {
                    if (currentValue.startLineNumber > previousValue.endLineNumber) {
                        reducedSelections.push(previousValue);
                        return currentValue;
                    }
                    else {
                        return new selection_1.Selection(previousValue.startLineNumber, previousValue.startColumn, currentValue.endLineNumber, currentValue.endColumn);
                    }
                }
            });
            reducedSelections.push(lastSelection);
            const model = editor.getModel();
            if (model === null) {
                return;
            }
            const edits = [];
            const endCursorState = [];
            let endPrimaryCursor = primaryCursor;
            let lineOffset = 0;
            for (let i = 0, len = reducedSelections.length; i < len; i++) {
                const selection = reducedSelections[i];
                const startLineNumber = selection.startLineNumber;
                const startColumn = 1;
                let columnDeltaOffset = 0;
                let endLineNumber, endColumn;
                const selectionEndPositionOffset = model.getLineLength(selection.endLineNumber) - selection.endColumn;
                if (selection.isEmpty() || selection.startLineNumber === selection.endLineNumber) {
                    const position = selection.getStartPosition();
                    if (position.lineNumber < model.getLineCount()) {
                        endLineNumber = startLineNumber + 1;
                        endColumn = model.getLineMaxColumn(endLineNumber);
                    }
                    else {
                        endLineNumber = position.lineNumber;
                        endColumn = model.getLineMaxColumn(position.lineNumber);
                    }
                }
                else {
                    endLineNumber = selection.endLineNumber;
                    endColumn = model.getLineMaxColumn(endLineNumber);
                }
                let trimmedLinesContent = model.getLineContent(startLineNumber);
                for (let i = startLineNumber + 1; i <= endLineNumber; i++) {
                    const lineText = model.getLineContent(i);
                    const firstNonWhitespaceIdx = model.getLineFirstNonWhitespaceColumn(i);
                    if (firstNonWhitespaceIdx >= 1) {
                        let insertSpace = true;
                        if (trimmedLinesContent === '') {
                            insertSpace = false;
                        }
                        if (insertSpace && (trimmedLinesContent.charAt(trimmedLinesContent.length - 1) === ' ' ||
                            trimmedLinesContent.charAt(trimmedLinesContent.length - 1) === '\t')) {
                            insertSpace = false;
                            trimmedLinesContent = trimmedLinesContent.replace(/[\s\uFEFF\xA0]+$/g, ' ');
                        }
                        const lineTextWithoutIndent = lineText.substr(firstNonWhitespaceIdx - 1);
                        trimmedLinesContent += (insertSpace ? ' ' : '') + lineTextWithoutIndent;
                        if (insertSpace) {
                            columnDeltaOffset = lineTextWithoutIndent.length + 1;
                        }
                        else {
                            columnDeltaOffset = lineTextWithoutIndent.length;
                        }
                    }
                    else {
                        columnDeltaOffset = 0;
                    }
                }
                const deleteSelection = new range_1.Range(startLineNumber, startColumn, endLineNumber, endColumn);
                if (!deleteSelection.isEmpty()) {
                    let resultSelection;
                    if (selection.isEmpty()) {
                        edits.push(editOperation_1.EditOperation.replace(deleteSelection, trimmedLinesContent));
                        resultSelection = new selection_1.Selection(deleteSelection.startLineNumber - lineOffset, trimmedLinesContent.length - columnDeltaOffset + 1, startLineNumber - lineOffset, trimmedLinesContent.length - columnDeltaOffset + 1);
                    }
                    else {
                        if (selection.startLineNumber === selection.endLineNumber) {
                            edits.push(editOperation_1.EditOperation.replace(deleteSelection, trimmedLinesContent));
                            resultSelection = new selection_1.Selection(selection.startLineNumber - lineOffset, selection.startColumn, selection.endLineNumber - lineOffset, selection.endColumn);
                        }
                        else {
                            edits.push(editOperation_1.EditOperation.replace(deleteSelection, trimmedLinesContent));
                            resultSelection = new selection_1.Selection(selection.startLineNumber - lineOffset, selection.startColumn, selection.startLineNumber - lineOffset, trimmedLinesContent.length - selectionEndPositionOffset);
                        }
                    }
                    if (range_1.Range.intersectRanges(deleteSelection, primaryCursor) !== null) {
                        endPrimaryCursor = resultSelection;
                    }
                    else {
                        endCursorState.push(resultSelection);
                    }
                }
                lineOffset += deleteSelection.endLineNumber - deleteSelection.startLineNumber;
            }
            endCursorState.unshift(endPrimaryCursor);
            editor.pushUndoStop();
            editor.executeEdits(this.id, edits, endCursorState);
            editor.pushUndoStop();
        }
    }
    exports.JoinLinesAction = JoinLinesAction;
    class TransposeAction extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: 'editor.action.transpose',
                label: nls.localize(1128, "Transpose Characters around the Cursor"),
                alias: 'Transpose Characters around the Cursor',
                precondition: editorContextKeys_1.EditorContextKeys.writable
            });
        }
        run(_accessor, editor) {
            const selections = editor.getSelections();
            if (selections === null) {
                return;
            }
            const model = editor.getModel();
            if (model === null) {
                return;
            }
            const commands = [];
            for (let i = 0, len = selections.length; i < len; i++) {
                const selection = selections[i];
                if (!selection.isEmpty()) {
                    continue;
                }
                const cursor = selection.getStartPosition();
                const maxColumn = model.getLineMaxColumn(cursor.lineNumber);
                if (cursor.column >= maxColumn) {
                    if (cursor.lineNumber === model.getLineCount()) {
                        continue;
                    }
                    // The cursor is at the end of current line and current line is not empty
                    // then we transpose the character before the cursor and the line break if there is any following line.
                    const deleteSelection = new range_1.Range(cursor.lineNumber, Math.max(1, cursor.column - 1), cursor.lineNumber + 1, 1);
                    const chars = model.getValueInRange(deleteSelection).split('').reverse().join('');
                    commands.push(new replaceCommand_1.ReplaceCommand(new selection_1.Selection(cursor.lineNumber, Math.max(1, cursor.column - 1), cursor.lineNumber + 1, 1), chars));
                }
                else {
                    const deleteSelection = new range_1.Range(cursor.lineNumber, Math.max(1, cursor.column - 1), cursor.lineNumber, cursor.column + 1);
                    const chars = model.getValueInRange(deleteSelection).split('').reverse().join('');
                    commands.push(new replaceCommand_1.ReplaceCommandThatPreservesSelection(deleteSelection, chars, new selection_1.Selection(cursor.lineNumber, cursor.column + 1, cursor.lineNumber, cursor.column + 1)));
                }
            }
            editor.pushUndoStop();
            editor.executeCommands(this.id, commands);
            editor.pushUndoStop();
        }
    }
    exports.TransposeAction = TransposeAction;
    class AbstractCaseAction extends editorExtensions_1.EditorAction {
        run(_accessor, editor) {
            const selections = editor.getSelections();
            if (selections === null) {
                return;
            }
            const model = editor.getModel();
            if (model === null) {
                return;
            }
            const wordSeparators = editor.getOption(132 /* EditorOption.wordSeparators */);
            const textEdits = [];
            for (const selection of selections) {
                if (selection.isEmpty()) {
                    const cursor = selection.getStartPosition();
                    const word = editor.getConfiguredWordAtPosition(cursor);
                    if (!word) {
                        continue;
                    }
                    const wordRange = new range_1.Range(cursor.lineNumber, word.startColumn, cursor.lineNumber, word.endColumn);
                    const text = model.getValueInRange(wordRange);
                    textEdits.push(editOperation_1.EditOperation.replace(wordRange, this._modifyText(text, wordSeparators)));
                }
                else {
                    const text = model.getValueInRange(selection);
                    textEdits.push(editOperation_1.EditOperation.replace(selection, this._modifyText(text, wordSeparators)));
                }
            }
            editor.pushUndoStop();
            editor.executeEdits(this.id, textEdits);
            editor.pushUndoStop();
        }
    }
    exports.AbstractCaseAction = AbstractCaseAction;
    class UpperCaseAction extends AbstractCaseAction {
        constructor() {
            super({
                id: 'editor.action.transformToUppercase',
                label: nls.localize(1129, "Transform to Uppercase"),
                alias: 'Transform to Uppercase',
                precondition: editorContextKeys_1.EditorContextKeys.writable
            });
        }
        _modifyText(text, wordSeparators) {
            return text.toLocaleUpperCase();
        }
    }
    exports.UpperCaseAction = UpperCaseAction;
    class LowerCaseAction extends AbstractCaseAction {
        constructor() {
            super({
                id: 'editor.action.transformToLowercase',
                label: nls.localize(1130, "Transform to Lowercase"),
                alias: 'Transform to Lowercase',
                precondition: editorContextKeys_1.EditorContextKeys.writable
            });
        }
        _modifyText(text, wordSeparators) {
            return text.toLocaleLowerCase();
        }
    }
    exports.LowerCaseAction = LowerCaseAction;
    class BackwardsCompatibleRegExp {
        constructor(_pattern, _flags) {
            this._pattern = _pattern;
            this._flags = _flags;
            this._actual = null;
            this._evaluated = false;
        }
        get() {
            if (!this._evaluated) {
                this._evaluated = true;
                try {
                    this._actual = new RegExp(this._pattern, this._flags);
                }
                catch (err) {
                    // this browser does not support this regular expression
                }
            }
            return this._actual;
        }
        isSupported() {
            return (this.get() !== null);
        }
    }
    class TitleCaseAction extends AbstractCaseAction {
        static { this.titleBoundary = new BackwardsCompatibleRegExp('(^|[^\\p{L}\\p{N}\']|((^|\\P{L})\'))\\p{L}', 'gmu'); }
        constructor() {
            super({
                id: 'editor.action.transformToTitlecase',
                label: nls.localize(1131, "Transform to Title Case"),
                alias: 'Transform to Title Case',
                precondition: editorContextKeys_1.EditorContextKeys.writable
            });
        }
        _modifyText(text, wordSeparators) {
            const titleBoundary = TitleCaseAction.titleBoundary.get();
            if (!titleBoundary) {
                // cannot support this
                return text;
            }
            return text
                .toLocaleLowerCase()
                .replace(titleBoundary, (b) => b.toLocaleUpperCase());
        }
    }
    exports.TitleCaseAction = TitleCaseAction;
    class SnakeCaseAction extends AbstractCaseAction {
        static { this.caseBoundary = new BackwardsCompatibleRegExp('(\\p{Ll})(\\p{Lu})', 'gmu'); }
        static { this.singleLetters = new BackwardsCompatibleRegExp('(\\p{Lu}|\\p{N})(\\p{Lu})(\\p{Ll})', 'gmu'); }
        constructor() {
            super({
                id: 'editor.action.transformToSnakecase',
                label: nls.localize(1132, "Transform to Snake Case"),
                alias: 'Transform to Snake Case',
                precondition: editorContextKeys_1.EditorContextKeys.writable
            });
        }
        _modifyText(text, wordSeparators) {
            const caseBoundary = SnakeCaseAction.caseBoundary.get();
            const singleLetters = SnakeCaseAction.singleLetters.get();
            if (!caseBoundary || !singleLetters) {
                // cannot support this
                return text;
            }
            return (text
                .replace(caseBoundary, '$1_$2')
                .replace(singleLetters, '$1_$2$3')
                .toLocaleLowerCase());
        }
    }
    exports.SnakeCaseAction = SnakeCaseAction;
    class CamelCaseAction extends AbstractCaseAction {
        static { this.wordBoundary = new BackwardsCompatibleRegExp('[_\\s-]', 'gm'); }
        constructor() {
            super({
                id: 'editor.action.transformToCamelcase',
                label: nls.localize(1133, "Transform to Camel Case"),
                alias: 'Transform to Camel Case',
                precondition: editorContextKeys_1.EditorContextKeys.writable
            });
        }
        _modifyText(text, wordSeparators) {
            const wordBoundary = CamelCaseAction.wordBoundary.get();
            if (!wordBoundary) {
                // cannot support this
                return text;
            }
            const words = text.split(wordBoundary);
            const firstWord = words.shift();
            return firstWord + words.map((word) => word.substring(0, 1).toLocaleUpperCase() + word.substring(1))
                .join('');
        }
    }
    exports.CamelCaseAction = CamelCaseAction;
    class PascalCaseAction extends AbstractCaseAction {
        static { this.wordBoundary = new BackwardsCompatibleRegExp('[_\\s-]', 'gm'); }
        static { this.wordBoundaryToMaintain = new BackwardsCompatibleRegExp('(?<=\\.)', 'gm'); }
        constructor() {
            super({
                id: 'editor.action.transformToPascalcase',
                label: nls.localize(1134, "Transform to Pascal Case"),
                alias: 'Transform to Pascal Case',
                precondition: editorContextKeys_1.EditorContextKeys.writable
            });
        }
        _modifyText(text, wordSeparators) {
            const wordBoundary = PascalCaseAction.wordBoundary.get();
            const wordBoundaryToMaintain = PascalCaseAction.wordBoundaryToMaintain.get();
            if (!wordBoundary || !wordBoundaryToMaintain) {
                // cannot support this
                return text;
            }
            const wordsWithMaintainBoundaries = text.split(wordBoundaryToMaintain);
            const words = wordsWithMaintainBoundaries.map((word) => word.split(wordBoundary)).flat();
            return words.map((word) => word.substring(0, 1).toLocaleUpperCase() + word.substring(1))
                .join('');
        }
    }
    exports.PascalCaseAction = PascalCaseAction;
    class KebabCaseAction extends AbstractCaseAction {
        static isSupported() {
            const areAllRegexpsSupported = [
                this.caseBoundary,
                this.singleLetters,
                this.underscoreBoundary,
            ].every((regexp) => regexp.isSupported());
            return areAllRegexpsSupported;
        }
        static { this.caseBoundary = new BackwardsCompatibleRegExp('(\\p{Ll})(\\p{Lu})', 'gmu'); }
        static { this.singleLetters = new BackwardsCompatibleRegExp('(\\p{Lu}|\\p{N})(\\p{Lu}\\p{Ll})', 'gmu'); }
        static { this.underscoreBoundary = new BackwardsCompatibleRegExp('(\\S)(_)(\\S)', 'gm'); }
        constructor() {
            super({
                id: 'editor.action.transformToKebabcase',
                label: nls.localize(1135, 'Transform to Kebab Case'),
                alias: 'Transform to Kebab Case',
                precondition: editorContextKeys_1.EditorContextKeys.writable
            });
        }
        _modifyText(text, _) {
            const caseBoundary = KebabCaseAction.caseBoundary.get();
            const singleLetters = KebabCaseAction.singleLetters.get();
            const underscoreBoundary = KebabCaseAction.underscoreBoundary.get();
            if (!caseBoundary || !singleLetters || !underscoreBoundary) {
                // one or more regexps aren't supported
                return text;
            }
            return text
                .replace(underscoreBoundary, '$1-$3')
                .replace(caseBoundary, '$1-$2')
                .replace(singleLetters, '$1-$2')
                .toLocaleLowerCase();
        }
    }
    exports.KebabCaseAction = KebabCaseAction;
    (0, editorExtensions_1.registerEditorAction)(CopyLinesUpAction);
    (0, editorExtensions_1.registerEditorAction)(CopyLinesDownAction);
    (0, editorExtensions_1.registerEditorAction)(DuplicateSelectionAction);
    (0, editorExtensions_1.registerEditorAction)(MoveLinesUpAction);
    (0, editorExtensions_1.registerEditorAction)(MoveLinesDownAction);
    (0, editorExtensions_1.registerEditorAction)(SortLinesAscendingAction);
    (0, editorExtensions_1.registerEditorAction)(SortLinesDescendingAction);
    (0, editorExtensions_1.registerEditorAction)(DeleteDuplicateLinesAction);
    (0, editorExtensions_1.registerEditorAction)(TrimTrailingWhitespaceAction);
    (0, editorExtensions_1.registerEditorAction)(DeleteLinesAction);
    (0, editorExtensions_1.registerEditorAction)(IndentLinesAction);
    (0, editorExtensions_1.registerEditorAction)(OutdentLinesAction);
    (0, editorExtensions_1.registerEditorAction)(InsertLineBeforeAction);
    (0, editorExtensions_1.registerEditorAction)(InsertLineAfterAction);
    (0, editorExtensions_1.registerEditorAction)(DeleteAllLeftAction);
    (0, editorExtensions_1.registerEditorAction)(DeleteAllRightAction);
    (0, editorExtensions_1.registerEditorAction)(JoinLinesAction);
    (0, editorExtensions_1.registerEditorAction)(TransposeAction);
    (0, editorExtensions_1.registerEditorAction)(UpperCaseAction);
    (0, editorExtensions_1.registerEditorAction)(LowerCaseAction);
    if (SnakeCaseAction.caseBoundary.isSupported() && SnakeCaseAction.singleLetters.isSupported()) {
        (0, editorExtensions_1.registerEditorAction)(SnakeCaseAction);
    }
    if (CamelCaseAction.wordBoundary.isSupported()) {
        (0, editorExtensions_1.registerEditorAction)(CamelCaseAction);
    }
    if (PascalCaseAction.wordBoundary.isSupported()) {
        (0, editorExtensions_1.registerEditorAction)(PascalCaseAction);
    }
    if (TitleCaseAction.titleBoundary.isSupported()) {
        (0, editorExtensions_1.registerEditorAction)(TitleCaseAction);
    }
    if (KebabCaseAction.isSupported()) {
        (0, editorExtensions_1.registerEditorAction)(KebabCaseAction);
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[740/*vs/editor/contrib/longLinesHelper/browser/longLinesHelper*/], __M([1/*require*/,0/*exports*/,2/*vs/base/common/lifecycle*/,15/*vs/editor/browser/editorExtensions*/]), function (require, exports, lifecycle_1, editorExtensions_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    class LongLinesHelper extends lifecycle_1.Disposable {
        static { this.ID = 'editor.contrib.longLinesHelper'; }
        constructor(_editor) {
            super();
            this._editor = _editor;
            this._register(this._editor.onMouseDown((e) => {
                const stopRenderingLineAfter = this._editor.getOption(118 /* EditorOption.stopRenderingLineAfter */);
                if (stopRenderingLineAfter >= 0 && e.target.type === 6 /* MouseTargetType.CONTENT_TEXT */ && e.target.position.column >= stopRenderingLineAfter) {
                    this._editor.updateOptions({
                        stopRenderingLineAfter: -1
                    });
                }
            }));
        }
    }
    (0, editorExtensions_1.registerEditorContribution)(LongLinesHelper.ID, LongLinesHelper, 2 /* EditorContributionInstantiation.BeforeFirstInteraction */);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[184/*vs/editor/contrib/message/browser/messageController*/], __M([1/*require*/,0/*exports*/,207/*vs/base/browser/markdownRenderer*/,46/*vs/base/browser/ui/aria/aria*/,6/*vs/base/common/event*/,57/*vs/base/common/htmlContent*/,2/*vs/base/common/lifecycle*/,15/*vs/editor/browser/editorExtensions*/,4/*vs/editor/common/core/range*/,120/*vs/editor/browser/widget/markdownRenderer/browser/markdownRenderer*/,3/*vs/nls*/,12/*vs/platform/contextkey/common/contextkey*/,59/*vs/platform/opener/common/opener*/,5/*vs/base/browser/dom*/,525/*vs/css!vs/editor/contrib/message/browser/messageController*/]), function (require, exports, markdownRenderer_1, aria_1, event_1, htmlContent_1, lifecycle_1, editorExtensions_1, range_1, markdownRenderer_2, nls, contextkey_1, opener_1, dom) {
    "use strict";
    var MessageController_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MessageController = void 0;
    let MessageController = class MessageController {
        static { MessageController_1 = this; }
        static { this.ID = 'editor.contrib.messageController'; }
        static { this.MESSAGE_VISIBLE = new contextkey_1.RawContextKey('messageVisible', false, nls.localize(1148, 'Whether the editor is currently showing an inline message')); }
        static get(editor) {
            return editor.getContribution(MessageController_1.ID);
        }
        constructor(editor, contextKeyService, _openerService) {
            this._openerService = _openerService;
            this._messageWidget = new lifecycle_1.MutableDisposable();
            this._messageListeners = new lifecycle_1.DisposableStore();
            this._mouseOverMessage = false;
            this._editor = editor;
            this._visible = MessageController_1.MESSAGE_VISIBLE.bindTo(contextKeyService);
        }
        dispose() {
            this._message?.dispose();
            this._messageListeners.dispose();
            this._messageWidget.dispose();
            this._visible.reset();
        }
        showMessage(message, position) {
            (0, aria_1.alert)((0, htmlContent_1.isMarkdownString)(message) ? message.value : message);
            this._visible.set(true);
            this._messageWidget.clear();
            this._messageListeners.clear();
            this._message = (0, htmlContent_1.isMarkdownString)(message) ? (0, markdownRenderer_1.renderMarkdown)(message, {
                actionHandler: {
                    callback: (url) => {
                        this.closeMessage();
                        (0, markdownRenderer_2.openLinkFromMarkdown)(this._openerService, url, (0, htmlContent_1.isMarkdownString)(message) ? message.isTrusted : undefined);
                    },
                    disposables: this._messageListeners
                },
            }) : undefined;
            this._messageWidget.value = new MessageWidget(this._editor, position, typeof message === 'string' ? message : this._message.element);
            // close on blur (debounced to allow to tab into the message), cursor, model change, dispose
            this._messageListeners.add(event_1.Event.debounce(this._editor.onDidBlurEditorText, (last, event) => event, 0)(() => {
                if (this._mouseOverMessage) {
                    return; // override when mouse over message
                }
                if (this._messageWidget.value && dom.isAncestor(dom.getActiveElement(), this._messageWidget.value.getDomNode())) {
                    return; // override when focus is inside the message
                }
                this.closeMessage();
            }));
            this._messageListeners.add(this._editor.onDidChangeCursorPosition(() => this.closeMessage()));
            this._messageListeners.add(this._editor.onDidDispose(() => this.closeMessage()));
            this._messageListeners.add(this._editor.onDidChangeModel(() => this.closeMessage()));
            this._messageListeners.add(dom.addDisposableListener(this._messageWidget.value.getDomNode(), dom.EventType.MOUSE_ENTER, () => this._mouseOverMessage = true, true));
            this._messageListeners.add(dom.addDisposableListener(this._messageWidget.value.getDomNode(), dom.EventType.MOUSE_LEAVE, () => this._mouseOverMessage = false, true));
            // close on mouse move
            let bounds;
            this._messageListeners.add(this._editor.onMouseMove(e => {
                // outside the text area
                if (!e.target.position) {
                    return;
                }
                if (!bounds) {
                    // define bounding box around position and first mouse occurance
                    bounds = new range_1.Range(position.lineNumber - 3, 1, e.target.position.lineNumber + 3, 1);
                }
                else if (!bounds.containsPosition(e.target.position)) {
                    // check if position is still in bounds
                    this.closeMessage();
                }
            }));
        }
        closeMessage() {
            this._visible.reset();
            this._messageListeners.clear();
            if (this._messageWidget.value) {
                this._messageListeners.add(MessageWidget.fadeOut(this._messageWidget.value));
            }
        }
    };
    exports.MessageController = MessageController;
    exports.MessageController = MessageController = MessageController_1 = __decorate([
        __param(1, contextkey_1.IContextKeyService),
        __param(2, opener_1.IOpenerService)
    ], MessageController);
    const MessageCommand = editorExtensions_1.EditorCommand.bindToContribution(MessageController.get);
    (0, editorExtensions_1.registerEditorCommand)(new MessageCommand({
        id: 'leaveEditorMessage',
        precondition: MessageController.MESSAGE_VISIBLE,
        handler: c => c.closeMessage(),
        kbOpts: {
            weight: 100 /* KeybindingWeight.EditorContrib */ + 30,
            primary: 9 /* KeyCode.Escape */
        }
    }));
    class MessageWidget {
        static fadeOut(messageWidget) {
            const dispose = () => {
                messageWidget.dispose();
                clearTimeout(handle);
                messageWidget.getDomNode().removeEventListener('animationend', dispose);
            };
            const handle = setTimeout(dispose, 110);
            messageWidget.getDomNode().addEventListener('animationend', dispose);
            messageWidget.getDomNode().classList.add('fadeOut');
            return { dispose };
        }
        constructor(editor, { lineNumber, column }, text) {
            // Editor.IContentWidget.allowEditorOverflow
            this.allowEditorOverflow = true;
            this.suppressMouseDown = false;
            this._editor = editor;
            this._editor.revealLinesInCenterIfOutsideViewport(lineNumber, lineNumber, 0 /* ScrollType.Smooth */);
            this._position = { lineNumber, column };
            this._domNode = document.createElement('div');
            this._domNode.classList.add('monaco-editor-overlaymessage');
            this._domNode.style.marginLeft = '-6px';
            const anchorTop = document.createElement('div');
            anchorTop.classList.add('anchor', 'top');
            this._domNode.appendChild(anchorTop);
            const message = document.createElement('div');
            if (typeof text === 'string') {
                message.classList.add('message');
                message.textContent = text;
            }
            else {
                text.classList.add('message');
                message.appendChild(text);
            }
            this._domNode.appendChild(message);
            const anchorBottom = document.createElement('div');
            anchorBottom.classList.add('anchor', 'below');
            this._domNode.appendChild(anchorBottom);
            this._editor.addContentWidget(this);
            this._domNode.classList.add('fadeIn');
        }
        dispose() {
            this._editor.removeContentWidget(this);
        }
        getId() {
            return 'messageoverlay';
        }
        getDomNode() {
            return this._domNode;
        }
        getPosition() {
            return {
                position: this._position,
                preference: [
                    1 /* ContentWidgetPositionPreference.ABOVE */,
                    2 /* ContentWidgetPositionPreference.BELOW */,
                ],
                positionAffinity: 1 /* PositionAffinity.Right */,
            };
        }
        afterRender(position) {
            this._domNode.classList.toggle('below', position === 2 /* ContentWidgetPositionPreference.BELOW */);
        }
    }
    (0, editorExtensions_1.registerEditorContribution)(MessageController.ID, MessageController, 4 /* EditorContributionInstantiation.Lazy */);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[741/*vs/editor/contrib/readOnlyMessage/browser/contribution*/], __M([1/*require*/,0/*exports*/,57/*vs/base/common/htmlContent*/,2/*vs/base/common/lifecycle*/,15/*vs/editor/browser/editorExtensions*/,184/*vs/editor/contrib/message/browser/messageController*/,3/*vs/nls*/]), function (require, exports, htmlContent_1, lifecycle_1, editorExtensions_1, messageController_1, nls) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ReadOnlyMessageController = void 0;
    class ReadOnlyMessageController extends lifecycle_1.Disposable {
        static { this.ID = 'editor.contrib.readOnlyMessageController'; }
        constructor(editor) {
            super();
            this.editor = editor;
            this._register(this.editor.onDidAttemptReadOnlyEdit(() => this._onDidAttemptReadOnlyEdit()));
        }
        _onDidAttemptReadOnlyEdit() {
            const messageController = messageController_1.MessageController.get(this.editor);
            if (messageController && this.editor.hasModel()) {
                let message = this.editor.getOptions().get(93 /* EditorOption.readOnlyMessage */);
                if (!message) {
                    if (this.editor.isSimpleWidget) {
                        message = new htmlContent_1.MarkdownString(nls.localize(1233, "Cannot edit in read-only input"));
                    }
                    else {
                        message = new htmlContent_1.MarkdownString(nls.localize(1234, "Cannot edit in read-only editor"));
                    }
                }
                messageController.showMessage(message, this.editor.getPosition());
            }
        }
    }
    exports.ReadOnlyMessageController = ReadOnlyMessageController;
    (0, editorExtensions_1.registerEditorContribution)(ReadOnlyMessageController.ID, ReadOnlyMessageController, 2 /* EditorContributionInstantiation.BeforeFirstInteraction */);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[742/*vs/editor/contrib/smartSelect/browser/smartSelect*/], __M([1/*require*/,0/*exports*/,13/*vs/base/common/arrays*/,18/*vs/base/common/cancellation*/,8/*vs/base/common/errors*/,15/*vs/editor/browser/editorExtensions*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/,23/*vs/editor/common/core/selection*/,20/*vs/editor/common/editorContextKeys*/,340/*vs/editor/contrib/smartSelect/browser/bracketSelections*/,621/*vs/editor/contrib/smartSelect/browser/wordSelections*/,3/*vs/nls*/,29/*vs/platform/actions/common/actions*/,24/*vs/platform/commands/common/commands*/,17/*vs/editor/common/services/languageFeatures*/,78/*vs/editor/common/services/resolverService*/,19/*vs/base/common/types*/,22/*vs/base/common/uri*/]), function (require, exports, arrays, cancellation_1, errors_1, editorExtensions_1, position_1, range_1, selection_1, editorContextKeys_1, bracketSelections_1, wordSelections_1, nls, actions_1, commands_1, languageFeatures_1, resolverService_1, types_1, uri_1) {
    "use strict";
    var SmartSelectController_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SmartSelectController = void 0;
    exports.provideSelectionRanges = provideSelectionRanges;
    class SelectionRanges {
        constructor(index, ranges) {
            this.index = index;
            this.ranges = ranges;
        }
        mov(fwd) {
            const index = this.index + (fwd ? 1 : -1);
            if (index < 0 || index >= this.ranges.length) {
                return this;
            }
            const res = new SelectionRanges(index, this.ranges);
            if (res.ranges[index].equalsRange(this.ranges[this.index])) {
                // next range equals this range, retry with next-next
                return res.mov(fwd);
            }
            return res;
        }
    }
    let SmartSelectController = class SmartSelectController {
        static { SmartSelectController_1 = this; }
        static { this.ID = 'editor.contrib.smartSelectController'; }
        static get(editor) {
            return editor.getContribution(SmartSelectController_1.ID);
        }
        constructor(_editor, _languageFeaturesService) {
            this._editor = _editor;
            this._languageFeaturesService = _languageFeaturesService;
            this._ignoreSelection = false;
        }
        dispose() {
            this._selectionListener?.dispose();
        }
        async run(forward) {
            if (!this._editor.hasModel()) {
                return;
            }
            const selections = this._editor.getSelections();
            const model = this._editor.getModel();
            if (!this._state) {
                await provideSelectionRanges(this._languageFeaturesService.selectionRangeProvider, model, selections.map(s => s.getPosition()), this._editor.getOption(114 /* EditorOption.smartSelect */), cancellation_1.CancellationToken.None).then(ranges => {
                    if (!arrays.isNonEmptyArray(ranges) || ranges.length !== selections.length) {
                        // invalid result
                        return;
                    }
                    if (!this._editor.hasModel() || !arrays.equals(this._editor.getSelections(), selections, (a, b) => a.equalsSelection(b))) {
                        // invalid editor state
                        return;
                    }
                    for (let i = 0; i < ranges.length; i++) {
                        ranges[i] = ranges[i].filter(range => {
                            // filter ranges inside the selection
                            return range.containsPosition(selections[i].getStartPosition()) && range.containsPosition(selections[i].getEndPosition());
                        });
                        // prepend current selection
                        ranges[i].unshift(selections[i]);
                    }
                    this._state = ranges.map(ranges => new SelectionRanges(0, ranges));
                    // listen to caret move and forget about state
                    this._selectionListener?.dispose();
                    this._selectionListener = this._editor.onDidChangeCursorPosition(() => {
                        if (!this._ignoreSelection) {
                            this._selectionListener?.dispose();
                            this._state = undefined;
                        }
                    });
                });
            }
            if (!this._state) {
                // no state
                return;
            }
            this._state = this._state.map(state => state.mov(forward));
            const newSelections = this._state.map(state => selection_1.Selection.fromPositions(state.ranges[state.index].getStartPosition(), state.ranges[state.index].getEndPosition()));
            this._ignoreSelection = true;
            try {
                this._editor.setSelections(newSelections);
            }
            finally {
                this._ignoreSelection = false;
            }
        }
    };
    exports.SmartSelectController = SmartSelectController;
    exports.SmartSelectController = SmartSelectController = SmartSelectController_1 = __decorate([
        __param(1, languageFeatures_1.ILanguageFeaturesService)
    ], SmartSelectController);
    class AbstractSmartSelect extends editorExtensions_1.EditorAction {
        constructor(forward, opts) {
            super(opts);
            this._forward = forward;
        }
        async run(_accessor, editor) {
            const controller = SmartSelectController.get(editor);
            if (controller) {
                await controller.run(this._forward);
            }
        }
    }
    class GrowSelectionAction extends AbstractSmartSelect {
        constructor() {
            super(true, {
                id: 'editor.action.smartSelect.expand',
                label: nls.localize(1253, "Expand Selection"),
                alias: 'Expand Selection',
                precondition: undefined,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    primary: 1024 /* KeyMod.Shift */ | 512 /* KeyMod.Alt */ | 17 /* KeyCode.RightArrow */,
                    mac: {
                        primary: 2048 /* KeyMod.CtrlCmd */ | 256 /* KeyMod.WinCtrl */ | 1024 /* KeyMod.Shift */ | 17 /* KeyCode.RightArrow */,
                        secondary: [256 /* KeyMod.WinCtrl */ | 1024 /* KeyMod.Shift */ | 17 /* KeyCode.RightArrow */],
                    },
                    weight: 100 /* KeybindingWeight.EditorContrib */
                },
                menuOpts: {
                    menuId: actions_1.MenuId.MenubarSelectionMenu,
                    group: '1_basic',
                    title: nls.localize(1254, "&&Expand Selection"),
                    order: 2
                }
            });
        }
    }
    // renamed command id
    commands_1.CommandsRegistry.registerCommandAlias('editor.action.smartSelect.grow', 'editor.action.smartSelect.expand');
    class ShrinkSelectionAction extends AbstractSmartSelect {
        constructor() {
            super(false, {
                id: 'editor.action.smartSelect.shrink',
                label: nls.localize(1255, "Shrink Selection"),
                alias: 'Shrink Selection',
                precondition: undefined,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    primary: 1024 /* KeyMod.Shift */ | 512 /* KeyMod.Alt */ | 15 /* KeyCode.LeftArrow */,
                    mac: {
                        primary: 2048 /* KeyMod.CtrlCmd */ | 256 /* KeyMod.WinCtrl */ | 1024 /* KeyMod.Shift */ | 15 /* KeyCode.LeftArrow */,
                        secondary: [256 /* KeyMod.WinCtrl */ | 1024 /* KeyMod.Shift */ | 15 /* KeyCode.LeftArrow */],
                    },
                    weight: 100 /* KeybindingWeight.EditorContrib */
                },
                menuOpts: {
                    menuId: actions_1.MenuId.MenubarSelectionMenu,
                    group: '1_basic',
                    title: nls.localize(1256, "&&Shrink Selection"),
                    order: 3
                }
            });
        }
    }
    (0, editorExtensions_1.registerEditorContribution)(SmartSelectController.ID, SmartSelectController, 4 /* EditorContributionInstantiation.Lazy */);
    (0, editorExtensions_1.registerEditorAction)(GrowSelectionAction);
    (0, editorExtensions_1.registerEditorAction)(ShrinkSelectionAction);
    async function provideSelectionRanges(registry, model, positions, options, token) {
        const providers = registry.all(model)
            .concat(new wordSelections_1.WordSelectionRangeProvider(options.selectSubwords)); // ALWAYS have word based selection range
        if (providers.length === 1) {
            // add word selection and bracket selection when no provider exists
            providers.unshift(new bracketSelections_1.BracketSelectionRangeProvider());
        }
        const work = [];
        const allRawRanges = [];
        for (const provider of providers) {
            work.push(Promise.resolve(provider.provideSelectionRanges(model, positions, token)).then(allProviderRanges => {
                if (arrays.isNonEmptyArray(allProviderRanges) && allProviderRanges.length === positions.length) {
                    for (let i = 0; i < positions.length; i++) {
                        if (!allRawRanges[i]) {
                            allRawRanges[i] = [];
                        }
                        for (const oneProviderRanges of allProviderRanges[i]) {
                            if (range_1.Range.isIRange(oneProviderRanges.range) && range_1.Range.containsPosition(oneProviderRanges.range, positions[i])) {
                                allRawRanges[i].push(range_1.Range.lift(oneProviderRanges.range));
                            }
                        }
                    }
                }
            }, errors_1.onUnexpectedExternalError));
        }
        await Promise.all(work);
        return allRawRanges.map(oneRawRanges => {
            if (oneRawRanges.length === 0) {
                return [];
            }
            // sort all by start/end position
            oneRawRanges.sort((a, b) => {
                if (position_1.Position.isBefore(a.getStartPosition(), b.getStartPosition())) {
                    return 1;
                }
                else if (position_1.Position.isBefore(b.getStartPosition(), a.getStartPosition())) {
                    return -1;
                }
                else if (position_1.Position.isBefore(a.getEndPosition(), b.getEndPosition())) {
                    return -1;
                }
                else if (position_1.Position.isBefore(b.getEndPosition(), a.getEndPosition())) {
                    return 1;
                }
                else {
                    return 0;
                }
            });
            // remove ranges that don't contain the former range or that are equal to the
            // former range
            const oneRanges = [];
            let last;
            for (const range of oneRawRanges) {
                if (!last || (range_1.Range.containsRange(range, last) && !range_1.Range.equalsRange(range, last))) {
                    oneRanges.push(range);
                    last = range;
                }
            }
            if (!options.selectLeadingAndTrailingWhitespace) {
                return oneRanges;
            }
            // add ranges that expand trivia at line starts and ends whenever a range
            // wraps onto the a new line
            const oneRangesWithTrivia = [oneRanges[0]];
            for (let i = 1; i < oneRanges.length; i++) {
                const prev = oneRanges[i - 1];
                const cur = oneRanges[i];
                if (cur.startLineNumber !== prev.startLineNumber || cur.endLineNumber !== prev.endLineNumber) {
                    // add line/block range without leading/failing whitespace
                    const rangeNoWhitespace = new range_1.Range(prev.startLineNumber, model.getLineFirstNonWhitespaceColumn(prev.startLineNumber), prev.endLineNumber, model.getLineLastNonWhitespaceColumn(prev.endLineNumber));
                    if (rangeNoWhitespace.containsRange(prev) && !rangeNoWhitespace.equalsRange(prev) && cur.containsRange(rangeNoWhitespace) && !cur.equalsRange(rangeNoWhitespace)) {
                        oneRangesWithTrivia.push(rangeNoWhitespace);
                    }
                    // add line/block range
                    const rangeFull = new range_1.Range(prev.startLineNumber, 1, prev.endLineNumber, model.getLineMaxColumn(prev.endLineNumber));
                    if (rangeFull.containsRange(prev) && !rangeFull.equalsRange(rangeNoWhitespace) && cur.containsRange(rangeFull) && !cur.equalsRange(rangeFull)) {
                        oneRangesWithTrivia.push(rangeFull);
                    }
                }
                oneRangesWithTrivia.push(cur);
            }
            return oneRangesWithTrivia;
        });
    }
    commands_1.CommandsRegistry.registerCommand('_executeSelectionRangeProvider', async function (accessor, ...args) {
        const [resource, positions] = args;
        (0, types_1.assertType)(uri_1.URI.isUri(resource));
        const registry = accessor.get(languageFeatures_1.ILanguageFeaturesService).selectionRangeProvider;
        const reference = await accessor.get(resolverService_1.ITextModelService).createModelReference(resource);
        try {
            return provideSelectionRanges(registry, reference.object.textEditorModel, positions, { selectLeadingAndTrailingWhitespace: true, selectSubwords: true }, cancellation_1.CancellationToken.None);
        }
        finally {
            reference.dispose();
        }
    });
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[743/*vs/editor/contrib/tokenization/browser/tokenization*/], __M([1/*require*/,0/*exports*/,54/*vs/base/common/stopwatch*/,15/*vs/editor/browser/editorExtensions*/,3/*vs/nls*/]), function (require, exports, stopwatch_1, editorExtensions_1, nls) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    class ForceRetokenizeAction extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: 'editor.action.forceRetokenize',
                label: nls.localize(1385, "Developer: Force Retokenize"),
                alias: 'Developer: Force Retokenize',
                precondition: undefined
            });
        }
        run(accessor, editor) {
            if (!editor.hasModel()) {
                return;
            }
            const model = editor.getModel();
            model.tokenization.resetTokenization();
            const sw = new stopwatch_1.StopWatch();
            model.tokenization.forceTokenization(model.getLineCount());
            sw.stop();
            console.log(`tokenization took ${sw.elapsed()}`);
        }
    }
    (0, editorExtensions_1.registerEditorAction)(ForceRetokenizeAction);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[744/*vs/editor/contrib/unusualLineTerminators/browser/unusualLineTerminators*/], __M([1/*require*/,0/*exports*/,2/*vs/base/common/lifecycle*/,48/*vs/base/common/resources*/,15/*vs/editor/browser/editorExtensions*/,34/*vs/editor/browser/services/codeEditorService*/,3/*vs/nls*/,180/*vs/platform/dialogs/common/dialogs*/]), function (require, exports, lifecycle_1, resources_1, editorExtensions_1, codeEditorService_1, nls, dialogs_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.UnusualLineTerminatorsDetector = void 0;
    const ignoreUnusualLineTerminators = 'ignoreUnusualLineTerminators';
    function writeIgnoreState(codeEditorService, model, state) {
        codeEditorService.setModelProperty(model.uri, ignoreUnusualLineTerminators, state);
    }
    function readIgnoreState(codeEditorService, model) {
        return codeEditorService.getModelProperty(model.uri, ignoreUnusualLineTerminators);
    }
    let UnusualLineTerminatorsDetector = class UnusualLineTerminatorsDetector extends lifecycle_1.Disposable {
        static { this.ID = 'editor.contrib.unusualLineTerminatorsDetector'; }
        constructor(_editor, _dialogService, _codeEditorService) {
            super();
            this._editor = _editor;
            this._dialogService = _dialogService;
            this._codeEditorService = _codeEditorService;
            this._isPresentingDialog = false;
            this._config = this._editor.getOption(127 /* EditorOption.unusualLineTerminators */);
            this._register(this._editor.onDidChangeConfiguration((e) => {
                if (e.hasChanged(127 /* EditorOption.unusualLineTerminators */)) {
                    this._config = this._editor.getOption(127 /* EditorOption.unusualLineTerminators */);
                    this._checkForUnusualLineTerminators();
                }
            }));
            this._register(this._editor.onDidChangeModel(() => {
                this._checkForUnusualLineTerminators();
            }));
            this._register(this._editor.onDidChangeModelContent((e) => {
                if (e.isUndoing) {
                    // skip checking in case of undoing
                    return;
                }
                this._checkForUnusualLineTerminators();
            }));
            this._checkForUnusualLineTerminators();
        }
        async _checkForUnusualLineTerminators() {
            if (this._config === 'off') {
                return;
            }
            if (!this._editor.hasModel()) {
                return;
            }
            const model = this._editor.getModel();
            if (!model.mightContainUnusualLineTerminators()) {
                return;
            }
            const ignoreState = readIgnoreState(this._codeEditorService, model);
            if (ignoreState === true) {
                // this model should be ignored
                return;
            }
            if (this._editor.getOption(92 /* EditorOption.readOnly */)) {
                // read only editor => sorry!
                return;
            }
            if (this._config === 'auto') {
                // just do it!
                model.removeUnusualLineTerminators(this._editor.getSelections());
                return;
            }
            if (this._isPresentingDialog) {
                // we're currently showing the dialog, which is async.
                // avoid spamming the user
                return;
            }
            let result;
            try {
                this._isPresentingDialog = true;
                result = await this._dialogService.confirm({
                    title: nls.localize(1410, "Unusual Line Terminators"),
                    message: nls.localize(1411, "Detected unusual line terminators"),
                    detail: nls.localize(1412, "The file '{0}' contains one or more unusual line terminator characters, like Line Separator (LS) or Paragraph Separator (PS).\n\nIt is recommended to remove them from the file. This can be configured via `editor.unusualLineTerminators`.", (0, resources_1.basename)(model.uri)),
                    primaryButton: nls.localize(1413, "&&Remove Unusual Line Terminators"),
                    cancelButton: nls.localize(1414, "Ignore")
                });
            }
            finally {
                this._isPresentingDialog = false;
            }
            if (!result.confirmed) {
                // this model should be ignored
                writeIgnoreState(this._codeEditorService, model, true);
                return;
            }
            model.removeUnusualLineTerminators(this._editor.getSelections());
        }
    };
    exports.UnusualLineTerminatorsDetector = UnusualLineTerminatorsDetector;
    exports.UnusualLineTerminatorsDetector = UnusualLineTerminatorsDetector = __decorate([
        __param(1, dialogs_1.IDialogService),
        __param(2, codeEditorService_1.ICodeEditorService)
    ], UnusualLineTerminatorsDetector);
    (0, editorExtensions_1.registerEditorContribution)(UnusualLineTerminatorsDetector.ID, UnusualLineTerminatorsDetector, 1 /* EditorContributionInstantiation.AfterFirstRender */);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[411/*vs/editor/contrib/wordOperations/browser/wordOperations*/], __M([1/*require*/,0/*exports*/,15/*vs/editor/browser/editorExtensions*/,146/*vs/editor/common/commands/replaceCommand*/,37/*vs/editor/common/config/editorOptions*/,76/*vs/editor/common/cursorCommon*/,199/*vs/editor/common/cursor/cursorWordOperations*/,166/*vs/editor/common/core/wordCharacterClassifier*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/,23/*vs/editor/common/core/selection*/,20/*vs/editor/common/editorContextKeys*/,36/*vs/editor/common/languages/languageConfigurationRegistry*/,3/*vs/nls*/,61/*vs/platform/accessibility/common/accessibility*/,12/*vs/platform/contextkey/common/contextkey*/,179/*vs/platform/contextkey/common/contextkeys*/]), function (require, exports, editorExtensions_1, replaceCommand_1, editorOptions_1, cursorCommon_1, cursorWordOperations_1, wordCharacterClassifier_1, position_1, range_1, selection_1, editorContextKeys_1, languageConfigurationRegistry_1, nls, accessibility_1, contextkey_1, contextkeys_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DeleteInsideWord = exports.DeleteWordRight = exports.DeleteWordEndRight = exports.DeleteWordStartRight = exports.DeleteWordLeft = exports.DeleteWordEndLeft = exports.DeleteWordStartLeft = exports.DeleteWordRightCommand = exports.DeleteWordLeftCommand = exports.DeleteWordCommand = exports.CursorWordAccessibilityRightSelect = exports.CursorWordAccessibilityRight = exports.CursorWordRightSelect = exports.CursorWordEndRightSelect = exports.CursorWordStartRightSelect = exports.CursorWordRight = exports.CursorWordEndRight = exports.CursorWordStartRight = exports.CursorWordAccessibilityLeftSelect = exports.CursorWordAccessibilityLeft = exports.CursorWordLeftSelect = exports.CursorWordEndLeftSelect = exports.CursorWordStartLeftSelect = exports.CursorWordLeft = exports.CursorWordEndLeft = exports.CursorWordStartLeft = exports.WordRightCommand = exports.WordLeftCommand = exports.MoveWordCommand = void 0;
    class MoveWordCommand extends editorExtensions_1.EditorCommand {
        constructor(opts) {
            super(opts);
            this._inSelectionMode = opts.inSelectionMode;
            this._wordNavigationType = opts.wordNavigationType;
        }
        runEditorCommand(accessor, editor, args) {
            if (!editor.hasModel()) {
                return;
            }
            const wordSeparators = (0, wordCharacterClassifier_1.getMapForWordSeparators)(editor.getOption(132 /* EditorOption.wordSeparators */), editor.getOption(131 /* EditorOption.wordSegmenterLocales */));
            const model = editor.getModel();
            const selections = editor.getSelections();
            const hasMulticursor = selections.length > 1;
            const result = selections.map((sel) => {
                const inPosition = new position_1.Position(sel.positionLineNumber, sel.positionColumn);
                const outPosition = this._move(wordSeparators, model, inPosition, this._wordNavigationType, hasMulticursor);
                return this._moveTo(sel, outPosition, this._inSelectionMode);
            });
            model.pushStackElement();
            editor._getViewModel().setCursorStates('moveWordCommand', 3 /* CursorChangeReason.Explicit */, result.map(r => cursorCommon_1.CursorState.fromModelSelection(r)));
            if (result.length === 1) {
                const pos = new position_1.Position(result[0].positionLineNumber, result[0].positionColumn);
                editor.revealPosition(pos, 0 /* ScrollType.Smooth */);
            }
        }
        _moveTo(from, to, inSelectionMode) {
            if (inSelectionMode) {
                // move just position
                return new selection_1.Selection(from.selectionStartLineNumber, from.selectionStartColumn, to.lineNumber, to.column);
            }
            else {
                // move everything
                return new selection_1.Selection(to.lineNumber, to.column, to.lineNumber, to.column);
            }
        }
    }
    exports.MoveWordCommand = MoveWordCommand;
    class WordLeftCommand extends MoveWordCommand {
        _move(wordSeparators, model, position, wordNavigationType, hasMulticursor) {
            return cursorWordOperations_1.WordOperations.moveWordLeft(wordSeparators, model, position, wordNavigationType, hasMulticursor);
        }
    }
    exports.WordLeftCommand = WordLeftCommand;
    class WordRightCommand extends MoveWordCommand {
        _move(wordSeparators, model, position, wordNavigationType, hasMulticursor) {
            return cursorWordOperations_1.WordOperations.moveWordRight(wordSeparators, model, position, wordNavigationType);
        }
    }
    exports.WordRightCommand = WordRightCommand;
    class CursorWordStartLeft extends WordLeftCommand {
        constructor() {
            super({
                inSelectionMode: false,
                wordNavigationType: 0 /* WordNavigationType.WordStart */,
                id: 'cursorWordStartLeft',
                precondition: undefined
            });
        }
    }
    exports.CursorWordStartLeft = CursorWordStartLeft;
    class CursorWordEndLeft extends WordLeftCommand {
        constructor() {
            super({
                inSelectionMode: false,
                wordNavigationType: 2 /* WordNavigationType.WordEnd */,
                id: 'cursorWordEndLeft',
                precondition: undefined
            });
        }
    }
    exports.CursorWordEndLeft = CursorWordEndLeft;
    class CursorWordLeft extends WordLeftCommand {
        constructor() {
            super({
                inSelectionMode: false,
                wordNavigationType: 1 /* WordNavigationType.WordStartFast */,
                id: 'cursorWordLeft',
                precondition: undefined,
                kbOpts: {
                    kbExpr: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.textInputFocus, contextkey_1.ContextKeyExpr.and(accessibility_1.CONTEXT_ACCESSIBILITY_MODE_ENABLED, contextkeys_1.IsWindowsContext)?.negate()),
                    primary: 2048 /* KeyMod.CtrlCmd */ | 15 /* KeyCode.LeftArrow */,
                    mac: { primary: 512 /* KeyMod.Alt */ | 15 /* KeyCode.LeftArrow */ },
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
    }
    exports.CursorWordLeft = CursorWordLeft;
    class CursorWordStartLeftSelect extends WordLeftCommand {
        constructor() {
            super({
                inSelectionMode: true,
                wordNavigationType: 0 /* WordNavigationType.WordStart */,
                id: 'cursorWordStartLeftSelect',
                precondition: undefined
            });
        }
    }
    exports.CursorWordStartLeftSelect = CursorWordStartLeftSelect;
    class CursorWordEndLeftSelect extends WordLeftCommand {
        constructor() {
            super({
                inSelectionMode: true,
                wordNavigationType: 2 /* WordNavigationType.WordEnd */,
                id: 'cursorWordEndLeftSelect',
                precondition: undefined
            });
        }
    }
    exports.CursorWordEndLeftSelect = CursorWordEndLeftSelect;
    class CursorWordLeftSelect extends WordLeftCommand {
        constructor() {
            super({
                inSelectionMode: true,
                wordNavigationType: 1 /* WordNavigationType.WordStartFast */,
                id: 'cursorWordLeftSelect',
                precondition: undefined,
                kbOpts: {
                    kbExpr: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.textInputFocus, contextkey_1.ContextKeyExpr.and(accessibility_1.CONTEXT_ACCESSIBILITY_MODE_ENABLED, contextkeys_1.IsWindowsContext)?.negate()),
                    primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 15 /* KeyCode.LeftArrow */,
                    mac: { primary: 512 /* KeyMod.Alt */ | 1024 /* KeyMod.Shift */ | 15 /* KeyCode.LeftArrow */ },
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
    }
    exports.CursorWordLeftSelect = CursorWordLeftSelect;
    // Accessibility navigation commands should only be enabled on windows since they are tuned to what NVDA expects
    class CursorWordAccessibilityLeft extends WordLeftCommand {
        constructor() {
            super({
                inSelectionMode: false,
                wordNavigationType: 3 /* WordNavigationType.WordAccessibility */,
                id: 'cursorWordAccessibilityLeft',
                precondition: undefined
            });
        }
        _move(wordCharacterClassifier, model, position, wordNavigationType, hasMulticursor) {
            return super._move((0, wordCharacterClassifier_1.getMapForWordSeparators)(editorOptions_1.EditorOptions.wordSeparators.defaultValue, wordCharacterClassifier.intlSegmenterLocales), model, position, wordNavigationType, hasMulticursor);
        }
    }
    exports.CursorWordAccessibilityLeft = CursorWordAccessibilityLeft;
    class CursorWordAccessibilityLeftSelect extends WordLeftCommand {
        constructor() {
            super({
                inSelectionMode: true,
                wordNavigationType: 3 /* WordNavigationType.WordAccessibility */,
                id: 'cursorWordAccessibilityLeftSelect',
                precondition: undefined
            });
        }
        _move(wordCharacterClassifier, model, position, wordNavigationType, hasMulticursor) {
            return super._move((0, wordCharacterClassifier_1.getMapForWordSeparators)(editorOptions_1.EditorOptions.wordSeparators.defaultValue, wordCharacterClassifier.intlSegmenterLocales), model, position, wordNavigationType, hasMulticursor);
        }
    }
    exports.CursorWordAccessibilityLeftSelect = CursorWordAccessibilityLeftSelect;
    class CursorWordStartRight extends WordRightCommand {
        constructor() {
            super({
                inSelectionMode: false,
                wordNavigationType: 0 /* WordNavigationType.WordStart */,
                id: 'cursorWordStartRight',
                precondition: undefined
            });
        }
    }
    exports.CursorWordStartRight = CursorWordStartRight;
    class CursorWordEndRight extends WordRightCommand {
        constructor() {
            super({
                inSelectionMode: false,
                wordNavigationType: 2 /* WordNavigationType.WordEnd */,
                id: 'cursorWordEndRight',
                precondition: undefined,
                kbOpts: {
                    kbExpr: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.textInputFocus, contextkey_1.ContextKeyExpr.and(accessibility_1.CONTEXT_ACCESSIBILITY_MODE_ENABLED, contextkeys_1.IsWindowsContext)?.negate()),
                    primary: 2048 /* KeyMod.CtrlCmd */ | 17 /* KeyCode.RightArrow */,
                    mac: { primary: 512 /* KeyMod.Alt */ | 17 /* KeyCode.RightArrow */ },
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
    }
    exports.CursorWordEndRight = CursorWordEndRight;
    class CursorWordRight extends WordRightCommand {
        constructor() {
            super({
                inSelectionMode: false,
                wordNavigationType: 2 /* WordNavigationType.WordEnd */,
                id: 'cursorWordRight',
                precondition: undefined
            });
        }
    }
    exports.CursorWordRight = CursorWordRight;
    class CursorWordStartRightSelect extends WordRightCommand {
        constructor() {
            super({
                inSelectionMode: true,
                wordNavigationType: 0 /* WordNavigationType.WordStart */,
                id: 'cursorWordStartRightSelect',
                precondition: undefined
            });
        }
    }
    exports.CursorWordStartRightSelect = CursorWordStartRightSelect;
    class CursorWordEndRightSelect extends WordRightCommand {
        constructor() {
            super({
                inSelectionMode: true,
                wordNavigationType: 2 /* WordNavigationType.WordEnd */,
                id: 'cursorWordEndRightSelect',
                precondition: undefined,
                kbOpts: {
                    kbExpr: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.textInputFocus, contextkey_1.ContextKeyExpr.and(accessibility_1.CONTEXT_ACCESSIBILITY_MODE_ENABLED, contextkeys_1.IsWindowsContext)?.negate()),
                    primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 17 /* KeyCode.RightArrow */,
                    mac: { primary: 512 /* KeyMod.Alt */ | 1024 /* KeyMod.Shift */ | 17 /* KeyCode.RightArrow */ },
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
    }
    exports.CursorWordEndRightSelect = CursorWordEndRightSelect;
    class CursorWordRightSelect extends WordRightCommand {
        constructor() {
            super({
                inSelectionMode: true,
                wordNavigationType: 2 /* WordNavigationType.WordEnd */,
                id: 'cursorWordRightSelect',
                precondition: undefined
            });
        }
    }
    exports.CursorWordRightSelect = CursorWordRightSelect;
    class CursorWordAccessibilityRight extends WordRightCommand {
        constructor() {
            super({
                inSelectionMode: false,
                wordNavigationType: 3 /* WordNavigationType.WordAccessibility */,
                id: 'cursorWordAccessibilityRight',
                precondition: undefined
            });
        }
        _move(wordCharacterClassifier, model, position, wordNavigationType, hasMulticursor) {
            return super._move((0, wordCharacterClassifier_1.getMapForWordSeparators)(editorOptions_1.EditorOptions.wordSeparators.defaultValue, wordCharacterClassifier.intlSegmenterLocales), model, position, wordNavigationType, hasMulticursor);
        }
    }
    exports.CursorWordAccessibilityRight = CursorWordAccessibilityRight;
    class CursorWordAccessibilityRightSelect extends WordRightCommand {
        constructor() {
            super({
                inSelectionMode: true,
                wordNavigationType: 3 /* WordNavigationType.WordAccessibility */,
                id: 'cursorWordAccessibilityRightSelect',
                precondition: undefined
            });
        }
        _move(wordCharacterClassifier, model, position, wordNavigationType, hasMulticursor) {
            return super._move((0, wordCharacterClassifier_1.getMapForWordSeparators)(editorOptions_1.EditorOptions.wordSeparators.defaultValue, wordCharacterClassifier.intlSegmenterLocales), model, position, wordNavigationType, hasMulticursor);
        }
    }
    exports.CursorWordAccessibilityRightSelect = CursorWordAccessibilityRightSelect;
    class DeleteWordCommand extends editorExtensions_1.EditorCommand {
        constructor(opts) {
            super(opts);
            this._whitespaceHeuristics = opts.whitespaceHeuristics;
            this._wordNavigationType = opts.wordNavigationType;
        }
        runEditorCommand(accessor, editor, args) {
            const languageConfigurationService = accessor.get(languageConfigurationRegistry_1.ILanguageConfigurationService);
            if (!editor.hasModel()) {
                return;
            }
            const wordSeparators = (0, wordCharacterClassifier_1.getMapForWordSeparators)(editor.getOption(132 /* EditorOption.wordSeparators */), editor.getOption(131 /* EditorOption.wordSegmenterLocales */));
            const model = editor.getModel();
            const selections = editor.getSelections();
            const autoClosingBrackets = editor.getOption(6 /* EditorOption.autoClosingBrackets */);
            const autoClosingQuotes = editor.getOption(11 /* EditorOption.autoClosingQuotes */);
            const autoClosingPairs = languageConfigurationService.getLanguageConfiguration(model.getLanguageId()).getAutoClosingPairs();
            const viewModel = editor._getViewModel();
            const commands = selections.map((sel) => {
                const deleteRange = this._delete({
                    wordSeparators,
                    model,
                    selection: sel,
                    whitespaceHeuristics: this._whitespaceHeuristics,
                    autoClosingDelete: editor.getOption(9 /* EditorOption.autoClosingDelete */),
                    autoClosingBrackets,
                    autoClosingQuotes,
                    autoClosingPairs,
                    autoClosedCharacters: viewModel.getCursorAutoClosedCharacters(),
                }, this._wordNavigationType);
                return new replaceCommand_1.ReplaceCommand(deleteRange, '');
            });
            editor.pushUndoStop();
            editor.executeCommands(this.id, commands);
            editor.pushUndoStop();
        }
    }
    exports.DeleteWordCommand = DeleteWordCommand;
    class DeleteWordLeftCommand extends DeleteWordCommand {
        _delete(ctx, wordNavigationType) {
            const r = cursorWordOperations_1.WordOperations.deleteWordLeft(ctx, wordNavigationType);
            if (r) {
                return r;
            }
            return new range_1.Range(1, 1, 1, 1);
        }
    }
    exports.DeleteWordLeftCommand = DeleteWordLeftCommand;
    class DeleteWordRightCommand extends DeleteWordCommand {
        _delete(ctx, wordNavigationType) {
            const r = cursorWordOperations_1.WordOperations.deleteWordRight(ctx, wordNavigationType);
            if (r) {
                return r;
            }
            const lineCount = ctx.model.getLineCount();
            const maxColumn = ctx.model.getLineMaxColumn(lineCount);
            return new range_1.Range(lineCount, maxColumn, lineCount, maxColumn);
        }
    }
    exports.DeleteWordRightCommand = DeleteWordRightCommand;
    class DeleteWordStartLeft extends DeleteWordLeftCommand {
        constructor() {
            super({
                whitespaceHeuristics: false,
                wordNavigationType: 0 /* WordNavigationType.WordStart */,
                id: 'deleteWordStartLeft',
                precondition: editorContextKeys_1.EditorContextKeys.writable
            });
        }
    }
    exports.DeleteWordStartLeft = DeleteWordStartLeft;
    class DeleteWordEndLeft extends DeleteWordLeftCommand {
        constructor() {
            super({
                whitespaceHeuristics: false,
                wordNavigationType: 2 /* WordNavigationType.WordEnd */,
                id: 'deleteWordEndLeft',
                precondition: editorContextKeys_1.EditorContextKeys.writable
            });
        }
    }
    exports.DeleteWordEndLeft = DeleteWordEndLeft;
    class DeleteWordLeft extends DeleteWordLeftCommand {
        constructor() {
            super({
                whitespaceHeuristics: true,
                wordNavigationType: 0 /* WordNavigationType.WordStart */,
                id: 'deleteWordLeft',
                precondition: editorContextKeys_1.EditorContextKeys.writable,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                    primary: 2048 /* KeyMod.CtrlCmd */ | 1 /* KeyCode.Backspace */,
                    mac: { primary: 512 /* KeyMod.Alt */ | 1 /* KeyCode.Backspace */ },
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
    }
    exports.DeleteWordLeft = DeleteWordLeft;
    class DeleteWordStartRight extends DeleteWordRightCommand {
        constructor() {
            super({
                whitespaceHeuristics: false,
                wordNavigationType: 0 /* WordNavigationType.WordStart */,
                id: 'deleteWordStartRight',
                precondition: editorContextKeys_1.EditorContextKeys.writable
            });
        }
    }
    exports.DeleteWordStartRight = DeleteWordStartRight;
    class DeleteWordEndRight extends DeleteWordRightCommand {
        constructor() {
            super({
                whitespaceHeuristics: false,
                wordNavigationType: 2 /* WordNavigationType.WordEnd */,
                id: 'deleteWordEndRight',
                precondition: editorContextKeys_1.EditorContextKeys.writable
            });
        }
    }
    exports.DeleteWordEndRight = DeleteWordEndRight;
    class DeleteWordRight extends DeleteWordRightCommand {
        constructor() {
            super({
                whitespaceHeuristics: true,
                wordNavigationType: 2 /* WordNavigationType.WordEnd */,
                id: 'deleteWordRight',
                precondition: editorContextKeys_1.EditorContextKeys.writable,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                    primary: 2048 /* KeyMod.CtrlCmd */ | 20 /* KeyCode.Delete */,
                    mac: { primary: 512 /* KeyMod.Alt */ | 20 /* KeyCode.Delete */ },
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
    }
    exports.DeleteWordRight = DeleteWordRight;
    class DeleteInsideWord extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: 'deleteInsideWord',
                precondition: editorContextKeys_1.EditorContextKeys.writable,
                label: nls.localize(1427, "Delete Word"),
                alias: 'Delete Word'
            });
        }
        run(accessor, editor, args) {
            if (!editor.hasModel()) {
                return;
            }
            const wordSeparators = (0, wordCharacterClassifier_1.getMapForWordSeparators)(editor.getOption(132 /* EditorOption.wordSeparators */), editor.getOption(131 /* EditorOption.wordSegmenterLocales */));
            const model = editor.getModel();
            const selections = editor.getSelections();
            const commands = selections.map((sel) => {
                const deleteRange = cursorWordOperations_1.WordOperations.deleteInsideWord(wordSeparators, model, sel);
                return new replaceCommand_1.ReplaceCommand(deleteRange, '');
            });
            editor.pushUndoStop();
            editor.executeCommands(this.id, commands);
            editor.pushUndoStop();
        }
    }
    exports.DeleteInsideWord = DeleteInsideWord;
    (0, editorExtensions_1.registerEditorCommand)(new CursorWordStartLeft());
    (0, editorExtensions_1.registerEditorCommand)(new CursorWordEndLeft());
    (0, editorExtensions_1.registerEditorCommand)(new CursorWordLeft());
    (0, editorExtensions_1.registerEditorCommand)(new CursorWordStartLeftSelect());
    (0, editorExtensions_1.registerEditorCommand)(new CursorWordEndLeftSelect());
    (0, editorExtensions_1.registerEditorCommand)(new CursorWordLeftSelect());
    (0, editorExtensions_1.registerEditorCommand)(new CursorWordStartRight());
    (0, editorExtensions_1.registerEditorCommand)(new CursorWordEndRight());
    (0, editorExtensions_1.registerEditorCommand)(new CursorWordRight());
    (0, editorExtensions_1.registerEditorCommand)(new CursorWordStartRightSelect());
    (0, editorExtensions_1.registerEditorCommand)(new CursorWordEndRightSelect());
    (0, editorExtensions_1.registerEditorCommand)(new CursorWordRightSelect());
    (0, editorExtensions_1.registerEditorCommand)(new CursorWordAccessibilityLeft());
    (0, editorExtensions_1.registerEditorCommand)(new CursorWordAccessibilityLeftSelect());
    (0, editorExtensions_1.registerEditorCommand)(new CursorWordAccessibilityRight());
    (0, editorExtensions_1.registerEditorCommand)(new CursorWordAccessibilityRightSelect());
    (0, editorExtensions_1.registerEditorCommand)(new DeleteWordStartLeft());
    (0, editorExtensions_1.registerEditorCommand)(new DeleteWordEndLeft());
    (0, editorExtensions_1.registerEditorCommand)(new DeleteWordLeft());
    (0, editorExtensions_1.registerEditorCommand)(new DeleteWordStartRight());
    (0, editorExtensions_1.registerEditorCommand)(new DeleteWordEndRight());
    (0, editorExtensions_1.registerEditorCommand)(new DeleteWordRight());
    (0, editorExtensions_1.registerEditorAction)(DeleteInsideWord);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[745/*vs/editor/contrib/wordPartOperations/browser/wordPartOperations*/], __M([1/*require*/,0/*exports*/,15/*vs/editor/browser/editorExtensions*/,199/*vs/editor/common/cursor/cursorWordOperations*/,4/*vs/editor/common/core/range*/,20/*vs/editor/common/editorContextKeys*/,411/*vs/editor/contrib/wordOperations/browser/wordOperations*/,24/*vs/platform/commands/common/commands*/]), function (require, exports, editorExtensions_1, cursorWordOperations_1, range_1, editorContextKeys_1, wordOperations_1, commands_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CursorWordPartRightSelect = exports.CursorWordPartRight = exports.WordPartRightCommand = exports.CursorWordPartLeftSelect = exports.CursorWordPartLeft = exports.WordPartLeftCommand = exports.DeleteWordPartRight = exports.DeleteWordPartLeft = void 0;
    class DeleteWordPartLeft extends wordOperations_1.DeleteWordCommand {
        constructor() {
            super({
                whitespaceHeuristics: true,
                wordNavigationType: 0 /* WordNavigationType.WordStart */,
                id: 'deleteWordPartLeft',
                precondition: editorContextKeys_1.EditorContextKeys.writable,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                    primary: 0,
                    mac: { primary: 256 /* KeyMod.WinCtrl */ | 512 /* KeyMod.Alt */ | 1 /* KeyCode.Backspace */ },
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
        _delete(ctx, wordNavigationType) {
            const r = cursorWordOperations_1.WordPartOperations.deleteWordPartLeft(ctx);
            if (r) {
                return r;
            }
            return new range_1.Range(1, 1, 1, 1);
        }
    }
    exports.DeleteWordPartLeft = DeleteWordPartLeft;
    class DeleteWordPartRight extends wordOperations_1.DeleteWordCommand {
        constructor() {
            super({
                whitespaceHeuristics: true,
                wordNavigationType: 2 /* WordNavigationType.WordEnd */,
                id: 'deleteWordPartRight',
                precondition: editorContextKeys_1.EditorContextKeys.writable,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                    primary: 0,
                    mac: { primary: 256 /* KeyMod.WinCtrl */ | 512 /* KeyMod.Alt */ | 20 /* KeyCode.Delete */ },
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
        _delete(ctx, wordNavigationType) {
            const r = cursorWordOperations_1.WordPartOperations.deleteWordPartRight(ctx);
            if (r) {
                return r;
            }
            const lineCount = ctx.model.getLineCount();
            const maxColumn = ctx.model.getLineMaxColumn(lineCount);
            return new range_1.Range(lineCount, maxColumn, lineCount, maxColumn);
        }
    }
    exports.DeleteWordPartRight = DeleteWordPartRight;
    class WordPartLeftCommand extends wordOperations_1.MoveWordCommand {
        _move(wordSeparators, model, position, wordNavigationType, hasMulticursor) {
            return cursorWordOperations_1.WordPartOperations.moveWordPartLeft(wordSeparators, model, position, hasMulticursor);
        }
    }
    exports.WordPartLeftCommand = WordPartLeftCommand;
    class CursorWordPartLeft extends WordPartLeftCommand {
        constructor() {
            super({
                inSelectionMode: false,
                wordNavigationType: 0 /* WordNavigationType.WordStart */,
                id: 'cursorWordPartLeft',
                precondition: undefined,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                    primary: 0,
                    mac: { primary: 256 /* KeyMod.WinCtrl */ | 512 /* KeyMod.Alt */ | 15 /* KeyCode.LeftArrow */ },
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
    }
    exports.CursorWordPartLeft = CursorWordPartLeft;
    // Register previous id for compatibility purposes
    commands_1.CommandsRegistry.registerCommandAlias('cursorWordPartStartLeft', 'cursorWordPartLeft');
    class CursorWordPartLeftSelect extends WordPartLeftCommand {
        constructor() {
            super({
                inSelectionMode: true,
                wordNavigationType: 0 /* WordNavigationType.WordStart */,
                id: 'cursorWordPartLeftSelect',
                precondition: undefined,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                    primary: 0,
                    mac: { primary: 256 /* KeyMod.WinCtrl */ | 512 /* KeyMod.Alt */ | 1024 /* KeyMod.Shift */ | 15 /* KeyCode.LeftArrow */ },
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
    }
    exports.CursorWordPartLeftSelect = CursorWordPartLeftSelect;
    // Register previous id for compatibility purposes
    commands_1.CommandsRegistry.registerCommandAlias('cursorWordPartStartLeftSelect', 'cursorWordPartLeftSelect');
    class WordPartRightCommand extends wordOperations_1.MoveWordCommand {
        _move(wordSeparators, model, position, wordNavigationType, hasMulticursor) {
            return cursorWordOperations_1.WordPartOperations.moveWordPartRight(wordSeparators, model, position);
        }
    }
    exports.WordPartRightCommand = WordPartRightCommand;
    class CursorWordPartRight extends WordPartRightCommand {
        constructor() {
            super({
                inSelectionMode: false,
                wordNavigationType: 2 /* WordNavigationType.WordEnd */,
                id: 'cursorWordPartRight',
                precondition: undefined,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                    primary: 0,
                    mac: { primary: 256 /* KeyMod.WinCtrl */ | 512 /* KeyMod.Alt */ | 17 /* KeyCode.RightArrow */ },
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
    }
    exports.CursorWordPartRight = CursorWordPartRight;
    class CursorWordPartRightSelect extends WordPartRightCommand {
        constructor() {
            super({
                inSelectionMode: true,
                wordNavigationType: 2 /* WordNavigationType.WordEnd */,
                id: 'cursorWordPartRightSelect',
                precondition: undefined,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                    primary: 0,
                    mac: { primary: 256 /* KeyMod.WinCtrl */ | 512 /* KeyMod.Alt */ | 1024 /* KeyMod.Shift */ | 17 /* KeyCode.RightArrow */ },
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
    }
    exports.CursorWordPartRightSelect = CursorWordPartRightSelect;
    (0, editorExtensions_1.registerEditorCommand)(new DeleteWordPartLeft());
    (0, editorExtensions_1.registerEditorCommand)(new DeleteWordPartRight());
    (0, editorExtensions_1.registerEditorCommand)(new CursorWordPartLeft());
    (0, editorExtensions_1.registerEditorCommand)(new CursorWordPartLeftSelect());
    (0, editorExtensions_1.registerEditorCommand)(new CursorWordPartRight());
    (0, editorExtensions_1.registerEditorCommand)(new CursorWordPartRightSelect());
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[746/*vs/editor/standalone/browser/iPadShowKeyboard/iPadShowKeyboard*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,2/*vs/base/common/lifecycle*/,15/*vs/editor/browser/editorExtensions*/,16/*vs/base/common/platform*/,538/*vs/css!vs/editor/standalone/browser/iPadShowKeyboard/iPadShowKeyboard*/]), function (require, exports, dom, lifecycle_1, editorExtensions_1, platform_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.IPadShowKeyboard = void 0;
    class IPadShowKeyboard extends lifecycle_1.Disposable {
        static { this.ID = 'editor.contrib.iPadShowKeyboard'; }
        constructor(editor) {
            super();
            this.editor = editor;
            this.widget = null;
            if (platform_1.isIOS) {
                this._register(editor.onDidChangeConfiguration(() => this.update()));
                this.update();
            }
        }
        update() {
            const shouldHaveWidget = (!this.editor.getOption(92 /* EditorOption.readOnly */));
            if (!this.widget && shouldHaveWidget) {
                this.widget = new ShowKeyboardWidget(this.editor);
            }
            else if (this.widget && !shouldHaveWidget) {
                this.widget.dispose();
                this.widget = null;
            }
        }
        dispose() {
            super.dispose();
            if (this.widget) {
                this.widget.dispose();
                this.widget = null;
            }
        }
    }
    exports.IPadShowKeyboard = IPadShowKeyboard;
    class ShowKeyboardWidget extends lifecycle_1.Disposable {
        static { this.ID = 'editor.contrib.ShowKeyboardWidget'; }
        constructor(editor) {
            super();
            this.editor = editor;
            this._domNode = document.createElement('textarea');
            this._domNode.className = 'iPadShowKeyboard';
            this._register(dom.addDisposableListener(this._domNode, 'touchstart', (e) => {
                this.editor.focus();
            }));
            this._register(dom.addDisposableListener(this._domNode, 'focus', (e) => {
                this.editor.focus();
            }));
            this.editor.addOverlayWidget(this);
        }
        dispose() {
            this.editor.removeOverlayWidget(this);
            super.dispose();
        }
        // ----- IOverlayWidget API
        getId() {
            return ShowKeyboardWidget.ID;
        }
        getDomNode() {
            return this._domNode;
        }
        getPosition() {
            return {
                preference: 1 /* OverlayWidgetPositionPreference.BOTTOM_RIGHT_CORNER */
            };
        }
    }
    (0, editorExtensions_1.registerEditorContribution)(IPadShowKeyboard.ID, IPadShowKeyboard, 3 /* EditorContributionInstantiation.Eventually */);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[747/*vs/editor/standalone/browser/inspectTokens/inspectTokens*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,33/*vs/base/common/color*/,2/*vs/base/common/lifecycle*/,15/*vs/editor/browser/editorExtensions*/,27/*vs/editor/common/languages*/,148/*vs/editor/common/encodedTokenAttributes*/,177/*vs/editor/common/languages/nullTokenize*/,43/*vs/editor/common/languages/language*/,153/*vs/editor/standalone/common/standaloneTheme*/,107/*vs/editor/common/standaloneStrings*/,539/*vs/css!vs/editor/standalone/browser/inspectTokens/inspectTokens*/]), function (require, exports, dom_1, color_1, lifecycle_1, editorExtensions_1, languages_1, encodedTokenAttributes_1, nullTokenize_1, language_1, standaloneTheme_1, standaloneStrings_1) {
    "use strict";
    var InspectTokensController_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    let InspectTokensController = class InspectTokensController extends lifecycle_1.Disposable {
        static { InspectTokensController_1 = this; }
        static { this.ID = 'editor.contrib.inspectTokens'; }
        static get(editor) {
            return editor.getContribution(InspectTokensController_1.ID);
        }
        constructor(editor, standaloneColorService, languageService) {
            super();
            this._editor = editor;
            this._languageService = languageService;
            this._widget = null;
            this._register(this._editor.onDidChangeModel((e) => this.stop()));
            this._register(this._editor.onDidChangeModelLanguage((e) => this.stop()));
            this._register(languages_1.TokenizationRegistry.onDidChange((e) => this.stop()));
            this._register(this._editor.onKeyUp((e) => e.keyCode === 9 /* KeyCode.Escape */ && this.stop()));
        }
        dispose() {
            this.stop();
            super.dispose();
        }
        launch() {
            if (this._widget) {
                return;
            }
            if (!this._editor.hasModel()) {
                return;
            }
            this._widget = new InspectTokensWidget(this._editor, this._languageService);
        }
        stop() {
            if (this._widget) {
                this._widget.dispose();
                this._widget = null;
            }
        }
    };
    InspectTokensController = InspectTokensController_1 = __decorate([
        __param(1, standaloneTheme_1.IStandaloneThemeService),
        __param(2, language_1.ILanguageService)
    ], InspectTokensController);
    class InspectTokens extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: 'editor.action.inspectTokens',
                label: standaloneStrings_1.InspectTokensNLS.inspectTokensAction,
                alias: 'Developer: Inspect Tokens',
                precondition: undefined
            });
        }
        run(accessor, editor) {
            const controller = InspectTokensController.get(editor);
            controller?.launch();
        }
    }
    function renderTokenText(tokenText) {
        let result = '';
        for (let charIndex = 0, len = tokenText.length; charIndex < len; charIndex++) {
            const charCode = tokenText.charCodeAt(charIndex);
            switch (charCode) {
                case 9 /* CharCode.Tab */:
                    result += '\u2192'; // &rarr;
                    break;
                case 32 /* CharCode.Space */:
                    result += '\u00B7'; // &middot;
                    break;
                default:
                    result += String.fromCharCode(charCode);
            }
        }
        return result;
    }
    function getSafeTokenizationSupport(languageIdCodec, languageId) {
        const tokenizationSupport = languages_1.TokenizationRegistry.get(languageId);
        if (tokenizationSupport) {
            return tokenizationSupport;
        }
        const encodedLanguageId = languageIdCodec.encodeLanguageId(languageId);
        return {
            getInitialState: () => nullTokenize_1.NullState,
            tokenize: (line, hasEOL, state) => (0, nullTokenize_1.nullTokenize)(languageId, state),
            tokenizeEncoded: (line, hasEOL, state) => (0, nullTokenize_1.nullTokenizeEncoded)(encodedLanguageId, state)
        };
    }
    class InspectTokensWidget extends lifecycle_1.Disposable {
        static { this._ID = 'editor.contrib.inspectTokensWidget'; }
        constructor(editor, languageService) {
            super();
            // Editor.IContentWidget.allowEditorOverflow
            this.allowEditorOverflow = true;
            this._editor = editor;
            this._languageService = languageService;
            this._model = this._editor.getModel();
            this._domNode = document.createElement('div');
            this._domNode.className = 'tokens-inspect-widget';
            this._tokenizationSupport = getSafeTokenizationSupport(this._languageService.languageIdCodec, this._model.getLanguageId());
            this._compute(this._editor.getPosition());
            this._register(this._editor.onDidChangeCursorPosition((e) => this._compute(this._editor.getPosition())));
            this._editor.addContentWidget(this);
        }
        dispose() {
            this._editor.removeContentWidget(this);
            super.dispose();
        }
        getId() {
            return InspectTokensWidget._ID;
        }
        _compute(position) {
            const data = this._getTokensAtLine(position.lineNumber);
            let token1Index = 0;
            for (let i = data.tokens1.length - 1; i >= 0; i--) {
                const t = data.tokens1[i];
                if (position.column - 1 >= t.offset) {
                    token1Index = i;
                    break;
                }
            }
            let token2Index = 0;
            for (let i = (data.tokens2.length >>> 1); i >= 0; i--) {
                if (position.column - 1 >= data.tokens2[(i << 1)]) {
                    token2Index = i;
                    break;
                }
            }
            const lineContent = this._model.getLineContent(position.lineNumber);
            let tokenText = '';
            if (token1Index < data.tokens1.length) {
                const tokenStartIndex = data.tokens1[token1Index].offset;
                const tokenEndIndex = token1Index + 1 < data.tokens1.length ? data.tokens1[token1Index + 1].offset : lineContent.length;
                tokenText = lineContent.substring(tokenStartIndex, tokenEndIndex);
            }
            (0, dom_1.reset)(this._domNode, (0, dom_1.$)('h2.tm-token', undefined, renderTokenText(tokenText), (0, dom_1.$)('span.tm-token-length', undefined, `${tokenText.length} ${tokenText.length === 1 ? 'char' : 'chars'}`)));
            (0, dom_1.append)(this._domNode, (0, dom_1.$)('hr.tokens-inspect-separator', { 'style': 'clear:both' }));
            const metadata = (token2Index << 1) + 1 < data.tokens2.length ? this._decodeMetadata(data.tokens2[(token2Index << 1) + 1]) : null;
            (0, dom_1.append)(this._domNode, (0, dom_1.$)('table.tm-metadata-table', undefined, (0, dom_1.$)('tbody', undefined, (0, dom_1.$)('tr', undefined, (0, dom_1.$)('td.tm-metadata-key', undefined, 'language'), (0, dom_1.$)('td.tm-metadata-value', undefined, `${metadata ? metadata.languageId : '-?-'}`)), (0, dom_1.$)('tr', undefined, (0, dom_1.$)('td.tm-metadata-key', undefined, 'token type'), (0, dom_1.$)('td.tm-metadata-value', undefined, `${metadata ? this._tokenTypeToString(metadata.tokenType) : '-?-'}`)), (0, dom_1.$)('tr', undefined, (0, dom_1.$)('td.tm-metadata-key', undefined, 'font style'), (0, dom_1.$)('td.tm-metadata-value', undefined, `${metadata ? this._fontStyleToString(metadata.fontStyle) : '-?-'}`)), (0, dom_1.$)('tr', undefined, (0, dom_1.$)('td.tm-metadata-key', undefined, 'foreground'), (0, dom_1.$)('td.tm-metadata-value', undefined, `${metadata ? color_1.Color.Format.CSS.formatHex(metadata.foreground) : '-?-'}`)), (0, dom_1.$)('tr', undefined, (0, dom_1.$)('td.tm-metadata-key', undefined, 'background'), (0, dom_1.$)('td.tm-metadata-value', undefined, `${metadata ? color_1.Color.Format.CSS.formatHex(metadata.background) : '-?-'}`)))));
            (0, dom_1.append)(this._domNode, (0, dom_1.$)('hr.tokens-inspect-separator'));
            if (token1Index < data.tokens1.length) {
                (0, dom_1.append)(this._domNode, (0, dom_1.$)('span.tm-token-type', undefined, data.tokens1[token1Index].type));
            }
            this._editor.layoutContentWidget(this);
        }
        _decodeMetadata(metadata) {
            const colorMap = languages_1.TokenizationRegistry.getColorMap();
            const languageId = encodedTokenAttributes_1.TokenMetadata.getLanguageId(metadata);
            const tokenType = encodedTokenAttributes_1.TokenMetadata.getTokenType(metadata);
            const fontStyle = encodedTokenAttributes_1.TokenMetadata.getFontStyle(metadata);
            const foreground = encodedTokenAttributes_1.TokenMetadata.getForeground(metadata);
            const background = encodedTokenAttributes_1.TokenMetadata.getBackground(metadata);
            return {
                languageId: this._languageService.languageIdCodec.decodeLanguageId(languageId),
                tokenType: tokenType,
                fontStyle: fontStyle,
                foreground: colorMap[foreground],
                background: colorMap[background]
            };
        }
        _tokenTypeToString(tokenType) {
            switch (tokenType) {
                case 0 /* StandardTokenType.Other */: return 'Other';
                case 1 /* StandardTokenType.Comment */: return 'Comment';
                case 2 /* StandardTokenType.String */: return 'String';
                case 3 /* StandardTokenType.RegEx */: return 'RegEx';
                default: return '??';
            }
        }
        _fontStyleToString(fontStyle) {
            let r = '';
            if (fontStyle & 1 /* FontStyle.Italic */) {
                r += 'italic ';
            }
            if (fontStyle & 2 /* FontStyle.Bold */) {
                r += 'bold ';
            }
            if (fontStyle & 4 /* FontStyle.Underline */) {
                r += 'underline ';
            }
            if (fontStyle & 8 /* FontStyle.Strikethrough */) {
                r += 'strikethrough ';
            }
            if (r.length === 0) {
                r = '---';
            }
            return r;
        }
        _getTokensAtLine(lineNumber) {
            const stateBeforeLine = this._getStateBeforeLine(lineNumber);
            const tokenizationResult1 = this._tokenizationSupport.tokenize(this._model.getLineContent(lineNumber), true, stateBeforeLine);
            const tokenizationResult2 = this._tokenizationSupport.tokenizeEncoded(this._model.getLineContent(lineNumber), true, stateBeforeLine);
            return {
                startState: stateBeforeLine,
                tokens1: tokenizationResult1.tokens,
                tokens2: tokenizationResult2.tokens,
                endState: tokenizationResult1.endState
            };
        }
        _getStateBeforeLine(lineNumber) {
            let state = this._tokenizationSupport.getInitialState();
            for (let i = 1; i < lineNumber; i++) {
                const tokenizationResult = this._tokenizationSupport.tokenize(this._model.getLineContent(i), true, state);
                state = tokenizationResult.endState;
            }
            return state;
        }
        getDomNode() {
            return this._domNode;
        }
        getPosition() {
            return {
                position: this._editor.getPosition(),
                preference: [2 /* ContentWidgetPositionPreference.BELOW */, 1 /* ContentWidgetPositionPreference.ABOVE */]
            };
        }
    }
    (0, editorExtensions_1.registerEditorContribution)(InspectTokensController.ID, InspectTokensController, 4 /* EditorContributionInstantiation.Lazy */);
    (0, editorExtensions_1.registerEditorAction)(InspectTokens);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[748/*vs/platform/quickinput/browser/commandsQuickAccess*/], __M([1/*require*/,0/*exports*/,346/*vs/base/common/errorMessage*/,8/*vs/base/common/errors*/,82/*vs/base/common/filters*/,127/*vs/base/common/functional*/,2/*vs/base/common/lifecycle*/,45/*vs/base/common/map*/,456/*vs/base/common/tfIdf*/,3/*vs/nls*/,24/*vs/platform/commands/common/commands*/,28/*vs/platform/configuration/common/configuration*/,180/*vs/platform/dialogs/common/dialogs*/,7/*vs/platform/instantiation/common/instantiation*/,31/*vs/platform/keybinding/common/keybinding*/,62/*vs/platform/log/common/log*/,703/*vs/platform/quickinput/browser/pickerQuickAccess*/,101/*vs/platform/storage/common/storage*/,63/*vs/platform/telemetry/common/telemetry*/]), function (require, exports, errorMessage_1, errors_1, filters_1, functional_1, lifecycle_1, map_1, tfIdf_1, nls_1, commands_1, configuration_1, dialogs_1, instantiation_1, keybinding_1, log_1, pickerQuickAccess_1, storage_1, telemetry_1) {
    "use strict";
    var AbstractCommandsQuickAccessProvider_1, CommandsHistory_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CommandsHistory = exports.AbstractCommandsQuickAccessProvider = void 0;
    let AbstractCommandsQuickAccessProvider = class AbstractCommandsQuickAccessProvider extends pickerQuickAccess_1.PickerQuickAccessProvider {
        static { AbstractCommandsQuickAccessProvider_1 = this; }
        static { this.PREFIX = '>'; }
        static { this.TFIDF_THRESHOLD = 0.5; }
        static { this.TFIDF_MAX_RESULTS = 5; }
        static { this.WORD_FILTER = (0, filters_1.or)(filters_1.matchesPrefix, filters_1.matchesWords, filters_1.matchesContiguousSubString); }
        constructor(options, instantiationService, keybindingService, commandService, telemetryService, dialogService) {
            super(AbstractCommandsQuickAccessProvider_1.PREFIX, options);
            this.instantiationService = instantiationService;
            this.keybindingService = keybindingService;
            this.commandService = commandService;
            this.telemetryService = telemetryService;
            this.dialogService = dialogService;
            this.commandsHistory = this._register(this.instantiationService.createInstance(CommandsHistory));
            this.options = options;
        }
        async _getPicks(filter, _disposables, token, runOptions) {
            // Ask subclass for all command picks
            const allCommandPicks = await this.getCommandPicks(token);
            if (token.isCancellationRequested) {
                return [];
            }
            const runTfidf = (0, functional_1.createSingleCallFunction)(() => {
                const tfidf = new tfIdf_1.TfIdfCalculator();
                tfidf.updateDocuments(allCommandPicks.map(commandPick => ({
                    key: commandPick.commandId,
                    textChunks: [this.getTfIdfChunk(commandPick)]
                })));
                const result = tfidf.calculateScores(filter, token);
                return (0, tfIdf_1.normalizeTfIdfScores)(result)
                    .filter(score => score.score > AbstractCommandsQuickAccessProvider_1.TFIDF_THRESHOLD)
                    .slice(0, AbstractCommandsQuickAccessProvider_1.TFIDF_MAX_RESULTS);
            });
            // Filter
            const filteredCommandPicks = [];
            for (const commandPick of allCommandPicks) {
                const labelHighlights = AbstractCommandsQuickAccessProvider_1.WORD_FILTER(filter, commandPick.label) ?? undefined;
                const aliasHighlights = commandPick.commandAlias ? AbstractCommandsQuickAccessProvider_1.WORD_FILTER(filter, commandPick.commandAlias) ?? undefined : undefined;
                // Add if matching in label or alias
                if (labelHighlights || aliasHighlights) {
                    commandPick.highlights = {
                        label: labelHighlights,
                        detail: this.options.showAlias ? aliasHighlights : undefined
                    };
                    filteredCommandPicks.push(commandPick);
                }
                // Also add if we have a 100% command ID match
                else if (filter === commandPick.commandId) {
                    filteredCommandPicks.push(commandPick);
                }
                // Handle tf-idf scoring for the rest if there's a filter
                else if (filter.length >= 3) {
                    const tfidf = runTfidf();
                    if (token.isCancellationRequested) {
                        return [];
                    }
                    // Add if we have a tf-idf score
                    const tfidfScore = tfidf.find(score => score.key === commandPick.commandId);
                    if (tfidfScore) {
                        commandPick.tfIdfScore = tfidfScore.score;
                        filteredCommandPicks.push(commandPick);
                    }
                }
            }
            // Add description to commands that have duplicate labels
            const mapLabelToCommand = new Map();
            for (const commandPick of filteredCommandPicks) {
                const existingCommandForLabel = mapLabelToCommand.get(commandPick.label);
                if (existingCommandForLabel) {
                    commandPick.description = commandPick.commandId;
                    existingCommandForLabel.description = existingCommandForLabel.commandId;
                }
                else {
                    mapLabelToCommand.set(commandPick.label, commandPick);
                }
            }
            // Sort by MRU order and fallback to name otherwise
            filteredCommandPicks.sort((commandPickA, commandPickB) => {
                // If a result came from tf-idf, we want to put that towards the bottom
                if (commandPickA.tfIdfScore && commandPickB.tfIdfScore) {
                    if (commandPickA.tfIdfScore === commandPickB.tfIdfScore) {
                        return commandPickA.label.localeCompare(commandPickB.label); // prefer lexicographically smaller command
                    }
                    return commandPickB.tfIdfScore - commandPickA.tfIdfScore; // prefer higher tf-idf score
                }
                else if (commandPickA.tfIdfScore) {
                    return 1; // first command has a score but other doesn't so other wins
                }
                else if (commandPickB.tfIdfScore) {
                    return -1; // other command has a score but first doesn't so first wins
                }
                const commandACounter = this.commandsHistory.peek(commandPickA.commandId);
                const commandBCounter = this.commandsHistory.peek(commandPickB.commandId);
                if (commandACounter && commandBCounter) {
                    return commandACounter > commandBCounter ? -1 : 1; // use more recently used command before older
                }
                if (commandACounter) {
                    return -1; // first command was used, so it wins over the non used one
                }
                if (commandBCounter) {
                    return 1; // other command was used so it wins over the command
                }
                if (this.options.suggestedCommandIds) {
                    const commandASuggestion = this.options.suggestedCommandIds.has(commandPickA.commandId);
                    const commandBSuggestion = this.options.suggestedCommandIds.has(commandPickB.commandId);
                    if (commandASuggestion && commandBSuggestion) {
                        return 0; // honor the order of the array
                    }
                    if (commandASuggestion) {
                        return -1; // first command was suggested, so it wins over the non suggested one
                    }
                    if (commandBSuggestion) {
                        return 1; // other command was suggested so it wins over the command
                    }
                }
                // both commands were never used, so we sort by name
                return commandPickA.label.localeCompare(commandPickB.label);
            });
            const commandPicks = [];
            let addOtherSeparator = false;
            let addSuggestedSeparator = true;
            let addCommonlyUsedSeparator = !!this.options.suggestedCommandIds;
            for (let i = 0; i < filteredCommandPicks.length; i++) {
                const commandPick = filteredCommandPicks[i];
                // Separator: recently used
                if (i === 0 && this.commandsHistory.peek(commandPick.commandId)) {
                    commandPicks.push({ type: 'separator', label: (0, nls_1.localize)(1572, "recently used") });
                    addOtherSeparator = true;
                }
                if (addSuggestedSeparator && commandPick.tfIdfScore !== undefined) {
                    commandPicks.push({ type: 'separator', label: (0, nls_1.localize)(1573, "similar commands") });
                    addSuggestedSeparator = false;
                }
                // Separator: commonly used
                if (addCommonlyUsedSeparator && commandPick.tfIdfScore === undefined && !this.commandsHistory.peek(commandPick.commandId) && this.options.suggestedCommandIds?.has(commandPick.commandId)) {
                    commandPicks.push({ type: 'separator', label: (0, nls_1.localize)(1574, "commonly used") });
                    addOtherSeparator = true;
                    addCommonlyUsedSeparator = false;
                }
                // Separator: other commands
                if (addOtherSeparator && commandPick.tfIdfScore === undefined && !this.commandsHistory.peek(commandPick.commandId) && !this.options.suggestedCommandIds?.has(commandPick.commandId)) {
                    commandPicks.push({ type: 'separator', label: (0, nls_1.localize)(1575, "other commands") });
                    addOtherSeparator = false;
                }
                // Command
                commandPicks.push(this.toCommandPick(commandPick, runOptions));
            }
            if (!this.hasAdditionalCommandPicks(filter, token)) {
                return commandPicks;
            }
            return {
                picks: commandPicks,
                additionalPicks: (async () => {
                    const additionalCommandPicks = await this.getAdditionalCommandPicks(allCommandPicks, filteredCommandPicks, filter, token);
                    if (token.isCancellationRequested) {
                        return [];
                    }
                    const commandPicks = additionalCommandPicks.map(commandPick => this.toCommandPick(commandPick, runOptions));
                    // Basically, if we haven't already added a separator, we add one before the additional picks so long
                    // as one hasn't been added to the start of the array.
                    if (addSuggestedSeparator && commandPicks[0]?.type !== 'separator') {
                        commandPicks.unshift({ type: 'separator', label: (0, nls_1.localize)(1576, "similar commands") });
                    }
                    return commandPicks;
                })()
            };
        }
        toCommandPick(commandPick, runOptions) {
            if (commandPick.type === 'separator') {
                return commandPick;
            }
            const keybinding = this.keybindingService.lookupKeybinding(commandPick.commandId);
            const ariaLabel = keybinding ?
                (0, nls_1.localize)(1577, "{0}, {1}", commandPick.label, keybinding.getAriaLabel()) :
                commandPick.label;
            return {
                ...commandPick,
                ariaLabel,
                detail: this.options.showAlias && commandPick.commandAlias !== commandPick.label ? commandPick.commandAlias : undefined,
                keybinding,
                accept: async () => {
                    // Add to history
                    this.commandsHistory.push(commandPick.commandId);
                    // Telementry
                    this.telemetryService.publicLog2('workbenchActionExecuted', {
                        id: commandPick.commandId,
                        from: runOptions?.from ?? 'quick open'
                    });
                    // Run
                    try {
                        commandPick.args?.length
                            ? await this.commandService.executeCommand(commandPick.commandId, ...commandPick.args)
                            : await this.commandService.executeCommand(commandPick.commandId);
                    }
                    catch (error) {
                        if (!(0, errors_1.isCancellationError)(error)) {
                            this.dialogService.error((0, nls_1.localize)(1578, "Command '{0}' resulted in an error", commandPick.label), (0, errorMessage_1.toErrorMessage)(error));
                        }
                    }
                }
            };
        }
        // TF-IDF string to be indexed
        getTfIdfChunk({ label, commandAlias, commandDescription }) {
            let chunk = label;
            if (commandAlias && commandAlias !== label) {
                chunk += ` - ${commandAlias}`;
            }
            if (commandDescription && commandDescription.value !== label) {
                // If the original is the same as the value, don't add it
                chunk += ` - ${commandDescription.value === commandDescription.original ? commandDescription.value : `${commandDescription.value} (${commandDescription.original})`}`;
            }
            return chunk;
        }
    };
    exports.AbstractCommandsQuickAccessProvider = AbstractCommandsQuickAccessProvider;
    exports.AbstractCommandsQuickAccessProvider = AbstractCommandsQuickAccessProvider = AbstractCommandsQuickAccessProvider_1 = __decorate([
        __param(1, instantiation_1.IInstantiationService),
        __param(2, keybinding_1.IKeybindingService),
        __param(3, commands_1.ICommandService),
        __param(4, telemetry_1.ITelemetryService),
        __param(5, dialogs_1.IDialogService)
    ], AbstractCommandsQuickAccessProvider);
    let CommandsHistory = class CommandsHistory extends lifecycle_1.Disposable {
        static { CommandsHistory_1 = this; }
        static { this.DEFAULT_COMMANDS_HISTORY_LENGTH = 50; }
        static { this.PREF_KEY_CACHE = 'commandPalette.mru.cache'; }
        static { this.PREF_KEY_COUNTER = 'commandPalette.mru.counter'; }
        static { this.counter = 1; }
        static { this.hasChanges = false; }
        constructor(storageService, configurationService, logService) {
            super();
            this.storageService = storageService;
            this.configurationService = configurationService;
            this.logService = logService;
            this.configuredCommandsHistoryLength = 0;
            this.updateConfiguration();
            this.load();
            this.registerListeners();
        }
        registerListeners() {
            this._register(this.configurationService.onDidChangeConfiguration(e => this.updateConfiguration(e)));
            this._register(this.storageService.onWillSaveState(e => {
                if (e.reason === storage_1.WillSaveStateReason.SHUTDOWN) {
                    // Commands history is very dynamic and so we limit impact
                    // on storage to only save on shutdown. This helps reduce
                    // the overhead of syncing this data across machines.
                    this.saveState();
                }
            }));
        }
        updateConfiguration(e) {
            if (e && !e.affectsConfiguration('workbench.commandPalette.history')) {
                return;
            }
            this.configuredCommandsHistoryLength = CommandsHistory_1.getConfiguredCommandHistoryLength(this.configurationService);
            if (CommandsHistory_1.cache && CommandsHistory_1.cache.limit !== this.configuredCommandsHistoryLength) {
                CommandsHistory_1.cache.limit = this.configuredCommandsHistoryLength;
                CommandsHistory_1.hasChanges = true;
            }
        }
        load() {
            const raw = this.storageService.get(CommandsHistory_1.PREF_KEY_CACHE, 0 /* StorageScope.PROFILE */);
            let serializedCache;
            if (raw) {
                try {
                    serializedCache = JSON.parse(raw);
                }
                catch (error) {
                    this.logService.error(`[CommandsHistory] invalid data: ${error}`);
                }
            }
            const cache = CommandsHistory_1.cache = new map_1.LRUCache(this.configuredCommandsHistoryLength, 1);
            if (serializedCache) {
                let entries;
                if (serializedCache.usesLRU) {
                    entries = serializedCache.entries;
                }
                else {
                    entries = serializedCache.entries.sort((a, b) => a.value - b.value);
                }
                entries.forEach(entry => cache.set(entry.key, entry.value));
            }
            CommandsHistory_1.counter = this.storageService.getNumber(CommandsHistory_1.PREF_KEY_COUNTER, 0 /* StorageScope.PROFILE */, CommandsHistory_1.counter);
        }
        push(commandId) {
            if (!CommandsHistory_1.cache) {
                return;
            }
            CommandsHistory_1.cache.set(commandId, CommandsHistory_1.counter++); // set counter to command
            CommandsHistory_1.hasChanges = true;
        }
        peek(commandId) {
            return CommandsHistory_1.cache?.peek(commandId);
        }
        saveState() {
            if (!CommandsHistory_1.cache) {
                return;
            }
            if (!CommandsHistory_1.hasChanges) {
                return;
            }
            const serializedCache = { usesLRU: true, entries: [] };
            CommandsHistory_1.cache.forEach((value, key) => serializedCache.entries.push({ key, value }));
            this.storageService.store(CommandsHistory_1.PREF_KEY_CACHE, JSON.stringify(serializedCache), 0 /* StorageScope.PROFILE */, 0 /* StorageTarget.USER */);
            this.storageService.store(CommandsHistory_1.PREF_KEY_COUNTER, CommandsHistory_1.counter, 0 /* StorageScope.PROFILE */, 0 /* StorageTarget.USER */);
            CommandsHistory_1.hasChanges = false;
        }
        static getConfiguredCommandHistoryLength(configurationService) {
            const config = configurationService.getValue();
            const configuredCommandHistoryLength = config.workbench?.commandPalette?.history;
            if (typeof configuredCommandHistoryLength === 'number') {
                return configuredCommandHistoryLength;
            }
            return CommandsHistory_1.DEFAULT_COMMANDS_HISTORY_LENGTH;
        }
    };
    exports.CommandsHistory = CommandsHistory;
    exports.CommandsHistory = CommandsHistory = CommandsHistory_1 = __decorate([
        __param(0, storage_1.IStorageService),
        __param(1, configuration_1.IConfigurationService),
        __param(2, log_1.ILogService)
    ], CommandsHistory);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[749/*vs/editor/contrib/quickAccess/browser/commandsQuickAccess*/], __M([1/*require*/,0/*exports*/,142/*vs/base/common/iconLabels*/,381/*vs/platform/action/common/action*/,748/*vs/platform/quickinput/browser/commandsQuickAccess*/]), function (require, exports, iconLabels_1, action_1, commandsQuickAccess_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AbstractEditorCommandsQuickAccessProvider = void 0;
    class AbstractEditorCommandsQuickAccessProvider extends commandsQuickAccess_1.AbstractCommandsQuickAccessProvider {
        constructor(options, instantiationService, keybindingService, commandService, telemetryService, dialogService) {
            super(options, instantiationService, keybindingService, commandService, telemetryService, dialogService);
        }
        getCodeEditorCommandPicks() {
            const activeTextEditorControl = this.activeTextEditorControl;
            if (!activeTextEditorControl) {
                return [];
            }
            const editorCommandPicks = [];
            for (const editorAction of activeTextEditorControl.getSupportedActions()) {
                let commandDescription;
                if (editorAction.metadata?.description) {
                    if ((0, action_1.isLocalizedString)(editorAction.metadata.description)) {
                        commandDescription = editorAction.metadata.description;
                    }
                    else {
                        commandDescription = { original: editorAction.metadata.description, value: editorAction.metadata.description };
                    }
                }
                editorCommandPicks.push({
                    commandId: editorAction.id,
                    commandAlias: editorAction.alias,
                    commandDescription,
                    label: (0, iconLabels_1.stripIcons)(editorAction.label) || editorAction.id,
                });
            }
            return editorCommandPicks;
        }
    }
    exports.AbstractEditorCommandsQuickAccessProvider = AbstractEditorCommandsQuickAccessProvider;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[750/*vs/editor/standalone/browser/quickAccess/standaloneCommandsQuickAccess*/], __M([1/*require*/,0/*exports*/,38/*vs/platform/registry/common/platform*/,156/*vs/platform/quickinput/common/quickAccess*/,107/*vs/editor/common/standaloneStrings*/,34/*vs/editor/browser/services/codeEditorService*/,749/*vs/editor/contrib/quickAccess/browser/commandsQuickAccess*/,7/*vs/platform/instantiation/common/instantiation*/,31/*vs/platform/keybinding/common/keybinding*/,24/*vs/platform/commands/common/commands*/,63/*vs/platform/telemetry/common/telemetry*/,180/*vs/platform/dialogs/common/dialogs*/,15/*vs/editor/browser/editorExtensions*/,20/*vs/editor/common/editorContextKeys*/,66/*vs/platform/quickinput/common/quickInput*/]), function (require, exports, platform_1, quickAccess_1, standaloneStrings_1, codeEditorService_1, commandsQuickAccess_1, instantiation_1, keybinding_1, commands_1, telemetry_1, dialogs_1, editorExtensions_1, editorContextKeys_1, quickInput_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.GotoLineAction = exports.StandaloneCommandsQuickAccessProvider = void 0;
    let StandaloneCommandsQuickAccessProvider = class StandaloneCommandsQuickAccessProvider extends commandsQuickAccess_1.AbstractEditorCommandsQuickAccessProvider {
        get activeTextEditorControl() { return this.codeEditorService.getFocusedCodeEditor() ?? undefined; }
        constructor(instantiationService, codeEditorService, keybindingService, commandService, telemetryService, dialogService) {
            super({ showAlias: false }, instantiationService, keybindingService, commandService, telemetryService, dialogService);
            this.codeEditorService = codeEditorService;
        }
        async getCommandPicks() {
            return this.getCodeEditorCommandPicks();
        }
        hasAdditionalCommandPicks() {
            return false;
        }
        async getAdditionalCommandPicks() {
            return [];
        }
    };
    exports.StandaloneCommandsQuickAccessProvider = StandaloneCommandsQuickAccessProvider;
    exports.StandaloneCommandsQuickAccessProvider = StandaloneCommandsQuickAccessProvider = __decorate([
        __param(0, instantiation_1.IInstantiationService),
        __param(1, codeEditorService_1.ICodeEditorService),
        __param(2, keybinding_1.IKeybindingService),
        __param(3, commands_1.ICommandService),
        __param(4, telemetry_1.ITelemetryService),
        __param(5, dialogs_1.IDialogService)
    ], StandaloneCommandsQuickAccessProvider);
    class GotoLineAction extends editorExtensions_1.EditorAction {
        static { this.ID = 'editor.action.quickCommand'; }
        constructor() {
            super({
                id: GotoLineAction.ID,
                label: standaloneStrings_1.QuickCommandNLS.quickCommandActionLabel,
                alias: 'Command Palette',
                precondition: undefined,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.focus,
                    primary: 59 /* KeyCode.F1 */,
                    weight: 100 /* KeybindingWeight.EditorContrib */
                },
                contextMenuOpts: {
                    group: 'z_commands',
                    order: 1
                }
            });
        }
        run(accessor) {
            accessor.get(quickInput_1.IQuickInputService).quickAccess.show(StandaloneCommandsQuickAccessProvider.PREFIX);
        }
    }
    exports.GotoLineAction = GotoLineAction;
    (0, editorExtensions_1.registerEditorAction)(GotoLineAction);
    platform_1.Registry.as(quickAccess_1.Extensions.Quickaccess).registerQuickAccessProvider({
        ctor: StandaloneCommandsQuickAccessProvider,
        prefix: StandaloneCommandsQuickAccessProvider.PREFIX,
        helpEntries: [{ description: standaloneStrings_1.QuickCommandNLS.quickCommandHelp, commandId: GotoLineAction.ID }]
    });
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[89/*vs/platform/theme/common/colorUtils*/], __M([1/*require*/,0/*exports*/,90/*vs/base/common/assert*/,14/*vs/base/common/async*/,33/*vs/base/common/color*/,6/*vs/base/common/event*/,273/*vs/platform/jsonschemas/common/jsonContributionRegistry*/,38/*vs/platform/registry/common/platform*/,3/*vs/nls*/]), function (require, exports, assert_1, async_1, color_1, event_1, jsonContributionRegistry_1, platform, nls) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.workbenchColorsSchemaId = exports.DEFAULT_COLOR_CONFIG_VALUE = exports.Extensions = void 0;
    exports.asCssVariableName = asCssVariableName;
    exports.asCssVariable = asCssVariable;
    exports.asCssVariableWithDefault = asCssVariableWithDefault;
    exports.isColorDefaults = isColorDefaults;
    exports.registerColor = registerColor;
    exports.executeTransform = executeTransform;
    exports.darken = darken;
    exports.lighten = lighten;
    exports.transparent = transparent;
    exports.oneOf = oneOf;
    exports.ifDefinedThenElse = ifDefinedThenElse;
    exports.lessProminent = lessProminent;
    exports.resolveColorValue = resolveColorValue;
    /**
     * Returns the css variable name for the given color identifier. Dots (`.`) are replaced with hyphens (`-`) and
     * everything is prefixed with `--vscode-`.
     *
     * @sample `editorSuggestWidget.background` is `--vscode-editorSuggestWidget-background`.
     */
    function asCssVariableName(colorIdent) {
        return `--vscode-${colorIdent.replace(/\./g, '-')}`;
    }
    function asCssVariable(color) {
        return `var(${asCssVariableName(color)})`;
    }
    function asCssVariableWithDefault(color, defaultCssValue) {
        return `var(${asCssVariableName(color)}, ${defaultCssValue})`;
    }
    function isColorDefaults(value) {
        return value !== null && typeof value === 'object' && 'light' in value && 'dark' in value;
    }
    // color registry
    exports.Extensions = {
        ColorContribution: 'base.contributions.colors'
    };
    exports.DEFAULT_COLOR_CONFIG_VALUE = 'default';
    class ColorRegistry {
        constructor() {
            this._onDidChangeSchema = new event_1.Emitter();
            this.onDidChangeSchema = this._onDidChangeSchema.event;
            this.colorSchema = { type: 'object', properties: {} };
            this.colorReferenceSchema = { type: 'string', enum: [], enumDescriptions: [] };
            this.colorsById = {};
        }
        registerColor(id, defaults, description, needsTransparency = false, deprecationMessage) {
            const colorContribution = { id, description, defaults, needsTransparency, deprecationMessage };
            this.colorsById[id] = colorContribution;
            const propertySchema = { type: 'string', format: 'color-hex', defaultSnippets: [{ body: '${1:#ff0000}' }] };
            if (deprecationMessage) {
                propertySchema.deprecationMessage = deprecationMessage;
            }
            if (needsTransparency) {
                propertySchema.pattern = '^#(?:(?<rgba>[0-9a-fA-f]{3}[0-9a-eA-E])|(?:[0-9a-fA-F]{6}(?:(?![fF]{2})(?:[0-9a-fA-F]{2}))))?$';
                propertySchema.patternErrorMessage = nls.localize(1836, 'This color must be transparent or it will obscure content');
            }
            this.colorSchema.properties[id] = {
                description,
                oneOf: [
                    propertySchema,
                    { type: 'string', const: exports.DEFAULT_COLOR_CONFIG_VALUE, description: nls.localize(1837, 'Use the default color.') }
                ]
            };
            this.colorReferenceSchema.enum.push(id);
            this.colorReferenceSchema.enumDescriptions.push(description);
            this._onDidChangeSchema.fire();
            return id;
        }
        getColors() {
            return Object.keys(this.colorsById).map(id => this.colorsById[id]);
        }
        resolveDefaultColor(id, theme) {
            const colorDesc = this.colorsById[id];
            if (colorDesc?.defaults) {
                const colorValue = isColorDefaults(colorDesc.defaults) ? colorDesc.defaults[theme.type] : colorDesc.defaults;
                return resolveColorValue(colorValue, theme);
            }
            return undefined;
        }
        getColorSchema() {
            return this.colorSchema;
        }
        toString() {
            const sorter = (a, b) => {
                const cat1 = a.indexOf('.') === -1 ? 0 : 1;
                const cat2 = b.indexOf('.') === -1 ? 0 : 1;
                if (cat1 !== cat2) {
                    return cat1 - cat2;
                }
                return a.localeCompare(b);
            };
            return Object.keys(this.colorsById).sort(sorter).map(k => `- \`${k}\`: ${this.colorsById[k].description}`).join('\n');
        }
    }
    const colorRegistry = new ColorRegistry();
    platform.Registry.add(exports.Extensions.ColorContribution, colorRegistry);
    function registerColor(id, defaults, description, needsTransparency, deprecationMessage) {
        return colorRegistry.registerColor(id, defaults, description, needsTransparency, deprecationMessage);
    }
    // ----- color functions
    function executeTransform(transform, theme) {
        switch (transform.op) {
            case 0 /* ColorTransformType.Darken */:
                return resolveColorValue(transform.value, theme)?.darken(transform.factor);
            case 1 /* ColorTransformType.Lighten */:
                return resolveColorValue(transform.value, theme)?.lighten(transform.factor);
            case 2 /* ColorTransformType.Transparent */:
                return resolveColorValue(transform.value, theme)?.transparent(transform.factor);
            case 3 /* ColorTransformType.Opaque */: {
                const backgroundColor = resolveColorValue(transform.background, theme);
                if (!backgroundColor) {
                    return resolveColorValue(transform.value, theme);
                }
                return resolveColorValue(transform.value, theme)?.makeOpaque(backgroundColor);
            }
            case 4 /* ColorTransformType.OneOf */:
                for (const candidate of transform.values) {
                    const color = resolveColorValue(candidate, theme);
                    if (color) {
                        return color;
                    }
                }
                return undefined;
            case 6 /* ColorTransformType.IfDefinedThenElse */:
                return resolveColorValue(theme.defines(transform.if) ? transform.then : transform.else, theme);
            case 5 /* ColorTransformType.LessProminent */: {
                const from = resolveColorValue(transform.value, theme);
                if (!from) {
                    return undefined;
                }
                const backgroundColor = resolveColorValue(transform.background, theme);
                if (!backgroundColor) {
                    return from.transparent(transform.factor * transform.transparency);
                }
                return from.isDarkerThan(backgroundColor)
                    ? color_1.Color.getLighterColor(from, backgroundColor, transform.factor).transparent(transform.transparency)
                    : color_1.Color.getDarkerColor(from, backgroundColor, transform.factor).transparent(transform.transparency);
            }
            default:
                throw (0, assert_1.assertNever)(transform);
        }
    }
    function darken(colorValue, factor) {
        return { op: 0 /* ColorTransformType.Darken */, value: colorValue, factor };
    }
    function lighten(colorValue, factor) {
        return { op: 1 /* ColorTransformType.Lighten */, value: colorValue, factor };
    }
    function transparent(colorValue, factor) {
        return { op: 2 /* ColorTransformType.Transparent */, value: colorValue, factor };
    }
    function oneOf(...colorValues) {
        return { op: 4 /* ColorTransformType.OneOf */, values: colorValues };
    }
    function ifDefinedThenElse(ifArg, thenArg, elseArg) {
        return { op: 6 /* ColorTransformType.IfDefinedThenElse */, if: ifArg, then: thenArg, else: elseArg };
    }
    function lessProminent(colorValue, backgroundColorValue, factor, transparency) {
        return { op: 5 /* ColorTransformType.LessProminent */, value: colorValue, background: backgroundColorValue, factor, transparency };
    }
    // ----- implementation
    /**
     * @param colorValue Resolve a color value in the context of a theme
     */
    function resolveColorValue(colorValue, theme) {
        if (colorValue === null) {
            return undefined;
        }
        else if (typeof colorValue === 'string') {
            if (colorValue[0] === '#') {
                return color_1.Color.fromHex(colorValue);
            }
            return theme.getColor(colorValue);
        }
        else if (colorValue instanceof color_1.Color) {
            return colorValue;
        }
        else if (typeof colorValue === 'object') {
            return executeTransform(colorValue, theme);
        }
        return undefined;
    }
    exports.workbenchColorsSchemaId = 'vscode://schemas/workbench-colors';
    const schemaRegistry = platform.Registry.as(jsonContributionRegistry_1.Extensions.JSONContribution);
    schemaRegistry.registerSchema(exports.workbenchColorsSchemaId, colorRegistry.getColorSchema());
    const delayer = new async_1.RunOnceScheduler(() => schemaRegistry.notifySchemaChanged(exports.workbenchColorsSchemaId), 200);
    colorRegistry.onDidChangeSchema(() => {
        if (!delayer.isScheduled()) {
            delayer.schedule();
        }
    });
});
// setTimeout(_ => console.log(colorRegistry.toString()), 5000);

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[123/*vs/platform/theme/common/colors/baseColors*/], __M([1/*require*/,0/*exports*/,3/*vs/nls*/,33/*vs/base/common/color*/,89/*vs/platform/theme/common/colorUtils*/]), function (require, exports, nls, color_1, colorUtils_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.textCodeBlockBackground = exports.textBlockQuoteBorder = exports.textBlockQuoteBackground = exports.textPreformatBackground = exports.textPreformatForeground = exports.textSeparatorForeground = exports.textLinkActiveForeground = exports.textLinkForeground = exports.selectionBackground = exports.activeContrastBorder = exports.contrastBorder = exports.focusBorder = exports.iconForeground = exports.descriptionForeground = exports.errorForeground = exports.disabledForeground = exports.foreground = void 0;
    exports.foreground = (0, colorUtils_1.registerColor)('foreground', { dark: '#CCCCCC', light: '#616161', hcDark: '#FFFFFF', hcLight: '#292929' }, nls.localize(1599, "Overall foreground color. This color is only used if not overridden by a component."));
    exports.disabledForeground = (0, colorUtils_1.registerColor)('disabledForeground', { dark: '#CCCCCC80', light: '#61616180', hcDark: '#A5A5A5', hcLight: '#7F7F7F' }, nls.localize(1600, "Overall foreground for disabled elements. This color is only used if not overridden by a component."));
    exports.errorForeground = (0, colorUtils_1.registerColor)('errorForeground', { dark: '#F48771', light: '#A1260D', hcDark: '#F48771', hcLight: '#B5200D' }, nls.localize(1601, "Overall foreground color for error messages. This color is only used if not overridden by a component."));
    exports.descriptionForeground = (0, colorUtils_1.registerColor)('descriptionForeground', { light: '#717171', dark: (0, colorUtils_1.transparent)(exports.foreground, 0.7), hcDark: (0, colorUtils_1.transparent)(exports.foreground, 0.7), hcLight: (0, colorUtils_1.transparent)(exports.foreground, 0.7) }, nls.localize(1602, "Foreground color for description text providing additional information, for example for a label."));
    exports.iconForeground = (0, colorUtils_1.registerColor)('icon.foreground', { dark: '#C5C5C5', light: '#424242', hcDark: '#FFFFFF', hcLight: '#292929' }, nls.localize(1603, "The default color for icons in the workbench."));
    exports.focusBorder = (0, colorUtils_1.registerColor)('focusBorder', { dark: '#007FD4', light: '#0090F1', hcDark: '#F38518', hcLight: '#006BBD' }, nls.localize(1604, "Overall border color for focused elements. This color is only used if not overridden by a component."));
    exports.contrastBorder = (0, colorUtils_1.registerColor)('contrastBorder', { light: null, dark: null, hcDark: '#6FC3DF', hcLight: '#0F4A85' }, nls.localize(1605, "An extra border around elements to separate them from others for greater contrast."));
    exports.activeContrastBorder = (0, colorUtils_1.registerColor)('contrastActiveBorder', { light: null, dark: null, hcDark: exports.focusBorder, hcLight: exports.focusBorder }, nls.localize(1606, "An extra border around active elements to separate them from others for greater contrast."));
    exports.selectionBackground = (0, colorUtils_1.registerColor)('selection.background', null, nls.localize(1607, "The background color of text selections in the workbench (e.g. for input fields or text areas). Note that this does not apply to selections within the editor."));
    // ------ text link
    exports.textLinkForeground = (0, colorUtils_1.registerColor)('textLink.foreground', { light: '#006AB1', dark: '#3794FF', hcDark: '#21A6FF', hcLight: '#0F4A85' }, nls.localize(1608, "Foreground color for links in text."));
    exports.textLinkActiveForeground = (0, colorUtils_1.registerColor)('textLink.activeForeground', { light: '#006AB1', dark: '#3794FF', hcDark: '#21A6FF', hcLight: '#0F4A85' }, nls.localize(1609, "Foreground color for links in text when clicked on and on mouse hover."));
    exports.textSeparatorForeground = (0, colorUtils_1.registerColor)('textSeparator.foreground', { light: '#0000002e', dark: '#ffffff2e', hcDark: color_1.Color.black, hcLight: '#292929' }, nls.localize(1610, "Color for text separators."));
    // ------ text preformat
    exports.textPreformatForeground = (0, colorUtils_1.registerColor)('textPreformat.foreground', { light: '#A31515', dark: '#D7BA7D', hcDark: '#000000', hcLight: '#FFFFFF' }, nls.localize(1611, "Foreground color for preformatted text segments."));
    exports.textPreformatBackground = (0, colorUtils_1.registerColor)('textPreformat.background', { light: '#0000001A', dark: '#FFFFFF1A', hcDark: '#FFFFFF', hcLight: '#09345f' }, nls.localize(1612, "Background color for preformatted text segments."));
    // ------ text block quote
    exports.textBlockQuoteBackground = (0, colorUtils_1.registerColor)('textBlockQuote.background', { light: '#f2f2f2', dark: '#222222', hcDark: null, hcLight: '#F2F2F2' }, nls.localize(1613, "Background color for block quotes in text."));
    exports.textBlockQuoteBorder = (0, colorUtils_1.registerColor)('textBlockQuote.border', { light: '#007acc80', dark: '#007acc80', hcDark: color_1.Color.white, hcLight: '#292929' }, nls.localize(1614, "Border color for block quotes in text."));
    // ------ text code block
    exports.textCodeBlockBackground = (0, colorUtils_1.registerColor)('textCodeBlock.background', { light: '#dcdcdc66', dark: '#0a0a0a66', hcDark: color_1.Color.black, hcLight: '#F2F2F2' }, nls.localize(1615, "Background color for code blocks in text."));
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[278/*vs/platform/theme/common/colors/miscColors*/], __M([1/*require*/,0/*exports*/,3/*vs/nls*/,33/*vs/base/common/color*/,89/*vs/platform/theme/common/colorUtils*/,123/*vs/platform/theme/common/colors/baseColors*/]), function (require, exports, nls, color_1, colorUtils_1, baseColors_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.progressBarBackground = exports.scrollbarSliderActiveBackground = exports.scrollbarSliderHoverBackground = exports.scrollbarSliderBackground = exports.scrollbarShadow = exports.badgeForeground = exports.badgeBackground = exports.sashHoverBorder = void 0;
    // ----- sash
    exports.sashHoverBorder = (0, colorUtils_1.registerColor)('sash.hoverBorder', baseColors_1.focusBorder, nls.localize(1816, "Border color of active sashes."));
    // ----- badge
    exports.badgeBackground = (0, colorUtils_1.registerColor)('badge.background', { dark: '#4D4D4D', light: '#C4C4C4', hcDark: color_1.Color.black, hcLight: '#0F4A85' }, nls.localize(1817, "Badge background color. Badges are small information labels, e.g. for search results count."));
    exports.badgeForeground = (0, colorUtils_1.registerColor)('badge.foreground', { dark: color_1.Color.white, light: '#333', hcDark: color_1.Color.white, hcLight: color_1.Color.white }, nls.localize(1818, "Badge foreground color. Badges are small information labels, e.g. for search results count."));
    // ----- scrollbar
    exports.scrollbarShadow = (0, colorUtils_1.registerColor)('scrollbar.shadow', { dark: '#000000', light: '#DDDDDD', hcDark: null, hcLight: null }, nls.localize(1819, "Scrollbar shadow to indicate that the view is scrolled."));
    exports.scrollbarSliderBackground = (0, colorUtils_1.registerColor)('scrollbarSlider.background', { dark: color_1.Color.fromHex('#797979').transparent(0.4), light: color_1.Color.fromHex('#646464').transparent(0.4), hcDark: (0, colorUtils_1.transparent)(baseColors_1.contrastBorder, 0.6), hcLight: (0, colorUtils_1.transparent)(baseColors_1.contrastBorder, 0.4) }, nls.localize(1820, "Scrollbar slider background color."));
    exports.scrollbarSliderHoverBackground = (0, colorUtils_1.registerColor)('scrollbarSlider.hoverBackground', { dark: color_1.Color.fromHex('#646464').transparent(0.7), light: color_1.Color.fromHex('#646464').transparent(0.7), hcDark: (0, colorUtils_1.transparent)(baseColors_1.contrastBorder, 0.8), hcLight: (0, colorUtils_1.transparent)(baseColors_1.contrastBorder, 0.8) }, nls.localize(1821, "Scrollbar slider background color when hovering."));
    exports.scrollbarSliderActiveBackground = (0, colorUtils_1.registerColor)('scrollbarSlider.activeBackground', { dark: color_1.Color.fromHex('#BFBFBF').transparent(0.4), light: color_1.Color.fromHex('#000000').transparent(0.6), hcDark: baseColors_1.contrastBorder, hcLight: baseColors_1.contrastBorder }, nls.localize(1822, "Scrollbar slider background color when clicked on."));
    // ----- progress bar
    exports.progressBarBackground = (0, colorUtils_1.registerColor)('progressBar.background', { dark: color_1.Color.fromHex('#0E70C0'), light: color_1.Color.fromHex('#0E70C0'), hcDark: baseColors_1.contrastBorder, hcLight: baseColors_1.contrastBorder }, nls.localize(1823, "Background color of the progress bar that can show for long running operations."));
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[138/*vs/platform/theme/common/colors/editorColors*/], __M([1/*require*/,0/*exports*/,3/*vs/nls*/,33/*vs/base/common/color*/,89/*vs/platform/theme/common/colorUtils*/,123/*vs/platform/theme/common/colors/baseColors*/,278/*vs/platform/theme/common/colors/miscColors*/]), function (require, exports, nls, color_1, colorUtils_1, baseColors_1, miscColors_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.problemsInfoIconForeground = exports.problemsWarningIconForeground = exports.problemsErrorIconForeground = exports.overviewRulerSelectionHighlightForeground = exports.overviewRulerFindMatchForeground = exports.overviewRulerCommonContentForeground = exports.overviewRulerIncomingContentForeground = exports.overviewRulerCurrentContentForeground = exports.mergeBorder = exports.mergeCommonContentBackground = exports.mergeCommonHeaderBackground = exports.mergeIncomingContentBackground = exports.mergeIncomingHeaderBackground = exports.mergeCurrentContentBackground = exports.mergeCurrentHeaderBackground = exports.breadcrumbsPickerBackground = exports.breadcrumbsActiveSelectionForeground = exports.breadcrumbsFocusForeground = exports.breadcrumbsBackground = exports.breadcrumbsForeground = exports.toolbarActiveBackground = exports.toolbarHoverOutline = exports.toolbarHoverBackground = exports.widgetBorder = exports.widgetShadow = exports.diffUnchangedTextBackground = exports.diffUnchangedRegionForeground = exports.diffUnchangedRegionBackground = exports.diffDiagonalFill = exports.diffBorder = exports.diffRemovedOutline = exports.diffInsertedOutline = exports.diffOverviewRulerRemoved = exports.diffOverviewRulerInserted = exports.diffRemovedLineGutter = exports.diffInsertedLineGutter = exports.diffRemovedLine = exports.diffInsertedLine = exports.diffRemoved = exports.diffInserted = exports.defaultRemoveColor = exports.defaultInsertColor = exports.snippetFinalTabstopHighlightBorder = exports.snippetFinalTabstopHighlightBackground = exports.snippetTabstopHighlightBorder = exports.snippetTabstopHighlightBackground = exports.editorLightBulbAiForeground = exports.editorLightBulbAutoFixForeground = exports.editorLightBulbForeground = exports.editorInlayHintParameterBackground = exports.editorInlayHintParameterForeground = exports.editorInlayHintTypeBackground = exports.editorInlayHintTypeForeground = exports.editorInlayHintBackground = exports.editorInlayHintForeground = exports.editorHoverStatusBarBackground = exports.editorHoverBorder = exports.editorHoverForeground = exports.editorHoverBackground = exports.editorHoverHighlight = exports.editorFindRangeHighlightBorder = exports.editorFindMatchHighlightBorder = exports.editorFindMatchBorder = exports.editorFindRangeHighlight = exports.editorFindMatchHighlightForeground = exports.editorFindMatchHighlight = exports.editorFindMatchForeground = exports.editorFindMatch = exports.editorSelectionHighlightBorder = exports.editorSelectionHighlight = exports.editorInactiveSelection = exports.editorSelectionForeground = exports.editorSelectionBackground = exports.editorActiveLinkForeground = exports.editorHintBorder = exports.editorHintForeground = exports.editorInfoBorder = exports.editorInfoForeground = exports.editorInfoBackground = exports.editorWarningBorder = exports.editorWarningForeground = exports.editorWarningBackground = exports.editorErrorBorder = exports.editorErrorForeground = exports.editorErrorBackground = exports.editorWidgetResizeBorder = exports.editorWidgetBorder = exports.editorWidgetForeground = exports.editorWidgetBackground = exports.editorStickyScrollShadow = exports.editorStickyScrollBorder = exports.editorStickyScrollHoverBackground = exports.editorStickyScrollBackground = exports.editorForeground = exports.editorBackground = void 0;
    // ----- editor
    exports.editorBackground = (0, colorUtils_1.registerColor)('editor.background', { light: '#ffffff', dark: '#1E1E1E', hcDark: color_1.Color.black, hcLight: color_1.Color.white }, nls.localize(1624, "Editor background color."));
    exports.editorForeground = (0, colorUtils_1.registerColor)('editor.foreground', { light: '#333333', dark: '#BBBBBB', hcDark: color_1.Color.white, hcLight: baseColors_1.foreground }, nls.localize(1625, "Editor default foreground color."));
    exports.editorStickyScrollBackground = (0, colorUtils_1.registerColor)('editorStickyScroll.background', exports.editorBackground, nls.localize(1626, "Background color of sticky scroll in the editor"));
    exports.editorStickyScrollHoverBackground = (0, colorUtils_1.registerColor)('editorStickyScrollHover.background', { dark: '#2A2D2E', light: '#F0F0F0', hcDark: null, hcLight: color_1.Color.fromHex('#0F4A85').transparent(0.1) }, nls.localize(1627, "Background color of sticky scroll on hover in the editor"));
    exports.editorStickyScrollBorder = (0, colorUtils_1.registerColor)('editorStickyScroll.border', { dark: null, light: null, hcDark: baseColors_1.contrastBorder, hcLight: baseColors_1.contrastBorder }, nls.localize(1628, "Border color of sticky scroll in the editor"));
    exports.editorStickyScrollShadow = (0, colorUtils_1.registerColor)('editorStickyScroll.shadow', miscColors_1.scrollbarShadow, nls.localize(1629, " Shadow color of sticky scroll in the editor"));
    exports.editorWidgetBackground = (0, colorUtils_1.registerColor)('editorWidget.background', { dark: '#252526', light: '#F3F3F3', hcDark: '#0C141F', hcLight: color_1.Color.white }, nls.localize(1630, 'Background color of editor widgets, such as find/replace.'));
    exports.editorWidgetForeground = (0, colorUtils_1.registerColor)('editorWidget.foreground', baseColors_1.foreground, nls.localize(1631, 'Foreground color of editor widgets, such as find/replace.'));
    exports.editorWidgetBorder = (0, colorUtils_1.registerColor)('editorWidget.border', { dark: '#454545', light: '#C8C8C8', hcDark: baseColors_1.contrastBorder, hcLight: baseColors_1.contrastBorder }, nls.localize(1632, 'Border color of editor widgets. The color is only used if the widget chooses to have a border and if the color is not overridden by a widget.'));
    exports.editorWidgetResizeBorder = (0, colorUtils_1.registerColor)('editorWidget.resizeBorder', null, nls.localize(1633, "Border color of the resize bar of editor widgets. The color is only used if the widget chooses to have a resize border and if the color is not overridden by a widget."));
    exports.editorErrorBackground = (0, colorUtils_1.registerColor)('editorError.background', null, nls.localize(1634, 'Background color of error text in the editor. The color must not be opaque so as not to hide underlying decorations.'), true);
    exports.editorErrorForeground = (0, colorUtils_1.registerColor)('editorError.foreground', { dark: '#F14C4C', light: '#E51400', hcDark: '#F48771', hcLight: '#B5200D' }, nls.localize(1635, 'Foreground color of error squigglies in the editor.'));
    exports.editorErrorBorder = (0, colorUtils_1.registerColor)('editorError.border', { dark: null, light: null, hcDark: color_1.Color.fromHex('#E47777').transparent(0.8), hcLight: '#B5200D' }, nls.localize(1636, 'If set, color of double underlines for errors in the editor.'));
    exports.editorWarningBackground = (0, colorUtils_1.registerColor)('editorWarning.background', null, nls.localize(1637, 'Background color of warning text in the editor. The color must not be opaque so as not to hide underlying decorations.'), true);
    exports.editorWarningForeground = (0, colorUtils_1.registerColor)('editorWarning.foreground', { dark: '#CCA700', light: '#BF8803', hcDark: '#FFD370', hcLight: '#895503' }, nls.localize(1638, 'Foreground color of warning squigglies in the editor.'));
    exports.editorWarningBorder = (0, colorUtils_1.registerColor)('editorWarning.border', { dark: null, light: null, hcDark: color_1.Color.fromHex('#FFCC00').transparent(0.8), hcLight: color_1.Color.fromHex('#FFCC00').transparent(0.8) }, nls.localize(1639, 'If set, color of double underlines for warnings in the editor.'));
    exports.editorInfoBackground = (0, colorUtils_1.registerColor)('editorInfo.background', null, nls.localize(1640, 'Background color of info text in the editor. The color must not be opaque so as not to hide underlying decorations.'), true);
    exports.editorInfoForeground = (0, colorUtils_1.registerColor)('editorInfo.foreground', { dark: '#3794FF', light: '#1a85ff', hcDark: '#3794FF', hcLight: '#1a85ff' }, nls.localize(1641, 'Foreground color of info squigglies in the editor.'));
    exports.editorInfoBorder = (0, colorUtils_1.registerColor)('editorInfo.border', { dark: null, light: null, hcDark: color_1.Color.fromHex('#3794FF').transparent(0.8), hcLight: '#292929' }, nls.localize(1642, 'If set, color of double underlines for infos in the editor.'));
    exports.editorHintForeground = (0, colorUtils_1.registerColor)('editorHint.foreground', { dark: color_1.Color.fromHex('#eeeeee').transparent(0.7), light: '#6c6c6c', hcDark: null, hcLight: null }, nls.localize(1643, 'Foreground color of hint squigglies in the editor.'));
    exports.editorHintBorder = (0, colorUtils_1.registerColor)('editorHint.border', { dark: null, light: null, hcDark: color_1.Color.fromHex('#eeeeee').transparent(0.8), hcLight: '#292929' }, nls.localize(1644, 'If set, color of double underlines for hints in the editor.'));
    exports.editorActiveLinkForeground = (0, colorUtils_1.registerColor)('editorLink.activeForeground', { dark: '#4E94CE', light: color_1.Color.blue, hcDark: color_1.Color.cyan, hcLight: '#292929' }, nls.localize(1645, 'Color of active links.'));
    // ----- editor selection
    exports.editorSelectionBackground = (0, colorUtils_1.registerColor)('editor.selectionBackground', { light: '#ADD6FF', dark: '#264F78', hcDark: '#f3f518', hcLight: '#0F4A85' }, nls.localize(1646, "Color of the editor selection."));
    exports.editorSelectionForeground = (0, colorUtils_1.registerColor)('editor.selectionForeground', { light: null, dark: null, hcDark: '#000000', hcLight: color_1.Color.white }, nls.localize(1647, "Color of the selected text for high contrast."));
    exports.editorInactiveSelection = (0, colorUtils_1.registerColor)('editor.inactiveSelectionBackground', { light: (0, colorUtils_1.transparent)(exports.editorSelectionBackground, 0.5), dark: (0, colorUtils_1.transparent)(exports.editorSelectionBackground, 0.5), hcDark: (0, colorUtils_1.transparent)(exports.editorSelectionBackground, 0.7), hcLight: (0, colorUtils_1.transparent)(exports.editorSelectionBackground, 0.5) }, nls.localize(1648, "Color of the selection in an inactive editor. The color must not be opaque so as not to hide underlying decorations."), true);
    exports.editorSelectionHighlight = (0, colorUtils_1.registerColor)('editor.selectionHighlightBackground', { light: (0, colorUtils_1.lessProminent)(exports.editorSelectionBackground, exports.editorBackground, 0.3, 0.6), dark: (0, colorUtils_1.lessProminent)(exports.editorSelectionBackground, exports.editorBackground, 0.3, 0.6), hcDark: null, hcLight: null }, nls.localize(1649, 'Color for regions with the same content as the selection. The color must not be opaque so as not to hide underlying decorations.'), true);
    exports.editorSelectionHighlightBorder = (0, colorUtils_1.registerColor)('editor.selectionHighlightBorder', { light: null, dark: null, hcDark: baseColors_1.activeContrastBorder, hcLight: baseColors_1.activeContrastBorder }, nls.localize(1650, "Border color for regions with the same content as the selection."));
    // ----- editor find
    exports.editorFindMatch = (0, colorUtils_1.registerColor)('editor.findMatchBackground', { light: '#A8AC94', dark: '#515C6A', hcDark: null, hcLight: null }, nls.localize(1651, "Color of the current search match."));
    exports.editorFindMatchForeground = (0, colorUtils_1.registerColor)('editor.findMatchForeground', null, nls.localize(1652, "Text color of the current search match."));
    exports.editorFindMatchHighlight = (0, colorUtils_1.registerColor)('editor.findMatchHighlightBackground', { light: '#EA5C0055', dark: '#EA5C0055', hcDark: null, hcLight: null }, nls.localize(1653, "Color of the other search matches. The color must not be opaque so as not to hide underlying decorations."), true);
    exports.editorFindMatchHighlightForeground = (0, colorUtils_1.registerColor)('editor.findMatchHighlightForeground', null, nls.localize(1654, "Foreground color of the other search matches."), true);
    exports.editorFindRangeHighlight = (0, colorUtils_1.registerColor)('editor.findRangeHighlightBackground', { dark: '#3a3d4166', light: '#b4b4b44d', hcDark: null, hcLight: null }, nls.localize(1655, "Color of the range limiting the search. The color must not be opaque so as not to hide underlying decorations."), true);
    exports.editorFindMatchBorder = (0, colorUtils_1.registerColor)('editor.findMatchBorder', { light: null, dark: null, hcDark: baseColors_1.activeContrastBorder, hcLight: baseColors_1.activeContrastBorder }, nls.localize(1656, "Border color of the current search match."));
    exports.editorFindMatchHighlightBorder = (0, colorUtils_1.registerColor)('editor.findMatchHighlightBorder', { light: null, dark: null, hcDark: baseColors_1.activeContrastBorder, hcLight: baseColors_1.activeContrastBorder }, nls.localize(1657, "Border color of the other search matches."));
    exports.editorFindRangeHighlightBorder = (0, colorUtils_1.registerColor)('editor.findRangeHighlightBorder', { dark: null, light: null, hcDark: (0, colorUtils_1.transparent)(baseColors_1.activeContrastBorder, 0.4), hcLight: (0, colorUtils_1.transparent)(baseColors_1.activeContrastBorder, 0.4) }, nls.localize(1658, "Border color of the range limiting the search. The color must not be opaque so as not to hide underlying decorations."), true);
    // ----- editor hover
    exports.editorHoverHighlight = (0, colorUtils_1.registerColor)('editor.hoverHighlightBackground', { light: '#ADD6FF26', dark: '#264f7840', hcDark: '#ADD6FF26', hcLight: null }, nls.localize(1659, 'Highlight below the word for which a hover is shown. The color must not be opaque so as not to hide underlying decorations.'), true);
    exports.editorHoverBackground = (0, colorUtils_1.registerColor)('editorHoverWidget.background', exports.editorWidgetBackground, nls.localize(1660, 'Background color of the editor hover.'));
    exports.editorHoverForeground = (0, colorUtils_1.registerColor)('editorHoverWidget.foreground', exports.editorWidgetForeground, nls.localize(1661, 'Foreground color of the editor hover.'));
    exports.editorHoverBorder = (0, colorUtils_1.registerColor)('editorHoverWidget.border', exports.editorWidgetBorder, nls.localize(1662, 'Border color of the editor hover.'));
    exports.editorHoverStatusBarBackground = (0, colorUtils_1.registerColor)('editorHoverWidget.statusBarBackground', { dark: (0, colorUtils_1.lighten)(exports.editorHoverBackground, 0.2), light: (0, colorUtils_1.darken)(exports.editorHoverBackground, 0.05), hcDark: exports.editorWidgetBackground, hcLight: exports.editorWidgetBackground }, nls.localize(1663, "Background color of the editor hover status bar."));
    // ----- editor inlay hint
    exports.editorInlayHintForeground = (0, colorUtils_1.registerColor)('editorInlayHint.foreground', { dark: '#969696', light: '#969696', hcDark: color_1.Color.white, hcLight: color_1.Color.black }, nls.localize(1664, 'Foreground color of inline hints'));
    exports.editorInlayHintBackground = (0, colorUtils_1.registerColor)('editorInlayHint.background', { dark: (0, colorUtils_1.transparent)(miscColors_1.badgeBackground, .10), light: (0, colorUtils_1.transparent)(miscColors_1.badgeBackground, .10), hcDark: (0, colorUtils_1.transparent)(color_1.Color.white, .10), hcLight: (0, colorUtils_1.transparent)(miscColors_1.badgeBackground, .10) }, nls.localize(1665, 'Background color of inline hints'));
    exports.editorInlayHintTypeForeground = (0, colorUtils_1.registerColor)('editorInlayHint.typeForeground', exports.editorInlayHintForeground, nls.localize(1666, 'Foreground color of inline hints for types'));
    exports.editorInlayHintTypeBackground = (0, colorUtils_1.registerColor)('editorInlayHint.typeBackground', exports.editorInlayHintBackground, nls.localize(1667, 'Background color of inline hints for types'));
    exports.editorInlayHintParameterForeground = (0, colorUtils_1.registerColor)('editorInlayHint.parameterForeground', exports.editorInlayHintForeground, nls.localize(1668, 'Foreground color of inline hints for parameters'));
    exports.editorInlayHintParameterBackground = (0, colorUtils_1.registerColor)('editorInlayHint.parameterBackground', exports.editorInlayHintBackground, nls.localize(1669, 'Background color of inline hints for parameters'));
    // ----- editor lightbulb
    exports.editorLightBulbForeground = (0, colorUtils_1.registerColor)('editorLightBulb.foreground', { dark: '#FFCC00', light: '#DDB100', hcDark: '#FFCC00', hcLight: '#007ACC' }, nls.localize(1670, "The color used for the lightbulb actions icon."));
    exports.editorLightBulbAutoFixForeground = (0, colorUtils_1.registerColor)('editorLightBulbAutoFix.foreground', { dark: '#75BEFF', light: '#007ACC', hcDark: '#75BEFF', hcLight: '#007ACC' }, nls.localize(1671, "The color used for the lightbulb auto fix actions icon."));
    exports.editorLightBulbAiForeground = (0, colorUtils_1.registerColor)('editorLightBulbAi.foreground', exports.editorLightBulbForeground, nls.localize(1672, "The color used for the lightbulb AI icon."));
    // ----- editor snippet
    exports.snippetTabstopHighlightBackground = (0, colorUtils_1.registerColor)('editor.snippetTabstopHighlightBackground', { dark: new color_1.Color(new color_1.RGBA(124, 124, 124, 0.3)), light: new color_1.Color(new color_1.RGBA(10, 50, 100, 0.2)), hcDark: new color_1.Color(new color_1.RGBA(124, 124, 124, 0.3)), hcLight: new color_1.Color(new color_1.RGBA(10, 50, 100, 0.2)) }, nls.localize(1673, "Highlight background color of a snippet tabstop."));
    exports.snippetTabstopHighlightBorder = (0, colorUtils_1.registerColor)('editor.snippetTabstopHighlightBorder', null, nls.localize(1674, "Highlight border color of a snippet tabstop."));
    exports.snippetFinalTabstopHighlightBackground = (0, colorUtils_1.registerColor)('editor.snippetFinalTabstopHighlightBackground', null, nls.localize(1675, "Highlight background color of the final tabstop of a snippet."));
    exports.snippetFinalTabstopHighlightBorder = (0, colorUtils_1.registerColor)('editor.snippetFinalTabstopHighlightBorder', { dark: '#525252', light: new color_1.Color(new color_1.RGBA(10, 50, 100, 0.5)), hcDark: '#525252', hcLight: '#292929' }, nls.localize(1676, "Highlight border color of the final tabstop of a snippet."));
    // ----- diff editor
    exports.defaultInsertColor = new color_1.Color(new color_1.RGBA(155, 185, 85, .2));
    exports.defaultRemoveColor = new color_1.Color(new color_1.RGBA(255, 0, 0, .2));
    exports.diffInserted = (0, colorUtils_1.registerColor)('diffEditor.insertedTextBackground', { dark: '#9ccc2c33', light: '#9ccc2c40', hcDark: null, hcLight: null }, nls.localize(1677, 'Background color for text that got inserted. The color must not be opaque so as not to hide underlying decorations.'), true);
    exports.diffRemoved = (0, colorUtils_1.registerColor)('diffEditor.removedTextBackground', { dark: '#ff000033', light: '#ff000033', hcDark: null, hcLight: null }, nls.localize(1678, 'Background color for text that got removed. The color must not be opaque so as not to hide underlying decorations.'), true);
    exports.diffInsertedLine = (0, colorUtils_1.registerColor)('diffEditor.insertedLineBackground', { dark: exports.defaultInsertColor, light: exports.defaultInsertColor, hcDark: null, hcLight: null }, nls.localize(1679, 'Background color for lines that got inserted. The color must not be opaque so as not to hide underlying decorations.'), true);
    exports.diffRemovedLine = (0, colorUtils_1.registerColor)('diffEditor.removedLineBackground', { dark: exports.defaultRemoveColor, light: exports.defaultRemoveColor, hcDark: null, hcLight: null }, nls.localize(1680, 'Background color for lines that got removed. The color must not be opaque so as not to hide underlying decorations.'), true);
    exports.diffInsertedLineGutter = (0, colorUtils_1.registerColor)('diffEditorGutter.insertedLineBackground', null, nls.localize(1681, 'Background color for the margin where lines got inserted.'));
    exports.diffRemovedLineGutter = (0, colorUtils_1.registerColor)('diffEditorGutter.removedLineBackground', null, nls.localize(1682, 'Background color for the margin where lines got removed.'));
    exports.diffOverviewRulerInserted = (0, colorUtils_1.registerColor)('diffEditorOverview.insertedForeground', null, nls.localize(1683, 'Diff overview ruler foreground for inserted content.'));
    exports.diffOverviewRulerRemoved = (0, colorUtils_1.registerColor)('diffEditorOverview.removedForeground', null, nls.localize(1684, 'Diff overview ruler foreground for removed content.'));
    exports.diffInsertedOutline = (0, colorUtils_1.registerColor)('diffEditor.insertedTextBorder', { dark: null, light: null, hcDark: '#33ff2eff', hcLight: '#374E06' }, nls.localize(1685, 'Outline color for the text that got inserted.'));
    exports.diffRemovedOutline = (0, colorUtils_1.registerColor)('diffEditor.removedTextBorder', { dark: null, light: null, hcDark: '#FF008F', hcLight: '#AD0707' }, nls.localize(1686, 'Outline color for text that got removed.'));
    exports.diffBorder = (0, colorUtils_1.registerColor)('diffEditor.border', { dark: null, light: null, hcDark: baseColors_1.contrastBorder, hcLight: baseColors_1.contrastBorder }, nls.localize(1687, 'Border color between the two text editors.'));
    exports.diffDiagonalFill = (0, colorUtils_1.registerColor)('diffEditor.diagonalFill', { dark: '#cccccc33', light: '#22222233', hcDark: null, hcLight: null }, nls.localize(1688, "Color of the diff editor's diagonal fill. The diagonal fill is used in side-by-side diff views."));
    exports.diffUnchangedRegionBackground = (0, colorUtils_1.registerColor)('diffEditor.unchangedRegionBackground', 'sideBar.background', nls.localize(1689, "The background color of unchanged blocks in the diff editor."));
    exports.diffUnchangedRegionForeground = (0, colorUtils_1.registerColor)('diffEditor.unchangedRegionForeground', 'foreground', nls.localize(1690, "The foreground color of unchanged blocks in the diff editor."));
    exports.diffUnchangedTextBackground = (0, colorUtils_1.registerColor)('diffEditor.unchangedCodeBackground', { dark: '#74747429', light: '#b8b8b829', hcDark: null, hcLight: null }, nls.localize(1691, "The background color of unchanged code in the diff editor."));
    // ----- widget
    exports.widgetShadow = (0, colorUtils_1.registerColor)('widget.shadow', { dark: (0, colorUtils_1.transparent)(color_1.Color.black, .36), light: (0, colorUtils_1.transparent)(color_1.Color.black, .16), hcDark: null, hcLight: null }, nls.localize(1692, 'Shadow color of widgets such as find/replace inside the editor.'));
    exports.widgetBorder = (0, colorUtils_1.registerColor)('widget.border', { dark: null, light: null, hcDark: baseColors_1.contrastBorder, hcLight: baseColors_1.contrastBorder }, nls.localize(1693, 'Border color of widgets such as find/replace inside the editor.'));
    // ----- toolbar
    exports.toolbarHoverBackground = (0, colorUtils_1.registerColor)('toolbar.hoverBackground', { dark: '#5a5d5e50', light: '#b8b8b850', hcDark: null, hcLight: null }, nls.localize(1694, "Toolbar background when hovering over actions using the mouse"));
    exports.toolbarHoverOutline = (0, colorUtils_1.registerColor)('toolbar.hoverOutline', { dark: null, light: null, hcDark: baseColors_1.activeContrastBorder, hcLight: baseColors_1.activeContrastBorder }, nls.localize(1695, "Toolbar outline when hovering over actions using the mouse"));
    exports.toolbarActiveBackground = (0, colorUtils_1.registerColor)('toolbar.activeBackground', { dark: (0, colorUtils_1.lighten)(exports.toolbarHoverBackground, 0.1), light: (0, colorUtils_1.darken)(exports.toolbarHoverBackground, 0.1), hcDark: null, hcLight: null }, nls.localize(1696, "Toolbar background when holding the mouse over actions"));
    // ----- breadcumbs
    exports.breadcrumbsForeground = (0, colorUtils_1.registerColor)('breadcrumb.foreground', (0, colorUtils_1.transparent)(baseColors_1.foreground, 0.8), nls.localize(1697, "Color of focused breadcrumb items."));
    exports.breadcrumbsBackground = (0, colorUtils_1.registerColor)('breadcrumb.background', exports.editorBackground, nls.localize(1698, "Background color of breadcrumb items."));
    exports.breadcrumbsFocusForeground = (0, colorUtils_1.registerColor)('breadcrumb.focusForeground', { light: (0, colorUtils_1.darken)(baseColors_1.foreground, 0.2), dark: (0, colorUtils_1.lighten)(baseColors_1.foreground, 0.1), hcDark: (0, colorUtils_1.lighten)(baseColors_1.foreground, 0.1), hcLight: (0, colorUtils_1.lighten)(baseColors_1.foreground, 0.1) }, nls.localize(1699, "Color of focused breadcrumb items."));
    exports.breadcrumbsActiveSelectionForeground = (0, colorUtils_1.registerColor)('breadcrumb.activeSelectionForeground', { light: (0, colorUtils_1.darken)(baseColors_1.foreground, 0.2), dark: (0, colorUtils_1.lighten)(baseColors_1.foreground, 0.1), hcDark: (0, colorUtils_1.lighten)(baseColors_1.foreground, 0.1), hcLight: (0, colorUtils_1.lighten)(baseColors_1.foreground, 0.1) }, nls.localize(1700, "Color of selected breadcrumb items."));
    exports.breadcrumbsPickerBackground = (0, colorUtils_1.registerColor)('breadcrumbPicker.background', exports.editorWidgetBackground, nls.localize(1701, "Background color of breadcrumb item picker."));
    // ----- merge
    const headerTransparency = 0.5;
    const currentBaseColor = color_1.Color.fromHex('#40C8AE').transparent(headerTransparency);
    const incomingBaseColor = color_1.Color.fromHex('#40A6FF').transparent(headerTransparency);
    const commonBaseColor = color_1.Color.fromHex('#606060').transparent(0.4);
    const contentTransparency = 0.4;
    const rulerTransparency = 1;
    exports.mergeCurrentHeaderBackground = (0, colorUtils_1.registerColor)('merge.currentHeaderBackground', { dark: currentBaseColor, light: currentBaseColor, hcDark: null, hcLight: null }, nls.localize(1702, 'Current header background in inline merge-conflicts. The color must not be opaque so as not to hide underlying decorations.'), true);
    exports.mergeCurrentContentBackground = (0, colorUtils_1.registerColor)('merge.currentContentBackground', (0, colorUtils_1.transparent)(exports.mergeCurrentHeaderBackground, contentTransparency), nls.localize(1703, 'Current content background in inline merge-conflicts. The color must not be opaque so as not to hide underlying decorations.'), true);
    exports.mergeIncomingHeaderBackground = (0, colorUtils_1.registerColor)('merge.incomingHeaderBackground', { dark: incomingBaseColor, light: incomingBaseColor, hcDark: null, hcLight: null }, nls.localize(1704, 'Incoming header background in inline merge-conflicts. The color must not be opaque so as not to hide underlying decorations.'), true);
    exports.mergeIncomingContentBackground = (0, colorUtils_1.registerColor)('merge.incomingContentBackground', (0, colorUtils_1.transparent)(exports.mergeIncomingHeaderBackground, contentTransparency), nls.localize(1705, 'Incoming content background in inline merge-conflicts. The color must not be opaque so as not to hide underlying decorations.'), true);
    exports.mergeCommonHeaderBackground = (0, colorUtils_1.registerColor)('merge.commonHeaderBackground', { dark: commonBaseColor, light: commonBaseColor, hcDark: null, hcLight: null }, nls.localize(1706, 'Common ancestor header background in inline merge-conflicts. The color must not be opaque so as not to hide underlying decorations.'), true);
    exports.mergeCommonContentBackground = (0, colorUtils_1.registerColor)('merge.commonContentBackground', (0, colorUtils_1.transparent)(exports.mergeCommonHeaderBackground, contentTransparency), nls.localize(1707, 'Common ancestor content background in inline merge-conflicts. The color must not be opaque so as not to hide underlying decorations.'), true);
    exports.mergeBorder = (0, colorUtils_1.registerColor)('merge.border', { dark: null, light: null, hcDark: '#C3DF6F', hcLight: '#007ACC' }, nls.localize(1708, 'Border color on headers and the splitter in inline merge-conflicts.'));
    exports.overviewRulerCurrentContentForeground = (0, colorUtils_1.registerColor)('editorOverviewRuler.currentContentForeground', { dark: (0, colorUtils_1.transparent)(exports.mergeCurrentHeaderBackground, rulerTransparency), light: (0, colorUtils_1.transparent)(exports.mergeCurrentHeaderBackground, rulerTransparency), hcDark: exports.mergeBorder, hcLight: exports.mergeBorder }, nls.localize(1709, 'Current overview ruler foreground for inline merge-conflicts.'));
    exports.overviewRulerIncomingContentForeground = (0, colorUtils_1.registerColor)('editorOverviewRuler.incomingContentForeground', { dark: (0, colorUtils_1.transparent)(exports.mergeIncomingHeaderBackground, rulerTransparency), light: (0, colorUtils_1.transparent)(exports.mergeIncomingHeaderBackground, rulerTransparency), hcDark: exports.mergeBorder, hcLight: exports.mergeBorder }, nls.localize(1710, 'Incoming overview ruler foreground for inline merge-conflicts.'));
    exports.overviewRulerCommonContentForeground = (0, colorUtils_1.registerColor)('editorOverviewRuler.commonContentForeground', { dark: (0, colorUtils_1.transparent)(exports.mergeCommonHeaderBackground, rulerTransparency), light: (0, colorUtils_1.transparent)(exports.mergeCommonHeaderBackground, rulerTransparency), hcDark: exports.mergeBorder, hcLight: exports.mergeBorder }, nls.localize(1711, 'Common ancestor overview ruler foreground for inline merge-conflicts.'));
    exports.overviewRulerFindMatchForeground = (0, colorUtils_1.registerColor)('editorOverviewRuler.findMatchForeground', { dark: '#d186167e', light: '#d186167e', hcDark: '#AB5A00', hcLight: '#AB5A00' }, nls.localize(1712, 'Overview ruler marker color for find matches. The color must not be opaque so as not to hide underlying decorations.'), true);
    exports.overviewRulerSelectionHighlightForeground = (0, colorUtils_1.registerColor)('editorOverviewRuler.selectionHighlightForeground', '#A0A0A0CC', nls.localize(1713, 'Overview ruler marker color for selection highlights. The color must not be opaque so as not to hide underlying decorations.'), true);
    // ----- problems
    exports.problemsErrorIconForeground = (0, colorUtils_1.registerColor)('problemsErrorIcon.foreground', exports.editorErrorForeground, nls.localize(1714, "The color used for the problems error icon."));
    exports.problemsWarningIconForeground = (0, colorUtils_1.registerColor)('problemsWarningIcon.foreground', exports.editorWarningForeground, nls.localize(1715, "The color used for the problems warning icon."));
    exports.problemsInfoIconForeground = (0, colorUtils_1.registerColor)('problemsInfoIcon.foreground', exports.editorInfoForeground, nls.localize(1716, "The color used for the problems info icon."));
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[412/*vs/platform/theme/common/colors/inputColors*/], __M([1/*require*/,0/*exports*/,3/*vs/nls*/,33/*vs/base/common/color*/,89/*vs/platform/theme/common/colorUtils*/,123/*vs/platform/theme/common/colors/baseColors*/,138/*vs/platform/theme/common/colors/editorColors*/]), function (require, exports, nls, color_1, colorUtils_1, baseColors_1, editorColors_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.keybindingLabelBottomBorder = exports.keybindingLabelBorder = exports.keybindingLabelForeground = exports.keybindingLabelBackground = exports.checkboxSelectBorder = exports.checkboxBorder = exports.checkboxForeground = exports.checkboxSelectBackground = exports.checkboxBackground = exports.radioInactiveHoverBackground = exports.radioInactiveBorder = exports.radioInactiveBackground = exports.radioInactiveForeground = exports.radioActiveBorder = exports.radioActiveBackground = exports.radioActiveForeground = exports.buttonSecondaryHoverBackground = exports.buttonSecondaryBackground = exports.buttonSecondaryForeground = exports.buttonBorder = exports.buttonHoverBackground = exports.buttonBackground = exports.buttonSeparator = exports.buttonForeground = exports.selectBorder = exports.selectForeground = exports.selectListBackground = exports.selectBackground = exports.inputValidationErrorBorder = exports.inputValidationErrorForeground = exports.inputValidationErrorBackground = exports.inputValidationWarningBorder = exports.inputValidationWarningForeground = exports.inputValidationWarningBackground = exports.inputValidationInfoBorder = exports.inputValidationInfoForeground = exports.inputValidationInfoBackground = exports.inputPlaceholderForeground = exports.inputActiveOptionForeground = exports.inputActiveOptionBackground = exports.inputActiveOptionHoverBackground = exports.inputActiveOptionBorder = exports.inputBorder = exports.inputForeground = exports.inputBackground = void 0;
    // ----- input
    exports.inputBackground = (0, colorUtils_1.registerColor)('input.background', { dark: '#3C3C3C', light: color_1.Color.white, hcDark: color_1.Color.black, hcLight: color_1.Color.white }, nls.localize(1717, "Input box background."));
    exports.inputForeground = (0, colorUtils_1.registerColor)('input.foreground', baseColors_1.foreground, nls.localize(1718, "Input box foreground."));
    exports.inputBorder = (0, colorUtils_1.registerColor)('input.border', { dark: null, light: null, hcDark: baseColors_1.contrastBorder, hcLight: baseColors_1.contrastBorder }, nls.localize(1719, "Input box border."));
    exports.inputActiveOptionBorder = (0, colorUtils_1.registerColor)('inputOption.activeBorder', { dark: '#007ACC', light: '#007ACC', hcDark: baseColors_1.contrastBorder, hcLight: baseColors_1.contrastBorder }, nls.localize(1720, "Border color of activated options in input fields."));
    exports.inputActiveOptionHoverBackground = (0, colorUtils_1.registerColor)('inputOption.hoverBackground', { dark: '#5a5d5e80', light: '#b8b8b850', hcDark: null, hcLight: null }, nls.localize(1721, "Background color of activated options in input fields."));
    exports.inputActiveOptionBackground = (0, colorUtils_1.registerColor)('inputOption.activeBackground', { dark: (0, colorUtils_1.transparent)(baseColors_1.focusBorder, 0.4), light: (0, colorUtils_1.transparent)(baseColors_1.focusBorder, 0.2), hcDark: color_1.Color.transparent, hcLight: color_1.Color.transparent }, nls.localize(1722, "Background hover color of options in input fields."));
    exports.inputActiveOptionForeground = (0, colorUtils_1.registerColor)('inputOption.activeForeground', { dark: color_1.Color.white, light: color_1.Color.black, hcDark: baseColors_1.foreground, hcLight: baseColors_1.foreground }, nls.localize(1723, "Foreground color of activated options in input fields."));
    exports.inputPlaceholderForeground = (0, colorUtils_1.registerColor)('input.placeholderForeground', { light: (0, colorUtils_1.transparent)(baseColors_1.foreground, 0.5), dark: (0, colorUtils_1.transparent)(baseColors_1.foreground, 0.5), hcDark: (0, colorUtils_1.transparent)(baseColors_1.foreground, 0.7), hcLight: (0, colorUtils_1.transparent)(baseColors_1.foreground, 0.7) }, nls.localize(1724, "Input box foreground color for placeholder text."));
    // ----- input validation
    exports.inputValidationInfoBackground = (0, colorUtils_1.registerColor)('inputValidation.infoBackground', { dark: '#063B49', light: '#D6ECF2', hcDark: color_1.Color.black, hcLight: color_1.Color.white }, nls.localize(1725, "Input validation background color for information severity."));
    exports.inputValidationInfoForeground = (0, colorUtils_1.registerColor)('inputValidation.infoForeground', { dark: null, light: null, hcDark: null, hcLight: baseColors_1.foreground }, nls.localize(1726, "Input validation foreground color for information severity."));
    exports.inputValidationInfoBorder = (0, colorUtils_1.registerColor)('inputValidation.infoBorder', { dark: '#007acc', light: '#007acc', hcDark: baseColors_1.contrastBorder, hcLight: baseColors_1.contrastBorder }, nls.localize(1727, "Input validation border color for information severity."));
    exports.inputValidationWarningBackground = (0, colorUtils_1.registerColor)('inputValidation.warningBackground', { dark: '#352A05', light: '#F6F5D2', hcDark: color_1.Color.black, hcLight: color_1.Color.white }, nls.localize(1728, "Input validation background color for warning severity."));
    exports.inputValidationWarningForeground = (0, colorUtils_1.registerColor)('inputValidation.warningForeground', { dark: null, light: null, hcDark: null, hcLight: baseColors_1.foreground }, nls.localize(1729, "Input validation foreground color for warning severity."));
    exports.inputValidationWarningBorder = (0, colorUtils_1.registerColor)('inputValidation.warningBorder', { dark: '#B89500', light: '#B89500', hcDark: baseColors_1.contrastBorder, hcLight: baseColors_1.contrastBorder }, nls.localize(1730, "Input validation border color for warning severity."));
    exports.inputValidationErrorBackground = (0, colorUtils_1.registerColor)('inputValidation.errorBackground', { dark: '#5A1D1D', light: '#F2DEDE', hcDark: color_1.Color.black, hcLight: color_1.Color.white }, nls.localize(1731, "Input validation background color for error severity."));
    exports.inputValidationErrorForeground = (0, colorUtils_1.registerColor)('inputValidation.errorForeground', { dark: null, light: null, hcDark: null, hcLight: baseColors_1.foreground }, nls.localize(1732, "Input validation foreground color for error severity."));
    exports.inputValidationErrorBorder = (0, colorUtils_1.registerColor)('inputValidation.errorBorder', { dark: '#BE1100', light: '#BE1100', hcDark: baseColors_1.contrastBorder, hcLight: baseColors_1.contrastBorder }, nls.localize(1733, "Input validation border color for error severity."));
    // ----- select
    exports.selectBackground = (0, colorUtils_1.registerColor)('dropdown.background', { dark: '#3C3C3C', light: color_1.Color.white, hcDark: color_1.Color.black, hcLight: color_1.Color.white }, nls.localize(1734, "Dropdown background."));
    exports.selectListBackground = (0, colorUtils_1.registerColor)('dropdown.listBackground', { dark: null, light: null, hcDark: color_1.Color.black, hcLight: color_1.Color.white }, nls.localize(1735, "Dropdown list background."));
    exports.selectForeground = (0, colorUtils_1.registerColor)('dropdown.foreground', { dark: '#F0F0F0', light: baseColors_1.foreground, hcDark: color_1.Color.white, hcLight: baseColors_1.foreground }, nls.localize(1736, "Dropdown foreground."));
    exports.selectBorder = (0, colorUtils_1.registerColor)('dropdown.border', { dark: exports.selectBackground, light: '#CECECE', hcDark: baseColors_1.contrastBorder, hcLight: baseColors_1.contrastBorder }, nls.localize(1737, "Dropdown border."));
    // ------ button
    exports.buttonForeground = (0, colorUtils_1.registerColor)('button.foreground', color_1.Color.white, nls.localize(1738, "Button foreground color."));
    exports.buttonSeparator = (0, colorUtils_1.registerColor)('button.separator', (0, colorUtils_1.transparent)(exports.buttonForeground, .4), nls.localize(1739, "Button separator color."));
    exports.buttonBackground = (0, colorUtils_1.registerColor)('button.background', { dark: '#0E639C', light: '#007ACC', hcDark: null, hcLight: '#0F4A85' }, nls.localize(1740, "Button background color."));
    exports.buttonHoverBackground = (0, colorUtils_1.registerColor)('button.hoverBackground', { dark: (0, colorUtils_1.lighten)(exports.buttonBackground, 0.2), light: (0, colorUtils_1.darken)(exports.buttonBackground, 0.2), hcDark: exports.buttonBackground, hcLight: exports.buttonBackground }, nls.localize(1741, "Button background color when hovering."));
    exports.buttonBorder = (0, colorUtils_1.registerColor)('button.border', baseColors_1.contrastBorder, nls.localize(1742, "Button border color."));
    exports.buttonSecondaryForeground = (0, colorUtils_1.registerColor)('button.secondaryForeground', { dark: color_1.Color.white, light: color_1.Color.white, hcDark: color_1.Color.white, hcLight: baseColors_1.foreground }, nls.localize(1743, "Secondary button foreground color."));
    exports.buttonSecondaryBackground = (0, colorUtils_1.registerColor)('button.secondaryBackground', { dark: '#3A3D41', light: '#5F6A79', hcDark: null, hcLight: color_1.Color.white }, nls.localize(1744, "Secondary button background color."));
    exports.buttonSecondaryHoverBackground = (0, colorUtils_1.registerColor)('button.secondaryHoverBackground', { dark: (0, colorUtils_1.lighten)(exports.buttonSecondaryBackground, 0.2), light: (0, colorUtils_1.darken)(exports.buttonSecondaryBackground, 0.2), hcDark: null, hcLight: null }, nls.localize(1745, "Secondary button background color when hovering."));
    // ------ radio
    exports.radioActiveForeground = (0, colorUtils_1.registerColor)('radio.activeForeground', exports.inputActiveOptionForeground, nls.localize(1746, "Foreground color of active radio option."));
    exports.radioActiveBackground = (0, colorUtils_1.registerColor)('radio.activeBackground', exports.inputActiveOptionBackground, nls.localize(1747, "Background color of active radio option."));
    exports.radioActiveBorder = (0, colorUtils_1.registerColor)('radio.activeBorder', exports.inputActiveOptionBorder, nls.localize(1748, "Border color of the active radio option."));
    exports.radioInactiveForeground = (0, colorUtils_1.registerColor)('radio.inactiveForeground', null, nls.localize(1749, "Foreground color of inactive radio option."));
    exports.radioInactiveBackground = (0, colorUtils_1.registerColor)('radio.inactiveBackground', null, nls.localize(1750, "Background color of inactive radio option."));
    exports.radioInactiveBorder = (0, colorUtils_1.registerColor)('radio.inactiveBorder', { light: (0, colorUtils_1.transparent)(exports.radioActiveForeground, .2), dark: (0, colorUtils_1.transparent)(exports.radioActiveForeground, .2), hcDark: (0, colorUtils_1.transparent)(exports.radioActiveForeground, .4), hcLight: (0, colorUtils_1.transparent)(exports.radioActiveForeground, .2) }, nls.localize(1751, "Border color of the inactive radio option."));
    exports.radioInactiveHoverBackground = (0, colorUtils_1.registerColor)('radio.inactiveHoverBackground', exports.inputActiveOptionHoverBackground, nls.localize(1752, "Background color of inactive active radio option when hovering."));
    // ------ checkbox
    exports.checkboxBackground = (0, colorUtils_1.registerColor)('checkbox.background', exports.selectBackground, nls.localize(1753, "Background color of checkbox widget."));
    exports.checkboxSelectBackground = (0, colorUtils_1.registerColor)('checkbox.selectBackground', editorColors_1.editorWidgetBackground, nls.localize(1754, "Background color of checkbox widget when the element it's in is selected."));
    exports.checkboxForeground = (0, colorUtils_1.registerColor)('checkbox.foreground', exports.selectForeground, nls.localize(1755, "Foreground color of checkbox widget."));
    exports.checkboxBorder = (0, colorUtils_1.registerColor)('checkbox.border', exports.selectBorder, nls.localize(1756, "Border color of checkbox widget."));
    exports.checkboxSelectBorder = (0, colorUtils_1.registerColor)('checkbox.selectBorder', baseColors_1.iconForeground, nls.localize(1757, "Border color of checkbox widget when the element it's in is selected."));
    // ------ keybinding label
    exports.keybindingLabelBackground = (0, colorUtils_1.registerColor)('keybindingLabel.background', { dark: new color_1.Color(new color_1.RGBA(128, 128, 128, 0.17)), light: new color_1.Color(new color_1.RGBA(221, 221, 221, 0.4)), hcDark: color_1.Color.transparent, hcLight: color_1.Color.transparent }, nls.localize(1758, "Keybinding label background color. The keybinding label is used to represent a keyboard shortcut."));
    exports.keybindingLabelForeground = (0, colorUtils_1.registerColor)('keybindingLabel.foreground', { dark: color_1.Color.fromHex('#CCCCCC'), light: color_1.Color.fromHex('#555555'), hcDark: color_1.Color.white, hcLight: baseColors_1.foreground }, nls.localize(1759, "Keybinding label foreground color. The keybinding label is used to represent a keyboard shortcut."));
    exports.keybindingLabelBorder = (0, colorUtils_1.registerColor)('keybindingLabel.border', { dark: new color_1.Color(new color_1.RGBA(51, 51, 51, 0.6)), light: new color_1.Color(new color_1.RGBA(204, 204, 204, 0.4)), hcDark: new color_1.Color(new color_1.RGBA(111, 195, 223)), hcLight: baseColors_1.contrastBorder }, nls.localize(1760, "Keybinding label border color. The keybinding label is used to represent a keyboard shortcut."));
    exports.keybindingLabelBottomBorder = (0, colorUtils_1.registerColor)('keybindingLabel.bottomBorder', { dark: new color_1.Color(new color_1.RGBA(68, 68, 68, 0.6)), light: new color_1.Color(new color_1.RGBA(187, 187, 187, 0.4)), hcDark: new color_1.Color(new color_1.RGBA(111, 195, 223)), hcLight: baseColors_1.foreground }, nls.localize(1761, "Keybinding label border bottom color. The keybinding label is used to represent a keyboard shortcut."));
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[279/*vs/platform/theme/common/colors/listColors*/], __M([1/*require*/,0/*exports*/,3/*vs/nls*/,33/*vs/base/common/color*/,89/*vs/platform/theme/common/colorUtils*/,123/*vs/platform/theme/common/colors/baseColors*/,138/*vs/platform/theme/common/colors/editorColors*/]), function (require, exports, nls, color_1, colorUtils_1, baseColors_1, editorColors_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.editorActionListFocusBackground = exports.editorActionListFocusForeground = exports.editorActionListForeground = exports.editorActionListBackground = exports.tableOddRowsBackgroundColor = exports.tableColumnsBorder = exports.treeInactiveIndentGuidesStroke = exports.treeIndentGuidesStroke = exports.listDeemphasizedForeground = exports.listFilterMatchHighlightBorder = exports.listFilterMatchHighlight = exports.listFilterWidgetShadow = exports.listFilterWidgetNoMatchesOutline = exports.listFilterWidgetOutline = exports.listFilterWidgetBackground = exports.listWarningForeground = exports.listErrorForeground = exports.listInvalidItemForeground = exports.listFocusHighlightForeground = exports.listHighlightForeground = exports.listDropBetweenBackground = exports.listDropOverBackground = exports.listHoverForeground = exports.listHoverBackground = exports.listInactiveFocusOutline = exports.listInactiveFocusBackground = exports.listInactiveSelectionIconForeground = exports.listInactiveSelectionForeground = exports.listInactiveSelectionBackground = exports.listActiveSelectionIconForeground = exports.listActiveSelectionForeground = exports.listActiveSelectionBackground = exports.listFocusAndSelectionOutline = exports.listFocusOutline = exports.listFocusForeground = exports.listFocusBackground = void 0;
    exports.listFocusBackground = (0, colorUtils_1.registerColor)('list.focusBackground', null, nls.localize(1762, "List/Tree background color for the focused item when the list/tree is active. An active list/tree has keyboard focus, an inactive does not."));
    exports.listFocusForeground = (0, colorUtils_1.registerColor)('list.focusForeground', null, nls.localize(1763, "List/Tree foreground color for the focused item when the list/tree is active. An active list/tree has keyboard focus, an inactive does not."));
    exports.listFocusOutline = (0, colorUtils_1.registerColor)('list.focusOutline', { dark: baseColors_1.focusBorder, light: baseColors_1.focusBorder, hcDark: baseColors_1.activeContrastBorder, hcLight: baseColors_1.activeContrastBorder }, nls.localize(1764, "List/Tree outline color for the focused item when the list/tree is active. An active list/tree has keyboard focus, an inactive does not."));
    exports.listFocusAndSelectionOutline = (0, colorUtils_1.registerColor)('list.focusAndSelectionOutline', null, nls.localize(1765, "List/Tree outline color for the focused item when the list/tree is active and selected. An active list/tree has keyboard focus, an inactive does not."));
    exports.listActiveSelectionBackground = (0, colorUtils_1.registerColor)('list.activeSelectionBackground', { dark: '#04395E', light: '#0060C0', hcDark: null, hcLight: color_1.Color.fromHex('#0F4A85').transparent(0.1) }, nls.localize(1766, "List/Tree background color for the selected item when the list/tree is active. An active list/tree has keyboard focus, an inactive does not."));
    exports.listActiveSelectionForeground = (0, colorUtils_1.registerColor)('list.activeSelectionForeground', { dark: color_1.Color.white, light: color_1.Color.white, hcDark: null, hcLight: null }, nls.localize(1767, "List/Tree foreground color for the selected item when the list/tree is active. An active list/tree has keyboard focus, an inactive does not."));
    exports.listActiveSelectionIconForeground = (0, colorUtils_1.registerColor)('list.activeSelectionIconForeground', null, nls.localize(1768, "List/Tree icon foreground color for the selected item when the list/tree is active. An active list/tree has keyboard focus, an inactive does not."));
    exports.listInactiveSelectionBackground = (0, colorUtils_1.registerColor)('list.inactiveSelectionBackground', { dark: '#37373D', light: '#E4E6F1', hcDark: null, hcLight: color_1.Color.fromHex('#0F4A85').transparent(0.1) }, nls.localize(1769, "List/Tree background color for the selected item when the list/tree is inactive. An active list/tree has keyboard focus, an inactive does not."));
    exports.listInactiveSelectionForeground = (0, colorUtils_1.registerColor)('list.inactiveSelectionForeground', null, nls.localize(1770, "List/Tree foreground color for the selected item when the list/tree is inactive. An active list/tree has keyboard focus, an inactive does not."));
    exports.listInactiveSelectionIconForeground = (0, colorUtils_1.registerColor)('list.inactiveSelectionIconForeground', null, nls.localize(1771, "List/Tree icon foreground color for the selected item when the list/tree is inactive. An active list/tree has keyboard focus, an inactive does not."));
    exports.listInactiveFocusBackground = (0, colorUtils_1.registerColor)('list.inactiveFocusBackground', null, nls.localize(1772, "List/Tree background color for the focused item when the list/tree is inactive. An active list/tree has keyboard focus, an inactive does not."));
    exports.listInactiveFocusOutline = (0, colorUtils_1.registerColor)('list.inactiveFocusOutline', null, nls.localize(1773, "List/Tree outline color for the focused item when the list/tree is inactive. An active list/tree has keyboard focus, an inactive does not."));
    exports.listHoverBackground = (0, colorUtils_1.registerColor)('list.hoverBackground', { dark: '#2A2D2E', light: '#F0F0F0', hcDark: color_1.Color.white.transparent(0.1), hcLight: color_1.Color.fromHex('#0F4A85').transparent(0.1) }, nls.localize(1774, "List/Tree background when hovering over items using the mouse."));
    exports.listHoverForeground = (0, colorUtils_1.registerColor)('list.hoverForeground', null, nls.localize(1775, "List/Tree foreground when hovering over items using the mouse."));
    exports.listDropOverBackground = (0, colorUtils_1.registerColor)('list.dropBackground', { dark: '#062F4A', light: '#D6EBFF', hcDark: null, hcLight: null }, nls.localize(1776, "List/Tree drag and drop background when moving items over other items when using the mouse."));
    exports.listDropBetweenBackground = (0, colorUtils_1.registerColor)('list.dropBetweenBackground', { dark: baseColors_1.iconForeground, light: baseColors_1.iconForeground, hcDark: null, hcLight: null }, nls.localize(1777, "List/Tree drag and drop border color when moving items between items when using the mouse."));
    exports.listHighlightForeground = (0, colorUtils_1.registerColor)('list.highlightForeground', { dark: '#2AAAFF', light: '#0066BF', hcDark: baseColors_1.focusBorder, hcLight: baseColors_1.focusBorder }, nls.localize(1778, 'List/Tree foreground color of the match highlights when searching inside the list/tree.'));
    exports.listFocusHighlightForeground = (0, colorUtils_1.registerColor)('list.focusHighlightForeground', { dark: exports.listHighlightForeground, light: (0, colorUtils_1.ifDefinedThenElse)(exports.listActiveSelectionBackground, exports.listHighlightForeground, '#BBE7FF'), hcDark: exports.listHighlightForeground, hcLight: exports.listHighlightForeground }, nls.localize(1779, 'List/Tree foreground color of the match highlights on actively focused items when searching inside the list/tree.'));
    exports.listInvalidItemForeground = (0, colorUtils_1.registerColor)('list.invalidItemForeground', { dark: '#B89500', light: '#B89500', hcDark: '#B89500', hcLight: '#B5200D' }, nls.localize(1780, 'List/Tree foreground color for invalid items, for example an unresolved root in explorer.'));
    exports.listErrorForeground = (0, colorUtils_1.registerColor)('list.errorForeground', { dark: '#F88070', light: '#B01011', hcDark: null, hcLight: null }, nls.localize(1781, 'Foreground color of list items containing errors.'));
    exports.listWarningForeground = (0, colorUtils_1.registerColor)('list.warningForeground', { dark: '#CCA700', light: '#855F00', hcDark: null, hcLight: null }, nls.localize(1782, 'Foreground color of list items containing warnings.'));
    exports.listFilterWidgetBackground = (0, colorUtils_1.registerColor)('listFilterWidget.background', { light: (0, colorUtils_1.darken)(editorColors_1.editorWidgetBackground, 0), dark: (0, colorUtils_1.lighten)(editorColors_1.editorWidgetBackground, 0), hcDark: editorColors_1.editorWidgetBackground, hcLight: editorColors_1.editorWidgetBackground }, nls.localize(1783, 'Background color of the type filter widget in lists and trees.'));
    exports.listFilterWidgetOutline = (0, colorUtils_1.registerColor)('listFilterWidget.outline', { dark: color_1.Color.transparent, light: color_1.Color.transparent, hcDark: '#f38518', hcLight: '#007ACC' }, nls.localize(1784, 'Outline color of the type filter widget in lists and trees.'));
    exports.listFilterWidgetNoMatchesOutline = (0, colorUtils_1.registerColor)('listFilterWidget.noMatchesOutline', { dark: '#BE1100', light: '#BE1100', hcDark: baseColors_1.contrastBorder, hcLight: baseColors_1.contrastBorder }, nls.localize(1785, 'Outline color of the type filter widget in lists and trees, when there are no matches.'));
    exports.listFilterWidgetShadow = (0, colorUtils_1.registerColor)('listFilterWidget.shadow', editorColors_1.widgetShadow, nls.localize(1786, 'Shadow color of the type filter widget in lists and trees.'));
    exports.listFilterMatchHighlight = (0, colorUtils_1.registerColor)('list.filterMatchBackground', { dark: editorColors_1.editorFindMatchHighlight, light: editorColors_1.editorFindMatchHighlight, hcDark: null, hcLight: null }, nls.localize(1787, 'Background color of the filtered match.'));
    exports.listFilterMatchHighlightBorder = (0, colorUtils_1.registerColor)('list.filterMatchBorder', { dark: editorColors_1.editorFindMatchHighlightBorder, light: editorColors_1.editorFindMatchHighlightBorder, hcDark: baseColors_1.contrastBorder, hcLight: baseColors_1.activeContrastBorder }, nls.localize(1788, 'Border color of the filtered match.'));
    exports.listDeemphasizedForeground = (0, colorUtils_1.registerColor)('list.deemphasizedForeground', { dark: '#8C8C8C', light: '#8E8E90', hcDark: '#A7A8A9', hcLight: '#666666' }, nls.localize(1789, "List/Tree foreground color for items that are deemphasized."));
    // ------ tree
    exports.treeIndentGuidesStroke = (0, colorUtils_1.registerColor)('tree.indentGuidesStroke', { dark: '#585858', light: '#a9a9a9', hcDark: '#a9a9a9', hcLight: '#a5a5a5' }, nls.localize(1790, "Tree stroke color for the indentation guides."));
    exports.treeInactiveIndentGuidesStroke = (0, colorUtils_1.registerColor)('tree.inactiveIndentGuidesStroke', (0, colorUtils_1.transparent)(exports.treeIndentGuidesStroke, 0.4), nls.localize(1791, "Tree stroke color for the indentation guides that are not active."));
    // ------ table
    exports.tableColumnsBorder = (0, colorUtils_1.registerColor)('tree.tableColumnsBorder', { dark: '#CCCCCC20', light: '#61616120', hcDark: null, hcLight: null }, nls.localize(1792, "Table border color between columns."));
    exports.tableOddRowsBackgroundColor = (0, colorUtils_1.registerColor)('tree.tableOddRowsBackground', { dark: (0, colorUtils_1.transparent)(baseColors_1.foreground, 0.04), light: (0, colorUtils_1.transparent)(baseColors_1.foreground, 0.04), hcDark: null, hcLight: null }, nls.localize(1793, "Background color for odd table rows."));
    // ------ action list
    exports.editorActionListBackground = (0, colorUtils_1.registerColor)('editorActionList.background', editorColors_1.editorWidgetBackground, nls.localize(1794, "Action List background color."));
    exports.editorActionListForeground = (0, colorUtils_1.registerColor)('editorActionList.foreground', editorColors_1.editorWidgetForeground, nls.localize(1795, "Action List foreground color."));
    exports.editorActionListFocusForeground = (0, colorUtils_1.registerColor)('editorActionList.focusForeground', exports.listActiveSelectionForeground, nls.localize(1796, "Action List foreground color for the focused item."));
    exports.editorActionListFocusBackground = (0, colorUtils_1.registerColor)('editorActionList.focusBackground', exports.listActiveSelectionBackground, nls.localize(1797, "Action List background color for the focused item."));
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[751/*vs/platform/theme/common/colors/menuColors*/], __M([1/*require*/,0/*exports*/,3/*vs/nls*/,89/*vs/platform/theme/common/colorUtils*/,123/*vs/platform/theme/common/colors/baseColors*/,412/*vs/platform/theme/common/colors/inputColors*/,279/*vs/platform/theme/common/colors/listColors*/]), function (require, exports, nls, colorUtils_1, baseColors_1, inputColors_1, listColors_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.menuSeparatorBackground = exports.menuSelectionBorder = exports.menuSelectionBackground = exports.menuSelectionForeground = exports.menuBackground = exports.menuForeground = exports.menuBorder = void 0;
    exports.menuBorder = (0, colorUtils_1.registerColor)('menu.border', { dark: null, light: null, hcDark: baseColors_1.contrastBorder, hcLight: baseColors_1.contrastBorder }, nls.localize(1798, "Border color of menus."));
    exports.menuForeground = (0, colorUtils_1.registerColor)('menu.foreground', inputColors_1.selectForeground, nls.localize(1799, "Foreground color of menu items."));
    exports.menuBackground = (0, colorUtils_1.registerColor)('menu.background', inputColors_1.selectBackground, nls.localize(1800, "Background color of menu items."));
    exports.menuSelectionForeground = (0, colorUtils_1.registerColor)('menu.selectionForeground', listColors_1.listActiveSelectionForeground, nls.localize(1801, "Foreground color of the selected menu item in menus."));
    exports.menuSelectionBackground = (0, colorUtils_1.registerColor)('menu.selectionBackground', listColors_1.listActiveSelectionBackground, nls.localize(1802, "Background color of the selected menu item in menus."));
    exports.menuSelectionBorder = (0, colorUtils_1.registerColor)('menu.selectionBorder', { dark: null, light: null, hcDark: baseColors_1.activeContrastBorder, hcLight: baseColors_1.activeContrastBorder }, nls.localize(1803, "Border color of the selected menu item in menus."));
    exports.menuSeparatorBackground = (0, colorUtils_1.registerColor)('menu.separatorBackground', { dark: '#606060', light: '#D4D4D4', hcDark: baseColors_1.contrastBorder, hcLight: baseColors_1.contrastBorder }, nls.localize(1804, "Color of a separator menu item in menus."));
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[413/*vs/platform/theme/common/colors/minimapColors*/], __M([1/*require*/,0/*exports*/,3/*vs/nls*/,33/*vs/base/common/color*/,89/*vs/platform/theme/common/colorUtils*/,138/*vs/platform/theme/common/colors/editorColors*/,278/*vs/platform/theme/common/colors/miscColors*/]), function (require, exports, nls, color_1, colorUtils_1, editorColors_1, miscColors_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.minimapSliderActiveBackground = exports.minimapSliderHoverBackground = exports.minimapSliderBackground = exports.minimapForegroundOpacity = exports.minimapBackground = exports.minimapError = exports.minimapWarning = exports.minimapInfo = exports.minimapSelection = exports.minimapSelectionOccurrenceHighlight = exports.minimapFindMatch = void 0;
    exports.minimapFindMatch = (0, colorUtils_1.registerColor)('minimap.findMatchHighlight', { light: '#d18616', dark: '#d18616', hcDark: '#AB5A00', hcLight: '#0F4A85' }, nls.localize(1805, 'Minimap marker color for find matches.'), true);
    exports.minimapSelectionOccurrenceHighlight = (0, colorUtils_1.registerColor)('minimap.selectionOccurrenceHighlight', { light: '#c9c9c9', dark: '#676767', hcDark: '#ffffff', hcLight: '#0F4A85' }, nls.localize(1806, 'Minimap marker color for repeating editor selections.'), true);
    exports.minimapSelection = (0, colorUtils_1.registerColor)('minimap.selectionHighlight', { light: '#ADD6FF', dark: '#264F78', hcDark: '#ffffff', hcLight: '#0F4A85' }, nls.localize(1807, 'Minimap marker color for the editor selection.'), true);
    exports.minimapInfo = (0, colorUtils_1.registerColor)('minimap.infoHighlight', { dark: editorColors_1.editorInfoForeground, light: editorColors_1.editorInfoForeground, hcDark: editorColors_1.editorInfoBorder, hcLight: editorColors_1.editorInfoBorder }, nls.localize(1808, 'Minimap marker color for infos.'));
    exports.minimapWarning = (0, colorUtils_1.registerColor)('minimap.warningHighlight', { dark: editorColors_1.editorWarningForeground, light: editorColors_1.editorWarningForeground, hcDark: editorColors_1.editorWarningBorder, hcLight: editorColors_1.editorWarningBorder }, nls.localize(1809, 'Minimap marker color for warnings.'));
    exports.minimapError = (0, colorUtils_1.registerColor)('minimap.errorHighlight', { dark: new color_1.Color(new color_1.RGBA(255, 18, 18, 0.7)), light: new color_1.Color(new color_1.RGBA(255, 18, 18, 0.7)), hcDark: new color_1.Color(new color_1.RGBA(255, 50, 50, 1)), hcLight: '#B5200D' }, nls.localize(1810, 'Minimap marker color for errors.'));
    exports.minimapBackground = (0, colorUtils_1.registerColor)('minimap.background', null, nls.localize(1811, "Minimap background color."));
    exports.minimapForegroundOpacity = (0, colorUtils_1.registerColor)('minimap.foregroundOpacity', color_1.Color.fromHex('#000f'), nls.localize(1812, 'Opacity of foreground elements rendered in the minimap. For example, "#000000c0" will render the elements with 75% opacity.'));
    exports.minimapSliderBackground = (0, colorUtils_1.registerColor)('minimapSlider.background', (0, colorUtils_1.transparent)(miscColors_1.scrollbarSliderBackground, 0.5), nls.localize(1813, "Minimap slider background color."));
    exports.minimapSliderHoverBackground = (0, colorUtils_1.registerColor)('minimapSlider.hoverBackground', (0, colorUtils_1.transparent)(miscColors_1.scrollbarSliderHoverBackground, 0.5), nls.localize(1814, "Minimap slider background color when hovering."));
    exports.minimapSliderActiveBackground = (0, colorUtils_1.registerColor)('minimapSlider.activeBackground', (0, colorUtils_1.transparent)(miscColors_1.scrollbarSliderActiveBackground, 0.5), nls.localize(1815, "Minimap slider background color when clicked on."));
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[752/*vs/platform/theme/common/colors/chartsColors*/], __M([1/*require*/,0/*exports*/,3/*vs/nls*/,89/*vs/platform/theme/common/colorUtils*/,123/*vs/platform/theme/common/colors/baseColors*/,138/*vs/platform/theme/common/colors/editorColors*/,413/*vs/platform/theme/common/colors/minimapColors*/]), function (require, exports, nls, colorUtils_1, baseColors_1, editorColors_1, minimapColors_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.chartsPurple = exports.chartsGreen = exports.chartsOrange = exports.chartsYellow = exports.chartsBlue = exports.chartsRed = exports.chartsLines = exports.chartsForeground = void 0;
    exports.chartsForeground = (0, colorUtils_1.registerColor)('charts.foreground', baseColors_1.foreground, nls.localize(1616, "The foreground color used in charts."));
    exports.chartsLines = (0, colorUtils_1.registerColor)('charts.lines', (0, colorUtils_1.transparent)(baseColors_1.foreground, .5), nls.localize(1617, "The color used for horizontal lines in charts."));
    exports.chartsRed = (0, colorUtils_1.registerColor)('charts.red', editorColors_1.editorErrorForeground, nls.localize(1618, "The red color used in chart visualizations."));
    exports.chartsBlue = (0, colorUtils_1.registerColor)('charts.blue', editorColors_1.editorInfoForeground, nls.localize(1619, "The blue color used in chart visualizations."));
    exports.chartsYellow = (0, colorUtils_1.registerColor)('charts.yellow', editorColors_1.editorWarningForeground, nls.localize(1620, "The yellow color used in chart visualizations."));
    exports.chartsOrange = (0, colorUtils_1.registerColor)('charts.orange', minimapColors_1.minimapFindMatch, nls.localize(1621, "The orange color used in chart visualizations."));
    exports.chartsGreen = (0, colorUtils_1.registerColor)('charts.green', { dark: '#89D185', light: '#388A34', hcDark: '#89D185', hcLight: '#374e06' }, nls.localize(1622, "The green color used in chart visualizations."));
    exports.chartsPurple = (0, colorUtils_1.registerColor)('charts.purple', { dark: '#B180D7', light: '#652D90', hcDark: '#B180D7', hcLight: '#652D90' }, nls.localize(1623, "The purple color used in chart visualizations."));
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[753/*vs/platform/theme/common/colors/quickpickColors*/], __M([1/*require*/,0/*exports*/,3/*vs/nls*/,33/*vs/base/common/color*/,89/*vs/platform/theme/common/colorUtils*/,138/*vs/platform/theme/common/colors/editorColors*/,279/*vs/platform/theme/common/colors/listColors*/]), function (require, exports, nls, color_1, colorUtils_1, editorColors_1, listColors_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.quickInputListFocusBackground = exports.quickInputListFocusIconForeground = exports.quickInputListFocusForeground = exports._deprecatedQuickInputListFocusBackground = exports.pickerGroupBorder = exports.pickerGroupForeground = exports.quickInputTitleBackground = exports.quickInputForeground = exports.quickInputBackground = void 0;
    exports.quickInputBackground = (0, colorUtils_1.registerColor)('quickInput.background', editorColors_1.editorWidgetBackground, nls.localize(1824, "Quick picker background color. The quick picker widget is the container for pickers like the command palette."));
    exports.quickInputForeground = (0, colorUtils_1.registerColor)('quickInput.foreground', editorColors_1.editorWidgetForeground, nls.localize(1825, "Quick picker foreground color. The quick picker widget is the container for pickers like the command palette."));
    exports.quickInputTitleBackground = (0, colorUtils_1.registerColor)('quickInputTitle.background', { dark: new color_1.Color(new color_1.RGBA(255, 255, 255, 0.105)), light: new color_1.Color(new color_1.RGBA(0, 0, 0, 0.06)), hcDark: '#000000', hcLight: color_1.Color.white }, nls.localize(1826, "Quick picker title background color. The quick picker widget is the container for pickers like the command palette."));
    exports.pickerGroupForeground = (0, colorUtils_1.registerColor)('pickerGroup.foreground', { dark: '#3794FF', light: '#0066BF', hcDark: color_1.Color.white, hcLight: '#0F4A85' }, nls.localize(1827, "Quick picker color for grouping labels."));
    exports.pickerGroupBorder = (0, colorUtils_1.registerColor)('pickerGroup.border', { dark: '#3F3F46', light: '#CCCEDB', hcDark: color_1.Color.white, hcLight: '#0F4A85' }, nls.localize(1828, "Quick picker color for grouping borders."));
    exports._deprecatedQuickInputListFocusBackground = (0, colorUtils_1.registerColor)('quickInput.list.focusBackground', null, '', undefined, nls.localize(1829, "Please use quickInputList.focusBackground instead"));
    exports.quickInputListFocusForeground = (0, colorUtils_1.registerColor)('quickInputList.focusForeground', listColors_1.listActiveSelectionForeground, nls.localize(1830, "Quick picker foreground color for the focused item."));
    exports.quickInputListFocusIconForeground = (0, colorUtils_1.registerColor)('quickInputList.focusIconForeground', listColors_1.listActiveSelectionIconForeground, nls.localize(1831, "Quick picker icon foreground color for the focused item."));
    exports.quickInputListFocusBackground = (0, colorUtils_1.registerColor)('quickInputList.focusBackground', { dark: (0, colorUtils_1.oneOf)(exports._deprecatedQuickInputListFocusBackground, listColors_1.listActiveSelectionBackground), light: (0, colorUtils_1.oneOf)(exports._deprecatedQuickInputListFocusBackground, listColors_1.listActiveSelectionBackground), hcDark: null, hcLight: null }, nls.localize(1832, "Quick picker background color for the focused item."));
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[754/*vs/platform/theme/common/colors/searchColors*/], __M([1/*require*/,0/*exports*/,3/*vs/nls*/,89/*vs/platform/theme/common/colorUtils*/,123/*vs/platform/theme/common/colors/baseColors*/,138/*vs/platform/theme/common/colors/editorColors*/]), function (require, exports, nls, colorUtils_1, baseColors_1, editorColors_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.searchEditorFindMatchBorder = exports.searchEditorFindMatch = exports.searchResultsInfoForeground = void 0;
    exports.searchResultsInfoForeground = (0, colorUtils_1.registerColor)('search.resultsInfoForeground', { light: baseColors_1.foreground, dark: (0, colorUtils_1.transparent)(baseColors_1.foreground, 0.65), hcDark: baseColors_1.foreground, hcLight: baseColors_1.foreground }, nls.localize(1833, "Color of the text in the search viewlet's completion message."));
    // ----- search editor (Distinct from normal editor find match to allow for better differentiation)
    exports.searchEditorFindMatch = (0, colorUtils_1.registerColor)('searchEditor.findMatchBackground', { light: (0, colorUtils_1.transparent)(editorColors_1.editorFindMatchHighlight, 0.66), dark: (0, colorUtils_1.transparent)(editorColors_1.editorFindMatchHighlight, 0.66), hcDark: editorColors_1.editorFindMatchHighlight, hcLight: editorColors_1.editorFindMatchHighlight }, nls.localize(1834, "Color of the Search Editor query matches."));
    exports.searchEditorFindMatchBorder = (0, colorUtils_1.registerColor)('searchEditor.findMatchBorder', { light: (0, colorUtils_1.transparent)(editorColors_1.editorFindMatchHighlightBorder, 0.66), dark: (0, colorUtils_1.transparent)(editorColors_1.editorFindMatchHighlightBorder, 0.66), hcDark: editorColors_1.editorFindMatchHighlightBorder, hcLight: editorColors_1.editorFindMatchHighlightBorder }, nls.localize(1835, "Border color of the Search Editor query matches."));
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
define(__m[32/*vs/platform/theme/common/colorRegistry*/], __M([1/*require*/,0/*exports*/,89/*vs/platform/theme/common/colorUtils*/,123/*vs/platform/theme/common/colors/baseColors*/,752/*vs/platform/theme/common/colors/chartsColors*/,138/*vs/platform/theme/common/colors/editorColors*/,412/*vs/platform/theme/common/colors/inputColors*/,279/*vs/platform/theme/common/colors/listColors*/,751/*vs/platform/theme/common/colors/menuColors*/,413/*vs/platform/theme/common/colors/minimapColors*/,278/*vs/platform/theme/common/colors/miscColors*/,753/*vs/platform/theme/common/colors/quickpickColors*/,754/*vs/platform/theme/common/colors/searchColors*/]), function (require, exports, colorUtils_1, baseColors_1, chartsColors_1, editorColors_1, inputColors_1, listColors_1, menuColors_1, minimapColors_1, miscColors_1, quickpickColors_1, searchColors_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    __exportStar(colorUtils_1, exports);
    // Make sure all color files are exported
    __exportStar(baseColors_1, exports);
    __exportStar(chartsColors_1, exports);
    __exportStar(editorColors_1, exports);
    __exportStar(inputColors_1, exports);
    __exportStar(listColors_1, exports);
    __exportStar(menuColors_1, exports);
    __exportStar(minimapColors_1, exports);
    __exportStar(miscColors_1, exports);
    __exportStar(quickpickColors_1, exports);
    __exportStar(searchColors_1, exports);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[185/*vs/editor/browser/editorDom*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,172/*vs/base/browser/globalPointerMoveMonitor*/,77/*vs/base/browser/mouseEvent*/,14/*vs/base/common/async*/,2/*vs/base/common/lifecycle*/,32/*vs/platform/theme/common/colorRegistry*/]), function (require, exports, dom, globalPointerMoveMonitor_1, mouseEvent_1, async_1, lifecycle_1, colorRegistry_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DynamicCssRules = exports.GlobalEditorPointerMoveMonitor = exports.EditorPointerEventFactory = exports.EditorMouseEventFactory = exports.EditorMouseEvent = exports.CoordinatesRelativeToEditor = exports.EditorPagePosition = exports.ClientCoordinates = exports.PageCoordinates = void 0;
    exports.createEditorPagePosition = createEditorPagePosition;
    exports.createCoordinatesRelativeToEditor = createCoordinatesRelativeToEditor;
    /**
     * Coordinates relative to the whole document (e.g. mouse event's pageX and pageY)
     */
    class PageCoordinates {
        constructor(x, y) {
            this.x = x;
            this.y = y;
            this._pageCoordinatesBrand = undefined;
        }
        toClientCoordinates(targetWindow) {
            return new ClientCoordinates(this.x - targetWindow.scrollX, this.y - targetWindow.scrollY);
        }
    }
    exports.PageCoordinates = PageCoordinates;
    /**
     * Coordinates within the application's client area (i.e. origin is document's scroll position).
     *
     * For example, clicking in the top-left corner of the client area will
     * always result in a mouse event with a client.x value of 0, regardless
     * of whether the page is scrolled horizontally.
     */
    class ClientCoordinates {
        constructor(clientX, clientY) {
            this.clientX = clientX;
            this.clientY = clientY;
            this._clientCoordinatesBrand = undefined;
        }
        toPageCoordinates(targetWindow) {
            return new PageCoordinates(this.clientX + targetWindow.scrollX, this.clientY + targetWindow.scrollY);
        }
    }
    exports.ClientCoordinates = ClientCoordinates;
    /**
     * The position of the editor in the page.
     */
    class EditorPagePosition {
        constructor(x, y, width, height) {
            this.x = x;
            this.y = y;
            this.width = width;
            this.height = height;
            this._editorPagePositionBrand = undefined;
        }
    }
    exports.EditorPagePosition = EditorPagePosition;
    /**
     * Coordinates relative to the the (top;left) of the editor that can be used safely with other internal editor metrics.
     * **NOTE**: This position is obtained by taking page coordinates and transforming them relative to the
     * editor's (top;left) position in a way in which scale transformations are taken into account.
     * **NOTE**: These coordinates could be negative if the mouse position is outside the editor.
     */
    class CoordinatesRelativeToEditor {
        constructor(x, y) {
            this.x = x;
            this.y = y;
            this._positionRelativeToEditorBrand = undefined;
        }
    }
    exports.CoordinatesRelativeToEditor = CoordinatesRelativeToEditor;
    function createEditorPagePosition(editorViewDomNode) {
        const editorPos = dom.getDomNodePagePosition(editorViewDomNode);
        return new EditorPagePosition(editorPos.left, editorPos.top, editorPos.width, editorPos.height);
    }
    function createCoordinatesRelativeToEditor(editorViewDomNode, editorPagePosition, pos) {
        // The editor's page position is read from the DOM using getBoundingClientRect().
        //
        // getBoundingClientRect() returns the actual dimensions, while offsetWidth and offsetHeight
        // reflect the unscaled size. We can use this difference to detect a transform:scale()
        // and we will apply the transformation in inverse to get mouse coordinates that make sense inside the editor.
        //
        // This could be expanded to cover rotation as well maybe by walking the DOM up from `editorViewDomNode`
        // and computing the effective transformation matrix using getComputedStyle(element).transform.
        //
        const scaleX = editorPagePosition.width / editorViewDomNode.offsetWidth;
        const scaleY = editorPagePosition.height / editorViewDomNode.offsetHeight;
        // Adjust mouse offsets if editor appears to be scaled via transforms
        const relativeX = (pos.x - editorPagePosition.x) / scaleX;
        const relativeY = (pos.y - editorPagePosition.y) / scaleY;
        return new CoordinatesRelativeToEditor(relativeX, relativeY);
    }
    class EditorMouseEvent extends mouseEvent_1.StandardMouseEvent {
        constructor(e, isFromPointerCapture, editorViewDomNode) {
            super(dom.getWindow(editorViewDomNode), e);
            this._editorMouseEventBrand = undefined;
            this.isFromPointerCapture = isFromPointerCapture;
            this.pos = new PageCoordinates(this.posx, this.posy);
            this.editorPos = createEditorPagePosition(editorViewDomNode);
            this.relativePos = createCoordinatesRelativeToEditor(editorViewDomNode, this.editorPos, this.pos);
        }
    }
    exports.EditorMouseEvent = EditorMouseEvent;
    class EditorMouseEventFactory {
        constructor(editorViewDomNode) {
            this._editorViewDomNode = editorViewDomNode;
        }
        _create(e) {
            return new EditorMouseEvent(e, false, this._editorViewDomNode);
        }
        onContextMenu(target, callback) {
            return dom.addDisposableListener(target, 'contextmenu', (e) => {
                callback(this._create(e));
            });
        }
        onMouseUp(target, callback) {
            return dom.addDisposableListener(target, 'mouseup', (e) => {
                callback(this._create(e));
            });
        }
        onMouseDown(target, callback) {
            return dom.addDisposableListener(target, dom.EventType.MOUSE_DOWN, (e) => {
                callback(this._create(e));
            });
        }
        onPointerDown(target, callback) {
            return dom.addDisposableListener(target, dom.EventType.POINTER_DOWN, (e) => {
                callback(this._create(e), e.pointerId);
            });
        }
        onMouseLeave(target, callback) {
            return dom.addDisposableListener(target, dom.EventType.MOUSE_LEAVE, (e) => {
                callback(this._create(e));
            });
        }
        onMouseMove(target, callback) {
            return dom.addDisposableListener(target, 'mousemove', (e) => callback(this._create(e)));
        }
    }
    exports.EditorMouseEventFactory = EditorMouseEventFactory;
    class EditorPointerEventFactory {
        constructor(editorViewDomNode) {
            this._editorViewDomNode = editorViewDomNode;
        }
        _create(e) {
            return new EditorMouseEvent(e, false, this._editorViewDomNode);
        }
        onPointerUp(target, callback) {
            return dom.addDisposableListener(target, 'pointerup', (e) => {
                callback(this._create(e));
            });
        }
        onPointerDown(target, callback) {
            return dom.addDisposableListener(target, dom.EventType.POINTER_DOWN, (e) => {
                callback(this._create(e), e.pointerId);
            });
        }
        onPointerLeave(target, callback) {
            return dom.addDisposableListener(target, dom.EventType.POINTER_LEAVE, (e) => {
                callback(this._create(e));
            });
        }
        onPointerMove(target, callback) {
            return dom.addDisposableListener(target, 'pointermove', (e) => callback(this._create(e)));
        }
    }
    exports.EditorPointerEventFactory = EditorPointerEventFactory;
    class GlobalEditorPointerMoveMonitor extends lifecycle_1.Disposable {
        constructor(editorViewDomNode) {
            super();
            this._editorViewDomNode = editorViewDomNode;
            this._globalPointerMoveMonitor = this._register(new globalPointerMoveMonitor_1.GlobalPointerMoveMonitor());
            this._keydownListener = null;
        }
        startMonitoring(initialElement, pointerId, initialButtons, pointerMoveCallback, onStopCallback) {
            // Add a <<capture>> keydown event listener that will cancel the monitoring
            // if something other than a modifier key is pressed
            this._keydownListener = dom.addStandardDisposableListener(initialElement.ownerDocument, 'keydown', (e) => {
                const chord = e.toKeyCodeChord();
                if (chord.isModifierKey()) {
                    // Allow modifier keys
                    return;
                }
                this._globalPointerMoveMonitor.stopMonitoring(true, e.browserEvent);
            }, true);
            this._globalPointerMoveMonitor.startMonitoring(initialElement, pointerId, initialButtons, (e) => {
                pointerMoveCallback(new EditorMouseEvent(e, true, this._editorViewDomNode));
            }, (e) => {
                this._keydownListener.dispose();
                onStopCallback(e);
            });
        }
        stopMonitoring() {
            this._globalPointerMoveMonitor.stopMonitoring(true);
        }
    }
    exports.GlobalEditorPointerMoveMonitor = GlobalEditorPointerMoveMonitor;
    /**
     * A helper to create dynamic css rules, bound to a class name.
     * Rules are reused.
     * Reference counting and delayed garbage collection ensure that no rules leak.
    */
    class DynamicCssRules {
        static { this._idPool = 0; }
        constructor(_editor) {
            this._editor = _editor;
            this._instanceId = ++DynamicCssRules._idPool;
            this._counter = 0;
            this._rules = new Map();
            // We delay garbage collection so that hanging rules can be reused.
            this._garbageCollectionScheduler = new async_1.RunOnceScheduler(() => this.garbageCollect(), 1000);
        }
        createClassNameRef(options) {
            const rule = this.getOrCreateRule(options);
            rule.increaseRefCount();
            return {
                className: rule.className,
                dispose: () => {
                    rule.decreaseRefCount();
                    this._garbageCollectionScheduler.schedule();
                }
            };
        }
        getOrCreateRule(properties) {
            const key = this.computeUniqueKey(properties);
            let existingRule = this._rules.get(key);
            if (!existingRule) {
                const counter = this._counter++;
                existingRule = new RefCountedCssRule(key, `dyn-rule-${this._instanceId}-${counter}`, dom.isInShadowDOM(this._editor.getContainerDomNode())
                    ? this._editor.getContainerDomNode()
                    : undefined, properties);
                this._rules.set(key, existingRule);
            }
            return existingRule;
        }
        computeUniqueKey(properties) {
            return JSON.stringify(properties);
        }
        garbageCollect() {
            for (const rule of this._rules.values()) {
                if (!rule.hasReferences()) {
                    this._rules.delete(rule.key);
                    rule.dispose();
                }
            }
        }
    }
    exports.DynamicCssRules = DynamicCssRules;
    class RefCountedCssRule {
        constructor(key, className, _containerElement, properties) {
            this.key = key;
            this.className = className;
            this.properties = properties;
            this._referenceCount = 0;
            this._styleElementDisposables = new lifecycle_1.DisposableStore();
            this._styleElement = dom.createStyleSheet(_containerElement, undefined, this._styleElementDisposables);
            this._styleElement.textContent = this.getCssText(this.className, this.properties);
        }
        getCssText(className, properties) {
            let str = `.${className} {`;
            for (const prop in properties) {
                const value = properties[prop];
                let cssValue;
                if (typeof value === 'object') {
                    cssValue = (0, colorRegistry_1.asCssVariable)(value.id);
                }
                else {
                    cssValue = value;
                }
                const cssPropName = camelToDashes(prop);
                str += `\n\t${cssPropName}: ${cssValue};`;
            }
            str += `\n}`;
            return str;
        }
        dispose() {
            this._styleElementDisposables.dispose();
            this._styleElement = undefined;
        }
        increaseRefCount() {
            this._referenceCount++;
        }
        decreaseRefCount() {
            this._referenceCount--;
        }
        hasReferences() {
            return this._referenceCount > 0;
        }
    }
    function camelToDashes(str) {
        return str.replace(/(^[A-Z])/, ([first]) => first.toLowerCase())
            .replace(/([A-Z])/g, ([letter]) => `-${letter.toLowerCase()}`);
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[755/*vs/editor/browser/viewParts/minimap/minimap*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,39/*vs/base/browser/fastDomNode*/,172/*vs/base/browser/globalPointerMoveMonitor*/,2/*vs/base/common/lifecycle*/,16/*vs/base/common/platform*/,11/*vs/base/common/strings*/,262/*vs/editor/browser/view/viewLayer*/,56/*vs/editor/browser/view/viewPart*/,37/*vs/editor/common/config/editorOptions*/,4/*vs/editor/common/core/range*/,311/*vs/editor/common/core/rgba*/,374/*vs/editor/common/viewModel/minimapTokensColorTracker*/,95/*vs/editor/common/viewModel*/,32/*vs/platform/theme/common/colorRegistry*/,23/*vs/editor/common/core/selection*/,69/*vs/base/browser/touch*/,551/*vs/editor/browser/viewParts/minimap/minimapCharRendererFactory*/,127/*vs/base/common/functional*/,45/*vs/base/common/map*/,347/*vs/base/browser/fonts*/,491/*vs/css!vs/editor/browser/viewParts/minimap/minimap*/]), function (require, exports, dom, fastDomNode_1, globalPointerMoveMonitor_1, lifecycle_1, platform, strings, viewLayer_1, viewPart_1, editorOptions_1, range_1, rgba_1, minimapTokensColorTracker_1, viewModel_1, colorRegistry_1, selection_1, touch_1, minimapCharRendererFactory_1, functional_1, map_1, fonts_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Minimap = void 0;
    /**
     * The orthogonal distance to the slider at which dragging "resets". This implements "snapping"
     */
    const POINTER_DRAG_RESET_DISTANCE = 140;
    const GUTTER_DECORATION_WIDTH = 2;
    class MinimapOptions {
        constructor(configuration, theme, tokensColorTracker) {
            const options = configuration.options;
            const pixelRatio = options.get(144 /* EditorOption.pixelRatio */);
            const layoutInfo = options.get(146 /* EditorOption.layoutInfo */);
            const minimapLayout = layoutInfo.minimap;
            const fontInfo = options.get(50 /* EditorOption.fontInfo */);
            const minimapOpts = options.get(73 /* EditorOption.minimap */);
            this.renderMinimap = minimapLayout.renderMinimap;
            this.size = minimapOpts.size;
            this.minimapHeightIsEditorHeight = minimapLayout.minimapHeightIsEditorHeight;
            this.scrollBeyondLastLine = options.get(106 /* EditorOption.scrollBeyondLastLine */);
            this.paddingTop = options.get(84 /* EditorOption.padding */).top;
            this.paddingBottom = options.get(84 /* EditorOption.padding */).bottom;
            this.showSlider = minimapOpts.showSlider;
            this.autohide = minimapOpts.autohide;
            this.pixelRatio = pixelRatio;
            this.typicalHalfwidthCharacterWidth = fontInfo.typicalHalfwidthCharacterWidth;
            this.lineHeight = options.get(67 /* EditorOption.lineHeight */);
            this.minimapLeft = minimapLayout.minimapLeft;
            this.minimapWidth = minimapLayout.minimapWidth;
            this.minimapHeight = layoutInfo.height;
            this.canvasInnerWidth = minimapLayout.minimapCanvasInnerWidth;
            this.canvasInnerHeight = minimapLayout.minimapCanvasInnerHeight;
            this.canvasOuterWidth = minimapLayout.minimapCanvasOuterWidth;
            this.canvasOuterHeight = minimapLayout.minimapCanvasOuterHeight;
            this.isSampling = minimapLayout.minimapIsSampling;
            this.editorHeight = layoutInfo.height;
            this.fontScale = minimapLayout.minimapScale;
            this.minimapLineHeight = minimapLayout.minimapLineHeight;
            this.minimapCharWidth = 1 /* Constants.BASE_CHAR_WIDTH */ * this.fontScale;
            this.sectionHeaderFontFamily = fonts_1.DEFAULT_FONT_FAMILY;
            this.sectionHeaderFontSize = minimapOpts.sectionHeaderFontSize * pixelRatio;
            this.sectionHeaderLetterSpacing = minimapOpts.sectionHeaderLetterSpacing; // intentionally not multiplying by pixelRatio
            this.sectionHeaderFontColor = MinimapOptions._getSectionHeaderColor(theme, tokensColorTracker.getColor(1 /* ColorId.DefaultForeground */));
            this.charRenderer = (0, functional_1.createSingleCallFunction)(() => minimapCharRendererFactory_1.MinimapCharRendererFactory.create(this.fontScale, fontInfo.fontFamily));
            this.defaultBackgroundColor = tokensColorTracker.getColor(2 /* ColorId.DefaultBackground */);
            this.backgroundColor = MinimapOptions._getMinimapBackground(theme, this.defaultBackgroundColor);
            this.foregroundAlpha = MinimapOptions._getMinimapForegroundOpacity(theme);
        }
        static _getMinimapBackground(theme, defaultBackgroundColor) {
            const themeColor = theme.getColor(colorRegistry_1.minimapBackground);
            if (themeColor) {
                return new rgba_1.RGBA8(themeColor.rgba.r, themeColor.rgba.g, themeColor.rgba.b, Math.round(255 * themeColor.rgba.a));
            }
            return defaultBackgroundColor;
        }
        static _getMinimapForegroundOpacity(theme) {
            const themeColor = theme.getColor(colorRegistry_1.minimapForegroundOpacity);
            if (themeColor) {
                return rgba_1.RGBA8._clamp(Math.round(255 * themeColor.rgba.a));
            }
            return 255;
        }
        static _getSectionHeaderColor(theme, defaultForegroundColor) {
            const themeColor = theme.getColor(colorRegistry_1.editorForeground);
            if (themeColor) {
                return new rgba_1.RGBA8(themeColor.rgba.r, themeColor.rgba.g, themeColor.rgba.b, Math.round(255 * themeColor.rgba.a));
            }
            return defaultForegroundColor;
        }
        equals(other) {
            return (this.renderMinimap === other.renderMinimap
                && this.size === other.size
                && this.minimapHeightIsEditorHeight === other.minimapHeightIsEditorHeight
                && this.scrollBeyondLastLine === other.scrollBeyondLastLine
                && this.paddingTop === other.paddingTop
                && this.paddingBottom === other.paddingBottom
                && this.showSlider === other.showSlider
                && this.autohide === other.autohide
                && this.pixelRatio === other.pixelRatio
                && this.typicalHalfwidthCharacterWidth === other.typicalHalfwidthCharacterWidth
                && this.lineHeight === other.lineHeight
                && this.minimapLeft === other.minimapLeft
                && this.minimapWidth === other.minimapWidth
                && this.minimapHeight === other.minimapHeight
                && this.canvasInnerWidth === other.canvasInnerWidth
                && this.canvasInnerHeight === other.canvasInnerHeight
                && this.canvasOuterWidth === other.canvasOuterWidth
                && this.canvasOuterHeight === other.canvasOuterHeight
                && this.isSampling === other.isSampling
                && this.editorHeight === other.editorHeight
                && this.fontScale === other.fontScale
                && this.minimapLineHeight === other.minimapLineHeight
                && this.minimapCharWidth === other.minimapCharWidth
                && this.sectionHeaderFontSize === other.sectionHeaderFontSize
                && this.sectionHeaderLetterSpacing === other.sectionHeaderLetterSpacing
                && this.defaultBackgroundColor && this.defaultBackgroundColor.equals(other.defaultBackgroundColor)
                && this.backgroundColor && this.backgroundColor.equals(other.backgroundColor)
                && this.foregroundAlpha === other.foregroundAlpha);
        }
    }
    class MinimapLayout {
        constructor(
        /**
         * The given editor scrollTop (input).
         */
        scrollTop, 
        /**
         * The given editor scrollHeight (input).
         */
        scrollHeight, sliderNeeded, _computedSliderRatio, 
        /**
         * slider dom node top (in CSS px)
         */
        sliderTop, 
        /**
         * slider dom node height (in CSS px)
         */
        sliderHeight, 
        /**
         * empty lines to reserve at the top of the minimap.
         */
        topPaddingLineCount, 
        /**
         * minimap render start line number.
         */
        startLineNumber, 
        /**
         * minimap render end line number.
         */
        endLineNumber) {
            this.scrollTop = scrollTop;
            this.scrollHeight = scrollHeight;
            this.sliderNeeded = sliderNeeded;
            this._computedSliderRatio = _computedSliderRatio;
            this.sliderTop = sliderTop;
            this.sliderHeight = sliderHeight;
            this.topPaddingLineCount = topPaddingLineCount;
            this.startLineNumber = startLineNumber;
            this.endLineNumber = endLineNumber;
        }
        /**
         * Compute a desired `scrollPosition` such that the slider moves by `delta`.
         */
        getDesiredScrollTopFromDelta(delta) {
            return Math.round(this.scrollTop + delta / this._computedSliderRatio);
        }
        getDesiredScrollTopFromTouchLocation(pageY) {
            return Math.round((pageY - this.sliderHeight / 2) / this._computedSliderRatio);
        }
        /**
         * Intersect a line range with `this.startLineNumber` and `this.endLineNumber`.
         */
        intersectWithViewport(range) {
            const startLineNumber = Math.max(this.startLineNumber, range.startLineNumber);
            const endLineNumber = Math.min(this.endLineNumber, range.endLineNumber);
            if (startLineNumber > endLineNumber) {
                // entirely outside minimap's viewport
                return null;
            }
            return [startLineNumber, endLineNumber];
        }
        /**
         * Get the inner minimap y coordinate for a line number.
         */
        getYForLineNumber(lineNumber, minimapLineHeight) {
            return +(lineNumber - this.startLineNumber + this.topPaddingLineCount) * minimapLineHeight;
        }
        static create(options, viewportStartLineNumber, viewportEndLineNumber, viewportStartLineNumberVerticalOffset, viewportHeight, viewportContainsWhitespaceGaps, lineCount, realLineCount, scrollTop, scrollHeight, previousLayout) {
            const pixelRatio = options.pixelRatio;
            const minimapLineHeight = options.minimapLineHeight;
            const minimapLinesFitting = Math.floor(options.canvasInnerHeight / minimapLineHeight);
            const lineHeight = options.lineHeight;
            if (options.minimapHeightIsEditorHeight) {
                let logicalScrollHeight = (realLineCount * options.lineHeight
                    + options.paddingTop
                    + options.paddingBottom);
                if (options.scrollBeyondLastLine) {
                    logicalScrollHeight += Math.max(0, viewportHeight - options.lineHeight - options.paddingBottom);
                }
                const sliderHeight = Math.max(1, Math.floor(viewportHeight * viewportHeight / logicalScrollHeight));
                const maxMinimapSliderTop = Math.max(0, options.minimapHeight - sliderHeight);
                // The slider can move from 0 to `maxMinimapSliderTop`
                // in the same way `scrollTop` can move from 0 to `scrollHeight` - `viewportHeight`.
                const computedSliderRatio = (maxMinimapSliderTop) / (scrollHeight - viewportHeight);
                const sliderTop = (scrollTop * computedSliderRatio);
                const sliderNeeded = (maxMinimapSliderTop > 0);
                const maxLinesFitting = Math.floor(options.canvasInnerHeight / options.minimapLineHeight);
                const topPaddingLineCount = Math.floor(options.paddingTop / options.lineHeight);
                return new MinimapLayout(scrollTop, scrollHeight, sliderNeeded, computedSliderRatio, sliderTop, sliderHeight, topPaddingLineCount, 1, Math.min(lineCount, maxLinesFitting));
            }
            // The visible line count in a viewport can change due to a number of reasons:
            //  a) with the same viewport width, different scroll positions can result in partial lines being visible:
            //    e.g. for a line height of 20, and a viewport height of 600
            //          * scrollTop = 0  => visible lines are [1, 30]
            //          * scrollTop = 10 => visible lines are [1, 31] (with lines 1 and 31 partially visible)
            //          * scrollTop = 20 => visible lines are [2, 31]
            //  b) whitespace gaps might make their way in the viewport (which results in a decrease in the visible line count)
            //  c) we could be in the scroll beyond last line case (which also results in a decrease in the visible line count, down to possibly only one line being visible)
            // We must first establish a desirable slider height.
            let sliderHeight;
            if (viewportContainsWhitespaceGaps && viewportEndLineNumber !== lineCount) {
                // case b) from above: there are whitespace gaps in the viewport.
                // In this case, the height of the slider directly reflects the visible line count.
                const viewportLineCount = viewportEndLineNumber - viewportStartLineNumber + 1;
                sliderHeight = Math.floor(viewportLineCount * minimapLineHeight / pixelRatio);
            }
            else {
                // The slider has a stable height
                const expectedViewportLineCount = viewportHeight / lineHeight;
                sliderHeight = Math.floor(expectedViewportLineCount * minimapLineHeight / pixelRatio);
            }
            const extraLinesAtTheTop = Math.floor(options.paddingTop / lineHeight);
            let extraLinesAtTheBottom = Math.floor(options.paddingBottom / lineHeight);
            if (options.scrollBeyondLastLine) {
                const expectedViewportLineCount = viewportHeight / lineHeight;
                extraLinesAtTheBottom = Math.max(extraLinesAtTheBottom, expectedViewportLineCount - 1);
            }
            let maxMinimapSliderTop;
            if (extraLinesAtTheBottom > 0) {
                const expectedViewportLineCount = viewportHeight / lineHeight;
                // The minimap slider, when dragged all the way down, will contain the last line at its top
                maxMinimapSliderTop = (extraLinesAtTheTop + lineCount + extraLinesAtTheBottom - expectedViewportLineCount - 1) * minimapLineHeight / pixelRatio;
            }
            else {
                // The minimap slider, when dragged all the way down, will contain the last line at its bottom
                maxMinimapSliderTop = Math.max(0, (extraLinesAtTheTop + lineCount) * minimapLineHeight / pixelRatio - sliderHeight);
            }
            maxMinimapSliderTop = Math.min(options.minimapHeight - sliderHeight, maxMinimapSliderTop);
            // The slider can move from 0 to `maxMinimapSliderTop`
            // in the same way `scrollTop` can move from 0 to `scrollHeight` - `viewportHeight`.
            const computedSliderRatio = (maxMinimapSliderTop) / (scrollHeight - viewportHeight);
            const sliderTop = (scrollTop * computedSliderRatio);
            if (minimapLinesFitting >= extraLinesAtTheTop + lineCount + extraLinesAtTheBottom) {
                // All lines fit in the minimap
                const sliderNeeded = (maxMinimapSliderTop > 0);
                return new MinimapLayout(scrollTop, scrollHeight, sliderNeeded, computedSliderRatio, sliderTop, sliderHeight, extraLinesAtTheTop, 1, lineCount);
            }
            else {
                let consideringStartLineNumber;
                if (viewportStartLineNumber > 1) {
                    consideringStartLineNumber = viewportStartLineNumber + extraLinesAtTheTop;
                }
                else {
                    consideringStartLineNumber = Math.max(1, scrollTop / lineHeight);
                }
                let topPaddingLineCount;
                let startLineNumber = Math.max(1, Math.floor(consideringStartLineNumber - sliderTop * pixelRatio / minimapLineHeight));
                if (startLineNumber < extraLinesAtTheTop) {
                    topPaddingLineCount = extraLinesAtTheTop - startLineNumber + 1;
                    startLineNumber = 1;
                }
                else {
                    topPaddingLineCount = 0;
                    startLineNumber = Math.max(1, startLineNumber - extraLinesAtTheTop);
                }
                // Avoid flickering caused by a partial viewport start line
                // by being consistent w.r.t. the previous layout decision
                if (previousLayout && previousLayout.scrollHeight === scrollHeight) {
                    if (previousLayout.scrollTop > scrollTop) {
                        // Scrolling up => never increase `startLineNumber`
                        startLineNumber = Math.min(startLineNumber, previousLayout.startLineNumber);
                        topPaddingLineCount = Math.max(topPaddingLineCount, previousLayout.topPaddingLineCount);
                    }
                    if (previousLayout.scrollTop < scrollTop) {
                        // Scrolling down => never decrease `startLineNumber`
                        startLineNumber = Math.max(startLineNumber, previousLayout.startLineNumber);
                        topPaddingLineCount = Math.min(topPaddingLineCount, previousLayout.topPaddingLineCount);
                    }
                }
                const endLineNumber = Math.min(lineCount, startLineNumber - topPaddingLineCount + minimapLinesFitting - 1);
                const partialLine = (scrollTop - viewportStartLineNumberVerticalOffset) / lineHeight;
                let sliderTopAligned;
                if (scrollTop >= options.paddingTop) {
                    sliderTopAligned = (viewportStartLineNumber - startLineNumber + topPaddingLineCount + partialLine) * minimapLineHeight / pixelRatio;
                }
                else {
                    sliderTopAligned = (scrollTop / options.paddingTop) * (topPaddingLineCount + partialLine) * minimapLineHeight / pixelRatio;
                }
                return new MinimapLayout(scrollTop, scrollHeight, true, computedSliderRatio, sliderTopAligned, sliderHeight, topPaddingLineCount, startLineNumber, endLineNumber);
            }
        }
    }
    class MinimapLine {
        static { this.INVALID = new MinimapLine(-1); }
        constructor(dy) {
            this.dy = dy;
        }
        onContentChanged() {
            this.dy = -1;
        }
        onTokensChanged() {
            this.dy = -1;
        }
    }
    class RenderData {
        constructor(renderedLayout, imageData, lines) {
            this.renderedLayout = renderedLayout;
            this._imageData = imageData;
            this._renderedLines = new viewLayer_1.RenderedLinesCollection({
                createLine: () => MinimapLine.INVALID
            });
            this._renderedLines._set(renderedLayout.startLineNumber, lines);
        }
        /**
         * Check if the current RenderData matches accurately the new desired layout and no painting is needed.
         */
        linesEquals(layout) {
            if (!this.scrollEquals(layout)) {
                return false;
            }
            const tmp = this._renderedLines._get();
            const lines = tmp.lines;
            for (let i = 0, len = lines.length; i < len; i++) {
                if (lines[i].dy === -1) {
                    // This line is invalid
                    return false;
                }
            }
            return true;
        }
        /**
         * Check if the current RenderData matches the new layout's scroll position
         */
        scrollEquals(layout) {
            return this.renderedLayout.startLineNumber === layout.startLineNumber
                && this.renderedLayout.endLineNumber === layout.endLineNumber;
        }
        _get() {
            const tmp = this._renderedLines._get();
            return {
                imageData: this._imageData,
                rendLineNumberStart: tmp.rendLineNumberStart,
                lines: tmp.lines
            };
        }
        onLinesChanged(changeFromLineNumber, changeCount) {
            return this._renderedLines.onLinesChanged(changeFromLineNumber, changeCount);
        }
        onLinesDeleted(deleteFromLineNumber, deleteToLineNumber) {
            this._renderedLines.onLinesDeleted(deleteFromLineNumber, deleteToLineNumber);
        }
        onLinesInserted(insertFromLineNumber, insertToLineNumber) {
            this._renderedLines.onLinesInserted(insertFromLineNumber, insertToLineNumber);
        }
        onTokensChanged(ranges) {
            return this._renderedLines.onTokensChanged(ranges);
        }
    }
    /**
     * Some sort of double buffering.
     *
     * Keeps two buffers around that will be rotated for painting.
     * Always gives a buffer that is filled with the background color.
     */
    class MinimapBuffers {
        constructor(ctx, WIDTH, HEIGHT, background) {
            this._backgroundFillData = MinimapBuffers._createBackgroundFillData(WIDTH, HEIGHT, background);
            this._buffers = [
                ctx.createImageData(WIDTH, HEIGHT),
                ctx.createImageData(WIDTH, HEIGHT)
            ];
            this._lastUsedBuffer = 0;
        }
        getBuffer() {
            // rotate buffers
            this._lastUsedBuffer = 1 - this._lastUsedBuffer;
            const result = this._buffers[this._lastUsedBuffer];
            // fill with background color
            result.data.set(this._backgroundFillData);
            return result;
        }
        static _createBackgroundFillData(WIDTH, HEIGHT, background) {
            const backgroundR = background.r;
            const backgroundG = background.g;
            const backgroundB = background.b;
            const backgroundA = background.a;
            const result = new Uint8ClampedArray(WIDTH * HEIGHT * 4);
            let offset = 0;
            for (let i = 0; i < HEIGHT; i++) {
                for (let j = 0; j < WIDTH; j++) {
                    result[offset] = backgroundR;
                    result[offset + 1] = backgroundG;
                    result[offset + 2] = backgroundB;
                    result[offset + 3] = backgroundA;
                    offset += 4;
                }
            }
            return result;
        }
    }
    class MinimapSamplingState {
        static compute(options, viewLineCount, oldSamplingState) {
            if (options.renderMinimap === 0 /* RenderMinimap.None */ || !options.isSampling) {
                return [null, []];
            }
            // ratio is intentionally not part of the layout to avoid the layout changing all the time
            // so we need to recompute it again...
            const { minimapLineCount } = editorOptions_1.EditorLayoutInfoComputer.computeContainedMinimapLineCount({
                viewLineCount: viewLineCount,
                scrollBeyondLastLine: options.scrollBeyondLastLine,
                paddingTop: options.paddingTop,
                paddingBottom: options.paddingBottom,
                height: options.editorHeight,
                lineHeight: options.lineHeight,
                pixelRatio: options.pixelRatio
            });
            const ratio = viewLineCount / minimapLineCount;
            const halfRatio = ratio / 2;
            if (!oldSamplingState || oldSamplingState.minimapLines.length === 0) {
                const result = [];
                result[0] = 1;
                if (minimapLineCount > 1) {
                    for (let i = 0, lastIndex = minimapLineCount - 1; i < lastIndex; i++) {
                        result[i] = Math.round(i * ratio + halfRatio);
                    }
                    result[minimapLineCount - 1] = viewLineCount;
                }
                return [new MinimapSamplingState(ratio, result), []];
            }
            const oldMinimapLines = oldSamplingState.minimapLines;
            const oldLength = oldMinimapLines.length;
            const result = [];
            let oldIndex = 0;
            let oldDeltaLineCount = 0;
            let minViewLineNumber = 1;
            const MAX_EVENT_COUNT = 10; // generate at most 10 events, if there are more than 10 changes, just flush all previous data
            let events = [];
            let lastEvent = null;
            for (let i = 0; i < minimapLineCount; i++) {
                const fromViewLineNumber = Math.max(minViewLineNumber, Math.round(i * ratio));
                const toViewLineNumber = Math.max(fromViewLineNumber, Math.round((i + 1) * ratio));
                while (oldIndex < oldLength && oldMinimapLines[oldIndex] < fromViewLineNumber) {
                    if (events.length < MAX_EVENT_COUNT) {
                        const oldMinimapLineNumber = oldIndex + 1 + oldDeltaLineCount;
                        if (lastEvent && lastEvent.type === 'deleted' && lastEvent._oldIndex === oldIndex - 1) {
                            lastEvent.deleteToLineNumber++;
                        }
                        else {
                            lastEvent = { type: 'deleted', _oldIndex: oldIndex, deleteFromLineNumber: oldMinimapLineNumber, deleteToLineNumber: oldMinimapLineNumber };
                            events.push(lastEvent);
                        }
                        oldDeltaLineCount--;
                    }
                    oldIndex++;
                }
                let selectedViewLineNumber;
                if (oldIndex < oldLength && oldMinimapLines[oldIndex] <= toViewLineNumber) {
                    // reuse the old sampled line
                    selectedViewLineNumber = oldMinimapLines[oldIndex];
                    oldIndex++;
                }
                else {
                    if (i === 0) {
                        selectedViewLineNumber = 1;
                    }
                    else if (i + 1 === minimapLineCount) {
                        selectedViewLineNumber = viewLineCount;
                    }
                    else {
                        selectedViewLineNumber = Math.round(i * ratio + halfRatio);
                    }
                    if (events.length < MAX_EVENT_COUNT) {
                        const oldMinimapLineNumber = oldIndex + 1 + oldDeltaLineCount;
                        if (lastEvent && lastEvent.type === 'inserted' && lastEvent._i === i - 1) {
                            lastEvent.insertToLineNumber++;
                        }
                        else {
                            lastEvent = { type: 'inserted', _i: i, insertFromLineNumber: oldMinimapLineNumber, insertToLineNumber: oldMinimapLineNumber };
                            events.push(lastEvent);
                        }
                        oldDeltaLineCount++;
                    }
                }
                result[i] = selectedViewLineNumber;
                minViewLineNumber = selectedViewLineNumber;
            }
            if (events.length < MAX_EVENT_COUNT) {
                while (oldIndex < oldLength) {
                    const oldMinimapLineNumber = oldIndex + 1 + oldDeltaLineCount;
                    if (lastEvent && lastEvent.type === 'deleted' && lastEvent._oldIndex === oldIndex - 1) {
                        lastEvent.deleteToLineNumber++;
                    }
                    else {
                        lastEvent = { type: 'deleted', _oldIndex: oldIndex, deleteFromLineNumber: oldMinimapLineNumber, deleteToLineNumber: oldMinimapLineNumber };
                        events.push(lastEvent);
                    }
                    oldDeltaLineCount--;
                    oldIndex++;
                }
            }
            else {
                // too many events, just give up
                events = [{ type: 'flush' }];
            }
            return [new MinimapSamplingState(ratio, result), events];
        }
        constructor(samplingRatio, minimapLines // a map of 0-based minimap line indexes to 1-based view line numbers
        ) {
            this.samplingRatio = samplingRatio;
            this.minimapLines = minimapLines;
        }
        modelLineToMinimapLine(lineNumber) {
            return Math.min(this.minimapLines.length, Math.max(1, Math.round(lineNumber / this.samplingRatio)));
        }
        /**
         * Will return null if the model line ranges are not intersecting with a sampled model line.
         */
        modelLineRangeToMinimapLineRange(fromLineNumber, toLineNumber) {
            let fromLineIndex = this.modelLineToMinimapLine(fromLineNumber) - 1;
            while (fromLineIndex > 0 && this.minimapLines[fromLineIndex - 1] >= fromLineNumber) {
                fromLineIndex--;
            }
            let toLineIndex = this.modelLineToMinimapLine(toLineNumber) - 1;
            while (toLineIndex + 1 < this.minimapLines.length && this.minimapLines[toLineIndex + 1] <= toLineNumber) {
                toLineIndex++;
            }
            if (fromLineIndex === toLineIndex) {
                const sampledLineNumber = this.minimapLines[fromLineIndex];
                if (sampledLineNumber < fromLineNumber || sampledLineNumber > toLineNumber) {
                    // This line is not part of the sampled lines ==> nothing to do
                    return null;
                }
            }
            return [fromLineIndex + 1, toLineIndex + 1];
        }
        /**
         * Will always return a range, even if it is not intersecting with a sampled model line.
         */
        decorationLineRangeToMinimapLineRange(startLineNumber, endLineNumber) {
            let minimapLineStart = this.modelLineToMinimapLine(startLineNumber);
            let minimapLineEnd = this.modelLineToMinimapLine(endLineNumber);
            if (startLineNumber !== endLineNumber && minimapLineEnd === minimapLineStart) {
                if (minimapLineEnd === this.minimapLines.length) {
                    if (minimapLineStart > 1) {
                        minimapLineStart--;
                    }
                }
                else {
                    minimapLineEnd++;
                }
            }
            return [minimapLineStart, minimapLineEnd];
        }
        onLinesDeleted(e) {
            // have the mapping be sticky
            const deletedLineCount = e.toLineNumber - e.fromLineNumber + 1;
            let changeStartIndex = this.minimapLines.length;
            let changeEndIndex = 0;
            for (let i = this.minimapLines.length - 1; i >= 0; i--) {
                if (this.minimapLines[i] < e.fromLineNumber) {
                    break;
                }
                if (this.minimapLines[i] <= e.toLineNumber) {
                    // this line got deleted => move to previous available
                    this.minimapLines[i] = Math.max(1, e.fromLineNumber - 1);
                    changeStartIndex = Math.min(changeStartIndex, i);
                    changeEndIndex = Math.max(changeEndIndex, i);
                }
                else {
                    this.minimapLines[i] -= deletedLineCount;
                }
            }
            return [changeStartIndex, changeEndIndex];
        }
        onLinesInserted(e) {
            // have the mapping be sticky
            const insertedLineCount = e.toLineNumber - e.fromLineNumber + 1;
            for (let i = this.minimapLines.length - 1; i >= 0; i--) {
                if (this.minimapLines[i] < e.fromLineNumber) {
                    break;
                }
                this.minimapLines[i] += insertedLineCount;
            }
        }
    }
    class Minimap extends viewPart_1.ViewPart {
        constructor(context) {
            super(context);
            this._sectionHeaderCache = new map_1.LRUCache(10, 1.5);
            this.tokensColorTracker = minimapTokensColorTracker_1.MinimapTokensColorTracker.getInstance();
            this._selections = [];
            this._minimapSelections = null;
            this.options = new MinimapOptions(this._context.configuration, this._context.theme, this.tokensColorTracker);
            const [samplingState,] = MinimapSamplingState.compute(this.options, this._context.viewModel.getLineCount(), null);
            this._samplingState = samplingState;
            this._shouldCheckSampling = false;
            this._actual = new InnerMinimap(context.theme, this);
        }
        dispose() {
            this._actual.dispose();
            super.dispose();
        }
        getDomNode() {
            return this._actual.getDomNode();
        }
        _onOptionsMaybeChanged() {
            const opts = new MinimapOptions(this._context.configuration, this._context.theme, this.tokensColorTracker);
            if (this.options.equals(opts)) {
                return false;
            }
            this.options = opts;
            this._recreateLineSampling();
            this._actual.onDidChangeOptions();
            return true;
        }
        // ---- begin view event handlers
        onConfigurationChanged(e) {
            return this._onOptionsMaybeChanged();
        }
        onCursorStateChanged(e) {
            this._selections = e.selections;
            this._minimapSelections = null;
            return this._actual.onSelectionChanged();
        }
        onDecorationsChanged(e) {
            if (e.affectsMinimap) {
                return this._actual.onDecorationsChanged();
            }
            return false;
        }
        onFlushed(e) {
            if (this._samplingState) {
                this._shouldCheckSampling = true;
            }
            return this._actual.onFlushed();
        }
        onLinesChanged(e) {
            if (this._samplingState) {
                const minimapLineRange = this._samplingState.modelLineRangeToMinimapLineRange(e.fromLineNumber, e.fromLineNumber + e.count - 1);
                if (minimapLineRange) {
                    return this._actual.onLinesChanged(minimapLineRange[0], minimapLineRange[1] - minimapLineRange[0] + 1);
                }
                else {
                    return false;
                }
            }
            else {
                return this._actual.onLinesChanged(e.fromLineNumber, e.count);
            }
        }
        onLinesDeleted(e) {
            if (this._samplingState) {
                const [changeStartIndex, changeEndIndex] = this._samplingState.onLinesDeleted(e);
                if (changeStartIndex <= changeEndIndex) {
                    this._actual.onLinesChanged(changeStartIndex + 1, changeEndIndex - changeStartIndex + 1);
                }
                this._shouldCheckSampling = true;
                return true;
            }
            else {
                return this._actual.onLinesDeleted(e.fromLineNumber, e.toLineNumber);
            }
        }
        onLinesInserted(e) {
            if (this._samplingState) {
                this._samplingState.onLinesInserted(e);
                this._shouldCheckSampling = true;
                return true;
            }
            else {
                return this._actual.onLinesInserted(e.fromLineNumber, e.toLineNumber);
            }
        }
        onScrollChanged(e) {
            return this._actual.onScrollChanged();
        }
        onThemeChanged(e) {
            this._actual.onThemeChanged();
            this._onOptionsMaybeChanged();
            return true;
        }
        onTokensChanged(e) {
            if (this._samplingState) {
                const ranges = [];
                for (const range of e.ranges) {
                    const minimapLineRange = this._samplingState.modelLineRangeToMinimapLineRange(range.fromLineNumber, range.toLineNumber);
                    if (minimapLineRange) {
                        ranges.push({ fromLineNumber: minimapLineRange[0], toLineNumber: minimapLineRange[1] });
                    }
                }
                if (ranges.length) {
                    return this._actual.onTokensChanged(ranges);
                }
                else {
                    return false;
                }
            }
            else {
                return this._actual.onTokensChanged(e.ranges);
            }
        }
        onTokensColorsChanged(e) {
            this._onOptionsMaybeChanged();
            return this._actual.onTokensColorsChanged();
        }
        onZonesChanged(e) {
            return this._actual.onZonesChanged();
        }
        // --- end event handlers
        prepareRender(ctx) {
            if (this._shouldCheckSampling) {
                this._shouldCheckSampling = false;
                this._recreateLineSampling();
            }
        }
        render(ctx) {
            let viewportStartLineNumber = ctx.visibleRange.startLineNumber;
            let viewportEndLineNumber = ctx.visibleRange.endLineNumber;
            if (this._samplingState) {
                viewportStartLineNumber = this._samplingState.modelLineToMinimapLine(viewportStartLineNumber);
                viewportEndLineNumber = this._samplingState.modelLineToMinimapLine(viewportEndLineNumber);
            }
            const minimapCtx = {
                viewportContainsWhitespaceGaps: (ctx.viewportData.whitespaceViewportData.length > 0),
                scrollWidth: ctx.scrollWidth,
                scrollHeight: ctx.scrollHeight,
                viewportStartLineNumber: viewportStartLineNumber,
                viewportEndLineNumber: viewportEndLineNumber,
                viewportStartLineNumberVerticalOffset: ctx.getVerticalOffsetForLineNumber(viewportStartLineNumber),
                scrollTop: ctx.scrollTop,
                scrollLeft: ctx.scrollLeft,
                viewportWidth: ctx.viewportWidth,
                viewportHeight: ctx.viewportHeight,
            };
            this._actual.render(minimapCtx);
        }
        //#region IMinimapModel
        _recreateLineSampling() {
            this._minimapSelections = null;
            const wasSampling = Boolean(this._samplingState);
            const [samplingState, events] = MinimapSamplingState.compute(this.options, this._context.viewModel.getLineCount(), this._samplingState);
            this._samplingState = samplingState;
            if (wasSampling && this._samplingState) {
                // was sampling, is sampling
                for (const event of events) {
                    switch (event.type) {
                        case 'deleted':
                            this._actual.onLinesDeleted(event.deleteFromLineNumber, event.deleteToLineNumber);
                            break;
                        case 'inserted':
                            this._actual.onLinesInserted(event.insertFromLineNumber, event.insertToLineNumber);
                            break;
                        case 'flush':
                            this._actual.onFlushed();
                            break;
                    }
                }
            }
        }
        getLineCount() {
            if (this._samplingState) {
                return this._samplingState.minimapLines.length;
            }
            return this._context.viewModel.getLineCount();
        }
        getRealLineCount() {
            return this._context.viewModel.getLineCount();
        }
        getLineContent(lineNumber) {
            if (this._samplingState) {
                return this._context.viewModel.getLineContent(this._samplingState.minimapLines[lineNumber - 1]);
            }
            return this._context.viewModel.getLineContent(lineNumber);
        }
        getLineMaxColumn(lineNumber) {
            if (this._samplingState) {
                return this._context.viewModel.getLineMaxColumn(this._samplingState.minimapLines[lineNumber - 1]);
            }
            return this._context.viewModel.getLineMaxColumn(lineNumber);
        }
        getMinimapLinesRenderingData(startLineNumber, endLineNumber, needed) {
            if (this._samplingState) {
                const result = [];
                for (let lineIndex = 0, lineCount = endLineNumber - startLineNumber + 1; lineIndex < lineCount; lineIndex++) {
                    if (needed[lineIndex]) {
                        result[lineIndex] = this._context.viewModel.getViewLineData(this._samplingState.minimapLines[startLineNumber + lineIndex - 1]);
                    }
                    else {
                        result[lineIndex] = null;
                    }
                }
                return result;
            }
            return this._context.viewModel.getMinimapLinesRenderingData(startLineNumber, endLineNumber, needed).data;
        }
        getSelections() {
            if (this._minimapSelections === null) {
                if (this._samplingState) {
                    this._minimapSelections = [];
                    for (const selection of this._selections) {
                        const [minimapLineStart, minimapLineEnd] = this._samplingState.decorationLineRangeToMinimapLineRange(selection.startLineNumber, selection.endLineNumber);
                        this._minimapSelections.push(new selection_1.Selection(minimapLineStart, selection.startColumn, minimapLineEnd, selection.endColumn));
                    }
                }
                else {
                    this._minimapSelections = this._selections;
                }
            }
            return this._minimapSelections;
        }
        getMinimapDecorationsInViewport(startLineNumber, endLineNumber) {
            const decorations = this._getMinimapDecorationsInViewport(startLineNumber, endLineNumber)
                .filter(decoration => !decoration.options.minimap?.sectionHeaderStyle);
            if (this._samplingState) {
                const result = [];
                for (const decoration of decorations) {
                    if (!decoration.options.minimap) {
                        continue;
                    }
                    const range = decoration.range;
                    const minimapStartLineNumber = this._samplingState.modelLineToMinimapLine(range.startLineNumber);
                    const minimapEndLineNumber = this._samplingState.modelLineToMinimapLine(range.endLineNumber);
                    result.push(new viewModel_1.ViewModelDecoration(new range_1.Range(minimapStartLineNumber, range.startColumn, minimapEndLineNumber, range.endColumn), decoration.options));
                }
                return result;
            }
            return decorations;
        }
        getSectionHeaderDecorationsInViewport(startLineNumber, endLineNumber) {
            const minimapLineHeight = this.options.minimapLineHeight;
            const sectionHeaderFontSize = this.options.sectionHeaderFontSize;
            const headerHeightInMinimapLines = sectionHeaderFontSize / minimapLineHeight;
            startLineNumber = Math.floor(Math.max(1, startLineNumber - headerHeightInMinimapLines));
            return this._getMinimapDecorationsInViewport(startLineNumber, endLineNumber)
                .filter(decoration => !!decoration.options.minimap?.sectionHeaderStyle);
        }
        _getMinimapDecorationsInViewport(startLineNumber, endLineNumber) {
            let visibleRange;
            if (this._samplingState) {
                const modelStartLineNumber = this._samplingState.minimapLines[startLineNumber - 1];
                const modelEndLineNumber = this._samplingState.minimapLines[endLineNumber - 1];
                visibleRange = new range_1.Range(modelStartLineNumber, 1, modelEndLineNumber, this._context.viewModel.getLineMaxColumn(modelEndLineNumber));
            }
            else {
                visibleRange = new range_1.Range(startLineNumber, 1, endLineNumber, this._context.viewModel.getLineMaxColumn(endLineNumber));
            }
            return this._context.viewModel.getMinimapDecorationsInRange(visibleRange);
        }
        getSectionHeaderText(decoration, fitWidth) {
            const headerText = decoration.options.minimap?.sectionHeaderText;
            if (!headerText) {
                return null;
            }
            const cachedText = this._sectionHeaderCache.get(headerText);
            if (cachedText) {
                return cachedText;
            }
            const fittedText = fitWidth(headerText);
            this._sectionHeaderCache.set(headerText, fittedText);
            return fittedText;
        }
        getOptions() {
            return this._context.viewModel.model.getOptions();
        }
        revealLineNumber(lineNumber) {
            if (this._samplingState) {
                lineNumber = this._samplingState.minimapLines[lineNumber - 1];
            }
            this._context.viewModel.revealRange('mouse', false, new range_1.Range(lineNumber, 1, lineNumber, 1), 1 /* viewEvents.VerticalRevealType.Center */, 0 /* ScrollType.Smooth */);
        }
        setScrollTop(scrollTop) {
            this._context.viewModel.viewLayout.setScrollPosition({
                scrollTop: scrollTop
            }, 1 /* ScrollType.Immediate */);
        }
    }
    exports.Minimap = Minimap;
    class InnerMinimap extends lifecycle_1.Disposable {
        constructor(theme, model) {
            super();
            this._renderDecorations = false;
            this._gestureInProgress = false;
            this._theme = theme;
            this._model = model;
            this._lastRenderData = null;
            this._buffers = null;
            this._selectionColor = this._theme.getColor(colorRegistry_1.minimapSelection);
            this._domNode = (0, fastDomNode_1.createFastDomNode)(document.createElement('div'));
            viewPart_1.PartFingerprints.write(this._domNode, 9 /* PartFingerprint.Minimap */);
            this._domNode.setClassName(this._getMinimapDomNodeClassName());
            this._domNode.setPosition('absolute');
            this._domNode.setAttribute('role', 'presentation');
            this._domNode.setAttribute('aria-hidden', 'true');
            this._shadow = (0, fastDomNode_1.createFastDomNode)(document.createElement('div'));
            this._shadow.setClassName('minimap-shadow-hidden');
            this._domNode.appendChild(this._shadow);
            this._canvas = (0, fastDomNode_1.createFastDomNode)(document.createElement('canvas'));
            this._canvas.setPosition('absolute');
            this._canvas.setLeft(0);
            this._domNode.appendChild(this._canvas);
            this._decorationsCanvas = (0, fastDomNode_1.createFastDomNode)(document.createElement('canvas'));
            this._decorationsCanvas.setPosition('absolute');
            this._decorationsCanvas.setClassName('minimap-decorations-layer');
            this._decorationsCanvas.setLeft(0);
            this._domNode.appendChild(this._decorationsCanvas);
            this._slider = (0, fastDomNode_1.createFastDomNode)(document.createElement('div'));
            this._slider.setPosition('absolute');
            this._slider.setClassName('minimap-slider');
            this._slider.setLayerHinting(true);
            this._slider.setContain('strict');
            this._domNode.appendChild(this._slider);
            this._sliderHorizontal = (0, fastDomNode_1.createFastDomNode)(document.createElement('div'));
            this._sliderHorizontal.setPosition('absolute');
            this._sliderHorizontal.setClassName('minimap-slider-horizontal');
            this._slider.appendChild(this._sliderHorizontal);
            this._applyLayout();
            this._pointerDownListener = dom.addStandardDisposableListener(this._domNode.domNode, dom.EventType.POINTER_DOWN, (e) => {
                e.preventDefault();
                const renderMinimap = this._model.options.renderMinimap;
                if (renderMinimap === 0 /* RenderMinimap.None */) {
                    return;
                }
                if (!this._lastRenderData) {
                    return;
                }
                if (this._model.options.size !== 'proportional') {
                    if (e.button === 0 && this._lastRenderData) {
                        // pretend the click occurred in the center of the slider
                        const position = dom.getDomNodePagePosition(this._slider.domNode);
                        const initialPosY = position.top + position.height / 2;
                        this._startSliderDragging(e, initialPosY, this._lastRenderData.renderedLayout);
                    }
                    return;
                }
                const minimapLineHeight = this._model.options.minimapLineHeight;
                const internalOffsetY = (this._model.options.canvasInnerHeight / this._model.options.canvasOuterHeight) * e.offsetY;
                const lineIndex = Math.floor(internalOffsetY / minimapLineHeight);
                let lineNumber = lineIndex + this._lastRenderData.renderedLayout.startLineNumber - this._lastRenderData.renderedLayout.topPaddingLineCount;
                lineNumber = Math.min(lineNumber, this._model.getLineCount());
                this._model.revealLineNumber(lineNumber);
            });
            this._sliderPointerMoveMonitor = new globalPointerMoveMonitor_1.GlobalPointerMoveMonitor();
            this._sliderPointerDownListener = dom.addStandardDisposableListener(this._slider.domNode, dom.EventType.POINTER_DOWN, (e) => {
                e.preventDefault();
                e.stopPropagation();
                if (e.button === 0 && this._lastRenderData) {
                    this._startSliderDragging(e, e.pageY, this._lastRenderData.renderedLayout);
                }
            });
            this._gestureDisposable = touch_1.Gesture.addTarget(this._domNode.domNode);
            this._sliderTouchStartListener = dom.addDisposableListener(this._domNode.domNode, touch_1.EventType.Start, (e) => {
                e.preventDefault();
                e.stopPropagation();
                if (this._lastRenderData) {
                    this._slider.toggleClassName('active', true);
                    this._gestureInProgress = true;
                    this.scrollDueToTouchEvent(e);
                }
            }, { passive: false });
            this._sliderTouchMoveListener = dom.addDisposableListener(this._domNode.domNode, touch_1.EventType.Change, (e) => {
                e.preventDefault();
                e.stopPropagation();
                if (this._lastRenderData && this._gestureInProgress) {
                    this.scrollDueToTouchEvent(e);
                }
            }, { passive: false });
            this._sliderTouchEndListener = dom.addStandardDisposableListener(this._domNode.domNode, touch_1.EventType.End, (e) => {
                e.preventDefault();
                e.stopPropagation();
                this._gestureInProgress = false;
                this._slider.toggleClassName('active', false);
            });
        }
        _startSliderDragging(e, initialPosY, initialSliderState) {
            if (!e.target || !(e.target instanceof Element)) {
                return;
            }
            const initialPosX = e.pageX;
            this._slider.toggleClassName('active', true);
            const handlePointerMove = (posy, posx) => {
                const minimapPosition = dom.getDomNodePagePosition(this._domNode.domNode);
                const pointerOrthogonalDelta = Math.min(Math.abs(posx - initialPosX), Math.abs(posx - minimapPosition.left), Math.abs(posx - minimapPosition.left - minimapPosition.width));
                if (platform.isWindows && pointerOrthogonalDelta > POINTER_DRAG_RESET_DISTANCE) {
                    // The pointer has wondered away from the scrollbar => reset dragging
                    this._model.setScrollTop(initialSliderState.scrollTop);
                    return;
                }
                const pointerDelta = posy - initialPosY;
                this._model.setScrollTop(initialSliderState.getDesiredScrollTopFromDelta(pointerDelta));
            };
            if (e.pageY !== initialPosY) {
                handlePointerMove(e.pageY, initialPosX);
            }
            this._sliderPointerMoveMonitor.startMonitoring(e.target, e.pointerId, e.buttons, pointerMoveData => handlePointerMove(pointerMoveData.pageY, pointerMoveData.pageX), () => {
                this._slider.toggleClassName('active', false);
            });
        }
        scrollDueToTouchEvent(touch) {
            const startY = this._domNode.domNode.getBoundingClientRect().top;
            const scrollTop = this._lastRenderData.renderedLayout.getDesiredScrollTopFromTouchLocation(touch.pageY - startY);
            this._model.setScrollTop(scrollTop);
        }
        dispose() {
            this._pointerDownListener.dispose();
            this._sliderPointerMoveMonitor.dispose();
            this._sliderPointerDownListener.dispose();
            this._gestureDisposable.dispose();
            this._sliderTouchStartListener.dispose();
            this._sliderTouchMoveListener.dispose();
            this._sliderTouchEndListener.dispose();
            super.dispose();
        }
        _getMinimapDomNodeClassName() {
            const class_ = ['minimap'];
            if (this._model.options.showSlider === 'always') {
                class_.push('slider-always');
            }
            else {
                class_.push('slider-mouseover');
            }
            if (this._model.options.autohide) {
                class_.push('autohide');
            }
            return class_.join(' ');
        }
        getDomNode() {
            return this._domNode;
        }
        _applyLayout() {
            this._domNode.setLeft(this._model.options.minimapLeft);
            this._domNode.setWidth(this._model.options.minimapWidth);
            this._domNode.setHeight(this._model.options.minimapHeight);
            this._shadow.setHeight(this._model.options.minimapHeight);
            this._canvas.setWidth(this._model.options.canvasOuterWidth);
            this._canvas.setHeight(this._model.options.canvasOuterHeight);
            this._canvas.domNode.width = this._model.options.canvasInnerWidth;
            this._canvas.domNode.height = this._model.options.canvasInnerHeight;
            this._decorationsCanvas.setWidth(this._model.options.canvasOuterWidth);
            this._decorationsCanvas.setHeight(this._model.options.canvasOuterHeight);
            this._decorationsCanvas.domNode.width = this._model.options.canvasInnerWidth;
            this._decorationsCanvas.domNode.height = this._model.options.canvasInnerHeight;
            this._slider.setWidth(this._model.options.minimapWidth);
        }
        _getBuffer() {
            if (!this._buffers) {
                if (this._model.options.canvasInnerWidth > 0 && this._model.options.canvasInnerHeight > 0) {
                    this._buffers = new MinimapBuffers(this._canvas.domNode.getContext('2d'), this._model.options.canvasInnerWidth, this._model.options.canvasInnerHeight, this._model.options.backgroundColor);
                }
            }
            return this._buffers ? this._buffers.getBuffer() : null;
        }
        // ---- begin view event handlers
        onDidChangeOptions() {
            this._lastRenderData = null;
            this._buffers = null;
            this._applyLayout();
            this._domNode.setClassName(this._getMinimapDomNodeClassName());
        }
        onSelectionChanged() {
            this._renderDecorations = true;
            return true;
        }
        onDecorationsChanged() {
            this._renderDecorations = true;
            return true;
        }
        onFlushed() {
            this._lastRenderData = null;
            return true;
        }
        onLinesChanged(changeFromLineNumber, changeCount) {
            if (this._lastRenderData) {
                return this._lastRenderData.onLinesChanged(changeFromLineNumber, changeCount);
            }
            return false;
        }
        onLinesDeleted(deleteFromLineNumber, deleteToLineNumber) {
            this._lastRenderData?.onLinesDeleted(deleteFromLineNumber, deleteToLineNumber);
            return true;
        }
        onLinesInserted(insertFromLineNumber, insertToLineNumber) {
            this._lastRenderData?.onLinesInserted(insertFromLineNumber, insertToLineNumber);
            return true;
        }
        onScrollChanged() {
            this._renderDecorations = true;
            return true;
        }
        onThemeChanged() {
            this._selectionColor = this._theme.getColor(colorRegistry_1.minimapSelection);
            this._renderDecorations = true;
            return true;
        }
        onTokensChanged(ranges) {
            if (this._lastRenderData) {
                return this._lastRenderData.onTokensChanged(ranges);
            }
            return false;
        }
        onTokensColorsChanged() {
            this._lastRenderData = null;
            this._buffers = null;
            return true;
        }
        onZonesChanged() {
            this._lastRenderData = null;
            return true;
        }
        // --- end event handlers
        render(renderingCtx) {
            const renderMinimap = this._model.options.renderMinimap;
            if (renderMinimap === 0 /* RenderMinimap.None */) {
                this._shadow.setClassName('minimap-shadow-hidden');
                this._sliderHorizontal.setWidth(0);
                this._sliderHorizontal.setHeight(0);
                return;
            }
            if (renderingCtx.scrollLeft + renderingCtx.viewportWidth >= renderingCtx.scrollWidth) {
                this._shadow.setClassName('minimap-shadow-hidden');
            }
            else {
                this._shadow.setClassName('minimap-shadow-visible');
            }
            const layout = MinimapLayout.create(this._model.options, renderingCtx.viewportStartLineNumber, renderingCtx.viewportEndLineNumber, renderingCtx.viewportStartLineNumberVerticalOffset, renderingCtx.viewportHeight, renderingCtx.viewportContainsWhitespaceGaps, this._model.getLineCount(), this._model.getRealLineCount(), renderingCtx.scrollTop, renderingCtx.scrollHeight, this._lastRenderData ? this._lastRenderData.renderedLayout : null);
            this._slider.setDisplay(layout.sliderNeeded ? 'block' : 'none');
            this._slider.setTop(layout.sliderTop);
            this._slider.setHeight(layout.sliderHeight);
            // Compute horizontal slider coordinates
            this._sliderHorizontal.setLeft(0);
            this._sliderHorizontal.setWidth(this._model.options.minimapWidth);
            this._sliderHorizontal.setTop(0);
            this._sliderHorizontal.setHeight(layout.sliderHeight);
            this.renderDecorations(layout);
            this._lastRenderData = this.renderLines(layout);
        }
        renderDecorations(layout) {
            if (this._renderDecorations) {
                this._renderDecorations = false;
                const selections = this._model.getSelections();
                selections.sort(range_1.Range.compareRangesUsingStarts);
                const decorations = this._model.getMinimapDecorationsInViewport(layout.startLineNumber, layout.endLineNumber);
                decorations.sort((a, b) => (a.options.zIndex || 0) - (b.options.zIndex || 0));
                const { canvasInnerWidth, canvasInnerHeight } = this._model.options;
                const minimapLineHeight = this._model.options.minimapLineHeight;
                const minimapCharWidth = this._model.options.minimapCharWidth;
                const tabSize = this._model.getOptions().tabSize;
                const canvasContext = this._decorationsCanvas.domNode.getContext('2d');
                canvasContext.clearRect(0, 0, canvasInnerWidth, canvasInnerHeight);
                // We first need to render line highlights and then render decorations on top of those.
                // But we need to pick a single color for each line, and use that as a line highlight.
                // This needs to be the color of the decoration with the highest `zIndex`, but priority
                // is given to the selection.
                const highlightedLines = new ContiguousLineMap(layout.startLineNumber, layout.endLineNumber, false);
                this._renderSelectionLineHighlights(canvasContext, selections, highlightedLines, layout, minimapLineHeight);
                this._renderDecorationsLineHighlights(canvasContext, decorations, highlightedLines, layout, minimapLineHeight);
                const lineOffsetMap = new ContiguousLineMap(layout.startLineNumber, layout.endLineNumber, null);
                this._renderSelectionsHighlights(canvasContext, selections, lineOffsetMap, layout, minimapLineHeight, tabSize, minimapCharWidth, canvasInnerWidth);
                this._renderDecorationsHighlights(canvasContext, decorations, lineOffsetMap, layout, minimapLineHeight, tabSize, minimapCharWidth, canvasInnerWidth);
                this._renderSectionHeaders(layout);
            }
        }
        _renderSelectionLineHighlights(canvasContext, selections, highlightedLines, layout, minimapLineHeight) {
            if (!this._selectionColor || this._selectionColor.isTransparent()) {
                return;
            }
            canvasContext.fillStyle = this._selectionColor.transparent(0.5).toString();
            let y1 = 0;
            let y2 = 0;
            for (const selection of selections) {
                const intersection = layout.intersectWithViewport(selection);
                if (!intersection) {
                    // entirely outside minimap's viewport
                    continue;
                }
                const [startLineNumber, endLineNumber] = intersection;
                for (let line = startLineNumber; line <= endLineNumber; line++) {
                    highlightedLines.set(line, true);
                }
                const yy1 = layout.getYForLineNumber(startLineNumber, minimapLineHeight);
                const yy2 = layout.getYForLineNumber(endLineNumber, minimapLineHeight);
                if (y2 >= yy1) {
                    // merge into previous
                    y2 = yy2;
                }
                else {
                    if (y2 > y1) {
                        // flush
                        canvasContext.fillRect(editorOptions_1.MINIMAP_GUTTER_WIDTH, y1, canvasContext.canvas.width, y2 - y1);
                    }
                    y1 = yy1;
                    y2 = yy2;
                }
            }
            if (y2 > y1) {
                // flush
                canvasContext.fillRect(editorOptions_1.MINIMAP_GUTTER_WIDTH, y1, canvasContext.canvas.width, y2 - y1);
            }
        }
        _renderDecorationsLineHighlights(canvasContext, decorations, highlightedLines, layout, minimapLineHeight) {
            const highlightColors = new Map();
            // Loop backwards to hit first decorations with higher `zIndex`
            for (let i = decorations.length - 1; i >= 0; i--) {
                const decoration = decorations[i];
                const minimapOptions = decoration.options.minimap;
                if (!minimapOptions || minimapOptions.position !== 1 /* MinimapPosition.Inline */) {
                    continue;
                }
                const intersection = layout.intersectWithViewport(decoration.range);
                if (!intersection) {
                    // entirely outside minimap's viewport
                    continue;
                }
                const [startLineNumber, endLineNumber] = intersection;
                const decorationColor = minimapOptions.getColor(this._theme.value);
                if (!decorationColor || decorationColor.isTransparent()) {
                    continue;
                }
                let highlightColor = highlightColors.get(decorationColor.toString());
                if (!highlightColor) {
                    highlightColor = decorationColor.transparent(0.5).toString();
                    highlightColors.set(decorationColor.toString(), highlightColor);
                }
                canvasContext.fillStyle = highlightColor;
                for (let line = startLineNumber; line <= endLineNumber; line++) {
                    if (highlightedLines.has(line)) {
                        continue;
                    }
                    highlightedLines.set(line, true);
                    const y = layout.getYForLineNumber(startLineNumber, minimapLineHeight);
                    canvasContext.fillRect(editorOptions_1.MINIMAP_GUTTER_WIDTH, y, canvasContext.canvas.width, minimapLineHeight);
                }
            }
        }
        _renderSelectionsHighlights(canvasContext, selections, lineOffsetMap, layout, lineHeight, tabSize, characterWidth, canvasInnerWidth) {
            if (!this._selectionColor || this._selectionColor.isTransparent()) {
                return;
            }
            for (const selection of selections) {
                const intersection = layout.intersectWithViewport(selection);
                if (!intersection) {
                    // entirely outside minimap's viewport
                    continue;
                }
                const [startLineNumber, endLineNumber] = intersection;
                for (let line = startLineNumber; line <= endLineNumber; line++) {
                    this.renderDecorationOnLine(canvasContext, lineOffsetMap, selection, this._selectionColor, layout, line, lineHeight, lineHeight, tabSize, characterWidth, canvasInnerWidth);
                }
            }
        }
        _renderDecorationsHighlights(canvasContext, decorations, lineOffsetMap, layout, minimapLineHeight, tabSize, characterWidth, canvasInnerWidth) {
            // Loop forwards to hit first decorations with lower `zIndex`
            for (const decoration of decorations) {
                const minimapOptions = decoration.options.minimap;
                if (!minimapOptions) {
                    continue;
                }
                const intersection = layout.intersectWithViewport(decoration.range);
                if (!intersection) {
                    // entirely outside minimap's viewport
                    continue;
                }
                const [startLineNumber, endLineNumber] = intersection;
                const decorationColor = minimapOptions.getColor(this._theme.value);
                if (!decorationColor || decorationColor.isTransparent()) {
                    continue;
                }
                for (let line = startLineNumber; line <= endLineNumber; line++) {
                    switch (minimapOptions.position) {
                        case 1 /* MinimapPosition.Inline */:
                            this.renderDecorationOnLine(canvasContext, lineOffsetMap, decoration.range, decorationColor, layout, line, minimapLineHeight, minimapLineHeight, tabSize, characterWidth, canvasInnerWidth);
                            continue;
                        case 2 /* MinimapPosition.Gutter */: {
                            const y = layout.getYForLineNumber(line, minimapLineHeight);
                            const x = 2;
                            this.renderDecoration(canvasContext, decorationColor, x, y, GUTTER_DECORATION_WIDTH, minimapLineHeight);
                            continue;
                        }
                    }
                }
            }
        }
        renderDecorationOnLine(canvasContext, lineOffsetMap, decorationRange, decorationColor, layout, lineNumber, height, minimapLineHeight, tabSize, charWidth, canvasInnerWidth) {
            const y = layout.getYForLineNumber(lineNumber, minimapLineHeight);
            // Skip rendering the line if it's vertically outside our viewport
            if (y + height < 0 || y > this._model.options.canvasInnerHeight) {
                return;
            }
            const { startLineNumber, endLineNumber } = decorationRange;
            const startColumn = (startLineNumber === lineNumber ? decorationRange.startColumn : 1);
            const endColumn = (endLineNumber === lineNumber ? decorationRange.endColumn : this._model.getLineMaxColumn(lineNumber));
            const x1 = this.getXOffsetForPosition(lineOffsetMap, lineNumber, startColumn, tabSize, charWidth, canvasInnerWidth);
            const x2 = this.getXOffsetForPosition(lineOffsetMap, lineNumber, endColumn, tabSize, charWidth, canvasInnerWidth);
            this.renderDecoration(canvasContext, decorationColor, x1, y, x2 - x1, height);
        }
        getXOffsetForPosition(lineOffsetMap, lineNumber, column, tabSize, charWidth, canvasInnerWidth) {
            if (column === 1) {
                return editorOptions_1.MINIMAP_GUTTER_WIDTH;
            }
            const minimumXOffset = (column - 1) * charWidth;
            if (minimumXOffset >= canvasInnerWidth) {
                // there is no need to look at actual characters,
                // as this column is certainly after the minimap width
                return canvasInnerWidth;
            }
            // Cache line offset data so that it is only read once per line
            let lineIndexToXOffset = lineOffsetMap.get(lineNumber);
            if (!lineIndexToXOffset) {
                const lineData = this._model.getLineContent(lineNumber);
                lineIndexToXOffset = [editorOptions_1.MINIMAP_GUTTER_WIDTH];
                let prevx = editorOptions_1.MINIMAP_GUTTER_WIDTH;
                for (let i = 1; i < lineData.length + 1; i++) {
                    const charCode = lineData.charCodeAt(i - 1);
                    const dx = charCode === 9 /* CharCode.Tab */
                        ? tabSize * charWidth
                        : strings.isFullWidthCharacter(charCode)
                            ? 2 * charWidth
                            : charWidth;
                    const x = prevx + dx;
                    if (x >= canvasInnerWidth) {
                        // no need to keep on going, as we've hit the canvas width
                        lineIndexToXOffset[i] = canvasInnerWidth;
                        break;
                    }
                    lineIndexToXOffset[i] = x;
                    prevx = x;
                }
                lineOffsetMap.set(lineNumber, lineIndexToXOffset);
            }
            if (column - 1 < lineIndexToXOffset.length) {
                return lineIndexToXOffset[column - 1];
            }
            // goes over the canvas width
            return canvasInnerWidth;
        }
        renderDecoration(canvasContext, decorationColor, x, y, width, height) {
            canvasContext.fillStyle = decorationColor && decorationColor.toString() || '';
            canvasContext.fillRect(x, y, width, height);
        }
        _renderSectionHeaders(layout) {
            const minimapLineHeight = this._model.options.minimapLineHeight;
            const sectionHeaderFontSize = this._model.options.sectionHeaderFontSize;
            const sectionHeaderLetterSpacing = this._model.options.sectionHeaderLetterSpacing;
            const backgroundFillHeight = sectionHeaderFontSize * 1.5;
            const { canvasInnerWidth } = this._model.options;
            const backgroundColor = this._model.options.backgroundColor;
            const backgroundFill = `rgb(${backgroundColor.r} ${backgroundColor.g} ${backgroundColor.b} / .7)`;
            const foregroundColor = this._model.options.sectionHeaderFontColor;
            const foregroundFill = `rgb(${foregroundColor.r} ${foregroundColor.g} ${foregroundColor.b})`;
            const separatorStroke = foregroundFill;
            const canvasContext = this._decorationsCanvas.domNode.getContext('2d');
            canvasContext.letterSpacing = sectionHeaderLetterSpacing + 'px';
            canvasContext.font = '500 ' + sectionHeaderFontSize + 'px ' + this._model.options.sectionHeaderFontFamily;
            canvasContext.strokeStyle = separatorStroke;
            canvasContext.lineWidth = 0.2;
            const decorations = this._model.getSectionHeaderDecorationsInViewport(layout.startLineNumber, layout.endLineNumber);
            decorations.sort((a, b) => a.range.startLineNumber - b.range.startLineNumber);
            const fitWidth = InnerMinimap._fitSectionHeader.bind(null, canvasContext, canvasInnerWidth - editorOptions_1.MINIMAP_GUTTER_WIDTH);
            for (const decoration of decorations) {
                const y = layout.getYForLineNumber(decoration.range.startLineNumber, minimapLineHeight) + sectionHeaderFontSize;
                const backgroundFillY = y - sectionHeaderFontSize;
                const separatorY = backgroundFillY + 2;
                const headerText = this._model.getSectionHeaderText(decoration, fitWidth);
                InnerMinimap._renderSectionLabel(canvasContext, headerText, decoration.options.minimap?.sectionHeaderStyle === 2 /* MinimapSectionHeaderStyle.Underlined */, backgroundFill, foregroundFill, canvasInnerWidth, backgroundFillY, backgroundFillHeight, y, separatorY);
            }
        }
        static _fitSectionHeader(target, maxWidth, headerText) {
            if (!headerText) {
                return headerText;
            }
            const ellipsis = '…';
            const width = target.measureText(headerText).width;
            const ellipsisWidth = target.measureText(ellipsis).width;
            if (width <= maxWidth || width <= ellipsisWidth) {
                return headerText;
            }
            const len = headerText.length;
            const averageCharWidth = width / headerText.length;
            const maxCharCount = Math.floor((maxWidth - ellipsisWidth) / averageCharWidth) - 1;
            // Find a halfway point that isn't after whitespace
            let halfCharCount = Math.ceil(maxCharCount / 2);
            while (halfCharCount > 0 && /\s/.test(headerText[halfCharCount - 1])) {
                --halfCharCount;
            }
            // Split with ellipsis
            return headerText.substring(0, halfCharCount)
                + ellipsis + headerText.substring(len - (maxCharCount - halfCharCount));
        }
        static _renderSectionLabel(target, headerText, hasSeparatorLine, backgroundFill, foregroundFill, minimapWidth, backgroundFillY, backgroundFillHeight, textY, separatorY) {
            if (headerText) {
                target.fillStyle = backgroundFill;
                target.fillRect(0, backgroundFillY, minimapWidth, backgroundFillHeight);
                target.fillStyle = foregroundFill;
                target.fillText(headerText, editorOptions_1.MINIMAP_GUTTER_WIDTH, textY);
            }
            if (hasSeparatorLine) {
                target.beginPath();
                target.moveTo(0, separatorY);
                target.lineTo(minimapWidth, separatorY);
                target.closePath();
                target.stroke();
            }
        }
        renderLines(layout) {
            const startLineNumber = layout.startLineNumber;
            const endLineNumber = layout.endLineNumber;
            const minimapLineHeight = this._model.options.minimapLineHeight;
            // Check if nothing changed w.r.t. lines from last frame
            if (this._lastRenderData && this._lastRenderData.linesEquals(layout)) {
                const _lastData = this._lastRenderData._get();
                // Nice!! Nothing changed from last frame
                return new RenderData(layout, _lastData.imageData, _lastData.lines);
            }
            // Oh well!! We need to repaint some lines...
            const imageData = this._getBuffer();
            if (!imageData) {
                // 0 width or 0 height canvas, nothing to do
                return null;
            }
            // Render untouched lines by using last rendered data.
            const [_dirtyY1, _dirtyY2, needed] = InnerMinimap._renderUntouchedLines(imageData, layout.topPaddingLineCount, startLineNumber, endLineNumber, minimapLineHeight, this._lastRenderData);
            // Fetch rendering info from view model for rest of lines that need rendering.
            const lineInfo = this._model.getMinimapLinesRenderingData(startLineNumber, endLineNumber, needed);
            const tabSize = this._model.getOptions().tabSize;
            const defaultBackground = this._model.options.defaultBackgroundColor;
            const background = this._model.options.backgroundColor;
            const foregroundAlpha = this._model.options.foregroundAlpha;
            const tokensColorTracker = this._model.tokensColorTracker;
            const useLighterFont = tokensColorTracker.backgroundIsLight();
            const renderMinimap = this._model.options.renderMinimap;
            const charRenderer = this._model.options.charRenderer();
            const fontScale = this._model.options.fontScale;
            const minimapCharWidth = this._model.options.minimapCharWidth;
            const baseCharHeight = (renderMinimap === 1 /* RenderMinimap.Text */ ? 2 /* Constants.BASE_CHAR_HEIGHT */ : 2 /* Constants.BASE_CHAR_HEIGHT */ + 1);
            const renderMinimapLineHeight = baseCharHeight * fontScale;
            const innerLinePadding = (minimapLineHeight > renderMinimapLineHeight ? Math.floor((minimapLineHeight - renderMinimapLineHeight) / 2) : 0);
            // Render the rest of lines
            const backgroundA = background.a / 255;
            const renderBackground = new rgba_1.RGBA8(Math.round((background.r - defaultBackground.r) * backgroundA + defaultBackground.r), Math.round((background.g - defaultBackground.g) * backgroundA + defaultBackground.g), Math.round((background.b - defaultBackground.b) * backgroundA + defaultBackground.b), 255);
            let dy = layout.topPaddingLineCount * minimapLineHeight;
            const renderedLines = [];
            for (let lineIndex = 0, lineCount = endLineNumber - startLineNumber + 1; lineIndex < lineCount; lineIndex++) {
                if (needed[lineIndex]) {
                    InnerMinimap._renderLine(imageData, renderBackground, background.a, useLighterFont, renderMinimap, minimapCharWidth, tokensColorTracker, foregroundAlpha, charRenderer, dy, innerLinePadding, tabSize, lineInfo[lineIndex], fontScale, minimapLineHeight);
                }
                renderedLines[lineIndex] = new MinimapLine(dy);
                dy += minimapLineHeight;
            }
            const dirtyY1 = (_dirtyY1 === -1 ? 0 : _dirtyY1);
            const dirtyY2 = (_dirtyY2 === -1 ? imageData.height : _dirtyY2);
            const dirtyHeight = dirtyY2 - dirtyY1;
            // Finally, paint to the canvas
            const ctx = this._canvas.domNode.getContext('2d');
            ctx.putImageData(imageData, 0, 0, 0, dirtyY1, imageData.width, dirtyHeight);
            // Save rendered data for reuse on next frame if possible
            return new RenderData(layout, imageData, renderedLines);
        }
        static _renderUntouchedLines(target, topPaddingLineCount, startLineNumber, endLineNumber, minimapLineHeight, lastRenderData) {
            const needed = [];
            if (!lastRenderData) {
                for (let i = 0, len = endLineNumber - startLineNumber + 1; i < len; i++) {
                    needed[i] = true;
                }
                return [-1, -1, needed];
            }
            const _lastData = lastRenderData._get();
            const lastTargetData = _lastData.imageData.data;
            const lastStartLineNumber = _lastData.rendLineNumberStart;
            const lastLines = _lastData.lines;
            const lastLinesLength = lastLines.length;
            const WIDTH = target.width;
            const targetData = target.data;
            const maxDestPixel = (endLineNumber - startLineNumber + 1) * minimapLineHeight * WIDTH * 4;
            let dirtyPixel1 = -1; // the pixel offset up to which all the data is equal to the prev frame
            let dirtyPixel2 = -1; // the pixel offset after which all the data is equal to the prev frame
            let copySourceStart = -1;
            let copySourceEnd = -1;
            let copyDestStart = -1;
            let copyDestEnd = -1;
            let dest_dy = topPaddingLineCount * minimapLineHeight;
            for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
                const lineIndex = lineNumber - startLineNumber;
                const lastLineIndex = lineNumber - lastStartLineNumber;
                const source_dy = (lastLineIndex >= 0 && lastLineIndex < lastLinesLength ? lastLines[lastLineIndex].dy : -1);
                if (source_dy === -1) {
                    needed[lineIndex] = true;
                    dest_dy += minimapLineHeight;
                    continue;
                }
                const sourceStart = source_dy * WIDTH * 4;
                const sourceEnd = (source_dy + minimapLineHeight) * WIDTH * 4;
                const destStart = dest_dy * WIDTH * 4;
                const destEnd = (dest_dy + minimapLineHeight) * WIDTH * 4;
                if (copySourceEnd === sourceStart && copyDestEnd === destStart) {
                    // contiguous zone => extend copy request
                    copySourceEnd = sourceEnd;
                    copyDestEnd = destEnd;
                }
                else {
                    if (copySourceStart !== -1) {
                        // flush existing copy request
                        targetData.set(lastTargetData.subarray(copySourceStart, copySourceEnd), copyDestStart);
                        if (dirtyPixel1 === -1 && copySourceStart === 0 && copySourceStart === copyDestStart) {
                            dirtyPixel1 = copySourceEnd;
                        }
                        if (dirtyPixel2 === -1 && copySourceEnd === maxDestPixel && copySourceStart === copyDestStart) {
                            dirtyPixel2 = copySourceStart;
                        }
                    }
                    copySourceStart = sourceStart;
                    copySourceEnd = sourceEnd;
                    copyDestStart = destStart;
                    copyDestEnd = destEnd;
                }
                needed[lineIndex] = false;
                dest_dy += minimapLineHeight;
            }
            if (copySourceStart !== -1) {
                // flush existing copy request
                targetData.set(lastTargetData.subarray(copySourceStart, copySourceEnd), copyDestStart);
                if (dirtyPixel1 === -1 && copySourceStart === 0 && copySourceStart === copyDestStart) {
                    dirtyPixel1 = copySourceEnd;
                }
                if (dirtyPixel2 === -1 && copySourceEnd === maxDestPixel && copySourceStart === copyDestStart) {
                    dirtyPixel2 = copySourceStart;
                }
            }
            const dirtyY1 = (dirtyPixel1 === -1 ? -1 : dirtyPixel1 / (WIDTH * 4));
            const dirtyY2 = (dirtyPixel2 === -1 ? -1 : dirtyPixel2 / (WIDTH * 4));
            return [dirtyY1, dirtyY2, needed];
        }
        static _renderLine(target, backgroundColor, backgroundAlpha, useLighterFont, renderMinimap, charWidth, colorTracker, foregroundAlpha, minimapCharRenderer, dy, innerLinePadding, tabSize, lineData, fontScale, minimapLineHeight) {
            const content = lineData.content;
            const tokens = lineData.tokens;
            const maxDx = target.width - charWidth;
            const force1pxHeight = (minimapLineHeight === 1);
            let dx = editorOptions_1.MINIMAP_GUTTER_WIDTH;
            let charIndex = 0;
            let tabsCharDelta = 0;
            for (let tokenIndex = 0, tokensLen = tokens.getCount(); tokenIndex < tokensLen; tokenIndex++) {
                const tokenEndIndex = tokens.getEndOffset(tokenIndex);
                const tokenColorId = tokens.getForeground(tokenIndex);
                const tokenColor = colorTracker.getColor(tokenColorId);
                for (; charIndex < tokenEndIndex; charIndex++) {
                    if (dx > maxDx) {
                        // hit edge of minimap
                        return;
                    }
                    const charCode = content.charCodeAt(charIndex);
                    if (charCode === 9 /* CharCode.Tab */) {
                        const insertSpacesCount = tabSize - (charIndex + tabsCharDelta) % tabSize;
                        tabsCharDelta += insertSpacesCount - 1;
                        // No need to render anything since tab is invisible
                        dx += insertSpacesCount * charWidth;
                    }
                    else if (charCode === 32 /* CharCode.Space */) {
                        // No need to render anything since space is invisible
                        dx += charWidth;
                    }
                    else {
                        // Render twice for a full width character
                        const count = strings.isFullWidthCharacter(charCode) ? 2 : 1;
                        for (let i = 0; i < count; i++) {
                            if (renderMinimap === 2 /* RenderMinimap.Blocks */) {
                                minimapCharRenderer.blockRenderChar(target, dx, dy + innerLinePadding, tokenColor, foregroundAlpha, backgroundColor, backgroundAlpha, force1pxHeight);
                            }
                            else { // RenderMinimap.Text
                                minimapCharRenderer.renderChar(target, dx, dy + innerLinePadding, charCode, tokenColor, foregroundAlpha, backgroundColor, backgroundAlpha, fontScale, useLighterFont, force1pxHeight);
                            }
                            dx += charWidth;
                            if (dx > maxDx) {
                                // hit edge of minimap
                                return;
                            }
                        }
                    }
                }
            }
        }
    }
    class ContiguousLineMap {
        constructor(startLineNumber, endLineNumber, defaultValue) {
            this._startLineNumber = startLineNumber;
            this._endLineNumber = endLineNumber;
            this._defaultValue = defaultValue;
            this._values = [];
            for (let i = 0, count = this._endLineNumber - this._startLineNumber + 1; i < count; i++) {
                this._values[i] = defaultValue;
            }
        }
        has(lineNumber) {
            return (this.get(lineNumber) !== this._defaultValue);
        }
        set(lineNumber, value) {
            if (lineNumber < this._startLineNumber || lineNumber > this._endLineNumber) {
                return;
            }
            this._values[lineNumber - this._startLineNumber] = value;
        }
        get(lineNumber) {
            if (lineNumber < this._startLineNumber || lineNumber > this._endLineNumber) {
                return this._defaultValue;
            }
            return this._values[lineNumber - this._startLineNumber];
        }
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[756/*vs/editor/browser/widget/multiDiffEditor/colors*/], __M([1/*require*/,0/*exports*/,3/*vs/nls*/,32/*vs/platform/theme/common/colorRegistry*/]), function (require, exports, nls_1, colorRegistry_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.multiDiffEditorBorder = exports.multiDiffEditorBackground = exports.multiDiffEditorHeaderBackground = void 0;
    exports.multiDiffEditorHeaderBackground = (0, colorRegistry_1.registerColor)('multiDiffEditor.headerBackground', { dark: '#262626', light: 'tab.inactiveBackground', hcDark: 'tab.inactiveBackground', hcLight: 'tab.inactiveBackground', }, (0, nls_1.localize)(129, 'The background color of the diff editor\'s header'));
    exports.multiDiffEditorBackground = (0, colorRegistry_1.registerColor)('multiDiffEditor.background', colorRegistry_1.editorBackground, (0, nls_1.localize)(130, 'The background color of the multi file diff editor'));
    exports.multiDiffEditorBorder = (0, colorRegistry_1.registerColor)('multiDiffEditor.border', { dark: 'sideBarSectionHeader.border', light: '#cccccc', hcDark: 'sideBarSectionHeader.border', hcLight: '#cccccc', }, (0, nls_1.localize)(131, 'The border color of the multi file diff editor'));
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[280/*vs/editor/contrib/symbolIcons/browser/symbolIcons*/], __M([1/*require*/,0/*exports*/,3/*vs/nls*/,32/*vs/platform/theme/common/colorRegistry*/,533/*vs/css!vs/editor/contrib/symbolIcons/browser/symbolIcons*/]), function (require, exports, nls_1, colorRegistry_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SYMBOL_ICON_VARIABLE_FOREGROUND = exports.SYMBOL_ICON_UNIT_FOREGROUND = exports.SYMBOL_ICON_TYPEPARAMETER_FOREGROUND = exports.SYMBOL_ICON_TEXT_FOREGROUND = exports.SYMBOL_ICON_STRUCT_FOREGROUND = exports.SYMBOL_ICON_STRING_FOREGROUND = exports.SYMBOL_ICON_SNIPPET_FOREGROUND = exports.SYMBOL_ICON_REFERENCE_FOREGROUND = exports.SYMBOL_ICON_PROPERTY_FOREGROUND = exports.SYMBOL_ICON_PACKAGE_FOREGROUND = exports.SYMBOL_ICON_OPERATOR_FOREGROUND = exports.SYMBOL_ICON_OBJECT_FOREGROUND = exports.SYMBOL_ICON_NUMBER_FOREGROUND = exports.SYMBOL_ICON_NULL_FOREGROUND = exports.SYMBOL_ICON_NAMESPACE_FOREGROUND = exports.SYMBOL_ICON_MODULE_FOREGROUND = exports.SYMBOL_ICON_METHOD_FOREGROUND = exports.SYMBOL_ICON_KEYWORD_FOREGROUND = exports.SYMBOL_ICON_KEY_FOREGROUND = exports.SYMBOL_ICON_INTERFACE_FOREGROUND = exports.SYMBOL_ICON_FUNCTION_FOREGROUND = exports.SYMBOL_ICON_FOLDER_FOREGROUND = exports.SYMBOL_ICON_FILE_FOREGROUND = exports.SYMBOL_ICON_FIELD_FOREGROUND = exports.SYMBOL_ICON_EVENT_FOREGROUND = exports.SYMBOL_ICON_ENUMERATOR_MEMBER_FOREGROUND = exports.SYMBOL_ICON_ENUMERATOR_FOREGROUND = exports.SYMBOL_ICON_CONSTRUCTOR_FOREGROUND = exports.SYMBOL_ICON_CONSTANT_FOREGROUND = exports.SYMBOL_ICON_COLOR_FOREGROUND = exports.SYMBOL_ICON_CLASS_FOREGROUND = exports.SYMBOL_ICON_BOOLEAN_FOREGROUND = exports.SYMBOL_ICON_ARRAY_FOREGROUND = void 0;
    exports.SYMBOL_ICON_ARRAY_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.arrayForeground', colorRegistry_1.foreground, (0, nls_1.localize)(1348, 'The foreground color for array symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
    exports.SYMBOL_ICON_BOOLEAN_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.booleanForeground', colorRegistry_1.foreground, (0, nls_1.localize)(1349, 'The foreground color for boolean symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
    exports.SYMBOL_ICON_CLASS_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.classForeground', {
        dark: '#EE9D28',
        light: '#D67E00',
        hcDark: '#EE9D28',
        hcLight: '#D67E00'
    }, (0, nls_1.localize)(1350, 'The foreground color for class symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
    exports.SYMBOL_ICON_COLOR_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.colorForeground', colorRegistry_1.foreground, (0, nls_1.localize)(1351, 'The foreground color for color symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
    exports.SYMBOL_ICON_CONSTANT_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.constantForeground', colorRegistry_1.foreground, (0, nls_1.localize)(1352, 'The foreground color for constant symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
    exports.SYMBOL_ICON_CONSTRUCTOR_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.constructorForeground', {
        dark: '#B180D7',
        light: '#652D90',
        hcDark: '#B180D7',
        hcLight: '#652D90'
    }, (0, nls_1.localize)(1353, 'The foreground color for constructor symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
    exports.SYMBOL_ICON_ENUMERATOR_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.enumeratorForeground', {
        dark: '#EE9D28',
        light: '#D67E00',
        hcDark: '#EE9D28',
        hcLight: '#D67E00'
    }, (0, nls_1.localize)(1354, 'The foreground color for enumerator symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
    exports.SYMBOL_ICON_ENUMERATOR_MEMBER_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.enumeratorMemberForeground', {
        dark: '#75BEFF',
        light: '#007ACC',
        hcDark: '#75BEFF',
        hcLight: '#007ACC'
    }, (0, nls_1.localize)(1355, 'The foreground color for enumerator member symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
    exports.SYMBOL_ICON_EVENT_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.eventForeground', {
        dark: '#EE9D28',
        light: '#D67E00',
        hcDark: '#EE9D28',
        hcLight: '#D67E00'
    }, (0, nls_1.localize)(1356, 'The foreground color for event symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
    exports.SYMBOL_ICON_FIELD_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.fieldForeground', {
        dark: '#75BEFF',
        light: '#007ACC',
        hcDark: '#75BEFF',
        hcLight: '#007ACC'
    }, (0, nls_1.localize)(1357, 'The foreground color for field symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
    exports.SYMBOL_ICON_FILE_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.fileForeground', colorRegistry_1.foreground, (0, nls_1.localize)(1358, 'The foreground color for file symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
    exports.SYMBOL_ICON_FOLDER_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.folderForeground', colorRegistry_1.foreground, (0, nls_1.localize)(1359, 'The foreground color for folder symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
    exports.SYMBOL_ICON_FUNCTION_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.functionForeground', {
        dark: '#B180D7',
        light: '#652D90',
        hcDark: '#B180D7',
        hcLight: '#652D90'
    }, (0, nls_1.localize)(1360, 'The foreground color for function symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
    exports.SYMBOL_ICON_INTERFACE_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.interfaceForeground', {
        dark: '#75BEFF',
        light: '#007ACC',
        hcDark: '#75BEFF',
        hcLight: '#007ACC'
    }, (0, nls_1.localize)(1361, 'The foreground color for interface symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
    exports.SYMBOL_ICON_KEY_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.keyForeground', colorRegistry_1.foreground, (0, nls_1.localize)(1362, 'The foreground color for key symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
    exports.SYMBOL_ICON_KEYWORD_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.keywordForeground', colorRegistry_1.foreground, (0, nls_1.localize)(1363, 'The foreground color for keyword symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
    exports.SYMBOL_ICON_METHOD_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.methodForeground', {
        dark: '#B180D7',
        light: '#652D90',
        hcDark: '#B180D7',
        hcLight: '#652D90'
    }, (0, nls_1.localize)(1364, 'The foreground color for method symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
    exports.SYMBOL_ICON_MODULE_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.moduleForeground', colorRegistry_1.foreground, (0, nls_1.localize)(1365, 'The foreground color for module symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
    exports.SYMBOL_ICON_NAMESPACE_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.namespaceForeground', colorRegistry_1.foreground, (0, nls_1.localize)(1366, 'The foreground color for namespace symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
    exports.SYMBOL_ICON_NULL_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.nullForeground', colorRegistry_1.foreground, (0, nls_1.localize)(1367, 'The foreground color for null symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
    exports.SYMBOL_ICON_NUMBER_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.numberForeground', colorRegistry_1.foreground, (0, nls_1.localize)(1368, 'The foreground color for number symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
    exports.SYMBOL_ICON_OBJECT_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.objectForeground', colorRegistry_1.foreground, (0, nls_1.localize)(1369, 'The foreground color for object symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
    exports.SYMBOL_ICON_OPERATOR_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.operatorForeground', colorRegistry_1.foreground, (0, nls_1.localize)(1370, 'The foreground color for operator symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
    exports.SYMBOL_ICON_PACKAGE_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.packageForeground', colorRegistry_1.foreground, (0, nls_1.localize)(1371, 'The foreground color for package symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
    exports.SYMBOL_ICON_PROPERTY_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.propertyForeground', colorRegistry_1.foreground, (0, nls_1.localize)(1372, 'The foreground color for property symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
    exports.SYMBOL_ICON_REFERENCE_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.referenceForeground', colorRegistry_1.foreground, (0, nls_1.localize)(1373, 'The foreground color for reference symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
    exports.SYMBOL_ICON_SNIPPET_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.snippetForeground', colorRegistry_1.foreground, (0, nls_1.localize)(1374, 'The foreground color for snippet symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
    exports.SYMBOL_ICON_STRING_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.stringForeground', colorRegistry_1.foreground, (0, nls_1.localize)(1375, 'The foreground color for string symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
    exports.SYMBOL_ICON_STRUCT_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.structForeground', colorRegistry_1.foreground, (0, nls_1.localize)(1376, 'The foreground color for struct symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
    exports.SYMBOL_ICON_TEXT_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.textForeground', colorRegistry_1.foreground, (0, nls_1.localize)(1377, 'The foreground color for text symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
    exports.SYMBOL_ICON_TYPEPARAMETER_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.typeParameterForeground', colorRegistry_1.foreground, (0, nls_1.localize)(1378, 'The foreground color for type parameter symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
    exports.SYMBOL_ICON_UNIT_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.unitForeground', colorRegistry_1.foreground, (0, nls_1.localize)(1379, 'The foreground color for unit symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
    exports.SYMBOL_ICON_VARIABLE_FOREGROUND = (0, colorRegistry_1.registerColor)('symbolIcon.variableForeground', {
        dark: '#75BEFF',
        light: '#007ACC',
        hcDark: '#75BEFF',
        hcLight: '#007ACC',
    }, (0, nls_1.localize)(1380, 'The foreground color for variable symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[757/*vs/editor/contrib/codeAction/browser/codeActionMenu*/], __M([1/*require*/,0/*exports*/,26/*vs/base/common/codicons*/,134/*vs/editor/contrib/codeAction/common/types*/,3/*vs/nls*/,91/*vs/base/common/hierarchicalKind*/,195/*vs/base/browser/ui/codicons/codiconStyles*/,280/*vs/editor/contrib/symbolIcons/browser/symbolIcons*/]), function (require, exports, codicons_1, types_1, nls_1, hierarchicalKind_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.toMenuItems = toMenuItems;
    const uncategorizedCodeActionGroup = Object.freeze({ kind: hierarchicalKind_1.HierarchicalKind.Empty, title: (0, nls_1.localize)(777, 'More Actions...') });
    const codeActionGroups = Object.freeze([
        { kind: types_1.CodeActionKind.QuickFix, title: (0, nls_1.localize)(778, 'Quick Fix') },
        { kind: types_1.CodeActionKind.RefactorExtract, title: (0, nls_1.localize)(779, 'Extract'), icon: codicons_1.Codicon.wrench },
        { kind: types_1.CodeActionKind.RefactorInline, title: (0, nls_1.localize)(780, 'Inline'), icon: codicons_1.Codicon.wrench },
        { kind: types_1.CodeActionKind.RefactorRewrite, title: (0, nls_1.localize)(781, 'Rewrite'), icon: codicons_1.Codicon.wrench },
        { kind: types_1.CodeActionKind.RefactorMove, title: (0, nls_1.localize)(782, 'Move'), icon: codicons_1.Codicon.wrench },
        { kind: types_1.CodeActionKind.SurroundWith, title: (0, nls_1.localize)(783, 'Surround With'), icon: codicons_1.Codicon.surroundWith },
        { kind: types_1.CodeActionKind.Source, title: (0, nls_1.localize)(784, 'Source Action'), icon: codicons_1.Codicon.symbolFile },
        uncategorizedCodeActionGroup,
    ]);
    function toMenuItems(inputCodeActions, showHeaders, keybindingResolver) {
        if (!showHeaders) {
            return inputCodeActions.map((action) => {
                return {
                    kind: "action" /* ActionListItemKind.Action */,
                    item: action,
                    group: uncategorizedCodeActionGroup,
                    disabled: !!action.action.disabled,
                    label: action.action.disabled || action.action.title,
                    canPreview: !!action.action.edit?.edits.length,
                };
            });
        }
        // Group code actions
        const menuEntries = codeActionGroups.map(group => ({ group, actions: [] }));
        for (const action of inputCodeActions) {
            const kind = action.action.kind ? new hierarchicalKind_1.HierarchicalKind(action.action.kind) : hierarchicalKind_1.HierarchicalKind.None;
            for (const menuEntry of menuEntries) {
                if (menuEntry.group.kind.contains(kind)) {
                    menuEntry.actions.push(action);
                    break;
                }
            }
        }
        const allMenuItems = [];
        for (const menuEntry of menuEntries) {
            if (menuEntry.actions.length) {
                allMenuItems.push({ kind: "header" /* ActionListItemKind.Header */, group: menuEntry.group });
                for (const action of menuEntry.actions) {
                    const group = menuEntry.group;
                    allMenuItems.push({
                        kind: "action" /* ActionListItemKind.Action */,
                        item: action,
                        group: action.action.isAI ? { title: group.title, kind: group.kind, icon: codicons_1.Codicon.sparkle } : group,
                        label: action.action.title,
                        disabled: !!action.action.disabled,
                        keybinding: keybindingResolver(action.action),
                    });
                }
            }
        }
        return allMenuItems;
    }
});

define(__m[110/*vs/platform/theme/browser/defaultStyles*/], __M([1/*require*/,0/*exports*/,32/*vs/platform/theme/common/colorRegistry*/,33/*vs/base/common/color*/]), function (require, exports, colorRegistry_1, color_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.defaultMenuStyles = exports.defaultSelectBoxStyles = exports.defaultListStyles = exports.defaultBreadcrumbsWidgetStyles = exports.defaultCountBadgeStyles = exports.defaultFindWidgetStyles = exports.defaultInputBoxStyles = exports.defaultDialogStyles = exports.defaultCheckboxStyles = exports.defaultRadioStyles = exports.defaultToggleStyles = exports.defaultProgressBarStyles = exports.defaultButtonStyles = exports.defaultKeybindingLabelStyles = void 0;
    exports.getListStyles = getListStyles;
    function overrideStyles(override, styles) {
        const result = { ...styles };
        for (const key in override) {
            const val = override[key];
            result[key] = val !== undefined ? (0, colorRegistry_1.asCssVariable)(val) : undefined;
        }
        return result;
    }
    exports.defaultKeybindingLabelStyles = {
        keybindingLabelBackground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.keybindingLabelBackground),
        keybindingLabelForeground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.keybindingLabelForeground),
        keybindingLabelBorder: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.keybindingLabelBorder),
        keybindingLabelBottomBorder: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.keybindingLabelBottomBorder),
        keybindingLabelShadow: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.widgetShadow)
    };
    exports.defaultButtonStyles = {
        buttonForeground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.buttonForeground),
        buttonSeparator: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.buttonSeparator),
        buttonBackground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.buttonBackground),
        buttonHoverBackground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.buttonHoverBackground),
        buttonSecondaryForeground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.buttonSecondaryForeground),
        buttonSecondaryBackground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.buttonSecondaryBackground),
        buttonSecondaryHoverBackground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.buttonSecondaryHoverBackground),
        buttonBorder: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.buttonBorder),
    };
    exports.defaultProgressBarStyles = {
        progressBarBackground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.progressBarBackground)
    };
    exports.defaultToggleStyles = {
        inputActiveOptionBorder: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.inputActiveOptionBorder),
        inputActiveOptionForeground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.inputActiveOptionForeground),
        inputActiveOptionBackground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.inputActiveOptionBackground)
    };
    exports.defaultRadioStyles = {
        activeForeground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.radioActiveForeground),
        activeBackground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.radioActiveBackground),
        activeBorder: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.radioActiveBorder),
        inactiveForeground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.radioInactiveForeground),
        inactiveBackground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.radioInactiveBackground),
        inactiveBorder: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.radioInactiveBorder),
        inactiveHoverBackground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.radioInactiveHoverBackground),
    };
    exports.defaultCheckboxStyles = {
        checkboxBackground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.checkboxBackground),
        checkboxBorder: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.checkboxBorder),
        checkboxForeground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.checkboxForeground)
    };
    exports.defaultDialogStyles = {
        dialogBackground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.editorWidgetBackground),
        dialogForeground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.editorWidgetForeground),
        dialogShadow: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.widgetShadow),
        dialogBorder: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.contrastBorder),
        errorIconForeground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.problemsErrorIconForeground),
        warningIconForeground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.problemsWarningIconForeground),
        infoIconForeground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.problemsInfoIconForeground),
        textLinkForeground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.textLinkForeground)
    };
    exports.defaultInputBoxStyles = {
        inputBackground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.inputBackground),
        inputForeground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.inputForeground),
        inputBorder: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.inputBorder),
        inputValidationInfoBorder: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.inputValidationInfoBorder),
        inputValidationInfoBackground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.inputValidationInfoBackground),
        inputValidationInfoForeground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.inputValidationInfoForeground),
        inputValidationWarningBorder: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.inputValidationWarningBorder),
        inputValidationWarningBackground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.inputValidationWarningBackground),
        inputValidationWarningForeground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.inputValidationWarningForeground),
        inputValidationErrorBorder: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.inputValidationErrorBorder),
        inputValidationErrorBackground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.inputValidationErrorBackground),
        inputValidationErrorForeground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.inputValidationErrorForeground)
    };
    exports.defaultFindWidgetStyles = {
        listFilterWidgetBackground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.listFilterWidgetBackground),
        listFilterWidgetOutline: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.listFilterWidgetOutline),
        listFilterWidgetNoMatchesOutline: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.listFilterWidgetNoMatchesOutline),
        listFilterWidgetShadow: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.listFilterWidgetShadow),
        inputBoxStyles: exports.defaultInputBoxStyles,
        toggleStyles: exports.defaultToggleStyles
    };
    exports.defaultCountBadgeStyles = {
        badgeBackground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.badgeBackground),
        badgeForeground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.badgeForeground),
        badgeBorder: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.contrastBorder)
    };
    exports.defaultBreadcrumbsWidgetStyles = {
        breadcrumbsBackground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.breadcrumbsBackground),
        breadcrumbsForeground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.breadcrumbsForeground),
        breadcrumbsHoverForeground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.breadcrumbsFocusForeground),
        breadcrumbsFocusForeground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.breadcrumbsFocusForeground),
        breadcrumbsFocusAndSelectionForeground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.breadcrumbsActiveSelectionForeground)
    };
    exports.defaultListStyles = {
        listBackground: undefined,
        listInactiveFocusForeground: undefined,
        listFocusBackground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.listFocusBackground),
        listFocusForeground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.listFocusForeground),
        listFocusOutline: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.listFocusOutline),
        listActiveSelectionBackground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.listActiveSelectionBackground),
        listActiveSelectionForeground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.listActiveSelectionForeground),
        listActiveSelectionIconForeground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.listActiveSelectionIconForeground),
        listFocusAndSelectionOutline: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.listFocusAndSelectionOutline),
        listFocusAndSelectionBackground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.listActiveSelectionBackground),
        listFocusAndSelectionForeground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.listActiveSelectionForeground),
        listInactiveSelectionBackground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.listInactiveSelectionBackground),
        listInactiveSelectionIconForeground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.listInactiveSelectionIconForeground),
        listInactiveSelectionForeground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.listInactiveSelectionForeground),
        listInactiveFocusBackground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.listInactiveFocusBackground),
        listInactiveFocusOutline: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.listInactiveFocusOutline),
        listHoverBackground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.listHoverBackground),
        listHoverForeground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.listHoverForeground),
        listDropOverBackground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.listDropOverBackground),
        listDropBetweenBackground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.listDropBetweenBackground),
        listSelectionOutline: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.activeContrastBorder),
        listHoverOutline: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.activeContrastBorder),
        treeIndentGuidesStroke: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.treeIndentGuidesStroke),
        treeInactiveIndentGuidesStroke: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.treeInactiveIndentGuidesStroke),
        treeStickyScrollBackground: undefined,
        treeStickyScrollBorder: undefined,
        treeStickyScrollShadow: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.scrollbarShadow),
        tableColumnsBorder: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.tableColumnsBorder),
        tableOddRowsBackgroundColor: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.tableOddRowsBackgroundColor),
    };
    function getListStyles(override) {
        return overrideStyles(override, exports.defaultListStyles);
    }
    exports.defaultSelectBoxStyles = {
        selectBackground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.selectBackground),
        selectListBackground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.selectListBackground),
        selectForeground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.selectForeground),
        decoratorRightForeground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.pickerGroupForeground),
        selectBorder: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.selectBorder),
        focusBorder: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.focusBorder),
        listFocusBackground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.quickInputListFocusBackground),
        listInactiveSelectionIconForeground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.quickInputListFocusIconForeground),
        listFocusForeground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.quickInputListFocusForeground),
        listFocusOutline: (0, colorRegistry_1.asCssVariableWithDefault)(colorRegistry_1.activeContrastBorder, color_1.Color.transparent.toString()),
        listHoverBackground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.listHoverBackground),
        listHoverForeground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.listHoverForeground),
        listHoverOutline: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.activeContrastBorder),
        selectListBorder: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.editorWidgetBorder),
        listBackground: undefined,
        listActiveSelectionBackground: undefined,
        listActiveSelectionForeground: undefined,
        listActiveSelectionIconForeground: undefined,
        listFocusAndSelectionBackground: undefined,
        listDropOverBackground: undefined,
        listDropBetweenBackground: undefined,
        listInactiveSelectionBackground: undefined,
        listInactiveSelectionForeground: undefined,
        listInactiveFocusBackground: undefined,
        listInactiveFocusOutline: undefined,
        listSelectionOutline: undefined,
        listFocusAndSelectionForeground: undefined,
        listFocusAndSelectionOutline: undefined,
        listInactiveFocusForeground: undefined,
        tableColumnsBorder: undefined,
        tableOddRowsBackgroundColor: undefined,
        treeIndentGuidesStroke: undefined,
        treeInactiveIndentGuidesStroke: undefined,
        treeStickyScrollBackground: undefined,
        treeStickyScrollBorder: undefined,
        treeStickyScrollShadow: undefined
    };
    exports.defaultMenuStyles = {
        shadowColor: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.widgetShadow),
        borderColor: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.menuBorder),
        foregroundColor: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.menuForeground),
        backgroundColor: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.menuBackground),
        selectionForegroundColor: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.menuSelectionForeground),
        selectionBackgroundColor: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.menuSelectionBackground),
        selectionBorderColor: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.menuSelectionBorder),
        separatorColor: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.menuSeparatorBackground),
        scrollbarShadow: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.scrollbarShadow),
        scrollbarSliderBackground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.scrollbarSliderBackground),
        scrollbarSliderHoverBackground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.scrollbarSliderHoverBackground),
        scrollbarSliderActiveBackground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.scrollbarSliderActiveBackground)
    };
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[758/*vs/editor/contrib/gotoSymbol/browser/peek/referencesTree*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,354/*vs/base/browser/ui/countBadge/countBadge*/,355/*vs/base/browser/ui/highlightedlabel/highlightedLabel*/,254/*vs/base/browser/ui/iconLabel/iconLabel*/,82/*vs/base/common/filters*/,2/*vs/base/common/lifecycle*/,48/*vs/base/common/resources*/,78/*vs/editor/common/services/resolverService*/,3/*vs/nls*/,7/*vs/platform/instantiation/common/instantiation*/,31/*vs/platform/keybinding/common/keybinding*/,181/*vs/platform/label/common/label*/,110/*vs/platform/theme/browser/defaultStyles*/,178/*vs/editor/contrib/gotoSymbol/browser/referencesModel*/]), function (require, exports, dom, countBadge_1, highlightedLabel_1, iconLabel_1, filters_1, lifecycle_1, resources_1, resolverService_1, nls_1, instantiation_1, keybinding_1, label_1, defaultStyles_1, referencesModel_1) {
    "use strict";
    var FileReferencesRenderer_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AccessibilityProvider = exports.OneReferenceRenderer = exports.FileReferencesRenderer = exports.IdentityProvider = exports.StringRepresentationProvider = exports.Delegate = exports.DataSource = void 0;
    let DataSource = class DataSource {
        constructor(_resolverService) {
            this._resolverService = _resolverService;
        }
        hasChildren(element) {
            if (element instanceof referencesModel_1.ReferencesModel) {
                return true;
            }
            if (element instanceof referencesModel_1.FileReferences) {
                return true;
            }
            return false;
        }
        getChildren(element) {
            if (element instanceof referencesModel_1.ReferencesModel) {
                return element.groups;
            }
            if (element instanceof referencesModel_1.FileReferences) {
                return element.resolve(this._resolverService).then(val => {
                    // if (element.failure) {
                    // 	// refresh the element on failure so that
                    // 	// we can update its rendering
                    // 	return tree.refresh(element).then(() => val.children);
                    // }
                    return val.children;
                });
            }
            throw new Error('bad tree');
        }
    };
    exports.DataSource = DataSource;
    exports.DataSource = DataSource = __decorate([
        __param(0, resolverService_1.ITextModelService)
    ], DataSource);
    //#endregion
    class Delegate {
        getHeight() {
            return 23;
        }
        getTemplateId(element) {
            if (element instanceof referencesModel_1.FileReferences) {
                return FileReferencesRenderer.id;
            }
            else {
                return OneReferenceRenderer.id;
            }
        }
    }
    exports.Delegate = Delegate;
    let StringRepresentationProvider = class StringRepresentationProvider {
        constructor(_keybindingService) {
            this._keybindingService = _keybindingService;
        }
        getKeyboardNavigationLabel(element) {
            if (element instanceof referencesModel_1.OneReference) {
                const parts = element.parent.getPreview(element)?.preview(element.range);
                if (parts) {
                    return parts.value;
                }
            }
            // FileReferences or unresolved OneReference
            return (0, resources_1.basename)(element.uri);
        }
    };
    exports.StringRepresentationProvider = StringRepresentationProvider;
    exports.StringRepresentationProvider = StringRepresentationProvider = __decorate([
        __param(0, keybinding_1.IKeybindingService)
    ], StringRepresentationProvider);
    class IdentityProvider {
        getId(element) {
            return element instanceof referencesModel_1.OneReference ? element.id : element.uri;
        }
    }
    exports.IdentityProvider = IdentityProvider;
    //#region render: File
    let FileReferencesTemplate = class FileReferencesTemplate extends lifecycle_1.Disposable {
        constructor(container, _labelService) {
            super();
            this._labelService = _labelService;
            const parent = document.createElement('div');
            parent.classList.add('reference-file');
            this.file = this._register(new iconLabel_1.IconLabel(parent, { supportHighlights: true }));
            this.badge = new countBadge_1.CountBadge(dom.append(parent, dom.$('.count')), {}, defaultStyles_1.defaultCountBadgeStyles);
            container.appendChild(parent);
        }
        set(element, matches) {
            const parent = (0, resources_1.dirname)(element.uri);
            this.file.setLabel(this._labelService.getUriBasenameLabel(element.uri), this._labelService.getUriLabel(parent, { relative: true }), { title: this._labelService.getUriLabel(element.uri), matches });
            const len = element.children.length;
            this.badge.setCount(len);
            if (len > 1) {
                this.badge.setTitleFormat((0, nls_1.localize)(989, "{0} references", len));
            }
            else {
                this.badge.setTitleFormat((0, nls_1.localize)(990, "{0} reference", len));
            }
        }
    };
    FileReferencesTemplate = __decorate([
        __param(1, label_1.ILabelService)
    ], FileReferencesTemplate);
    let FileReferencesRenderer = class FileReferencesRenderer {
        static { FileReferencesRenderer_1 = this; }
        static { this.id = 'FileReferencesRenderer'; }
        constructor(_instantiationService) {
            this._instantiationService = _instantiationService;
            this.templateId = FileReferencesRenderer_1.id;
        }
        renderTemplate(container) {
            return this._instantiationService.createInstance(FileReferencesTemplate, container);
        }
        renderElement(node, index, template) {
            template.set(node.element, (0, filters_1.createMatches)(node.filterData));
        }
        disposeTemplate(templateData) {
            templateData.dispose();
        }
    };
    exports.FileReferencesRenderer = FileReferencesRenderer;
    exports.FileReferencesRenderer = FileReferencesRenderer = FileReferencesRenderer_1 = __decorate([
        __param(0, instantiation_1.IInstantiationService)
    ], FileReferencesRenderer);
    //#endregion
    //#region render: Reference
    class OneReferenceTemplate extends lifecycle_1.Disposable {
        constructor(container) {
            super();
            this.label = this._register(new highlightedLabel_1.HighlightedLabel(container));
        }
        set(element, score) {
            const preview = element.parent.getPreview(element)?.preview(element.range);
            if (!preview || !preview.value) {
                // this means we FAILED to resolve the document or the value is the empty string
                this.label.set(`${(0, resources_1.basename)(element.uri)}:${element.range.startLineNumber + 1}:${element.range.startColumn + 1}`);
            }
            else {
                // render search match as highlight unless
                // we have score, then render the score
                const { value, highlight } = preview;
                if (score && !filters_1.FuzzyScore.isDefault(score)) {
                    this.label.element.classList.toggle('referenceMatch', false);
                    this.label.set(value, (0, filters_1.createMatches)(score));
                }
                else {
                    this.label.element.classList.toggle('referenceMatch', true);
                    this.label.set(value, [highlight]);
                }
            }
        }
    }
    class OneReferenceRenderer {
        constructor() {
            this.templateId = OneReferenceRenderer.id;
        }
        static { this.id = 'OneReferenceRenderer'; }
        renderTemplate(container) {
            return new OneReferenceTemplate(container);
        }
        renderElement(node, index, templateData) {
            templateData.set(node.element, node.filterData);
        }
        disposeTemplate(templateData) {
            templateData.dispose();
        }
    }
    exports.OneReferenceRenderer = OneReferenceRenderer;
    //#endregion
    class AccessibilityProvider {
        getWidgetAriaLabel() {
            return (0, nls_1.localize)(991, "References");
        }
        getAriaLabel(element) {
            return element.ariaMessage;
        }
    }
    exports.AccessibilityProvider = AccessibilityProvider;
});










define(__m[759/*vs/platform/actionWidget/browser/actionList*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,206/*vs/base/browser/ui/keybindingLabel/keybindingLabel*/,115/*vs/base/browser/ui/list/listWidget*/,18/*vs/base/common/cancellation*/,26/*vs/base/common/codicons*/,2/*vs/base/common/lifecycle*/,16/*vs/base/common/platform*/,30/*vs/base/common/themables*/,3/*vs/nls*/,58/*vs/platform/contextview/browser/contextView*/,31/*vs/platform/keybinding/common/keybinding*/,110/*vs/platform/theme/browser/defaultStyles*/,32/*vs/platform/theme/common/colorRegistry*/,306/*vs/css!vs/platform/actionWidget/browser/actionWidget*/]), function (require, exports, dom, keybindingLabel_1, listWidget_1, cancellation_1, codicons_1, lifecycle_1, platform_1, themables_1, nls_1, contextView_1, keybinding_1, defaultStyles_1, colorRegistry_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ActionList = exports.previewSelectedActionCommand = exports.acceptSelectedActionCommand = void 0;
    exports.acceptSelectedActionCommand = 'acceptSelectedCodeAction';
    exports.previewSelectedActionCommand = 'previewSelectedCodeAction';
    class HeaderRenderer {
        get templateId() { return "header" /* ActionListItemKind.Header */; }
        renderTemplate(container) {
            container.classList.add('group-header');
            const text = document.createElement('span');
            container.append(text);
            return { container, text };
        }
        renderElement(element, _index, templateData) {
            templateData.text.textContent = element.group?.title ?? '';
        }
        disposeTemplate(_templateData) {
            // noop
        }
    }
    let ActionItemRenderer = class ActionItemRenderer {
        get templateId() { return "action" /* ActionListItemKind.Action */; }
        constructor(_supportsPreview, _keybindingService) {
            this._supportsPreview = _supportsPreview;
            this._keybindingService = _keybindingService;
        }
        renderTemplate(container) {
            container.classList.add(this.templateId);
            const icon = document.createElement('div');
            icon.className = 'icon';
            container.append(icon);
            const text = document.createElement('span');
            text.className = 'title';
            container.append(text);
            const keybinding = new keybindingLabel_1.KeybindingLabel(container, platform_1.OS);
            return { container, icon, text, keybinding };
        }
        renderElement(element, _index, data) {
            if (element.group?.icon) {
                data.icon.className = themables_1.ThemeIcon.asClassName(element.group.icon);
                if (element.group.icon.color) {
                    data.icon.style.color = (0, colorRegistry_1.asCssVariable)(element.group.icon.color.id);
                }
            }
            else {
                data.icon.className = themables_1.ThemeIcon.asClassName(codicons_1.Codicon.lightBulb);
                data.icon.style.color = 'var(--vscode-editorLightBulb-foreground)';
            }
            if (!element.item || !element.label) {
                return;
            }
            data.text.textContent = stripNewlines(element.label);
            data.keybinding.set(element.keybinding);
            dom.setVisibility(!!element.keybinding, data.keybinding.element);
            const actionTitle = this._keybindingService.lookupKeybinding(exports.acceptSelectedActionCommand)?.getLabel();
            const previewTitle = this._keybindingService.lookupKeybinding(exports.previewSelectedActionCommand)?.getLabel();
            data.container.classList.toggle('option-disabled', element.disabled);
            if (element.disabled) {
                data.container.title = element.label;
            }
            else if (actionTitle && previewTitle) {
                if (this._supportsPreview && element.canPreview) {
                    data.container.title = (0, nls_1.localize)(1492, "{0} to Apply, {1} to Preview", actionTitle, previewTitle);
                }
                else {
                    data.container.title = (0, nls_1.localize)(1493, "{0} to Apply", actionTitle);
                }
            }
            else {
                data.container.title = '';
            }
        }
        disposeTemplate(_templateData) {
            _templateData.keybinding.dispose();
        }
    };
    ActionItemRenderer = __decorate([
        __param(1, keybinding_1.IKeybindingService)
    ], ActionItemRenderer);
    class AcceptSelectedEvent extends UIEvent {
        constructor() { super('acceptSelectedAction'); }
    }
    class PreviewSelectedEvent extends UIEvent {
        constructor() { super('previewSelectedAction'); }
    }
    function getKeyboardNavigationLabel(item) {
        // Filter out header vs. action
        if (item.kind === 'action') {
            return item.label;
        }
        return undefined;
    }
    let ActionList = class ActionList extends lifecycle_1.Disposable {
        constructor(user, preview, items, _delegate, _contextViewService, _keybindingService) {
            super();
            this._delegate = _delegate;
            this._contextViewService = _contextViewService;
            this._keybindingService = _keybindingService;
            this._actionLineHeight = 24;
            this._headerLineHeight = 26;
            this.cts = this._register(new cancellation_1.CancellationTokenSource());
            this.domNode = document.createElement('div');
            this.domNode.classList.add('actionList');
            const virtualDelegate = {
                getHeight: element => element.kind === "header" /* ActionListItemKind.Header */ ? this._headerLineHeight : this._actionLineHeight,
                getTemplateId: element => element.kind
            };
            this._list = this._register(new listWidget_1.List(user, this.domNode, virtualDelegate, [
                new ActionItemRenderer(preview, this._keybindingService),
                new HeaderRenderer(),
            ], {
                keyboardSupport: false,
                typeNavigationEnabled: true,
                keyboardNavigationLabelProvider: { getKeyboardNavigationLabel },
                accessibilityProvider: {
                    getAriaLabel: element => {
                        if (element.kind === "action" /* ActionListItemKind.Action */) {
                            let label = element.label ? stripNewlines(element?.label) : '';
                            if (element.disabled) {
                                label = (0, nls_1.localize)(1494, "{0}, Disabled Reason: {1}", label, element.disabled);
                            }
                            return label;
                        }
                        return null;
                    },
                    getWidgetAriaLabel: () => (0, nls_1.localize)(1495, "Action Widget"),
                    getRole: (e) => e.kind === "action" /* ActionListItemKind.Action */ ? 'option' : 'separator',
                    getWidgetRole: () => 'listbox',
                },
            }));
            this._list.style(defaultStyles_1.defaultListStyles);
            this._register(this._list.onMouseClick(e => this.onListClick(e)));
            this._register(this._list.onMouseOver(e => this.onListHover(e)));
            this._register(this._list.onDidChangeFocus(() => this.onFocus()));
            this._register(this._list.onDidChangeSelection(e => this.onListSelection(e)));
            this._allMenuItems = items;
            this._list.splice(0, this._list.length, this._allMenuItems);
            if (this._list.length) {
                this.focusNext();
            }
        }
        focusCondition(element) {
            return !element.disabled && element.kind === "action" /* ActionListItemKind.Action */;
        }
        hide(didCancel) {
            this._delegate.onHide(didCancel);
            this.cts.cancel();
            this._contextViewService.hideContextView();
        }
        layout(minWidth) {
            // Updating list height, depending on how many separators and headers there are.
            const numHeaders = this._allMenuItems.filter(item => item.kind === 'header').length;
            const itemsHeight = this._allMenuItems.length * this._actionLineHeight;
            const heightWithHeaders = itemsHeight + numHeaders * this._headerLineHeight - numHeaders * this._actionLineHeight;
            this._list.layout(heightWithHeaders);
            let maxWidth = minWidth;
            if (this._allMenuItems.length >= 50) {
                maxWidth = 380;
            }
            else {
                // For finding width dynamically (not using resize observer)
                const itemWidths = this._allMenuItems.map((_, index) => {
                    const element = this.domNode.ownerDocument.getElementById(this._list.getElementID(index));
                    if (element) {
                        element.style.width = 'auto';
                        const width = element.getBoundingClientRect().width;
                        element.style.width = '';
                        return width;
                    }
                    return 0;
                });
                // resize observer - can be used in the future since list widget supports dynamic height but not width
                maxWidth = Math.max(...itemWidths, minWidth);
            }
            const maxVhPrecentage = 0.7;
            const height = Math.min(heightWithHeaders, this.domNode.ownerDocument.body.clientHeight * maxVhPrecentage);
            this._list.layout(height, maxWidth);
            this.domNode.style.height = `${height}px`;
            this._list.domFocus();
            return maxWidth;
        }
        focusPrevious() {
            this._list.focusPrevious(1, true, undefined, this.focusCondition);
        }
        focusNext() {
            this._list.focusNext(1, true, undefined, this.focusCondition);
        }
        acceptSelected(preview) {
            const focused = this._list.getFocus();
            if (focused.length === 0) {
                return;
            }
            const focusIndex = focused[0];
            const element = this._list.element(focusIndex);
            if (!this.focusCondition(element)) {
                return;
            }
            const event = preview ? new PreviewSelectedEvent() : new AcceptSelectedEvent();
            this._list.setSelection([focusIndex], event);
        }
        onListSelection(e) {
            if (!e.elements.length) {
                return;
            }
            const element = e.elements[0];
            if (element.item && this.focusCondition(element)) {
                this._delegate.onSelect(element.item, e.browserEvent instanceof PreviewSelectedEvent);
            }
            else {
                this._list.setSelection([]);
            }
        }
        onFocus() {
            const focused = this._list.getFocus();
            if (focused.length === 0) {
                return;
            }
            const focusIndex = focused[0];
            const element = this._list.element(focusIndex);
            this._delegate.onFocus?.(element.item);
        }
        async onListHover(e) {
            const element = e.element;
            if (element && element.item && this.focusCondition(element)) {
                if (this._delegate.onHover && !element.disabled && element.kind === "action" /* ActionListItemKind.Action */) {
                    const result = await this._delegate.onHover(element.item, this.cts.token);
                    element.canPreview = result ? result.canPreview : undefined;
                }
                if (e.index) {
                    this._list.splice(e.index, 1, [element]);
                }
            }
            this._list.setFocus(typeof e.index === 'number' ? [e.index] : []);
        }
        onListClick(e) {
            if (e.element && this.focusCondition(e.element)) {
                this._list.setFocus([]);
            }
        }
    };
    exports.ActionList = ActionList;
    exports.ActionList = ActionList = __decorate([
        __param(4, contextView_1.IContextViewService),
        __param(5, keybinding_1.IKeybindingService)
    ], ActionList);
    function stripNewlines(str) {
        return str.replace(/\r\n|\r|\n/g, ' ');
    }
});










define(__m[760/*vs/platform/actionWidget/browser/actionWidget*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,87/*vs/base/browser/ui/actionbar/actionbar*/,2/*vs/base/common/lifecycle*/,3/*vs/nls*/,759/*vs/platform/actionWidget/browser/actionList*/,29/*vs/platform/actions/common/actions*/,12/*vs/platform/contextkey/common/contextkey*/,58/*vs/platform/contextview/browser/contextView*/,49/*vs/platform/instantiation/common/extensions*/,7/*vs/platform/instantiation/common/instantiation*/,32/*vs/platform/theme/common/colorRegistry*/,306/*vs/css!vs/platform/actionWidget/browser/actionWidget*/]), function (require, exports, dom, actionbar_1, lifecycle_1, nls_1, actionList_1, actions_1, contextkey_1, contextView_1, extensions_1, instantiation_1, colorRegistry_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.IActionWidgetService = void 0;
    (0, colorRegistry_1.registerColor)('actionBar.toggledBackground', colorRegistry_1.inputActiveOptionBackground, (0, nls_1.localize)(1496, 'Background color for toggled action items in action bar.'));
    const ActionWidgetContextKeys = {
        Visible: new contextkey_1.RawContextKey('codeActionMenuVisible', false, (0, nls_1.localize)(1497, "Whether the action widget list is visible"))
    };
    exports.IActionWidgetService = (0, instantiation_1.createDecorator)('actionWidgetService');
    let ActionWidgetService = class ActionWidgetService extends lifecycle_1.Disposable {
        get isVisible() {
            return ActionWidgetContextKeys.Visible.getValue(this._contextKeyService) || false;
        }
        constructor(_contextViewService, _contextKeyService, _instantiationService) {
            super();
            this._contextViewService = _contextViewService;
            this._contextKeyService = _contextKeyService;
            this._instantiationService = _instantiationService;
            this._list = this._register(new lifecycle_1.MutableDisposable());
        }
        show(user, supportsPreview, items, delegate, anchor, container, actionBarActions) {
            const visibleContext = ActionWidgetContextKeys.Visible.bindTo(this._contextKeyService);
            const list = this._instantiationService.createInstance(actionList_1.ActionList, user, supportsPreview, items, delegate);
            this._contextViewService.showContextView({
                getAnchor: () => anchor,
                render: (container) => {
                    visibleContext.set(true);
                    return this._renderWidget(container, list, actionBarActions ?? []);
                },
                onHide: (didCancel) => {
                    visibleContext.reset();
                    this._onWidgetClosed(didCancel);
                },
            }, container, false);
        }
        acceptSelected(preview) {
            this._list.value?.acceptSelected(preview);
        }
        focusPrevious() {
            this._list?.value?.focusPrevious();
        }
        focusNext() {
            this._list?.value?.focusNext();
        }
        hide(didCancel) {
            this._list.value?.hide(didCancel);
            this._list.clear();
        }
        _renderWidget(element, list, actionBarActions) {
            const widget = document.createElement('div');
            widget.classList.add('action-widget');
            element.appendChild(widget);
            this._list.value = list;
            if (this._list.value) {
                widget.appendChild(this._list.value.domNode);
            }
            else {
                throw new Error('List has no value');
            }
            const renderDisposables = new lifecycle_1.DisposableStore();
            // Invisible div to block mouse interaction in the rest of the UI
            const menuBlock = document.createElement('div');
            const block = element.appendChild(menuBlock);
            block.classList.add('context-view-block');
            renderDisposables.add(dom.addDisposableListener(block, dom.EventType.MOUSE_DOWN, e => e.stopPropagation()));
            // Invisible div to block mouse interaction with the menu
            const pointerBlockDiv = document.createElement('div');
            const pointerBlock = element.appendChild(pointerBlockDiv);
            pointerBlock.classList.add('context-view-pointerBlock');
            // Removes block on click INSIDE widget or ANY mouse movement
            renderDisposables.add(dom.addDisposableListener(pointerBlock, dom.EventType.POINTER_MOVE, () => pointerBlock.remove()));
            renderDisposables.add(dom.addDisposableListener(pointerBlock, dom.EventType.MOUSE_DOWN, () => pointerBlock.remove()));
            // Action bar
            let actionBarWidth = 0;
            if (actionBarActions.length) {
                const actionBar = this._createActionBar('.action-widget-action-bar', actionBarActions);
                if (actionBar) {
                    widget.appendChild(actionBar.getContainer().parentElement);
                    renderDisposables.add(actionBar);
                    actionBarWidth = actionBar.getContainer().offsetWidth;
                }
            }
            const width = this._list.value?.layout(actionBarWidth);
            widget.style.width = `${width}px`;
            const focusTracker = renderDisposables.add(dom.trackFocus(element));
            renderDisposables.add(focusTracker.onDidBlur(() => this.hide(true)));
            return renderDisposables;
        }
        _createActionBar(className, actions) {
            if (!actions.length) {
                return undefined;
            }
            const container = dom.$(className);
            const actionBar = new actionbar_1.ActionBar(container);
            actionBar.push(actions, { icon: false, label: true });
            return actionBar;
        }
        _onWidgetClosed(didCancel) {
            this._list.value?.hide(didCancel);
        }
    };
    ActionWidgetService = __decorate([
        __param(0, contextView_1.IContextViewService),
        __param(1, contextkey_1.IContextKeyService),
        __param(2, instantiation_1.IInstantiationService)
    ], ActionWidgetService);
    (0, extensions_1.registerSingleton)(exports.IActionWidgetService, ActionWidgetService, 1 /* InstantiationType.Delayed */);
    const weight = 100 /* KeybindingWeight.EditorContrib */ + 1000;
    (0, actions_1.registerAction2)(class extends actions_1.Action2 {
        constructor() {
            super({
                id: 'hideCodeActionWidget',
                title: (0, nls_1.localize2)(1498, "Hide action widget"),
                precondition: ActionWidgetContextKeys.Visible,
                keybinding: {
                    weight,
                    primary: 9 /* KeyCode.Escape */,
                    secondary: [1024 /* KeyMod.Shift */ | 9 /* KeyCode.Escape */]
                },
            });
        }
        run(accessor) {
            accessor.get(exports.IActionWidgetService).hide(true);
        }
    });
    (0, actions_1.registerAction2)(class extends actions_1.Action2 {
        constructor() {
            super({
                id: 'selectPrevCodeAction',
                title: (0, nls_1.localize2)(1499, "Select previous action"),
                precondition: ActionWidgetContextKeys.Visible,
                keybinding: {
                    weight,
                    primary: 16 /* KeyCode.UpArrow */,
                    secondary: [2048 /* KeyMod.CtrlCmd */ | 16 /* KeyCode.UpArrow */],
                    mac: { primary: 16 /* KeyCode.UpArrow */, secondary: [2048 /* KeyMod.CtrlCmd */ | 16 /* KeyCode.UpArrow */, 256 /* KeyMod.WinCtrl */ | 46 /* KeyCode.KeyP */] },
                }
            });
        }
        run(accessor) {
            const widgetService = accessor.get(exports.IActionWidgetService);
            if (widgetService instanceof ActionWidgetService) {
                widgetService.focusPrevious();
            }
        }
    });
    (0, actions_1.registerAction2)(class extends actions_1.Action2 {
        constructor() {
            super({
                id: 'selectNextCodeAction',
                title: (0, nls_1.localize2)(1500, "Select next action"),
                precondition: ActionWidgetContextKeys.Visible,
                keybinding: {
                    weight,
                    primary: 18 /* KeyCode.DownArrow */,
                    secondary: [2048 /* KeyMod.CtrlCmd */ | 18 /* KeyCode.DownArrow */],
                    mac: { primary: 18 /* KeyCode.DownArrow */, secondary: [2048 /* KeyMod.CtrlCmd */ | 18 /* KeyCode.DownArrow */, 256 /* KeyMod.WinCtrl */ | 44 /* KeyCode.KeyN */] }
                }
            });
        }
        run(accessor) {
            const widgetService = accessor.get(exports.IActionWidgetService);
            if (widgetService instanceof ActionWidgetService) {
                widgetService.focusNext();
            }
        }
    });
    (0, actions_1.registerAction2)(class extends actions_1.Action2 {
        constructor() {
            super({
                id: actionList_1.acceptSelectedActionCommand,
                title: (0, nls_1.localize2)(1501, "Accept selected action"),
                precondition: ActionWidgetContextKeys.Visible,
                keybinding: {
                    weight,
                    primary: 3 /* KeyCode.Enter */,
                    secondary: [2048 /* KeyMod.CtrlCmd */ | 89 /* KeyCode.Period */],
                }
            });
        }
        run(accessor) {
            const widgetService = accessor.get(exports.IActionWidgetService);
            if (widgetService instanceof ActionWidgetService) {
                widgetService.acceptSelected();
            }
        }
    });
    (0, actions_1.registerAction2)(class extends actions_1.Action2 {
        constructor() {
            super({
                id: actionList_1.previewSelectedActionCommand,
                title: (0, nls_1.localize2)(1502, "Preview selected action"),
                precondition: ActionWidgetContextKeys.Visible,
                keybinding: {
                    weight,
                    primary: 2048 /* KeyMod.CtrlCmd */ | 3 /* KeyCode.Enter */,
                }
            });
        }
        run(accessor) {
            const widgetService = accessor.get(exports.IActionWidgetService);
            if (widgetService instanceof ActionWidgetService) {
                widgetService.acceptSelected(true);
            }
        }
    });
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[761/*vs/platform/contextview/browser/contextMenuHandler*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,77/*vs/base/browser/mouseEvent*/,642/*vs/base/browser/ui/menu/menu*/,41/*vs/base/common/actions*/,8/*vs/base/common/errors*/,2/*vs/base/common/lifecycle*/,110/*vs/platform/theme/browser/defaultStyles*/]), function (require, exports, dom_1, mouseEvent_1, menu_1, actions_1, errors_1, lifecycle_1, defaultStyles_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ContextMenuHandler = void 0;
    class ContextMenuHandler {
        constructor(contextViewService, telemetryService, notificationService, keybindingService) {
            this.contextViewService = contextViewService;
            this.telemetryService = telemetryService;
            this.notificationService = notificationService;
            this.keybindingService = keybindingService;
            this.focusToReturn = null;
            this.lastContainer = null;
            this.block = null;
            this.blockDisposable = null;
            this.options = { blockMouse: true };
        }
        configure(options) {
            this.options = options;
        }
        showContextMenu(delegate) {
            const actions = delegate.getActions();
            if (!actions.length) {
                return; // Don't render an empty context menu
            }
            this.focusToReturn = (0, dom_1.getActiveElement)();
            let menu;
            const shadowRootElement = (0, dom_1.isHTMLElement)(delegate.domForShadowRoot) ? delegate.domForShadowRoot : undefined;
            this.contextViewService.showContextView({
                getAnchor: () => delegate.getAnchor(),
                canRelayout: false,
                anchorAlignment: delegate.anchorAlignment,
                anchorAxisAlignment: delegate.anchorAxisAlignment,
                render: (container) => {
                    this.lastContainer = container;
                    const className = delegate.getMenuClassName ? delegate.getMenuClassName() : '';
                    if (className) {
                        container.className += ' ' + className;
                    }
                    // Render invisible div to block mouse interaction in the rest of the UI
                    if (this.options.blockMouse) {
                        this.block = container.appendChild((0, dom_1.$)('.context-view-block'));
                        this.block.style.position = 'fixed';
                        this.block.style.cursor = 'initial';
                        this.block.style.left = '0';
                        this.block.style.top = '0';
                        this.block.style.width = '100%';
                        this.block.style.height = '100%';
                        this.block.style.zIndex = '-1';
                        this.blockDisposable?.dispose();
                        this.blockDisposable = (0, dom_1.addDisposableListener)(this.block, dom_1.EventType.MOUSE_DOWN, e => e.stopPropagation());
                    }
                    const menuDisposables = new lifecycle_1.DisposableStore();
                    const actionRunner = delegate.actionRunner || new actions_1.ActionRunner();
                    actionRunner.onWillRun(evt => this.onActionRun(evt, !delegate.skipTelemetry), this, menuDisposables);
                    actionRunner.onDidRun(this.onDidActionRun, this, menuDisposables);
                    menu = new menu_1.Menu(container, actions, {
                        actionViewItemProvider: delegate.getActionViewItem,
                        context: delegate.getActionsContext ? delegate.getActionsContext() : null,
                        actionRunner,
                        getKeyBinding: delegate.getKeyBinding ? delegate.getKeyBinding : action => this.keybindingService.lookupKeybinding(action.id)
                    }, defaultStyles_1.defaultMenuStyles);
                    menu.onDidCancel(() => this.contextViewService.hideContextView(true), null, menuDisposables);
                    menu.onDidBlur(() => this.contextViewService.hideContextView(true), null, menuDisposables);
                    const targetWindow = (0, dom_1.getWindow)(container);
                    menuDisposables.add((0, dom_1.addDisposableListener)(targetWindow, dom_1.EventType.BLUR, () => this.contextViewService.hideContextView(true)));
                    menuDisposables.add((0, dom_1.addDisposableListener)(targetWindow, dom_1.EventType.MOUSE_DOWN, (e) => {
                        if (e.defaultPrevented) {
                            return;
                        }
                        const event = new mouseEvent_1.StandardMouseEvent(targetWindow, e);
                        let element = event.target;
                        // Don't do anything as we are likely creating a context menu
                        if (event.rightButton) {
                            return;
                        }
                        while (element) {
                            if (element === container) {
                                return;
                            }
                            element = element.parentElement;
                        }
                        this.contextViewService.hideContextView(true);
                    }));
                    return (0, lifecycle_1.combinedDisposable)(menuDisposables, menu);
                },
                focus: () => {
                    menu?.focus(!!delegate.autoSelectFirstItem);
                },
                onHide: (didCancel) => {
                    delegate.onHide?.(!!didCancel);
                    if (this.block) {
                        this.block.remove();
                        this.block = null;
                    }
                    this.blockDisposable?.dispose();
                    this.blockDisposable = null;
                    if (!!this.lastContainer && ((0, dom_1.getActiveElement)() === this.lastContainer || (0, dom_1.isAncestor)((0, dom_1.getActiveElement)(), this.lastContainer))) {
                        this.focusToReturn?.focus();
                    }
                    this.lastContainer = null;
                }
            }, shadowRootElement, !!shadowRootElement);
        }
        onActionRun(e, logTelemetry) {
            if (logTelemetry) {
                this.telemetryService.publicLog2('workbenchActionExecuted', { id: e.action.id, from: 'contextMenu' });
            }
            this.contextViewService.hideContextView(false);
        }
        onDidActionRun(e) {
            if (e.error && !(0, errors_1.isCancellationError)(e.error)) {
                this.notificationService.error(e.error);
            }
        }
    }
    exports.ContextMenuHandler = ContextMenuHandler;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[216/*vs/platform/list/browser/listService*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,637/*vs/base/browser/ui/list/listPaging*/,115/*vs/base/browser/ui/list/listWidget*/,638/*vs/base/browser/ui/table/tableWidget*/,176/*vs/base/browser/ui/tree/abstractTree*/,645/*vs/base/browser/ui/tree/asyncDataTree*/,644/*vs/base/browser/ui/tree/dataTree*/,360/*vs/base/browser/ui/tree/objectTree*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,3/*vs/nls*/,28/*vs/platform/configuration/common/configuration*/,109/*vs/platform/configuration/common/configurationRegistry*/,12/*vs/platform/contextkey/common/contextkey*/,179/*vs/platform/contextkey/common/contextkeys*/,58/*vs/platform/contextview/browser/contextView*/,7/*vs/platform/instantiation/common/instantiation*/,31/*vs/platform/keybinding/common/keybinding*/,38/*vs/platform/registry/common/platform*/,110/*vs/platform/theme/browser/defaultStyles*/]), function (require, exports, dom_1, listPaging_1, listWidget_1, tableWidget_1, abstractTree_1, asyncDataTree_1, dataTree_1, objectTree_1, event_1, lifecycle_1, nls_1, configuration_1, configurationRegistry_1, contextkey_1, contextkeys_1, contextView_1, instantiation_1, keybinding_1, platform_1, defaultStyles_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.WorkbenchCompressibleAsyncDataTree = exports.WorkbenchAsyncDataTree = exports.WorkbenchDataTree = exports.WorkbenchCompressibleObjectTree = exports.WorkbenchObjectTree = exports.WorkbenchTable = exports.WorkbenchPagedList = exports.WorkbenchList = exports.WorkbenchTreeFindOpen = exports.WorkbenchTreeElementHasChild = exports.WorkbenchTreeElementCanExpand = exports.WorkbenchTreeElementHasParent = exports.WorkbenchTreeElementCanCollapse = exports.WorkbenchListSupportsFind = exports.WorkbenchListSelectionNavigation = exports.WorkbenchListMultiSelection = exports.WorkbenchListDoubleSelection = exports.WorkbenchListHasSelectionOrFocus = exports.WorkbenchListFocusContextKey = exports.WorkbenchListSupportsMultiSelectContextKey = exports.WorkbenchTreeStickyScrollFocused = exports.RawWorkbenchListFocusContextKey = exports.WorkbenchListScrollAtBottomContextKey = exports.WorkbenchListScrollAtTopContextKey = exports.RawWorkbenchListScrollAtBoundaryContextKey = exports.ListService = exports.IListService = void 0;
    exports.IListService = (0, instantiation_1.createDecorator)('listService');
    class ListService {
        get lastFocusedList() {
            return this._lastFocusedWidget;
        }
        constructor() {
            this.disposables = new lifecycle_1.DisposableStore();
            this.lists = [];
            this._lastFocusedWidget = undefined;
            this._hasCreatedStyleController = false;
        }
        setLastFocusedList(widget) {
            if (widget === this._lastFocusedWidget) {
                return;
            }
            this._lastFocusedWidget?.getHTMLElement().classList.remove('last-focused');
            this._lastFocusedWidget = widget;
            this._lastFocusedWidget?.getHTMLElement().classList.add('last-focused');
        }
        register(widget, extraContextKeys) {
            if (!this._hasCreatedStyleController) {
                this._hasCreatedStyleController = true;
                // create a shared default tree style sheet for performance reasons
                const styleController = new listWidget_1.DefaultStyleController((0, dom_1.createStyleSheet)(), '');
                styleController.style(defaultStyles_1.defaultListStyles);
            }
            if (this.lists.some(l => l.widget === widget)) {
                throw new Error('Cannot register the same widget multiple times');
            }
            // Keep in our lists list
            const registeredList = { widget, extraContextKeys };
            this.lists.push(registeredList);
            // Check for currently being focused
            if ((0, dom_1.isActiveElement)(widget.getHTMLElement())) {
                this.setLastFocusedList(widget);
            }
            return (0, lifecycle_1.combinedDisposable)(widget.onDidFocus(() => this.setLastFocusedList(widget)), (0, lifecycle_1.toDisposable)(() => this.lists.splice(this.lists.indexOf(registeredList), 1)), widget.onDidDispose(() => {
                this.lists = this.lists.filter(l => l !== registeredList);
                if (this._lastFocusedWidget === widget) {
                    this.setLastFocusedList(undefined);
                }
            }));
        }
        dispose() {
            this.disposables.dispose();
        }
    }
    exports.ListService = ListService;
    exports.RawWorkbenchListScrollAtBoundaryContextKey = new contextkey_1.RawContextKey('listScrollAtBoundary', 'none');
    exports.WorkbenchListScrollAtTopContextKey = contextkey_1.ContextKeyExpr.or(exports.RawWorkbenchListScrollAtBoundaryContextKey.isEqualTo('top'), exports.RawWorkbenchListScrollAtBoundaryContextKey.isEqualTo('both'));
    exports.WorkbenchListScrollAtBottomContextKey = contextkey_1.ContextKeyExpr.or(exports.RawWorkbenchListScrollAtBoundaryContextKey.isEqualTo('bottom'), exports.RawWorkbenchListScrollAtBoundaryContextKey.isEqualTo('both'));
    exports.RawWorkbenchListFocusContextKey = new contextkey_1.RawContextKey('listFocus', true);
    exports.WorkbenchTreeStickyScrollFocused = new contextkey_1.RawContextKey('treestickyScrollFocused', false);
    exports.WorkbenchListSupportsMultiSelectContextKey = new contextkey_1.RawContextKey('listSupportsMultiselect', true);
    exports.WorkbenchListFocusContextKey = contextkey_1.ContextKeyExpr.and(exports.RawWorkbenchListFocusContextKey, contextkey_1.ContextKeyExpr.not(contextkeys_1.InputFocusedContextKey), exports.WorkbenchTreeStickyScrollFocused.negate());
    exports.WorkbenchListHasSelectionOrFocus = new contextkey_1.RawContextKey('listHasSelectionOrFocus', false);
    exports.WorkbenchListDoubleSelection = new contextkey_1.RawContextKey('listDoubleSelection', false);
    exports.WorkbenchListMultiSelection = new contextkey_1.RawContextKey('listMultiSelection', false);
    exports.WorkbenchListSelectionNavigation = new contextkey_1.RawContextKey('listSelectionNavigation', false);
    exports.WorkbenchListSupportsFind = new contextkey_1.RawContextKey('listSupportsFind', true);
    exports.WorkbenchTreeElementCanCollapse = new contextkey_1.RawContextKey('treeElementCanCollapse', false);
    exports.WorkbenchTreeElementHasParent = new contextkey_1.RawContextKey('treeElementHasParent', false);
    exports.WorkbenchTreeElementCanExpand = new contextkey_1.RawContextKey('treeElementCanExpand', false);
    exports.WorkbenchTreeElementHasChild = new contextkey_1.RawContextKey('treeElementHasChild', false);
    exports.WorkbenchTreeFindOpen = new contextkey_1.RawContextKey('treeFindOpen', false);
    const WorkbenchListTypeNavigationModeKey = 'listTypeNavigationMode';
    /**
     * @deprecated in favor of WorkbenchListTypeNavigationModeKey
     */
    const WorkbenchListAutomaticKeyboardNavigationLegacyKey = 'listAutomaticKeyboardNavigation';
    function createScopedContextKeyService(contextKeyService, widget) {
        const result = contextKeyService.createScoped(widget.getHTMLElement());
        exports.RawWorkbenchListFocusContextKey.bindTo(result);
        return result;
    }
    function createScrollObserver(contextKeyService, widget) {
        const listScrollAt = exports.RawWorkbenchListScrollAtBoundaryContextKey.bindTo(contextKeyService);
        const update = () => {
            const atTop = widget.scrollTop === 0;
            // We need a threshold `1` since scrollHeight is rounded.
            // https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollHeight#determine_if_an_element_has_been_totally_scrolled
            const atBottom = widget.scrollHeight - widget.renderHeight - widget.scrollTop < 1;
            if (atTop && atBottom) {
                listScrollAt.set('both');
            }
            else if (atTop) {
                listScrollAt.set('top');
            }
            else if (atBottom) {
                listScrollAt.set('bottom');
            }
            else {
                listScrollAt.set('none');
            }
        };
        update();
        return widget.onDidScroll(update);
    }
    const multiSelectModifierSettingKey = 'workbench.list.multiSelectModifier';
    const openModeSettingKey = 'workbench.list.openMode';
    const horizontalScrollingKey = 'workbench.list.horizontalScrolling';
    const defaultFindModeSettingKey = 'workbench.list.defaultFindMode';
    const typeNavigationModeSettingKey = 'workbench.list.typeNavigationMode';
    /** @deprecated in favor of `workbench.list.defaultFindMode` and `workbench.list.typeNavigationMode` */
    const keyboardNavigationSettingKey = 'workbench.list.keyboardNavigation';
    const scrollByPageKey = 'workbench.list.scrollByPage';
    const defaultFindMatchTypeSettingKey = 'workbench.list.defaultFindMatchType';
    const treeIndentKey = 'workbench.tree.indent';
    const treeRenderIndentGuidesKey = 'workbench.tree.renderIndentGuides';
    const listSmoothScrolling = 'workbench.list.smoothScrolling';
    const mouseWheelScrollSensitivityKey = 'workbench.list.mouseWheelScrollSensitivity';
    const fastScrollSensitivityKey = 'workbench.list.fastScrollSensitivity';
    const treeExpandMode = 'workbench.tree.expandMode';
    const treeStickyScroll = 'workbench.tree.enableStickyScroll';
    const treeStickyScrollMaxElements = 'workbench.tree.stickyScrollMaxItemCount';
    function useAltAsMultipleSelectionModifier(configurationService) {
        return configurationService.getValue(multiSelectModifierSettingKey) === 'alt';
    }
    class MultipleSelectionController extends lifecycle_1.Disposable {
        constructor(configurationService) {
            super();
            this.configurationService = configurationService;
            this.useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(configurationService);
            this.registerListeners();
        }
        registerListeners() {
            this._register(this.configurationService.onDidChangeConfiguration(e => {
                if (e.affectsConfiguration(multiSelectModifierSettingKey)) {
                    this.useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(this.configurationService);
                }
            }));
        }
        isSelectionSingleChangeEvent(event) {
            if (this.useAltAsMultipleSelectionModifier) {
                return event.browserEvent.altKey;
            }
            return (0, listWidget_1.isSelectionSingleChangeEvent)(event);
        }
        isSelectionRangeChangeEvent(event) {
            return (0, listWidget_1.isSelectionRangeChangeEvent)(event);
        }
    }
    function toWorkbenchListOptions(accessor, options) {
        const configurationService = accessor.get(configuration_1.IConfigurationService);
        const keybindingService = accessor.get(keybinding_1.IKeybindingService);
        const disposables = new lifecycle_1.DisposableStore();
        const result = {
            ...options,
            keyboardNavigationDelegate: { mightProducePrintableCharacter(e) { return keybindingService.mightProducePrintableCharacter(e); } },
            smoothScrolling: Boolean(configurationService.getValue(listSmoothScrolling)),
            mouseWheelScrollSensitivity: configurationService.getValue(mouseWheelScrollSensitivityKey),
            fastScrollSensitivity: configurationService.getValue(fastScrollSensitivityKey),
            multipleSelectionController: options.multipleSelectionController ?? disposables.add(new MultipleSelectionController(configurationService)),
            keyboardNavigationEventFilter: createKeyboardNavigationEventFilter(keybindingService),
            scrollByPage: Boolean(configurationService.getValue(scrollByPageKey))
        };
        return [result, disposables];
    }
    let WorkbenchList = class WorkbenchList extends listWidget_1.List {
        constructor(user, container, delegate, renderers, options, contextKeyService, listService, configurationService, instantiationService) {
            const horizontalScrolling = typeof options.horizontalScrolling !== 'undefined' ? options.horizontalScrolling : Boolean(configurationService.getValue(horizontalScrollingKey));
            const [workbenchListOptions, workbenchListOptionsDisposable] = instantiationService.invokeFunction(toWorkbenchListOptions, options);
            super(user, container, delegate, renderers, {
                keyboardSupport: false,
                ...workbenchListOptions,
                horizontalScrolling,
            });
            this.disposables.add(workbenchListOptionsDisposable);
            this.contextKeyService = createScopedContextKeyService(contextKeyService, this);
            this.disposables.add(createScrollObserver(this.contextKeyService, this));
            this.listSupportsMultiSelect = exports.WorkbenchListSupportsMultiSelectContextKey.bindTo(this.contextKeyService);
            this.listSupportsMultiSelect.set(options.multipleSelectionSupport !== false);
            const listSelectionNavigation = exports.WorkbenchListSelectionNavigation.bindTo(this.contextKeyService);
            listSelectionNavigation.set(Boolean(options.selectionNavigation));
            this.listHasSelectionOrFocus = exports.WorkbenchListHasSelectionOrFocus.bindTo(this.contextKeyService);
            this.listDoubleSelection = exports.WorkbenchListDoubleSelection.bindTo(this.contextKeyService);
            this.listMultiSelection = exports.WorkbenchListMultiSelection.bindTo(this.contextKeyService);
            this.horizontalScrolling = options.horizontalScrolling;
            this._useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(configurationService);
            this.disposables.add(this.contextKeyService);
            this.disposables.add(listService.register(this));
            this.updateStyles(options.overrideStyles);
            this.disposables.add(this.onDidChangeSelection(() => {
                const selection = this.getSelection();
                const focus = this.getFocus();
                this.contextKeyService.bufferChangeEvents(() => {
                    this.listHasSelectionOrFocus.set(selection.length > 0 || focus.length > 0);
                    this.listMultiSelection.set(selection.length > 1);
                    this.listDoubleSelection.set(selection.length === 2);
                });
            }));
            this.disposables.add(this.onDidChangeFocus(() => {
                const selection = this.getSelection();
                const focus = this.getFocus();
                this.listHasSelectionOrFocus.set(selection.length > 0 || focus.length > 0);
            }));
            this.disposables.add(configurationService.onDidChangeConfiguration(e => {
                if (e.affectsConfiguration(multiSelectModifierSettingKey)) {
                    this._useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(configurationService);
                }
                let options = {};
                if (e.affectsConfiguration(horizontalScrollingKey) && this.horizontalScrolling === undefined) {
                    const horizontalScrolling = Boolean(configurationService.getValue(horizontalScrollingKey));
                    options = { ...options, horizontalScrolling };
                }
                if (e.affectsConfiguration(scrollByPageKey)) {
                    const scrollByPage = Boolean(configurationService.getValue(scrollByPageKey));
                    options = { ...options, scrollByPage };
                }
                if (e.affectsConfiguration(listSmoothScrolling)) {
                    const smoothScrolling = Boolean(configurationService.getValue(listSmoothScrolling));
                    options = { ...options, smoothScrolling };
                }
                if (e.affectsConfiguration(mouseWheelScrollSensitivityKey)) {
                    const mouseWheelScrollSensitivity = configurationService.getValue(mouseWheelScrollSensitivityKey);
                    options = { ...options, mouseWheelScrollSensitivity };
                }
                if (e.affectsConfiguration(fastScrollSensitivityKey)) {
                    const fastScrollSensitivity = configurationService.getValue(fastScrollSensitivityKey);
                    options = { ...options, fastScrollSensitivity };
                }
                if (Object.keys(options).length > 0) {
                    this.updateOptions(options);
                }
            }));
            this.navigator = new ListResourceNavigator(this, { configurationService, ...options });
            this.disposables.add(this.navigator);
        }
        updateOptions(options) {
            super.updateOptions(options);
            if (options.overrideStyles !== undefined) {
                this.updateStyles(options.overrideStyles);
            }
            if (options.multipleSelectionSupport !== undefined) {
                this.listSupportsMultiSelect.set(!!options.multipleSelectionSupport);
            }
        }
        updateStyles(styles) {
            this.style(styles ? (0, defaultStyles_1.getListStyles)(styles) : defaultStyles_1.defaultListStyles);
        }
    };
    exports.WorkbenchList = WorkbenchList;
    exports.WorkbenchList = WorkbenchList = __decorate([
        __param(5, contextkey_1.IContextKeyService),
        __param(6, exports.IListService),
        __param(7, configuration_1.IConfigurationService),
        __param(8, instantiation_1.IInstantiationService)
    ], WorkbenchList);
    let WorkbenchPagedList = class WorkbenchPagedList extends listPaging_1.PagedList {
        constructor(user, container, delegate, renderers, options, contextKeyService, listService, configurationService, instantiationService) {
            const horizontalScrolling = typeof options.horizontalScrolling !== 'undefined' ? options.horizontalScrolling : Boolean(configurationService.getValue(horizontalScrollingKey));
            const [workbenchListOptions, workbenchListOptionsDisposable] = instantiationService.invokeFunction(toWorkbenchListOptions, options);
            super(user, container, delegate, renderers, {
                keyboardSupport: false,
                ...workbenchListOptions,
                horizontalScrolling,
            });
            this.disposables = new lifecycle_1.DisposableStore();
            this.disposables.add(workbenchListOptionsDisposable);
            this.contextKeyService = createScopedContextKeyService(contextKeyService, this);
            this.disposables.add(createScrollObserver(this.contextKeyService, this.widget));
            this.horizontalScrolling = options.horizontalScrolling;
            this.listSupportsMultiSelect = exports.WorkbenchListSupportsMultiSelectContextKey.bindTo(this.contextKeyService);
            this.listSupportsMultiSelect.set(options.multipleSelectionSupport !== false);
            const listSelectionNavigation = exports.WorkbenchListSelectionNavigation.bindTo(this.contextKeyService);
            listSelectionNavigation.set(Boolean(options.selectionNavigation));
            this._useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(configurationService);
            this.disposables.add(this.contextKeyService);
            this.disposables.add(listService.register(this));
            this.updateStyles(options.overrideStyles);
            this.disposables.add(configurationService.onDidChangeConfiguration(e => {
                if (e.affectsConfiguration(multiSelectModifierSettingKey)) {
                    this._useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(configurationService);
                }
                let options = {};
                if (e.affectsConfiguration(horizontalScrollingKey) && this.horizontalScrolling === undefined) {
                    const horizontalScrolling = Boolean(configurationService.getValue(horizontalScrollingKey));
                    options = { ...options, horizontalScrolling };
                }
                if (e.affectsConfiguration(scrollByPageKey)) {
                    const scrollByPage = Boolean(configurationService.getValue(scrollByPageKey));
                    options = { ...options, scrollByPage };
                }
                if (e.affectsConfiguration(listSmoothScrolling)) {
                    const smoothScrolling = Boolean(configurationService.getValue(listSmoothScrolling));
                    options = { ...options, smoothScrolling };
                }
                if (e.affectsConfiguration(mouseWheelScrollSensitivityKey)) {
                    const mouseWheelScrollSensitivity = configurationService.getValue(mouseWheelScrollSensitivityKey);
                    options = { ...options, mouseWheelScrollSensitivity };
                }
                if (e.affectsConfiguration(fastScrollSensitivityKey)) {
                    const fastScrollSensitivity = configurationService.getValue(fastScrollSensitivityKey);
                    options = { ...options, fastScrollSensitivity };
                }
                if (Object.keys(options).length > 0) {
                    this.updateOptions(options);
                }
            }));
            this.navigator = new ListResourceNavigator(this, { configurationService, ...options });
            this.disposables.add(this.navigator);
        }
        updateOptions(options) {
            super.updateOptions(options);
            if (options.overrideStyles !== undefined) {
                this.updateStyles(options.overrideStyles);
            }
            if (options.multipleSelectionSupport !== undefined) {
                this.listSupportsMultiSelect.set(!!options.multipleSelectionSupport);
            }
        }
        updateStyles(styles) {
            this.style(styles ? (0, defaultStyles_1.getListStyles)(styles) : defaultStyles_1.defaultListStyles);
        }
        dispose() {
            this.disposables.dispose();
            super.dispose();
        }
    };
    exports.WorkbenchPagedList = WorkbenchPagedList;
    exports.WorkbenchPagedList = WorkbenchPagedList = __decorate([
        __param(5, contextkey_1.IContextKeyService),
        __param(6, exports.IListService),
        __param(7, configuration_1.IConfigurationService),
        __param(8, instantiation_1.IInstantiationService)
    ], WorkbenchPagedList);
    let WorkbenchTable = class WorkbenchTable extends tableWidget_1.Table {
        constructor(user, container, delegate, columns, renderers, options, contextKeyService, listService, configurationService, instantiationService) {
            const horizontalScrolling = typeof options.horizontalScrolling !== 'undefined' ? options.horizontalScrolling : Boolean(configurationService.getValue(horizontalScrollingKey));
            const [workbenchListOptions, workbenchListOptionsDisposable] = instantiationService.invokeFunction(toWorkbenchListOptions, options);
            super(user, container, delegate, columns, renderers, {
                keyboardSupport: false,
                ...workbenchListOptions,
                horizontalScrolling,
            });
            this.disposables.add(workbenchListOptionsDisposable);
            this.contextKeyService = createScopedContextKeyService(contextKeyService, this);
            this.disposables.add(createScrollObserver(this.contextKeyService, this));
            this.listSupportsMultiSelect = exports.WorkbenchListSupportsMultiSelectContextKey.bindTo(this.contextKeyService);
            this.listSupportsMultiSelect.set(options.multipleSelectionSupport !== false);
            const listSelectionNavigation = exports.WorkbenchListSelectionNavigation.bindTo(this.contextKeyService);
            listSelectionNavigation.set(Boolean(options.selectionNavigation));
            this.listHasSelectionOrFocus = exports.WorkbenchListHasSelectionOrFocus.bindTo(this.contextKeyService);
            this.listDoubleSelection = exports.WorkbenchListDoubleSelection.bindTo(this.contextKeyService);
            this.listMultiSelection = exports.WorkbenchListMultiSelection.bindTo(this.contextKeyService);
            this.horizontalScrolling = options.horizontalScrolling;
            this._useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(configurationService);
            this.disposables.add(this.contextKeyService);
            this.disposables.add(listService.register(this));
            this.updateStyles(options.overrideStyles);
            this.disposables.add(this.onDidChangeSelection(() => {
                const selection = this.getSelection();
                const focus = this.getFocus();
                this.contextKeyService.bufferChangeEvents(() => {
                    this.listHasSelectionOrFocus.set(selection.length > 0 || focus.length > 0);
                    this.listMultiSelection.set(selection.length > 1);
                    this.listDoubleSelection.set(selection.length === 2);
                });
            }));
            this.disposables.add(this.onDidChangeFocus(() => {
                const selection = this.getSelection();
                const focus = this.getFocus();
                this.listHasSelectionOrFocus.set(selection.length > 0 || focus.length > 0);
            }));
            this.disposables.add(configurationService.onDidChangeConfiguration(e => {
                if (e.affectsConfiguration(multiSelectModifierSettingKey)) {
                    this._useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(configurationService);
                }
                let options = {};
                if (e.affectsConfiguration(horizontalScrollingKey) && this.horizontalScrolling === undefined) {
                    const horizontalScrolling = Boolean(configurationService.getValue(horizontalScrollingKey));
                    options = { ...options, horizontalScrolling };
                }
                if (e.affectsConfiguration(scrollByPageKey)) {
                    const scrollByPage = Boolean(configurationService.getValue(scrollByPageKey));
                    options = { ...options, scrollByPage };
                }
                if (e.affectsConfiguration(listSmoothScrolling)) {
                    const smoothScrolling = Boolean(configurationService.getValue(listSmoothScrolling));
                    options = { ...options, smoothScrolling };
                }
                if (e.affectsConfiguration(mouseWheelScrollSensitivityKey)) {
                    const mouseWheelScrollSensitivity = configurationService.getValue(mouseWheelScrollSensitivityKey);
                    options = { ...options, mouseWheelScrollSensitivity };
                }
                if (e.affectsConfiguration(fastScrollSensitivityKey)) {
                    const fastScrollSensitivity = configurationService.getValue(fastScrollSensitivityKey);
                    options = { ...options, fastScrollSensitivity };
                }
                if (Object.keys(options).length > 0) {
                    this.updateOptions(options);
                }
            }));
            this.navigator = new TableResourceNavigator(this, { configurationService, ...options });
            this.disposables.add(this.navigator);
        }
        updateOptions(options) {
            super.updateOptions(options);
            if (options.overrideStyles !== undefined) {
                this.updateStyles(options.overrideStyles);
            }
            if (options.multipleSelectionSupport !== undefined) {
                this.listSupportsMultiSelect.set(!!options.multipleSelectionSupport);
            }
        }
        updateStyles(styles) {
            this.style(styles ? (0, defaultStyles_1.getListStyles)(styles) : defaultStyles_1.defaultListStyles);
        }
        dispose() {
            this.disposables.dispose();
            super.dispose();
        }
    };
    exports.WorkbenchTable = WorkbenchTable;
    exports.WorkbenchTable = WorkbenchTable = __decorate([
        __param(6, contextkey_1.IContextKeyService),
        __param(7, exports.IListService),
        __param(8, configuration_1.IConfigurationService),
        __param(9, instantiation_1.IInstantiationService)
    ], WorkbenchTable);
    class ResourceNavigator extends lifecycle_1.Disposable {
        constructor(widget, options) {
            super();
            this.widget = widget;
            this._onDidOpen = this._register(new event_1.Emitter());
            this.onDidOpen = this._onDidOpen.event;
            this._register(event_1.Event.filter(this.widget.onDidChangeSelection, e => (0, dom_1.isKeyboardEvent)(e.browserEvent))(e => this.onSelectionFromKeyboard(e)));
            this._register(this.widget.onPointer((e) => this.onPointer(e.element, e.browserEvent)));
            this._register(this.widget.onMouseDblClick((e) => this.onMouseDblClick(e.element, e.browserEvent)));
            if (typeof options?.openOnSingleClick !== 'boolean' && options?.configurationService) {
                this.openOnSingleClick = options?.configurationService.getValue(openModeSettingKey) !== 'doubleClick';
                this._register(options?.configurationService.onDidChangeConfiguration(e => {
                    if (e.affectsConfiguration(openModeSettingKey)) {
                        this.openOnSingleClick = options?.configurationService.getValue(openModeSettingKey) !== 'doubleClick';
                    }
                }));
            }
            else {
                this.openOnSingleClick = options?.openOnSingleClick ?? true;
            }
        }
        onSelectionFromKeyboard(event) {
            if (event.elements.length !== 1) {
                return;
            }
            const selectionKeyboardEvent = event.browserEvent;
            const preserveFocus = typeof selectionKeyboardEvent.preserveFocus === 'boolean' ? selectionKeyboardEvent.preserveFocus : true;
            const pinned = typeof selectionKeyboardEvent.pinned === 'boolean' ? selectionKeyboardEvent.pinned : !preserveFocus;
            const sideBySide = false;
            this._open(this.getSelectedElement(), preserveFocus, pinned, sideBySide, event.browserEvent);
        }
        onPointer(element, browserEvent) {
            if (!this.openOnSingleClick) {
                return;
            }
            const isDoubleClick = browserEvent.detail === 2;
            if (isDoubleClick) {
                return;
            }
            const isMiddleClick = browserEvent.button === 1;
            const preserveFocus = true;
            const pinned = isMiddleClick;
            const sideBySide = browserEvent.ctrlKey || browserEvent.metaKey || browserEvent.altKey;
            this._open(element, preserveFocus, pinned, sideBySide, browserEvent);
        }
        onMouseDblClick(element, browserEvent) {
            if (!browserEvent) {
                return;
            }
            // copied from AbstractTree
            const target = browserEvent.target;
            const onTwistie = target.classList.contains('monaco-tl-twistie')
                || (target.classList.contains('monaco-icon-label') && target.classList.contains('folder-icon') && browserEvent.offsetX < 16);
            if (onTwistie) {
                return;
            }
            const preserveFocus = false;
            const pinned = true;
            const sideBySide = (browserEvent.ctrlKey || browserEvent.metaKey || browserEvent.altKey);
            this._open(element, preserveFocus, pinned, sideBySide, browserEvent);
        }
        _open(element, preserveFocus, pinned, sideBySide, browserEvent) {
            if (!element) {
                return;
            }
            this._onDidOpen.fire({
                editorOptions: {
                    preserveFocus,
                    pinned,
                    revealIfVisible: true
                },
                sideBySide,
                element,
                browserEvent
            });
        }
    }
    class ListResourceNavigator extends ResourceNavigator {
        constructor(widget, options) {
            super(widget, options);
            this.widget = widget;
        }
        getSelectedElement() {
            return this.widget.getSelectedElements()[0];
        }
    }
    class TableResourceNavigator extends ResourceNavigator {
        constructor(widget, options) {
            super(widget, options);
        }
        getSelectedElement() {
            return this.widget.getSelectedElements()[0];
        }
    }
    class TreeResourceNavigator extends ResourceNavigator {
        constructor(widget, options) {
            super(widget, options);
        }
        getSelectedElement() {
            return this.widget.getSelection()[0] ?? undefined;
        }
    }
    function createKeyboardNavigationEventFilter(keybindingService) {
        let inMultiChord = false;
        return event => {
            if (event.toKeyCodeChord().isModifierKey()) {
                return false;
            }
            if (inMultiChord) {
                inMultiChord = false;
                return false;
            }
            const result = keybindingService.softDispatch(event, event.target);
            if (result.kind === 1 /* ResultKind.MoreChordsNeeded */) {
                inMultiChord = true;
                return false;
            }
            inMultiChord = false;
            return result.kind === 0 /* ResultKind.NoMatchingKb */;
        };
    }
    let WorkbenchObjectTree = class WorkbenchObjectTree extends objectTree_1.ObjectTree {
        constructor(user, container, delegate, renderers, options, instantiationService, contextKeyService, listService, configurationService) {
            const { options: treeOptions, getTypeNavigationMode, disposable } = instantiationService.invokeFunction(workbenchTreeDataPreamble, options);
            super(user, container, delegate, renderers, treeOptions);
            this.disposables.add(disposable);
            this.internals = new WorkbenchTreeInternals(this, options, getTypeNavigationMode, options.overrideStyles, contextKeyService, listService, configurationService);
            this.disposables.add(this.internals);
        }
        updateOptions(options) {
            super.updateOptions(options);
            this.internals.updateOptions(options);
        }
    };
    exports.WorkbenchObjectTree = WorkbenchObjectTree;
    exports.WorkbenchObjectTree = WorkbenchObjectTree = __decorate([
        __param(5, instantiation_1.IInstantiationService),
        __param(6, contextkey_1.IContextKeyService),
        __param(7, exports.IListService),
        __param(8, configuration_1.IConfigurationService)
    ], WorkbenchObjectTree);
    let WorkbenchCompressibleObjectTree = class WorkbenchCompressibleObjectTree extends objectTree_1.CompressibleObjectTree {
        constructor(user, container, delegate, renderers, options, instantiationService, contextKeyService, listService, configurationService) {
            const { options: treeOptions, getTypeNavigationMode, disposable } = instantiationService.invokeFunction(workbenchTreeDataPreamble, options);
            super(user, container, delegate, renderers, treeOptions);
            this.disposables.add(disposable);
            this.internals = new WorkbenchTreeInternals(this, options, getTypeNavigationMode, options.overrideStyles, contextKeyService, listService, configurationService);
            this.disposables.add(this.internals);
        }
        updateOptions(options = {}) {
            super.updateOptions(options);
            if (options.overrideStyles) {
                this.internals.updateStyleOverrides(options.overrideStyles);
            }
            this.internals.updateOptions(options);
        }
    };
    exports.WorkbenchCompressibleObjectTree = WorkbenchCompressibleObjectTree;
    exports.WorkbenchCompressibleObjectTree = WorkbenchCompressibleObjectTree = __decorate([
        __param(5, instantiation_1.IInstantiationService),
        __param(6, contextkey_1.IContextKeyService),
        __param(7, exports.IListService),
        __param(8, configuration_1.IConfigurationService)
    ], WorkbenchCompressibleObjectTree);
    let WorkbenchDataTree = class WorkbenchDataTree extends dataTree_1.DataTree {
        constructor(user, container, delegate, renderers, dataSource, options, instantiationService, contextKeyService, listService, configurationService) {
            const { options: treeOptions, getTypeNavigationMode, disposable } = instantiationService.invokeFunction(workbenchTreeDataPreamble, options);
            super(user, container, delegate, renderers, dataSource, treeOptions);
            this.disposables.add(disposable);
            this.internals = new WorkbenchTreeInternals(this, options, getTypeNavigationMode, options.overrideStyles, contextKeyService, listService, configurationService);
            this.disposables.add(this.internals);
        }
        updateOptions(options = {}) {
            super.updateOptions(options);
            if (options.overrideStyles !== undefined) {
                this.internals.updateStyleOverrides(options.overrideStyles);
            }
            this.internals.updateOptions(options);
        }
    };
    exports.WorkbenchDataTree = WorkbenchDataTree;
    exports.WorkbenchDataTree = WorkbenchDataTree = __decorate([
        __param(6, instantiation_1.IInstantiationService),
        __param(7, contextkey_1.IContextKeyService),
        __param(8, exports.IListService),
        __param(9, configuration_1.IConfigurationService)
    ], WorkbenchDataTree);
    let WorkbenchAsyncDataTree = class WorkbenchAsyncDataTree extends asyncDataTree_1.AsyncDataTree {
        get onDidOpen() { return this.internals.onDidOpen; }
        constructor(user, container, delegate, renderers, dataSource, options, instantiationService, contextKeyService, listService, configurationService) {
            const { options: treeOptions, getTypeNavigationMode, disposable } = instantiationService.invokeFunction(workbenchTreeDataPreamble, options);
            super(user, container, delegate, renderers, dataSource, treeOptions);
            this.disposables.add(disposable);
            this.internals = new WorkbenchTreeInternals(this, options, getTypeNavigationMode, options.overrideStyles, contextKeyService, listService, configurationService);
            this.disposables.add(this.internals);
        }
        updateOptions(options = {}) {
            super.updateOptions(options);
            if (options.overrideStyles) {
                this.internals.updateStyleOverrides(options.overrideStyles);
            }
            this.internals.updateOptions(options);
        }
    };
    exports.WorkbenchAsyncDataTree = WorkbenchAsyncDataTree;
    exports.WorkbenchAsyncDataTree = WorkbenchAsyncDataTree = __decorate([
        __param(6, instantiation_1.IInstantiationService),
        __param(7, contextkey_1.IContextKeyService),
        __param(8, exports.IListService),
        __param(9, configuration_1.IConfigurationService)
    ], WorkbenchAsyncDataTree);
    let WorkbenchCompressibleAsyncDataTree = class WorkbenchCompressibleAsyncDataTree extends asyncDataTree_1.CompressibleAsyncDataTree {
        constructor(user, container, virtualDelegate, compressionDelegate, renderers, dataSource, options, instantiationService, contextKeyService, listService, configurationService) {
            const { options: treeOptions, getTypeNavigationMode, disposable } = instantiationService.invokeFunction(workbenchTreeDataPreamble, options);
            super(user, container, virtualDelegate, compressionDelegate, renderers, dataSource, treeOptions);
            this.disposables.add(disposable);
            this.internals = new WorkbenchTreeInternals(this, options, getTypeNavigationMode, options.overrideStyles, contextKeyService, listService, configurationService);
            this.disposables.add(this.internals);
        }
        updateOptions(options) {
            super.updateOptions(options);
            this.internals.updateOptions(options);
        }
    };
    exports.WorkbenchCompressibleAsyncDataTree = WorkbenchCompressibleAsyncDataTree;
    exports.WorkbenchCompressibleAsyncDataTree = WorkbenchCompressibleAsyncDataTree = __decorate([
        __param(7, instantiation_1.IInstantiationService),
        __param(8, contextkey_1.IContextKeyService),
        __param(9, exports.IListService),
        __param(10, configuration_1.IConfigurationService)
    ], WorkbenchCompressibleAsyncDataTree);
    function getDefaultTreeFindMode(configurationService) {
        const value = configurationService.getValue(defaultFindModeSettingKey);
        if (value === 'highlight') {
            return abstractTree_1.TreeFindMode.Highlight;
        }
        else if (value === 'filter') {
            return abstractTree_1.TreeFindMode.Filter;
        }
        const deprecatedValue = configurationService.getValue(keyboardNavigationSettingKey);
        if (deprecatedValue === 'simple' || deprecatedValue === 'highlight') {
            return abstractTree_1.TreeFindMode.Highlight;
        }
        else if (deprecatedValue === 'filter') {
            return abstractTree_1.TreeFindMode.Filter;
        }
        return undefined;
    }
    function getDefaultTreeFindMatchType(configurationService) {
        const value = configurationService.getValue(defaultFindMatchTypeSettingKey);
        if (value === 'fuzzy') {
            return abstractTree_1.TreeFindMatchType.Fuzzy;
        }
        else if (value === 'contiguous') {
            return abstractTree_1.TreeFindMatchType.Contiguous;
        }
        return undefined;
    }
    function workbenchTreeDataPreamble(accessor, options) {
        const configurationService = accessor.get(configuration_1.IConfigurationService);
        const contextViewService = accessor.get(contextView_1.IContextViewService);
        const contextKeyService = accessor.get(contextkey_1.IContextKeyService);
        const instantiationService = accessor.get(instantiation_1.IInstantiationService);
        const getTypeNavigationMode = () => {
            // give priority to the context key value to specify a value
            const modeString = contextKeyService.getContextKeyValue(WorkbenchListTypeNavigationModeKey);
            if (modeString === 'automatic') {
                return listWidget_1.TypeNavigationMode.Automatic;
            }
            else if (modeString === 'trigger') {
                return listWidget_1.TypeNavigationMode.Trigger;
            }
            // also check the deprecated context key to set the mode to 'trigger'
            const modeBoolean = contextKeyService.getContextKeyValue(WorkbenchListAutomaticKeyboardNavigationLegacyKey);
            if (modeBoolean === false) {
                return listWidget_1.TypeNavigationMode.Trigger;
            }
            // finally, check the setting
            const configString = configurationService.getValue(typeNavigationModeSettingKey);
            if (configString === 'automatic') {
                return listWidget_1.TypeNavigationMode.Automatic;
            }
            else if (configString === 'trigger') {
                return listWidget_1.TypeNavigationMode.Trigger;
            }
            return undefined;
        };
        const horizontalScrolling = options.horizontalScrolling !== undefined ? options.horizontalScrolling : Boolean(configurationService.getValue(horizontalScrollingKey));
        const [workbenchListOptions, disposable] = instantiationService.invokeFunction(toWorkbenchListOptions, options);
        const paddingBottom = options.paddingBottom;
        const renderIndentGuides = options.renderIndentGuides !== undefined ? options.renderIndentGuides : configurationService.getValue(treeRenderIndentGuidesKey);
        return {
            getTypeNavigationMode,
            disposable,
            options: {
                // ...options, // TODO@Joao why is this not splatted here?
                keyboardSupport: false,
                ...workbenchListOptions,
                indent: typeof configurationService.getValue(treeIndentKey) === 'number' ? configurationService.getValue(treeIndentKey) : undefined,
                renderIndentGuides,
                smoothScrolling: Boolean(configurationService.getValue(listSmoothScrolling)),
                defaultFindMode: getDefaultTreeFindMode(configurationService),
                defaultFindMatchType: getDefaultTreeFindMatchType(configurationService),
                horizontalScrolling,
                scrollByPage: Boolean(configurationService.getValue(scrollByPageKey)),
                paddingBottom: paddingBottom,
                hideTwistiesOfChildlessElements: options.hideTwistiesOfChildlessElements,
                expandOnlyOnTwistieClick: options.expandOnlyOnTwistieClick ?? (configurationService.getValue(treeExpandMode) === 'doubleClick'),
                contextViewProvider: contextViewService,
                findWidgetStyles: defaultStyles_1.defaultFindWidgetStyles,
                enableStickyScroll: Boolean(configurationService.getValue(treeStickyScroll)),
                stickyScrollMaxItemCount: Number(configurationService.getValue(treeStickyScrollMaxElements)),
            }
        };
    }
    let WorkbenchTreeInternals = class WorkbenchTreeInternals {
        get onDidOpen() { return this.navigator.onDidOpen; }
        constructor(tree, options, getTypeNavigationMode, overrideStyles, contextKeyService, listService, configurationService) {
            this.tree = tree;
            this.disposables = [];
            this.contextKeyService = createScopedContextKeyService(contextKeyService, tree);
            this.disposables.push(createScrollObserver(this.contextKeyService, tree));
            this.listSupportsMultiSelect = exports.WorkbenchListSupportsMultiSelectContextKey.bindTo(this.contextKeyService);
            this.listSupportsMultiSelect.set(options.multipleSelectionSupport !== false);
            const listSelectionNavigation = exports.WorkbenchListSelectionNavigation.bindTo(this.contextKeyService);
            listSelectionNavigation.set(Boolean(options.selectionNavigation));
            this.listSupportFindWidget = exports.WorkbenchListSupportsFind.bindTo(this.contextKeyService);
            this.listSupportFindWidget.set(options.findWidgetEnabled ?? true);
            this.hasSelectionOrFocus = exports.WorkbenchListHasSelectionOrFocus.bindTo(this.contextKeyService);
            this.hasDoubleSelection = exports.WorkbenchListDoubleSelection.bindTo(this.contextKeyService);
            this.hasMultiSelection = exports.WorkbenchListMultiSelection.bindTo(this.contextKeyService);
            this.treeElementCanCollapse = exports.WorkbenchTreeElementCanCollapse.bindTo(this.contextKeyService);
            this.treeElementHasParent = exports.WorkbenchTreeElementHasParent.bindTo(this.contextKeyService);
            this.treeElementCanExpand = exports.WorkbenchTreeElementCanExpand.bindTo(this.contextKeyService);
            this.treeElementHasChild = exports.WorkbenchTreeElementHasChild.bindTo(this.contextKeyService);
            this.treeFindOpen = exports.WorkbenchTreeFindOpen.bindTo(this.contextKeyService);
            this.treeStickyScrollFocused = exports.WorkbenchTreeStickyScrollFocused.bindTo(this.contextKeyService);
            this._useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(configurationService);
            this.updateStyleOverrides(overrideStyles);
            const updateCollapseContextKeys = () => {
                const focus = tree.getFocus()[0];
                if (!focus) {
                    return;
                }
                const node = tree.getNode(focus);
                this.treeElementCanCollapse.set(node.collapsible && !node.collapsed);
                this.treeElementHasParent.set(!!tree.getParentElement(focus));
                this.treeElementCanExpand.set(node.collapsible && node.collapsed);
                this.treeElementHasChild.set(!!tree.getFirstElementChild(focus));
            };
            const interestingContextKeys = new Set();
            interestingContextKeys.add(WorkbenchListTypeNavigationModeKey);
            interestingContextKeys.add(WorkbenchListAutomaticKeyboardNavigationLegacyKey);
            this.disposables.push(this.contextKeyService, listService.register(tree), tree.onDidChangeSelection(() => {
                const selection = tree.getSelection();
                const focus = tree.getFocus();
                this.contextKeyService.bufferChangeEvents(() => {
                    this.hasSelectionOrFocus.set(selection.length > 0 || focus.length > 0);
                    this.hasMultiSelection.set(selection.length > 1);
                    this.hasDoubleSelection.set(selection.length === 2);
                });
            }), tree.onDidChangeFocus(() => {
                const selection = tree.getSelection();
                const focus = tree.getFocus();
                this.hasSelectionOrFocus.set(selection.length > 0 || focus.length > 0);
                updateCollapseContextKeys();
            }), tree.onDidChangeCollapseState(updateCollapseContextKeys), tree.onDidChangeModel(updateCollapseContextKeys), tree.onDidChangeFindOpenState(enabled => this.treeFindOpen.set(enabled)), tree.onDidChangeStickyScrollFocused(focused => this.treeStickyScrollFocused.set(focused)), configurationService.onDidChangeConfiguration(e => {
                let newOptions = {};
                if (e.affectsConfiguration(multiSelectModifierSettingKey)) {
                    this._useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(configurationService);
                }
                if (e.affectsConfiguration(treeIndentKey)) {
                    const indent = configurationService.getValue(treeIndentKey);
                    newOptions = { ...newOptions, indent };
                }
                if (e.affectsConfiguration(treeRenderIndentGuidesKey) && options.renderIndentGuides === undefined) {
                    const renderIndentGuides = configurationService.getValue(treeRenderIndentGuidesKey);
                    newOptions = { ...newOptions, renderIndentGuides };
                }
                if (e.affectsConfiguration(listSmoothScrolling)) {
                    const smoothScrolling = Boolean(configurationService.getValue(listSmoothScrolling));
                    newOptions = { ...newOptions, smoothScrolling };
                }
                if (e.affectsConfiguration(defaultFindModeSettingKey) || e.affectsConfiguration(keyboardNavigationSettingKey)) {
                    const defaultFindMode = getDefaultTreeFindMode(configurationService);
                    newOptions = { ...newOptions, defaultFindMode };
                }
                if (e.affectsConfiguration(typeNavigationModeSettingKey) || e.affectsConfiguration(keyboardNavigationSettingKey)) {
                    const typeNavigationMode = getTypeNavigationMode();
                    newOptions = { ...newOptions, typeNavigationMode };
                }
                if (e.affectsConfiguration(defaultFindMatchTypeSettingKey)) {
                    const defaultFindMatchType = getDefaultTreeFindMatchType(configurationService);
                    newOptions = { ...newOptions, defaultFindMatchType };
                }
                if (e.affectsConfiguration(horizontalScrollingKey) && options.horizontalScrolling === undefined) {
                    const horizontalScrolling = Boolean(configurationService.getValue(horizontalScrollingKey));
                    newOptions = { ...newOptions, horizontalScrolling };
                }
                if (e.affectsConfiguration(scrollByPageKey)) {
                    const scrollByPage = Boolean(configurationService.getValue(scrollByPageKey));
                    newOptions = { ...newOptions, scrollByPage };
                }
                if (e.affectsConfiguration(treeExpandMode) && options.expandOnlyOnTwistieClick === undefined) {
                    newOptions = { ...newOptions, expandOnlyOnTwistieClick: configurationService.getValue(treeExpandMode) === 'doubleClick' };
                }
                if (e.affectsConfiguration(treeStickyScroll)) {
                    const enableStickyScroll = configurationService.getValue(treeStickyScroll);
                    newOptions = { ...newOptions, enableStickyScroll };
                }
                if (e.affectsConfiguration(treeStickyScrollMaxElements)) {
                    const stickyScrollMaxItemCount = Math.max(1, configurationService.getValue(treeStickyScrollMaxElements));
                    newOptions = { ...newOptions, stickyScrollMaxItemCount };
                }
                if (e.affectsConfiguration(mouseWheelScrollSensitivityKey)) {
                    const mouseWheelScrollSensitivity = configurationService.getValue(mouseWheelScrollSensitivityKey);
                    newOptions = { ...newOptions, mouseWheelScrollSensitivity };
                }
                if (e.affectsConfiguration(fastScrollSensitivityKey)) {
                    const fastScrollSensitivity = configurationService.getValue(fastScrollSensitivityKey);
                    newOptions = { ...newOptions, fastScrollSensitivity };
                }
                if (Object.keys(newOptions).length > 0) {
                    tree.updateOptions(newOptions);
                }
            }), this.contextKeyService.onDidChangeContext(e => {
                if (e.affectsSome(interestingContextKeys)) {
                    tree.updateOptions({ typeNavigationMode: getTypeNavigationMode() });
                }
            }));
            this.navigator = new TreeResourceNavigator(tree, { configurationService, ...options });
            this.disposables.push(this.navigator);
        }
        updateOptions(options) {
            if (options.multipleSelectionSupport !== undefined) {
                this.listSupportsMultiSelect.set(!!options.multipleSelectionSupport);
            }
        }
        updateStyleOverrides(overrideStyles) {
            this.tree.style(overrideStyles ? (0, defaultStyles_1.getListStyles)(overrideStyles) : defaultStyles_1.defaultListStyles);
        }
        dispose() {
            this.disposables = (0, lifecycle_1.dispose)(this.disposables);
        }
    };
    WorkbenchTreeInternals = __decorate([
        __param(4, contextkey_1.IContextKeyService),
        __param(5, exports.IListService),
        __param(6, configuration_1.IConfigurationService)
    ], WorkbenchTreeInternals);
    const configurationRegistry = platform_1.Registry.as(configurationRegistry_1.Extensions.Configuration);
    configurationRegistry.registerConfiguration({
        id: 'workbench',
        order: 7,
        title: (0, nls_1.localize)(1542, "Workbench"),
        type: 'object',
        properties: {
            [multiSelectModifierSettingKey]: {
                type: 'string',
                enum: ['ctrlCmd', 'alt'],
                markdownEnumDescriptions: [
                    (0, nls_1.localize)(1543, "Maps to `Control` on Windows and Linux and to `Command` on macOS."),
                    (0, nls_1.localize)(1544, "Maps to `Alt` on Windows and Linux and to `Option` on macOS.")
                ],
                default: 'ctrlCmd',
                description: (0, nls_1.localize)(1545, "The modifier to be used to add an item in trees and lists to a multi-selection with the mouse (for example in the explorer, open editors and scm view). The 'Open to Side' mouse gestures - if supported - will adapt such that they do not conflict with the multiselect modifier.")






            },
            [openModeSettingKey]: {
                type: 'string',
                enum: ['singleClick', 'doubleClick'],
                default: 'singleClick',
                description: (0, nls_1.localize)(1546, "Controls how to open items in trees and lists using the mouse (if supported). Note that some trees and lists might choose to ignore this setting if it is not applicable.")



            },
            [horizontalScrollingKey]: {
                type: 'boolean',
                default: false,
                description: (0, nls_1.localize)(1547, "Controls whether lists and trees support horizontal scrolling in the workbench. Warning: turning on this setting has a performance implication.")
            },
            [scrollByPageKey]: {
                type: 'boolean',
                default: false,
                description: (0, nls_1.localize)(1548, "Controls whether clicks in the scrollbar scroll page by page.")
            },
            [treeIndentKey]: {
                type: 'number',
                default: 8,
                minimum: 4,
                maximum: 40,
                description: (0, nls_1.localize)(1549, "Controls tree indentation in pixels.")
            },
            [treeRenderIndentGuidesKey]: {
                type: 'string',
                enum: ['none', 'onHover', 'always'],
                default: 'onHover',
                description: (0, nls_1.localize)(1550, "Controls whether the tree should render indent guides.")
            },
            [listSmoothScrolling]: {
                type: 'boolean',
                default: false,
                description: (0, nls_1.localize)(1551, "Controls whether lists and trees have smooth scrolling."),
            },
            [mouseWheelScrollSensitivityKey]: {
                type: 'number',
                default: 1,
                markdownDescription: (0, nls_1.localize)(1552, "A multiplier to be used on the `deltaX` and `deltaY` of mouse wheel scroll events.")
            },
            [fastScrollSensitivityKey]: {
                type: 'number',
                default: 5,
                markdownDescription: (0, nls_1.localize)(1553, "Scrolling speed multiplier when pressing `Alt`.")
            },
            [defaultFindModeSettingKey]: {
                type: 'string',
                enum: ['highlight', 'filter'],
                enumDescriptions: [
                    (0, nls_1.localize)(1554, "Highlight elements when searching. Further up and down navigation will traverse only the highlighted elements."),
                    (0, nls_1.localize)(1555, "Filter elements when searching.")
                ],
                default: 'highlight',
                description: (0, nls_1.localize)(1556, "Controls the default find mode for lists and trees in the workbench.")
            },
            [keyboardNavigationSettingKey]: {
                type: 'string',
                enum: ['simple', 'highlight', 'filter'],
                enumDescriptions: [
                    (0, nls_1.localize)(1557, "Simple keyboard navigation focuses elements which match the keyboard input. Matching is done only on prefixes."),
                    (0, nls_1.localize)(1558, "Highlight keyboard navigation highlights elements which match the keyboard input. Further up and down navigation will traverse only the highlighted elements."),
                    (0, nls_1.localize)(1559, "Filter keyboard navigation will filter out and hide all the elements which do not match the keyboard input.")
                ],
                default: 'highlight',
                description: (0, nls_1.localize)(1560, "Controls the keyboard navigation style for lists and trees in the workbench. Can be simple, highlight and filter."),
                deprecated: true,
                deprecationMessage: (0, nls_1.localize)(1561, "Please use 'workbench.list.defaultFindMode' and	'workbench.list.typeNavigationMode' instead.")
            },
            [defaultFindMatchTypeSettingKey]: {
                type: 'string',
                enum: ['fuzzy', 'contiguous'],
                enumDescriptions: [
                    (0, nls_1.localize)(1562, "Use fuzzy matching when searching."),
                    (0, nls_1.localize)(1563, "Use contiguous matching when searching.")
                ],
                default: 'fuzzy',
                description: (0, nls_1.localize)(1564, "Controls the type of matching used when searching lists and trees in the workbench.")
            },
            [treeExpandMode]: {
                type: 'string',
                enum: ['singleClick', 'doubleClick'],
                default: 'singleClick',
                description: (0, nls_1.localize)(1565, "Controls how tree folders are expanded when clicking the folder names. Note that some trees and lists might choose to ignore this setting if it is not applicable."),
            },
            [treeStickyScroll]: {
                type: 'boolean',
                default: true,
                description: (0, nls_1.localize)(1566, "Controls whether sticky scrolling is enabled in trees."),
            },
            [treeStickyScrollMaxElements]: {
                type: 'number',
                minimum: 1,
                default: 7,
                markdownDescription: (0, nls_1.localize)(1567, "Controls the number of sticky elements displayed in the tree when {0} is enabled.", '`#workbench.tree.enableStickyScroll#`'),
            },
            [typeNavigationModeSettingKey]: {
                type: 'string',
                enum: ['automatic', 'trigger'],
                default: 'automatic',
                markdownDescription: (0, nls_1.localize)(1568, "Controls how type navigation works in lists and trees in the workbench. When set to `trigger`, type navigation begins once the `list.triggerTypeNavigation` command is run."),
            }
        }
    });
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[71/*vs/platform/theme/common/iconRegistry*/], __M([1/*require*/,0/*exports*/,14/*vs/base/common/async*/,26/*vs/base/common/codicons*/,191/*vs/base/common/codiconsUtil*/,30/*vs/base/common/themables*/,6/*vs/base/common/event*/,19/*vs/base/common/types*/,22/*vs/base/common/uri*/,3/*vs/nls*/,273/*vs/platform/jsonschemas/common/jsonContributionRegistry*/,38/*vs/platform/registry/common/platform*/]), function (require, exports, async_1, codicons_1, codiconsUtil_1, themables_1, event_1, types_1, uri_1, nls_1, jsonContributionRegistry_1, platform) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.spinningLoading = exports.syncing = exports.gotoNextLocation = exports.gotoPreviousLocation = exports.widgetClose = exports.iconsSchemaId = exports.IconFontDefinition = exports.IconContribution = exports.Extensions = void 0;
    exports.registerIcon = registerIcon;
    exports.getIconRegistry = getIconRegistry;
    //  ------ API types
    // icon registry
    exports.Extensions = {
        IconContribution: 'base.contributions.icons'
    };
    var IconContribution;
    (function (IconContribution) {
        function getDefinition(contribution, registry) {
            let definition = contribution.defaults;
            while (themables_1.ThemeIcon.isThemeIcon(definition)) {
                const c = iconRegistry.getIcon(definition.id);
                if (!c) {
                    return undefined;
                }
                definition = c.defaults;
            }
            return definition;
        }
        IconContribution.getDefinition = getDefinition;
    })(IconContribution || (exports.IconContribution = IconContribution = {}));
    var IconFontDefinition;
    (function (IconFontDefinition) {
        function toJSONObject(iconFont) {
            return {
                weight: iconFont.weight,
                style: iconFont.style,
                src: iconFont.src.map(s => ({ format: s.format, location: s.location.toString() }))
            };
        }
        IconFontDefinition.toJSONObject = toJSONObject;
        function fromJSONObject(json) {
            const stringOrUndef = (s) => (0, types_1.isString)(s) ? s : undefined;
            if (json && Array.isArray(json.src) && json.src.every((s) => (0, types_1.isString)(s.format) && (0, types_1.isString)(s.location))) {
                return {
                    weight: stringOrUndef(json.weight),
                    style: stringOrUndef(json.style),
                    src: json.src.map((s) => ({ format: s.format, location: uri_1.URI.parse(s.location) }))
                };
            }
            return undefined;
        }
        IconFontDefinition.fromJSONObject = fromJSONObject;
    })(IconFontDefinition || (exports.IconFontDefinition = IconFontDefinition = {}));
    class IconRegistry {
        constructor() {
            this._onDidChange = new event_1.Emitter();
            this.onDidChange = this._onDidChange.event;
            this.iconSchema = {
                definitions: {
                    icons: {
                        type: 'object',
                        properties: {
                            fontId: { type: 'string', description: (0, nls_1.localize)(1838, 'The id of the font to use. If not set, the font that is defined first is used.') },
                            fontCharacter: { type: 'string', description: (0, nls_1.localize)(1839, 'The font character associated with the icon definition.') }
                        },
                        additionalProperties: false,
                        defaultSnippets: [{ body: { fontCharacter: '\\\\e030' } }]
                    }
                },
                type: 'object',
                properties: {}
            };
            this.iconReferenceSchema = { type: 'string', pattern: `^${themables_1.ThemeIcon.iconNameExpression}$`, enum: [], enumDescriptions: [] };
            this.iconsById = {};
            this.iconFontsById = {};
        }
        registerIcon(id, defaults, description, deprecationMessage) {
            const existing = this.iconsById[id];
            if (existing) {
                if (description && !existing.description) {
                    existing.description = description;
                    this.iconSchema.properties[id].markdownDescription = `${description} $(${id})`;
                    const enumIndex = this.iconReferenceSchema.enum.indexOf(id);
                    if (enumIndex !== -1) {
                        this.iconReferenceSchema.enumDescriptions[enumIndex] = description;
                    }
                    this._onDidChange.fire();
                }
                return existing;
            }
            const iconContribution = { id, description, defaults, deprecationMessage };
            this.iconsById[id] = iconContribution;
            const propertySchema = { $ref: '#/definitions/icons' };
            if (deprecationMessage) {
                propertySchema.deprecationMessage = deprecationMessage;
            }
            if (description) {
                propertySchema.markdownDescription = `${description}: $(${id})`;
            }
            this.iconSchema.properties[id] = propertySchema;
            this.iconReferenceSchema.enum.push(id);
            this.iconReferenceSchema.enumDescriptions.push(description || '');
            this._onDidChange.fire();
            return { id };
        }
        getIcons() {
            return Object.keys(this.iconsById).map(id => this.iconsById[id]);
        }
        getIcon(id) {
            return this.iconsById[id];
        }
        getIconSchema() {
            return this.iconSchema;
        }
        toString() {
            const sorter = (i1, i2) => {
                return i1.id.localeCompare(i2.id);
            };
            const classNames = (i) => {
                while (themables_1.ThemeIcon.isThemeIcon(i.defaults)) {
                    i = this.iconsById[i.defaults.id];
                }
                return `codicon codicon-${i ? i.id : ''}`;
            };
            const reference = [];
            reference.push(`| preview     | identifier                        | default codicon ID                | description`);
            reference.push(`| ----------- | --------------------------------- | --------------------------------- | --------------------------------- |`);
            const contributions = Object.keys(this.iconsById).map(key => this.iconsById[key]);
            for (const i of contributions.filter(i => !!i.description).sort(sorter)) {
                reference.push(`|<i class="${classNames(i)}"></i>|${i.id}|${themables_1.ThemeIcon.isThemeIcon(i.defaults) ? i.defaults.id : i.id}|${i.description || ''}|`);
            }
            reference.push(`| preview     | identifier                        `);
            reference.push(`| ----------- | --------------------------------- |`);
            for (const i of contributions.filter(i => !themables_1.ThemeIcon.isThemeIcon(i.defaults)).sort(sorter)) {
                reference.push(`|<i class="${classNames(i)}"></i>|${i.id}|`);
            }
            return reference.join('\n');
        }
    }
    const iconRegistry = new IconRegistry();
    platform.Registry.add(exports.Extensions.IconContribution, iconRegistry);
    function registerIcon(id, defaults, description, deprecationMessage) {
        return iconRegistry.registerIcon(id, defaults, description, deprecationMessage);
    }
    function getIconRegistry() {
        return iconRegistry;
    }
    function initialize() {
        const codiconFontCharacters = (0, codiconsUtil_1.getCodiconFontCharacters)();
        for (const icon in codiconFontCharacters) {
            const fontCharacter = '\\' + codiconFontCharacters[icon].toString(16);
            iconRegistry.registerIcon(icon, { fontCharacter });
        }
    }
    initialize();
    exports.iconsSchemaId = 'vscode://schemas/icons';
    const schemaRegistry = platform.Registry.as(jsonContributionRegistry_1.Extensions.JSONContribution);
    schemaRegistry.registerSchema(exports.iconsSchemaId, iconRegistry.getIconSchema());
    const delayer = new async_1.RunOnceScheduler(() => schemaRegistry.notifySchemaChanged(exports.iconsSchemaId), 200);
    iconRegistry.onDidChange(() => {
        if (!delayer.isScheduled()) {
            delayer.schedule();
        }
    });
    //setTimeout(_ => console.log(iconRegistry.toString()), 5000);
    // common icons
    exports.widgetClose = registerIcon('widget-close', codicons_1.Codicon.close, (0, nls_1.localize)(1840, 'Icon for the close action in widgets.'));
    exports.gotoPreviousLocation = registerIcon('goto-previous-location', codicons_1.Codicon.arrowUp, (0, nls_1.localize)(1841, 'Icon for goto previous editor location.'));
    exports.gotoNextLocation = registerIcon('goto-next-location', codicons_1.Codicon.arrowDown, (0, nls_1.localize)(1842, 'Icon for goto next editor location.'));
    exports.syncing = themables_1.ThemeIcon.modify(codicons_1.Codicon.sync, 'spin');
    exports.spinningLoading = themables_1.ThemeIcon.modify(codicons_1.Codicon.loading, 'spin');
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[762/*vs/editor/browser/widget/diffEditor/components/accessibleDiffViewer*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,103/*vs/base/browser/trustedTypes*/,87/*vs/base/browser/ui/actionbar/actionbar*/,86/*vs/base/browser/ui/scrollbar/scrollableElement*/,41/*vs/base/common/actions*/,13/*vs/base/common/arrays*/,26/*vs/base/common/codicons*/,2/*vs/base/common/lifecycle*/,21/*vs/base/common/observable*/,30/*vs/base/common/themables*/,74/*vs/editor/browser/config/domFontInfo*/,88/*vs/editor/browser/widget/diffEditor/utils*/,37/*vs/editor/common/config/editorOptions*/,55/*vs/editor/common/core/lineRange*/,68/*vs/editor/common/core/offsetRange*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/,105/*vs/editor/common/diff/rangeMapping*/,43/*vs/editor/common/languages/language*/,83/*vs/editor/common/tokens/lineTokens*/,136/*vs/editor/common/viewLayout/viewLineRenderer*/,95/*vs/editor/common/viewModel*/,3/*vs/nls*/,137/*vs/platform/accessibilitySignal/browser/accessibilitySignalService*/,7/*vs/platform/instantiation/common/instantiation*/,71/*vs/platform/theme/common/iconRegistry*/,499/*vs/css!vs/editor/browser/widget/diffEditor/components/accessibleDiffViewer*/]), function (require, exports, dom_1, trustedTypes_1, actionbar_1, scrollableElement_1, actions_1, arrays_1, codicons_1, lifecycle_1, observable_1, themables_1, domFontInfo_1, utils_1, editorOptions_1, lineRange_1, offsetRange_1, position_1, range_1, rangeMapping_1, language_1, lineTokens_1, viewLineRenderer_1, viewModel_1, nls_1, accessibilitySignalService_1, instantiation_1, iconRegistry_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AccessibleDiffViewerModelFromEditors = exports.AccessibleDiffViewer = void 0;
    const accessibleDiffViewerInsertIcon = (0, iconRegistry_1.registerIcon)('diff-review-insert', codicons_1.Codicon.add, (0, nls_1.localize)(84, 'Icon for \'Insert\' in accessible diff viewer.'));
    const accessibleDiffViewerRemoveIcon = (0, iconRegistry_1.registerIcon)('diff-review-remove', codicons_1.Codicon.remove, (0, nls_1.localize)(85, 'Icon for \'Remove\' in accessible diff viewer.'));
    const accessibleDiffViewerCloseIcon = (0, iconRegistry_1.registerIcon)('diff-review-close', codicons_1.Codicon.close, (0, nls_1.localize)(86, 'Icon for \'Close\' in accessible diff viewer.'));
    let AccessibleDiffViewer = class AccessibleDiffViewer extends lifecycle_1.Disposable {
        static { this._ttPolicy = (0, trustedTypes_1.createTrustedTypesPolicy)('diffReview', { createHTML: value => value }); }
        constructor(_parentNode, _visible, _setVisible, _canClose, _width, _height, _diffs, _models, _instantiationService) {
            super();
            this._parentNode = _parentNode;
            this._visible = _visible;
            this._setVisible = _setVisible;
            this._canClose = _canClose;
            this._width = _width;
            this._height = _height;
            this._diffs = _diffs;
            this._models = _models;
            this._instantiationService = _instantiationService;
            this._state = (0, observable_1.derivedWithStore)(this, (reader, store) => {
                const visible = this._visible.read(reader);
                this._parentNode.style.visibility = visible ? 'visible' : 'hidden';
                if (!visible) {
                    return null;
                }
                const model = store.add(this._instantiationService.createInstance(ViewModel, this._diffs, this._models, this._setVisible, this._canClose));
                const view = store.add(this._instantiationService.createInstance(View, this._parentNode, model, this._width, this._height, this._models));
                return { model, view, };
            }).recomputeInitiallyAndOnChange(this._store);
        }
        next() {
            (0, observable_1.transaction)(tx => {
                const isVisible = this._visible.get();
                this._setVisible(true, tx);
                if (isVisible) {
                    this._state.get().model.nextGroup(tx);
                }
            });
        }
        prev() {
            (0, observable_1.transaction)(tx => {
                this._setVisible(true, tx);
                this._state.get().model.previousGroup(tx);
            });
        }
        close() {
            (0, observable_1.transaction)(tx => {
                this._setVisible(false, tx);
            });
        }
    };
    exports.AccessibleDiffViewer = AccessibleDiffViewer;
    exports.AccessibleDiffViewer = AccessibleDiffViewer = __decorate([
        __param(8, instantiation_1.IInstantiationService)
    ], AccessibleDiffViewer);
    let ViewModel = class ViewModel extends lifecycle_1.Disposable {
        constructor(_diffs, _models, _setVisible, canClose, _accessibilitySignalService) {
            super();
            this._diffs = _diffs;
            this._models = _models;
            this._setVisible = _setVisible;
            this.canClose = canClose;
            this._accessibilitySignalService = _accessibilitySignalService;
            this._groups = (0, observable_1.observableValue)(this, []);
            this._currentGroupIdx = (0, observable_1.observableValue)(this, 0);
            this._currentElementIdx = (0, observable_1.observableValue)(this, 0);
            this.groups = this._groups;
            this.currentGroup = this._currentGroupIdx.map((idx, r) => this._groups.read(r)[idx]);
            this.currentGroupIndex = this._currentGroupIdx;
            this.currentElement = this._currentElementIdx.map((idx, r) => this.currentGroup.read(r)?.lines[idx]);
            this._register((0, observable_1.autorun)(reader => {
                /** @description update groups */
                const diffs = this._diffs.read(reader);
                if (!diffs) {
                    this._groups.set([], undefined);
                    return;
                }
                const groups = computeViewElementGroups(diffs, this._models.getOriginalModel().getLineCount(), this._models.getModifiedModel().getLineCount());
                (0, observable_1.transaction)(tx => {
                    const p = this._models.getModifiedPosition();
                    if (p) {
                        const nextGroup = groups.findIndex(g => p?.lineNumber < g.range.modified.endLineNumberExclusive);
                        if (nextGroup !== -1) {
                            this._currentGroupIdx.set(nextGroup, tx);
                        }
                    }
                    this._groups.set(groups, tx);
                });
            }));
            this._register((0, observable_1.autorun)(reader => {
                /** @description play audio-cue for diff */
                const currentViewItem = this.currentElement.read(reader);
                if (currentViewItem?.type === LineType.Deleted) {
                    this._accessibilitySignalService.playSignal(accessibilitySignalService_1.AccessibilitySignal.diffLineDeleted, { source: 'accessibleDiffViewer.currentElementChanged' });
                }
                else if (currentViewItem?.type === LineType.Added) {
                    this._accessibilitySignalService.playSignal(accessibilitySignalService_1.AccessibilitySignal.diffLineInserted, { source: 'accessibleDiffViewer.currentElementChanged' });
                }
            }));
            this._register((0, observable_1.autorun)(reader => {
                /** @description select lines in editor */
                // This ensures editor commands (like revert/stage) work
                const currentViewItem = this.currentElement.read(reader);
                if (currentViewItem && currentViewItem.type !== LineType.Header) {
                    const lineNumber = currentViewItem.modifiedLineNumber ?? currentViewItem.diff.modified.startLineNumber;
                    this._models.modifiedSetSelection(range_1.Range.fromPositions(new position_1.Position(lineNumber, 1)));
                }
            }));
        }
        _goToGroupDelta(delta, tx) {
            const groups = this.groups.get();
            if (!groups || groups.length <= 1) {
                return;
            }
            (0, observable_1.subtransaction)(tx, tx => {
                this._currentGroupIdx.set(offsetRange_1.OffsetRange.ofLength(groups.length).clipCyclic(this._currentGroupIdx.get() + delta), tx);
                this._currentElementIdx.set(0, tx);
            });
        }
        nextGroup(tx) { this._goToGroupDelta(1, tx); }
        previousGroup(tx) { this._goToGroupDelta(-1, tx); }
        _goToLineDelta(delta) {
            const group = this.currentGroup.get();
            if (!group || group.lines.length <= 1) {
                return;
            }
            (0, observable_1.transaction)(tx => {
                this._currentElementIdx.set(offsetRange_1.OffsetRange.ofLength(group.lines.length).clip(this._currentElementIdx.get() + delta), tx);
            });
        }
        goToNextLine() { this._goToLineDelta(1); }
        goToPreviousLine() { this._goToLineDelta(-1); }
        goToLine(line) {
            const group = this.currentGroup.get();
            if (!group) {
                return;
            }
            const idx = group.lines.indexOf(line);
            if (idx === -1) {
                return;
            }
            (0, observable_1.transaction)(tx => {
                this._currentElementIdx.set(idx, tx);
            });
        }
        revealCurrentElementInEditor() {
            if (!this.canClose.get()) {
                return;
            }
            this._setVisible(false, undefined);
            const curElem = this.currentElement.get();
            if (curElem) {
                if (curElem.type === LineType.Deleted) {
                    this._models.originalReveal(range_1.Range.fromPositions(new position_1.Position(curElem.originalLineNumber, 1)));
                }
                else {
                    this._models.modifiedReveal(curElem.type !== LineType.Header
                        ? range_1.Range.fromPositions(new position_1.Position(curElem.modifiedLineNumber, 1))
                        : undefined);
                }
            }
        }
        close() {
            if (!this.canClose.get()) {
                return;
            }
            this._setVisible(false, undefined);
            this._models.modifiedFocus();
        }
    };
    ViewModel = __decorate([
        __param(4, accessibilitySignalService_1.IAccessibilitySignalService)
    ], ViewModel);
    const viewElementGroupLineMargin = 3;
    function computeViewElementGroups(diffs, originalLineCount, modifiedLineCount) {
        const result = [];
        for (const g of (0, arrays_1.groupAdjacentBy)(diffs, (a, b) => (b.modified.startLineNumber - a.modified.endLineNumberExclusive < 2 * viewElementGroupLineMargin))) {
            const viewElements = [];
            viewElements.push(new HeaderViewElement());
            const origFullRange = new lineRange_1.LineRange(Math.max(1, g[0].original.startLineNumber - viewElementGroupLineMargin), Math.min(g[g.length - 1].original.endLineNumberExclusive + viewElementGroupLineMargin, originalLineCount + 1));
            const modifiedFullRange = new lineRange_1.LineRange(Math.max(1, g[0].modified.startLineNumber - viewElementGroupLineMargin), Math.min(g[g.length - 1].modified.endLineNumberExclusive + viewElementGroupLineMargin, modifiedLineCount + 1));
            (0, arrays_1.forEachAdjacent)(g, (a, b) => {
                const origRange = new lineRange_1.LineRange(a ? a.original.endLineNumberExclusive : origFullRange.startLineNumber, b ? b.original.startLineNumber : origFullRange.endLineNumberExclusive);
                const modifiedRange = new lineRange_1.LineRange(a ? a.modified.endLineNumberExclusive : modifiedFullRange.startLineNumber, b ? b.modified.startLineNumber : modifiedFullRange.endLineNumberExclusive);
                origRange.forEach(origLineNumber => {
                    viewElements.push(new UnchangedLineViewElement(origLineNumber, modifiedRange.startLineNumber + (origLineNumber - origRange.startLineNumber)));
                });
                if (b) {
                    b.original.forEach(origLineNumber => {
                        viewElements.push(new DeletedLineViewElement(b, origLineNumber));
                    });
                    b.modified.forEach(modifiedLineNumber => {
                        viewElements.push(new AddedLineViewElement(b, modifiedLineNumber));
                    });
                }
            });
            const modifiedRange = g[0].modified.join(g[g.length - 1].modified);
            const originalRange = g[0].original.join(g[g.length - 1].original);
            result.push(new ViewElementGroup(new rangeMapping_1.LineRangeMapping(modifiedRange, originalRange), viewElements));
        }
        return result;
    }
    var LineType;
    (function (LineType) {
        LineType[LineType["Header"] = 0] = "Header";
        LineType[LineType["Unchanged"] = 1] = "Unchanged";
        LineType[LineType["Deleted"] = 2] = "Deleted";
        LineType[LineType["Added"] = 3] = "Added";
    })(LineType || (LineType = {}));
    class ViewElementGroup {
        constructor(range, lines) {
            this.range = range;
            this.lines = lines;
        }
    }
    class HeaderViewElement {
        constructor() {
            this.type = LineType.Header;
        }
    }
    class DeletedLineViewElement {
        constructor(diff, originalLineNumber) {
            this.diff = diff;
            this.originalLineNumber = originalLineNumber;
            this.type = LineType.Deleted;
            this.modifiedLineNumber = undefined;
        }
    }
    class AddedLineViewElement {
        constructor(diff, modifiedLineNumber) {
            this.diff = diff;
            this.modifiedLineNumber = modifiedLineNumber;
            this.type = LineType.Added;
            this.originalLineNumber = undefined;
        }
    }
    class UnchangedLineViewElement {
        constructor(originalLineNumber, modifiedLineNumber) {
            this.originalLineNumber = originalLineNumber;
            this.modifiedLineNumber = modifiedLineNumber;
            this.type = LineType.Unchanged;
        }
    }
    let View = class View extends lifecycle_1.Disposable {
        constructor(_element, _model, _width, _height, _models, _languageService) {
            super();
            this._element = _element;
            this._model = _model;
            this._width = _width;
            this._height = _height;
            this._models = _models;
            this._languageService = _languageService;
            this.domNode = this._element;
            this.domNode.className = 'monaco-component diff-review monaco-editor-background';
            const actionBarContainer = document.createElement('div');
            actionBarContainer.className = 'diff-review-actions';
            this._actionBar = this._register(new actionbar_1.ActionBar(actionBarContainer));
            this._register((0, observable_1.autorun)(reader => {
                /** @description update actions */
                this._actionBar.clear();
                if (this._model.canClose.read(reader)) {
                    this._actionBar.push(new actions_1.Action('diffreview.close', (0, nls_1.localize)(87, "Close"), 'close-diff-review ' + themables_1.ThemeIcon.asClassName(accessibleDiffViewerCloseIcon), true, async () => _model.close()), { label: false, icon: true });
                }
            }));
            this._content = document.createElement('div');
            this._content.className = 'diff-review-content';
            this._content.setAttribute('role', 'code');
            this._scrollbar = this._register(new scrollableElement_1.DomScrollableElement(this._content, {}));
            (0, dom_1.reset)(this.domNode, this._scrollbar.getDomNode(), actionBarContainer);
            this._register((0, observable_1.autorun)(r => {
                this._height.read(r);
                this._width.read(r);
                this._scrollbar.scanDomNode();
            }));
            this._register((0, lifecycle_1.toDisposable)(() => { (0, dom_1.reset)(this.domNode); }));
            this._register((0, utils_1.applyStyle)(this.domNode, { width: this._width, height: this._height }));
            this._register((0, utils_1.applyStyle)(this._content, { width: this._width, height: this._height }));
            this._register((0, observable_1.autorunWithStore)((reader, store) => {
                /** @description render */
                this._model.currentGroup.read(reader);
                this._render(store);
            }));
            // TODO@hediet use commands
            this._register((0, dom_1.addStandardDisposableListener)(this.domNode, 'keydown', (e) => {
                if (e.equals(18 /* KeyCode.DownArrow */)
                    || e.equals(2048 /* KeyMod.CtrlCmd */ | 18 /* KeyCode.DownArrow */)
                    || e.equals(512 /* KeyMod.Alt */ | 18 /* KeyCode.DownArrow */)) {
                    e.preventDefault();
                    this._model.goToNextLine();
                }
                if (e.equals(16 /* KeyCode.UpArrow */)
                    || e.equals(2048 /* KeyMod.CtrlCmd */ | 16 /* KeyCode.UpArrow */)
                    || e.equals(512 /* KeyMod.Alt */ | 16 /* KeyCode.UpArrow */)) {
                    e.preventDefault();
                    this._model.goToPreviousLine();
                }
                if (e.equals(9 /* KeyCode.Escape */)
                    || e.equals(2048 /* KeyMod.CtrlCmd */ | 9 /* KeyCode.Escape */)
                    || e.equals(512 /* KeyMod.Alt */ | 9 /* KeyCode.Escape */)
                    || e.equals(1024 /* KeyMod.Shift */ | 9 /* KeyCode.Escape */)) {
                    e.preventDefault();
                    this._model.close();
                }
                if (e.equals(10 /* KeyCode.Space */)
                    || e.equals(3 /* KeyCode.Enter */)) {
                    e.preventDefault();
                    this._model.revealCurrentElementInEditor();
                }
            }));
        }
        _render(store) {
            const originalOptions = this._models.getOriginalOptions();
            const modifiedOptions = this._models.getModifiedOptions();
            const container = document.createElement('div');
            container.className = 'diff-review-table';
            container.setAttribute('role', 'list');
            container.setAttribute('aria-label', (0, nls_1.localize)(88, 'Accessible Diff Viewer. Use arrow up and down to navigate.'));
            (0, domFontInfo_1.applyFontInfo)(container, modifiedOptions.get(50 /* EditorOption.fontInfo */));
            (0, dom_1.reset)(this._content, container);
            const originalModel = this._models.getOriginalModel();
            const modifiedModel = this._models.getModifiedModel();
            if (!originalModel || !modifiedModel) {
                return;
            }
            const originalModelOpts = originalModel.getOptions();
            const modifiedModelOpts = modifiedModel.getOptions();
            const lineHeight = modifiedOptions.get(67 /* EditorOption.lineHeight */);
            const group = this._model.currentGroup.get();
            for (const viewItem of group?.lines || []) {
                if (!group) {
                    break;
                }
                let row;
                if (viewItem.type === LineType.Header) {
                    const header = document.createElement('div');
                    header.className = 'diff-review-row';
                    header.setAttribute('role', 'listitem');
                    const r = group.range;
                    const diffIndex = this._model.currentGroupIndex.get();
                    const diffsLength = this._model.groups.get().length;
                    const getAriaLines = (lines) => lines === 0 ? (0, nls_1.localize)(89, "no lines changed")
                        : lines === 1 ? (0, nls_1.localize)(90, "1 line changed")
                            : (0, nls_1.localize)(91, "{0} lines changed", lines);
                    const originalChangedLinesCntAria = getAriaLines(r.original.length);
                    const modifiedChangedLinesCntAria = getAriaLines(r.modified.length);
                    header.setAttribute('aria-label', (0, nls_1.localize)(92, "Difference {0} of {1}: original line {2}, {3}, modified line {4}, {5}", (diffIndex + 1), diffsLength, r.original.startLineNumber, originalChangedLinesCntAria, r.modified.startLineNumber, modifiedChangedLinesCntAria));










                    const cell = document.createElement('div');
                    cell.className = 'diff-review-cell diff-review-summary';
                    // e.g.: `1/10: @@ -504,7 +517,7 @@`
                    cell.appendChild(document.createTextNode(`${diffIndex + 1}/${diffsLength}: @@ -${r.original.startLineNumber},${r.original.length} +${r.modified.startLineNumber},${r.modified.length} @@`));
                    header.appendChild(cell);
                    row = header;
                }
                else {
                    row = this._createRow(viewItem, lineHeight, this._width.get(), originalOptions, originalModel, originalModelOpts, modifiedOptions, modifiedModel, modifiedModelOpts);
                }
                container.appendChild(row);
                const isSelectedObs = (0, observable_1.derived)(reader => /** @description isSelected */ this._model.currentElement.read(reader) === viewItem);
                store.add((0, observable_1.autorun)(reader => {
                    /** @description update tab index */
                    const isSelected = isSelectedObs.read(reader);
                    row.tabIndex = isSelected ? 0 : -1;
                    if (isSelected) {
                        row.focus();
                    }
                }));
                store.add((0, dom_1.addDisposableListener)(row, 'focus', () => {
                    this._model.goToLine(viewItem);
                }));
            }
            this._scrollbar.scanDomNode();
        }
        _createRow(item, lineHeight, width, originalOptions, originalModel, originalModelOpts, modifiedOptions, modifiedModel, modifiedModelOpts) {
            const originalLayoutInfo = originalOptions.get(146 /* EditorOption.layoutInfo */);
            const originalLineNumbersWidth = originalLayoutInfo.glyphMarginWidth + originalLayoutInfo.lineNumbersWidth;
            const modifiedLayoutInfo = modifiedOptions.get(146 /* EditorOption.layoutInfo */);
            const modifiedLineNumbersWidth = 10 + modifiedLayoutInfo.glyphMarginWidth + modifiedLayoutInfo.lineNumbersWidth;
            let rowClassName = 'diff-review-row';
            let lineNumbersExtraClassName = '';
            const spacerClassName = 'diff-review-spacer';
            let spacerIcon = null;
            switch (item.type) {
                case LineType.Added:
                    rowClassName = 'diff-review-row line-insert';
                    lineNumbersExtraClassName = ' char-insert';
                    spacerIcon = accessibleDiffViewerInsertIcon;
                    break;
                case LineType.Deleted:
                    rowClassName = 'diff-review-row line-delete';
                    lineNumbersExtraClassName = ' char-delete';
                    spacerIcon = accessibleDiffViewerRemoveIcon;
                    break;
            }
            const row = document.createElement('div');
            row.style.minWidth = width + 'px';
            row.className = rowClassName;
            row.setAttribute('role', 'listitem');
            row.ariaLevel = '';
            const cell = document.createElement('div');
            cell.className = 'diff-review-cell';
            cell.style.height = `${lineHeight}px`;
            row.appendChild(cell);
            const originalLineNumber = document.createElement('span');
            originalLineNumber.style.width = (originalLineNumbersWidth + 'px');
            originalLineNumber.style.minWidth = (originalLineNumbersWidth + 'px');
            originalLineNumber.className = 'diff-review-line-number' + lineNumbersExtraClassName;
            if (item.originalLineNumber !== undefined) {
                originalLineNumber.appendChild(document.createTextNode(String(item.originalLineNumber)));
            }
            else {
                originalLineNumber.innerText = '\u00a0';
            }
            cell.appendChild(originalLineNumber);
            const modifiedLineNumber = document.createElement('span');
            modifiedLineNumber.style.width = (modifiedLineNumbersWidth + 'px');
            modifiedLineNumber.style.minWidth = (modifiedLineNumbersWidth + 'px');
            modifiedLineNumber.style.paddingRight = '10px';
            modifiedLineNumber.className = 'diff-review-line-number' + lineNumbersExtraClassName;
            if (item.modifiedLineNumber !== undefined) {
                modifiedLineNumber.appendChild(document.createTextNode(String(item.modifiedLineNumber)));
            }
            else {
                modifiedLineNumber.innerText = '\u00a0';
            }
            cell.appendChild(modifiedLineNumber);
            const spacer = document.createElement('span');
            spacer.className = spacerClassName;
            if (spacerIcon) {
                const spacerCodicon = document.createElement('span');
                spacerCodicon.className = themables_1.ThemeIcon.asClassName(spacerIcon);
                spacerCodicon.innerText = '\u00a0\u00a0';
                spacer.appendChild(spacerCodicon);
            }
            else {
                spacer.innerText = '\u00a0\u00a0';
            }
            cell.appendChild(spacer);
            let lineContent;
            if (item.modifiedLineNumber !== undefined) {
                let html = this._getLineHtml(modifiedModel, modifiedOptions, modifiedModelOpts.tabSize, item.modifiedLineNumber, this._languageService.languageIdCodec);
                if (AccessibleDiffViewer._ttPolicy) {
                    html = AccessibleDiffViewer._ttPolicy.createHTML(html);
                }
                cell.insertAdjacentHTML('beforeend', html);
                lineContent = modifiedModel.getLineContent(item.modifiedLineNumber);
            }
            else {
                let html = this._getLineHtml(originalModel, originalOptions, originalModelOpts.tabSize, item.originalLineNumber, this._languageService.languageIdCodec);
                if (AccessibleDiffViewer._ttPolicy) {
                    html = AccessibleDiffViewer._ttPolicy.createHTML(html);
                }
                cell.insertAdjacentHTML('beforeend', html);
                lineContent = originalModel.getLineContent(item.originalLineNumber);
            }
            if (lineContent.length === 0) {
                lineContent = (0, nls_1.localize)(93, "blank");
            }
            let ariaLabel = '';
            switch (item.type) {
                case LineType.Unchanged:
                    if (item.originalLineNumber === item.modifiedLineNumber) {
                        ariaLabel = (0, nls_1.localize)(94, "{0} unchanged line {1}", lineContent, item.originalLineNumber);
                    }
                    else {
                        ariaLabel = (0, nls_1.localize)(95, "{0} original line {1} modified line {2}", lineContent, item.originalLineNumber, item.modifiedLineNumber);
                    }
                    break;
                case LineType.Added:
                    ariaLabel = (0, nls_1.localize)(96, "+ {0} modified line {1}", lineContent, item.modifiedLineNumber);
                    break;
                case LineType.Deleted:
                    ariaLabel = (0, nls_1.localize)(97, "- {0} original line {1}", lineContent, item.originalLineNumber);
                    break;
            }
            row.setAttribute('aria-label', ariaLabel);
            return row;
        }
        _getLineHtml(model, options, tabSize, lineNumber, languageIdCodec) {
            const lineContent = model.getLineContent(lineNumber);
            const fontInfo = options.get(50 /* EditorOption.fontInfo */);
            const lineTokens = lineTokens_1.LineTokens.createEmpty(lineContent, languageIdCodec);
            const isBasicASCII = viewModel_1.ViewLineRenderingData.isBasicASCII(lineContent, model.mightContainNonBasicASCII());
            const containsRTL = viewModel_1.ViewLineRenderingData.containsRTL(lineContent, isBasicASCII, model.mightContainRTL());
            const r = (0, viewLineRenderer_1.renderViewLine2)(new viewLineRenderer_1.RenderLineInput((fontInfo.isMonospace && !options.get(33 /* EditorOption.disableMonospaceOptimizations */)), fontInfo.canUseHalfwidthRightwardsArrow, lineContent, false, isBasicASCII, containsRTL, 0, lineTokens, [], tabSize, 0, fontInfo.spaceWidth, fontInfo.middotWidth, fontInfo.wsmiddotWidth, options.get(118 /* EditorOption.stopRenderingLineAfter */), options.get(100 /* EditorOption.renderWhitespace */), options.get(95 /* EditorOption.renderControlCharacters */), options.get(51 /* EditorOption.fontLigatures */) !== editorOptions_1.EditorFontLigatures.OFF, null));
            return r.html;
        }
    };
    View = __decorate([
        __param(5, language_1.ILanguageService)
    ], View);
    class AccessibleDiffViewerModelFromEditors {
        constructor(editors) {
            this.editors = editors;
        }
        getOriginalModel() {
            return this.editors.original.getModel();
        }
        getOriginalOptions() {
            return this.editors.original.getOptions();
        }
        originalReveal(range) {
            this.editors.original.revealRange(range);
            this.editors.original.setSelection(range);
            this.editors.original.focus();
        }
        getModifiedModel() {
            return this.editors.modified.getModel();
        }
        getModifiedOptions() {
            return this.editors.modified.getOptions();
        }
        modifiedReveal(range) {
            if (range) {
                this.editors.modified.revealRange(range);
                this.editors.modified.setSelection(range);
            }
            this.editors.modified.focus();
        }
        modifiedSetSelection(range) {
            this.editors.modified.setSelection(range);
        }
        modifiedFocus() {
            this.editors.modified.focus();
        }
        getModifiedPosition() {
            return this.editors.modified.getPosition() ?? undefined;
        }
    }
    exports.AccessibleDiffViewerModelFromEditors = AccessibleDiffViewerModelFromEditors;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[763/*vs/editor/contrib/colorPicker/browser/colorPickerWidget*/], __M([1/*require*/,0/*exports*/,253/*vs/base/browser/pixelRatio*/,5/*vs/base/browser/dom*/,172/*vs/base/browser/globalPointerMoveMonitor*/,85/*vs/base/browser/ui/widget*/,26/*vs/base/common/codicons*/,33/*vs/base/common/color*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,30/*vs/base/common/themables*/,3/*vs/nls*/,32/*vs/platform/theme/common/colorRegistry*/,71/*vs/platform/theme/common/iconRegistry*/,227/*vs/css!vs/editor/contrib/colorPicker/browser/colorPicker*/]), function (require, exports, pixelRatio_1, dom, globalPointerMoveMonitor_1, widget_1, codicons_1, color_1, event_1, lifecycle_1, themables_1, nls_1, colorRegistry_1, iconRegistry_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ColorPickerWidget = exports.InsertButton = exports.ColorPickerBody = exports.ColorPickerHeader = void 0;
    const $ = dom.$;
    class ColorPickerHeader extends lifecycle_1.Disposable {
        constructor(container, model, themeService, showingStandaloneColorPicker = false) {
            super();
            this.model = model;
            this.showingStandaloneColorPicker = showingStandaloneColorPicker;
            this._closeButton = null;
            this._domNode = $('.colorpicker-header');
            dom.append(container, this._domNode);
            this._pickedColorNode = dom.append(this._domNode, $('.picked-color'));
            dom.append(this._pickedColorNode, $('span.codicon.codicon-color-mode'));
            this._pickedColorPresentation = dom.append(this._pickedColorNode, document.createElement('span'));
            this._pickedColorPresentation.classList.add('picked-color-presentation');
            const tooltip = (0, nls_1.localize)(796, "Click to toggle color options (rgb/hsl/hex)");
            this._pickedColorNode.setAttribute('title', tooltip);
            this._originalColorNode = dom.append(this._domNode, $('.original-color'));
            this._originalColorNode.style.backgroundColor = color_1.Color.Format.CSS.format(this.model.originalColor) || '';
            this.backgroundColor = themeService.getColorTheme().getColor(colorRegistry_1.editorHoverBackground) || color_1.Color.white;
            this._register(themeService.onDidColorThemeChange(theme => {
                this.backgroundColor = theme.getColor(colorRegistry_1.editorHoverBackground) || color_1.Color.white;
            }));
            this._register(dom.addDisposableListener(this._pickedColorNode, dom.EventType.CLICK, () => this.model.selectNextColorPresentation()));
            this._register(dom.addDisposableListener(this._originalColorNode, dom.EventType.CLICK, () => {
                this.model.color = this.model.originalColor;
                this.model.flushColor();
            }));
            this._register(model.onDidChangeColor(this.onDidChangeColor, this));
            this._register(model.onDidChangePresentation(this.onDidChangePresentation, this));
            this._pickedColorNode.style.backgroundColor = color_1.Color.Format.CSS.format(model.color) || '';
            this._pickedColorNode.classList.toggle('light', model.color.rgba.a < 0.5 ? this.backgroundColor.isLighter() : model.color.isLighter());
            this.onDidChangeColor(this.model.color);
            // When the color picker widget is a standalone color picker widget, then add a close button
            if (this.showingStandaloneColorPicker) {
                this._domNode.classList.add('standalone-colorpicker');
                this._closeButton = this._register(new CloseButton(this._domNode));
            }
        }
        get closeButton() {
            return this._closeButton;
        }
        get pickedColorNode() {
            return this._pickedColorNode;
        }
        get originalColorNode() {
            return this._originalColorNode;
        }
        onDidChangeColor(color) {
            this._pickedColorNode.style.backgroundColor = color_1.Color.Format.CSS.format(color) || '';
            this._pickedColorNode.classList.toggle('light', color.rgba.a < 0.5 ? this.backgroundColor.isLighter() : color.isLighter());
            this.onDidChangePresentation();
        }
        onDidChangePresentation() {
            this._pickedColorPresentation.textContent = this.model.presentation ? this.model.presentation.label : '';
        }
    }
    exports.ColorPickerHeader = ColorPickerHeader;
    class CloseButton extends lifecycle_1.Disposable {
        constructor(container) {
            super();
            this._onClicked = this._register(new event_1.Emitter());
            this.onClicked = this._onClicked.event;
            this._button = document.createElement('div');
            this._button.classList.add('close-button');
            dom.append(container, this._button);
            const innerDiv = document.createElement('div');
            innerDiv.classList.add('close-button-inner-div');
            dom.append(this._button, innerDiv);
            const closeButton = dom.append(innerDiv, $('.button' + themables_1.ThemeIcon.asCSSSelector((0, iconRegistry_1.registerIcon)('color-picker-close', codicons_1.Codicon.close, (0, nls_1.localize)(797, 'Icon to close the color picker')))));
            closeButton.classList.add('close-icon');
            this._register(dom.addDisposableListener(this._button, dom.EventType.CLICK, () => {
                this._onClicked.fire();
            }));
        }
    }
    class ColorPickerBody extends lifecycle_1.Disposable {
        constructor(container, model, pixelRatio, isStandaloneColorPicker = false) {
            super();
            this.model = model;
            this.pixelRatio = pixelRatio;
            this._insertButton = null;
            this._domNode = $('.colorpicker-body');
            dom.append(container, this._domNode);
            this._saturationBox = new SaturationBox(this._domNode, this.model, this.pixelRatio);
            this._register(this._saturationBox);
            this._register(this._saturationBox.onDidChange(this.onDidSaturationValueChange, this));
            this._register(this._saturationBox.onColorFlushed(this.flushColor, this));
            this._opacityStrip = new OpacityStrip(this._domNode, this.model, isStandaloneColorPicker);
            this._register(this._opacityStrip);
            this._register(this._opacityStrip.onDidChange(this.onDidOpacityChange, this));
            this._register(this._opacityStrip.onColorFlushed(this.flushColor, this));
            this._hueStrip = new HueStrip(this._domNode, this.model, isStandaloneColorPicker);
            this._register(this._hueStrip);
            this._register(this._hueStrip.onDidChange(this.onDidHueChange, this));
            this._register(this._hueStrip.onColorFlushed(this.flushColor, this));
            if (isStandaloneColorPicker) {
                this._insertButton = this._register(new InsertButton(this._domNode));
                this._domNode.classList.add('standalone-colorpicker');
            }
        }
        flushColor() {
            this.model.flushColor();
        }
        onDidSaturationValueChange({ s, v }) {
            const hsva = this.model.color.hsva;
            this.model.color = new color_1.Color(new color_1.HSVA(hsva.h, s, v, hsva.a));
        }
        onDidOpacityChange(a) {
            const hsva = this.model.color.hsva;
            this.model.color = new color_1.Color(new color_1.HSVA(hsva.h, hsva.s, hsva.v, a));
        }
        onDidHueChange(value) {
            const hsva = this.model.color.hsva;
            const h = (1 - value) * 360;
            this.model.color = new color_1.Color(new color_1.HSVA(h === 360 ? 0 : h, hsva.s, hsva.v, hsva.a));
        }
        get domNode() {
            return this._domNode;
        }
        get saturationBox() {
            return this._saturationBox;
        }
        get enterButton() {
            return this._insertButton;
        }
        layout() {
            this._saturationBox.layout();
            this._opacityStrip.layout();
            this._hueStrip.layout();
        }
    }
    exports.ColorPickerBody = ColorPickerBody;
    class SaturationBox extends lifecycle_1.Disposable {
        constructor(container, model, pixelRatio) {
            super();
            this.model = model;
            this.pixelRatio = pixelRatio;
            this._onDidChange = new event_1.Emitter();
            this.onDidChange = this._onDidChange.event;
            this._onColorFlushed = new event_1.Emitter();
            this.onColorFlushed = this._onColorFlushed.event;
            this._domNode = $('.saturation-wrap');
            dom.append(container, this._domNode);
            // Create canvas, draw selected color
            this._canvas = document.createElement('canvas');
            this._canvas.className = 'saturation-box';
            dom.append(this._domNode, this._canvas);
            // Add selection circle
            this.selection = $('.saturation-selection');
            dom.append(this._domNode, this.selection);
            this.layout();
            this._register(dom.addDisposableListener(this._domNode, dom.EventType.POINTER_DOWN, e => this.onPointerDown(e)));
            this._register(this.model.onDidChangeColor(this.onDidChangeColor, this));
            this.monitor = null;
        }
        get domNode() {
            return this._domNode;
        }
        onPointerDown(e) {
            if (!e.target || !(e.target instanceof Element)) {
                return;
            }
            this.monitor = this._register(new globalPointerMoveMonitor_1.GlobalPointerMoveMonitor());
            const origin = dom.getDomNodePagePosition(this._domNode);
            if (e.target !== this.selection) {
                this.onDidChangePosition(e.offsetX, e.offsetY);
            }
            this.monitor.startMonitoring(e.target, e.pointerId, e.buttons, event => this.onDidChangePosition(event.pageX - origin.left, event.pageY - origin.top), () => null);
            const pointerUpListener = dom.addDisposableListener(e.target.ownerDocument, dom.EventType.POINTER_UP, () => {
                this._onColorFlushed.fire();
                pointerUpListener.dispose();
                if (this.monitor) {
                    this.monitor.stopMonitoring(true);
                    this.monitor = null;
                }
            }, true);
        }
        onDidChangePosition(left, top) {
            const s = Math.max(0, Math.min(1, left / this.width));
            const v = Math.max(0, Math.min(1, 1 - (top / this.height)));
            this.paintSelection(s, v);
            this._onDidChange.fire({ s, v });
        }
        layout() {
            this.width = this._domNode.offsetWidth;
            this.height = this._domNode.offsetHeight;
            this._canvas.width = this.width * this.pixelRatio;
            this._canvas.height = this.height * this.pixelRatio;
            this.paint();
            const hsva = this.model.color.hsva;
            this.paintSelection(hsva.s, hsva.v);
        }
        paint() {
            const hsva = this.model.color.hsva;
            const saturatedColor = new color_1.Color(new color_1.HSVA(hsva.h, 1, 1, 1));
            const ctx = this._canvas.getContext('2d');
            const whiteGradient = ctx.createLinearGradient(0, 0, this._canvas.width, 0);
            whiteGradient.addColorStop(0, 'rgba(255, 255, 255, 1)');
            whiteGradient.addColorStop(0.5, 'rgba(255, 255, 255, 0.5)');
            whiteGradient.addColorStop(1, 'rgba(255, 255, 255, 0)');
            const blackGradient = ctx.createLinearGradient(0, 0, 0, this._canvas.height);
            blackGradient.addColorStop(0, 'rgba(0, 0, 0, 0)');
            blackGradient.addColorStop(1, 'rgba(0, 0, 0, 1)');
            ctx.rect(0, 0, this._canvas.width, this._canvas.height);
            ctx.fillStyle = color_1.Color.Format.CSS.format(saturatedColor);
            ctx.fill();
            ctx.fillStyle = whiteGradient;
            ctx.fill();
            ctx.fillStyle = blackGradient;
            ctx.fill();
        }
        paintSelection(s, v) {
            this.selection.style.left = `${s * this.width}px`;
            this.selection.style.top = `${this.height - v * this.height}px`;
        }
        onDidChangeColor(color) {
            if (this.monitor && this.monitor.isMonitoring()) {
                return;
            }
            this.paint();
            const hsva = color.hsva;
            this.paintSelection(hsva.s, hsva.v);
        }
    }
    class Strip extends lifecycle_1.Disposable {
        constructor(container, model, showingStandaloneColorPicker = false) {
            super();
            this.model = model;
            this._onDidChange = new event_1.Emitter();
            this.onDidChange = this._onDidChange.event;
            this._onColorFlushed = new event_1.Emitter();
            this.onColorFlushed = this._onColorFlushed.event;
            if (showingStandaloneColorPicker) {
                this.domNode = dom.append(container, $('.standalone-strip'));
                this.overlay = dom.append(this.domNode, $('.standalone-overlay'));
            }
            else {
                this.domNode = dom.append(container, $('.strip'));
                this.overlay = dom.append(this.domNode, $('.overlay'));
            }
            this.slider = dom.append(this.domNode, $('.slider'));
            this.slider.style.top = `0px`;
            this._register(dom.addDisposableListener(this.domNode, dom.EventType.POINTER_DOWN, e => this.onPointerDown(e)));
            this._register(model.onDidChangeColor(this.onDidChangeColor, this));
            this.layout();
        }
        layout() {
            this.height = this.domNode.offsetHeight - this.slider.offsetHeight;
            const value = this.getValue(this.model.color);
            this.updateSliderPosition(value);
        }
        onDidChangeColor(color) {
            const value = this.getValue(color);
            this.updateSliderPosition(value);
        }
        onPointerDown(e) {
            if (!e.target || !(e.target instanceof Element)) {
                return;
            }
            const monitor = this._register(new globalPointerMoveMonitor_1.GlobalPointerMoveMonitor());
            const origin = dom.getDomNodePagePosition(this.domNode);
            this.domNode.classList.add('grabbing');
            if (e.target !== this.slider) {
                this.onDidChangeTop(e.offsetY);
            }
            monitor.startMonitoring(e.target, e.pointerId, e.buttons, event => this.onDidChangeTop(event.pageY - origin.top), () => null);
            const pointerUpListener = dom.addDisposableListener(e.target.ownerDocument, dom.EventType.POINTER_UP, () => {
                this._onColorFlushed.fire();
                pointerUpListener.dispose();
                monitor.stopMonitoring(true);
                this.domNode.classList.remove('grabbing');
            }, true);
        }
        onDidChangeTop(top) {
            const value = Math.max(0, Math.min(1, 1 - (top / this.height)));
            this.updateSliderPosition(value);
            this._onDidChange.fire(value);
        }
        updateSliderPosition(value) {
            this.slider.style.top = `${(1 - value) * this.height}px`;
        }
    }
    class OpacityStrip extends Strip {
        constructor(container, model, showingStandaloneColorPicker = false) {
            super(container, model, showingStandaloneColorPicker);
            this.domNode.classList.add('opacity-strip');
            this.onDidChangeColor(this.model.color);
        }
        onDidChangeColor(color) {
            super.onDidChangeColor(color);
            const { r, g, b } = color.rgba;
            const opaque = new color_1.Color(new color_1.RGBA(r, g, b, 1));
            const transparent = new color_1.Color(new color_1.RGBA(r, g, b, 0));
            this.overlay.style.background = `linear-gradient(to bottom, ${opaque} 0%, ${transparent} 100%)`;
        }
        getValue(color) {
            return color.hsva.a;
        }
    }
    class HueStrip extends Strip {
        constructor(container, model, showingStandaloneColorPicker = false) {
            super(container, model, showingStandaloneColorPicker);
            this.domNode.classList.add('hue-strip');
        }
        getValue(color) {
            return 1 - (color.hsva.h / 360);
        }
    }
    class InsertButton extends lifecycle_1.Disposable {
        constructor(container) {
            super();
            this._onClicked = this._register(new event_1.Emitter());
            this.onClicked = this._onClicked.event;
            this._button = dom.append(container, document.createElement('button'));
            this._button.classList.add('insert-button');
            this._button.textContent = 'Insert';
            this._register(dom.addDisposableListener(this._button, dom.EventType.CLICK, () => {
                this._onClicked.fire();
            }));
        }
        get button() {
            return this._button;
        }
    }
    exports.InsertButton = InsertButton;
    class ColorPickerWidget extends widget_1.Widget {
        constructor(container, model, pixelRatio, themeService, standaloneColorPicker = false) {
            super();
            this.model = model;
            this.pixelRatio = pixelRatio;
            this._register(pixelRatio_1.PixelRatio.getInstance(dom.getWindow(container)).onDidChange(() => this.layout()));
            this._domNode = $('.colorpicker-widget');
            container.appendChild(this._domNode);
            this.header = this._register(new ColorPickerHeader(this._domNode, this.model, themeService, standaloneColorPicker));
            this.body = this._register(new ColorPickerBody(this._domNode, this.model, this.pixelRatio, standaloneColorPicker));
        }
        layout() {
            this.body.layout();
        }
        get domNode() {
            return this._domNode;
        }
    }
    exports.ColorPickerWidget = ColorPickerWidget;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[217/*vs/editor/contrib/hover/browser/markdownHoverParticipant*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,13/*vs/base/common/arrays*/,18/*vs/base/common/cancellation*/,57/*vs/base/common/htmlContent*/,2/*vs/base/common/lifecycle*/,120/*vs/editor/browser/widget/markdownRenderer/browser/markdownRenderer*/,264/*vs/editor/contrib/hover/browser/hoverActionIds*/,4/*vs/editor/common/core/range*/,43/*vs/editor/common/languages/language*/,84/*vs/editor/contrib/hover/browser/hoverTypes*/,3/*vs/nls*/,28/*vs/platform/configuration/common/configuration*/,59/*vs/platform/opener/common/opener*/,17/*vs/editor/common/services/languageFeatures*/,27/*vs/editor/common/languages*/,71/*vs/platform/theme/common/iconRegistry*/,26/*vs/base/common/codicons*/,30/*vs/base/common/themables*/,8/*vs/base/common/errors*/,31/*vs/platform/keybinding/common/keybinding*/,174/*vs/base/browser/ui/hover/hoverWidget*/,118/*vs/platform/hover/browser/hover*/,14/*vs/base/common/async*/,410/*vs/editor/contrib/hover/browser/getHover*/,24/*vs/platform/commands/common/commands*/]), function (require, exports, dom, arrays_1, cancellation_1, htmlContent_1, lifecycle_1, markdownRenderer_1, hoverActionIds_1, range_1, language_1, hoverTypes_1, nls, configuration_1, opener_1, languageFeatures_1, languages_1, iconRegistry_1, codicons_1, themables_1, errors_1, keybinding_1, hoverWidget_1, hover_1, async_1, getHover_1, commands_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MarkdownHoverParticipant = exports.MarkdownHover = void 0;
    exports.renderMarkdownHovers = renderMarkdownHovers;
    exports.labelForHoverVerbosityAction = labelForHoverVerbosityAction;
    const $ = dom.$;
    const increaseHoverVerbosityIcon = (0, iconRegistry_1.registerIcon)('hover-increase-verbosity', codicons_1.Codicon.add, nls.localize(1031, 'Icon for increaseing hover verbosity.'));
    const decreaseHoverVerbosityIcon = (0, iconRegistry_1.registerIcon)('hover-decrease-verbosity', codicons_1.Codicon.remove, nls.localize(1032, 'Icon for decreasing hover verbosity.'));
    class MarkdownHover {
        constructor(owner, range, contents, isBeforeContent, ordinal, source = undefined) {
            this.owner = owner;
            this.range = range;
            this.contents = contents;
            this.isBeforeContent = isBeforeContent;
            this.ordinal = ordinal;
            this.source = source;
        }
        isValidForHoverAnchor(anchor) {
            return (anchor.type === 1 /* HoverAnchorType.Range */
                && this.range.startColumn <= anchor.range.startColumn
                && this.range.endColumn >= anchor.range.endColumn);
        }
    }
    exports.MarkdownHover = MarkdownHover;
    class HoverSource {
        constructor(hover, hoverProvider, hoverPosition) {
            this.hover = hover;
            this.hoverProvider = hoverProvider;
            this.hoverPosition = hoverPosition;
        }
        supportsVerbosityAction(hoverVerbosityAction) {
            switch (hoverVerbosityAction) {
                case languages_1.HoverVerbosityAction.Increase:
                    return this.hover.canIncreaseVerbosity ?? false;
                case languages_1.HoverVerbosityAction.Decrease:
                    return this.hover.canDecreaseVerbosity ?? false;
            }
        }
    }
    let MarkdownHoverParticipant = class MarkdownHoverParticipant {
        constructor(_editor, _languageService, _openerService, _configurationService, _languageFeaturesService, _keybindingService, _hoverService, _commandService) {
            this._editor = _editor;
            this._languageService = _languageService;
            this._openerService = _openerService;
            this._configurationService = _configurationService;
            this._languageFeaturesService = _languageFeaturesService;
            this._keybindingService = _keybindingService;
            this._hoverService = _hoverService;
            this._commandService = _commandService;
            this.hoverOrdinal = 3;
        }
        createLoadingMessage(anchor) {
            return new MarkdownHover(this, anchor.range, [new htmlContent_1.MarkdownString().appendText(nls.localize(1033, "Loading..."))], false, 2000);
        }
        computeSync(anchor, lineDecorations) {
            if (!this._editor.hasModel() || anchor.type !== 1 /* HoverAnchorType.Range */) {
                return [];
            }
            const model = this._editor.getModel();
            const lineNumber = anchor.range.startLineNumber;
            const maxColumn = model.getLineMaxColumn(lineNumber);
            const result = [];
            let index = 1000;
            const lineLength = model.getLineLength(lineNumber);
            const languageId = model.getLanguageIdAtPosition(anchor.range.startLineNumber, anchor.range.startColumn);
            const stopRenderingLineAfter = this._editor.getOption(118 /* EditorOption.stopRenderingLineAfter */);
            const maxTokenizationLineLength = this._configurationService.getValue('editor.maxTokenizationLineLength', {
                overrideIdentifier: languageId
            });
            let stopRenderingMessage = false;
            if (stopRenderingLineAfter >= 0 && lineLength > stopRenderingLineAfter && anchor.range.startColumn >= stopRenderingLineAfter) {
                stopRenderingMessage = true;
                result.push(new MarkdownHover(this, anchor.range, [{
                        value: nls.localize(1034, "Rendering paused for long line for performance reasons. This can be configured via `editor.stopRenderingLineAfter`.")
                    }], false, index++));
            }
            if (!stopRenderingMessage && typeof maxTokenizationLineLength === 'number' && lineLength >= maxTokenizationLineLength) {
                result.push(new MarkdownHover(this, anchor.range, [{
                        value: nls.localize(1035, "Tokenization is skipped for long lines for performance reasons. This can be configured via `editor.maxTokenizationLineLength`.")
                    }], false, index++));
            }
            let isBeforeContent = false;
            for (const d of lineDecorations) {
                const startColumn = (d.range.startLineNumber === lineNumber) ? d.range.startColumn : 1;
                const endColumn = (d.range.endLineNumber === lineNumber) ? d.range.endColumn : maxColumn;
                const hoverMessage = d.options.hoverMessage;
                if (!hoverMessage || (0, htmlContent_1.isEmptyMarkdownString)(hoverMessage)) {
                    continue;
                }
                if (d.options.beforeContentClassName) {
                    isBeforeContent = true;
                }
                const range = new range_1.Range(anchor.range.startLineNumber, startColumn, anchor.range.startLineNumber, endColumn);
                result.push(new MarkdownHover(this, range, (0, arrays_1.asArray)(hoverMessage), isBeforeContent, index++));
            }
            return result;
        }
        computeAsync(anchor, lineDecorations, token) {
            if (!this._editor.hasModel() || anchor.type !== 1 /* HoverAnchorType.Range */) {
                return async_1.AsyncIterableObject.EMPTY;
            }
            const model = this._editor.getModel();
            const hoverProviderRegistry = this._languageFeaturesService.hoverProvider;
            if (!hoverProviderRegistry.has(model)) {
                return async_1.AsyncIterableObject.EMPTY;
            }
            const markdownHovers = this._getMarkdownHovers(hoverProviderRegistry, model, anchor, token);
            return markdownHovers;
        }
        _getMarkdownHovers(hoverProviderRegistry, model, anchor, token) {
            const position = anchor.range.getStartPosition();
            const hoverProviderResults = (0, getHover_1.getHoverProviderResultsAsAsyncIterable)(hoverProviderRegistry, model, position, token);
            const markdownHovers = hoverProviderResults.filter(item => !(0, htmlContent_1.isEmptyMarkdownString)(item.hover.contents))
                .map(item => {
                const range = item.hover.range ? range_1.Range.lift(item.hover.range) : anchor.range;
                const hoverSource = new HoverSource(item.hover, item.provider, position);
                return new MarkdownHover(this, range, item.hover.contents, false, item.ordinal, hoverSource);
            });
            return markdownHovers;
        }
        renderHoverParts(context, hoverParts) {
            this._renderedHoverParts = new MarkdownRenderedHoverParts(hoverParts, context.fragment, this, this._editor, this._languageService, this._openerService, this._commandService, this._keybindingService, this._hoverService, this._configurationService, context.onContentsChanged);
            return this._renderedHoverParts;
        }
        updateMarkdownHoverVerbosityLevel(action, index, focus) {
            return Promise.resolve(this._renderedHoverParts?.updateMarkdownHoverPartVerbosityLevel(action, index, focus));
        }
    };
    exports.MarkdownHoverParticipant = MarkdownHoverParticipant;
    exports.MarkdownHoverParticipant = MarkdownHoverParticipant = __decorate([
        __param(1, language_1.ILanguageService),
        __param(2, opener_1.IOpenerService),
        __param(3, configuration_1.IConfigurationService),
        __param(4, languageFeatures_1.ILanguageFeaturesService),
        __param(5, keybinding_1.IKeybindingService),
        __param(6, hover_1.IHoverService),
        __param(7, commands_1.ICommandService)
    ], MarkdownHoverParticipant);
    class RenderedMarkdownHoverPart {
        constructor(hoverPart, hoverElement, disposables) {
            this.hoverPart = hoverPart;
            this.hoverElement = hoverElement;
            this.disposables = disposables;
        }
        dispose() {
            this.disposables.dispose();
        }
    }
    class MarkdownRenderedHoverParts {
        constructor(hoverParts, hoverPartsContainer, _hoverParticipant, _editor, _languageService, _openerService, _commandService, _keybindingService, _hoverService, _configurationService, _onFinishedRendering) {
            this._hoverParticipant = _hoverParticipant;
            this._editor = _editor;
            this._languageService = _languageService;
            this._openerService = _openerService;
            this._commandService = _commandService;
            this._keybindingService = _keybindingService;
            this._hoverService = _hoverService;
            this._configurationService = _configurationService;
            this._onFinishedRendering = _onFinishedRendering;
            this._ongoingHoverOperations = new Map();
            this._disposables = new lifecycle_1.DisposableStore();
            this.renderedHoverParts = this._renderHoverParts(hoverParts, hoverPartsContainer, this._onFinishedRendering);
            this._disposables.add((0, lifecycle_1.toDisposable)(() => {
                this.renderedHoverParts.forEach(renderedHoverPart => {
                    renderedHoverPart.dispose();
                });
                this._ongoingHoverOperations.forEach(operation => {
                    operation.tokenSource.dispose(true);
                });
            }));
        }
        _renderHoverParts(hoverParts, hoverPartsContainer, onFinishedRendering) {
            hoverParts.sort((0, arrays_1.compareBy)(hover => hover.ordinal, arrays_1.numberComparator));
            return hoverParts.map(hoverPart => {
                const renderedHoverPart = this._renderHoverPart(hoverPart, onFinishedRendering);
                hoverPartsContainer.appendChild(renderedHoverPart.hoverElement);
                return renderedHoverPart;
            });
        }
        _renderHoverPart(hoverPart, onFinishedRendering) {
            const renderedMarkdownPart = this._renderMarkdownHover(hoverPart, onFinishedRendering);
            const renderedMarkdownElement = renderedMarkdownPart.hoverElement;
            const hoverSource = hoverPart.source;
            const disposables = new lifecycle_1.DisposableStore();
            disposables.add(renderedMarkdownPart);
            if (!hoverSource) {
                return new RenderedMarkdownHoverPart(hoverPart, renderedMarkdownElement, disposables);
            }
            const canIncreaseVerbosity = hoverSource.supportsVerbosityAction(languages_1.HoverVerbosityAction.Increase);
            const canDecreaseVerbosity = hoverSource.supportsVerbosityAction(languages_1.HoverVerbosityAction.Decrease);
            if (!canIncreaseVerbosity && !canDecreaseVerbosity) {
                return new RenderedMarkdownHoverPart(hoverPart, renderedMarkdownElement, disposables);
            }
            const actionsContainer = $('div.verbosity-actions');
            renderedMarkdownElement.prepend(actionsContainer);
            disposables.add(this._renderHoverExpansionAction(actionsContainer, languages_1.HoverVerbosityAction.Increase, canIncreaseVerbosity));
            disposables.add(this._renderHoverExpansionAction(actionsContainer, languages_1.HoverVerbosityAction.Decrease, canDecreaseVerbosity));
            return new RenderedMarkdownHoverPart(hoverPart, renderedMarkdownElement, disposables);
        }
        _renderMarkdownHover(markdownHover, onFinishedRendering) {
            const renderedMarkdownHover = renderMarkdownInContainer(this._editor, markdownHover, this._languageService, this._openerService, onFinishedRendering);
            return renderedMarkdownHover;
        }
        _renderHoverExpansionAction(container, action, actionEnabled) {
            const store = new lifecycle_1.DisposableStore();
            const isActionIncrease = action === languages_1.HoverVerbosityAction.Increase;
            const actionElement = dom.append(container, $(themables_1.ThemeIcon.asCSSSelector(isActionIncrease ? increaseHoverVerbosityIcon : decreaseHoverVerbosityIcon)));
            actionElement.tabIndex = 0;
            const hoverDelegate = new hover_1.WorkbenchHoverDelegate('mouse', false, { target: container, position: { hoverPosition: 0 /* HoverPosition.LEFT */ } }, this._configurationService, this._hoverService);
            store.add(this._hoverService.setupManagedHover(hoverDelegate, actionElement, labelForHoverVerbosityAction(this._keybindingService, action)));
            if (!actionEnabled) {
                actionElement.classList.add('disabled');
                return store;
            }
            actionElement.classList.add('enabled');
            const actionFunction = () => this._commandService.executeCommand(action === languages_1.HoverVerbosityAction.Increase ? hoverActionIds_1.INCREASE_HOVER_VERBOSITY_ACTION_ID : hoverActionIds_1.DECREASE_HOVER_VERBOSITY_ACTION_ID);
            store.add(new hoverWidget_1.ClickAction(actionElement, actionFunction));
            store.add(new hoverWidget_1.KeyDownAction(actionElement, actionFunction, [3 /* KeyCode.Enter */, 10 /* KeyCode.Space */]));
            return store;
        }
        async updateMarkdownHoverPartVerbosityLevel(action, index, focus = true) {
            const model = this._editor.getModel();
            if (!model) {
                return undefined;
            }
            const hoverRenderedPart = this._getRenderedHoverPartAtIndex(index);
            const hoverSource = hoverRenderedPart?.hoverPart.source;
            if (!hoverRenderedPart || !hoverSource?.supportsVerbosityAction(action)) {
                return undefined;
            }
            const newHover = await this._fetchHover(hoverSource, model, action);
            if (!newHover) {
                return undefined;
            }
            const newHoverSource = new HoverSource(newHover, hoverSource.hoverProvider, hoverSource.hoverPosition);
            const initialHoverPart = hoverRenderedPart.hoverPart;
            const newHoverPart = new MarkdownHover(this._hoverParticipant, initialHoverPart.range, newHover.contents, initialHoverPart.isBeforeContent, initialHoverPart.ordinal, newHoverSource);
            const newHoverRenderedPart = this._renderHoverPart(newHoverPart, this._onFinishedRendering);
            this._replaceRenderedHoverPartAtIndex(index, newHoverRenderedPart, newHoverPart);
            if (focus) {
                this._focusOnHoverPartWithIndex(index);
            }
            return {
                hoverPart: newHoverPart,
                hoverElement: newHoverRenderedPart.hoverElement
            };
        }
        async _fetchHover(hoverSource, model, action) {
            let verbosityDelta = action === languages_1.HoverVerbosityAction.Increase ? 1 : -1;
            const provider = hoverSource.hoverProvider;
            const ongoingHoverOperation = this._ongoingHoverOperations.get(provider);
            if (ongoingHoverOperation) {
                ongoingHoverOperation.tokenSource.cancel();
                verbosityDelta += ongoingHoverOperation.verbosityDelta;
            }
            const tokenSource = new cancellation_1.CancellationTokenSource();
            this._ongoingHoverOperations.set(provider, { verbosityDelta, tokenSource });
            const context = { verbosityRequest: { verbosityDelta, previousHover: hoverSource.hover } };
            let hover;
            try {
                hover = await Promise.resolve(provider.provideHover(model, hoverSource.hoverPosition, tokenSource.token, context));
            }
            catch (e) {
                (0, errors_1.onUnexpectedExternalError)(e);
            }
            tokenSource.dispose();
            this._ongoingHoverOperations.delete(provider);
            return hover;
        }
        _replaceRenderedHoverPartAtIndex(index, renderedHoverPart, hoverPart) {
            if (index >= this.renderedHoverParts.length || index < 0) {
                return;
            }
            const currentRenderedHoverPart = this.renderedHoverParts[index];
            const currentRenderedMarkdown = currentRenderedHoverPart.hoverElement;
            const renderedMarkdown = renderedHoverPart.hoverElement;
            const renderedChildrenElements = Array.from(renderedMarkdown.children);
            currentRenderedMarkdown.replaceChildren(...renderedChildrenElements);
            const newRenderedHoverPart = new RenderedMarkdownHoverPart(hoverPart, currentRenderedMarkdown, renderedHoverPart.disposables);
            currentRenderedMarkdown.focus();
            currentRenderedHoverPart.dispose();
            this.renderedHoverParts[index] = newRenderedHoverPart;
        }
        _focusOnHoverPartWithIndex(index) {
            this.renderedHoverParts[index].hoverElement.focus();
        }
        _getRenderedHoverPartAtIndex(index) {
            return this.renderedHoverParts[index];
        }
        dispose() {
            this._disposables.dispose();
        }
    }
    function renderMarkdownHovers(context, markdownHovers, editor, languageService, openerService) {
        // Sort hover parts to keep them stable since they might come in async, out-of-order
        markdownHovers.sort((0, arrays_1.compareBy)(hover => hover.ordinal, arrays_1.numberComparator));
        const renderedHoverParts = [];
        for (const markdownHover of markdownHovers) {
            renderedHoverParts.push(renderMarkdownInContainer(editor, markdownHover, languageService, openerService, context.onContentsChanged));
        }
        return new hoverTypes_1.RenderedHoverParts(renderedHoverParts);
    }
    function renderMarkdownInContainer(editor, markdownHover, languageService, openerService, onFinishedRendering) {
        const disposables = new lifecycle_1.DisposableStore();
        const renderedMarkdown = $('div.hover-row');
        const renderedMarkdownContents = $('div.hover-row-contents');
        renderedMarkdown.appendChild(renderedMarkdownContents);
        const markdownStrings = markdownHover.contents;
        for (const markdownString of markdownStrings) {
            if ((0, htmlContent_1.isEmptyMarkdownString)(markdownString)) {
                continue;
            }
            const markdownHoverElement = $('div.markdown-hover');
            const hoverContentsElement = dom.append(markdownHoverElement, $('div.hover-contents'));
            const renderer = disposables.add(new markdownRenderer_1.MarkdownRenderer({ editor }, languageService, openerService));
            disposables.add(renderer.onDidRenderAsync(() => {
                hoverContentsElement.className = 'hover-contents code-hover-contents';
                onFinishedRendering();
            }));
            const renderedContents = disposables.add(renderer.render(markdownString));
            hoverContentsElement.appendChild(renderedContents.element);
            renderedMarkdownContents.appendChild(markdownHoverElement);
        }
        const renderedHoverPart = {
            hoverPart: markdownHover,
            hoverElement: renderedMarkdown,
            dispose() { disposables.dispose(); }
        };
        return renderedHoverPart;
    }
    function labelForHoverVerbosityAction(keybindingService, action) {
        switch (action) {
            case languages_1.HoverVerbosityAction.Increase: {
                const kb = keybindingService.lookupKeybinding(hoverActionIds_1.INCREASE_HOVER_VERBOSITY_ACTION_ID);
                return kb ?
                    nls.localize(1036, "Increase Hover Verbosity ({0})", kb.getLabel()) :
                    nls.localize(1037, "Increase Hover Verbosity");
            }
            case languages_1.HoverVerbosityAction.Decrease: {
                const kb = keybindingService.lookupKeybinding(hoverActionIds_1.DECREASE_HOVER_VERBOSITY_ACTION_ID);
                return kb ?
                    nls.localize(1038, "Decrease Hover Verbosity ({0})", kb.getLabel()) :
                    nls.localize(1039, "Decrease Hover Verbosity");
            }
        }
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[764/*vs/editor/contrib/parameterHints/browser/parameterHintsWidget*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,46/*vs/base/browser/ui/aria/aria*/,86/*vs/base/browser/ui/scrollbar/scrollableElement*/,26/*vs/base/common/codicons*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,11/*vs/base/common/strings*/,19/*vs/base/common/types*/,37/*vs/editor/common/config/editorOptions*/,43/*vs/editor/common/languages/language*/,120/*vs/editor/browser/widget/markdownRenderer/browser/markdownRenderer*/,270/*vs/editor/contrib/parameterHints/browser/provideSignatureHelp*/,3/*vs/nls*/,12/*vs/platform/contextkey/common/contextkey*/,59/*vs/platform/opener/common/opener*/,32/*vs/platform/theme/common/colorRegistry*/,71/*vs/platform/theme/common/iconRegistry*/,30/*vs/base/common/themables*/,54/*vs/base/common/stopwatch*/,63/*vs/platform/telemetry/common/telemetry*/,526/*vs/css!vs/editor/contrib/parameterHints/browser/parameterHints*/]), function (require, exports, dom, aria, scrollableElement_1, codicons_1, event_1, lifecycle_1, strings_1, types_1, editorOptions_1, language_1, markdownRenderer_1, provideSignatureHelp_1, nls, contextkey_1, opener_1, colorRegistry_1, iconRegistry_1, themables_1, stopwatch_1, telemetry_1) {
    "use strict";
    var ParameterHintsWidget_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ParameterHintsWidget = void 0;
    const $ = dom.$;
    const parameterHintsNextIcon = (0, iconRegistry_1.registerIcon)('parameter-hints-next', codicons_1.Codicon.chevronDown, nls.localize(1173, 'Icon for show next parameter hint.'));
    const parameterHintsPreviousIcon = (0, iconRegistry_1.registerIcon)('parameter-hints-previous', codicons_1.Codicon.chevronUp, nls.localize(1174, 'Icon for show previous parameter hint.'));
    let ParameterHintsWidget = class ParameterHintsWidget extends lifecycle_1.Disposable {
        static { ParameterHintsWidget_1 = this; }
        static { this.ID = 'editor.widget.parameterHintsWidget'; }
        constructor(editor, model, contextKeyService, openerService, languageService, telemetryService) {
            super();
            this.editor = editor;
            this.model = model;
            this.telemetryService = telemetryService;
            this.renderDisposeables = this._register(new lifecycle_1.DisposableStore());
            this.visible = false;
            this.announcedLabel = null;
            // Editor.IContentWidget.allowEditorOverflow
            this.allowEditorOverflow = true;
            this.markdownRenderer = this._register(new markdownRenderer_1.MarkdownRenderer({ editor }, languageService, openerService));
            this.keyVisible = provideSignatureHelp_1.Context.Visible.bindTo(contextKeyService);
            this.keyMultipleSignatures = provideSignatureHelp_1.Context.MultipleSignatures.bindTo(contextKeyService);
        }
        createParameterHintDOMNodes() {
            const element = $('.editor-widget.parameter-hints-widget');
            const wrapper = dom.append(element, $('.phwrapper'));
            wrapper.tabIndex = -1;
            const controls = dom.append(wrapper, $('.controls'));
            const previous = dom.append(controls, $('.button' + themables_1.ThemeIcon.asCSSSelector(parameterHintsPreviousIcon)));
            const overloads = dom.append(controls, $('.overloads'));
            const next = dom.append(controls, $('.button' + themables_1.ThemeIcon.asCSSSelector(parameterHintsNextIcon)));
            this._register(dom.addDisposableListener(previous, 'click', e => {
                dom.EventHelper.stop(e);
                this.previous();
            }));
            this._register(dom.addDisposableListener(next, 'click', e => {
                dom.EventHelper.stop(e);
                this.next();
            }));
            const body = $('.body');
            const scrollbar = new scrollableElement_1.DomScrollableElement(body, {
                alwaysConsumeMouseWheel: true,
            });
            this._register(scrollbar);
            wrapper.appendChild(scrollbar.getDomNode());
            const signature = dom.append(body, $('.signature'));
            const docs = dom.append(body, $('.docs'));
            element.style.userSelect = 'text';
            this.domNodes = {
                element,
                signature,
                overloads,
                docs,
                scrollbar,
            };
            this.editor.addContentWidget(this);
            this.hide();
            this._register(this.editor.onDidChangeCursorSelection(e => {
                if (this.visible) {
                    this.editor.layoutContentWidget(this);
                }
            }));
            const updateFont = () => {
                if (!this.domNodes) {
                    return;
                }
                const fontInfo = this.editor.getOption(50 /* EditorOption.fontInfo */);
                const element = this.domNodes.element;
                element.style.fontSize = `${fontInfo.fontSize}px`;
                element.style.lineHeight = `${fontInfo.lineHeight / fontInfo.fontSize}`;
                element.style.setProperty('--vscode-parameterHintsWidget-editorFontFamily', fontInfo.fontFamily);
                element.style.setProperty('--vscode-parameterHintsWidget-editorFontFamilyDefault', editorOptions_1.EDITOR_FONT_DEFAULTS.fontFamily);
            };
            updateFont();
            this._register(event_1.Event.chain(this.editor.onDidChangeConfiguration.bind(this.editor), $ => $.filter(e => e.hasChanged(50 /* EditorOption.fontInfo */)))(updateFont));
            this._register(this.editor.onDidLayoutChange(e => this.updateMaxHeight()));
            this.updateMaxHeight();
        }
        show() {
            if (this.visible) {
                return;
            }
            if (!this.domNodes) {
                this.createParameterHintDOMNodes();
            }
            this.keyVisible.set(true);
            this.visible = true;
            setTimeout(() => {
                this.domNodes?.element.classList.add('visible');
            }, 100);
            this.editor.layoutContentWidget(this);
        }
        hide() {
            this.renderDisposeables.clear();
            if (!this.visible) {
                return;
            }
            this.keyVisible.reset();
            this.visible = false;
            this.announcedLabel = null;
            this.domNodes?.element.classList.remove('visible');
            this.editor.layoutContentWidget(this);
        }
        getPosition() {
            if (this.visible) {
                return {
                    position: this.editor.getPosition(),
                    preference: [1 /* ContentWidgetPositionPreference.ABOVE */, 2 /* ContentWidgetPositionPreference.BELOW */]
                };
            }
            return null;
        }
        render(hints) {
            this.renderDisposeables.clear();
            if (!this.domNodes) {
                return;
            }
            const multiple = hints.signatures.length > 1;
            this.domNodes.element.classList.toggle('multiple', multiple);
            this.keyMultipleSignatures.set(multiple);
            this.domNodes.signature.innerText = '';
            this.domNodes.docs.innerText = '';
            const signature = hints.signatures[hints.activeSignature];
            if (!signature) {
                return;
            }
            const code = dom.append(this.domNodes.signature, $('.code'));
            const hasParameters = signature.parameters.length > 0;
            const activeParameterIndex = signature.activeParameter ?? hints.activeParameter;
            if (!hasParameters) {
                const label = dom.append(code, $('span'));
                label.textContent = signature.label;
            }
            else {
                this.renderParameters(code, signature, activeParameterIndex);
            }
            const activeParameter = signature.parameters[activeParameterIndex];
            if (activeParameter?.documentation) {
                const documentation = $('span.documentation');
                if (typeof activeParameter.documentation === 'string') {
                    documentation.textContent = activeParameter.documentation;
                }
                else {
                    const renderedContents = this.renderMarkdownDocs(activeParameter.documentation);
                    documentation.appendChild(renderedContents.element);
                }
                dom.append(this.domNodes.docs, $('p', {}, documentation));
            }
            if (signature.documentation === undefined) {
                /** no op */
            }
            else if (typeof signature.documentation === 'string') {
                dom.append(this.domNodes.docs, $('p', {}, signature.documentation));
            }
            else {
                const renderedContents = this.renderMarkdownDocs(signature.documentation);
                dom.append(this.domNodes.docs, renderedContents.element);
            }
            const hasDocs = this.hasDocs(signature, activeParameter);
            this.domNodes.signature.classList.toggle('has-docs', hasDocs);
            this.domNodes.docs.classList.toggle('empty', !hasDocs);
            this.domNodes.overloads.textContent =
                String(hints.activeSignature + 1).padStart(hints.signatures.length.toString().length, '0') + '/' + hints.signatures.length;
            if (activeParameter) {
                let labelToAnnounce = '';
                const param = signature.parameters[activeParameterIndex];
                if (Array.isArray(param.label)) {
                    labelToAnnounce = signature.label.substring(param.label[0], param.label[1]);
                }
                else {
                    labelToAnnounce = param.label;
                }
                if (param.documentation) {
                    labelToAnnounce += typeof param.documentation === 'string' ? `, ${param.documentation}` : `, ${param.documentation.value}`;
                }
                if (signature.documentation) {
                    labelToAnnounce += typeof signature.documentation === 'string' ? `, ${signature.documentation}` : `, ${signature.documentation.value}`;
                }
                // Select method gets called on every user type while parameter hints are visible.
                // We do not want to spam the user with same announcements, so we only announce if the current parameter changed.
                if (this.announcedLabel !== labelToAnnounce) {
                    aria.alert(nls.localize(1175, "{0}, hint", labelToAnnounce));
                    this.announcedLabel = labelToAnnounce;
                }
            }
            this.editor.layoutContentWidget(this);
            this.domNodes.scrollbar.scanDomNode();
        }
        renderMarkdownDocs(markdown) {
            const stopWatch = new stopwatch_1.StopWatch();
            const renderedContents = this.renderDisposeables.add(this.markdownRenderer.render(markdown, {
                asyncRenderCallback: () => {
                    this.domNodes?.scrollbar.scanDomNode();
                }
            }));
            renderedContents.element.classList.add('markdown-docs');
            const renderDuration = stopWatch.elapsed();
            if (renderDuration > 300) {
                this.telemetryService.publicLog2('parameterHints.parseMarkdown', {
                    renderDuration
                });
            }
            return renderedContents;
        }
        hasDocs(signature, activeParameter) {
            if (activeParameter && typeof activeParameter.documentation === 'string' && (0, types_1.assertIsDefined)(activeParameter.documentation).length > 0) {
                return true;
            }
            if (activeParameter && typeof activeParameter.documentation === 'object' && (0, types_1.assertIsDefined)(activeParameter.documentation).value.length > 0) {
                return true;
            }
            if (signature.documentation && typeof signature.documentation === 'string' && (0, types_1.assertIsDefined)(signature.documentation).length > 0) {
                return true;
            }
            if (signature.documentation && typeof signature.documentation === 'object' && (0, types_1.assertIsDefined)(signature.documentation.value).length > 0) {
                return true;
            }
            return false;
        }
        renderParameters(parent, signature, activeParameterIndex) {
            const [start, end] = this.getParameterLabelOffsets(signature, activeParameterIndex);
            const beforeSpan = document.createElement('span');
            beforeSpan.textContent = signature.label.substring(0, start);
            const paramSpan = document.createElement('span');
            paramSpan.textContent = signature.label.substring(start, end);
            paramSpan.className = 'parameter active';
            const afterSpan = document.createElement('span');
            afterSpan.textContent = signature.label.substring(end);
            dom.append(parent, beforeSpan, paramSpan, afterSpan);
        }
        getParameterLabelOffsets(signature, paramIdx) {
            const param = signature.parameters[paramIdx];
            if (!param) {
                return [0, 0];
            }
            else if (Array.isArray(param.label)) {
                return param.label;
            }
            else if (!param.label.length) {
                return [0, 0];
            }
            else {
                const regex = new RegExp(`(\\W|^)${(0, strings_1.escapeRegExpCharacters)(param.label)}(?=\\W|$)`, 'g');
                regex.test(signature.label);
                const idx = regex.lastIndex - param.label.length;
                return idx >= 0
                    ? [idx, regex.lastIndex]
                    : [0, 0];
            }
        }
        next() {
            this.editor.focus();
            this.model.next();
        }
        previous() {
            this.editor.focus();
            this.model.previous();
        }
        getDomNode() {
            if (!this.domNodes) {
                this.createParameterHintDOMNodes();
            }
            return this.domNodes.element;
        }
        getId() {
            return ParameterHintsWidget_1.ID;
        }
        updateMaxHeight() {
            if (!this.domNodes) {
                return;
            }
            const height = Math.max(this.editor.getLayoutInfo().height / 4, 250);
            const maxHeight = `${height}px`;
            this.domNodes.element.style.maxHeight = maxHeight;
            const wrapper = this.domNodes.element.getElementsByClassName('phwrapper');
            if (wrapper.length) {
                wrapper[0].style.maxHeight = maxHeight;
            }
        }
    };
    exports.ParameterHintsWidget = ParameterHintsWidget;
    exports.ParameterHintsWidget = ParameterHintsWidget = ParameterHintsWidget_1 = __decorate([
        __param(2, contextkey_1.IContextKeyService),
        __param(3, opener_1.IOpenerService),
        __param(4, language_1.ILanguageService),
        __param(5, telemetry_1.ITelemetryService)
    ], ParameterHintsWidget);
    (0, colorRegistry_1.registerColor)('editorHoverWidget.highlightForeground', colorRegistry_1.listHighlightForeground, nls.localize(1176, 'Foreground color of the active item in the parameter hint.'));
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[765/*vs/editor/contrib/parameterHints/browser/parameterHints*/], __M([1/*require*/,0/*exports*/,98/*vs/base/common/lazy*/,2/*vs/base/common/lifecycle*/,15/*vs/editor/browser/editorExtensions*/,20/*vs/editor/common/editorContextKeys*/,27/*vs/editor/common/languages*/,17/*vs/editor/common/services/languageFeatures*/,683/*vs/editor/contrib/parameterHints/browser/parameterHintsModel*/,270/*vs/editor/contrib/parameterHints/browser/provideSignatureHelp*/,3/*vs/nls*/,12/*vs/platform/contextkey/common/contextkey*/,7/*vs/platform/instantiation/common/instantiation*/,764/*vs/editor/contrib/parameterHints/browser/parameterHintsWidget*/]), function (require, exports, lazy_1, lifecycle_1, editorExtensions_1, editorContextKeys_1, languages, languageFeatures_1, parameterHintsModel_1, provideSignatureHelp_1, nls, contextkey_1, instantiation_1, parameterHintsWidget_1) {
    "use strict";
    var ParameterHintsController_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.TriggerParameterHintsAction = exports.ParameterHintsController = void 0;
    let ParameterHintsController = class ParameterHintsController extends lifecycle_1.Disposable {
        static { ParameterHintsController_1 = this; }
        static { this.ID = 'editor.controller.parameterHints'; }
        static get(editor) {
            return editor.getContribution(ParameterHintsController_1.ID);
        }
        constructor(editor, instantiationService, languageFeaturesService) {
            super();
            this.editor = editor;
            this.model = this._register(new parameterHintsModel_1.ParameterHintsModel(editor, languageFeaturesService.signatureHelpProvider));
            this._register(this.model.onChangedHints(newParameterHints => {
                if (newParameterHints) {
                    this.widget.value.show();
                    this.widget.value.render(newParameterHints);
                }
                else {
                    this.widget.rawValue?.hide();
                }
            }));
            this.widget = new lazy_1.Lazy(() => this._register(instantiationService.createInstance(parameterHintsWidget_1.ParameterHintsWidget, this.editor, this.model)));
        }
        cancel() {
            this.model.cancel();
        }
        previous() {
            this.widget.rawValue?.previous();
        }
        next() {
            this.widget.rawValue?.next();
        }
        trigger(context) {
            this.model.trigger(context, 0);
        }
    };
    exports.ParameterHintsController = ParameterHintsController;
    exports.ParameterHintsController = ParameterHintsController = ParameterHintsController_1 = __decorate([
        __param(1, instantiation_1.IInstantiationService),
        __param(2, languageFeatures_1.ILanguageFeaturesService)
    ], ParameterHintsController);
    class TriggerParameterHintsAction extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: 'editor.action.triggerParameterHints',
                label: nls.localize(1172, "Trigger Parameter Hints"),
                alias: 'Trigger Parameter Hints',
                precondition: editorContextKeys_1.EditorContextKeys.hasSignatureHelpProvider,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 10 /* KeyCode.Space */,
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
        run(accessor, editor) {
            const controller = ParameterHintsController.get(editor);
            controller?.trigger({
                triggerKind: languages.SignatureHelpTriggerKind.Invoke
            });
        }
    }
    exports.TriggerParameterHintsAction = TriggerParameterHintsAction;
    (0, editorExtensions_1.registerEditorContribution)(ParameterHintsController.ID, ParameterHintsController, 2 /* EditorContributionInstantiation.BeforeFirstInteraction */);
    (0, editorExtensions_1.registerEditorAction)(TriggerParameterHintsAction);
    const weight = 100 /* KeybindingWeight.EditorContrib */ + 75;
    const ParameterHintsCommand = editorExtensions_1.EditorCommand.bindToContribution(ParameterHintsController.get);
    (0, editorExtensions_1.registerEditorCommand)(new ParameterHintsCommand({
        id: 'closeParameterHints',
        precondition: provideSignatureHelp_1.Context.Visible,
        handler: x => x.cancel(),
        kbOpts: {
            weight: weight,
            kbExpr: editorContextKeys_1.EditorContextKeys.focus,
            primary: 9 /* KeyCode.Escape */,
            secondary: [1024 /* KeyMod.Shift */ | 9 /* KeyCode.Escape */]
        }
    }));
    (0, editorExtensions_1.registerEditorCommand)(new ParameterHintsCommand({
        id: 'showPrevParameterHint',
        precondition: contextkey_1.ContextKeyExpr.and(provideSignatureHelp_1.Context.Visible, provideSignatureHelp_1.Context.MultipleSignatures),
        handler: x => x.previous(),
        kbOpts: {
            weight: weight,
            kbExpr: editorContextKeys_1.EditorContextKeys.focus,
            primary: 16 /* KeyCode.UpArrow */,
            secondary: [512 /* KeyMod.Alt */ | 16 /* KeyCode.UpArrow */],
            mac: { primary: 16 /* KeyCode.UpArrow */, secondary: [512 /* KeyMod.Alt */ | 16 /* KeyCode.UpArrow */, 256 /* KeyMod.WinCtrl */ | 46 /* KeyCode.KeyP */] }
        }
    }));
    (0, editorExtensions_1.registerEditorCommand)(new ParameterHintsCommand({
        id: 'showNextParameterHint',
        precondition: contextkey_1.ContextKeyExpr.and(provideSignatureHelp_1.Context.Visible, provideSignatureHelp_1.Context.MultipleSignatures),
        handler: x => x.next(),
        kbOpts: {
            weight: weight,
            kbExpr: editorContextKeys_1.EditorContextKeys.focus,
            primary: 18 /* KeyCode.DownArrow */,
            secondary: [512 /* KeyMod.Alt */ | 18 /* KeyCode.DownArrow */],
            mac: { primary: 18 /* KeyCode.DownArrow */, secondary: [512 /* KeyMod.Alt */ | 18 /* KeyCode.DownArrow */, 256 /* KeyMod.WinCtrl */ | 44 /* KeyCode.KeyN */] }
        }
    }));
});










define(__m[766/*vs/editor/contrib/unicodeHighlighter/browser/bannerController*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,87/*vs/base/browser/ui/actionbar/actionbar*/,41/*vs/base/common/actions*/,2/*vs/base/common/lifecycle*/,120/*vs/editor/browser/widget/markdownRenderer/browser/markdownRenderer*/,7/*vs/platform/instantiation/common/instantiation*/,702/*vs/platform/opener/browser/link*/,71/*vs/platform/theme/common/iconRegistry*/,30/*vs/base/common/themables*/,534/*vs/css!vs/editor/contrib/unicodeHighlighter/browser/bannerController*/]), function (require, exports, dom_1, actionbar_1, actions_1, lifecycle_1, markdownRenderer_1, instantiation_1, link_1, iconRegistry_1, themables_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.BannerController = void 0;
    const BANNER_ELEMENT_HEIGHT = 26;
    let BannerController = class BannerController extends lifecycle_1.Disposable {
        constructor(_editor, instantiationService) {
            super();
            this._editor = _editor;
            this.instantiationService = instantiationService;
            this.banner = this._register(this.instantiationService.createInstance(Banner));
        }
        hide() {
            this._editor.setBanner(null, 0);
            this.banner.clear();
        }
        show(item) {
            this.banner.show({
                ...item,
                onClose: () => {
                    this.hide();
                    item.onClose?.();
                }
            });
            this._editor.setBanner(this.banner.element, BANNER_ELEMENT_HEIGHT);
        }
    };
    exports.BannerController = BannerController;
    exports.BannerController = BannerController = __decorate([
        __param(1, instantiation_1.IInstantiationService)
    ], BannerController);
    // TODO@hediet: Investigate if this can be reused by the workspace banner (bannerPart.ts).
    let Banner = class Banner extends lifecycle_1.Disposable {
        constructor(instantiationService) {
            super();
            this.instantiationService = instantiationService;
            this.markdownRenderer = this.instantiationService.createInstance(markdownRenderer_1.MarkdownRenderer, {});
            this.element = (0, dom_1.$)('div.editor-banner');
            this.element.tabIndex = 0;
        }
        getAriaLabel(item) {
            if (item.ariaLabel) {
                return item.ariaLabel;
            }
            if (typeof item.message === 'string') {
                return item.message;
            }
            return undefined;
        }
        getBannerMessage(message) {
            if (typeof message === 'string') {
                const element = (0, dom_1.$)('span');
                element.innerText = message;
                return element;
            }
            return this.markdownRenderer.render(message).element;
        }
        clear() {
            (0, dom_1.clearNode)(this.element);
        }
        show(item) {
            // Clear previous item
            (0, dom_1.clearNode)(this.element);
            // Banner aria label
            const ariaLabel = this.getAriaLabel(item);
            if (ariaLabel) {
                this.element.setAttribute('aria-label', ariaLabel);
            }
            // Icon
            const iconContainer = (0, dom_1.append)(this.element, (0, dom_1.$)('div.icon-container'));
            iconContainer.setAttribute('aria-hidden', 'true');
            if (item.icon) {
                iconContainer.appendChild((0, dom_1.$)(`div${themables_1.ThemeIcon.asCSSSelector(item.icon)}`));
            }
            // Message
            const messageContainer = (0, dom_1.append)(this.element, (0, dom_1.$)('div.message-container'));
            messageContainer.setAttribute('aria-hidden', 'true');
            messageContainer.appendChild(this.getBannerMessage(item.message));
            // Message Actions
            this.messageActionsContainer = (0, dom_1.append)(this.element, (0, dom_1.$)('div.message-actions-container'));
            if (item.actions) {
                for (const action of item.actions) {
                    this._register(this.instantiationService.createInstance(link_1.Link, this.messageActionsContainer, { ...action, tabIndex: -1 }, {}));
                }
            }
            // Action
            const actionBarContainer = (0, dom_1.append)(this.element, (0, dom_1.$)('div.action-container'));
            this.actionBar = this._register(new actionbar_1.ActionBar(actionBarContainer));
            this.actionBar.push(this._register(new actions_1.Action('banner.close', 'Close Banner', themables_1.ThemeIcon.asClassName(iconRegistry_1.widgetClose), true, () => {
                if (typeof item.onClose === 'function') {
                    item.onClose();
                }
            })), { icon: true, label: false });
            this.actionBar.setFocusable(false);
        }
    };
    Banner = __decorate([
        __param(0, instantiation_1.IInstantiationService)
    ], Banner);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[767/*vs/platform/theme/browser/iconsStyleSheet*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,30/*vs/base/common/themables*/,71/*vs/platform/theme/common/iconRegistry*/]), function (require, exports, dom_1, event_1, lifecycle_1, themables_1, iconRegistry_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.UnthemedProductIconTheme = void 0;
    exports.getIconsStyleSheet = getIconsStyleSheet;
    function getIconsStyleSheet(themeService) {
        const disposable = new lifecycle_1.DisposableStore();
        const onDidChangeEmmiter = disposable.add(new event_1.Emitter());
        const iconRegistry = (0, iconRegistry_1.getIconRegistry)();
        disposable.add(iconRegistry.onDidChange(() => onDidChangeEmmiter.fire()));
        if (themeService) {
            disposable.add(themeService.onDidProductIconThemeChange(() => onDidChangeEmmiter.fire()));
        }
        return {
            dispose: () => disposable.dispose(),
            onDidChange: onDidChangeEmmiter.event,
            getCSS() {
                const productIconTheme = themeService ? themeService.getProductIconTheme() : new UnthemedProductIconTheme();
                const usedFontIds = {};
                const rules = [];
                const rootAttribs = [];
                for (const contribution of iconRegistry.getIcons()) {
                    const definition = productIconTheme.getIcon(contribution);
                    if (!definition) {
                        continue;
                    }
                    const fontContribution = definition.font;
                    const fontFamilyVar = `--vscode-icon-${contribution.id}-font-family`;
                    const contentVar = `--vscode-icon-${contribution.id}-content`;
                    if (fontContribution) {
                        usedFontIds[fontContribution.id] = fontContribution.definition;
                        rootAttribs.push(`${fontFamilyVar}: ${(0, dom_1.asCSSPropertyValue)(fontContribution.id)};`, `${contentVar}: '${definition.fontCharacter}';`);
                        rules.push(`.codicon-${contribution.id}:before { content: '${definition.fontCharacter}'; font-family: ${(0, dom_1.asCSSPropertyValue)(fontContribution.id)}; }`);
                    }
                    else {
                        rootAttribs.push(`${contentVar}: '${definition.fontCharacter}'; ${fontFamilyVar}: 'codicon';`);
                        rules.push(`.codicon-${contribution.id}:before { content: '${definition.fontCharacter}'; }`);
                    }
                }
                for (const id in usedFontIds) {
                    const definition = usedFontIds[id];
                    const fontWeight = definition.weight ? `font-weight: ${definition.weight};` : '';
                    const fontStyle = definition.style ? `font-style: ${definition.style};` : '';
                    const src = definition.src.map(l => `${(0, dom_1.asCSSUrl)(l.location)} format('${l.format}')`).join(', ');
                    rules.push(`@font-face { src: ${src}; font-family: ${(0, dom_1.asCSSPropertyValue)(id)};${fontWeight}${fontStyle} font-display: block; }`);
                }
                rules.push(`:root { ${rootAttribs.join(' ')} }`);
                return rules.join('\n');
            }
        };
    }
    class UnthemedProductIconTheme {
        getIcon(contribution) {
            const iconRegistry = (0, iconRegistry_1.getIconRegistry)();
            let definition = contribution.defaults;
            while (themables_1.ThemeIcon.isThemeIcon(definition)) {
                const c = iconRegistry.getIcon(definition.id);
                if (!c) {
                    return undefined;
                }
                definition = c.defaults;
            }
            return definition;
        }
    }
    exports.UnthemedProductIconTheme = UnthemedProductIconTheme;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[97/*vs/platform/theme/common/theme*/], __M([1/*require*/,0/*exports*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ColorScheme = void 0;
    exports.isHighContrast = isHighContrast;
    exports.isDark = isDark;
    /**
     * Color scheme used by the OS and by color themes.
     */
    var ColorScheme;
    (function (ColorScheme) {
        ColorScheme["DARK"] = "dark";
        ColorScheme["LIGHT"] = "light";
        ColorScheme["HIGH_CONTRAST_DARK"] = "hcDark";
        ColorScheme["HIGH_CONTRAST_LIGHT"] = "hcLight";
    })(ColorScheme || (exports.ColorScheme = ColorScheme = {}));
    function isHighContrast(scheme) {
        return scheme === ColorScheme.HIGH_CONTRAST_DARK || scheme === ColorScheme.HIGH_CONTRAST_LIGHT;
    }
    function isDark(scheme) {
        return scheme === ColorScheme.DARK || scheme === ColorScheme.HIGH_CONTRAST_DARK;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[281/*vs/editor/browser/viewParts/lines/viewLine*/], __M([1/*require*/,0/*exports*/,64/*vs/base/browser/browser*/,39/*vs/base/browser/fastDomNode*/,16/*vs/base/common/platform*/,548/*vs/editor/browser/viewParts/lines/rangeUtil*/,164/*vs/editor/browser/view/renderingContext*/,150/*vs/editor/common/viewLayout/lineDecorations*/,136/*vs/editor/common/viewLayout/viewLineRenderer*/,97/*vs/platform/theme/common/theme*/,37/*vs/editor/common/config/editorOptions*/]), function (require, exports, browser, fastDomNode_1, platform, rangeUtil_1, renderingContext_1, lineDecorations_1, viewLineRenderer_1, theme_1, editorOptions_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ViewLine = exports.ViewLineOptions = void 0;
    exports.getColumnOfNodeOffset = getColumnOfNodeOffset;
    const canUseFastRenderedViewLine = (function () {
        if (platform.isNative) {
            // In VSCode we know very well when the zoom level changes
            return true;
        }
        if (platform.isLinux || browser.isFirefox || browser.isSafari) {
            // On Linux, it appears that zooming affects char widths (in pixels), which is unexpected.
            // --
            // Even though we read character widths correctly, having read them at a specific zoom level
            // does not mean they are the same at the current zoom level.
            // --
            // This could be improved if we ever figure out how to get an event when browsers zoom,
            // but until then we have to stick with reading client rects.
            // --
            // The same has been observed with Firefox on Windows7
            // --
            // The same has been oversved with Safari
            return false;
        }
        return true;
    })();
    let monospaceAssumptionsAreValid = true;
    class ViewLineOptions {
        constructor(config, themeType) {
            this.themeType = themeType;
            const options = config.options;
            const fontInfo = options.get(50 /* EditorOption.fontInfo */);
            const experimentalWhitespaceRendering = options.get(38 /* EditorOption.experimentalWhitespaceRendering */);
            if (experimentalWhitespaceRendering === 'off') {
                this.renderWhitespace = options.get(100 /* EditorOption.renderWhitespace */);
            }
            else {
                // whitespace is rendered in a different layer
                this.renderWhitespace = 'none';
            }
            this.renderControlCharacters = options.get(95 /* EditorOption.renderControlCharacters */);
            this.spaceWidth = fontInfo.spaceWidth;
            this.middotWidth = fontInfo.middotWidth;
            this.wsmiddotWidth = fontInfo.wsmiddotWidth;
            this.useMonospaceOptimizations = (fontInfo.isMonospace
                && !options.get(33 /* EditorOption.disableMonospaceOptimizations */));
            this.canUseHalfwidthRightwardsArrow = fontInfo.canUseHalfwidthRightwardsArrow;
            this.lineHeight = options.get(67 /* EditorOption.lineHeight */);
            this.stopRenderingLineAfter = options.get(118 /* EditorOption.stopRenderingLineAfter */);
            this.fontLigatures = options.get(51 /* EditorOption.fontLigatures */);
        }
        equals(other) {
            return (this.themeType === other.themeType
                && this.renderWhitespace === other.renderWhitespace
                && this.renderControlCharacters === other.renderControlCharacters
                && this.spaceWidth === other.spaceWidth
                && this.middotWidth === other.middotWidth
                && this.wsmiddotWidth === other.wsmiddotWidth
                && this.useMonospaceOptimizations === other.useMonospaceOptimizations
                && this.canUseHalfwidthRightwardsArrow === other.canUseHalfwidthRightwardsArrow
                && this.lineHeight === other.lineHeight
                && this.stopRenderingLineAfter === other.stopRenderingLineAfter
                && this.fontLigatures === other.fontLigatures);
        }
    }
    exports.ViewLineOptions = ViewLineOptions;
    class ViewLine {
        static { this.CLASS_NAME = 'view-line'; }
        constructor(options) {
            this._options = options;
            this._isMaybeInvalid = true;
            this._renderedViewLine = null;
        }
        // --- begin IVisibleLineData
        getDomNode() {
            if (this._renderedViewLine && this._renderedViewLine.domNode) {
                return this._renderedViewLine.domNode.domNode;
            }
            return null;
        }
        setDomNode(domNode) {
            if (this._renderedViewLine) {
                this._renderedViewLine.domNode = (0, fastDomNode_1.createFastDomNode)(domNode);
            }
            else {
                throw new Error('I have no rendered view line to set the dom node to...');
            }
        }
        onContentChanged() {
            this._isMaybeInvalid = true;
        }
        onTokensChanged() {
            this._isMaybeInvalid = true;
        }
        onDecorationsChanged() {
            this._isMaybeInvalid = true;
        }
        onOptionsChanged(newOptions) {
            this._isMaybeInvalid = true;
            this._options = newOptions;
        }
        onSelectionChanged() {
            if ((0, theme_1.isHighContrast)(this._options.themeType) || this._options.renderWhitespace === 'selection') {
                this._isMaybeInvalid = true;
                return true;
            }
            return false;
        }
        renderLine(lineNumber, deltaTop, lineHeight, viewportData, sb) {
            if (this._isMaybeInvalid === false) {
                // it appears that nothing relevant has changed
                return false;
            }
            this._isMaybeInvalid = false;
            const lineData = viewportData.getViewLineRenderingData(lineNumber);
            const options = this._options;
            const actualInlineDecorations = lineDecorations_1.LineDecoration.filter(lineData.inlineDecorations, lineNumber, lineData.minColumn, lineData.maxColumn);
            // Only send selection information when needed for rendering whitespace
            let selectionsOnLine = null;
            if ((0, theme_1.isHighContrast)(options.themeType) || this._options.renderWhitespace === 'selection') {
                const selections = viewportData.selections;
                for (const selection of selections) {
                    if (selection.endLineNumber < lineNumber || selection.startLineNumber > lineNumber) {
                        // Selection does not intersect line
                        continue;
                    }
                    const startColumn = (selection.startLineNumber === lineNumber ? selection.startColumn : lineData.minColumn);
                    const endColumn = (selection.endLineNumber === lineNumber ? selection.endColumn : lineData.maxColumn);
                    if (startColumn < endColumn) {
                        if ((0, theme_1.isHighContrast)(options.themeType)) {
                            actualInlineDecorations.push(new lineDecorations_1.LineDecoration(startColumn, endColumn, 'inline-selected-text', 0 /* InlineDecorationType.Regular */));
                        }
                        if (this._options.renderWhitespace === 'selection') {
                            if (!selectionsOnLine) {
                                selectionsOnLine = [];
                            }
                            selectionsOnLine.push(new viewLineRenderer_1.LineRange(startColumn - 1, endColumn - 1));
                        }
                    }
                }
            }
            const renderLineInput = new viewLineRenderer_1.RenderLineInput(options.useMonospaceOptimizations, options.canUseHalfwidthRightwardsArrow, lineData.content, lineData.continuesWithWrappedLine, lineData.isBasicASCII, lineData.containsRTL, lineData.minColumn - 1, lineData.tokens, actualInlineDecorations, lineData.tabSize, lineData.startVisibleColumn, options.spaceWidth, options.middotWidth, options.wsmiddotWidth, options.stopRenderingLineAfter, options.renderWhitespace, options.renderControlCharacters, options.fontLigatures !== editorOptions_1.EditorFontLigatures.OFF, selectionsOnLine);
            if (this._renderedViewLine && this._renderedViewLine.input.equals(renderLineInput)) {
                // no need to do anything, we have the same render input
                return false;
            }
            sb.appendString('<div style="top:');
            sb.appendString(String(deltaTop));
            sb.appendString('px;height:');
            sb.appendString(String(lineHeight));
            sb.appendString('px;" class="');
            sb.appendString(ViewLine.CLASS_NAME);
            sb.appendString('">');
            const output = (0, viewLineRenderer_1.renderViewLine)(renderLineInput, sb);
            sb.appendString('</div>');
            let renderedViewLine = null;
            if (monospaceAssumptionsAreValid && canUseFastRenderedViewLine && lineData.isBasicASCII && options.useMonospaceOptimizations && output.containsForeignElements === 0 /* ForeignElementType.None */) {
                renderedViewLine = new FastRenderedViewLine(this._renderedViewLine ? this._renderedViewLine.domNode : null, renderLineInput, output.characterMapping);
            }
            if (!renderedViewLine) {
                renderedViewLine = createRenderedLine(this._renderedViewLine ? this._renderedViewLine.domNode : null, renderLineInput, output.characterMapping, output.containsRTL, output.containsForeignElements);
            }
            this._renderedViewLine = renderedViewLine;
            return true;
        }
        layoutLine(lineNumber, deltaTop, lineHeight) {
            if (this._renderedViewLine && this._renderedViewLine.domNode) {
                this._renderedViewLine.domNode.setTop(deltaTop);
                this._renderedViewLine.domNode.setHeight(lineHeight);
            }
        }
        // --- end IVisibleLineData
        getWidth(context) {
            if (!this._renderedViewLine) {
                return 0;
            }
            return this._renderedViewLine.getWidth(context);
        }
        getWidthIsFast() {
            if (!this._renderedViewLine) {
                return true;
            }
            return this._renderedViewLine.getWidthIsFast();
        }
        needsMonospaceFontCheck() {
            if (!this._renderedViewLine) {
                return false;
            }
            return (this._renderedViewLine instanceof FastRenderedViewLine);
        }
        monospaceAssumptionsAreValid() {
            if (!this._renderedViewLine) {
                return monospaceAssumptionsAreValid;
            }
            if (this._renderedViewLine instanceof FastRenderedViewLine) {
                return this._renderedViewLine.monospaceAssumptionsAreValid();
            }
            return monospaceAssumptionsAreValid;
        }
        onMonospaceAssumptionsInvalidated() {
            if (this._renderedViewLine && this._renderedViewLine instanceof FastRenderedViewLine) {
                this._renderedViewLine = this._renderedViewLine.toSlowRenderedLine();
            }
        }
        getVisibleRangesForRange(lineNumber, startColumn, endColumn, context) {
            if (!this._renderedViewLine) {
                return null;
            }
            startColumn = Math.min(this._renderedViewLine.input.lineContent.length + 1, Math.max(1, startColumn));
            endColumn = Math.min(this._renderedViewLine.input.lineContent.length + 1, Math.max(1, endColumn));
            const stopRenderingLineAfter = this._renderedViewLine.input.stopRenderingLineAfter;
            if (stopRenderingLineAfter !== -1 && startColumn > stopRenderingLineAfter + 1 && endColumn > stopRenderingLineAfter + 1) {
                // This range is obviously not visible
                return new renderingContext_1.VisibleRanges(true, [new renderingContext_1.FloatHorizontalRange(this.getWidth(context), 0)]);
            }
            if (stopRenderingLineAfter !== -1 && startColumn > stopRenderingLineAfter + 1) {
                startColumn = stopRenderingLineAfter + 1;
            }
            if (stopRenderingLineAfter !== -1 && endColumn > stopRenderingLineAfter + 1) {
                endColumn = stopRenderingLineAfter + 1;
            }
            const horizontalRanges = this._renderedViewLine.getVisibleRangesForRange(lineNumber, startColumn, endColumn, context);
            if (horizontalRanges && horizontalRanges.length > 0) {
                return new renderingContext_1.VisibleRanges(false, horizontalRanges);
            }
            return null;
        }
        getColumnOfNodeOffset(spanNode, offset) {
            if (!this._renderedViewLine) {
                return 1;
            }
            return this._renderedViewLine.getColumnOfNodeOffset(spanNode, offset);
        }
    }
    exports.ViewLine = ViewLine;
    /**
     * A rendered line which is guaranteed to contain only regular ASCII and is rendered with a monospace font.
     */
    class FastRenderedViewLine {
        constructor(domNode, renderLineInput, characterMapping) {
            this._cachedWidth = -1;
            this.domNode = domNode;
            this.input = renderLineInput;
            const keyColumnCount = Math.floor(renderLineInput.lineContent.length / 300 /* Constants.MaxMonospaceDistance */);
            if (keyColumnCount > 0) {
                this._keyColumnPixelOffsetCache = new Float32Array(keyColumnCount);
                for (let i = 0; i < keyColumnCount; i++) {
                    this._keyColumnPixelOffsetCache[i] = -1;
                }
            }
            else {
                this._keyColumnPixelOffsetCache = null;
            }
            this._characterMapping = characterMapping;
            this._charWidth = renderLineInput.spaceWidth;
        }
        getWidth(context) {
            if (!this.domNode || this.input.lineContent.length < 300 /* Constants.MaxMonospaceDistance */) {
                const horizontalOffset = this._characterMapping.getHorizontalOffset(this._characterMapping.length);
                return Math.round(this._charWidth * horizontalOffset);
            }
            if (this._cachedWidth === -1) {
                this._cachedWidth = this._getReadingTarget(this.domNode).offsetWidth;
                context?.markDidDomLayout();
            }
            return this._cachedWidth;
        }
        getWidthIsFast() {
            return (this.input.lineContent.length < 300 /* Constants.MaxMonospaceDistance */) || this._cachedWidth !== -1;
        }
        monospaceAssumptionsAreValid() {
            if (!this.domNode) {
                return monospaceAssumptionsAreValid;
            }
            if (this.input.lineContent.length < 300 /* Constants.MaxMonospaceDistance */) {
                const expectedWidth = this.getWidth(null);
                const actualWidth = this.domNode.domNode.firstChild.offsetWidth;
                if (Math.abs(expectedWidth - actualWidth) >= 2) {
                    // more than 2px off
                    console.warn(`monospace assumptions have been violated, therefore disabling monospace optimizations!`);
                    monospaceAssumptionsAreValid = false;
                }
            }
            return monospaceAssumptionsAreValid;
        }
        toSlowRenderedLine() {
            return createRenderedLine(this.domNode, this.input, this._characterMapping, false, 0 /* ForeignElementType.None */);
        }
        getVisibleRangesForRange(lineNumber, startColumn, endColumn, context) {
            const startPosition = this._getColumnPixelOffset(lineNumber, startColumn, context);
            const endPosition = this._getColumnPixelOffset(lineNumber, endColumn, context);
            return [new renderingContext_1.FloatHorizontalRange(startPosition, endPosition - startPosition)];
        }
        _getColumnPixelOffset(lineNumber, column, context) {
            if (column <= 300 /* Constants.MaxMonospaceDistance */) {
                const horizontalOffset = this._characterMapping.getHorizontalOffset(column);
                return this._charWidth * horizontalOffset;
            }
            const keyColumnOrdinal = Math.floor((column - 1) / 300 /* Constants.MaxMonospaceDistance */) - 1;
            const keyColumn = (keyColumnOrdinal + 1) * 300 /* Constants.MaxMonospaceDistance */ + 1;
            let keyColumnPixelOffset = -1;
            if (this._keyColumnPixelOffsetCache) {
                keyColumnPixelOffset = this._keyColumnPixelOffsetCache[keyColumnOrdinal];
                if (keyColumnPixelOffset === -1) {
                    keyColumnPixelOffset = this._actualReadPixelOffset(lineNumber, keyColumn, context);
                    this._keyColumnPixelOffsetCache[keyColumnOrdinal] = keyColumnPixelOffset;
                }
            }
            if (keyColumnPixelOffset === -1) {
                // Could not read actual key column pixel offset
                const horizontalOffset = this._characterMapping.getHorizontalOffset(column);
                return this._charWidth * horizontalOffset;
            }
            const keyColumnHorizontalOffset = this._characterMapping.getHorizontalOffset(keyColumn);
            const horizontalOffset = this._characterMapping.getHorizontalOffset(column);
            return keyColumnPixelOffset + this._charWidth * (horizontalOffset - keyColumnHorizontalOffset);
        }
        _getReadingTarget(myDomNode) {
            return myDomNode.domNode.firstChild;
        }
        _actualReadPixelOffset(lineNumber, column, context) {
            if (!this.domNode) {
                return -1;
            }
            const domPosition = this._characterMapping.getDomPosition(column);
            const r = rangeUtil_1.RangeUtil.readHorizontalRanges(this._getReadingTarget(this.domNode), domPosition.partIndex, domPosition.charIndex, domPosition.partIndex, domPosition.charIndex, context);
            if (!r || r.length === 0) {
                return -1;
            }
            return r[0].left;
        }
        getColumnOfNodeOffset(spanNode, offset) {
            return getColumnOfNodeOffset(this._characterMapping, spanNode, offset);
        }
    }
    /**
     * Every time we render a line, we save what we have rendered in an instance of this class.
     */
    class RenderedViewLine {
        constructor(domNode, renderLineInput, characterMapping, containsRTL, containsForeignElements) {
            this.domNode = domNode;
            this.input = renderLineInput;
            this._characterMapping = characterMapping;
            this._isWhitespaceOnly = /^\s*$/.test(renderLineInput.lineContent);
            this._containsForeignElements = containsForeignElements;
            this._cachedWidth = -1;
            this._pixelOffsetCache = null;
            if (!containsRTL || this._characterMapping.length === 0 /* the line is empty */) {
                this._pixelOffsetCache = new Float32Array(Math.max(2, this._characterMapping.length + 1));
                for (let column = 0, len = this._characterMapping.length; column <= len; column++) {
                    this._pixelOffsetCache[column] = -1;
                }
            }
        }
        // --- Reading from the DOM methods
        _getReadingTarget(myDomNode) {
            return myDomNode.domNode.firstChild;
        }
        /**
         * Width of the line in pixels
         */
        getWidth(context) {
            if (!this.domNode) {
                return 0;
            }
            if (this._cachedWidth === -1) {
                this._cachedWidth = this._getReadingTarget(this.domNode).offsetWidth;
                context?.markDidDomLayout();
            }
            return this._cachedWidth;
        }
        getWidthIsFast() {
            if (this._cachedWidth === -1) {
                return false;
            }
            return true;
        }
        /**
         * Visible ranges for a model range
         */
        getVisibleRangesForRange(lineNumber, startColumn, endColumn, context) {
            if (!this.domNode) {
                return null;
            }
            if (this._pixelOffsetCache !== null) {
                // the text is LTR
                const startOffset = this._readPixelOffset(this.domNode, lineNumber, startColumn, context);
                if (startOffset === -1) {
                    return null;
                }
                const endOffset = this._readPixelOffset(this.domNode, lineNumber, endColumn, context);
                if (endOffset === -1) {
                    return null;
                }
                return [new renderingContext_1.FloatHorizontalRange(startOffset, endOffset - startOffset)];
            }
            return this._readVisibleRangesForRange(this.domNode, lineNumber, startColumn, endColumn, context);
        }
        _readVisibleRangesForRange(domNode, lineNumber, startColumn, endColumn, context) {
            if (startColumn === endColumn) {
                const pixelOffset = this._readPixelOffset(domNode, lineNumber, startColumn, context);
                if (pixelOffset === -1) {
                    return null;
                }
                else {
                    return [new renderingContext_1.FloatHorizontalRange(pixelOffset, 0)];
                }
            }
            else {
                return this._readRawVisibleRangesForRange(domNode, startColumn, endColumn, context);
            }
        }
        _readPixelOffset(domNode, lineNumber, column, context) {
            if (this._characterMapping.length === 0) {
                // This line has no content
                if (this._containsForeignElements === 0 /* ForeignElementType.None */) {
                    // We can assume the line is really empty
                    return 0;
                }
                if (this._containsForeignElements === 2 /* ForeignElementType.After */) {
                    // We have foreign elements after the (empty) line
                    return 0;
                }
                if (this._containsForeignElements === 1 /* ForeignElementType.Before */) {
                    // We have foreign elements before the (empty) line
                    return this.getWidth(context);
                }
                // We have foreign elements before & after the (empty) line
                const readingTarget = this._getReadingTarget(domNode);
                if (readingTarget.firstChild) {
                    context.markDidDomLayout();
                    return readingTarget.firstChild.offsetWidth;
                }
                else {
                    return 0;
                }
            }
            if (this._pixelOffsetCache !== null) {
                // the text is LTR
                const cachedPixelOffset = this._pixelOffsetCache[column];
                if (cachedPixelOffset !== -1) {
                    return cachedPixelOffset;
                }
                const result = this._actualReadPixelOffset(domNode, lineNumber, column, context);
                this._pixelOffsetCache[column] = result;
                return result;
            }
            return this._actualReadPixelOffset(domNode, lineNumber, column, context);
        }
        _actualReadPixelOffset(domNode, lineNumber, column, context) {
            if (this._characterMapping.length === 0) {
                // This line has no content
                const r = rangeUtil_1.RangeUtil.readHorizontalRanges(this._getReadingTarget(domNode), 0, 0, 0, 0, context);
                if (!r || r.length === 0) {
                    return -1;
                }
                return r[0].left;
            }
            if (column === this._characterMapping.length && this._isWhitespaceOnly && this._containsForeignElements === 0 /* ForeignElementType.None */) {
                // This branch helps in the case of whitespace only lines which have a width set
                return this.getWidth(context);
            }
            const domPosition = this._characterMapping.getDomPosition(column);
            const r = rangeUtil_1.RangeUtil.readHorizontalRanges(this._getReadingTarget(domNode), domPosition.partIndex, domPosition.charIndex, domPosition.partIndex, domPosition.charIndex, context);
            if (!r || r.length === 0) {
                return -1;
            }
            const result = r[0].left;
            if (this.input.isBasicASCII) {
                const horizontalOffset = this._characterMapping.getHorizontalOffset(column);
                const expectedResult = Math.round(this.input.spaceWidth * horizontalOffset);
                if (Math.abs(expectedResult - result) <= 1) {
                    return expectedResult;
                }
            }
            return result;
        }
        _readRawVisibleRangesForRange(domNode, startColumn, endColumn, context) {
            if (startColumn === 1 && endColumn === this._characterMapping.length) {
                // This branch helps IE with bidi text & gives a performance boost to other browsers when reading visible ranges for an entire line
                return [new renderingContext_1.FloatHorizontalRange(0, this.getWidth(context))];
            }
            const startDomPosition = this._characterMapping.getDomPosition(startColumn);
            const endDomPosition = this._characterMapping.getDomPosition(endColumn);
            return rangeUtil_1.RangeUtil.readHorizontalRanges(this._getReadingTarget(domNode), startDomPosition.partIndex, startDomPosition.charIndex, endDomPosition.partIndex, endDomPosition.charIndex, context);
        }
        /**
         * Returns the column for the text found at a specific offset inside a rendered dom node
         */
        getColumnOfNodeOffset(spanNode, offset) {
            return getColumnOfNodeOffset(this._characterMapping, spanNode, offset);
        }
    }
    class WebKitRenderedViewLine extends RenderedViewLine {
        _readVisibleRangesForRange(domNode, lineNumber, startColumn, endColumn, context) {
            const output = super._readVisibleRangesForRange(domNode, lineNumber, startColumn, endColumn, context);
            if (!output || output.length === 0 || startColumn === endColumn || (startColumn === 1 && endColumn === this._characterMapping.length)) {
                return output;
            }
            // WebKit is buggy and returns an expanded range (to contain words in some cases)
            // The last client rect is enlarged (I think)
            if (!this.input.containsRTL) {
                // This is an attempt to patch things up
                // Find position of last column
                const endPixelOffset = this._readPixelOffset(domNode, lineNumber, endColumn, context);
                if (endPixelOffset !== -1) {
                    const lastRange = output[output.length - 1];
                    if (lastRange.left < endPixelOffset) {
                        // Trim down the width of the last visible range to not go after the last column's position
                        lastRange.width = endPixelOffset - lastRange.left;
                    }
                }
            }
            return output;
        }
    }
    const createRenderedLine = (function () {
        if (browser.isWebKit) {
            return createWebKitRenderedLine;
        }
        return createNormalRenderedLine;
    })();
    function createWebKitRenderedLine(domNode, renderLineInput, characterMapping, containsRTL, containsForeignElements) {
        return new WebKitRenderedViewLine(domNode, renderLineInput, characterMapping, containsRTL, containsForeignElements);
    }
    function createNormalRenderedLine(domNode, renderLineInput, characterMapping, containsRTL, containsForeignElements) {
        return new RenderedViewLine(domNode, renderLineInput, characterMapping, containsRTL, containsForeignElements);
    }
    function getColumnOfNodeOffset(characterMapping, spanNode, offset) {
        const spanNodeTextContentLength = spanNode.textContent.length;
        let spanIndex = -1;
        while (spanNode) {
            spanNode = spanNode.previousSibling;
            spanIndex++;
        }
        return characterMapping.getColumn(new viewLineRenderer_1.DomPosition(spanIndex, offset), spanNodeTextContentLength);
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[414/*vs/editor/browser/controller/mouseTarget*/], __M([1/*require*/,0/*exports*/,185/*vs/editor/browser/editorDom*/,56/*vs/editor/browser/view/viewPart*/,281/*vs/editor/browser/viewParts/lines/viewLine*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/,94/*vs/editor/common/core/cursorColumns*/,5/*vs/base/browser/dom*/,313/*vs/editor/common/cursor/cursorAtomicMoveOperations*/,98/*vs/base/common/lazy*/]), function (require, exports, editorDom_1, viewPart_1, viewLine_1, position_1, range_1, cursorColumns_1, dom, cursorAtomicMoveOperations_1, lazy_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MouseTargetFactory = exports.HitTestContext = exports.MouseTarget = exports.PointerHandlerLastRenderData = void 0;
    class UnknownHitTestResult {
        constructor(hitTarget = null) {
            this.hitTarget = hitTarget;
            this.type = 0 /* HitTestResultType.Unknown */;
        }
    }
    class ContentHitTestResult {
        get hitTarget() { return this.spanNode; }
        constructor(position, spanNode, injectedText) {
            this.position = position;
            this.spanNode = spanNode;
            this.injectedText = injectedText;
            this.type = 1 /* HitTestResultType.Content */;
        }
    }
    var HitTestResult;
    (function (HitTestResult) {
        function createFromDOMInfo(ctx, spanNode, offset) {
            const position = ctx.getPositionFromDOMInfo(spanNode, offset);
            if (position) {
                return new ContentHitTestResult(position, spanNode, null);
            }
            return new UnknownHitTestResult(spanNode);
        }
        HitTestResult.createFromDOMInfo = createFromDOMInfo;
    })(HitTestResult || (HitTestResult = {}));
    class PointerHandlerLastRenderData {
        constructor(lastViewCursorsRenderData, lastTextareaPosition) {
            this.lastViewCursorsRenderData = lastViewCursorsRenderData;
            this.lastTextareaPosition = lastTextareaPosition;
        }
    }
    exports.PointerHandlerLastRenderData = PointerHandlerLastRenderData;
    class MouseTarget {
        static _deduceRage(position, range = null) {
            if (!range && position) {
                return new range_1.Range(position.lineNumber, position.column, position.lineNumber, position.column);
            }
            return range ?? null;
        }
        static createUnknown(element, mouseColumn, position) {
            return { type: 0 /* MouseTargetType.UNKNOWN */, element, mouseColumn, position, range: this._deduceRage(position) };
        }
        static createTextarea(element, mouseColumn) {
            return { type: 1 /* MouseTargetType.TEXTAREA */, element, mouseColumn, position: null, range: null };
        }
        static createMargin(type, element, mouseColumn, position, range, detail) {
            return { type, element, mouseColumn, position, range, detail };
        }
        static createViewZone(type, element, mouseColumn, position, detail) {
            return { type, element, mouseColumn, position, range: this._deduceRage(position), detail };
        }
        static createContentText(element, mouseColumn, position, range, detail) {
            return { type: 6 /* MouseTargetType.CONTENT_TEXT */, element, mouseColumn, position, range: this._deduceRage(position, range), detail };
        }
        static createContentEmpty(element, mouseColumn, position, detail) {
            return { type: 7 /* MouseTargetType.CONTENT_EMPTY */, element, mouseColumn, position, range: this._deduceRage(position), detail };
        }
        static createContentWidget(element, mouseColumn, detail) {
            return { type: 9 /* MouseTargetType.CONTENT_WIDGET */, element, mouseColumn, position: null, range: null, detail };
        }
        static createScrollbar(element, mouseColumn, position) {
            return { type: 11 /* MouseTargetType.SCROLLBAR */, element, mouseColumn, position, range: this._deduceRage(position) };
        }
        static createOverlayWidget(element, mouseColumn, detail) {
            return { type: 12 /* MouseTargetType.OVERLAY_WIDGET */, element, mouseColumn, position: null, range: null, detail };
        }
        static createOutsideEditor(mouseColumn, position, outsidePosition, outsideDistance) {
            return { type: 13 /* MouseTargetType.OUTSIDE_EDITOR */, element: null, mouseColumn, position, range: this._deduceRage(position), outsidePosition, outsideDistance };
        }
        static _typeToString(type) {
            if (type === 1 /* MouseTargetType.TEXTAREA */) {
                return 'TEXTAREA';
            }
            if (type === 2 /* MouseTargetType.GUTTER_GLYPH_MARGIN */) {
                return 'GUTTER_GLYPH_MARGIN';
            }
            if (type === 3 /* MouseTargetType.GUTTER_LINE_NUMBERS */) {
                return 'GUTTER_LINE_NUMBERS';
            }
            if (type === 4 /* MouseTargetType.GUTTER_LINE_DECORATIONS */) {
                return 'GUTTER_LINE_DECORATIONS';
            }
            if (type === 5 /* MouseTargetType.GUTTER_VIEW_ZONE */) {
                return 'GUTTER_VIEW_ZONE';
            }
            if (type === 6 /* MouseTargetType.CONTENT_TEXT */) {
                return 'CONTENT_TEXT';
            }
            if (type === 7 /* MouseTargetType.CONTENT_EMPTY */) {
                return 'CONTENT_EMPTY';
            }
            if (type === 8 /* MouseTargetType.CONTENT_VIEW_ZONE */) {
                return 'CONTENT_VIEW_ZONE';
            }
            if (type === 9 /* MouseTargetType.CONTENT_WIDGET */) {
                return 'CONTENT_WIDGET';
            }
            if (type === 10 /* MouseTargetType.OVERVIEW_RULER */) {
                return 'OVERVIEW_RULER';
            }
            if (type === 11 /* MouseTargetType.SCROLLBAR */) {
                return 'SCROLLBAR';
            }
            if (type === 12 /* MouseTargetType.OVERLAY_WIDGET */) {
                return 'OVERLAY_WIDGET';
            }
            return 'UNKNOWN';
        }
        static toString(target) {
            return this._typeToString(target.type) + ': ' + target.position + ' - ' + target.range + ' - ' + JSON.stringify(target.detail);
        }
    }
    exports.MouseTarget = MouseTarget;
    class ElementPath {
        static isTextArea(path) {
            return (path.length === 2
                && path[0] === 3 /* PartFingerprint.OverflowGuard */
                && path[1] === 7 /* PartFingerprint.TextArea */);
        }
        static isChildOfViewLines(path) {
            return (path.length >= 4
                && path[0] === 3 /* PartFingerprint.OverflowGuard */
                && path[3] === 8 /* PartFingerprint.ViewLines */);
        }
        static isStrictChildOfViewLines(path) {
            return (path.length > 4
                && path[0] === 3 /* PartFingerprint.OverflowGuard */
                && path[3] === 8 /* PartFingerprint.ViewLines */);
        }
        static isChildOfScrollableElement(path) {
            return (path.length >= 2
                && path[0] === 3 /* PartFingerprint.OverflowGuard */
                && path[1] === 6 /* PartFingerprint.ScrollableElement */);
        }
        static isChildOfMinimap(path) {
            return (path.length >= 2
                && path[0] === 3 /* PartFingerprint.OverflowGuard */
                && path[1] === 9 /* PartFingerprint.Minimap */);
        }
        static isChildOfContentWidgets(path) {
            return (path.length >= 4
                && path[0] === 3 /* PartFingerprint.OverflowGuard */
                && path[3] === 1 /* PartFingerprint.ContentWidgets */);
        }
        static isChildOfOverflowGuard(path) {
            return (path.length >= 1
                && path[0] === 3 /* PartFingerprint.OverflowGuard */);
        }
        static isChildOfOverflowingContentWidgets(path) {
            return (path.length >= 1
                && path[0] === 2 /* PartFingerprint.OverflowingContentWidgets */);
        }
        static isChildOfOverlayWidgets(path) {
            return (path.length >= 2
                && path[0] === 3 /* PartFingerprint.OverflowGuard */
                && path[1] === 4 /* PartFingerprint.OverlayWidgets */);
        }
        static isChildOfOverflowingOverlayWidgets(path) {
            return (path.length >= 1
                && path[0] === 5 /* PartFingerprint.OverflowingOverlayWidgets */);
        }
    }
    class HitTestContext {
        constructor(context, viewHelper, lastRenderData) {
            this.viewModel = context.viewModel;
            const options = context.configuration.options;
            this.layoutInfo = options.get(146 /* EditorOption.layoutInfo */);
            this.viewDomNode = viewHelper.viewDomNode;
            this.lineHeight = options.get(67 /* EditorOption.lineHeight */);
            this.stickyTabStops = options.get(117 /* EditorOption.stickyTabStops */);
            this.typicalHalfwidthCharacterWidth = options.get(50 /* EditorOption.fontInfo */).typicalHalfwidthCharacterWidth;
            this.lastRenderData = lastRenderData;
            this._context = context;
            this._viewHelper = viewHelper;
        }
        getZoneAtCoord(mouseVerticalOffset) {
            return HitTestContext.getZoneAtCoord(this._context, mouseVerticalOffset);
        }
        static getZoneAtCoord(context, mouseVerticalOffset) {
            // The target is either a view zone or the empty space after the last view-line
            const viewZoneWhitespace = context.viewLayout.getWhitespaceAtVerticalOffset(mouseVerticalOffset);
            if (viewZoneWhitespace) {
                const viewZoneMiddle = viewZoneWhitespace.verticalOffset + viewZoneWhitespace.height / 2;
                const lineCount = context.viewModel.getLineCount();
                let positionBefore = null;
                let position;
                let positionAfter = null;
                if (viewZoneWhitespace.afterLineNumber !== lineCount) {
                    // There are more lines after this view zone
                    positionAfter = new position_1.Position(viewZoneWhitespace.afterLineNumber + 1, 1);
                }
                if (viewZoneWhitespace.afterLineNumber > 0) {
                    // There are more lines above this view zone
                    positionBefore = new position_1.Position(viewZoneWhitespace.afterLineNumber, context.viewModel.getLineMaxColumn(viewZoneWhitespace.afterLineNumber));
                }
                if (positionAfter === null) {
                    position = positionBefore;
                }
                else if (positionBefore === null) {
                    position = positionAfter;
                }
                else if (mouseVerticalOffset < viewZoneMiddle) {
                    position = positionBefore;
                }
                else {
                    position = positionAfter;
                }
                return {
                    viewZoneId: viewZoneWhitespace.id,
                    afterLineNumber: viewZoneWhitespace.afterLineNumber,
                    positionBefore: positionBefore,
                    positionAfter: positionAfter,
                    position: position
                };
            }
            return null;
        }
        getFullLineRangeAtCoord(mouseVerticalOffset) {
            if (this._context.viewLayout.isAfterLines(mouseVerticalOffset)) {
                // Below the last line
                const lineNumber = this._context.viewModel.getLineCount();
                const maxLineColumn = this._context.viewModel.getLineMaxColumn(lineNumber);
                return {
                    range: new range_1.Range(lineNumber, maxLineColumn, lineNumber, maxLineColumn),
                    isAfterLines: true
                };
            }
            const lineNumber = this._context.viewLayout.getLineNumberAtVerticalOffset(mouseVerticalOffset);
            const maxLineColumn = this._context.viewModel.getLineMaxColumn(lineNumber);
            return {
                range: new range_1.Range(lineNumber, 1, lineNumber, maxLineColumn),
                isAfterLines: false
            };
        }
        getLineNumberAtVerticalOffset(mouseVerticalOffset) {
            return this._context.viewLayout.getLineNumberAtVerticalOffset(mouseVerticalOffset);
        }
        isAfterLines(mouseVerticalOffset) {
            return this._context.viewLayout.isAfterLines(mouseVerticalOffset);
        }
        isInTopPadding(mouseVerticalOffset) {
            return this._context.viewLayout.isInTopPadding(mouseVerticalOffset);
        }
        isInBottomPadding(mouseVerticalOffset) {
            return this._context.viewLayout.isInBottomPadding(mouseVerticalOffset);
        }
        getVerticalOffsetForLineNumber(lineNumber) {
            return this._context.viewLayout.getVerticalOffsetForLineNumber(lineNumber);
        }
        findAttribute(element, attr) {
            return HitTestContext._findAttribute(element, attr, this._viewHelper.viewDomNode);
        }
        static _findAttribute(element, attr, stopAt) {
            while (element && element !== element.ownerDocument.body) {
                if (element.hasAttribute && element.hasAttribute(attr)) {
                    return element.getAttribute(attr);
                }
                if (element === stopAt) {
                    return null;
                }
                element = element.parentNode;
            }
            return null;
        }
        getLineWidth(lineNumber) {
            return this._viewHelper.getLineWidth(lineNumber);
        }
        visibleRangeForPosition(lineNumber, column) {
            return this._viewHelper.visibleRangeForPosition(lineNumber, column);
        }
        getPositionFromDOMInfo(spanNode, offset) {
            return this._viewHelper.getPositionFromDOMInfo(spanNode, offset);
        }
        getCurrentScrollTop() {
            return this._context.viewLayout.getCurrentScrollTop();
        }
        getCurrentScrollLeft() {
            return this._context.viewLayout.getCurrentScrollLeft();
        }
    }
    exports.HitTestContext = HitTestContext;
    class BareHitTestRequest {
        constructor(ctx, editorPos, pos, relativePos) {
            this.editorPos = editorPos;
            this.pos = pos;
            this.relativePos = relativePos;
            this.mouseVerticalOffset = Math.max(0, ctx.getCurrentScrollTop() + this.relativePos.y);
            this.mouseContentHorizontalOffset = ctx.getCurrentScrollLeft() + this.relativePos.x - ctx.layoutInfo.contentLeft;
            this.isInMarginArea = (this.relativePos.x < ctx.layoutInfo.contentLeft && this.relativePos.x >= ctx.layoutInfo.glyphMarginLeft);
            this.isInContentArea = !this.isInMarginArea;
            this.mouseColumn = Math.max(0, MouseTargetFactory._getMouseColumn(this.mouseContentHorizontalOffset, ctx.typicalHalfwidthCharacterWidth));
        }
    }
    class HitTestRequest extends BareHitTestRequest {
        get target() {
            if (this._useHitTestTarget) {
                return this.hitTestResult.value.hitTarget;
            }
            return this._eventTarget;
        }
        get targetPath() {
            if (this._targetPathCacheElement !== this.target) {
                this._targetPathCacheElement = this.target;
                this._targetPathCacheValue = viewPart_1.PartFingerprints.collect(this.target, this._ctx.viewDomNode);
            }
            return this._targetPathCacheValue;
        }
        constructor(ctx, editorPos, pos, relativePos, eventTarget) {
            super(ctx, editorPos, pos, relativePos);
            this.hitTestResult = new lazy_1.Lazy(() => MouseTargetFactory.doHitTest(this._ctx, this));
            this._targetPathCacheElement = null;
            this._targetPathCacheValue = new Uint8Array(0);
            this._ctx = ctx;
            this._eventTarget = eventTarget;
            // If no event target is passed in, we will use the hit test target
            const hasEventTarget = Boolean(this._eventTarget);
            this._useHitTestTarget = !hasEventTarget;
        }
        toString() {
            return `pos(${this.pos.x},${this.pos.y}), editorPos(${this.editorPos.x},${this.editorPos.y}), relativePos(${this.relativePos.x},${this.relativePos.y}), mouseVerticalOffset: ${this.mouseVerticalOffset}, mouseContentHorizontalOffset: ${this.mouseContentHorizontalOffset}\n\ttarget: ${this.target ? this.target.outerHTML : null}`;
        }
        get wouldBenefitFromHitTestTargetSwitch() {
            return (!this._useHitTestTarget
                && this.hitTestResult.value.hitTarget !== null
                && this.target !== this.hitTestResult.value.hitTarget);
        }
        switchToHitTestTarget() {
            this._useHitTestTarget = true;
        }
        _getMouseColumn(position = null) {
            if (position && position.column < this._ctx.viewModel.getLineMaxColumn(position.lineNumber)) {
                // Most likely, the line contains foreign decorations...
                return cursorColumns_1.CursorColumns.visibleColumnFromColumn(this._ctx.viewModel.getLineContent(position.lineNumber), position.column, this._ctx.viewModel.model.getOptions().tabSize) + 1;
            }
            return this.mouseColumn;
        }
        fulfillUnknown(position = null) {
            return MouseTarget.createUnknown(this.target, this._getMouseColumn(position), position);
        }
        fulfillTextarea() {
            return MouseTarget.createTextarea(this.target, this._getMouseColumn());
        }
        fulfillMargin(type, position, range, detail) {
            return MouseTarget.createMargin(type, this.target, this._getMouseColumn(position), position, range, detail);
        }
        fulfillViewZone(type, position, detail) {
            return MouseTarget.createViewZone(type, this.target, this._getMouseColumn(position), position, detail);
        }
        fulfillContentText(position, range, detail) {
            return MouseTarget.createContentText(this.target, this._getMouseColumn(position), position, range, detail);
        }
        fulfillContentEmpty(position, detail) {
            return MouseTarget.createContentEmpty(this.target, this._getMouseColumn(position), position, detail);
        }
        fulfillContentWidget(detail) {
            return MouseTarget.createContentWidget(this.target, this._getMouseColumn(), detail);
        }
        fulfillScrollbar(position) {
            return MouseTarget.createScrollbar(this.target, this._getMouseColumn(position), position);
        }
        fulfillOverlayWidget(detail) {
            return MouseTarget.createOverlayWidget(this.target, this._getMouseColumn(), detail);
        }
    }
    const EMPTY_CONTENT_AFTER_LINES = { isAfterLines: true };
    function createEmptyContentDataInLines(horizontalDistanceToText) {
        return {
            isAfterLines: false,
            horizontalDistanceToText: horizontalDistanceToText
        };
    }
    class MouseTargetFactory {
        constructor(context, viewHelper) {
            this._context = context;
            this._viewHelper = viewHelper;
        }
        mouseTargetIsWidget(e) {
            const t = e.target;
            const path = viewPart_1.PartFingerprints.collect(t, this._viewHelper.viewDomNode);
            // Is it a content widget?
            if (ElementPath.isChildOfContentWidgets(path) || ElementPath.isChildOfOverflowingContentWidgets(path)) {
                return true;
            }
            // Is it an overlay widget?
            if (ElementPath.isChildOfOverlayWidgets(path) || ElementPath.isChildOfOverflowingOverlayWidgets(path)) {
                return true;
            }
            return false;
        }
        createMouseTarget(lastRenderData, editorPos, pos, relativePos, target) {
            const ctx = new HitTestContext(this._context, this._viewHelper, lastRenderData);
            const request = new HitTestRequest(ctx, editorPos, pos, relativePos, target);
            try {
                const r = MouseTargetFactory._createMouseTarget(ctx, request);
                if (r.type === 6 /* MouseTargetType.CONTENT_TEXT */) {
                    // Snap to the nearest soft tab boundary if atomic soft tabs are enabled.
                    if (ctx.stickyTabStops && r.position !== null) {
                        const position = MouseTargetFactory._snapToSoftTabBoundary(r.position, ctx.viewModel);
                        const range = range_1.Range.fromPositions(position, position).plusRange(r.range);
                        return request.fulfillContentText(position, range, r.detail);
                    }
                }
                // console.log(MouseTarget.toString(r));
                return r;
            }
            catch (err) {
                // console.log(err);
                return request.fulfillUnknown();
            }
        }
        static _createMouseTarget(ctx, request) {
            // console.log(`${domHitTestExecuted ? '=>' : ''}CAME IN REQUEST: ${request}`);
            if (request.target === null) {
                // No target
                return request.fulfillUnknown();
            }
            // we know for a fact that request.target is not null
            const resolvedRequest = request;
            let result = null;
            if (!ElementPath.isChildOfOverflowGuard(request.targetPath) && !ElementPath.isChildOfOverflowingContentWidgets(request.targetPath) && !ElementPath.isChildOfOverflowingOverlayWidgets(request.targetPath)) {
                // We only render dom nodes inside the overflow guard or in the overflowing content widgets
                result = result || request.fulfillUnknown();
            }
            result = result || MouseTargetFactory._hitTestContentWidget(ctx, resolvedRequest);
            result = result || MouseTargetFactory._hitTestOverlayWidget(ctx, resolvedRequest);
            result = result || MouseTargetFactory._hitTestMinimap(ctx, resolvedRequest);
            result = result || MouseTargetFactory._hitTestScrollbarSlider(ctx, resolvedRequest);
            result = result || MouseTargetFactory._hitTestViewZone(ctx, resolvedRequest);
            result = result || MouseTargetFactory._hitTestMargin(ctx, resolvedRequest);
            result = result || MouseTargetFactory._hitTestViewCursor(ctx, resolvedRequest);
            result = result || MouseTargetFactory._hitTestTextArea(ctx, resolvedRequest);
            result = result || MouseTargetFactory._hitTestViewLines(ctx, resolvedRequest);
            result = result || MouseTargetFactory._hitTestScrollbar(ctx, resolvedRequest);
            return (result || request.fulfillUnknown());
        }
        static _hitTestContentWidget(ctx, request) {
            // Is it a content widget?
            if (ElementPath.isChildOfContentWidgets(request.targetPath) || ElementPath.isChildOfOverflowingContentWidgets(request.targetPath)) {
                const widgetId = ctx.findAttribute(request.target, 'widgetId');
                if (widgetId) {
                    return request.fulfillContentWidget(widgetId);
                }
                else {
                    return request.fulfillUnknown();
                }
            }
            return null;
        }
        static _hitTestOverlayWidget(ctx, request) {
            // Is it an overlay widget?
            if (ElementPath.isChildOfOverlayWidgets(request.targetPath) || ElementPath.isChildOfOverflowingOverlayWidgets(request.targetPath)) {
                const widgetId = ctx.findAttribute(request.target, 'widgetId');
                if (widgetId) {
                    return request.fulfillOverlayWidget(widgetId);
                }
                else {
                    return request.fulfillUnknown();
                }
            }
            return null;
        }
        static _hitTestViewCursor(ctx, request) {
            if (request.target) {
                // Check if we've hit a painted cursor
                const lastViewCursorsRenderData = ctx.lastRenderData.lastViewCursorsRenderData;
                for (const d of lastViewCursorsRenderData) {
                    if (request.target === d.domNode) {
                        return request.fulfillContentText(d.position, null, { mightBeForeignElement: false, injectedText: null });
                    }
                }
            }
            if (request.isInContentArea) {
                // Edge has a bug when hit-testing the exact position of a cursor,
                // instead of returning the correct dom node, it returns the
                // first or last rendered view line dom node, therefore help it out
                // and first check if we are on top of a cursor
                const lastViewCursorsRenderData = ctx.lastRenderData.lastViewCursorsRenderData;
                const mouseContentHorizontalOffset = request.mouseContentHorizontalOffset;
                const mouseVerticalOffset = request.mouseVerticalOffset;
                for (const d of lastViewCursorsRenderData) {
                    if (mouseContentHorizontalOffset < d.contentLeft) {
                        // mouse position is to the left of the cursor
                        continue;
                    }
                    if (mouseContentHorizontalOffset > d.contentLeft + d.width) {
                        // mouse position is to the right of the cursor
                        continue;
                    }
                    const cursorVerticalOffset = ctx.getVerticalOffsetForLineNumber(d.position.lineNumber);
                    if (cursorVerticalOffset <= mouseVerticalOffset
                        && mouseVerticalOffset <= cursorVerticalOffset + d.height) {
                        return request.fulfillContentText(d.position, null, { mightBeForeignElement: false, injectedText: null });
                    }
                }
            }
            return null;
        }
        static _hitTestViewZone(ctx, request) {
            const viewZoneData = ctx.getZoneAtCoord(request.mouseVerticalOffset);
            if (viewZoneData) {
                const mouseTargetType = (request.isInContentArea ? 8 /* MouseTargetType.CONTENT_VIEW_ZONE */ : 5 /* MouseTargetType.GUTTER_VIEW_ZONE */);
                return request.fulfillViewZone(mouseTargetType, viewZoneData.position, viewZoneData);
            }
            return null;
        }
        static _hitTestTextArea(ctx, request) {
            // Is it the textarea?
            if (ElementPath.isTextArea(request.targetPath)) {
                if (ctx.lastRenderData.lastTextareaPosition) {
                    return request.fulfillContentText(ctx.lastRenderData.lastTextareaPosition, null, { mightBeForeignElement: false, injectedText: null });
                }
                return request.fulfillTextarea();
            }
            return null;
        }
        static _hitTestMargin(ctx, request) {
            if (request.isInMarginArea) {
                const res = ctx.getFullLineRangeAtCoord(request.mouseVerticalOffset);
                const pos = res.range.getStartPosition();
                let offset = Math.abs(request.relativePos.x);
                const detail = {
                    isAfterLines: res.isAfterLines,
                    glyphMarginLeft: ctx.layoutInfo.glyphMarginLeft,
                    glyphMarginWidth: ctx.layoutInfo.glyphMarginWidth,
                    lineNumbersWidth: ctx.layoutInfo.lineNumbersWidth,
                    offsetX: offset
                };
                offset -= ctx.layoutInfo.glyphMarginLeft;
                if (offset <= ctx.layoutInfo.glyphMarginWidth) {
                    // On the glyph margin
                    const modelCoordinate = ctx.viewModel.coordinatesConverter.convertViewPositionToModelPosition(res.range.getStartPosition());
                    const lanes = ctx.viewModel.glyphLanes.getLanesAtLine(modelCoordinate.lineNumber);
                    detail.glyphMarginLane = lanes[Math.floor(offset / ctx.lineHeight)];
                    return request.fulfillMargin(2 /* MouseTargetType.GUTTER_GLYPH_MARGIN */, pos, res.range, detail);
                }
                offset -= ctx.layoutInfo.glyphMarginWidth;
                if (offset <= ctx.layoutInfo.lineNumbersWidth) {
                    // On the line numbers
                    return request.fulfillMargin(3 /* MouseTargetType.GUTTER_LINE_NUMBERS */, pos, res.range, detail);
                }
                offset -= ctx.layoutInfo.lineNumbersWidth;
                // On the line decorations
                return request.fulfillMargin(4 /* MouseTargetType.GUTTER_LINE_DECORATIONS */, pos, res.range, detail);
            }
            return null;
        }
        static _hitTestViewLines(ctx, request) {
            if (!ElementPath.isChildOfViewLines(request.targetPath)) {
                return null;
            }
            if (ctx.isInTopPadding(request.mouseVerticalOffset)) {
                return request.fulfillContentEmpty(new position_1.Position(1, 1), EMPTY_CONTENT_AFTER_LINES);
            }
            // Check if it is below any lines and any view zones
            if (ctx.isAfterLines(request.mouseVerticalOffset) || ctx.isInBottomPadding(request.mouseVerticalOffset)) {
                // This most likely indicates it happened after the last view-line
                const lineCount = ctx.viewModel.getLineCount();
                const maxLineColumn = ctx.viewModel.getLineMaxColumn(lineCount);
                return request.fulfillContentEmpty(new position_1.Position(lineCount, maxLineColumn), EMPTY_CONTENT_AFTER_LINES);
            }
            // Check if we are hitting a view-line (can happen in the case of inline decorations on empty lines)
            // See https://github.com/microsoft/vscode/issues/46942
            if (ElementPath.isStrictChildOfViewLines(request.targetPath)) {
                const lineNumber = ctx.getLineNumberAtVerticalOffset(request.mouseVerticalOffset);
                if (ctx.viewModel.getLineLength(lineNumber) === 0) {
                    const lineWidth = ctx.getLineWidth(lineNumber);
                    const detail = createEmptyContentDataInLines(request.mouseContentHorizontalOffset - lineWidth);
                    return request.fulfillContentEmpty(new position_1.Position(lineNumber, 1), detail);
                }
                const lineWidth = ctx.getLineWidth(lineNumber);
                if (request.mouseContentHorizontalOffset >= lineWidth) {
                    // TODO: This is wrong for RTL
                    const detail = createEmptyContentDataInLines(request.mouseContentHorizontalOffset - lineWidth);
                    const pos = new position_1.Position(lineNumber, ctx.viewModel.getLineMaxColumn(lineNumber));
                    return request.fulfillContentEmpty(pos, detail);
                }
            }
            // Do the hit test (if not already done)
            const hitTestResult = request.hitTestResult.value;
            if (hitTestResult.type === 1 /* HitTestResultType.Content */) {
                return MouseTargetFactory.createMouseTargetFromHitTestPosition(ctx, request, hitTestResult.spanNode, hitTestResult.position, hitTestResult.injectedText);
            }
            // We didn't hit content...
            if (request.wouldBenefitFromHitTestTargetSwitch) {
                // We actually hit something different... Give it one last change by trying again with this new target
                request.switchToHitTestTarget();
                return this._createMouseTarget(ctx, request);
            }
            // We have tried everything...
            return request.fulfillUnknown();
        }
        static _hitTestMinimap(ctx, request) {
            if (ElementPath.isChildOfMinimap(request.targetPath)) {
                const possibleLineNumber = ctx.getLineNumberAtVerticalOffset(request.mouseVerticalOffset);
                const maxColumn = ctx.viewModel.getLineMaxColumn(possibleLineNumber);
                return request.fulfillScrollbar(new position_1.Position(possibleLineNumber, maxColumn));
            }
            return null;
        }
        static _hitTestScrollbarSlider(ctx, request) {
            if (ElementPath.isChildOfScrollableElement(request.targetPath)) {
                if (request.target && request.target.nodeType === 1) {
                    const className = request.target.className;
                    if (className && /\b(slider|scrollbar)\b/.test(className)) {
                        const possibleLineNumber = ctx.getLineNumberAtVerticalOffset(request.mouseVerticalOffset);
                        const maxColumn = ctx.viewModel.getLineMaxColumn(possibleLineNumber);
                        return request.fulfillScrollbar(new position_1.Position(possibleLineNumber, maxColumn));
                    }
                }
            }
            return null;
        }
        static _hitTestScrollbar(ctx, request) {
            // Is it the overview ruler?
            // Is it a child of the scrollable element?
            if (ElementPath.isChildOfScrollableElement(request.targetPath)) {
                const possibleLineNumber = ctx.getLineNumberAtVerticalOffset(request.mouseVerticalOffset);
                const maxColumn = ctx.viewModel.getLineMaxColumn(possibleLineNumber);
                return request.fulfillScrollbar(new position_1.Position(possibleLineNumber, maxColumn));
            }
            return null;
        }
        getMouseColumn(relativePos) {
            const options = this._context.configuration.options;
            const layoutInfo = options.get(146 /* EditorOption.layoutInfo */);
            const mouseContentHorizontalOffset = this._context.viewLayout.getCurrentScrollLeft() + relativePos.x - layoutInfo.contentLeft;
            return MouseTargetFactory._getMouseColumn(mouseContentHorizontalOffset, options.get(50 /* EditorOption.fontInfo */).typicalHalfwidthCharacterWidth);
        }
        static _getMouseColumn(mouseContentHorizontalOffset, typicalHalfwidthCharacterWidth) {
            if (mouseContentHorizontalOffset < 0) {
                return 1;
            }
            const chars = Math.round(mouseContentHorizontalOffset / typicalHalfwidthCharacterWidth);
            return (chars + 1);
        }
        static createMouseTargetFromHitTestPosition(ctx, request, spanNode, pos, injectedText) {
            const lineNumber = pos.lineNumber;
            const column = pos.column;
            const lineWidth = ctx.getLineWidth(lineNumber);
            if (request.mouseContentHorizontalOffset > lineWidth) {
                const detail = createEmptyContentDataInLines(request.mouseContentHorizontalOffset - lineWidth);
                return request.fulfillContentEmpty(pos, detail);
            }
            const visibleRange = ctx.visibleRangeForPosition(lineNumber, column);
            if (!visibleRange) {
                return request.fulfillUnknown(pos);
            }
            const columnHorizontalOffset = visibleRange.left;
            if (Math.abs(request.mouseContentHorizontalOffset - columnHorizontalOffset) < 1) {
                return request.fulfillContentText(pos, null, { mightBeForeignElement: !!injectedText, injectedText });
            }
            const points = [];
            points.push({ offset: visibleRange.left, column: column });
            if (column > 1) {
                const visibleRange = ctx.visibleRangeForPosition(lineNumber, column - 1);
                if (visibleRange) {
                    points.push({ offset: visibleRange.left, column: column - 1 });
                }
            }
            const lineMaxColumn = ctx.viewModel.getLineMaxColumn(lineNumber);
            if (column < lineMaxColumn) {
                const visibleRange = ctx.visibleRangeForPosition(lineNumber, column + 1);
                if (visibleRange) {
                    points.push({ offset: visibleRange.left, column: column + 1 });
                }
            }
            points.sort((a, b) => a.offset - b.offset);
            const mouseCoordinates = request.pos.toClientCoordinates(dom.getWindow(ctx.viewDomNode));
            const spanNodeClientRect = spanNode.getBoundingClientRect();
            const mouseIsOverSpanNode = (spanNodeClientRect.left <= mouseCoordinates.clientX && mouseCoordinates.clientX <= spanNodeClientRect.right);
            let rng = null;
            for (let i = 1; i < points.length; i++) {
                const prev = points[i - 1];
                const curr = points[i];
                if (prev.offset <= request.mouseContentHorizontalOffset && request.mouseContentHorizontalOffset <= curr.offset) {
                    rng = new range_1.Range(lineNumber, prev.column, lineNumber, curr.column);
                    // See https://github.com/microsoft/vscode/issues/152819
                    // Due to the use of zwj, the browser's hit test result is skewed towards the left
                    // Here we try to correct that if the mouse horizontal offset is closer to the right than the left
                    const prevDelta = Math.abs(prev.offset - request.mouseContentHorizontalOffset);
                    const nextDelta = Math.abs(curr.offset - request.mouseContentHorizontalOffset);
                    pos = (prevDelta < nextDelta
                        ? new position_1.Position(lineNumber, prev.column)
                        : new position_1.Position(lineNumber, curr.column));
                    break;
                }
            }
            return request.fulfillContentText(pos, rng, { mightBeForeignElement: !mouseIsOverSpanNode || !!injectedText, injectedText });
        }
        /**
         * Most probably WebKit browsers and Edge
         */
        static _doHitTestWithCaretRangeFromPoint(ctx, request) {
            // In Chrome, especially on Linux it is possible to click between lines,
            // so try to adjust the `hity` below so that it lands in the center of a line
            const lineNumber = ctx.getLineNumberAtVerticalOffset(request.mouseVerticalOffset);
            const lineStartVerticalOffset = ctx.getVerticalOffsetForLineNumber(lineNumber);
            const lineEndVerticalOffset = lineStartVerticalOffset + ctx.lineHeight;
            const isBelowLastLine = (lineNumber === ctx.viewModel.getLineCount()
                && request.mouseVerticalOffset > lineEndVerticalOffset);
            if (!isBelowLastLine) {
                const lineCenteredVerticalOffset = Math.floor((lineStartVerticalOffset + lineEndVerticalOffset) / 2);
                let adjustedPageY = request.pos.y + (lineCenteredVerticalOffset - request.mouseVerticalOffset);
                if (adjustedPageY <= request.editorPos.y) {
                    adjustedPageY = request.editorPos.y + 1;
                }
                if (adjustedPageY >= request.editorPos.y + request.editorPos.height) {
                    adjustedPageY = request.editorPos.y + request.editorPos.height - 1;
                }
                const adjustedPage = new editorDom_1.PageCoordinates(request.pos.x, adjustedPageY);
                const r = this._actualDoHitTestWithCaretRangeFromPoint(ctx, adjustedPage.toClientCoordinates(dom.getWindow(ctx.viewDomNode)));
                if (r.type === 1 /* HitTestResultType.Content */) {
                    return r;
                }
            }
            // Also try to hit test without the adjustment (for the edge cases that we are near the top or bottom)
            return this._actualDoHitTestWithCaretRangeFromPoint(ctx, request.pos.toClientCoordinates(dom.getWindow(ctx.viewDomNode)));
        }
        static _actualDoHitTestWithCaretRangeFromPoint(ctx, coords) {
            const shadowRoot = dom.getShadowRoot(ctx.viewDomNode);
            let range;
            if (shadowRoot) {
                if (typeof shadowRoot.caretRangeFromPoint === 'undefined') {
                    range = shadowCaretRangeFromPoint(shadowRoot, coords.clientX, coords.clientY);
                }
                else {
                    range = shadowRoot.caretRangeFromPoint(coords.clientX, coords.clientY);
                }
            }
            else {
                range = ctx.viewDomNode.ownerDocument.caretRangeFromPoint(coords.clientX, coords.clientY);
            }
            if (!range || !range.startContainer) {
                return new UnknownHitTestResult();
            }
            // Chrome always hits a TEXT_NODE, while Edge sometimes hits a token span
            const startContainer = range.startContainer;
            if (startContainer.nodeType === startContainer.TEXT_NODE) {
                // startContainer is expected to be the token text
                const parent1 = startContainer.parentNode; // expected to be the token span
                const parent2 = parent1 ? parent1.parentNode : null; // expected to be the view line container span
                const parent3 = parent2 ? parent2.parentNode : null; // expected to be the view line div
                const parent3ClassName = parent3 && parent3.nodeType === parent3.ELEMENT_NODE ? parent3.className : null;
                if (parent3ClassName === viewLine_1.ViewLine.CLASS_NAME) {
                    return HitTestResult.createFromDOMInfo(ctx, parent1, range.startOffset);
                }
                else {
                    return new UnknownHitTestResult(startContainer.parentNode);
                }
            }
            else if (startContainer.nodeType === startContainer.ELEMENT_NODE) {
                // startContainer is expected to be the token span
                const parent1 = startContainer.parentNode; // expected to be the view line container span
                const parent2 = parent1 ? parent1.parentNode : null; // expected to be the view line div
                const parent2ClassName = parent2 && parent2.nodeType === parent2.ELEMENT_NODE ? parent2.className : null;
                if (parent2ClassName === viewLine_1.ViewLine.CLASS_NAME) {
                    return HitTestResult.createFromDOMInfo(ctx, startContainer, startContainer.textContent.length);
                }
                else {
                    return new UnknownHitTestResult(startContainer);
                }
            }
            return new UnknownHitTestResult();
        }
        /**
         * Most probably Gecko
         */
        static _doHitTestWithCaretPositionFromPoint(ctx, coords) {
            const hitResult = ctx.viewDomNode.ownerDocument.caretPositionFromPoint(coords.clientX, coords.clientY);
            if (hitResult.offsetNode.nodeType === hitResult.offsetNode.TEXT_NODE) {
                // offsetNode is expected to be the token text
                const parent1 = hitResult.offsetNode.parentNode; // expected to be the token span
                const parent2 = parent1 ? parent1.parentNode : null; // expected to be the view line container span
                const parent3 = parent2 ? parent2.parentNode : null; // expected to be the view line div
                const parent3ClassName = parent3 && parent3.nodeType === parent3.ELEMENT_NODE ? parent3.className : null;
                if (parent3ClassName === viewLine_1.ViewLine.CLASS_NAME) {
                    return HitTestResult.createFromDOMInfo(ctx, hitResult.offsetNode.parentNode, hitResult.offset);
                }
                else {
                    return new UnknownHitTestResult(hitResult.offsetNode.parentNode);
                }
            }
            // For inline decorations, Gecko sometimes returns the `<span>` of the line and the offset is the `<span>` with the inline decoration
            // Some other times, it returns the `<span>` with the inline decoration
            if (hitResult.offsetNode.nodeType === hitResult.offsetNode.ELEMENT_NODE) {
                const parent1 = hitResult.offsetNode.parentNode;
                const parent1ClassName = parent1 && parent1.nodeType === parent1.ELEMENT_NODE ? parent1.className : null;
                const parent2 = parent1 ? parent1.parentNode : null;
                const parent2ClassName = parent2 && parent2.nodeType === parent2.ELEMENT_NODE ? parent2.className : null;
                if (parent1ClassName === viewLine_1.ViewLine.CLASS_NAME) {
                    // it returned the `<span>` of the line and the offset is the `<span>` with the inline decoration
                    const tokenSpan = hitResult.offsetNode.childNodes[Math.min(hitResult.offset, hitResult.offsetNode.childNodes.length - 1)];
                    if (tokenSpan) {
                        return HitTestResult.createFromDOMInfo(ctx, tokenSpan, 0);
                    }
                }
                else if (parent2ClassName === viewLine_1.ViewLine.CLASS_NAME) {
                    // it returned the `<span>` with the inline decoration
                    return HitTestResult.createFromDOMInfo(ctx, hitResult.offsetNode, 0);
                }
            }
            return new UnknownHitTestResult(hitResult.offsetNode);
        }
        static _snapToSoftTabBoundary(position, viewModel) {
            const lineContent = viewModel.getLineContent(position.lineNumber);
            const { tabSize } = viewModel.model.getOptions();
            const newPosition = cursorAtomicMoveOperations_1.AtomicTabMoveOperations.atomicPosition(lineContent, position.column - 1, tabSize, 2 /* Direction.Nearest */);
            if (newPosition !== -1) {
                return new position_1.Position(position.lineNumber, newPosition + 1);
            }
            return position;
        }
        static doHitTest(ctx, request) {
            let result = new UnknownHitTestResult();
            if (typeof ctx.viewDomNode.ownerDocument.caretRangeFromPoint === 'function') {
                result = this._doHitTestWithCaretRangeFromPoint(ctx, request);
            }
            else if (ctx.viewDomNode.ownerDocument.caretPositionFromPoint) {
                result = this._doHitTestWithCaretPositionFromPoint(ctx, request.pos.toClientCoordinates(dom.getWindow(ctx.viewDomNode)));
            }
            if (result.type === 1 /* HitTestResultType.Content */) {
                const injectedText = ctx.viewModel.getInjectedTextAt(result.position);
                const normalizedPosition = ctx.viewModel.normalizePosition(result.position, 2 /* PositionAffinity.None */);
                if (injectedText || !normalizedPosition.equals(result.position)) {
                    result = new ContentHitTestResult(normalizedPosition, result.spanNode, injectedText);
                }
            }
            return result;
        }
    }
    exports.MouseTargetFactory = MouseTargetFactory;
    function shadowCaretRangeFromPoint(shadowRoot, x, y) {
        const range = document.createRange();
        // Get the element under the point
        let el = shadowRoot.elementFromPoint(x, y);
        if (el !== null) {
            // Get the last child of the element until its firstChild is a text node
            // This assumes that the pointer is on the right of the line, out of the tokens
            // and that we want to get the offset of the last token of the line
            while (el && el.firstChild && el.firstChild.nodeType !== el.firstChild.TEXT_NODE && el.lastChild && el.lastChild.firstChild) {
                el = el.lastChild;
            }
            // Grab its rect
            const rect = el.getBoundingClientRect();
            // And its font (the computed shorthand font property might be empty, see #3217)
            const elWindow = dom.getWindow(el);
            const fontStyle = elWindow.getComputedStyle(el, null).getPropertyValue('font-style');
            const fontVariant = elWindow.getComputedStyle(el, null).getPropertyValue('font-variant');
            const fontWeight = elWindow.getComputedStyle(el, null).getPropertyValue('font-weight');
            const fontSize = elWindow.getComputedStyle(el, null).getPropertyValue('font-size');
            const lineHeight = elWindow.getComputedStyle(el, null).getPropertyValue('line-height');
            const fontFamily = elWindow.getComputedStyle(el, null).getPropertyValue('font-family');
            const font = `${fontStyle} ${fontVariant} ${fontWeight} ${fontSize}/${lineHeight} ${fontFamily}`;
            // And also its txt content
            const text = el.innerText;
            // Position the pixel cursor at the left of the element
            let pixelCursor = rect.left;
            let offset = 0;
            let step;
            // If the point is on the right of the box put the cursor after the last character
            if (x > rect.left + rect.width) {
                offset = text.length;
            }
            else {
                const charWidthReader = CharWidthReader.getInstance();
                // Goes through all the characters of the innerText, and checks if the x of the point
                // belongs to the character.
                for (let i = 0; i < text.length + 1; i++) {
                    // The step is half the width of the character
                    step = charWidthReader.getCharWidth(text.charAt(i), font) / 2;
                    // Move to the center of the character
                    pixelCursor += step;
                    // If the x of the point is smaller that the position of the cursor, the point is over that character
                    if (x < pixelCursor) {
                        offset = i;
                        break;
                    }
                    // Move between the current character and the next
                    pixelCursor += step;
                }
            }
            // Creates a range with the text node of the element and set the offset found
            range.setStart(el.firstChild, offset);
            range.setEnd(el.firstChild, offset);
        }
        return range;
    }
    class CharWidthReader {
        static { this._INSTANCE = null; }
        static getInstance() {
            if (!CharWidthReader._INSTANCE) {
                CharWidthReader._INSTANCE = new CharWidthReader();
            }
            return CharWidthReader._INSTANCE;
        }
        constructor() {
            this._cache = {};
            this._canvas = document.createElement('canvas');
        }
        getCharWidth(char, font) {
            const cacheKey = char + font;
            if (this._cache[cacheKey]) {
                return this._cache[cacheKey];
            }
            const context = this._canvas.getContext('2d');
            context.font = font;
            const metrics = context.measureText(char);
            const width = metrics.width;
            this._cache[cacheKey] = width;
            return width;
        }
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[768/*vs/editor/browser/controller/mouseHandler*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,77/*vs/base/browser/mouseEvent*/,2/*vs/base/common/lifecycle*/,16/*vs/base/common/platform*/,414/*vs/editor/browser/controller/mouseTarget*/,185/*vs/editor/browser/editorDom*/,165/*vs/editor/common/config/editorZoom*/,9/*vs/editor/common/core/position*/,23/*vs/editor/common/core/selection*/,170/*vs/editor/common/viewEventHandler*/,86/*vs/base/browser/ui/scrollbar/scrollableElement*/]), function (require, exports, dom, mouseEvent_1, lifecycle_1, platform, mouseTarget_1, editorDom_1, editorZoom_1, position_1, selection_1, viewEventHandler_1, scrollableElement_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MouseHandler = void 0;
    class MouseHandler extends viewEventHandler_1.ViewEventHandler {
        constructor(context, viewController, viewHelper) {
            super();
            this._mouseLeaveMonitor = null;
            this._context = context;
            this.viewController = viewController;
            this.viewHelper = viewHelper;
            this.mouseTargetFactory = new mouseTarget_1.MouseTargetFactory(this._context, viewHelper);
            this._mouseDownOperation = this._register(new MouseDownOperation(this._context, this.viewController, this.viewHelper, this.mouseTargetFactory, (e, testEventTarget) => this._createMouseTarget(e, testEventTarget), (e) => this._getMouseColumn(e)));
            this.lastMouseLeaveTime = -1;
            this._height = this._context.configuration.options.get(146 /* EditorOption.layoutInfo */).height;
            const mouseEvents = new editorDom_1.EditorMouseEventFactory(this.viewHelper.viewDomNode);
            this._register(mouseEvents.onContextMenu(this.viewHelper.viewDomNode, (e) => this._onContextMenu(e, true)));
            this._register(mouseEvents.onMouseMove(this.viewHelper.viewDomNode, (e) => {
                this._onMouseMove(e);
                // See https://github.com/microsoft/vscode/issues/138789
                // When moving the mouse really quickly, the browser sometimes forgets to
                // send us a `mouseleave` or `mouseout` event. We therefore install here
                // a global `mousemove` listener to manually recover if the mouse goes outside
                // the editor. As soon as the mouse leaves outside of the editor, we
                // remove this listener
                if (!this._mouseLeaveMonitor) {
                    this._mouseLeaveMonitor = dom.addDisposableListener(this.viewHelper.viewDomNode.ownerDocument, 'mousemove', (e) => {
                        if (!this.viewHelper.viewDomNode.contains(e.target)) {
                            // went outside the editor!
                            this._onMouseLeave(new editorDom_1.EditorMouseEvent(e, false, this.viewHelper.viewDomNode));
                        }
                    });
                }
            }));
            this._register(mouseEvents.onMouseUp(this.viewHelper.viewDomNode, (e) => this._onMouseUp(e)));
            this._register(mouseEvents.onMouseLeave(this.viewHelper.viewDomNode, (e) => this._onMouseLeave(e)));
            // `pointerdown` events can't be used to determine if there's a double click, or triple click
            // because their `e.detail` is always 0.
            // We will therefore save the pointer id for the mouse and then reuse it in the `mousedown` event
            // for `element.setPointerCapture`.
            let capturePointerId = 0;
            this._register(mouseEvents.onPointerDown(this.viewHelper.viewDomNode, (e, pointerId) => {
                capturePointerId = pointerId;
            }));
            // The `pointerup` listener registered by `GlobalEditorPointerMoveMonitor` does not get invoked 100% of the times.
            // I speculate that this is because the `pointerup` listener is only registered during the `mousedown` event, and perhaps
            // the `pointerup` event is already queued for dispatching, which makes it that the new listener doesn't get fired.
            // See https://github.com/microsoft/vscode/issues/146486 for repro steps.
            // To compensate for that, we simply register here a `pointerup` listener and just communicate it.
            this._register(dom.addDisposableListener(this.viewHelper.viewDomNode, dom.EventType.POINTER_UP, (e) => {
                this._mouseDownOperation.onPointerUp();
            }));
            this._register(mouseEvents.onMouseDown(this.viewHelper.viewDomNode, (e) => this._onMouseDown(e, capturePointerId)));
            this._setupMouseWheelZoomListener();
            this._context.addEventHandler(this);
        }
        _setupMouseWheelZoomListener() {
            const classifier = scrollableElement_1.MouseWheelClassifier.INSTANCE;
            let prevMouseWheelTime = 0;
            let gestureStartZoomLevel = editorZoom_1.EditorZoom.getZoomLevel();
            let gestureHasZoomModifiers = false;
            let gestureAccumulatedDelta = 0;
            const onMouseWheel = (browserEvent) => {
                this.viewController.emitMouseWheel(browserEvent);
                if (!this._context.configuration.options.get(76 /* EditorOption.mouseWheelZoom */)) {
                    return;
                }
                const e = new mouseEvent_1.StandardWheelEvent(browserEvent);
                classifier.acceptStandardWheelEvent(e);
                if (classifier.isPhysicalMouseWheel()) {
                    if (hasMouseWheelZoomModifiers(browserEvent)) {
                        const zoomLevel = editorZoom_1.EditorZoom.getZoomLevel();
                        const delta = e.deltaY > 0 ? 1 : -1;
                        editorZoom_1.EditorZoom.setZoomLevel(zoomLevel + delta);
                        e.preventDefault();
                        e.stopPropagation();
                    }
                }
                else {
                    // we consider mousewheel events that occur within 50ms of each other to be part of the same gesture
                    // we don't want to consider mouse wheel events where ctrl/cmd is pressed during the inertia phase
                    // we also want to accumulate deltaY values from the same gesture and use that to set the zoom level
                    if (Date.now() - prevMouseWheelTime > 50) {
                        // reset if more than 50ms have passed
                        gestureStartZoomLevel = editorZoom_1.EditorZoom.getZoomLevel();
                        gestureHasZoomModifiers = hasMouseWheelZoomModifiers(browserEvent);
                        gestureAccumulatedDelta = 0;
                    }
                    prevMouseWheelTime = Date.now();
                    gestureAccumulatedDelta += e.deltaY;
                    if (gestureHasZoomModifiers) {
                        editorZoom_1.EditorZoom.setZoomLevel(gestureStartZoomLevel + gestureAccumulatedDelta / 5);
                        e.preventDefault();
                        e.stopPropagation();
                    }
                }
            };
            this._register(dom.addDisposableListener(this.viewHelper.viewDomNode, dom.EventType.MOUSE_WHEEL, onMouseWheel, { capture: true, passive: false }));
            function hasMouseWheelZoomModifiers(browserEvent) {
                return (platform.isMacintosh
                    // on macOS we support cmd + two fingers scroll (`metaKey` set)
                    // and also the two fingers pinch gesture (`ctrKey` set)
                    ? ((browserEvent.metaKey || browserEvent.ctrlKey) && !browserEvent.shiftKey && !browserEvent.altKey)
                    : (browserEvent.ctrlKey && !browserEvent.metaKey && !browserEvent.shiftKey && !browserEvent.altKey));
            }
        }
        dispose() {
            this._context.removeEventHandler(this);
            if (this._mouseLeaveMonitor) {
                this._mouseLeaveMonitor.dispose();
                this._mouseLeaveMonitor = null;
            }
            super.dispose();
        }
        // --- begin event handlers
        onConfigurationChanged(e) {
            if (e.hasChanged(146 /* EditorOption.layoutInfo */)) {
                // layout change
                const height = this._context.configuration.options.get(146 /* EditorOption.layoutInfo */).height;
                if (this._height !== height) {
                    this._height = height;
                    this._mouseDownOperation.onHeightChanged();
                }
            }
            return false;
        }
        onCursorStateChanged(e) {
            this._mouseDownOperation.onCursorStateChanged(e);
            return false;
        }
        onFocusChanged(e) {
            return false;
        }
        // --- end event handlers
        getTargetAtClientPoint(clientX, clientY) {
            const clientPos = new editorDom_1.ClientCoordinates(clientX, clientY);
            const pos = clientPos.toPageCoordinates(dom.getWindow(this.viewHelper.viewDomNode));
            const editorPos = (0, editorDom_1.createEditorPagePosition)(this.viewHelper.viewDomNode);
            if (pos.y < editorPos.y || pos.y > editorPos.y + editorPos.height || pos.x < editorPos.x || pos.x > editorPos.x + editorPos.width) {
                return null;
            }
            const relativePos = (0, editorDom_1.createCoordinatesRelativeToEditor)(this.viewHelper.viewDomNode, editorPos, pos);
            return this.mouseTargetFactory.createMouseTarget(this.viewHelper.getLastRenderData(), editorPos, pos, relativePos, null);
        }
        _createMouseTarget(e, testEventTarget) {
            let target = e.target;
            if (!this.viewHelper.viewDomNode.contains(target)) {
                const shadowRoot = dom.getShadowRoot(this.viewHelper.viewDomNode);
                if (shadowRoot) {
                    target = shadowRoot.elementsFromPoint(e.posx, e.posy).find((el) => this.viewHelper.viewDomNode.contains(el));
                }
            }
            return this.mouseTargetFactory.createMouseTarget(this.viewHelper.getLastRenderData(), e.editorPos, e.pos, e.relativePos, testEventTarget ? target : null);
        }
        _getMouseColumn(e) {
            return this.mouseTargetFactory.getMouseColumn(e.relativePos);
        }
        _onContextMenu(e, testEventTarget) {
            this.viewController.emitContextMenu({
                event: e,
                target: this._createMouseTarget(e, testEventTarget)
            });
        }
        _onMouseMove(e) {
            const targetIsWidget = this.mouseTargetFactory.mouseTargetIsWidget(e);
            if (!targetIsWidget) {
                e.preventDefault();
            }
            if (this._mouseDownOperation.isActive()) {
                // In selection/drag operation
                return;
            }
            const actualMouseMoveTime = e.timestamp;
            if (actualMouseMoveTime < this.lastMouseLeaveTime) {
                // Due to throttling, this event occurred before the mouse left the editor, therefore ignore it.
                return;
            }
            this.viewController.emitMouseMove({
                event: e,
                target: this._createMouseTarget(e, true)
            });
        }
        _onMouseLeave(e) {
            if (this._mouseLeaveMonitor) {
                this._mouseLeaveMonitor.dispose();
                this._mouseLeaveMonitor = null;
            }
            this.lastMouseLeaveTime = (new Date()).getTime();
            this.viewController.emitMouseLeave({
                event: e,
                target: null
            });
        }
        _onMouseUp(e) {
            this.viewController.emitMouseUp({
                event: e,
                target: this._createMouseTarget(e, true)
            });
        }
        _onMouseDown(e, pointerId) {
            const t = this._createMouseTarget(e, true);
            const targetIsContent = (t.type === 6 /* MouseTargetType.CONTENT_TEXT */ || t.type === 7 /* MouseTargetType.CONTENT_EMPTY */);
            const targetIsGutter = (t.type === 2 /* MouseTargetType.GUTTER_GLYPH_MARGIN */ || t.type === 3 /* MouseTargetType.GUTTER_LINE_NUMBERS */ || t.type === 4 /* MouseTargetType.GUTTER_LINE_DECORATIONS */);
            const targetIsLineNumbers = (t.type === 3 /* MouseTargetType.GUTTER_LINE_NUMBERS */);
            const selectOnLineNumbers = this._context.configuration.options.get(110 /* EditorOption.selectOnLineNumbers */);
            const targetIsViewZone = (t.type === 8 /* MouseTargetType.CONTENT_VIEW_ZONE */ || t.type === 5 /* MouseTargetType.GUTTER_VIEW_ZONE */);
            const targetIsWidget = (t.type === 9 /* MouseTargetType.CONTENT_WIDGET */);
            let shouldHandle = e.leftButton || e.middleButton;
            if (platform.isMacintosh && e.leftButton && e.ctrlKey) {
                shouldHandle = false;
            }
            const focus = () => {
                e.preventDefault();
                this.viewHelper.focusTextArea();
            };
            if (shouldHandle && (targetIsContent || (targetIsLineNumbers && selectOnLineNumbers))) {
                focus();
                this._mouseDownOperation.start(t.type, e, pointerId);
            }
            else if (targetIsGutter) {
                // Do not steal focus
                e.preventDefault();
            }
            else if (targetIsViewZone) {
                const viewZoneData = t.detail;
                if (shouldHandle && this.viewHelper.shouldSuppressMouseDownOnViewZone(viewZoneData.viewZoneId)) {
                    focus();
                    this._mouseDownOperation.start(t.type, e, pointerId);
                    e.preventDefault();
                }
            }
            else if (targetIsWidget && this.viewHelper.shouldSuppressMouseDownOnWidget(t.detail)) {
                focus();
                e.preventDefault();
            }
            this.viewController.emitMouseDown({
                event: e,
                target: t
            });
        }
    }
    exports.MouseHandler = MouseHandler;
    class MouseDownOperation extends lifecycle_1.Disposable {
        constructor(_context, _viewController, _viewHelper, _mouseTargetFactory, createMouseTarget, getMouseColumn) {
            super();
            this._context = _context;
            this._viewController = _viewController;
            this._viewHelper = _viewHelper;
            this._mouseTargetFactory = _mouseTargetFactory;
            this._createMouseTarget = createMouseTarget;
            this._getMouseColumn = getMouseColumn;
            this._mouseMoveMonitor = this._register(new editorDom_1.GlobalEditorPointerMoveMonitor(this._viewHelper.viewDomNode));
            this._topBottomDragScrolling = this._register(new TopBottomDragScrolling(this._context, this._viewHelper, this._mouseTargetFactory, (position, inSelectionMode, revealType) => this._dispatchMouse(position, inSelectionMode, revealType)));
            this._mouseState = new MouseDownState();
            this._currentSelection = new selection_1.Selection(1, 1, 1, 1);
            this._isActive = false;
            this._lastMouseEvent = null;
        }
        dispose() {
            super.dispose();
        }
        isActive() {
            return this._isActive;
        }
        _onMouseDownThenMove(e) {
            this._lastMouseEvent = e;
            this._mouseState.setModifiers(e);
            const position = this._findMousePosition(e, false);
            if (!position) {
                // Ignoring because position is unknown
                return;
            }
            if (this._mouseState.isDragAndDrop) {
                this._viewController.emitMouseDrag({
                    event: e,
                    target: position
                });
            }
            else {
                if (position.type === 13 /* MouseTargetType.OUTSIDE_EDITOR */ && (position.outsidePosition === 'above' || position.outsidePosition === 'below')) {
                    this._topBottomDragScrolling.start(position, e);
                }
                else {
                    this._topBottomDragScrolling.stop();
                    this._dispatchMouse(position, true, 1 /* NavigationCommandRevealType.Minimal */);
                }
            }
        }
        start(targetType, e, pointerId) {
            this._lastMouseEvent = e;
            this._mouseState.setStartedOnLineNumbers(targetType === 3 /* MouseTargetType.GUTTER_LINE_NUMBERS */);
            this._mouseState.setStartButtons(e);
            this._mouseState.setModifiers(e);
            const position = this._findMousePosition(e, true);
            if (!position || !position.position) {
                // Ignoring because position is unknown
                return;
            }
            this._mouseState.trySetCount(e.detail, position.position);
            // Overwrite the detail of the MouseEvent, as it will be sent out in an event and contributions might rely on it.
            e.detail = this._mouseState.count;
            const options = this._context.configuration.options;
            if (!options.get(92 /* EditorOption.readOnly */)
                && options.get(35 /* EditorOption.dragAndDrop */)
                && !options.get(22 /* EditorOption.columnSelection */)
                && !this._mouseState.altKey // we don't support multiple mouse
                && e.detail < 2 // only single click on a selection can work
                && !this._isActive // the mouse is not down yet
                && !this._currentSelection.isEmpty() // we don't drag single cursor
                && (position.type === 6 /* MouseTargetType.CONTENT_TEXT */) // single click on text
                && position.position && this._currentSelection.containsPosition(position.position) // single click on a selection
            ) {
                this._mouseState.isDragAndDrop = true;
                this._isActive = true;
                this._mouseMoveMonitor.startMonitoring(this._viewHelper.viewLinesDomNode, pointerId, e.buttons, (e) => this._onMouseDownThenMove(e), (browserEvent) => {
                    const position = this._findMousePosition(this._lastMouseEvent, false);
                    if (dom.isKeyboardEvent(browserEvent)) {
                        // cancel
                        this._viewController.emitMouseDropCanceled();
                    }
                    else {
                        this._viewController.emitMouseDrop({
                            event: this._lastMouseEvent,
                            target: (position ? this._createMouseTarget(this._lastMouseEvent, true) : null) // Ignoring because position is unknown, e.g., Content View Zone
                        });
                    }
                    this._stop();
                });
                return;
            }
            this._mouseState.isDragAndDrop = false;
            this._dispatchMouse(position, e.shiftKey, 1 /* NavigationCommandRevealType.Minimal */);
            if (!this._isActive) {
                this._isActive = true;
                this._mouseMoveMonitor.startMonitoring(this._viewHelper.viewLinesDomNode, pointerId, e.buttons, (e) => this._onMouseDownThenMove(e), () => this._stop());
            }
        }
        _stop() {
            this._isActive = false;
            this._topBottomDragScrolling.stop();
        }
        onHeightChanged() {
            this._mouseMoveMonitor.stopMonitoring();
        }
        onPointerUp() {
            this._mouseMoveMonitor.stopMonitoring();
        }
        onCursorStateChanged(e) {
            this._currentSelection = e.selections[0];
        }
        _getPositionOutsideEditor(e) {
            const editorContent = e.editorPos;
            const model = this._context.viewModel;
            const viewLayout = this._context.viewLayout;
            const mouseColumn = this._getMouseColumn(e);
            if (e.posy < editorContent.y) {
                const outsideDistance = editorContent.y - e.posy;
                const verticalOffset = Math.max(viewLayout.getCurrentScrollTop() - outsideDistance, 0);
                const viewZoneData = mouseTarget_1.HitTestContext.getZoneAtCoord(this._context, verticalOffset);
                if (viewZoneData) {
                    const newPosition = this._helpPositionJumpOverViewZone(viewZoneData);
                    if (newPosition) {
                        return mouseTarget_1.MouseTarget.createOutsideEditor(mouseColumn, newPosition, 'above', outsideDistance);
                    }
                }
                const aboveLineNumber = viewLayout.getLineNumberAtVerticalOffset(verticalOffset);
                return mouseTarget_1.MouseTarget.createOutsideEditor(mouseColumn, new position_1.Position(aboveLineNumber, 1), 'above', outsideDistance);
            }
            if (e.posy > editorContent.y + editorContent.height) {
                const outsideDistance = e.posy - editorContent.y - editorContent.height;
                const verticalOffset = viewLayout.getCurrentScrollTop() + e.relativePos.y;
                const viewZoneData = mouseTarget_1.HitTestContext.getZoneAtCoord(this._context, verticalOffset);
                if (viewZoneData) {
                    const newPosition = this._helpPositionJumpOverViewZone(viewZoneData);
                    if (newPosition) {
                        return mouseTarget_1.MouseTarget.createOutsideEditor(mouseColumn, newPosition, 'below', outsideDistance);
                    }
                }
                const belowLineNumber = viewLayout.getLineNumberAtVerticalOffset(verticalOffset);
                return mouseTarget_1.MouseTarget.createOutsideEditor(mouseColumn, new position_1.Position(belowLineNumber, model.getLineMaxColumn(belowLineNumber)), 'below', outsideDistance);
            }
            const possibleLineNumber = viewLayout.getLineNumberAtVerticalOffset(viewLayout.getCurrentScrollTop() + e.relativePos.y);
            if (e.posx < editorContent.x) {
                const outsideDistance = editorContent.x - e.posx;
                return mouseTarget_1.MouseTarget.createOutsideEditor(mouseColumn, new position_1.Position(possibleLineNumber, 1), 'left', outsideDistance);
            }
            if (e.posx > editorContent.x + editorContent.width) {
                const outsideDistance = e.posx - editorContent.x - editorContent.width;
                return mouseTarget_1.MouseTarget.createOutsideEditor(mouseColumn, new position_1.Position(possibleLineNumber, model.getLineMaxColumn(possibleLineNumber)), 'right', outsideDistance);
            }
            return null;
        }
        _findMousePosition(e, testEventTarget) {
            const positionOutsideEditor = this._getPositionOutsideEditor(e);
            if (positionOutsideEditor) {
                return positionOutsideEditor;
            }
            const t = this._createMouseTarget(e, testEventTarget);
            const hintedPosition = t.position;
            if (!hintedPosition) {
                return null;
            }
            if (t.type === 8 /* MouseTargetType.CONTENT_VIEW_ZONE */ || t.type === 5 /* MouseTargetType.GUTTER_VIEW_ZONE */) {
                const newPosition = this._helpPositionJumpOverViewZone(t.detail);
                if (newPosition) {
                    return mouseTarget_1.MouseTarget.createViewZone(t.type, t.element, t.mouseColumn, newPosition, t.detail);
                }
            }
            return t;
        }
        _helpPositionJumpOverViewZone(viewZoneData) {
            // Force position on view zones to go above or below depending on where selection started from
            const selectionStart = new position_1.Position(this._currentSelection.selectionStartLineNumber, this._currentSelection.selectionStartColumn);
            const positionBefore = viewZoneData.positionBefore;
            const positionAfter = viewZoneData.positionAfter;
            if (positionBefore && positionAfter) {
                if (positionBefore.isBefore(selectionStart)) {
                    return positionBefore;
                }
                else {
                    return positionAfter;
                }
            }
            return null;
        }
        _dispatchMouse(position, inSelectionMode, revealType) {
            if (!position.position) {
                return;
            }
            this._viewController.dispatchMouse({
                position: position.position,
                mouseColumn: position.mouseColumn,
                startedOnLineNumbers: this._mouseState.startedOnLineNumbers,
                revealType,
                inSelectionMode: inSelectionMode,
                mouseDownCount: this._mouseState.count,
                altKey: this._mouseState.altKey,
                ctrlKey: this._mouseState.ctrlKey,
                metaKey: this._mouseState.metaKey,
                shiftKey: this._mouseState.shiftKey,
                leftButton: this._mouseState.leftButton,
                middleButton: this._mouseState.middleButton,
                onInjectedText: position.type === 6 /* MouseTargetType.CONTENT_TEXT */ && position.detail.injectedText !== null
            });
        }
    }
    class TopBottomDragScrolling extends lifecycle_1.Disposable {
        constructor(_context, _viewHelper, _mouseTargetFactory, _dispatchMouse) {
            super();
            this._context = _context;
            this._viewHelper = _viewHelper;
            this._mouseTargetFactory = _mouseTargetFactory;
            this._dispatchMouse = _dispatchMouse;
            this._operation = null;
        }
        dispose() {
            super.dispose();
            this.stop();
        }
        start(position, mouseEvent) {
            if (this._operation) {
                this._operation.setPosition(position, mouseEvent);
            }
            else {
                this._operation = new TopBottomDragScrollingOperation(this._context, this._viewHelper, this._mouseTargetFactory, this._dispatchMouse, position, mouseEvent);
            }
        }
        stop() {
            if (this._operation) {
                this._operation.dispose();
                this._operation = null;
            }
        }
    }
    class TopBottomDragScrollingOperation extends lifecycle_1.Disposable {
        constructor(_context, _viewHelper, _mouseTargetFactory, _dispatchMouse, position, mouseEvent) {
            super();
            this._context = _context;
            this._viewHelper = _viewHelper;
            this._mouseTargetFactory = _mouseTargetFactory;
            this._dispatchMouse = _dispatchMouse;
            this._position = position;
            this._mouseEvent = mouseEvent;
            this._lastTime = Date.now();
            this._animationFrameDisposable = dom.scheduleAtNextAnimationFrame(dom.getWindow(mouseEvent.browserEvent), () => this._execute());
        }
        dispose() {
            this._animationFrameDisposable.dispose();
            super.dispose();
        }
        setPosition(position, mouseEvent) {
            this._position = position;
            this._mouseEvent = mouseEvent;
        }
        /**
         * update internal state and return elapsed ms since last time
         */
        _tick() {
            const now = Date.now();
            const elapsed = now - this._lastTime;
            this._lastTime = now;
            return elapsed;
        }
        /**
         * get the number of lines per second to auto-scroll
         */
        _getScrollSpeed() {
            const lineHeight = this._context.configuration.options.get(67 /* EditorOption.lineHeight */);
            const viewportInLines = this._context.configuration.options.get(146 /* EditorOption.layoutInfo */).height / lineHeight;
            const outsideDistanceInLines = this._position.outsideDistance / lineHeight;
            if (outsideDistanceInLines <= 1.5) {
                return Math.max(30, viewportInLines * (1 + outsideDistanceInLines));
            }
            if (outsideDistanceInLines <= 3) {
                return Math.max(60, viewportInLines * (2 + outsideDistanceInLines));
            }
            return Math.max(200, viewportInLines * (7 + outsideDistanceInLines));
        }
        _execute() {
            const lineHeight = this._context.configuration.options.get(67 /* EditorOption.lineHeight */);
            const scrollSpeedInLines = this._getScrollSpeed();
            const elapsed = this._tick();
            const scrollInPixels = scrollSpeedInLines * (elapsed / 1000) * lineHeight;
            const scrollValue = (this._position.outsidePosition === 'above' ? -scrollInPixels : scrollInPixels);
            this._context.viewModel.viewLayout.deltaScrollNow(0, scrollValue);
            this._viewHelper.renderNow();
            const viewportData = this._context.viewLayout.getLinesViewportData();
            const edgeLineNumber = (this._position.outsidePosition === 'above' ? viewportData.startLineNumber : viewportData.endLineNumber);
            // First, try to find a position that matches the horizontal position of the mouse
            let mouseTarget;
            {
                const editorPos = (0, editorDom_1.createEditorPagePosition)(this._viewHelper.viewDomNode);
                const horizontalScrollbarHeight = this._context.configuration.options.get(146 /* EditorOption.layoutInfo */).horizontalScrollbarHeight;
                const pos = new editorDom_1.PageCoordinates(this._mouseEvent.pos.x, editorPos.y + editorPos.height - horizontalScrollbarHeight - 0.1);
                const relativePos = (0, editorDom_1.createCoordinatesRelativeToEditor)(this._viewHelper.viewDomNode, editorPos, pos);
                mouseTarget = this._mouseTargetFactory.createMouseTarget(this._viewHelper.getLastRenderData(), editorPos, pos, relativePos, null);
            }
            if (!mouseTarget.position || mouseTarget.position.lineNumber !== edgeLineNumber) {
                if (this._position.outsidePosition === 'above') {
                    mouseTarget = mouseTarget_1.MouseTarget.createOutsideEditor(this._position.mouseColumn, new position_1.Position(edgeLineNumber, 1), 'above', this._position.outsideDistance);
                }
                else {
                    mouseTarget = mouseTarget_1.MouseTarget.createOutsideEditor(this._position.mouseColumn, new position_1.Position(edgeLineNumber, this._context.viewModel.getLineMaxColumn(edgeLineNumber)), 'below', this._position.outsideDistance);
                }
            }
            this._dispatchMouse(mouseTarget, true, 2 /* NavigationCommandRevealType.None */);
            this._animationFrameDisposable = dom.scheduleAtNextAnimationFrame(dom.getWindow(mouseTarget.element), () => this._execute());
        }
    }
    class MouseDownState {
        static { this.CLEAR_MOUSE_DOWN_COUNT_TIME = 400; } // ms
        get altKey() { return this._altKey; }
        get ctrlKey() { return this._ctrlKey; }
        get metaKey() { return this._metaKey; }
        get shiftKey() { return this._shiftKey; }
        get leftButton() { return this._leftButton; }
        get middleButton() { return this._middleButton; }
        get startedOnLineNumbers() { return this._startedOnLineNumbers; }
        constructor() {
            this._altKey = false;
            this._ctrlKey = false;
            this._metaKey = false;
            this._shiftKey = false;
            this._leftButton = false;
            this._middleButton = false;
            this._startedOnLineNumbers = false;
            this._lastMouseDownPosition = null;
            this._lastMouseDownPositionEqualCount = 0;
            this._lastMouseDownCount = 0;
            this._lastSetMouseDownCountTime = 0;
            this.isDragAndDrop = false;
        }
        get count() {
            return this._lastMouseDownCount;
        }
        setModifiers(source) {
            this._altKey = source.altKey;
            this._ctrlKey = source.ctrlKey;
            this._metaKey = source.metaKey;
            this._shiftKey = source.shiftKey;
        }
        setStartButtons(source) {
            this._leftButton = source.leftButton;
            this._middleButton = source.middleButton;
        }
        setStartedOnLineNumbers(startedOnLineNumbers) {
            this._startedOnLineNumbers = startedOnLineNumbers;
        }
        trySetCount(setMouseDownCount, newMouseDownPosition) {
            // a. Invalidate multiple clicking if too much time has passed (will be hit by IE because the detail field of mouse events contains garbage in IE10)
            const currentTime = (new Date()).getTime();
            if (currentTime - this._lastSetMouseDownCountTime > MouseDownState.CLEAR_MOUSE_DOWN_COUNT_TIME) {
                setMouseDownCount = 1;
            }
            this._lastSetMouseDownCountTime = currentTime;
            // b. Ensure that we don't jump from single click to triple click in one go (will be hit by IE because the detail field of mouse events contains garbage in IE10)
            if (setMouseDownCount > this._lastMouseDownCount + 1) {
                setMouseDownCount = this._lastMouseDownCount + 1;
            }
            // c. Invalidate multiple clicking if the logical position is different
            if (this._lastMouseDownPosition && this._lastMouseDownPosition.equals(newMouseDownPosition)) {
                this._lastMouseDownPositionEqualCount++;
            }
            else {
                this._lastMouseDownPositionEqualCount = 1;
            }
            this._lastMouseDownPosition = newMouseDownPosition;
            // Finally set the lastMouseDownCount
            this._lastMouseDownCount = Math.min(setMouseDownCount, this._lastMouseDownPositionEqualCount);
        }
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[769/*vs/editor/browser/controller/pointerHandler*/], __M([1/*require*/,0/*exports*/,248/*vs/base/browser/canIUse*/,5/*vs/base/browser/dom*/,69/*vs/base/browser/touch*/,52/*vs/base/browser/window*/,2/*vs/base/common/lifecycle*/,16/*vs/base/common/platform*/,768/*vs/editor/browser/controller/mouseHandler*/,212/*vs/editor/browser/controller/textAreaInput*/,185/*vs/editor/browser/editorDom*/]), function (require, exports, canIUse_1, dom, touch_1, window_1, lifecycle_1, platform, mouseHandler_1, textAreaInput_1, editorDom_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.PointerHandler = exports.PointerEventHandler = void 0;
    /**
     * Currently only tested on iOS 13/ iPadOS.
     */
    class PointerEventHandler extends mouseHandler_1.MouseHandler {
        constructor(context, viewController, viewHelper) {
            super(context, viewController, viewHelper);
            this._register(touch_1.Gesture.addTarget(this.viewHelper.linesContentDomNode));
            this._register(dom.addDisposableListener(this.viewHelper.linesContentDomNode, touch_1.EventType.Tap, (e) => this.onTap(e)));
            this._register(dom.addDisposableListener(this.viewHelper.linesContentDomNode, touch_1.EventType.Change, (e) => this.onChange(e)));
            this._register(dom.addDisposableListener(this.viewHelper.linesContentDomNode, touch_1.EventType.Contextmenu, (e) => this._onContextMenu(new editorDom_1.EditorMouseEvent(e, false, this.viewHelper.viewDomNode), false)));
            this._lastPointerType = 'mouse';
            this._register(dom.addDisposableListener(this.viewHelper.linesContentDomNode, 'pointerdown', (e) => {
                const pointerType = e.pointerType;
                if (pointerType === 'mouse') {
                    this._lastPointerType = 'mouse';
                    return;
                }
                else if (pointerType === 'touch') {
                    this._lastPointerType = 'touch';
                }
                else {
                    this._lastPointerType = 'pen';
                }
            }));
            // PonterEvents
            const pointerEvents = new editorDom_1.EditorPointerEventFactory(this.viewHelper.viewDomNode);
            this._register(pointerEvents.onPointerMove(this.viewHelper.viewDomNode, (e) => this._onMouseMove(e)));
            this._register(pointerEvents.onPointerUp(this.viewHelper.viewDomNode, (e) => this._onMouseUp(e)));
            this._register(pointerEvents.onPointerLeave(this.viewHelper.viewDomNode, (e) => this._onMouseLeave(e)));
            this._register(pointerEvents.onPointerDown(this.viewHelper.viewDomNode, (e, pointerId) => this._onMouseDown(e, pointerId)));
        }
        onTap(event) {
            if (!event.initialTarget || !this.viewHelper.linesContentDomNode.contains(event.initialTarget)) {
                return;
            }
            event.preventDefault();
            this.viewHelper.focusTextArea();
            this._dispatchGesture(event, /*inSelectionMode*/ false);
        }
        onChange(event) {
            if (this._lastPointerType === 'touch') {
                this._context.viewModel.viewLayout.deltaScrollNow(-event.translationX, -event.translationY);
            }
            if (this._lastPointerType === 'pen') {
                this._dispatchGesture(event, /*inSelectionMode*/ true);
            }
        }
        _dispatchGesture(event, inSelectionMode) {
            const target = this._createMouseTarget(new editorDom_1.EditorMouseEvent(event, false, this.viewHelper.viewDomNode), false);
            if (target.position) {
                this.viewController.dispatchMouse({
                    position: target.position,
                    mouseColumn: target.position.column,
                    startedOnLineNumbers: false,
                    revealType: 1 /* NavigationCommandRevealType.Minimal */,
                    mouseDownCount: event.tapCount,
                    inSelectionMode,
                    altKey: false,
                    ctrlKey: false,
                    metaKey: false,
                    shiftKey: false,
                    leftButton: false,
                    middleButton: false,
                    onInjectedText: target.type === 6 /* MouseTargetType.CONTENT_TEXT */ && target.detail.injectedText !== null
                });
            }
        }
        _onMouseDown(e, pointerId) {
            if (e.browserEvent.pointerType === 'touch') {
                return;
            }
            super._onMouseDown(e, pointerId);
        }
    }
    exports.PointerEventHandler = PointerEventHandler;
    class TouchHandler extends mouseHandler_1.MouseHandler {
        constructor(context, viewController, viewHelper) {
            super(context, viewController, viewHelper);
            this._register(touch_1.Gesture.addTarget(this.viewHelper.linesContentDomNode));
            this._register(dom.addDisposableListener(this.viewHelper.linesContentDomNode, touch_1.EventType.Tap, (e) => this.onTap(e)));
            this._register(dom.addDisposableListener(this.viewHelper.linesContentDomNode, touch_1.EventType.Change, (e) => this.onChange(e)));
            this._register(dom.addDisposableListener(this.viewHelper.linesContentDomNode, touch_1.EventType.Contextmenu, (e) => this._onContextMenu(new editorDom_1.EditorMouseEvent(e, false, this.viewHelper.viewDomNode), false)));
        }
        onTap(event) {
            event.preventDefault();
            this.viewHelper.focusTextArea();
            const target = this._createMouseTarget(new editorDom_1.EditorMouseEvent(event, false, this.viewHelper.viewDomNode), false);
            if (target.position) {
                // Send the tap event also to the <textarea> (for input purposes)
                const event = document.createEvent('CustomEvent');
                event.initEvent(textAreaInput_1.TextAreaSyntethicEvents.Tap, false, true);
                this.viewHelper.dispatchTextAreaEvent(event);
                this.viewController.moveTo(target.position, 1 /* NavigationCommandRevealType.Minimal */);
            }
        }
        onChange(e) {
            this._context.viewModel.viewLayout.deltaScrollNow(-e.translationX, -e.translationY);
        }
    }
    class PointerHandler extends lifecycle_1.Disposable {
        constructor(context, viewController, viewHelper) {
            super();
            const isPhone = platform.isIOS || (platform.isAndroid && platform.isMobile);
            if (isPhone && canIUse_1.BrowserFeatures.pointerEvents) {
                this.handler = this._register(new PointerEventHandler(context, viewController, viewHelper));
            }
            else if (window_1.mainWindow.TouchEvent) {
                this.handler = this._register(new TouchHandler(context, viewController, viewHelper));
            }
            else {
                this.handler = this._register(new mouseHandler_1.MouseHandler(context, viewController, viewHelper));
            }
        }
        getTargetAtClientPoint(clientX, clientY) {
            return this.handler.getTargetAtClientPoint(clientX, clientY);
        }
    }
    exports.PointerHandler = PointerHandler;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[770/*vs/editor/browser/viewParts/lines/viewLines*/], __M([1/*require*/,0/*exports*/,226/*vs/base/browser/ui/mouseCursor/mouseCursor*/,14/*vs/base/common/async*/,16/*vs/base/common/platform*/,74/*vs/editor/browser/config/domFontInfo*/,164/*vs/editor/browser/view/renderingContext*/,262/*vs/editor/browser/view/viewLayer*/,56/*vs/editor/browser/view/viewPart*/,547/*vs/editor/browser/viewParts/lines/domReadingContext*/,281/*vs/editor/browser/viewParts/lines/viewLine*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/,487/*vs/css!vs/editor/browser/viewParts/lines/viewLines*/]), function (require, exports, mouseCursor_1, async_1, platform, domFontInfo_1, renderingContext_1, viewLayer_1, viewPart_1, domReadingContext_1, viewLine_1, position_1, range_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ViewLines = void 0;
    class LastRenderedData {
        constructor() {
            this._currentVisibleRange = new range_1.Range(1, 1, 1, 1);
        }
        getCurrentVisibleRange() {
            return this._currentVisibleRange;
        }
        setCurrentVisibleRange(currentVisibleRange) {
            this._currentVisibleRange = currentVisibleRange;
        }
    }
    class HorizontalRevealRangeRequest {
        constructor(minimalReveal, lineNumber, startColumn, endColumn, startScrollTop, stopScrollTop, scrollType) {
            this.minimalReveal = minimalReveal;
            this.lineNumber = lineNumber;
            this.startColumn = startColumn;
            this.endColumn = endColumn;
            this.startScrollTop = startScrollTop;
            this.stopScrollTop = stopScrollTop;
            this.scrollType = scrollType;
            this.type = 'range';
            this.minLineNumber = lineNumber;
            this.maxLineNumber = lineNumber;
        }
    }
    class HorizontalRevealSelectionsRequest {
        constructor(minimalReveal, selections, startScrollTop, stopScrollTop, scrollType) {
            this.minimalReveal = minimalReveal;
            this.selections = selections;
            this.startScrollTop = startScrollTop;
            this.stopScrollTop = stopScrollTop;
            this.scrollType = scrollType;
            this.type = 'selections';
            let minLineNumber = selections[0].startLineNumber;
            let maxLineNumber = selections[0].endLineNumber;
            for (let i = 1, len = selections.length; i < len; i++) {
                const selection = selections[i];
                minLineNumber = Math.min(minLineNumber, selection.startLineNumber);
                maxLineNumber = Math.max(maxLineNumber, selection.endLineNumber);
            }
            this.minLineNumber = minLineNumber;
            this.maxLineNumber = maxLineNumber;
        }
    }
    class ViewLines extends viewPart_1.ViewPart {
        /**
         * Adds this amount of pixels to the right of lines (no-one wants to type near the edge of the viewport)
         */
        static { this.HORIZONTAL_EXTRA_PX = 30; }
        constructor(context, linesContent) {
            super(context);
            const conf = this._context.configuration;
            const options = this._context.configuration.options;
            const fontInfo = options.get(50 /* EditorOption.fontInfo */);
            const wrappingInfo = options.get(147 /* EditorOption.wrappingInfo */);
            this._lineHeight = options.get(67 /* EditorOption.lineHeight */);
            this._typicalHalfwidthCharacterWidth = fontInfo.typicalHalfwidthCharacterWidth;
            this._isViewportWrapping = wrappingInfo.isViewportWrapping;
            this._revealHorizontalRightPadding = options.get(101 /* EditorOption.revealHorizontalRightPadding */);
            this._cursorSurroundingLines = options.get(29 /* EditorOption.cursorSurroundingLines */);
            this._cursorSurroundingLinesStyle = options.get(30 /* EditorOption.cursorSurroundingLinesStyle */);
            this._canUseLayerHinting = !options.get(32 /* EditorOption.disableLayerHinting */);
            this._viewLineOptions = new viewLine_1.ViewLineOptions(conf, this._context.theme.type);
            this._linesContent = linesContent;
            this._textRangeRestingSpot = document.createElement('div');
            this._visibleLines = new viewLayer_1.VisibleLinesCollection({
                createLine: () => new viewLine_1.ViewLine(this._viewLineOptions),
            });
            this.domNode = this._visibleLines.domNode;
            viewPart_1.PartFingerprints.write(this.domNode, 8 /* PartFingerprint.ViewLines */);
            this.domNode.setClassName(`view-lines ${mouseCursor_1.MOUSE_CURSOR_TEXT_CSS_CLASS_NAME}`);
            (0, domFontInfo_1.applyFontInfo)(this.domNode, fontInfo);
            // --- width & height
            this._maxLineWidth = 0;
            this._asyncUpdateLineWidths = new async_1.RunOnceScheduler(() => {
                this._updateLineWidthsSlow();
            }, 200);
            this._asyncCheckMonospaceFontAssumptions = new async_1.RunOnceScheduler(() => {
                this._checkMonospaceFontAssumptions();
            }, 2000);
            this._lastRenderedData = new LastRenderedData();
            this._horizontalRevealRequest = null;
            // sticky scroll widget
            this._stickyScrollEnabled = options.get(116 /* EditorOption.stickyScroll */).enabled;
            this._maxNumberStickyLines = options.get(116 /* EditorOption.stickyScroll */).maxLineCount;
        }
        dispose() {
            this._asyncUpdateLineWidths.dispose();
            this._asyncCheckMonospaceFontAssumptions.dispose();
            super.dispose();
        }
        getDomNode() {
            return this.domNode;
        }
        // ---- begin view event handlers
        onConfigurationChanged(e) {
            this._visibleLines.onConfigurationChanged(e);
            if (e.hasChanged(147 /* EditorOption.wrappingInfo */)) {
                this._maxLineWidth = 0;
            }
            const options = this._context.configuration.options;
            const fontInfo = options.get(50 /* EditorOption.fontInfo */);
            const wrappingInfo = options.get(147 /* EditorOption.wrappingInfo */);
            this._lineHeight = options.get(67 /* EditorOption.lineHeight */);
            this._typicalHalfwidthCharacterWidth = fontInfo.typicalHalfwidthCharacterWidth;
            this._isViewportWrapping = wrappingInfo.isViewportWrapping;
            this._revealHorizontalRightPadding = options.get(101 /* EditorOption.revealHorizontalRightPadding */);
            this._cursorSurroundingLines = options.get(29 /* EditorOption.cursorSurroundingLines */);
            this._cursorSurroundingLinesStyle = options.get(30 /* EditorOption.cursorSurroundingLinesStyle */);
            this._canUseLayerHinting = !options.get(32 /* EditorOption.disableLayerHinting */);
            // sticky scroll
            this._stickyScrollEnabled = options.get(116 /* EditorOption.stickyScroll */).enabled;
            this._maxNumberStickyLines = options.get(116 /* EditorOption.stickyScroll */).maxLineCount;
            (0, domFontInfo_1.applyFontInfo)(this.domNode, fontInfo);
            this._onOptionsMaybeChanged();
            if (e.hasChanged(146 /* EditorOption.layoutInfo */)) {
                this._maxLineWidth = 0;
            }
            return true;
        }
        _onOptionsMaybeChanged() {
            const conf = this._context.configuration;
            const newViewLineOptions = new viewLine_1.ViewLineOptions(conf, this._context.theme.type);
            if (!this._viewLineOptions.equals(newViewLineOptions)) {
                this._viewLineOptions = newViewLineOptions;
                const startLineNumber = this._visibleLines.getStartLineNumber();
                const endLineNumber = this._visibleLines.getEndLineNumber();
                for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
                    const line = this._visibleLines.getVisibleLine(lineNumber);
                    line.onOptionsChanged(this._viewLineOptions);
                }
                return true;
            }
            return false;
        }
        onCursorStateChanged(e) {
            const rendStartLineNumber = this._visibleLines.getStartLineNumber();
            const rendEndLineNumber = this._visibleLines.getEndLineNumber();
            let r = false;
            for (let lineNumber = rendStartLineNumber; lineNumber <= rendEndLineNumber; lineNumber++) {
                r = this._visibleLines.getVisibleLine(lineNumber).onSelectionChanged() || r;
            }
            return r;
        }
        onDecorationsChanged(e) {
            if (true /*e.inlineDecorationsChanged*/) {
                const rendStartLineNumber = this._visibleLines.getStartLineNumber();
                const rendEndLineNumber = this._visibleLines.getEndLineNumber();
                for (let lineNumber = rendStartLineNumber; lineNumber <= rendEndLineNumber; lineNumber++) {
                    this._visibleLines.getVisibleLine(lineNumber).onDecorationsChanged();
                }
            }
            return true;
        }
        onFlushed(e) {
            const shouldRender = this._visibleLines.onFlushed(e);
            this._maxLineWidth = 0;
            return shouldRender;
        }
        onLinesChanged(e) {
            return this._visibleLines.onLinesChanged(e);
        }
        onLinesDeleted(e) {
            return this._visibleLines.onLinesDeleted(e);
        }
        onLinesInserted(e) {
            return this._visibleLines.onLinesInserted(e);
        }
        onRevealRangeRequest(e) {
            // Using the future viewport here in order to handle multiple
            // incoming reveal range requests that might all desire to be animated
            const desiredScrollTop = this._computeScrollTopToRevealRange(this._context.viewLayout.getFutureViewport(), e.source, e.minimalReveal, e.range, e.selections, e.verticalType);
            if (desiredScrollTop === -1) {
                // marker to abort the reveal range request
                return false;
            }
            // validate the new desired scroll top
            let newScrollPosition = this._context.viewLayout.validateScrollPosition({ scrollTop: desiredScrollTop });
            if (e.revealHorizontal) {
                if (e.range && e.range.startLineNumber !== e.range.endLineNumber) {
                    // Two or more lines? => scroll to base (That's how you see most of the two lines)
                    newScrollPosition = {
                        scrollTop: newScrollPosition.scrollTop,
                        scrollLeft: 0
                    };
                }
                else if (e.range) {
                    // We don't necessarily know the horizontal offset of this range since the line might not be in the view...
                    this._horizontalRevealRequest = new HorizontalRevealRangeRequest(e.minimalReveal, e.range.startLineNumber, e.range.startColumn, e.range.endColumn, this._context.viewLayout.getCurrentScrollTop(), newScrollPosition.scrollTop, e.scrollType);
                }
                else if (e.selections && e.selections.length > 0) {
                    this._horizontalRevealRequest = new HorizontalRevealSelectionsRequest(e.minimalReveal, e.selections, this._context.viewLayout.getCurrentScrollTop(), newScrollPosition.scrollTop, e.scrollType);
                }
            }
            else {
                this._horizontalRevealRequest = null;
            }
            const scrollTopDelta = Math.abs(this._context.viewLayout.getCurrentScrollTop() - newScrollPosition.scrollTop);
            const scrollType = (scrollTopDelta <= this._lineHeight ? 1 /* ScrollType.Immediate */ : e.scrollType);
            this._context.viewModel.viewLayout.setScrollPosition(newScrollPosition, scrollType);
            return true;
        }
        onScrollChanged(e) {
            if (this._horizontalRevealRequest && e.scrollLeftChanged) {
                // cancel any outstanding horizontal reveal request if someone else scrolls horizontally.
                this._horizontalRevealRequest = null;
            }
            if (this._horizontalRevealRequest && e.scrollTopChanged) {
                const min = Math.min(this._horizontalRevealRequest.startScrollTop, this._horizontalRevealRequest.stopScrollTop);
                const max = Math.max(this._horizontalRevealRequest.startScrollTop, this._horizontalRevealRequest.stopScrollTop);
                if (e.scrollTop < min || e.scrollTop > max) {
                    // cancel any outstanding horizontal reveal request if someone else scrolls vertically.
                    this._horizontalRevealRequest = null;
                }
            }
            this.domNode.setWidth(e.scrollWidth);
            return this._visibleLines.onScrollChanged(e) || true;
        }
        onTokensChanged(e) {
            return this._visibleLines.onTokensChanged(e);
        }
        onZonesChanged(e) {
            this._context.viewModel.viewLayout.setMaxLineWidth(this._maxLineWidth);
            return this._visibleLines.onZonesChanged(e);
        }
        onThemeChanged(e) {
            return this._onOptionsMaybeChanged();
        }
        // ---- end view event handlers
        // ----------- HELPERS FOR OTHERS
        getPositionFromDOMInfo(spanNode, offset) {
            const viewLineDomNode = this._getViewLineDomNode(spanNode);
            if (viewLineDomNode === null) {
                // Couldn't find view line node
                return null;
            }
            const lineNumber = this._getLineNumberFor(viewLineDomNode);
            if (lineNumber === -1) {
                // Couldn't find view line node
                return null;
            }
            if (lineNumber < 1 || lineNumber > this._context.viewModel.getLineCount()) {
                // lineNumber is outside range
                return null;
            }
            if (this._context.viewModel.getLineMaxColumn(lineNumber) === 1) {
                // Line is empty
                return new position_1.Position(lineNumber, 1);
            }
            const rendStartLineNumber = this._visibleLines.getStartLineNumber();
            const rendEndLineNumber = this._visibleLines.getEndLineNumber();
            if (lineNumber < rendStartLineNumber || lineNumber > rendEndLineNumber) {
                // Couldn't find line
                return null;
            }
            let column = this._visibleLines.getVisibleLine(lineNumber).getColumnOfNodeOffset(spanNode, offset);
            const minColumn = this._context.viewModel.getLineMinColumn(lineNumber);
            if (column < minColumn) {
                column = minColumn;
            }
            return new position_1.Position(lineNumber, column);
        }
        _getViewLineDomNode(node) {
            while (node && node.nodeType === 1) {
                if (node.className === viewLine_1.ViewLine.CLASS_NAME) {
                    return node;
                }
                node = node.parentElement;
            }
            return null;
        }
        /**
         * @returns the line number of this view line dom node.
         */
        _getLineNumberFor(domNode) {
            const startLineNumber = this._visibleLines.getStartLineNumber();
            const endLineNumber = this._visibleLines.getEndLineNumber();
            for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
                const line = this._visibleLines.getVisibleLine(lineNumber);
                if (domNode === line.getDomNode()) {
                    return lineNumber;
                }
            }
            return -1;
        }
        getLineWidth(lineNumber) {
            const rendStartLineNumber = this._visibleLines.getStartLineNumber();
            const rendEndLineNumber = this._visibleLines.getEndLineNumber();
            if (lineNumber < rendStartLineNumber || lineNumber > rendEndLineNumber) {
                // Couldn't find line
                return -1;
            }
            const context = new domReadingContext_1.DomReadingContext(this.domNode.domNode, this._textRangeRestingSpot);
            const result = this._visibleLines.getVisibleLine(lineNumber).getWidth(context);
            this._updateLineWidthsSlowIfDomDidLayout(context);
            return result;
        }
        linesVisibleRangesForRange(_range, includeNewLines) {
            if (this.shouldRender()) {
                // Cannot read from the DOM because it is dirty
                // i.e. the model & the dom are out of sync, so I'd be reading something stale
                return null;
            }
            const originalEndLineNumber = _range.endLineNumber;
            const range = range_1.Range.intersectRanges(_range, this._lastRenderedData.getCurrentVisibleRange());
            if (!range) {
                return null;
            }
            const visibleRanges = [];
            let visibleRangesLen = 0;
            const domReadingContext = new domReadingContext_1.DomReadingContext(this.domNode.domNode, this._textRangeRestingSpot);
            let nextLineModelLineNumber = 0;
            if (includeNewLines) {
                nextLineModelLineNumber = this._context.viewModel.coordinatesConverter.convertViewPositionToModelPosition(new position_1.Position(range.startLineNumber, 1)).lineNumber;
            }
            const rendStartLineNumber = this._visibleLines.getStartLineNumber();
            const rendEndLineNumber = this._visibleLines.getEndLineNumber();
            for (let lineNumber = range.startLineNumber; lineNumber <= range.endLineNumber; lineNumber++) {
                if (lineNumber < rendStartLineNumber || lineNumber > rendEndLineNumber) {
                    continue;
                }
                const startColumn = lineNumber === range.startLineNumber ? range.startColumn : 1;
                const continuesInNextLine = lineNumber !== range.endLineNumber;
                const endColumn = continuesInNextLine ? this._context.viewModel.getLineMaxColumn(lineNumber) : range.endColumn;
                const visibleRangesForLine = this._visibleLines.getVisibleLine(lineNumber).getVisibleRangesForRange(lineNumber, startColumn, endColumn, domReadingContext);
                if (!visibleRangesForLine) {
                    continue;
                }
                if (includeNewLines && lineNumber < originalEndLineNumber) {
                    const currentLineModelLineNumber = nextLineModelLineNumber;
                    nextLineModelLineNumber = this._context.viewModel.coordinatesConverter.convertViewPositionToModelPosition(new position_1.Position(lineNumber + 1, 1)).lineNumber;
                    if (currentLineModelLineNumber !== nextLineModelLineNumber) {
                        visibleRangesForLine.ranges[visibleRangesForLine.ranges.length - 1].width += this._typicalHalfwidthCharacterWidth;
                    }
                }
                visibleRanges[visibleRangesLen++] = new renderingContext_1.LineVisibleRanges(visibleRangesForLine.outsideRenderedLine, lineNumber, renderingContext_1.HorizontalRange.from(visibleRangesForLine.ranges), continuesInNextLine);
            }
            this._updateLineWidthsSlowIfDomDidLayout(domReadingContext);
            if (visibleRangesLen === 0) {
                return null;
            }
            return visibleRanges;
        }
        _visibleRangesForLineRange(lineNumber, startColumn, endColumn) {
            if (this.shouldRender()) {
                // Cannot read from the DOM because it is dirty
                // i.e. the model & the dom are out of sync, so I'd be reading something stale
                return null;
            }
            if (lineNumber < this._visibleLines.getStartLineNumber() || lineNumber > this._visibleLines.getEndLineNumber()) {
                return null;
            }
            const domReadingContext = new domReadingContext_1.DomReadingContext(this.domNode.domNode, this._textRangeRestingSpot);
            const result = this._visibleLines.getVisibleLine(lineNumber).getVisibleRangesForRange(lineNumber, startColumn, endColumn, domReadingContext);
            this._updateLineWidthsSlowIfDomDidLayout(domReadingContext);
            return result;
        }
        visibleRangeForPosition(position) {
            const visibleRanges = this._visibleRangesForLineRange(position.lineNumber, position.column, position.column);
            if (!visibleRanges) {
                return null;
            }
            return new renderingContext_1.HorizontalPosition(visibleRanges.outsideRenderedLine, visibleRanges.ranges[0].left);
        }
        /**
         * Updates the max line width if it is fast to compute.
         * Returns true if all lines were taken into account.
         * Returns false if some lines need to be reevaluated (in a slow fashion).
         */
        _updateLineWidthsFast() {
            return this._updateLineWidths(true);
        }
        _updateLineWidthsSlow() {
            this._updateLineWidths(false);
        }
        /**
         * Update the line widths using DOM layout information after someone else
         * has caused a synchronous layout.
         */
        _updateLineWidthsSlowIfDomDidLayout(domReadingContext) {
            if (!domReadingContext.didDomLayout) {
                // only proceed if we just did a layout
                return;
            }
            if (this._asyncUpdateLineWidths.isScheduled()) {
                // reading widths is not scheduled => widths are up-to-date
                return;
            }
            this._asyncUpdateLineWidths.cancel();
            this._updateLineWidthsSlow();
        }
        _updateLineWidths(fast) {
            const rendStartLineNumber = this._visibleLines.getStartLineNumber();
            const rendEndLineNumber = this._visibleLines.getEndLineNumber();
            let localMaxLineWidth = 1;
            let allWidthsComputed = true;
            for (let lineNumber = rendStartLineNumber; lineNumber <= rendEndLineNumber; lineNumber++) {
                const visibleLine = this._visibleLines.getVisibleLine(lineNumber);
                if (fast && !visibleLine.getWidthIsFast()) {
                    // Cannot compute width in a fast way for this line
                    allWidthsComputed = false;
                    continue;
                }
                localMaxLineWidth = Math.max(localMaxLineWidth, visibleLine.getWidth(null));
            }
            if (allWidthsComputed && rendStartLineNumber === 1 && rendEndLineNumber === this._context.viewModel.getLineCount()) {
                // we know the max line width for all the lines
                this._maxLineWidth = 0;
            }
            this._ensureMaxLineWidth(localMaxLineWidth);
            return allWidthsComputed;
        }
        _checkMonospaceFontAssumptions() {
            // Problems with monospace assumptions are more apparent for longer lines,
            // as small rounding errors start to sum up, so we will select the longest
            // line for a closer inspection
            let longestLineNumber = -1;
            let longestWidth = -1;
            const rendStartLineNumber = this._visibleLines.getStartLineNumber();
            const rendEndLineNumber = this._visibleLines.getEndLineNumber();
            for (let lineNumber = rendStartLineNumber; lineNumber <= rendEndLineNumber; lineNumber++) {
                const visibleLine = this._visibleLines.getVisibleLine(lineNumber);
                if (visibleLine.needsMonospaceFontCheck()) {
                    const lineWidth = visibleLine.getWidth(null);
                    if (lineWidth > longestWidth) {
                        longestWidth = lineWidth;
                        longestLineNumber = lineNumber;
                    }
                }
            }
            if (longestLineNumber === -1) {
                return;
            }
            if (!this._visibleLines.getVisibleLine(longestLineNumber).monospaceAssumptionsAreValid()) {
                for (let lineNumber = rendStartLineNumber; lineNumber <= rendEndLineNumber; lineNumber++) {
                    const visibleLine = this._visibleLines.getVisibleLine(lineNumber);
                    visibleLine.onMonospaceAssumptionsInvalidated();
                }
            }
        }
        prepareRender() {
            throw new Error('Not supported');
        }
        render() {
            throw new Error('Not supported');
        }
        renderText(viewportData) {
            // (1) render lines - ensures lines are in the DOM
            this._visibleLines.renderLines(viewportData);
            this._lastRenderedData.setCurrentVisibleRange(viewportData.visibleRange);
            this.domNode.setWidth(this._context.viewLayout.getScrollWidth());
            this.domNode.setHeight(Math.min(this._context.viewLayout.getScrollHeight(), 1000000));
            // (2) compute horizontal scroll position:
            //  - this must happen after the lines are in the DOM since it might need a line that rendered just now
            //  - it might change `scrollWidth` and `scrollLeft`
            if (this._horizontalRevealRequest) {
                const horizontalRevealRequest = this._horizontalRevealRequest;
                // Check that we have the line that contains the horizontal range in the viewport
                if (viewportData.startLineNumber <= horizontalRevealRequest.minLineNumber && horizontalRevealRequest.maxLineNumber <= viewportData.endLineNumber) {
                    this._horizontalRevealRequest = null;
                    // allow `visibleRangesForRange2` to work
                    this.onDidRender();
                    // compute new scroll position
                    const newScrollLeft = this._computeScrollLeftToReveal(horizontalRevealRequest);
                    if (newScrollLeft) {
                        if (!this._isViewportWrapping) {
                            // ensure `scrollWidth` is large enough
                            this._ensureMaxLineWidth(newScrollLeft.maxHorizontalOffset);
                        }
                        // set `scrollLeft`
                        this._context.viewModel.viewLayout.setScrollPosition({
                            scrollLeft: newScrollLeft.scrollLeft
                        }, horizontalRevealRequest.scrollType);
                    }
                }
            }
            // Update max line width (not so important, it is just so the horizontal scrollbar doesn't get too small)
            if (!this._updateLineWidthsFast()) {
                // Computing the width of some lines would be slow => delay it
                this._asyncUpdateLineWidths.schedule();
            }
            else {
                this._asyncUpdateLineWidths.cancel();
            }
            if (platform.isLinux && !this._asyncCheckMonospaceFontAssumptions.isScheduled()) {
                const rendStartLineNumber = this._visibleLines.getStartLineNumber();
                const rendEndLineNumber = this._visibleLines.getEndLineNumber();
                for (let lineNumber = rendStartLineNumber; lineNumber <= rendEndLineNumber; lineNumber++) {
                    const visibleLine = this._visibleLines.getVisibleLine(lineNumber);
                    if (visibleLine.needsMonospaceFontCheck()) {
                        this._asyncCheckMonospaceFontAssumptions.schedule();
                        break;
                    }
                }
            }
            // (3) handle scrolling
            this._linesContent.setLayerHinting(this._canUseLayerHinting);
            this._linesContent.setContain('strict');
            const adjustedScrollTop = this._context.viewLayout.getCurrentScrollTop() - viewportData.bigNumbersDelta;
            this._linesContent.setTop(-adjustedScrollTop);
            this._linesContent.setLeft(-this._context.viewLayout.getCurrentScrollLeft());
        }
        // --- width
        _ensureMaxLineWidth(lineWidth) {
            const iLineWidth = Math.ceil(lineWidth);
            if (this._maxLineWidth < iLineWidth) {
                this._maxLineWidth = iLineWidth;
                this._context.viewModel.viewLayout.setMaxLineWidth(this._maxLineWidth);
            }
        }
        _computeScrollTopToRevealRange(viewport, source, minimalReveal, range, selections, verticalType) {
            const viewportStartY = viewport.top;
            const viewportHeight = viewport.height;
            const viewportEndY = viewportStartY + viewportHeight;
            let boxIsSingleRange;
            let boxStartY;
            let boxEndY;
            if (selections && selections.length > 0) {
                let minLineNumber = selections[0].startLineNumber;
                let maxLineNumber = selections[0].endLineNumber;
                for (let i = 1, len = selections.length; i < len; i++) {
                    const selection = selections[i];
                    minLineNumber = Math.min(minLineNumber, selection.startLineNumber);
                    maxLineNumber = Math.max(maxLineNumber, selection.endLineNumber);
                }
                boxIsSingleRange = false;
                boxStartY = this._context.viewLayout.getVerticalOffsetForLineNumber(minLineNumber);
                boxEndY = this._context.viewLayout.getVerticalOffsetForLineNumber(maxLineNumber) + this._lineHeight;
            }
            else if (range) {
                boxIsSingleRange = true;
                boxStartY = this._context.viewLayout.getVerticalOffsetForLineNumber(range.startLineNumber);
                boxEndY = this._context.viewLayout.getVerticalOffsetForLineNumber(range.endLineNumber) + this._lineHeight;
            }
            else {
                return -1;
            }
            const shouldIgnoreScrollOff = (source === 'mouse' || minimalReveal) && this._cursorSurroundingLinesStyle === 'default';
            let paddingTop = 0;
            let paddingBottom = 0;
            if (!shouldIgnoreScrollOff) {
                const maxLinesInViewport = (viewportHeight / this._lineHeight);
                const surroundingLines = Math.max(this._cursorSurroundingLines, this._stickyScrollEnabled ? this._maxNumberStickyLines : 0);
                const context = Math.min(maxLinesInViewport / 2, surroundingLines);
                paddingTop = context * this._lineHeight;
                paddingBottom = Math.max(0, (context - 1)) * this._lineHeight;
            }
            else {
                if (!minimalReveal) {
                    // Reveal one more line above (this case is hit when dragging)
                    paddingTop = this._lineHeight;
                }
            }
            if (!minimalReveal) {
                if (verticalType === 0 /* viewEvents.VerticalRevealType.Simple */ || verticalType === 4 /* viewEvents.VerticalRevealType.Bottom */) {
                    // Reveal one line more when the last line would be covered by the scrollbar - arrow down case or revealing a line explicitly at bottom
                    paddingBottom += this._lineHeight;
                }
            }
            boxStartY -= paddingTop;
            boxEndY += paddingBottom;
            let newScrollTop;
            if (boxEndY - boxStartY > viewportHeight) {
                // the box is larger than the viewport ... scroll to its top
                if (!boxIsSingleRange) {
                    // do not reveal multiple cursors if there are more than fit the viewport
                    return -1;
                }
                newScrollTop = boxStartY;
            }
            else if (verticalType === 5 /* viewEvents.VerticalRevealType.NearTop */ || verticalType === 6 /* viewEvents.VerticalRevealType.NearTopIfOutsideViewport */) {
                if (verticalType === 6 /* viewEvents.VerticalRevealType.NearTopIfOutsideViewport */ && viewportStartY <= boxStartY && boxEndY <= viewportEndY) {
                    // Box is already in the viewport... do nothing
                    newScrollTop = viewportStartY;
                }
                else {
                    // We want a gap that is 20% of the viewport, but with a minimum of 5 lines
                    const desiredGapAbove = Math.max(5 * this._lineHeight, viewportHeight * 0.2);
                    // Try to scroll just above the box with the desired gap
                    const desiredScrollTop = boxStartY - desiredGapAbove;
                    // But ensure that the box is not pushed out of viewport
                    const minScrollTop = boxEndY - viewportHeight;
                    newScrollTop = Math.max(minScrollTop, desiredScrollTop);
                }
            }
            else if (verticalType === 1 /* viewEvents.VerticalRevealType.Center */ || verticalType === 2 /* viewEvents.VerticalRevealType.CenterIfOutsideViewport */) {
                if (verticalType === 2 /* viewEvents.VerticalRevealType.CenterIfOutsideViewport */ && viewportStartY <= boxStartY && boxEndY <= viewportEndY) {
                    // Box is already in the viewport... do nothing
                    newScrollTop = viewportStartY;
                }
                else {
                    // Box is outside the viewport... center it
                    const boxMiddleY = (boxStartY + boxEndY) / 2;
                    newScrollTop = Math.max(0, boxMiddleY - viewportHeight / 2);
                }
            }
            else {
                newScrollTop = this._computeMinimumScrolling(viewportStartY, viewportEndY, boxStartY, boxEndY, verticalType === 3 /* viewEvents.VerticalRevealType.Top */, verticalType === 4 /* viewEvents.VerticalRevealType.Bottom */);
            }
            return newScrollTop;
        }
        _computeScrollLeftToReveal(horizontalRevealRequest) {
            const viewport = this._context.viewLayout.getCurrentViewport();
            const layoutInfo = this._context.configuration.options.get(146 /* EditorOption.layoutInfo */);
            const viewportStartX = viewport.left;
            const viewportEndX = viewportStartX + viewport.width - layoutInfo.verticalScrollbarWidth;
            let boxStartX = 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */;
            let boxEndX = 0;
            if (horizontalRevealRequest.type === 'range') {
                const visibleRanges = this._visibleRangesForLineRange(horizontalRevealRequest.lineNumber, horizontalRevealRequest.startColumn, horizontalRevealRequest.endColumn);
                if (!visibleRanges) {
                    return null;
                }
                for (const visibleRange of visibleRanges.ranges) {
                    boxStartX = Math.min(boxStartX, Math.round(visibleRange.left));
                    boxEndX = Math.max(boxEndX, Math.round(visibleRange.left + visibleRange.width));
                }
            }
            else {
                for (const selection of horizontalRevealRequest.selections) {
                    if (selection.startLineNumber !== selection.endLineNumber) {
                        return null;
                    }
                    const visibleRanges = this._visibleRangesForLineRange(selection.startLineNumber, selection.startColumn, selection.endColumn);
                    if (!visibleRanges) {
                        return null;
                    }
                    for (const visibleRange of visibleRanges.ranges) {
                        boxStartX = Math.min(boxStartX, Math.round(visibleRange.left));
                        boxEndX = Math.max(boxEndX, Math.round(visibleRange.left + visibleRange.width));
                    }
                }
            }
            if (!horizontalRevealRequest.minimalReveal) {
                boxStartX = Math.max(0, boxStartX - ViewLines.HORIZONTAL_EXTRA_PX);
                boxEndX += this._revealHorizontalRightPadding;
            }
            if (horizontalRevealRequest.type === 'selections' && boxEndX - boxStartX > viewport.width) {
                return null;
            }
            const newScrollLeft = this._computeMinimumScrolling(viewportStartX, viewportEndX, boxStartX, boxEndX);
            return {
                scrollLeft: newScrollLeft,
                maxHorizontalOffset: boxEndX
            };
        }
        _computeMinimumScrolling(viewportStart, viewportEnd, boxStart, boxEnd, revealAtStart, revealAtEnd) {
            viewportStart = viewportStart | 0;
            viewportEnd = viewportEnd | 0;
            boxStart = boxStart | 0;
            boxEnd = boxEnd | 0;
            revealAtStart = !!revealAtStart;
            revealAtEnd = !!revealAtEnd;
            const viewportLength = viewportEnd - viewportStart;
            const boxLength = boxEnd - boxStart;
            if (boxLength < viewportLength) {
                // The box would fit in the viewport
                if (revealAtStart) {
                    return boxStart;
                }
                if (revealAtEnd) {
                    return Math.max(0, boxEnd - viewportLength);
                }
                if (boxStart < viewportStart) {
                    // The box is above the viewport
                    return boxStart;
                }
                else if (boxEnd > viewportEnd) {
                    // The box is below the viewport
                    return Math.max(0, boxEnd - viewportLength);
                }
            }
            else {
                // The box would not fit in the viewport
                // Reveal the beginning of the box
                return boxStart;
            }
            return viewportStart;
        }
    }
    exports.ViewLines = ViewLines;
});

define(__m[25/*vs/platform/theme/common/themeService*/], __M([1/*require*/,0/*exports*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,7/*vs/platform/instantiation/common/instantiation*/,38/*vs/platform/registry/common/platform*/,97/*vs/platform/theme/common/theme*/]), function (require, exports, event_1, lifecycle_1, instantiation_1, platform, theme_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Themable = exports.Extensions = exports.IThemeService = void 0;
    exports.themeColorFromId = themeColorFromId;
    exports.getThemeTypeSelector = getThemeTypeSelector;
    exports.registerThemingParticipant = registerThemingParticipant;
    exports.IThemeService = (0, instantiation_1.createDecorator)('themeService');
    function themeColorFromId(id) {
        return { id };
    }
    function getThemeTypeSelector(type) {
        switch (type) {
            case theme_1.ColorScheme.DARK: return 'vs-dark';
            case theme_1.ColorScheme.HIGH_CONTRAST_DARK: return 'hc-black';
            case theme_1.ColorScheme.HIGH_CONTRAST_LIGHT: return 'hc-light';
            default: return 'vs';
        }
    }
    // static theming participant
    exports.Extensions = {
        ThemingContribution: 'base.contributions.theming'
    };
    class ThemingRegistry {
        constructor() {
            this.themingParticipants = [];
            this.themingParticipants = [];
            this.onThemingParticipantAddedEmitter = new event_1.Emitter();
        }
        onColorThemeChange(participant) {
            this.themingParticipants.push(participant);
            this.onThemingParticipantAddedEmitter.fire(participant);
            return (0, lifecycle_1.toDisposable)(() => {
                const idx = this.themingParticipants.indexOf(participant);
                this.themingParticipants.splice(idx, 1);
            });
        }
        getThemingParticipants() {
            return this.themingParticipants;
        }
    }
    const themingRegistry = new ThemingRegistry();
    platform.Registry.add(exports.Extensions.ThemingContribution, themingRegistry);
    function registerThemingParticipant(participant) {
        return themingRegistry.onColorThemeChange(participant);
    }
    /**
     * Utility base class for all themable components.
     */
    class Themable extends lifecycle_1.Disposable {
        constructor(themeService) {
            super();
            this.themeService = themeService;
            this.theme = themeService.getColorTheme();
            // Hook up to theme changes
            this._register(this.themeService.onDidColorThemeChange(theme => this.onThemeChange(theme)));
        }
        onThemeChange(theme) {
            this.theme = theme;
            this.updateStyles();
        }
        updateStyles() {
            // Subclasses to override
        }
    }
    exports.Themable = Themable;
});










define(__m[771/*vs/editor/browser/services/abstractCodeEditorService*/], __M([1/*require*/,0/*exports*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,73/*vs/base/common/linkedList*/,25/*vs/platform/theme/common/themeService*/]), function (require, exports, event_1, lifecycle_1, linkedList_1, themeService_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.GlobalStyleSheet = exports.AbstractCodeEditorService = void 0;
    let AbstractCodeEditorService = class AbstractCodeEditorService extends lifecycle_1.Disposable {
        constructor(_themeService) {
            super();
            this._themeService = _themeService;
            this._onWillCreateCodeEditor = this._register(new event_1.Emitter());
            this._onCodeEditorAdd = this._register(new event_1.Emitter());
            this.onCodeEditorAdd = this._onCodeEditorAdd.event;
            this._onCodeEditorRemove = this._register(new event_1.Emitter());
            this.onCodeEditorRemove = this._onCodeEditorRemove.event;
            this._onWillCreateDiffEditor = this._register(new event_1.Emitter());
            this._onDiffEditorAdd = this._register(new event_1.Emitter());
            this.onDiffEditorAdd = this._onDiffEditorAdd.event;
            this._onDiffEditorRemove = this._register(new event_1.Emitter());
            this.onDiffEditorRemove = this._onDiffEditorRemove.event;
            this._decorationOptionProviders = new Map();
            this._codeEditorOpenHandlers = new linkedList_1.LinkedList();
            this._modelProperties = new Map();
            this._codeEditors = Object.create(null);
            this._diffEditors = Object.create(null);
            this._globalStyleSheet = null;
        }
        willCreateCodeEditor() {
            this._onWillCreateCodeEditor.fire();
        }
        addCodeEditor(editor) {
            this._codeEditors[editor.getId()] = editor;
            this._onCodeEditorAdd.fire(editor);
        }
        removeCodeEditor(editor) {
            if (delete this._codeEditors[editor.getId()]) {
                this._onCodeEditorRemove.fire(editor);
            }
        }
        listCodeEditors() {
            return Object.keys(this._codeEditors).map(id => this._codeEditors[id]);
        }
        willCreateDiffEditor() {
            this._onWillCreateDiffEditor.fire();
        }
        addDiffEditor(editor) {
            this._diffEditors[editor.getId()] = editor;
            this._onDiffEditorAdd.fire(editor);
        }
        listDiffEditors() {
            return Object.keys(this._diffEditors).map(id => this._diffEditors[id]);
        }
        getFocusedCodeEditor() {
            let editorWithWidgetFocus = null;
            const editors = this.listCodeEditors();
            for (const editor of editors) {
                if (editor.hasTextFocus()) {
                    // bingo!
                    return editor;
                }
                if (editor.hasWidgetFocus()) {
                    editorWithWidgetFocus = editor;
                }
            }
            return editorWithWidgetFocus;
        }
        removeDecorationType(key) {
            const provider = this._decorationOptionProviders.get(key);
            if (provider) {
                provider.refCount--;
                if (provider.refCount <= 0) {
                    this._decorationOptionProviders.delete(key);
                    provider.dispose();
                    this.listCodeEditors().forEach((ed) => ed.removeDecorationsByType(key));
                }
            }
        }
        setModelProperty(resource, key, value) {
            const key1 = resource.toString();
            let dest;
            if (this._modelProperties.has(key1)) {
                dest = this._modelProperties.get(key1);
            }
            else {
                dest = new Map();
                this._modelProperties.set(key1, dest);
            }
            dest.set(key, value);
        }
        getModelProperty(resource, key) {
            const key1 = resource.toString();
            if (this._modelProperties.has(key1)) {
                const innerMap = this._modelProperties.get(key1);
                return innerMap.get(key);
            }
            return undefined;
        }
        async openCodeEditor(input, source, sideBySide) {
            for (const handler of this._codeEditorOpenHandlers) {
                const candidate = await handler(input, source, sideBySide);
                if (candidate !== null) {
                    return candidate;
                }
            }
            return null;
        }
        registerCodeEditorOpenHandler(handler) {
            const rm = this._codeEditorOpenHandlers.unshift(handler);
            return (0, lifecycle_1.toDisposable)(rm);
        }
    };
    exports.AbstractCodeEditorService = AbstractCodeEditorService;
    exports.AbstractCodeEditorService = AbstractCodeEditorService = __decorate([
        __param(0, themeService_1.IThemeService)
    ], AbstractCodeEditorService);
    class GlobalStyleSheet {
        constructor(styleSheet) {
            this._styleSheet = styleSheet;
        }
    }
    exports.GlobalStyleSheet = GlobalStyleSheet;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[772/*vs/editor/browser/services/hoverService/hoverService*/], __M([1/*require*/,0/*exports*/,49/*vs/platform/instantiation/common/extensions*/,25/*vs/platform/theme/common/themeService*/,32/*vs/platform/theme/common/colorRegistry*/,118/*vs/platform/hover/browser/hover*/,58/*vs/platform/contextview/browser/contextView*/,7/*vs/platform/instantiation/common/instantiation*/,705/*vs/editor/browser/services/hoverService/hoverWidget*/,2/*vs/base/common/lifecycle*/,5/*vs/base/browser/dom*/,31/*vs/platform/keybinding/common/keybinding*/,47/*vs/base/browser/keyboardEvent*/,61/*vs/platform/accessibility/common/accessibility*/,119/*vs/platform/layout/browser/layoutService*/,52/*vs/base/browser/window*/,395/*vs/platform/contextview/browser/contextViewService*/,648/*vs/editor/browser/services/hoverService/updatableHoverWidget*/,14/*vs/base/common/async*/]), function (require, exports, extensions_1, themeService_1, colorRegistry_1, hover_1, contextView_1, instantiation_1, hoverWidget_1, lifecycle_1, dom_1, keybinding_1, keyboardEvent_1, accessibility_1, layoutService_1, window_1, contextViewService_1, updatableHoverWidget_1, async_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.HoverService = void 0;
    let HoverService = class HoverService extends lifecycle_1.Disposable {
        constructor(_instantiationService, contextMenuService, _keybindingService, _layoutService, _accessibilityService) {
            super();
            this._instantiationService = _instantiationService;
            this._keybindingService = _keybindingService;
            this._layoutService = _layoutService;
            this._accessibilityService = _accessibilityService;
            this._managedHovers = new Map();
            contextMenuService.onDidShowContextMenu(() => this.hideHover());
            this._contextViewHandler = this._register(new contextViewService_1.ContextViewHandler(this._layoutService));
        }
        showHover(options, focus, skipLastFocusedUpdate) {
            if (getHoverOptionsIdentity(this._currentHoverOptions) === getHoverOptionsIdentity(options)) {
                return undefined;
            }
            if (this._currentHover && this._currentHoverOptions?.persistence?.sticky) {
                return undefined;
            }
            this._currentHoverOptions = options;
            this._lastHoverOptions = options;
            const trapFocus = options.trapFocus || this._accessibilityService.isScreenReaderOptimized();
            const activeElement = (0, dom_1.getActiveElement)();
            // HACK, remove this check when #189076 is fixed
            if (!skipLastFocusedUpdate) {
                if (trapFocus && activeElement) {
                    if (!activeElement.classList.contains('monaco-hover')) {
                        this._lastFocusedElementBeforeOpen = activeElement;
                    }
                }
                else {
                    this._lastFocusedElementBeforeOpen = undefined;
                }
            }
            const hoverDisposables = new lifecycle_1.DisposableStore();
            const hover = this._instantiationService.createInstance(hoverWidget_1.HoverWidget, options);
            if (options.persistence?.sticky) {
                hover.isLocked = true;
            }
            hover.onDispose(() => {
                const hoverWasFocused = this._currentHover?.domNode && (0, dom_1.isAncestorOfActiveElement)(this._currentHover.domNode);
                if (hoverWasFocused) {
                    // Required to handle cases such as closing the hover with the escape key
                    this._lastFocusedElementBeforeOpen?.focus();
                }
                // Only clear the current options if it's the current hover, the current options help
                // reduce flickering when the same hover is shown multiple times
                if (this._currentHoverOptions === options) {
                    this._currentHoverOptions = undefined;
                }
                hoverDisposables.dispose();
            }, undefined, hoverDisposables);
            // Set the container explicitly to enable aux window support
            if (!options.container) {
                const targetElement = (0, dom_1.isHTMLElement)(options.target) ? options.target : options.target.targetElements[0];
                options.container = this._layoutService.getContainer((0, dom_1.getWindow)(targetElement));
            }
            this._contextViewHandler.showContextView(new HoverContextViewDelegate(hover, focus), options.container);
            hover.onRequestLayout(() => this._contextViewHandler.layout(), undefined, hoverDisposables);
            if (options.persistence?.sticky) {
                hoverDisposables.add((0, dom_1.addDisposableListener)((0, dom_1.getWindow)(options.container).document, dom_1.EventType.MOUSE_DOWN, e => {
                    if (!(0, dom_1.isAncestor)(e.target, hover.domNode)) {
                        this.doHideHover();
                    }
                }));
            }
            else {
                if ('targetElements' in options.target) {
                    for (const element of options.target.targetElements) {
                        hoverDisposables.add((0, dom_1.addDisposableListener)(element, dom_1.EventType.CLICK, () => this.hideHover()));
                    }
                }
                else {
                    hoverDisposables.add((0, dom_1.addDisposableListener)(options.target, dom_1.EventType.CLICK, () => this.hideHover()));
                }
                const focusedElement = (0, dom_1.getActiveElement)();
                if (focusedElement) {
                    const focusedElementDocument = (0, dom_1.getWindow)(focusedElement).document;
                    hoverDisposables.add((0, dom_1.addDisposableListener)(focusedElement, dom_1.EventType.KEY_DOWN, e => this._keyDown(e, hover, !!options.persistence?.hideOnKeyDown)));
                    hoverDisposables.add((0, dom_1.addDisposableListener)(focusedElementDocument, dom_1.EventType.KEY_DOWN, e => this._keyDown(e, hover, !!options.persistence?.hideOnKeyDown)));
                    hoverDisposables.add((0, dom_1.addDisposableListener)(focusedElement, dom_1.EventType.KEY_UP, e => this._keyUp(e, hover)));
                    hoverDisposables.add((0, dom_1.addDisposableListener)(focusedElementDocument, dom_1.EventType.KEY_UP, e => this._keyUp(e, hover)));
                }
            }
            if ('IntersectionObserver' in window_1.mainWindow) {
                const observer = new IntersectionObserver(e => this._intersectionChange(e, hover), { threshold: 0 });
                const firstTargetElement = 'targetElements' in options.target ? options.target.targetElements[0] : options.target;
                observer.observe(firstTargetElement);
                hoverDisposables.add((0, lifecycle_1.toDisposable)(() => observer.disconnect()));
            }
            this._currentHover = hover;
            return hover;
        }
        hideHover() {
            if (this._currentHover?.isLocked || !this._currentHoverOptions) {
                return;
            }
            this.doHideHover();
        }
        doHideHover() {
            this._currentHover = undefined;
            this._currentHoverOptions = undefined;
            this._contextViewHandler.hideContextView();
        }
        _intersectionChange(entries, hover) {
            const entry = entries[entries.length - 1];
            if (!entry.isIntersecting) {
                hover.dispose();
            }
        }
        showAndFocusLastHover() {
            if (!this._lastHoverOptions) {
                return;
            }
            this.showHover(this._lastHoverOptions, true, true);
        }
        _keyDown(e, hover, hideOnKeyDown) {
            if (e.key === 'Alt') {
                hover.isLocked = true;
                return;
            }
            const event = new keyboardEvent_1.StandardKeyboardEvent(e);
            const keybinding = this._keybindingService.resolveKeyboardEvent(event);
            if (keybinding.getSingleModifierDispatchChords().some(value => !!value) || this._keybindingService.softDispatch(event, event.target).kind !== 0 /* ResultKind.NoMatchingKb */) {
                return;
            }
            if (hideOnKeyDown && (!this._currentHoverOptions?.trapFocus || e.key !== 'Tab')) {
                this.hideHover();
                this._lastFocusedElementBeforeOpen?.focus();
            }
        }
        _keyUp(e, hover) {
            if (e.key === 'Alt') {
                hover.isLocked = false;
                // Hide if alt is released while the mouse is not over hover/target
                if (!hover.isMouseIn) {
                    this.hideHover();
                    this._lastFocusedElementBeforeOpen?.focus();
                }
            }
        }
        // TODO: Investigate performance of this function. There seems to be a lot of content created
        //       and thrown away on start up
        setupManagedHover(hoverDelegate, targetElement, content, options) {
            targetElement.setAttribute('custom-hover', 'true');
            if (targetElement.title !== '') {
                console.warn('HTML element already has a title attribute, which will conflict with the custom hover. Please remove the title attribute.');
                console.trace('Stack trace:', targetElement.title);
                targetElement.title = '';
            }
            let hoverPreparation;
            let hoverWidget;
            const hideHover = (disposeWidget, disposePreparation) => {
                const hadHover = hoverWidget !== undefined;
                if (disposeWidget) {
                    hoverWidget?.dispose();
                    hoverWidget = undefined;
                }
                if (disposePreparation) {
                    hoverPreparation?.dispose();
                    hoverPreparation = undefined;
                }
                if (hadHover) {
                    hoverDelegate.onDidHideHover?.();
                    hoverWidget = undefined;
                }
            };
            const triggerShowHover = (delay, focus, target, trapFocus) => {
                return new async_1.TimeoutTimer(async () => {
                    if (!hoverWidget || hoverWidget.isDisposed) {
                        hoverWidget = new updatableHoverWidget_1.ManagedHoverWidget(hoverDelegate, target || targetElement, delay > 0);
                        await hoverWidget.update(typeof content === 'function' ? content() : content, focus, { ...options, trapFocus });
                    }
                }, delay);
            };
            let isMouseDown = false;
            const mouseDownEmitter = (0, dom_1.addDisposableListener)(targetElement, dom_1.EventType.MOUSE_DOWN, () => {
                isMouseDown = true;
                hideHover(true, true);
            }, true);
            const mouseUpEmitter = (0, dom_1.addDisposableListener)(targetElement, dom_1.EventType.MOUSE_UP, () => {
                isMouseDown = false;
            }, true);
            const mouseLeaveEmitter = (0, dom_1.addDisposableListener)(targetElement, dom_1.EventType.MOUSE_LEAVE, (e) => {
                isMouseDown = false;
                hideHover(false, e.fromElement === targetElement);
            }, true);
            const onMouseOver = (e) => {
                if (hoverPreparation) {
                    return;
                }
                const toDispose = new lifecycle_1.DisposableStore();
                const target = {
                    targetElements: [targetElement],
                    dispose: () => { }
                };
                if (hoverDelegate.placement === undefined || hoverDelegate.placement === 'mouse') {
                    // track the mouse position
                    const onMouseMove = (e) => {
                        target.x = e.x + 10;
                        if (((0, dom_1.isHTMLElement)(e.target)) && getHoverTargetElement(e.target, targetElement) !== targetElement) {
                            hideHover(true, true);
                        }
                    };
                    toDispose.add((0, dom_1.addDisposableListener)(targetElement, dom_1.EventType.MOUSE_MOVE, onMouseMove, true));
                }
                hoverPreparation = toDispose;
                if (((0, dom_1.isHTMLElement)(e.target)) && getHoverTargetElement(e.target, targetElement) !== targetElement) {
                    return; // Do not show hover when the mouse is over another hover target
                }
                toDispose.add(triggerShowHover(hoverDelegate.delay, false, target));
            };
            const mouseOverDomEmitter = (0, dom_1.addDisposableListener)(targetElement, dom_1.EventType.MOUSE_OVER, onMouseOver, true);
            const onFocus = () => {
                if (isMouseDown || hoverPreparation) {
                    return;
                }
                const target = {
                    targetElements: [targetElement],
                    dispose: () => { }
                };
                const toDispose = new lifecycle_1.DisposableStore();
                const onBlur = () => hideHover(true, true);
                toDispose.add((0, dom_1.addDisposableListener)(targetElement, dom_1.EventType.BLUR, onBlur, true));
                toDispose.add(triggerShowHover(hoverDelegate.delay, false, target));
                hoverPreparation = toDispose;
            };
            // Do not show hover when focusing an input or textarea
            let focusDomEmitter;
            const tagName = targetElement.tagName.toLowerCase();
            if (tagName !== 'input' && tagName !== 'textarea') {
                focusDomEmitter = (0, dom_1.addDisposableListener)(targetElement, dom_1.EventType.FOCUS, onFocus, true);
            }
            const hover = {
                show: focus => {
                    hideHover(false, true); // terminate a ongoing mouse over preparation
                    triggerShowHover(0, focus, undefined, focus); // show hover immediately
                },
                hide: () => {
                    hideHover(true, true);
                },
                update: async (newContent, hoverOptions) => {
                    content = newContent;
                    await hoverWidget?.update(content, undefined, hoverOptions);
                },
                dispose: () => {
                    this._managedHovers.delete(targetElement);
                    mouseOverDomEmitter.dispose();
                    mouseLeaveEmitter.dispose();
                    mouseDownEmitter.dispose();
                    mouseUpEmitter.dispose();
                    focusDomEmitter?.dispose();
                    hideHover(true, true);
                }
            };
            this._managedHovers.set(targetElement, hover);
            return hover;
        }
        showManagedHover(target) {
            const hover = this._managedHovers.get(target);
            if (hover) {
                hover.show(true);
            }
        }
        dispose() {
            this._managedHovers.forEach(hover => hover.dispose());
            super.dispose();
        }
    };
    exports.HoverService = HoverService;
    exports.HoverService = HoverService = __decorate([
        __param(0, instantiation_1.IInstantiationService),
        __param(1, contextView_1.IContextMenuService),
        __param(2, keybinding_1.IKeybindingService),
        __param(3, layoutService_1.ILayoutService),
        __param(4, accessibility_1.IAccessibilityService)
    ], HoverService);
    function getHoverOptionsIdentity(options) {
        if (options === undefined) {
            return undefined;
        }
        return options?.id ?? options;
    }
    class HoverContextViewDelegate {
        get anchorPosition() {
            return this._hover.anchor;
        }
        constructor(_hover, _focus = false) {
            this._hover = _hover;
            this._focus = _focus;
            // Render over all other context views
            this.layer = 1;
        }
        render(container) {
            this._hover.render(container);
            if (this._focus) {
                this._hover.focus();
            }
            return this._hover;
        }
        getAnchor() {
            return {
                x: this._hover.x,
                y: this._hover.y
            };
        }
        layout() {
            this._hover.layout();
        }
    }
    function getHoverTargetElement(element, stopElement) {
        stopElement = stopElement ?? (0, dom_1.getWindow)(element).document.body;
        while (!element.hasAttribute('custom-hover') && element !== stopElement) {
            element = element.parentElement;
        }
        return element;
    }
    (0, extensions_1.registerSingleton)(hover_1.IHoverService, HoverService, 1 /* InstantiationType.Delayed */);
    (0, themeService_1.registerThemingParticipant)((theme, collector) => {
        const hoverBorder = theme.getColor(colorRegistry_1.editorHoverBorder);
        if (hoverBorder) {
            collector.addRule(`.monaco-workbench .workbench-hover .hover-row:not(:first-child):not(:empty) { border-top: 1px solid ${hoverBorder.transparent(0.5)}; }`);
            collector.addRule(`.monaco-workbench .workbench-hover hr { border-top: 1px solid ${hoverBorder.transparent(0.5)}; }`);
        }
    });
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[773/*vs/editor/browser/viewParts/editorScrollbar/editorScrollbar*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,39/*vs/base/browser/fastDomNode*/,86/*vs/base/browser/ui/scrollbar/scrollableElement*/,56/*vs/editor/browser/view/viewPart*/,25/*vs/platform/theme/common/themeService*/]), function (require, exports, dom, fastDomNode_1, scrollableElement_1, viewPart_1, themeService_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.EditorScrollbar = void 0;
    class EditorScrollbar extends viewPart_1.ViewPart {
        constructor(context, linesContent, viewDomNode, overflowGuardDomNode) {
            super(context);
            const options = this._context.configuration.options;
            const scrollbar = options.get(104 /* EditorOption.scrollbar */);
            const mouseWheelScrollSensitivity = options.get(75 /* EditorOption.mouseWheelScrollSensitivity */);
            const fastScrollSensitivity = options.get(40 /* EditorOption.fastScrollSensitivity */);
            const scrollPredominantAxis = options.get(107 /* EditorOption.scrollPredominantAxis */);
            const scrollbarOptions = {
                listenOnDomNode: viewDomNode.domNode,
                className: 'editor-scrollable' + ' ' + (0, themeService_1.getThemeTypeSelector)(context.theme.type),
                useShadows: false,
                lazyRender: true,
                vertical: scrollbar.vertical,
                horizontal: scrollbar.horizontal,
                verticalHasArrows: scrollbar.verticalHasArrows,
                horizontalHasArrows: scrollbar.horizontalHasArrows,
                verticalScrollbarSize: scrollbar.verticalScrollbarSize,
                verticalSliderSize: scrollbar.verticalSliderSize,
                horizontalScrollbarSize: scrollbar.horizontalScrollbarSize,
                horizontalSliderSize: scrollbar.horizontalSliderSize,
                handleMouseWheel: scrollbar.handleMouseWheel,
                alwaysConsumeMouseWheel: scrollbar.alwaysConsumeMouseWheel,
                arrowSize: scrollbar.arrowSize,
                mouseWheelScrollSensitivity: mouseWheelScrollSensitivity,
                fastScrollSensitivity: fastScrollSensitivity,
                scrollPredominantAxis: scrollPredominantAxis,
                scrollByPage: scrollbar.scrollByPage,
            };
            this.scrollbar = this._register(new scrollableElement_1.SmoothScrollableElement(linesContent.domNode, scrollbarOptions, this._context.viewLayout.getScrollable()));
            viewPart_1.PartFingerprints.write(this.scrollbar.getDomNode(), 6 /* PartFingerprint.ScrollableElement */);
            this.scrollbarDomNode = (0, fastDomNode_1.createFastDomNode)(this.scrollbar.getDomNode());
            this.scrollbarDomNode.setPosition('absolute');
            this._setLayout();
            // When having a zone widget that calls .focus() on one of its dom elements,
            // the browser will try desperately to reveal that dom node, unexpectedly
            // changing the .scrollTop of this.linesContent
            const onBrowserDesperateReveal = (domNode, lookAtScrollTop, lookAtScrollLeft) => {
                const newScrollPosition = {};
                if (lookAtScrollTop) {
                    const deltaTop = domNode.scrollTop;
                    if (deltaTop) {
                        newScrollPosition.scrollTop = this._context.viewLayout.getCurrentScrollTop() + deltaTop;
                        domNode.scrollTop = 0;
                    }
                }
                if (lookAtScrollLeft) {
                    const deltaLeft = domNode.scrollLeft;
                    if (deltaLeft) {
                        newScrollPosition.scrollLeft = this._context.viewLayout.getCurrentScrollLeft() + deltaLeft;
                        domNode.scrollLeft = 0;
                    }
                }
                this._context.viewModel.viewLayout.setScrollPosition(newScrollPosition, 1 /* ScrollType.Immediate */);
            };
            // I've seen this happen both on the view dom node & on the lines content dom node.
            this._register(dom.addDisposableListener(viewDomNode.domNode, 'scroll', (e) => onBrowserDesperateReveal(viewDomNode.domNode, true, true)));
            this._register(dom.addDisposableListener(linesContent.domNode, 'scroll', (e) => onBrowserDesperateReveal(linesContent.domNode, true, false)));
            this._register(dom.addDisposableListener(overflowGuardDomNode.domNode, 'scroll', (e) => onBrowserDesperateReveal(overflowGuardDomNode.domNode, true, false)));
            this._register(dom.addDisposableListener(this.scrollbarDomNode.domNode, 'scroll', (e) => onBrowserDesperateReveal(this.scrollbarDomNode.domNode, true, false)));
        }
        dispose() {
            super.dispose();
        }
        _setLayout() {
            const options = this._context.configuration.options;
            const layoutInfo = options.get(146 /* EditorOption.layoutInfo */);
            this.scrollbarDomNode.setLeft(layoutInfo.contentLeft);
            const minimap = options.get(73 /* EditorOption.minimap */);
            const side = minimap.side;
            if (side === 'right') {
                this.scrollbarDomNode.setWidth(layoutInfo.contentWidth + layoutInfo.minimap.minimapWidth);
            }
            else {
                this.scrollbarDomNode.setWidth(layoutInfo.contentWidth);
            }
            this.scrollbarDomNode.setHeight(layoutInfo.height);
        }
        getOverviewRulerLayoutInfo() {
            return this.scrollbar.getOverviewRulerLayoutInfo();
        }
        getDomNode() {
            return this.scrollbarDomNode;
        }
        delegateVerticalScrollbarPointerDown(browserEvent) {
            this.scrollbar.delegateVerticalScrollbarPointerDown(browserEvent);
        }
        delegateScrollFromMouseWheelEvent(browserEvent) {
            this.scrollbar.delegateScrollFromMouseWheelEvent(browserEvent);
        }
        // --- begin event handlers
        onConfigurationChanged(e) {
            if (e.hasChanged(104 /* EditorOption.scrollbar */)
                || e.hasChanged(75 /* EditorOption.mouseWheelScrollSensitivity */)
                || e.hasChanged(40 /* EditorOption.fastScrollSensitivity */)) {
                const options = this._context.configuration.options;
                const scrollbar = options.get(104 /* EditorOption.scrollbar */);
                const mouseWheelScrollSensitivity = options.get(75 /* EditorOption.mouseWheelScrollSensitivity */);
                const fastScrollSensitivity = options.get(40 /* EditorOption.fastScrollSensitivity */);
                const scrollPredominantAxis = options.get(107 /* EditorOption.scrollPredominantAxis */);
                const newOpts = {
                    vertical: scrollbar.vertical,
                    horizontal: scrollbar.horizontal,
                    verticalScrollbarSize: scrollbar.verticalScrollbarSize,
                    horizontalScrollbarSize: scrollbar.horizontalScrollbarSize,
                    scrollByPage: scrollbar.scrollByPage,
                    handleMouseWheel: scrollbar.handleMouseWheel,
                    mouseWheelScrollSensitivity: mouseWheelScrollSensitivity,
                    fastScrollSensitivity: fastScrollSensitivity,
                    scrollPredominantAxis: scrollPredominantAxis
                };
                this.scrollbar.updateOptions(newOpts);
            }
            if (e.hasChanged(146 /* EditorOption.layoutInfo */)) {
                this._setLayout();
            }
            return true;
        }
        onScrollChanged(e) {
            return true;
        }
        onThemeChanged(e) {
            this.scrollbar.updateClassName('editor-scrollable' + ' ' + (0, themeService_1.getThemeTypeSelector)(this._context.theme.type));
            return true;
        }
        // --- end event handlers
        prepareRender(ctx) {
            // Nothing to do
        }
        render(ctx) {
            this.scrollbar.renderNow();
        }
    }
    exports.EditorScrollbar = EditorScrollbar;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[774/*vs/editor/browser/viewParts/selections/selections*/], __M([1/*require*/,0/*exports*/,133/*vs/editor/browser/view/dynamicViewOverlay*/,32/*vs/platform/theme/common/colorRegistry*/,25/*vs/platform/theme/common/themeService*/,495/*vs/css!vs/editor/browser/viewParts/selections/selections*/]), function (require, exports, dynamicViewOverlay_1, colorRegistry_1, themeService_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SelectionsOverlay = void 0;
    class HorizontalRangeWithStyle {
        constructor(other) {
            this.left = other.left;
            this.width = other.width;
            this.startStyle = null;
            this.endStyle = null;
        }
    }
    class LineVisibleRangesWithStyle {
        constructor(lineNumber, ranges) {
            this.lineNumber = lineNumber;
            this.ranges = ranges;
        }
    }
    function toStyledRange(item) {
        return new HorizontalRangeWithStyle(item);
    }
    function toStyled(item) {
        return new LineVisibleRangesWithStyle(item.lineNumber, item.ranges.map(toStyledRange));
    }
    class SelectionsOverlay extends dynamicViewOverlay_1.DynamicViewOverlay {
        static { this.SELECTION_CLASS_NAME = 'selected-text'; }
        static { this.SELECTION_TOP_LEFT = 'top-left-radius'; }
        static { this.SELECTION_BOTTOM_LEFT = 'bottom-left-radius'; }
        static { this.SELECTION_TOP_RIGHT = 'top-right-radius'; }
        static { this.SELECTION_BOTTOM_RIGHT = 'bottom-right-radius'; }
        static { this.EDITOR_BACKGROUND_CLASS_NAME = 'monaco-editor-background'; }
        static { this.ROUNDED_PIECE_WIDTH = 10; }
        constructor(context) {
            super();
            this._previousFrameVisibleRangesWithStyle = [];
            this._context = context;
            const options = this._context.configuration.options;
            this._roundedSelection = options.get(102 /* EditorOption.roundedSelection */);
            this._typicalHalfwidthCharacterWidth = options.get(50 /* EditorOption.fontInfo */).typicalHalfwidthCharacterWidth;
            this._selections = [];
            this._renderResult = null;
            this._context.addEventHandler(this);
        }
        dispose() {
            this._context.removeEventHandler(this);
            this._renderResult = null;
            super.dispose();
        }
        // --- begin event handlers
        onConfigurationChanged(e) {
            const options = this._context.configuration.options;
            this._roundedSelection = options.get(102 /* EditorOption.roundedSelection */);
            this._typicalHalfwidthCharacterWidth = options.get(50 /* EditorOption.fontInfo */).typicalHalfwidthCharacterWidth;
            return true;
        }
        onCursorStateChanged(e) {
            this._selections = e.selections.slice(0);
            return true;
        }
        onDecorationsChanged(e) {
            // true for inline decorations that can end up relayouting text
            return true; //e.inlineDecorationsChanged;
        }
        onFlushed(e) {
            return true;
        }
        onLinesChanged(e) {
            return true;
        }
        onLinesDeleted(e) {
            return true;
        }
        onLinesInserted(e) {
            return true;
        }
        onScrollChanged(e) {
            return e.scrollTopChanged;
        }
        onZonesChanged(e) {
            return true;
        }
        // --- end event handlers
        _visibleRangesHaveGaps(linesVisibleRanges) {
            for (let i = 0, len = linesVisibleRanges.length; i < len; i++) {
                const lineVisibleRanges = linesVisibleRanges[i];
                if (lineVisibleRanges.ranges.length > 1) {
                    // There are two ranges on the same line
                    return true;
                }
            }
            return false;
        }
        _enrichVisibleRangesWithStyle(viewport, linesVisibleRanges, previousFrame) {
            const epsilon = this._typicalHalfwidthCharacterWidth / 4;
            let previousFrameTop = null;
            let previousFrameBottom = null;
            if (previousFrame && previousFrame.length > 0 && linesVisibleRanges.length > 0) {
                const topLineNumber = linesVisibleRanges[0].lineNumber;
                if (topLineNumber === viewport.startLineNumber) {
                    for (let i = 0; !previousFrameTop && i < previousFrame.length; i++) {
                        if (previousFrame[i].lineNumber === topLineNumber) {
                            previousFrameTop = previousFrame[i].ranges[0];
                        }
                    }
                }
                const bottomLineNumber = linesVisibleRanges[linesVisibleRanges.length - 1].lineNumber;
                if (bottomLineNumber === viewport.endLineNumber) {
                    for (let i = previousFrame.length - 1; !previousFrameBottom && i >= 0; i--) {
                        if (previousFrame[i].lineNumber === bottomLineNumber) {
                            previousFrameBottom = previousFrame[i].ranges[0];
                        }
                    }
                }
                if (previousFrameTop && !previousFrameTop.startStyle) {
                    previousFrameTop = null;
                }
                if (previousFrameBottom && !previousFrameBottom.startStyle) {
                    previousFrameBottom = null;
                }
            }
            for (let i = 0, len = linesVisibleRanges.length; i < len; i++) {
                // We know for a fact that there is precisely one range on each line
                const curLineRange = linesVisibleRanges[i].ranges[0];
                const curLeft = curLineRange.left;
                const curRight = curLineRange.left + curLineRange.width;
                const startStyle = {
                    top: 0 /* CornerStyle.EXTERN */,
                    bottom: 0 /* CornerStyle.EXTERN */
                };
                const endStyle = {
                    top: 0 /* CornerStyle.EXTERN */,
                    bottom: 0 /* CornerStyle.EXTERN */
                };
                if (i > 0) {
                    // Look above
                    const prevLeft = linesVisibleRanges[i - 1].ranges[0].left;
                    const prevRight = linesVisibleRanges[i - 1].ranges[0].left + linesVisibleRanges[i - 1].ranges[0].width;
                    if (abs(curLeft - prevLeft) < epsilon) {
                        startStyle.top = 2 /* CornerStyle.FLAT */;
                    }
                    else if (curLeft > prevLeft) {
                        startStyle.top = 1 /* CornerStyle.INTERN */;
                    }
                    if (abs(curRight - prevRight) < epsilon) {
                        endStyle.top = 2 /* CornerStyle.FLAT */;
                    }
                    else if (prevLeft < curRight && curRight < prevRight) {
                        endStyle.top = 1 /* CornerStyle.INTERN */;
                    }
                }
                else if (previousFrameTop) {
                    // Accept some hiccups near the viewport edges to save on repaints
                    startStyle.top = previousFrameTop.startStyle.top;
                    endStyle.top = previousFrameTop.endStyle.top;
                }
                if (i + 1 < len) {
                    // Look below
                    const nextLeft = linesVisibleRanges[i + 1].ranges[0].left;
                    const nextRight = linesVisibleRanges[i + 1].ranges[0].left + linesVisibleRanges[i + 1].ranges[0].width;
                    if (abs(curLeft - nextLeft) < epsilon) {
                        startStyle.bottom = 2 /* CornerStyle.FLAT */;
                    }
                    else if (nextLeft < curLeft && curLeft < nextRight) {
                        startStyle.bottom = 1 /* CornerStyle.INTERN */;
                    }
                    if (abs(curRight - nextRight) < epsilon) {
                        endStyle.bottom = 2 /* CornerStyle.FLAT */;
                    }
                    else if (curRight < nextRight) {
                        endStyle.bottom = 1 /* CornerStyle.INTERN */;
                    }
                }
                else if (previousFrameBottom) {
                    // Accept some hiccups near the viewport edges to save on repaints
                    startStyle.bottom = previousFrameBottom.startStyle.bottom;
                    endStyle.bottom = previousFrameBottom.endStyle.bottom;
                }
                curLineRange.startStyle = startStyle;
                curLineRange.endStyle = endStyle;
            }
        }
        _getVisibleRangesWithStyle(selection, ctx, previousFrame) {
            const _linesVisibleRanges = ctx.linesVisibleRangesForRange(selection, true) || [];
            const linesVisibleRanges = _linesVisibleRanges.map(toStyled);
            const visibleRangesHaveGaps = this._visibleRangesHaveGaps(linesVisibleRanges);
            if (!visibleRangesHaveGaps && this._roundedSelection) {
                this._enrichVisibleRangesWithStyle(ctx.visibleRange, linesVisibleRanges, previousFrame);
            }
            // The visible ranges are sorted TOP-BOTTOM and LEFT-RIGHT
            return linesVisibleRanges;
        }
        _createSelectionPiece(top, bottom, className, left, width) {
            return ('<div class="cslr '
                + className
                + '" style="'
                + 'top:' + top.toString() + 'px;'
                + 'bottom:' + bottom.toString() + 'px;'
                + 'left:' + left.toString() + 'px;'
                + 'width:' + width.toString() + 'px;'
                + '"></div>');
        }
        _actualRenderOneSelection(output2, visibleStartLineNumber, hasMultipleSelections, visibleRanges) {
            if (visibleRanges.length === 0) {
                return;
            }
            const visibleRangesHaveStyle = !!visibleRanges[0].ranges[0].startStyle;
            const firstLineNumber = visibleRanges[0].lineNumber;
            const lastLineNumber = visibleRanges[visibleRanges.length - 1].lineNumber;
            for (let i = 0, len = visibleRanges.length; i < len; i++) {
                const lineVisibleRanges = visibleRanges[i];
                const lineNumber = lineVisibleRanges.lineNumber;
                const lineIndex = lineNumber - visibleStartLineNumber;
                const top = hasMultipleSelections ? (lineNumber === firstLineNumber ? 1 : 0) : 0;
                const bottom = hasMultipleSelections ? (lineNumber !== firstLineNumber && lineNumber === lastLineNumber ? 1 : 0) : 0;
                let innerCornerOutput = '';
                let restOfSelectionOutput = '';
                for (let j = 0, lenJ = lineVisibleRanges.ranges.length; j < lenJ; j++) {
                    const visibleRange = lineVisibleRanges.ranges[j];
                    if (visibleRangesHaveStyle) {
                        const startStyle = visibleRange.startStyle;
                        const endStyle = visibleRange.endStyle;
                        if (startStyle.top === 1 /* CornerStyle.INTERN */ || startStyle.bottom === 1 /* CornerStyle.INTERN */) {
                            // Reverse rounded corner to the left
                            // First comes the selection (blue layer)
                            innerCornerOutput += this._createSelectionPiece(top, bottom, SelectionsOverlay.SELECTION_CLASS_NAME, visibleRange.left - SelectionsOverlay.ROUNDED_PIECE_WIDTH, SelectionsOverlay.ROUNDED_PIECE_WIDTH);
                            // Second comes the background (white layer) with inverse border radius
                            let className = SelectionsOverlay.EDITOR_BACKGROUND_CLASS_NAME;
                            if (startStyle.top === 1 /* CornerStyle.INTERN */) {
                                className += ' ' + SelectionsOverlay.SELECTION_TOP_RIGHT;
                            }
                            if (startStyle.bottom === 1 /* CornerStyle.INTERN */) {
                                className += ' ' + SelectionsOverlay.SELECTION_BOTTOM_RIGHT;
                            }
                            innerCornerOutput += this._createSelectionPiece(top, bottom, className, visibleRange.left - SelectionsOverlay.ROUNDED_PIECE_WIDTH, SelectionsOverlay.ROUNDED_PIECE_WIDTH);
                        }
                        if (endStyle.top === 1 /* CornerStyle.INTERN */ || endStyle.bottom === 1 /* CornerStyle.INTERN */) {
                            // Reverse rounded corner to the right
                            // First comes the selection (blue layer)
                            innerCornerOutput += this._createSelectionPiece(top, bottom, SelectionsOverlay.SELECTION_CLASS_NAME, visibleRange.left + visibleRange.width, SelectionsOverlay.ROUNDED_PIECE_WIDTH);
                            // Second comes the background (white layer) with inverse border radius
                            let className = SelectionsOverlay.EDITOR_BACKGROUND_CLASS_NAME;
                            if (endStyle.top === 1 /* CornerStyle.INTERN */) {
                                className += ' ' + SelectionsOverlay.SELECTION_TOP_LEFT;
                            }
                            if (endStyle.bottom === 1 /* CornerStyle.INTERN */) {
                                className += ' ' + SelectionsOverlay.SELECTION_BOTTOM_LEFT;
                            }
                            innerCornerOutput += this._createSelectionPiece(top, bottom, className, visibleRange.left + visibleRange.width, SelectionsOverlay.ROUNDED_PIECE_WIDTH);
                        }
                    }
                    let className = SelectionsOverlay.SELECTION_CLASS_NAME;
                    if (visibleRangesHaveStyle) {
                        const startStyle = visibleRange.startStyle;
                        const endStyle = visibleRange.endStyle;
                        if (startStyle.top === 0 /* CornerStyle.EXTERN */) {
                            className += ' ' + SelectionsOverlay.SELECTION_TOP_LEFT;
                        }
                        if (startStyle.bottom === 0 /* CornerStyle.EXTERN */) {
                            className += ' ' + SelectionsOverlay.SELECTION_BOTTOM_LEFT;
                        }
                        if (endStyle.top === 0 /* CornerStyle.EXTERN */) {
                            className += ' ' + SelectionsOverlay.SELECTION_TOP_RIGHT;
                        }
                        if (endStyle.bottom === 0 /* CornerStyle.EXTERN */) {
                            className += ' ' + SelectionsOverlay.SELECTION_BOTTOM_RIGHT;
                        }
                    }
                    restOfSelectionOutput += this._createSelectionPiece(top, bottom, className, visibleRange.left, visibleRange.width);
                }
                output2[lineIndex][0] += innerCornerOutput;
                output2[lineIndex][1] += restOfSelectionOutput;
            }
        }
        prepareRender(ctx) {
            // Build HTML for inner corners separate from HTML for the rest of selections,
            // as the inner corner HTML can interfere with that of other selections.
            // In final render, make sure to place the inner corner HTML before the rest of selection HTML. See issue #77777.
            const output = [];
            const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
            const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
            for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
                const lineIndex = lineNumber - visibleStartLineNumber;
                output[lineIndex] = ['', ''];
            }
            const thisFrameVisibleRangesWithStyle = [];
            for (let i = 0, len = this._selections.length; i < len; i++) {
                const selection = this._selections[i];
                if (selection.isEmpty()) {
                    thisFrameVisibleRangesWithStyle[i] = null;
                    continue;
                }
                const visibleRangesWithStyle = this._getVisibleRangesWithStyle(selection, ctx, this._previousFrameVisibleRangesWithStyle[i]);
                thisFrameVisibleRangesWithStyle[i] = visibleRangesWithStyle;
                this._actualRenderOneSelection(output, visibleStartLineNumber, this._selections.length > 1, visibleRangesWithStyle);
            }
            this._previousFrameVisibleRangesWithStyle = thisFrameVisibleRangesWithStyle;
            this._renderResult = output.map(([internalCorners, restOfSelection]) => internalCorners + restOfSelection);
        }
        render(startLineNumber, lineNumber) {
            if (!this._renderResult) {
                return '';
            }
            const lineIndex = lineNumber - startLineNumber;
            if (lineIndex < 0 || lineIndex >= this._renderResult.length) {
                return '';
            }
            return this._renderResult[lineIndex];
        }
    }
    exports.SelectionsOverlay = SelectionsOverlay;
    (0, themeService_1.registerThemingParticipant)((theme, collector) => {
        const editorSelectionForegroundColor = theme.getColor(colorRegistry_1.editorSelectionForeground);
        if (editorSelectionForegroundColor && !editorSelectionForegroundColor.isTransparent()) {
            collector.addRule(`.monaco-editor .view-line span.inline-selected-text { color: ${editorSelectionForegroundColor}; }`);
        }
    });
    function abs(n) {
        return n < 0 ? -n : n;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[415/*vs/editor/browser/widget/diffEditor/features/overviewRulerFeature*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,39/*vs/base/browser/fastDomNode*/,223/*vs/base/browser/ui/scrollbar/scrollbarState*/,2/*vs/base/common/lifecycle*/,21/*vs/base/common/observable*/,88/*vs/editor/browser/widget/diffEditor/utils*/,9/*vs/editor/common/core/position*/,332/*vs/editor/common/viewModel/overviewZoneManager*/,32/*vs/platform/theme/common/colorRegistry*/,25/*vs/platform/theme/common/themeService*/]), function (require, exports, dom_1, fastDomNode_1, scrollbarState_1, lifecycle_1, observable_1, utils_1, position_1, overviewZoneManager_1, colorRegistry_1, themeService_1) {
    "use strict";
    var OverviewRulerFeature_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.OverviewRulerFeature = void 0;
    let OverviewRulerFeature = class OverviewRulerFeature extends lifecycle_1.Disposable {
        static { OverviewRulerFeature_1 = this; }
        static { this.ONE_OVERVIEW_WIDTH = 15; }
        static { this.ENTIRE_DIFF_OVERVIEW_WIDTH = this.ONE_OVERVIEW_WIDTH * 2; }
        constructor(_editors, _rootElement, _diffModel, _rootWidth, _rootHeight, _modifiedEditorLayoutInfo, _themeService) {
            super();
            this._editors = _editors;
            this._rootElement = _rootElement;
            this._diffModel = _diffModel;
            this._rootWidth = _rootWidth;
            this._rootHeight = _rootHeight;
            this._modifiedEditorLayoutInfo = _modifiedEditorLayoutInfo;
            this._themeService = _themeService;
            this.width = OverviewRulerFeature_1.ENTIRE_DIFF_OVERVIEW_WIDTH;
            const currentColorTheme = (0, observable_1.observableFromEvent)(this._themeService.onDidColorThemeChange, () => this._themeService.getColorTheme());
            const currentColors = (0, observable_1.derived)(reader => {
                /** @description colors */
                const theme = currentColorTheme.read(reader);
                const insertColor = theme.getColor(colorRegistry_1.diffOverviewRulerInserted) || (theme.getColor(colorRegistry_1.diffInserted) || colorRegistry_1.defaultInsertColor).transparent(2);
                const removeColor = theme.getColor(colorRegistry_1.diffOverviewRulerRemoved) || (theme.getColor(colorRegistry_1.diffRemoved) || colorRegistry_1.defaultRemoveColor).transparent(2);
                return { insertColor, removeColor };
            });
            const viewportDomElement = (0, fastDomNode_1.createFastDomNode)(document.createElement('div'));
            viewportDomElement.setClassName('diffViewport');
            viewportDomElement.setPosition('absolute');
            const diffOverviewRoot = (0, dom_1.h)('div.diffOverview', {
                style: { position: 'absolute', top: '0px', width: OverviewRulerFeature_1.ENTIRE_DIFF_OVERVIEW_WIDTH + 'px' }
            }).root;
            this._register((0, utils_1.appendRemoveOnDispose)(diffOverviewRoot, viewportDomElement.domNode));
            this._register((0, dom_1.addStandardDisposableListener)(diffOverviewRoot, dom_1.EventType.POINTER_DOWN, (e) => {
                this._editors.modified.delegateVerticalScrollbarPointerDown(e);
            }));
            this._register((0, dom_1.addDisposableListener)(diffOverviewRoot, dom_1.EventType.MOUSE_WHEEL, (e) => {
                this._editors.modified.delegateScrollFromMouseWheelEvent(e);
            }, { passive: false }));
            this._register((0, utils_1.appendRemoveOnDispose)(this._rootElement, diffOverviewRoot));
            this._register((0, observable_1.autorunWithStore)((reader, store) => {
                /** @description recreate overview rules when model changes */
                const m = this._diffModel.read(reader);
                const originalOverviewRuler = this._editors.original.createOverviewRuler('original diffOverviewRuler');
                if (originalOverviewRuler) {
                    store.add(originalOverviewRuler);
                    store.add((0, utils_1.appendRemoveOnDispose)(diffOverviewRoot, originalOverviewRuler.getDomNode()));
                }
                const modifiedOverviewRuler = this._editors.modified.createOverviewRuler('modified diffOverviewRuler');
                if (modifiedOverviewRuler) {
                    store.add(modifiedOverviewRuler);
                    store.add((0, utils_1.appendRemoveOnDispose)(diffOverviewRoot, modifiedOverviewRuler.getDomNode()));
                }
                if (!originalOverviewRuler || !modifiedOverviewRuler) {
                    // probably no model
                    return;
                }
                const origViewZonesChanged = (0, observable_1.observableSignalFromEvent)('viewZoneChanged', this._editors.original.onDidChangeViewZones);
                const modViewZonesChanged = (0, observable_1.observableSignalFromEvent)('viewZoneChanged', this._editors.modified.onDidChangeViewZones);
                const origHiddenRangesChanged = (0, observable_1.observableSignalFromEvent)('hiddenRangesChanged', this._editors.original.onDidChangeHiddenAreas);
                const modHiddenRangesChanged = (0, observable_1.observableSignalFromEvent)('hiddenRangesChanged', this._editors.modified.onDidChangeHiddenAreas);
                store.add((0, observable_1.autorun)(reader => {
                    /** @description set overview ruler zones */
                    origViewZonesChanged.read(reader);
                    modViewZonesChanged.read(reader);
                    origHiddenRangesChanged.read(reader);
                    modHiddenRangesChanged.read(reader);
                    const colors = currentColors.read(reader);
                    const diff = m?.diff.read(reader)?.mappings;
                    function createZones(ranges, color, editor) {
                        const vm = editor._getViewModel();
                        if (!vm) {
                            return [];
                        }
                        return ranges
                            .filter(d => d.length > 0)
                            .map(r => {
                            const start = vm.coordinatesConverter.convertModelPositionToViewPosition(new position_1.Position(r.startLineNumber, 1));
                            const end = vm.coordinatesConverter.convertModelPositionToViewPosition(new position_1.Position(r.endLineNumberExclusive, 1));
                            // By computing the lineCount, we won't ask the view model later for the bottom vertical position.
                            // (The view model will take into account the alignment viewzones, which will give
                            // modifications and deletetions always the same height.)
                            const lineCount = end.lineNumber - start.lineNumber;
                            return new overviewZoneManager_1.OverviewRulerZone(start.lineNumber, end.lineNumber, lineCount, color.toString());
                        });
                    }
                    const originalZones = createZones((diff || []).map(d => d.lineRangeMapping.original), colors.removeColor, this._editors.original);
                    const modifiedZones = createZones((diff || []).map(d => d.lineRangeMapping.modified), colors.insertColor, this._editors.modified);
                    originalOverviewRuler?.setZones(originalZones);
                    modifiedOverviewRuler?.setZones(modifiedZones);
                }));
                store.add((0, observable_1.autorun)(reader => {
                    /** @description layout overview ruler */
                    const height = this._rootHeight.read(reader);
                    const width = this._rootWidth.read(reader);
                    const layoutInfo = this._modifiedEditorLayoutInfo.read(reader);
                    if (layoutInfo) {
                        const freeSpace = OverviewRulerFeature_1.ENTIRE_DIFF_OVERVIEW_WIDTH - 2 * OverviewRulerFeature_1.ONE_OVERVIEW_WIDTH;
                        originalOverviewRuler.setLayout({
                            top: 0,
                            height: height,
                            right: freeSpace + OverviewRulerFeature_1.ONE_OVERVIEW_WIDTH,
                            width: OverviewRulerFeature_1.ONE_OVERVIEW_WIDTH,
                        });
                        modifiedOverviewRuler.setLayout({
                            top: 0,
                            height: height,
                            right: 0,
                            width: OverviewRulerFeature_1.ONE_OVERVIEW_WIDTH,
                        });
                        const scrollTop = this._editors.modifiedScrollTop.read(reader);
                        const scrollHeight = this._editors.modifiedScrollHeight.read(reader);
                        const scrollBarOptions = this._editors.modified.getOption(104 /* EditorOption.scrollbar */);
                        const state = new scrollbarState_1.ScrollbarState(scrollBarOptions.verticalHasArrows ? scrollBarOptions.arrowSize : 0, scrollBarOptions.verticalScrollbarSize, 0, layoutInfo.height, scrollHeight, scrollTop);
                        viewportDomElement.setTop(state.getSliderPosition());
                        viewportDomElement.setHeight(state.getSliderSize());
                    }
                    else {
                        viewportDomElement.setTop(0);
                        viewportDomElement.setHeight(0);
                    }
                    diffOverviewRoot.style.height = height + 'px';
                    diffOverviewRoot.style.left = (width - OverviewRulerFeature_1.ENTIRE_DIFF_OVERVIEW_WIDTH) + 'px';
                    viewportDomElement.setWidth(OverviewRulerFeature_1.ENTIRE_DIFF_OVERVIEW_WIDTH);
                }));
            }));
        }
    };
    exports.OverviewRulerFeature = OverviewRulerFeature;
    exports.OverviewRulerFeature = OverviewRulerFeature = OverviewRulerFeature_1 = __decorate([
        __param(6, themeService_1.IThemeService)
    ], OverviewRulerFeature);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[775/*vs/editor/browser/widget/diffEditor/components/diffEditorEditors*/], __M([1/*require*/,0/*exports*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,21/*vs/base/common/observable*/,112/*vs/editor/browser/observableCodeEditor*/,415/*vs/editor/browser/widget/diffEditor/features/overviewRulerFeature*/,37/*vs/editor/common/config/editorOptions*/,9/*vs/editor/common/core/position*/,3/*vs/nls*/,7/*vs/platform/instantiation/common/instantiation*/,31/*vs/platform/keybinding/common/keybinding*/]), function (require, exports, event_1, lifecycle_1, observable_1, observableCodeEditor_1, overviewRulerFeature_1, editorOptions_1, position_1, nls_1, instantiation_1, keybinding_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DiffEditorEditors = void 0;
    let DiffEditorEditors = class DiffEditorEditors extends lifecycle_1.Disposable {
        get onDidContentSizeChange() { return this._onDidContentSizeChange.event; }
        constructor(originalEditorElement, modifiedEditorElement, _options, _argCodeEditorWidgetOptions, _createInnerEditor, _instantiationService, _keybindingService) {
            super();
            this.originalEditorElement = originalEditorElement;
            this.modifiedEditorElement = modifiedEditorElement;
            this._options = _options;
            this._argCodeEditorWidgetOptions = _argCodeEditorWidgetOptions;
            this._createInnerEditor = _createInnerEditor;
            this._instantiationService = _instantiationService;
            this._keybindingService = _keybindingService;
            this.original = this._register(this._createLeftHandSideEditor(this._options.editorOptions.get(), this._argCodeEditorWidgetOptions.originalEditor || {}));
            this.modified = this._register(this._createRightHandSideEditor(this._options.editorOptions.get(), this._argCodeEditorWidgetOptions.modifiedEditor || {}));
            this._onDidContentSizeChange = this._register(new event_1.Emitter());
            this.modifiedScrollTop = (0, observable_1.observableFromEvent)(this, this.modified.onDidScrollChange, () => /** @description modified.getScrollTop */ this.modified.getScrollTop());
            this.modifiedScrollHeight = (0, observable_1.observableFromEvent)(this, this.modified.onDidScrollChange, () => /** @description modified.getScrollHeight */ this.modified.getScrollHeight());
            this.modifiedObs = (0, observableCodeEditor_1.observableCodeEditor)(this.modified);
            this.originalObs = (0, observableCodeEditor_1.observableCodeEditor)(this.original);
            this.modifiedModel = this.modifiedObs.model;
            this.modifiedSelections = (0, observable_1.observableFromEvent)(this, this.modified.onDidChangeCursorSelection, () => this.modified.getSelections() ?? []);
            this.modifiedCursor = (0, observable_1.derivedOpts)({ owner: this, equalsFn: position_1.Position.equals }, reader => this.modifiedSelections.read(reader)[0]?.getPosition() ?? new position_1.Position(1, 1));
            this.originalCursor = (0, observable_1.observableFromEvent)(this, this.original.onDidChangeCursorPosition, () => this.original.getPosition() ?? new position_1.Position(1, 1));
            this._argCodeEditorWidgetOptions = null;
            this._register((0, observable_1.autorunHandleChanges)({
                createEmptyChangeSummary: () => ({}),
                handleChange: (ctx, changeSummary) => {
                    if (ctx.didChange(_options.editorOptions)) {
                        Object.assign(changeSummary, ctx.change.changedOptions);
                    }
                    return true;
                }
            }, (reader, changeSummary) => {
                /** @description update editor options */
                _options.editorOptions.read(reader);
                this._options.renderSideBySide.read(reader);
                this.modified.updateOptions(this._adjustOptionsForRightHandSide(reader, changeSummary));
                this.original.updateOptions(this._adjustOptionsForLeftHandSide(reader, changeSummary));
            }));
        }
        _createLeftHandSideEditor(options, codeEditorWidgetOptions) {
            const leftHandSideOptions = this._adjustOptionsForLeftHandSide(undefined, options);
            const editor = this._constructInnerEditor(this._instantiationService, this.originalEditorElement, leftHandSideOptions, codeEditorWidgetOptions);
            editor.setContextValue('isInDiffLeftEditor', true);
            return editor;
        }
        _createRightHandSideEditor(options, codeEditorWidgetOptions) {
            const rightHandSideOptions = this._adjustOptionsForRightHandSide(undefined, options);
            const editor = this._constructInnerEditor(this._instantiationService, this.modifiedEditorElement, rightHandSideOptions, codeEditorWidgetOptions);
            editor.setContextValue('isInDiffRightEditor', true);
            return editor;
        }
        _constructInnerEditor(instantiationService, container, options, editorWidgetOptions) {
            const editor = this._createInnerEditor(instantiationService, container, options, editorWidgetOptions);
            this._register(editor.onDidContentSizeChange(e => {
                const width = this.original.getContentWidth() + this.modified.getContentWidth() + overviewRulerFeature_1.OverviewRulerFeature.ENTIRE_DIFF_OVERVIEW_WIDTH;
                const height = Math.max(this.modified.getContentHeight(), this.original.getContentHeight());
                this._onDidContentSizeChange.fire({
                    contentHeight: height,
                    contentWidth: width,
                    contentHeightChanged: e.contentHeightChanged,
                    contentWidthChanged: e.contentWidthChanged
                });
            }));
            return editor;
        }
        _adjustOptionsForLeftHandSide(_reader, changedOptions) {
            const result = this._adjustOptionsForSubEditor(changedOptions);
            if (!this._options.renderSideBySide.get()) {
                // never wrap hidden editor
                result.wordWrapOverride1 = 'off';
                result.wordWrapOverride2 = 'off';
                result.stickyScroll = { enabled: false };
                // Disable unicode highlighting for the original side in inline mode, as they are not shown anyway.
                result.unicodeHighlight = { nonBasicASCII: false, ambiguousCharacters: false, invisibleCharacters: false };
            }
            else {
                result.unicodeHighlight = this._options.editorOptions.get().unicodeHighlight || {};
                result.wordWrapOverride1 = this._options.diffWordWrap.get();
            }
            result.glyphMargin = this._options.renderSideBySide.get();
            if (changedOptions.originalAriaLabel) {
                result.ariaLabel = changedOptions.originalAriaLabel;
            }
            result.ariaLabel = this._updateAriaLabel(result.ariaLabel);
            result.readOnly = !this._options.originalEditable.get();
            result.dropIntoEditor = { enabled: !result.readOnly };
            result.extraEditorClassName = 'original-in-monaco-diff-editor';
            return result;
        }
        _adjustOptionsForRightHandSide(reader, changedOptions) {
            const result = this._adjustOptionsForSubEditor(changedOptions);
            if (changedOptions.modifiedAriaLabel) {
                result.ariaLabel = changedOptions.modifiedAriaLabel;
            }
            result.ariaLabel = this._updateAriaLabel(result.ariaLabel);
            result.wordWrapOverride1 = this._options.diffWordWrap.get();
            result.revealHorizontalRightPadding = editorOptions_1.EditorOptions.revealHorizontalRightPadding.defaultValue + overviewRulerFeature_1.OverviewRulerFeature.ENTIRE_DIFF_OVERVIEW_WIDTH;
            result.scrollbar.verticalHasArrows = false;
            result.extraEditorClassName = 'modified-in-monaco-diff-editor';
            return result;
        }
        _adjustOptionsForSubEditor(options) {
            const clonedOptions = {
                ...options,
                dimension: {
                    height: 0,
                    width: 0
                },
            };
            clonedOptions.inDiffEditor = true;
            clonedOptions.automaticLayout = false;
            // Clone scrollbar options before changing them
            clonedOptions.scrollbar = { ...(clonedOptions.scrollbar || {}) };
            clonedOptions.folding = false;
            clonedOptions.codeLens = this._options.diffCodeLens.get();
            clonedOptions.fixedOverflowWidgets = true;
            // Clone minimap options before changing them
            clonedOptions.minimap = { ...(clonedOptions.minimap || {}) };
            clonedOptions.minimap.enabled = false;
            if (this._options.hideUnchangedRegions.get()) {
                clonedOptions.stickyScroll = { enabled: false };
            }
            else {
                clonedOptions.stickyScroll = this._options.editorOptions.get().stickyScroll;
            }
            return clonedOptions;
        }
        _updateAriaLabel(ariaLabel) {
            if (!ariaLabel) {
                ariaLabel = '';
            }
            const ariaNavigationTip = (0, nls_1.localize)(98, ' use {0} to open the accessibility help.', this._keybindingService.lookupKeybinding('editor.action.accessibilityHelp')?.getAriaLabel());
            if (this._options.accessibilityVerbose.get()) {
                return ariaLabel + ariaNavigationTip;
            }
            else if (ariaLabel) {
                return ariaLabel.replaceAll(ariaNavigationTip, '');
            }
            return '';
        }
    };
    exports.DiffEditorEditors = DiffEditorEditors;
    exports.DiffEditorEditors = DiffEditorEditors = __decorate([
        __param(5, instantiation_1.IInstantiationService),
        __param(6, keybinding_1.IKeybindingService)
    ], DiffEditorEditors);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[80/*vs/editor/common/core/editorColorRegistry*/], __M([1/*require*/,0/*exports*/,3/*vs/nls*/,33/*vs/base/common/color*/,32/*vs/platform/theme/common/colorRegistry*/,25/*vs/platform/theme/common/themeService*/]), function (require, exports, nls, color_1, colorRegistry_1, themeService_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.editorUnicodeHighlightBackground = exports.editorUnicodeHighlightBorder = exports.editorBracketPairGuideActiveBackground6 = exports.editorBracketPairGuideActiveBackground5 = exports.editorBracketPairGuideActiveBackground4 = exports.editorBracketPairGuideActiveBackground3 = exports.editorBracketPairGuideActiveBackground2 = exports.editorBracketPairGuideActiveBackground1 = exports.editorBracketPairGuideBackground6 = exports.editorBracketPairGuideBackground5 = exports.editorBracketPairGuideBackground4 = exports.editorBracketPairGuideBackground3 = exports.editorBracketPairGuideBackground2 = exports.editorBracketPairGuideBackground1 = exports.editorBracketHighlightingUnexpectedBracketForeground = exports.editorBracketHighlightingForeground6 = exports.editorBracketHighlightingForeground5 = exports.editorBracketHighlightingForeground4 = exports.editorBracketHighlightingForeground3 = exports.editorBracketHighlightingForeground2 = exports.editorBracketHighlightingForeground1 = exports.overviewRulerInfo = exports.overviewRulerWarning = exports.overviewRulerError = exports.overviewRulerRangeHighlight = exports.ghostTextBackground = exports.ghostTextForeground = exports.ghostTextBorder = exports.editorUnnecessaryCodeOpacity = exports.editorUnnecessaryCodeBorder = exports.editorGutter = exports.editorOverviewRulerBackground = exports.editorOverviewRulerBorder = exports.editorBracketMatchBorder = exports.editorBracketMatchBackground = exports.editorCodeLensForeground = exports.editorRuler = exports.editorDimmedLineNumber = exports.editorActiveLineNumber = exports.editorActiveIndentGuide6 = exports.editorActiveIndentGuide5 = exports.editorActiveIndentGuide4 = exports.editorActiveIndentGuide3 = exports.editorActiveIndentGuide2 = exports.editorActiveIndentGuide1 = exports.editorIndentGuide6 = exports.editorIndentGuide5 = exports.editorIndentGuide4 = exports.editorIndentGuide3 = exports.editorIndentGuide2 = exports.editorIndentGuide1 = exports.deprecatedEditorActiveIndentGuides = exports.deprecatedEditorIndentGuides = exports.editorLineNumbers = exports.editorWhitespaces = exports.editorMultiCursorSecondaryBackground = exports.editorMultiCursorSecondaryForeground = exports.editorMultiCursorPrimaryBackground = exports.editorMultiCursorPrimaryForeground = exports.editorCursorBackground = exports.editorCursorForeground = exports.editorSymbolHighlightBorder = exports.editorSymbolHighlight = exports.editorRangeHighlightBorder = exports.editorRangeHighlight = exports.editorLineHighlightBorder = exports.editorLineHighlight = void 0;
    /**
     * Definition of the editor colors
     */
    exports.editorLineHighlight = (0, colorRegistry_1.registerColor)('editor.lineHighlightBackground', null, nls.localize(551, 'Background color for the highlight of line at the cursor position.'));
    exports.editorLineHighlightBorder = (0, colorRegistry_1.registerColor)('editor.lineHighlightBorder', { dark: '#282828', light: '#eeeeee', hcDark: '#f38518', hcLight: colorRegistry_1.contrastBorder }, nls.localize(552, 'Background color for the border around the line at the cursor position.'));
    exports.editorRangeHighlight = (0, colorRegistry_1.registerColor)('editor.rangeHighlightBackground', { dark: '#ffffff0b', light: '#fdff0033', hcDark: null, hcLight: null }, nls.localize(553, 'Background color of highlighted ranges, like by quick open and find features. The color must not be opaque so as not to hide underlying decorations.'), true);
    exports.editorRangeHighlightBorder = (0, colorRegistry_1.registerColor)('editor.rangeHighlightBorder', { dark: null, light: null, hcDark: colorRegistry_1.activeContrastBorder, hcLight: colorRegistry_1.activeContrastBorder }, nls.localize(554, 'Background color of the border around highlighted ranges.'));
    exports.editorSymbolHighlight = (0, colorRegistry_1.registerColor)('editor.symbolHighlightBackground', { dark: colorRegistry_1.editorFindMatchHighlight, light: colorRegistry_1.editorFindMatchHighlight, hcDark: null, hcLight: null }, nls.localize(555, 'Background color of highlighted symbol, like for go to definition or go next/previous symbol. The color must not be opaque so as not to hide underlying decorations.'), true);
    exports.editorSymbolHighlightBorder = (0, colorRegistry_1.registerColor)('editor.symbolHighlightBorder', { dark: null, light: null, hcDark: colorRegistry_1.activeContrastBorder, hcLight: colorRegistry_1.activeContrastBorder }, nls.localize(556, 'Background color of the border around highlighted symbols.'));
    exports.editorCursorForeground = (0, colorRegistry_1.registerColor)('editorCursor.foreground', { dark: '#AEAFAD', light: color_1.Color.black, hcDark: color_1.Color.white, hcLight: '#0F4A85' }, nls.localize(557, 'Color of the editor cursor.'));
    exports.editorCursorBackground = (0, colorRegistry_1.registerColor)('editorCursor.background', null, nls.localize(558, 'The background color of the editor cursor. Allows customizing the color of a character overlapped by a block cursor.'));
    exports.editorMultiCursorPrimaryForeground = (0, colorRegistry_1.registerColor)('editorMultiCursor.primary.foreground', exports.editorCursorForeground, nls.localize(559, 'Color of the primary editor cursor when multiple cursors are present.'));
    exports.editorMultiCursorPrimaryBackground = (0, colorRegistry_1.registerColor)('editorMultiCursor.primary.background', exports.editorCursorBackground, nls.localize(560, 'The background color of the primary editor cursor when multiple cursors are present. Allows customizing the color of a character overlapped by a block cursor.'));
    exports.editorMultiCursorSecondaryForeground = (0, colorRegistry_1.registerColor)('editorMultiCursor.secondary.foreground', exports.editorCursorForeground, nls.localize(561, 'Color of secondary editor cursors when multiple cursors are present.'));
    exports.editorMultiCursorSecondaryBackground = (0, colorRegistry_1.registerColor)('editorMultiCursor.secondary.background', exports.editorCursorBackground, nls.localize(562, 'The background color of secondary editor cursors when multiple cursors are present. Allows customizing the color of a character overlapped by a block cursor.'));
    exports.editorWhitespaces = (0, colorRegistry_1.registerColor)('editorWhitespace.foreground', { dark: '#e3e4e229', light: '#33333333', hcDark: '#e3e4e229', hcLight: '#CCCCCC' }, nls.localize(563, 'Color of whitespace characters in the editor.'));
    exports.editorLineNumbers = (0, colorRegistry_1.registerColor)('editorLineNumber.foreground', { dark: '#858585', light: '#237893', hcDark: color_1.Color.white, hcLight: '#292929' }, nls.localize(564, 'Color of editor line numbers.'));
    exports.deprecatedEditorIndentGuides = (0, colorRegistry_1.registerColor)('editorIndentGuide.background', exports.editorWhitespaces, nls.localize(565, 'Color of the editor indentation guides.'), false, nls.localize(566, '\'editorIndentGuide.background\' is deprecated. Use \'editorIndentGuide.background1\' instead.'));
    exports.deprecatedEditorActiveIndentGuides = (0, colorRegistry_1.registerColor)('editorIndentGuide.activeBackground', exports.editorWhitespaces, nls.localize(567, 'Color of the active editor indentation guides.'), false, nls.localize(568, '\'editorIndentGuide.activeBackground\' is deprecated. Use \'editorIndentGuide.activeBackground1\' instead.'));
    exports.editorIndentGuide1 = (0, colorRegistry_1.registerColor)('editorIndentGuide.background1', exports.deprecatedEditorIndentGuides, nls.localize(569, 'Color of the editor indentation guides (1).'));
    exports.editorIndentGuide2 = (0, colorRegistry_1.registerColor)('editorIndentGuide.background2', '#00000000', nls.localize(570, 'Color of the editor indentation guides (2).'));
    exports.editorIndentGuide3 = (0, colorRegistry_1.registerColor)('editorIndentGuide.background3', '#00000000', nls.localize(571, 'Color of the editor indentation guides (3).'));
    exports.editorIndentGuide4 = (0, colorRegistry_1.registerColor)('editorIndentGuide.background4', '#00000000', nls.localize(572, 'Color of the editor indentation guides (4).'));
    exports.editorIndentGuide5 = (0, colorRegistry_1.registerColor)('editorIndentGuide.background5', '#00000000', nls.localize(573, 'Color of the editor indentation guides (5).'));
    exports.editorIndentGuide6 = (0, colorRegistry_1.registerColor)('editorIndentGuide.background6', '#00000000', nls.localize(574, 'Color of the editor indentation guides (6).'));
    exports.editorActiveIndentGuide1 = (0, colorRegistry_1.registerColor)('editorIndentGuide.activeBackground1', exports.deprecatedEditorActiveIndentGuides, nls.localize(575, 'Color of the active editor indentation guides (1).'));
    exports.editorActiveIndentGuide2 = (0, colorRegistry_1.registerColor)('editorIndentGuide.activeBackground2', '#00000000', nls.localize(576, 'Color of the active editor indentation guides (2).'));
    exports.editorActiveIndentGuide3 = (0, colorRegistry_1.registerColor)('editorIndentGuide.activeBackground3', '#00000000', nls.localize(577, 'Color of the active editor indentation guides (3).'));
    exports.editorActiveIndentGuide4 = (0, colorRegistry_1.registerColor)('editorIndentGuide.activeBackground4', '#00000000', nls.localize(578, 'Color of the active editor indentation guides (4).'));
    exports.editorActiveIndentGuide5 = (0, colorRegistry_1.registerColor)('editorIndentGuide.activeBackground5', '#00000000', nls.localize(579, 'Color of the active editor indentation guides (5).'));
    exports.editorActiveIndentGuide6 = (0, colorRegistry_1.registerColor)('editorIndentGuide.activeBackground6', '#00000000', nls.localize(580, 'Color of the active editor indentation guides (6).'));
    const deprecatedEditorActiveLineNumber = (0, colorRegistry_1.registerColor)('editorActiveLineNumber.foreground', { dark: '#c6c6c6', light: '#0B216F', hcDark: colorRegistry_1.activeContrastBorder, hcLight: colorRegistry_1.activeContrastBorder }, nls.localize(581, 'Color of editor active line number'), false, nls.localize(582, 'Id is deprecated. Use \'editorLineNumber.activeForeground\' instead.'));
    exports.editorActiveLineNumber = (0, colorRegistry_1.registerColor)('editorLineNumber.activeForeground', deprecatedEditorActiveLineNumber, nls.localize(583, 'Color of editor active line number'));
    exports.editorDimmedLineNumber = (0, colorRegistry_1.registerColor)('editorLineNumber.dimmedForeground', null, nls.localize(584, 'Color of the final editor line when editor.renderFinalNewline is set to dimmed.'));
    exports.editorRuler = (0, colorRegistry_1.registerColor)('editorRuler.foreground', { dark: '#5A5A5A', light: color_1.Color.lightgrey, hcDark: color_1.Color.white, hcLight: '#292929' }, nls.localize(585, 'Color of the editor rulers.'));
    exports.editorCodeLensForeground = (0, colorRegistry_1.registerColor)('editorCodeLens.foreground', { dark: '#999999', light: '#919191', hcDark: '#999999', hcLight: '#292929' }, nls.localize(586, 'Foreground color of editor CodeLens'));
    exports.editorBracketMatchBackground = (0, colorRegistry_1.registerColor)('editorBracketMatch.background', { dark: '#0064001a', light: '#0064001a', hcDark: '#0064001a', hcLight: '#0000' }, nls.localize(587, 'Background color behind matching brackets'));
    exports.editorBracketMatchBorder = (0, colorRegistry_1.registerColor)('editorBracketMatch.border', { dark: '#888', light: '#B9B9B9', hcDark: colorRegistry_1.contrastBorder, hcLight: colorRegistry_1.contrastBorder }, nls.localize(588, 'Color for matching brackets boxes'));
    exports.editorOverviewRulerBorder = (0, colorRegistry_1.registerColor)('editorOverviewRuler.border', { dark: '#7f7f7f4d', light: '#7f7f7f4d', hcDark: '#7f7f7f4d', hcLight: '#666666' }, nls.localize(589, 'Color of the overview ruler border.'));
    exports.editorOverviewRulerBackground = (0, colorRegistry_1.registerColor)('editorOverviewRuler.background', null, nls.localize(590, 'Background color of the editor overview ruler.'));
    exports.editorGutter = (0, colorRegistry_1.registerColor)('editorGutter.background', colorRegistry_1.editorBackground, nls.localize(591, 'Background color of the editor gutter. The gutter contains the glyph margins and the line numbers.'));
    exports.editorUnnecessaryCodeBorder = (0, colorRegistry_1.registerColor)('editorUnnecessaryCode.border', { dark: null, light: null, hcDark: color_1.Color.fromHex('#fff').transparent(0.8), hcLight: colorRegistry_1.contrastBorder }, nls.localize(592, 'Border color of unnecessary (unused) source code in the editor.'));
    exports.editorUnnecessaryCodeOpacity = (0, colorRegistry_1.registerColor)('editorUnnecessaryCode.opacity', { dark: color_1.Color.fromHex('#000a'), light: color_1.Color.fromHex('#0007'), hcDark: null, hcLight: null }, nls.localize(593, 'Opacity of unnecessary (unused) source code in the editor. For example, "#000000c0" will render the code with 75% opacity. For high contrast themes, use the  \'editorUnnecessaryCode.border\' theme color to underline unnecessary code instead of fading it out.'));
    exports.ghostTextBorder = (0, colorRegistry_1.registerColor)('editorGhostText.border', { dark: null, light: null, hcDark: color_1.Color.fromHex('#fff').transparent(0.8), hcLight: color_1.Color.fromHex('#292929').transparent(0.8) }, nls.localize(594, 'Border color of ghost text in the editor.'));
    exports.ghostTextForeground = (0, colorRegistry_1.registerColor)('editorGhostText.foreground', { dark: color_1.Color.fromHex('#ffffff56'), light: color_1.Color.fromHex('#0007'), hcDark: null, hcLight: null }, nls.localize(595, 'Foreground color of the ghost text in the editor.'));
    exports.ghostTextBackground = (0, colorRegistry_1.registerColor)('editorGhostText.background', null, nls.localize(596, 'Background color of the ghost text in the editor.'));
    const rulerRangeDefault = new color_1.Color(new color_1.RGBA(0, 122, 204, 0.6));
    exports.overviewRulerRangeHighlight = (0, colorRegistry_1.registerColor)('editorOverviewRuler.rangeHighlightForeground', rulerRangeDefault, nls.localize(597, 'Overview ruler marker color for range highlights. The color must not be opaque so as not to hide underlying decorations.'), true);
    exports.overviewRulerError = (0, colorRegistry_1.registerColor)('editorOverviewRuler.errorForeground', { dark: new color_1.Color(new color_1.RGBA(255, 18, 18, 0.7)), light: new color_1.Color(new color_1.RGBA(255, 18, 18, 0.7)), hcDark: new color_1.Color(new color_1.RGBA(255, 50, 50, 1)), hcLight: '#B5200D' }, nls.localize(598, 'Overview ruler marker color for errors.'));
    exports.overviewRulerWarning = (0, colorRegistry_1.registerColor)('editorOverviewRuler.warningForeground', { dark: colorRegistry_1.editorWarningForeground, light: colorRegistry_1.editorWarningForeground, hcDark: colorRegistry_1.editorWarningBorder, hcLight: colorRegistry_1.editorWarningBorder }, nls.localize(599, 'Overview ruler marker color for warnings.'));
    exports.overviewRulerInfo = (0, colorRegistry_1.registerColor)('editorOverviewRuler.infoForeground', { dark: colorRegistry_1.editorInfoForeground, light: colorRegistry_1.editorInfoForeground, hcDark: colorRegistry_1.editorInfoBorder, hcLight: colorRegistry_1.editorInfoBorder }, nls.localize(600, 'Overview ruler marker color for infos.'));
    exports.editorBracketHighlightingForeground1 = (0, colorRegistry_1.registerColor)('editorBracketHighlight.foreground1', { dark: '#FFD700', light: '#0431FAFF', hcDark: '#FFD700', hcLight: '#0431FAFF' }, nls.localize(601, 'Foreground color of brackets (1). Requires enabling bracket pair colorization.'));
    exports.editorBracketHighlightingForeground2 = (0, colorRegistry_1.registerColor)('editorBracketHighlight.foreground2', { dark: '#DA70D6', light: '#319331FF', hcDark: '#DA70D6', hcLight: '#319331FF' }, nls.localize(602, 'Foreground color of brackets (2). Requires enabling bracket pair colorization.'));
    exports.editorBracketHighlightingForeground3 = (0, colorRegistry_1.registerColor)('editorBracketHighlight.foreground3', { dark: '#179FFF', light: '#7B3814FF', hcDark: '#87CEFA', hcLight: '#7B3814FF' }, nls.localize(603, 'Foreground color of brackets (3). Requires enabling bracket pair colorization.'));
    exports.editorBracketHighlightingForeground4 = (0, colorRegistry_1.registerColor)('editorBracketHighlight.foreground4', '#00000000', nls.localize(604, 'Foreground color of brackets (4). Requires enabling bracket pair colorization.'));
    exports.editorBracketHighlightingForeground5 = (0, colorRegistry_1.registerColor)('editorBracketHighlight.foreground5', '#00000000', nls.localize(605, 'Foreground color of brackets (5). Requires enabling bracket pair colorization.'));
    exports.editorBracketHighlightingForeground6 = (0, colorRegistry_1.registerColor)('editorBracketHighlight.foreground6', '#00000000', nls.localize(606, 'Foreground color of brackets (6). Requires enabling bracket pair colorization.'));
    exports.editorBracketHighlightingUnexpectedBracketForeground = (0, colorRegistry_1.registerColor)('editorBracketHighlight.unexpectedBracket.foreground', { dark: new color_1.Color(new color_1.RGBA(255, 18, 18, 0.8)), light: new color_1.Color(new color_1.RGBA(255, 18, 18, 0.8)), hcDark: 'new Color(new RGBA(255, 50, 50, 1))', hcLight: '#B5200D' }, nls.localize(607, 'Foreground color of unexpected brackets.'));
    exports.editorBracketPairGuideBackground1 = (0, colorRegistry_1.registerColor)('editorBracketPairGuide.background1', '#00000000', nls.localize(608, 'Background color of inactive bracket pair guides (1). Requires enabling bracket pair guides.'));
    exports.editorBracketPairGuideBackground2 = (0, colorRegistry_1.registerColor)('editorBracketPairGuide.background2', '#00000000', nls.localize(609, 'Background color of inactive bracket pair guides (2). Requires enabling bracket pair guides.'));
    exports.editorBracketPairGuideBackground3 = (0, colorRegistry_1.registerColor)('editorBracketPairGuide.background3', '#00000000', nls.localize(610, 'Background color of inactive bracket pair guides (3). Requires enabling bracket pair guides.'));
    exports.editorBracketPairGuideBackground4 = (0, colorRegistry_1.registerColor)('editorBracketPairGuide.background4', '#00000000', nls.localize(611, 'Background color of inactive bracket pair guides (4). Requires enabling bracket pair guides.'));
    exports.editorBracketPairGuideBackground5 = (0, colorRegistry_1.registerColor)('editorBracketPairGuide.background5', '#00000000', nls.localize(612, 'Background color of inactive bracket pair guides (5). Requires enabling bracket pair guides.'));
    exports.editorBracketPairGuideBackground6 = (0, colorRegistry_1.registerColor)('editorBracketPairGuide.background6', '#00000000', nls.localize(613, 'Background color of inactive bracket pair guides (6). Requires enabling bracket pair guides.'));
    exports.editorBracketPairGuideActiveBackground1 = (0, colorRegistry_1.registerColor)('editorBracketPairGuide.activeBackground1', '#00000000', nls.localize(614, 'Background color of active bracket pair guides (1). Requires enabling bracket pair guides.'));
    exports.editorBracketPairGuideActiveBackground2 = (0, colorRegistry_1.registerColor)('editorBracketPairGuide.activeBackground2', '#00000000', nls.localize(615, 'Background color of active bracket pair guides (2). Requires enabling bracket pair guides.'));
    exports.editorBracketPairGuideActiveBackground3 = (0, colorRegistry_1.registerColor)('editorBracketPairGuide.activeBackground3', '#00000000', nls.localize(616, 'Background color of active bracket pair guides (3). Requires enabling bracket pair guides.'));
    exports.editorBracketPairGuideActiveBackground4 = (0, colorRegistry_1.registerColor)('editorBracketPairGuide.activeBackground4', '#00000000', nls.localize(617, 'Background color of active bracket pair guides (4). Requires enabling bracket pair guides.'));
    exports.editorBracketPairGuideActiveBackground5 = (0, colorRegistry_1.registerColor)('editorBracketPairGuide.activeBackground5', '#00000000', nls.localize(618, 'Background color of active bracket pair guides (5). Requires enabling bracket pair guides.'));
    exports.editorBracketPairGuideActiveBackground6 = (0, colorRegistry_1.registerColor)('editorBracketPairGuide.activeBackground6', '#00000000', nls.localize(619, 'Background color of active bracket pair guides (6). Requires enabling bracket pair guides.'));
    exports.editorUnicodeHighlightBorder = (0, colorRegistry_1.registerColor)('editorUnicodeHighlight.border', colorRegistry_1.editorWarningForeground, nls.localize(620, 'Border color used to highlight unicode characters.'));
    exports.editorUnicodeHighlightBackground = (0, colorRegistry_1.registerColor)('editorUnicodeHighlight.background', colorRegistry_1.editorWarningBackground, nls.localize(621, 'Background color used to highlight unicode characters.'));
    // contains all color rules that used to defined in editor/browser/widget/editor.css
    (0, themeService_1.registerThemingParticipant)((theme, collector) => {
        const background = theme.getColor(colorRegistry_1.editorBackground);
        const lineHighlight = theme.getColor(exports.editorLineHighlight);
        const imeBackground = (lineHighlight && !lineHighlight.isTransparent() ? lineHighlight : background);
        if (imeBackground) {
            collector.addRule(`.monaco-editor .inputarea.ime-input { background-color: ${imeBackground}; }`);
        }
    });
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[776/*vs/editor/browser/viewParts/currentLineHighlight/currentLineHighlight*/], __M([1/*require*/,0/*exports*/,133/*vs/editor/browser/view/dynamicViewOverlay*/,80/*vs/editor/common/core/editorColorRegistry*/,13/*vs/base/common/arrays*/,25/*vs/platform/theme/common/themeService*/,23/*vs/editor/common/core/selection*/,97/*vs/platform/theme/common/theme*/,9/*vs/editor/common/core/position*/,482/*vs/css!vs/editor/browser/viewParts/currentLineHighlight/currentLineHighlight*/]), function (require, exports, dynamicViewOverlay_1, editorColorRegistry_1, arrays, themeService_1, selection_1, theme_1, position_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CurrentLineMarginHighlightOverlay = exports.CurrentLineHighlightOverlay = exports.AbstractLineHighlightOverlay = void 0;
    class AbstractLineHighlightOverlay extends dynamicViewOverlay_1.DynamicViewOverlay {
        constructor(context) {
            super();
            this._context = context;
            const options = this._context.configuration.options;
            const layoutInfo = options.get(146 /* EditorOption.layoutInfo */);
            this._renderLineHighlight = options.get(97 /* EditorOption.renderLineHighlight */);
            this._renderLineHighlightOnlyWhenFocus = options.get(98 /* EditorOption.renderLineHighlightOnlyWhenFocus */);
            this._wordWrap = layoutInfo.isViewportWrapping;
            this._contentLeft = layoutInfo.contentLeft;
            this._contentWidth = layoutInfo.contentWidth;
            this._selectionIsEmpty = true;
            this._focused = false;
            this._cursorLineNumbers = [1];
            this._selections = [new selection_1.Selection(1, 1, 1, 1)];
            this._renderData = null;
            this._context.addEventHandler(this);
        }
        dispose() {
            this._context.removeEventHandler(this);
            super.dispose();
        }
        _readFromSelections() {
            let hasChanged = false;
            const lineNumbers = new Set();
            for (const selection of this._selections) {
                lineNumbers.add(selection.positionLineNumber);
            }
            const cursorsLineNumbers = Array.from(lineNumbers);
            cursorsLineNumbers.sort((a, b) => a - b);
            if (!arrays.equals(this._cursorLineNumbers, cursorsLineNumbers)) {
                this._cursorLineNumbers = cursorsLineNumbers;
                hasChanged = true;
            }
            const selectionIsEmpty = this._selections.every(s => s.isEmpty());
            if (this._selectionIsEmpty !== selectionIsEmpty) {
                this._selectionIsEmpty = selectionIsEmpty;
                hasChanged = true;
            }
            return hasChanged;
        }
        // --- begin event handlers
        onThemeChanged(e) {
            return this._readFromSelections();
        }
        onConfigurationChanged(e) {
            const options = this._context.configuration.options;
            const layoutInfo = options.get(146 /* EditorOption.layoutInfo */);
            this._renderLineHighlight = options.get(97 /* EditorOption.renderLineHighlight */);
            this._renderLineHighlightOnlyWhenFocus = options.get(98 /* EditorOption.renderLineHighlightOnlyWhenFocus */);
            this._wordWrap = layoutInfo.isViewportWrapping;
            this._contentLeft = layoutInfo.contentLeft;
            this._contentWidth = layoutInfo.contentWidth;
            return true;
        }
        onCursorStateChanged(e) {
            this._selections = e.selections;
            return this._readFromSelections();
        }
        onFlushed(e) {
            return true;
        }
        onLinesDeleted(e) {
            return true;
        }
        onLinesInserted(e) {
            return true;
        }
        onScrollChanged(e) {
            return e.scrollWidthChanged || e.scrollTopChanged;
        }
        onZonesChanged(e) {
            return true;
        }
        onFocusChanged(e) {
            if (!this._renderLineHighlightOnlyWhenFocus) {
                return false;
            }
            this._focused = e.isFocused;
            return true;
        }
        // --- end event handlers
        prepareRender(ctx) {
            if (!this._shouldRenderThis()) {
                this._renderData = null;
                return;
            }
            const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
            const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
            // initialize renderData
            const renderData = [];
            for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
                const lineIndex = lineNumber - visibleStartLineNumber;
                renderData[lineIndex] = '';
            }
            if (this._wordWrap) {
                // do a first pass to render wrapped lines
                const renderedLineWrapped = this._renderOne(ctx, false);
                for (const cursorLineNumber of this._cursorLineNumbers) {
                    const coordinatesConverter = this._context.viewModel.coordinatesConverter;
                    const modelLineNumber = coordinatesConverter.convertViewPositionToModelPosition(new position_1.Position(cursorLineNumber, 1)).lineNumber;
                    const firstViewLineNumber = coordinatesConverter.convertModelPositionToViewPosition(new position_1.Position(modelLineNumber, 1)).lineNumber;
                    const lastViewLineNumber = coordinatesConverter.convertModelPositionToViewPosition(new position_1.Position(modelLineNumber, this._context.viewModel.model.getLineMaxColumn(modelLineNumber))).lineNumber;
                    const firstLine = Math.max(firstViewLineNumber, visibleStartLineNumber);
                    const lastLine = Math.min(lastViewLineNumber, visibleEndLineNumber);
                    for (let lineNumber = firstLine; lineNumber <= lastLine; lineNumber++) {
                        const lineIndex = lineNumber - visibleStartLineNumber;
                        renderData[lineIndex] = renderedLineWrapped;
                    }
                }
            }
            // do a second pass to render exact lines
            const renderedLineExact = this._renderOne(ctx, true);
            for (const cursorLineNumber of this._cursorLineNumbers) {
                if (cursorLineNumber < visibleStartLineNumber || cursorLineNumber > visibleEndLineNumber) {
                    continue;
                }
                const lineIndex = cursorLineNumber - visibleStartLineNumber;
                renderData[lineIndex] = renderedLineExact;
            }
            this._renderData = renderData;
        }
        render(startLineNumber, lineNumber) {
            if (!this._renderData) {
                return '';
            }
            const lineIndex = lineNumber - startLineNumber;
            if (lineIndex >= this._renderData.length) {
                return '';
            }
            return this._renderData[lineIndex];
        }
        _shouldRenderInMargin() {
            return ((this._renderLineHighlight === 'gutter' || this._renderLineHighlight === 'all')
                && (!this._renderLineHighlightOnlyWhenFocus || this._focused));
        }
        _shouldRenderInContent() {
            return ((this._renderLineHighlight === 'line' || this._renderLineHighlight === 'all')
                && this._selectionIsEmpty
                && (!this._renderLineHighlightOnlyWhenFocus || this._focused));
        }
    }
    exports.AbstractLineHighlightOverlay = AbstractLineHighlightOverlay;
    class CurrentLineHighlightOverlay extends AbstractLineHighlightOverlay {
        _renderOne(ctx, exact) {
            const className = 'current-line' + (this._shouldRenderInMargin() ? ' current-line-both' : '') + (exact ? ' current-line-exact' : '');
            return `<div class="${className}" style="width:${Math.max(ctx.scrollWidth, this._contentWidth)}px;"></div>`;
        }
        _shouldRenderThis() {
            return this._shouldRenderInContent();
        }
        _shouldRenderOther() {
            return this._shouldRenderInMargin();
        }
    }
    exports.CurrentLineHighlightOverlay = CurrentLineHighlightOverlay;
    class CurrentLineMarginHighlightOverlay extends AbstractLineHighlightOverlay {
        _renderOne(ctx, exact) {
            const className = 'current-line' + (this._shouldRenderInMargin() ? ' current-line-margin' : '') + (this._shouldRenderOther() ? ' current-line-margin-both' : '') + (this._shouldRenderInMargin() && exact ? ' current-line-exact-margin' : '');
            return `<div class="${className}" style="width:${this._contentLeft}px"></div>`;
        }
        _shouldRenderThis() {
            return true;
        }
        _shouldRenderOther() {
            return this._shouldRenderInContent();
        }
    }
    exports.CurrentLineMarginHighlightOverlay = CurrentLineMarginHighlightOverlay;
    (0, themeService_1.registerThemingParticipant)((theme, collector) => {
        const lineHighlight = theme.getColor(editorColorRegistry_1.editorLineHighlight);
        if (lineHighlight) {
            collector.addRule(`.monaco-editor .view-overlays .current-line { background-color: ${lineHighlight}; }`);
            collector.addRule(`.monaco-editor .margin-view-overlays .current-line-margin { background-color: ${lineHighlight}; border: none; }`);
        }
        if (!lineHighlight || lineHighlight.isTransparent() || theme.defines(editorColorRegistry_1.editorLineHighlightBorder)) {
            const lineHighlightBorder = theme.getColor(editorColorRegistry_1.editorLineHighlightBorder);
            if (lineHighlightBorder) {
                collector.addRule(`.monaco-editor .view-overlays .current-line-exact { border: 2px solid ${lineHighlightBorder}; }`);
                collector.addRule(`.monaco-editor .margin-view-overlays .current-line-exact-margin { border: 2px solid ${lineHighlightBorder}; }`);
                if ((0, theme_1.isHighContrast)(theme.type)) {
                    collector.addRule(`.monaco-editor .view-overlays .current-line-exact { border-width: 1px; }`);
                    collector.addRule(`.monaco-editor .margin-view-overlays .current-line-exact-margin { border-width: 1px; }`);
                }
            }
        }
    });
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[777/*vs/editor/browser/viewParts/indentGuides/indentGuides*/], __M([1/*require*/,0/*exports*/,133/*vs/editor/browser/view/dynamicViewOverlay*/,80/*vs/editor/common/core/editorColorRegistry*/,25/*vs/platform/theme/common/themeService*/,9/*vs/editor/common/core/position*/,13/*vs/base/common/arrays*/,19/*vs/base/common/types*/,329/*vs/editor/common/model/guidesTextModelPart*/,239/*vs/editor/common/textModelGuides*/,485/*vs/css!vs/editor/browser/viewParts/indentGuides/indentGuides*/]), function (require, exports, dynamicViewOverlay_1, editorColorRegistry_1, themeService_1, position_1, arrays_1, types_1, guidesTextModelPart_1, textModelGuides_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.IndentGuidesOverlay = void 0;
    class IndentGuidesOverlay extends dynamicViewOverlay_1.DynamicViewOverlay {
        constructor(context) {
            super();
            this._context = context;
            this._primaryPosition = null;
            const options = this._context.configuration.options;
            const wrappingInfo = options.get(147 /* EditorOption.wrappingInfo */);
            const fontInfo = options.get(50 /* EditorOption.fontInfo */);
            this._spaceWidth = fontInfo.spaceWidth;
            this._maxIndentLeft = wrappingInfo.wrappingColumn === -1 ? -1 : (wrappingInfo.wrappingColumn * fontInfo.typicalHalfwidthCharacterWidth);
            this._bracketPairGuideOptions = options.get(16 /* EditorOption.guides */);
            this._renderResult = null;
            this._context.addEventHandler(this);
        }
        dispose() {
            this._context.removeEventHandler(this);
            this._renderResult = null;
            super.dispose();
        }
        // --- begin event handlers
        onConfigurationChanged(e) {
            const options = this._context.configuration.options;
            const wrappingInfo = options.get(147 /* EditorOption.wrappingInfo */);
            const fontInfo = options.get(50 /* EditorOption.fontInfo */);
            this._spaceWidth = fontInfo.spaceWidth;
            this._maxIndentLeft = wrappingInfo.wrappingColumn === -1 ? -1 : (wrappingInfo.wrappingColumn * fontInfo.typicalHalfwidthCharacterWidth);
            this._bracketPairGuideOptions = options.get(16 /* EditorOption.guides */);
            return true;
        }
        onCursorStateChanged(e) {
            const selection = e.selections[0];
            const newPosition = selection.getPosition();
            if (!this._primaryPosition?.equals(newPosition)) {
                this._primaryPosition = newPosition;
                return true;
            }
            return false;
        }
        onDecorationsChanged(e) {
            // true for inline decorations
            return true;
        }
        onFlushed(e) {
            return true;
        }
        onLinesChanged(e) {
            return true;
        }
        onLinesDeleted(e) {
            return true;
        }
        onLinesInserted(e) {
            return true;
        }
        onScrollChanged(e) {
            return e.scrollTopChanged; // || e.scrollWidthChanged;
        }
        onZonesChanged(e) {
            return true;
        }
        onLanguageConfigurationChanged(e) {
            return true;
        }
        // --- end event handlers
        prepareRender(ctx) {
            if (!this._bracketPairGuideOptions.indentation && this._bracketPairGuideOptions.bracketPairs === false) {
                this._renderResult = null;
                return;
            }
            const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
            const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
            const scrollWidth = ctx.scrollWidth;
            const activeCursorPosition = this._primaryPosition;
            const indents = this.getGuidesByLine(visibleStartLineNumber, Math.min(visibleEndLineNumber + 1, this._context.viewModel.getLineCount()), activeCursorPosition);
            const output = [];
            for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
                const lineIndex = lineNumber - visibleStartLineNumber;
                const indent = indents[lineIndex];
                let result = '';
                const leftOffset = ctx.visibleRangeForPosition(new position_1.Position(lineNumber, 1))?.left ?? 0;
                for (const guide of indent) {
                    const left = guide.column === -1
                        ? leftOffset + (guide.visibleColumn - 1) * this._spaceWidth
                        : ctx.visibleRangeForPosition(new position_1.Position(lineNumber, guide.column)).left;
                    if (left > scrollWidth || (this._maxIndentLeft > 0 && left > this._maxIndentLeft)) {
                        break;
                    }
                    const className = guide.horizontalLine ? (guide.horizontalLine.top ? 'horizontal-top' : 'horizontal-bottom') : 'vertical';
                    const width = guide.horizontalLine
                        ? (ctx.visibleRangeForPosition(new position_1.Position(lineNumber, guide.horizontalLine.endColumn))?.left ?? (left + this._spaceWidth)) - left
                        : this._spaceWidth;
                    result += `<div class="core-guide ${guide.className} ${className}" style="left:${left}px;width:${width}px"></div>`;
                }
                output[lineIndex] = result;
            }
            this._renderResult = output;
        }
        getGuidesByLine(visibleStartLineNumber, visibleEndLineNumber, activeCursorPosition) {
            const bracketGuides = this._bracketPairGuideOptions.bracketPairs !== false
                ? this._context.viewModel.getBracketGuidesInRangeByLine(visibleStartLineNumber, visibleEndLineNumber, activeCursorPosition, {
                    highlightActive: this._bracketPairGuideOptions.highlightActiveBracketPair,
                    horizontalGuides: this._bracketPairGuideOptions.bracketPairsHorizontal === true
                        ? textModelGuides_1.HorizontalGuidesState.Enabled
                        : this._bracketPairGuideOptions.bracketPairsHorizontal === 'active'
                            ? textModelGuides_1.HorizontalGuidesState.EnabledForActive
                            : textModelGuides_1.HorizontalGuidesState.Disabled,
                    includeInactive: this._bracketPairGuideOptions.bracketPairs === true,
                })
                : null;
            const indentGuides = this._bracketPairGuideOptions.indentation
                ? this._context.viewModel.getLinesIndentGuides(visibleStartLineNumber, visibleEndLineNumber)
                : null;
            let activeIndentStartLineNumber = 0;
            let activeIndentEndLineNumber = 0;
            let activeIndentLevel = 0;
            if (this._bracketPairGuideOptions.highlightActiveIndentation !== false && activeCursorPosition) {
                const activeIndentInfo = this._context.viewModel.getActiveIndentGuide(activeCursorPosition.lineNumber, visibleStartLineNumber, visibleEndLineNumber);
                activeIndentStartLineNumber = activeIndentInfo.startLineNumber;
                activeIndentEndLineNumber = activeIndentInfo.endLineNumber;
                activeIndentLevel = activeIndentInfo.indent;
            }
            const { indentSize } = this._context.viewModel.model.getOptions();
            const result = [];
            for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
                const lineGuides = new Array();
                result.push(lineGuides);
                const bracketGuidesInLine = bracketGuides ? bracketGuides[lineNumber - visibleStartLineNumber] : [];
                const bracketGuidesInLineQueue = new arrays_1.ArrayQueue(bracketGuidesInLine);
                const indentGuidesInLine = indentGuides ? indentGuides[lineNumber - visibleStartLineNumber] : 0;
                for (let indentLvl = 1; indentLvl <= indentGuidesInLine; indentLvl++) {
                    const indentGuide = (indentLvl - 1) * indentSize + 1;
                    const isActive = 
                    // Disable active indent guide if there are bracket guides.
                    (this._bracketPairGuideOptions.highlightActiveIndentation === 'always' || bracketGuidesInLine.length === 0) &&
                        activeIndentStartLineNumber <= lineNumber &&
                        lineNumber <= activeIndentEndLineNumber &&
                        indentLvl === activeIndentLevel;
                    lineGuides.push(...bracketGuidesInLineQueue.takeWhile(g => g.visibleColumn < indentGuide) || []);
                    const peeked = bracketGuidesInLineQueue.peek();
                    if (!peeked || peeked.visibleColumn !== indentGuide || peeked.horizontalLine) {
                        lineGuides.push(new textModelGuides_1.IndentGuide(indentGuide, -1, `core-guide-indent lvl-${(indentLvl - 1) % 30}` + (isActive ? ' indent-active' : ''), null, -1, -1));
                    }
                }
                lineGuides.push(...bracketGuidesInLineQueue.takeWhile(g => true) || []);
            }
            return result;
        }
        render(startLineNumber, lineNumber) {
            if (!this._renderResult) {
                return '';
            }
            const lineIndex = lineNumber - startLineNumber;
            if (lineIndex < 0 || lineIndex >= this._renderResult.length) {
                return '';
            }
            return this._renderResult[lineIndex];
        }
    }
    exports.IndentGuidesOverlay = IndentGuidesOverlay;
    function transparentToUndefined(color) {
        if (color && color.isTransparent()) {
            return undefined;
        }
        return color;
    }
    (0, themeService_1.registerThemingParticipant)((theme, collector) => {
        const colors = [
            { bracketColor: editorColorRegistry_1.editorBracketHighlightingForeground1, guideColor: editorColorRegistry_1.editorBracketPairGuideBackground1, guideColorActive: editorColorRegistry_1.editorBracketPairGuideActiveBackground1 },
            { bracketColor: editorColorRegistry_1.editorBracketHighlightingForeground2, guideColor: editorColorRegistry_1.editorBracketPairGuideBackground2, guideColorActive: editorColorRegistry_1.editorBracketPairGuideActiveBackground2 },
            { bracketColor: editorColorRegistry_1.editorBracketHighlightingForeground3, guideColor: editorColorRegistry_1.editorBracketPairGuideBackground3, guideColorActive: editorColorRegistry_1.editorBracketPairGuideActiveBackground3 },
            { bracketColor: editorColorRegistry_1.editorBracketHighlightingForeground4, guideColor: editorColorRegistry_1.editorBracketPairGuideBackground4, guideColorActive: editorColorRegistry_1.editorBracketPairGuideActiveBackground4 },
            { bracketColor: editorColorRegistry_1.editorBracketHighlightingForeground5, guideColor: editorColorRegistry_1.editorBracketPairGuideBackground5, guideColorActive: editorColorRegistry_1.editorBracketPairGuideActiveBackground5 },
            { bracketColor: editorColorRegistry_1.editorBracketHighlightingForeground6, guideColor: editorColorRegistry_1.editorBracketPairGuideBackground6, guideColorActive: editorColorRegistry_1.editorBracketPairGuideActiveBackground6 }
        ];
        const colorProvider = new guidesTextModelPart_1.BracketPairGuidesClassNames();
        const indentColors = [
            { indentColor: editorColorRegistry_1.editorIndentGuide1, indentColorActive: editorColorRegistry_1.editorActiveIndentGuide1 },
            { indentColor: editorColorRegistry_1.editorIndentGuide2, indentColorActive: editorColorRegistry_1.editorActiveIndentGuide2 },
            { indentColor: editorColorRegistry_1.editorIndentGuide3, indentColorActive: editorColorRegistry_1.editorActiveIndentGuide3 },
            { indentColor: editorColorRegistry_1.editorIndentGuide4, indentColorActive: editorColorRegistry_1.editorActiveIndentGuide4 },
            { indentColor: editorColorRegistry_1.editorIndentGuide5, indentColorActive: editorColorRegistry_1.editorActiveIndentGuide5 },
            { indentColor: editorColorRegistry_1.editorIndentGuide6, indentColorActive: editorColorRegistry_1.editorActiveIndentGuide6 },
        ];
        const colorValues = colors
            .map(c => {
            const bracketColor = theme.getColor(c.bracketColor);
            const guideColor = theme.getColor(c.guideColor);
            const guideColorActive = theme.getColor(c.guideColorActive);
            const effectiveGuideColor = transparentToUndefined(transparentToUndefined(guideColor) ?? bracketColor?.transparent(0.3));
            const effectiveGuideColorActive = transparentToUndefined(transparentToUndefined(guideColorActive) ?? bracketColor);
            if (!effectiveGuideColor || !effectiveGuideColorActive) {
                return undefined;
            }
            return {
                guideColor: effectiveGuideColor,
                guideColorActive: effectiveGuideColorActive,
            };
        })
            .filter(types_1.isDefined);
        const indentColorValues = indentColors
            .map(c => {
            const indentColor = theme.getColor(c.indentColor);
            const indentColorActive = theme.getColor(c.indentColorActive);
            const effectiveIndentColor = transparentToUndefined(indentColor);
            const effectiveIndentColorActive = transparentToUndefined(indentColorActive);
            if (!effectiveIndentColor || !effectiveIndentColorActive) {
                return undefined;
            }
            return {
                indentColor: effectiveIndentColor,
                indentColorActive: effectiveIndentColorActive,
            };
        })
            .filter(types_1.isDefined);
        if (colorValues.length > 0) {
            for (let level = 0; level < 30; level++) {
                const colors = colorValues[level % colorValues.length];
                collector.addRule(`.monaco-editor .${colorProvider.getInlineClassNameOfLevel(level).replace(/ /g, '.')} { --guide-color: ${colors.guideColor}; --guide-color-active: ${colors.guideColorActive}; }`);
            }
            collector.addRule(`.monaco-editor .vertical { box-shadow: 1px 0 0 0 var(--guide-color) inset; }`);
            collector.addRule(`.monaco-editor .horizontal-top { border-top: 1px solid var(--guide-color); }`);
            collector.addRule(`.monaco-editor .horizontal-bottom { border-bottom: 1px solid var(--guide-color); }`);
            collector.addRule(`.monaco-editor .vertical.${colorProvider.activeClassName} { box-shadow: 1px 0 0 0 var(--guide-color-active) inset; }`);
            collector.addRule(`.monaco-editor .horizontal-top.${colorProvider.activeClassName} { border-top: 1px solid var(--guide-color-active); }`);
            collector.addRule(`.monaco-editor .horizontal-bottom.${colorProvider.activeClassName} { border-bottom: 1px solid var(--guide-color-active); }`);
        }
        if (indentColorValues.length > 0) {
            for (let level = 0; level < 30; level++) {
                const colors = indentColorValues[level % indentColorValues.length];
                collector.addRule(`.monaco-editor .lines-content .core-guide-indent.lvl-${level} { --indent-color: ${colors.indentColor}; --indent-color-active: ${colors.indentColorActive}; }`);
            }
            collector.addRule(`.monaco-editor .lines-content .core-guide-indent { box-shadow: 1px 0 0 0 var(--indent-color) inset; }`);
            collector.addRule(`.monaco-editor .lines-content .core-guide-indent.indent-active { box-shadow: 1px 0 0 0 var(--indent-color-active) inset; }`);
        }
    });
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[416/*vs/editor/browser/viewParts/lineNumbers/lineNumbers*/], __M([1/*require*/,0/*exports*/,16/*vs/base/common/platform*/,133/*vs/editor/browser/view/dynamicViewOverlay*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/,25/*vs/platform/theme/common/themeService*/,80/*vs/editor/common/core/editorColorRegistry*/,486/*vs/css!vs/editor/browser/viewParts/lineNumbers/lineNumbers*/]), function (require, exports, platform, dynamicViewOverlay_1, position_1, range_1, themeService_1, editorColorRegistry_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.LineNumbersOverlay = void 0;
    class LineNumbersOverlay extends dynamicViewOverlay_1.DynamicViewOverlay {
        static { this.CLASS_NAME = 'line-numbers'; }
        constructor(context) {
            super();
            this._context = context;
            this._readConfig();
            this._lastCursorModelPosition = new position_1.Position(1, 1);
            this._renderResult = null;
            this._activeLineNumber = 1;
            this._context.addEventHandler(this);
        }
        _readConfig() {
            const options = this._context.configuration.options;
            this._lineHeight = options.get(67 /* EditorOption.lineHeight */);
            const lineNumbers = options.get(68 /* EditorOption.lineNumbers */);
            this._renderLineNumbers = lineNumbers.renderType;
            this._renderCustomLineNumbers = lineNumbers.renderFn;
            this._renderFinalNewline = options.get(96 /* EditorOption.renderFinalNewline */);
            const layoutInfo = options.get(146 /* EditorOption.layoutInfo */);
            this._lineNumbersLeft = layoutInfo.lineNumbersLeft;
            this._lineNumbersWidth = layoutInfo.lineNumbersWidth;
        }
        dispose() {
            this._context.removeEventHandler(this);
            this._renderResult = null;
            super.dispose();
        }
        // --- begin event handlers
        onConfigurationChanged(e) {
            this._readConfig();
            return true;
        }
        onCursorStateChanged(e) {
            const primaryViewPosition = e.selections[0].getPosition();
            this._lastCursorModelPosition = this._context.viewModel.coordinatesConverter.convertViewPositionToModelPosition(primaryViewPosition);
            let shouldRender = false;
            if (this._activeLineNumber !== primaryViewPosition.lineNumber) {
                this._activeLineNumber = primaryViewPosition.lineNumber;
                shouldRender = true;
            }
            if (this._renderLineNumbers === 2 /* RenderLineNumbersType.Relative */ || this._renderLineNumbers === 3 /* RenderLineNumbersType.Interval */) {
                shouldRender = true;
            }
            return shouldRender;
        }
        onFlushed(e) {
            return true;
        }
        onLinesChanged(e) {
            return true;
        }
        onLinesDeleted(e) {
            return true;
        }
        onLinesInserted(e) {
            return true;
        }
        onScrollChanged(e) {
            return e.scrollTopChanged;
        }
        onZonesChanged(e) {
            return true;
        }
        onDecorationsChanged(e) {
            return e.affectsLineNumber;
        }
        // --- end event handlers
        _getLineRenderLineNumber(viewLineNumber) {
            const modelPosition = this._context.viewModel.coordinatesConverter.convertViewPositionToModelPosition(new position_1.Position(viewLineNumber, 1));
            if (modelPosition.column !== 1) {
                return '';
            }
            const modelLineNumber = modelPosition.lineNumber;
            if (this._renderCustomLineNumbers) {
                return this._renderCustomLineNumbers(modelLineNumber);
            }
            if (this._renderLineNumbers === 2 /* RenderLineNumbersType.Relative */) {
                const diff = Math.abs(this._lastCursorModelPosition.lineNumber - modelLineNumber);
                if (diff === 0) {
                    return '<span class="relative-current-line-number">' + modelLineNumber + '</span>';
                }
                return String(diff);
            }
            if (this._renderLineNumbers === 3 /* RenderLineNumbersType.Interval */) {
                if (this._lastCursorModelPosition.lineNumber === modelLineNumber) {
                    return String(modelLineNumber);
                }
                if (modelLineNumber % 10 === 0) {
                    return String(modelLineNumber);
                }
                const finalLineNumber = this._context.viewModel.getLineCount();
                if (modelLineNumber === finalLineNumber) {
                    return String(modelLineNumber);
                }
                return '';
            }
            return String(modelLineNumber);
        }
        prepareRender(ctx) {
            if (this._renderLineNumbers === 0 /* RenderLineNumbersType.Off */) {
                this._renderResult = null;
                return;
            }
            const lineHeightClassName = (platform.isLinux ? (this._lineHeight % 2 === 0 ? ' lh-even' : ' lh-odd') : '');
            const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
            const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
            const lineNoDecorations = this._context.viewModel.getDecorationsInViewport(ctx.visibleRange).filter(d => !!d.options.lineNumberClassName);
            lineNoDecorations.sort((a, b) => range_1.Range.compareRangesUsingEnds(a.range, b.range));
            let decorationStartIndex = 0;
            const lineCount = this._context.viewModel.getLineCount();
            const output = [];
            for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
                const lineIndex = lineNumber - visibleStartLineNumber;
                let renderLineNumber = this._getLineRenderLineNumber(lineNumber);
                let extraClassNames = '';
                // skip decorations whose end positions we've already passed
                while (decorationStartIndex < lineNoDecorations.length && lineNoDecorations[decorationStartIndex].range.endLineNumber < lineNumber) {
                    decorationStartIndex++;
                }
                for (let i = decorationStartIndex; i < lineNoDecorations.length; i++) {
                    const { range, options } = lineNoDecorations[i];
                    if (range.startLineNumber <= lineNumber) {
                        extraClassNames += ' ' + options.lineNumberClassName;
                    }
                }
                if (!renderLineNumber && !extraClassNames) {
                    output[lineIndex] = '';
                    continue;
                }
                if (lineNumber === lineCount && this._context.viewModel.getLineLength(lineNumber) === 0) {
                    // this is the last line
                    if (this._renderFinalNewline === 'off') {
                        renderLineNumber = '';
                    }
                    if (this._renderFinalNewline === 'dimmed') {
                        extraClassNames += ' dimmed-line-number';
                    }
                }
                if (lineNumber === this._activeLineNumber) {
                    extraClassNames += ' active-line-number';
                }
                output[lineIndex] = (`<div class="${LineNumbersOverlay.CLASS_NAME}${lineHeightClassName}${extraClassNames}" style="left:${this._lineNumbersLeft}px;width:${this._lineNumbersWidth}px;">${renderLineNumber}</div>`);
            }
            this._renderResult = output;
        }
        render(startLineNumber, lineNumber) {
            if (!this._renderResult) {
                return '';
            }
            const lineIndex = lineNumber - startLineNumber;
            if (lineIndex < 0 || lineIndex >= this._renderResult.length) {
                return '';
            }
            return this._renderResult[lineIndex];
        }
    }
    exports.LineNumbersOverlay = LineNumbersOverlay;
    (0, themeService_1.registerThemingParticipant)((theme, collector) => {
        const editorLineNumbersColor = theme.getColor(editorColorRegistry_1.editorLineNumbers);
        const editorDimmedLineNumberColor = theme.getColor(editorColorRegistry_1.editorDimmedLineNumber);
        if (editorDimmedLineNumberColor) {
            collector.addRule(`.monaco-editor .line-numbers.dimmed-line-number { color: ${editorDimmedLineNumberColor}; }`);
        }
        else if (editorLineNumbersColor) {
            collector.addRule(`.monaco-editor .line-numbers.dimmed-line-number { color: ${editorLineNumbersColor.transparent(0.4)}; }`);
        }
    });
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[778/*vs/editor/browser/controller/textAreaHandler*/], __M([1/*require*/,0/*exports*/,3/*vs/nls*/,64/*vs/base/browser/browser*/,39/*vs/base/browser/fastDomNode*/,16/*vs/base/common/platform*/,11/*vs/base/common/strings*/,74/*vs/editor/browser/config/domFontInfo*/,212/*vs/editor/browser/controller/textAreaInput*/,310/*vs/editor/browser/controller/textAreaState*/,56/*vs/editor/browser/view/viewPart*/,416/*vs/editor/browser/viewParts/lineNumbers/lineNumbers*/,331/*vs/editor/browser/viewParts/margin/margin*/,37/*vs/editor/common/config/editorOptions*/,166/*vs/editor/common/core/wordCharacterClassifier*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/,23/*vs/editor/common/core/selection*/,226/*vs/base/browser/ui/mouseCursor/mouseCursor*/,27/*vs/editor/common/languages*/,33/*vs/base/common/color*/,300/*vs/base/common/ime*/,31/*vs/platform/keybinding/common/keybinding*/,7/*vs/platform/instantiation/common/instantiation*/,479/*vs/css!vs/editor/browser/controller/textAreaHandler*/]), function (require, exports, nls, browser, fastDomNode_1, platform, strings, domFontInfo_1, textAreaInput_1, textAreaState_1, viewPart_1, lineNumbers_1, margin_1, editorOptions_1, wordCharacterClassifier_1, position_1, range_1, selection_1, mouseCursor_1, languages_1, color_1, ime_1, keybinding_1, instantiation_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.TextAreaHandler = void 0;
    class VisibleTextAreaData {
        constructor(_context, modelLineNumber, distanceToModelLineStart, widthOfHiddenLineTextBefore, distanceToModelLineEnd) {
            this._context = _context;
            this.modelLineNumber = modelLineNumber;
            this.distanceToModelLineStart = distanceToModelLineStart;
            this.widthOfHiddenLineTextBefore = widthOfHiddenLineTextBefore;
            this.distanceToModelLineEnd = distanceToModelLineEnd;
            this._visibleTextAreaBrand = undefined;
            this.startPosition = null;
            this.endPosition = null;
            this.visibleTextareaStart = null;
            this.visibleTextareaEnd = null;
            /**
             * When doing composition, the currently composed text might be split up into
             * multiple tokens, then merged again into a single token, etc. Here we attempt
             * to keep the presentation of the <textarea> stable by using the previous used
             * style if multiple tokens come into play. This avoids flickering.
             */
            this._previousPresentation = null;
        }
        prepareRender(visibleRangeProvider) {
            const startModelPosition = new position_1.Position(this.modelLineNumber, this.distanceToModelLineStart + 1);
            const endModelPosition = new position_1.Position(this.modelLineNumber, this._context.viewModel.model.getLineMaxColumn(this.modelLineNumber) - this.distanceToModelLineEnd);
            this.startPosition = this._context.viewModel.coordinatesConverter.convertModelPositionToViewPosition(startModelPosition);
            this.endPosition = this._context.viewModel.coordinatesConverter.convertModelPositionToViewPosition(endModelPosition);
            if (this.startPosition.lineNumber === this.endPosition.lineNumber) {
                this.visibleTextareaStart = visibleRangeProvider.visibleRangeForPosition(this.startPosition);
                this.visibleTextareaEnd = visibleRangeProvider.visibleRangeForPosition(this.endPosition);
            }
            else {
                // TODO: what if the view positions are not on the same line?
                this.visibleTextareaStart = null;
                this.visibleTextareaEnd = null;
            }
        }
        definePresentation(tokenPresentation) {
            if (!this._previousPresentation) {
                // To avoid flickering, once set, always reuse a presentation throughout the entire IME session
                if (tokenPresentation) {
                    this._previousPresentation = tokenPresentation;
                }
                else {
                    this._previousPresentation = {
                        foreground: 1 /* ColorId.DefaultForeground */,
                        italic: false,
                        bold: false,
                        underline: false,
                        strikethrough: false,
                    };
                }
            }
            return this._previousPresentation;
        }
    }
    const canUseZeroSizeTextarea = (browser.isFirefox);
    let TextAreaHandler = class TextAreaHandler extends viewPart_1.ViewPart {
        constructor(context, viewController, visibleRangeProvider, _keybindingService, _instantiationService) {
            super(context);
            this._keybindingService = _keybindingService;
            this._instantiationService = _instantiationService;
            this._primaryCursorPosition = new position_1.Position(1, 1);
            this._primaryCursorVisibleRange = null;
            this._viewController = viewController;
            this._visibleRangeProvider = visibleRangeProvider;
            this._scrollLeft = 0;
            this._scrollTop = 0;
            const options = this._context.configuration.options;
            const layoutInfo = options.get(146 /* EditorOption.layoutInfo */);
            this._setAccessibilityOptions(options);
            this._contentLeft = layoutInfo.contentLeft;
            this._contentWidth = layoutInfo.contentWidth;
            this._contentHeight = layoutInfo.height;
            this._fontInfo = options.get(50 /* EditorOption.fontInfo */);
            this._lineHeight = options.get(67 /* EditorOption.lineHeight */);
            this._emptySelectionClipboard = options.get(37 /* EditorOption.emptySelectionClipboard */);
            this._copyWithSyntaxHighlighting = options.get(25 /* EditorOption.copyWithSyntaxHighlighting */);
            this._visibleTextArea = null;
            this._selections = [new selection_1.Selection(1, 1, 1, 1)];
            this._modelSelections = [new selection_1.Selection(1, 1, 1, 1)];
            this._lastRenderPosition = null;
            // Text Area (The focus will always be in the textarea when the cursor is blinking)
            this.textArea = (0, fastDomNode_1.createFastDomNode)(document.createElement('textarea'));
            viewPart_1.PartFingerprints.write(this.textArea, 7 /* PartFingerprint.TextArea */);
            this.textArea.setClassName(`inputarea ${mouseCursor_1.MOUSE_CURSOR_TEXT_CSS_CLASS_NAME}`);
            this.textArea.setAttribute('wrap', this._textAreaWrapping && !this._visibleTextArea ? 'on' : 'off');
            const { tabSize } = this._context.viewModel.model.getOptions();
            this.textArea.domNode.style.tabSize = `${tabSize * this._fontInfo.spaceWidth}px`;
            this.textArea.setAttribute('autocorrect', 'off');
            this.textArea.setAttribute('autocapitalize', 'off');
            this.textArea.setAttribute('autocomplete', 'off');
            this.textArea.setAttribute('spellcheck', 'false');
            this.textArea.setAttribute('aria-label', this._getAriaLabel(options));
            this.textArea.setAttribute('aria-required', options.get(5 /* EditorOption.ariaRequired */) ? 'true' : 'false');
            this.textArea.setAttribute('tabindex', String(options.get(125 /* EditorOption.tabIndex */)));
            this.textArea.setAttribute('role', 'textbox');
            this.textArea.setAttribute('aria-roledescription', nls.localize(54, "editor"));
            this.textArea.setAttribute('aria-multiline', 'true');
            this.textArea.setAttribute('aria-autocomplete', options.get(92 /* EditorOption.readOnly */) ? 'none' : 'both');
            this._ensureReadOnlyAttribute();
            this.textAreaCover = (0, fastDomNode_1.createFastDomNode)(document.createElement('div'));
            this.textAreaCover.setPosition('absolute');
            const simpleModel = {
                getLineCount: () => {
                    return this._context.viewModel.getLineCount();
                },
                getLineMaxColumn: (lineNumber) => {
                    return this._context.viewModel.getLineMaxColumn(lineNumber);
                },
                getValueInRange: (range, eol) => {
                    return this._context.viewModel.getValueInRange(range, eol);
                },
                getValueLengthInRange: (range, eol) => {
                    return this._context.viewModel.getValueLengthInRange(range, eol);
                },
                modifyPosition: (position, offset) => {
                    return this._context.viewModel.modifyPosition(position, offset);
                }
            };
            const textAreaInputHost = {
                getDataToCopy: () => {
                    const rawTextToCopy = this._context.viewModel.getPlainTextToCopy(this._modelSelections, this._emptySelectionClipboard, platform.isWindows);
                    const newLineCharacter = this._context.viewModel.model.getEOL();
                    const isFromEmptySelection = (this._emptySelectionClipboard && this._modelSelections.length === 1 && this._modelSelections[0].isEmpty());
                    const multicursorText = (Array.isArray(rawTextToCopy) ? rawTextToCopy : null);
                    const text = (Array.isArray(rawTextToCopy) ? rawTextToCopy.join(newLineCharacter) : rawTextToCopy);
                    let html = undefined;
                    let mode = null;
                    if (textAreaInput_1.CopyOptions.forceCopyWithSyntaxHighlighting || (this._copyWithSyntaxHighlighting && text.length < 65536)) {
                        const richText = this._context.viewModel.getRichTextToCopy(this._modelSelections, this._emptySelectionClipboard);
                        if (richText) {
                            html = richText.html;
                            mode = richText.mode;
                        }
                    }
                    return {
                        isFromEmptySelection,
                        multicursorText,
                        text,
                        html,
                        mode
                    };
                },
                getScreenReaderContent: () => {
                    if (this._accessibilitySupport === 1 /* AccessibilitySupport.Disabled */) {
                        // We know for a fact that a screen reader is not attached
                        // On OSX, we write the character before the cursor to allow for "long-press" composition
                        // Also on OSX, we write the word before the cursor to allow for the Accessibility Keyboard to give good hints
                        const selection = this._selections[0];
                        if (platform.isMacintosh && selection.isEmpty()) {
                            const position = selection.getStartPosition();
                            let textBefore = this._getWordBeforePosition(position);
                            if (textBefore.length === 0) {
                                textBefore = this._getCharacterBeforePosition(position);
                            }
                            if (textBefore.length > 0) {
                                return new textAreaState_1.TextAreaState(textBefore, textBefore.length, textBefore.length, range_1.Range.fromPositions(position), 0);
                            }
                        }
                        // on macOS, write current selection into textarea will allow system text services pick selected text,
                        // but we still want to limit the amount of text given Chromium handles very poorly text even of a few
                        // thousand chars
                        // (https://github.com/microsoft/vscode/issues/27799)
                        const LIMIT_CHARS = 500;
                        if (platform.isMacintosh && !selection.isEmpty() && simpleModel.getValueLengthInRange(selection, 0 /* EndOfLinePreference.TextDefined */) < LIMIT_CHARS) {
                            const text = simpleModel.getValueInRange(selection, 0 /* EndOfLinePreference.TextDefined */);
                            return new textAreaState_1.TextAreaState(text, 0, text.length, selection, 0);
                        }
                        // on Safari, document.execCommand('cut') and document.execCommand('copy') will just not work
                        // if the textarea has no content selected. So if there is an editor selection, ensure something
                        // is selected in the textarea.
                        if (browser.isSafari && !selection.isEmpty()) {
                            const placeholderText = 'vscode-placeholder';
                            return new textAreaState_1.TextAreaState(placeholderText, 0, placeholderText.length, null, undefined);
                        }
                        return textAreaState_1.TextAreaState.EMPTY;
                    }
                    if (browser.isAndroid) {
                        // when tapping in the editor on a word, Android enters composition mode.
                        // in the `compositionstart` event we cannot clear the textarea, because
                        // it then forgets to ever send a `compositionend`.
                        // we therefore only write the current word in the textarea
                        const selection = this._selections[0];
                        if (selection.isEmpty()) {
                            const position = selection.getStartPosition();
                            const [wordAtPosition, positionOffsetInWord] = this._getAndroidWordAtPosition(position);
                            if (wordAtPosition.length > 0) {
                                return new textAreaState_1.TextAreaState(wordAtPosition, positionOffsetInWord, positionOffsetInWord, range_1.Range.fromPositions(position), 0);
                            }
                        }
                        return textAreaState_1.TextAreaState.EMPTY;
                    }
                    return textAreaState_1.PagedScreenReaderStrategy.fromEditorSelection(simpleModel, this._selections[0], this._accessibilityPageSize, this._accessibilitySupport === 0 /* AccessibilitySupport.Unknown */);
                },
                deduceModelPosition: (viewAnchorPosition, deltaOffset, lineFeedCnt) => {
                    return this._context.viewModel.deduceModelPositionRelativeToViewPosition(viewAnchorPosition, deltaOffset, lineFeedCnt);
                }
            };
            const textAreaWrapper = this._register(new textAreaInput_1.TextAreaWrapper(this.textArea.domNode));
            this._textAreaInput = this._register(this._instantiationService.createInstance(textAreaInput_1.TextAreaInput, textAreaInputHost, textAreaWrapper, platform.OS, {
                isAndroid: browser.isAndroid,
                isChrome: browser.isChrome,
                isFirefox: browser.isFirefox,
                isSafari: browser.isSafari,
            }));
            this._register(this._textAreaInput.onKeyDown((e) => {
                this._viewController.emitKeyDown(e);
            }));
            this._register(this._textAreaInput.onKeyUp((e) => {
                this._viewController.emitKeyUp(e);
            }));
            this._register(this._textAreaInput.onPaste((e) => {
                let pasteOnNewLine = false;
                let multicursorText = null;
                let mode = null;
                if (e.metadata) {
                    pasteOnNewLine = (this._emptySelectionClipboard && !!e.metadata.isFromEmptySelection);
                    multicursorText = (typeof e.metadata.multicursorText !== 'undefined' ? e.metadata.multicursorText : null);
                    mode = e.metadata.mode;
                }
                this._viewController.paste(e.text, pasteOnNewLine, multicursorText, mode);
            }));
            this._register(this._textAreaInput.onCut(() => {
                this._viewController.cut();
            }));
            this._register(this._textAreaInput.onType((e) => {
                if (e.replacePrevCharCnt || e.replaceNextCharCnt || e.positionDelta) {
                    // must be handled through the new command
                    if (textAreaState_1._debugComposition) {
                        console.log(` => compositionType: <<${e.text}>>, ${e.replacePrevCharCnt}, ${e.replaceNextCharCnt}, ${e.positionDelta}`);
                    }
                    this._viewController.compositionType(e.text, e.replacePrevCharCnt, e.replaceNextCharCnt, e.positionDelta);
                }
                else {
                    if (textAreaState_1._debugComposition) {
                        console.log(` => type: <<${e.text}>>`);
                    }
                    this._viewController.type(e.text);
                }
            }));
            this._register(this._textAreaInput.onSelectionChangeRequest((modelSelection) => {
                this._viewController.setSelection(modelSelection);
            }));
            this._register(this._textAreaInput.onCompositionStart((e) => {
                // The textarea might contain some content when composition starts.
                //
                // When we make the textarea visible, it always has a height of 1 line,
                // so we don't need to worry too much about content on lines above or below
                // the selection.
                //
                // However, the text on the current line needs to be made visible because
                // some IME methods allow to move to other glyphs on the current line
                // (by pressing arrow keys).
                //
                // (1) The textarea might contain only some parts of the current line,
                // like the word before the selection. Also, the content inside the textarea
                // can grow or shrink as composition occurs. We therefore anchor the textarea
                // in terms of distance to a certain line start and line end.
                //
                // (2) Also, we should not make \t characters visible, because their rendering
                // inside the <textarea> will not align nicely with our rendering. We therefore
                // will hide (if necessary) some of the leading text on the current line.
                const ta = this.textArea.domNode;
                const modelSelection = this._modelSelections[0];
                const { distanceToModelLineStart, widthOfHiddenTextBefore } = (() => {
                    // Find the text that is on the current line before the selection
                    const textBeforeSelection = ta.value.substring(0, Math.min(ta.selectionStart, ta.selectionEnd));
                    const lineFeedOffset1 = textBeforeSelection.lastIndexOf('\n');
                    const lineTextBeforeSelection = textBeforeSelection.substring(lineFeedOffset1 + 1);
                    // We now search to see if we should hide some part of it (if it contains \t)
                    const tabOffset1 = lineTextBeforeSelection.lastIndexOf('\t');
                    const desiredVisibleBeforeCharCount = lineTextBeforeSelection.length - tabOffset1 - 1;
                    const startModelPosition = modelSelection.getStartPosition();
                    const visibleBeforeCharCount = Math.min(startModelPosition.column - 1, desiredVisibleBeforeCharCount);
                    const distanceToModelLineStart = startModelPosition.column - 1 - visibleBeforeCharCount;
                    const hiddenLineTextBefore = lineTextBeforeSelection.substring(0, lineTextBeforeSelection.length - visibleBeforeCharCount);
                    const { tabSize } = this._context.viewModel.model.getOptions();
                    const widthOfHiddenTextBefore = measureText(this.textArea.domNode.ownerDocument, hiddenLineTextBefore, this._fontInfo, tabSize);
                    return { distanceToModelLineStart, widthOfHiddenTextBefore };
                })();
                const { distanceToModelLineEnd } = (() => {
                    // Find the text that is on the current line after the selection
                    const textAfterSelection = ta.value.substring(Math.max(ta.selectionStart, ta.selectionEnd));
                    const lineFeedOffset2 = textAfterSelection.indexOf('\n');
                    const lineTextAfterSelection = lineFeedOffset2 === -1 ? textAfterSelection : textAfterSelection.substring(0, lineFeedOffset2);
                    const tabOffset2 = lineTextAfterSelection.indexOf('\t');
                    const desiredVisibleAfterCharCount = (tabOffset2 === -1 ? lineTextAfterSelection.length : lineTextAfterSelection.length - tabOffset2 - 1);
                    const endModelPosition = modelSelection.getEndPosition();
                    const visibleAfterCharCount = Math.min(this._context.viewModel.model.getLineMaxColumn(endModelPosition.lineNumber) - endModelPosition.column, desiredVisibleAfterCharCount);
                    const distanceToModelLineEnd = this._context.viewModel.model.getLineMaxColumn(endModelPosition.lineNumber) - endModelPosition.column - visibleAfterCharCount;
                    return { distanceToModelLineEnd };
                })();
                // Scroll to reveal the location in the editor where composition occurs
                this._context.viewModel.revealRange('keyboard', true, range_1.Range.fromPositions(this._selections[0].getStartPosition()), 0 /* viewEvents.VerticalRevealType.Simple */, 1 /* ScrollType.Immediate */);
                this._visibleTextArea = new VisibleTextAreaData(this._context, modelSelection.startLineNumber, distanceToModelLineStart, widthOfHiddenTextBefore, distanceToModelLineEnd);
                // We turn off wrapping if the <textarea> becomes visible for composition
                this.textArea.setAttribute('wrap', this._textAreaWrapping && !this._visibleTextArea ? 'on' : 'off');
                this._visibleTextArea.prepareRender(this._visibleRangeProvider);
                this._render();
                // Show the textarea
                this.textArea.setClassName(`inputarea ${mouseCursor_1.MOUSE_CURSOR_TEXT_CSS_CLASS_NAME} ime-input`);
                this._viewController.compositionStart();
                this._context.viewModel.onCompositionStart();
            }));
            this._register(this._textAreaInput.onCompositionUpdate((e) => {
                if (!this._visibleTextArea) {
                    return;
                }
                this._visibleTextArea.prepareRender(this._visibleRangeProvider);
                this._render();
            }));
            this._register(this._textAreaInput.onCompositionEnd(() => {
                this._visibleTextArea = null;
                // We turn on wrapping as necessary if the <textarea> hides after composition
                this.textArea.setAttribute('wrap', this._textAreaWrapping && !this._visibleTextArea ? 'on' : 'off');
                this._render();
                this.textArea.setClassName(`inputarea ${mouseCursor_1.MOUSE_CURSOR_TEXT_CSS_CLASS_NAME}`);
                this._viewController.compositionEnd();
                this._context.viewModel.onCompositionEnd();
            }));
            this._register(this._textAreaInput.onFocus(() => {
                this._context.viewModel.setHasFocus(true);
            }));
            this._register(this._textAreaInput.onBlur(() => {
                this._context.viewModel.setHasFocus(false);
            }));
            this._register(ime_1.IME.onDidChange(() => {
                this._ensureReadOnlyAttribute();
            }));
        }
        writeScreenReaderContent(reason) {
            this._textAreaInput.writeNativeTextAreaContent(reason);
        }
        dispose() {
            super.dispose();
        }
        _getAndroidWordAtPosition(position) {
            const ANDROID_WORD_SEPARATORS = '`~!@#$%^&*()-=+[{]}\\|;:",.<>/?';
            const lineContent = this._context.viewModel.getLineContent(position.lineNumber);
            const wordSeparators = (0, wordCharacterClassifier_1.getMapForWordSeparators)(ANDROID_WORD_SEPARATORS, []);
            let goingLeft = true;
            let startColumn = position.column;
            let goingRight = true;
            let endColumn = position.column;
            let distance = 0;
            while (distance < 50 && (goingLeft || goingRight)) {
                if (goingLeft && startColumn <= 1) {
                    goingLeft = false;
                }
                if (goingLeft) {
                    const charCode = lineContent.charCodeAt(startColumn - 2);
                    const charClass = wordSeparators.get(charCode);
                    if (charClass !== 0 /* WordCharacterClass.Regular */) {
                        goingLeft = false;
                    }
                    else {
                        startColumn--;
                    }
                }
                if (goingRight && endColumn > lineContent.length) {
                    goingRight = false;
                }
                if (goingRight) {
                    const charCode = lineContent.charCodeAt(endColumn - 1);
                    const charClass = wordSeparators.get(charCode);
                    if (charClass !== 0 /* WordCharacterClass.Regular */) {
                        goingRight = false;
                    }
                    else {
                        endColumn++;
                    }
                }
                distance++;
            }
            return [lineContent.substring(startColumn - 1, endColumn - 1), position.column - startColumn];
        }
        _getWordBeforePosition(position) {
            const lineContent = this._context.viewModel.getLineContent(position.lineNumber);
            const wordSeparators = (0, wordCharacterClassifier_1.getMapForWordSeparators)(this._context.configuration.options.get(132 /* EditorOption.wordSeparators */), []);
            let column = position.column;
            let distance = 0;
            while (column > 1) {
                const charCode = lineContent.charCodeAt(column - 2);
                const charClass = wordSeparators.get(charCode);
                if (charClass !== 0 /* WordCharacterClass.Regular */ || distance > 50) {
                    return lineContent.substring(column - 1, position.column - 1);
                }
                distance++;
                column--;
            }
            return lineContent.substring(0, position.column - 1);
        }
        _getCharacterBeforePosition(position) {
            if (position.column > 1) {
                const lineContent = this._context.viewModel.getLineContent(position.lineNumber);
                const charBefore = lineContent.charAt(position.column - 2);
                if (!strings.isHighSurrogate(charBefore.charCodeAt(0))) {
                    return charBefore;
                }
            }
            return '';
        }
        _getAriaLabel(options) {
            const accessibilitySupport = options.get(2 /* EditorOption.accessibilitySupport */);
            if (accessibilitySupport === 1 /* AccessibilitySupport.Disabled */) {
                const toggleKeybindingLabel = this._keybindingService.lookupKeybinding('editor.action.toggleScreenReaderAccessibilityMode')?.getAriaLabel();
                const runCommandKeybindingLabel = this._keybindingService.lookupKeybinding('workbench.action.showCommands')?.getAriaLabel();
                const keybindingEditorKeybindingLabel = this._keybindingService.lookupKeybinding('workbench.action.openGlobalKeybindings')?.getAriaLabel();
                const editorNotAccessibleMessage = nls.localize(55, "The editor is not accessible at this time.");
                if (toggleKeybindingLabel) {
                    return nls.localize(56, "{0} To enable screen reader optimized mode, use {1}", editorNotAccessibleMessage, toggleKeybindingLabel);
                }
                else if (runCommandKeybindingLabel) {
                    return nls.localize(57, "{0} To enable screen reader optimized mode, open the quick pick with {1} and run the command Toggle Screen Reader Accessibility Mode, which is currently not triggerable via keyboard.", editorNotAccessibleMessage, runCommandKeybindingLabel);
                }
                else if (keybindingEditorKeybindingLabel) {
                    return nls.localize(58, "{0} Please assign a keybinding for the command Toggle Screen Reader Accessibility Mode by accessing the keybindings editor with {1} and run it.", editorNotAccessibleMessage, keybindingEditorKeybindingLabel);
                }
                else {
                    // SOS
                    return editorNotAccessibleMessage;
                }
            }
            return options.get(4 /* EditorOption.ariaLabel */);
        }
        _setAccessibilityOptions(options) {
            this._accessibilitySupport = options.get(2 /* EditorOption.accessibilitySupport */);
            const accessibilityPageSize = options.get(3 /* EditorOption.accessibilityPageSize */);
            if (this._accessibilitySupport === 2 /* AccessibilitySupport.Enabled */ && accessibilityPageSize === editorOptions_1.EditorOptions.accessibilityPageSize.defaultValue) {
                // If a screen reader is attached and the default value is not set we should automatically increase the page size to 500 for a better experience
                this._accessibilityPageSize = 500;
            }
            else {
                this._accessibilityPageSize = accessibilityPageSize;
            }
            // When wrapping is enabled and a screen reader might be attached,
            // we will size the textarea to match the width used for wrapping points computation (see `domLineBreaksComputer.ts`).
            // This is because screen readers will read the text in the textarea and we'd like that the
            // wrapping points in the textarea match the wrapping points in the editor.
            const layoutInfo = options.get(146 /* EditorOption.layoutInfo */);
            const wrappingColumn = layoutInfo.wrappingColumn;
            if (wrappingColumn !== -1 && this._accessibilitySupport !== 1 /* AccessibilitySupport.Disabled */) {
                const fontInfo = options.get(50 /* EditorOption.fontInfo */);
                this._textAreaWrapping = true;
                this._textAreaWidth = Math.round(wrappingColumn * fontInfo.typicalHalfwidthCharacterWidth);
            }
            else {
                this._textAreaWrapping = false;
                this._textAreaWidth = (canUseZeroSizeTextarea ? 0 : 1);
            }
        }
        // --- begin event handlers
        onConfigurationChanged(e) {
            const options = this._context.configuration.options;
            const layoutInfo = options.get(146 /* EditorOption.layoutInfo */);
            this._setAccessibilityOptions(options);
            this._contentLeft = layoutInfo.contentLeft;
            this._contentWidth = layoutInfo.contentWidth;
            this._contentHeight = layoutInfo.height;
            this._fontInfo = options.get(50 /* EditorOption.fontInfo */);
            this._lineHeight = options.get(67 /* EditorOption.lineHeight */);
            this._emptySelectionClipboard = options.get(37 /* EditorOption.emptySelectionClipboard */);
            this._copyWithSyntaxHighlighting = options.get(25 /* EditorOption.copyWithSyntaxHighlighting */);
            this.textArea.setAttribute('wrap', this._textAreaWrapping && !this._visibleTextArea ? 'on' : 'off');
            const { tabSize } = this._context.viewModel.model.getOptions();
            this.textArea.domNode.style.tabSize = `${tabSize * this._fontInfo.spaceWidth}px`;
            this.textArea.setAttribute('aria-label', this._getAriaLabel(options));
            this.textArea.setAttribute('aria-required', options.get(5 /* EditorOption.ariaRequired */) ? 'true' : 'false');
            this.textArea.setAttribute('tabindex', String(options.get(125 /* EditorOption.tabIndex */)));
            if (e.hasChanged(34 /* EditorOption.domReadOnly */) || e.hasChanged(92 /* EditorOption.readOnly */)) {
                this._ensureReadOnlyAttribute();
            }
            if (e.hasChanged(2 /* EditorOption.accessibilitySupport */)) {
                this._textAreaInput.writeNativeTextAreaContent('strategy changed');
            }
            return true;
        }
        onCursorStateChanged(e) {
            this._selections = e.selections.slice(0);
            this._modelSelections = e.modelSelections.slice(0);
            // We must update the <textarea> synchronously, otherwise long press IME on macos breaks.
            // See https://github.com/microsoft/vscode/issues/165821
            this._textAreaInput.writeNativeTextAreaContent('selection changed');
            return true;
        }
        onDecorationsChanged(e) {
            // true for inline decorations that can end up relayouting text
            return true;
        }
        onFlushed(e) {
            return true;
        }
        onLinesChanged(e) {
            return true;
        }
        onLinesDeleted(e) {
            return true;
        }
        onLinesInserted(e) {
            return true;
        }
        onScrollChanged(e) {
            this._scrollLeft = e.scrollLeft;
            this._scrollTop = e.scrollTop;
            return true;
        }
        onZonesChanged(e) {
            return true;
        }
        // --- end event handlers
        // --- begin view API
        isFocused() {
            return this._textAreaInput.isFocused();
        }
        focusTextArea() {
            this._textAreaInput.focusTextArea();
        }
        getLastRenderData() {
            return this._lastRenderPosition;
        }
        setAriaOptions(options) {
            if (options.activeDescendant) {
                this.textArea.setAttribute('aria-haspopup', 'true');
                this.textArea.setAttribute('aria-autocomplete', 'list');
                this.textArea.setAttribute('aria-activedescendant', options.activeDescendant);
            }
            else {
                this.textArea.setAttribute('aria-haspopup', 'false');
                this.textArea.setAttribute('aria-autocomplete', 'both');
                this.textArea.removeAttribute('aria-activedescendant');
            }
            if (options.role) {
                this.textArea.setAttribute('role', options.role);
            }
        }
        // --- end view API
        _ensureReadOnlyAttribute() {
            const options = this._context.configuration.options;
            // When someone requests to disable IME, we set the "readonly" attribute on the <textarea>.
            // This will prevent composition.
            const useReadOnly = !ime_1.IME.enabled || (options.get(34 /* EditorOption.domReadOnly */) && options.get(92 /* EditorOption.readOnly */));
            if (useReadOnly) {
                this.textArea.setAttribute('readonly', 'true');
            }
            else {
                this.textArea.removeAttribute('readonly');
            }
        }
        prepareRender(ctx) {
            this._primaryCursorPosition = new position_1.Position(this._selections[0].positionLineNumber, this._selections[0].positionColumn);
            this._primaryCursorVisibleRange = ctx.visibleRangeForPosition(this._primaryCursorPosition);
            this._visibleTextArea?.prepareRender(ctx);
        }
        render(ctx) {
            this._textAreaInput.writeNativeTextAreaContent('render');
            this._render();
        }
        _render() {
            if (this._visibleTextArea) {
                // The text area is visible for composition reasons
                const visibleStart = this._visibleTextArea.visibleTextareaStart;
                const visibleEnd = this._visibleTextArea.visibleTextareaEnd;
                const startPosition = this._visibleTextArea.startPosition;
                const endPosition = this._visibleTextArea.endPosition;
                if (startPosition && endPosition && visibleStart && visibleEnd && visibleEnd.left >= this._scrollLeft && visibleStart.left <= this._scrollLeft + this._contentWidth) {
                    const top = (this._context.viewLayout.getVerticalOffsetForLineNumber(this._primaryCursorPosition.lineNumber) - this._scrollTop);
                    const lineCount = this._newlinecount(this.textArea.domNode.value.substr(0, this.textArea.domNode.selectionStart));
                    let scrollLeft = this._visibleTextArea.widthOfHiddenLineTextBefore;
                    let left = (this._contentLeft + visibleStart.left - this._scrollLeft);
                    // See https://github.com/microsoft/vscode/issues/141725#issuecomment-1050670841
                    // Here we are adding +1 to avoid flickering that might be caused by having a width that is too small.
                    // This could be caused by rounding errors that might only show up with certain font families.
                    // In other words, a pixel might be lost when doing something like
                    //      `Math.round(end) - Math.round(start)`
                    // vs
                    //      `Math.round(end - start)`
                    let width = visibleEnd.left - visibleStart.left + 1;
                    if (left < this._contentLeft) {
                        // the textarea would be rendered on top of the margin,
                        // so reduce its width. We use the same technique as
                        // for hiding text before
                        const delta = (this._contentLeft - left);
                        left += delta;
                        scrollLeft += delta;
                        width -= delta;
                    }
                    if (width > this._contentWidth) {
                        // the textarea would be wider than the content width,
                        // so reduce its width.
                        width = this._contentWidth;
                    }
                    // Try to render the textarea with the color/font style to match the text under it
                    const viewLineData = this._context.viewModel.getViewLineData(startPosition.lineNumber);
                    const startTokenIndex = viewLineData.tokens.findTokenIndexAtOffset(startPosition.column - 1);
                    const endTokenIndex = viewLineData.tokens.findTokenIndexAtOffset(endPosition.column - 1);
                    const textareaSpansSingleToken = (startTokenIndex === endTokenIndex);
                    const presentation = this._visibleTextArea.definePresentation((textareaSpansSingleToken ? viewLineData.tokens.getPresentation(startTokenIndex) : null));
                    this.textArea.domNode.scrollTop = lineCount * this._lineHeight;
                    this.textArea.domNode.scrollLeft = scrollLeft;
                    this._doRender({
                        lastRenderPosition: null,
                        top: top,
                        left: left,
                        width: width,
                        height: this._lineHeight,
                        useCover: false,
                        color: (languages_1.TokenizationRegistry.getColorMap() || [])[presentation.foreground],
                        italic: presentation.italic,
                        bold: presentation.bold,
                        underline: presentation.underline,
                        strikethrough: presentation.strikethrough
                    });
                }
                return;
            }
            if (!this._primaryCursorVisibleRange) {
                // The primary cursor is outside the viewport => place textarea to the top left
                this._renderAtTopLeft();
                return;
            }
            const left = this._contentLeft + this._primaryCursorVisibleRange.left - this._scrollLeft;
            if (left < this._contentLeft || left > this._contentLeft + this._contentWidth) {
                // cursor is outside the viewport
                this._renderAtTopLeft();
                return;
            }
            const top = this._context.viewLayout.getVerticalOffsetForLineNumber(this._selections[0].positionLineNumber) - this._scrollTop;
            if (top < 0 || top > this._contentHeight) {
                // cursor is outside the viewport
                this._renderAtTopLeft();
                return;
            }
            // The primary cursor is in the viewport (at least vertically) => place textarea on the cursor
            if (platform.isMacintosh || this._accessibilitySupport === 2 /* AccessibilitySupport.Enabled */) {
                // For the popup emoji input, we will make the text area as high as the line height
                // We will also make the fontSize and lineHeight the correct dimensions to help with the placement of these pickers
                this._doRender({
                    lastRenderPosition: this._primaryCursorPosition,
                    top,
                    left: this._textAreaWrapping ? this._contentLeft : left,
                    width: this._textAreaWidth,
                    height: this._lineHeight,
                    useCover: false
                });
                // In case the textarea contains a word, we're going to try to align the textarea's cursor
                // with our cursor by scrolling the textarea as much as possible
                this.textArea.domNode.scrollLeft = this._primaryCursorVisibleRange.left;
                const lineCount = this._textAreaInput.textAreaState.newlineCountBeforeSelection ?? this._newlinecount(this.textArea.domNode.value.substr(0, this.textArea.domNode.selectionStart));
                this.textArea.domNode.scrollTop = lineCount * this._lineHeight;
                return;
            }
            this._doRender({
                lastRenderPosition: this._primaryCursorPosition,
                top: top,
                left: this._textAreaWrapping ? this._contentLeft : left,
                width: this._textAreaWidth,
                height: (canUseZeroSizeTextarea ? 0 : 1),
                useCover: false
            });
        }
        _newlinecount(text) {
            let result = 0;
            let startIndex = -1;
            do {
                startIndex = text.indexOf('\n', startIndex + 1);
                if (startIndex === -1) {
                    break;
                }
                result++;
            } while (true);
            return result;
        }
        _renderAtTopLeft() {
            // (in WebKit the textarea is 1px by 1px because it cannot handle input to a 0x0 textarea)
            // specifically, when doing Korean IME, setting the textarea to 0x0 breaks IME badly.
            this._doRender({
                lastRenderPosition: null,
                top: 0,
                left: 0,
                width: this._textAreaWidth,
                height: (canUseZeroSizeTextarea ? 0 : 1),
                useCover: true
            });
        }
        _doRender(renderData) {
            this._lastRenderPosition = renderData.lastRenderPosition;
            const ta = this.textArea;
            const tac = this.textAreaCover;
            (0, domFontInfo_1.applyFontInfo)(ta, this._fontInfo);
            ta.setTop(renderData.top);
            ta.setLeft(renderData.left);
            ta.setWidth(renderData.width);
            ta.setHeight(renderData.height);
            ta.setColor(renderData.color ? color_1.Color.Format.CSS.formatHex(renderData.color) : '');
            ta.setFontStyle(renderData.italic ? 'italic' : '');
            if (renderData.bold) {
                // fontWeight is also set by `applyFontInfo`, so only overwrite it if necessary
                ta.setFontWeight('bold');
            }
            ta.setTextDecoration(`${renderData.underline ? ' underline' : ''}${renderData.strikethrough ? ' line-through' : ''}`);
            tac.setTop(renderData.useCover ? renderData.top : 0);
            tac.setLeft(renderData.useCover ? renderData.left : 0);
            tac.setWidth(renderData.useCover ? renderData.width : 0);
            tac.setHeight(renderData.useCover ? renderData.height : 0);
            const options = this._context.configuration.options;
            if (options.get(57 /* EditorOption.glyphMargin */)) {
                tac.setClassName('monaco-editor-background textAreaCover ' + margin_1.Margin.OUTER_CLASS_NAME);
            }
            else {
                if (options.get(68 /* EditorOption.lineNumbers */).renderType !== 0 /* RenderLineNumbersType.Off */) {
                    tac.setClassName('monaco-editor-background textAreaCover ' + lineNumbers_1.LineNumbersOverlay.CLASS_NAME);
                }
                else {
                    tac.setClassName('monaco-editor-background textAreaCover');
                }
            }
        }
    };
    exports.TextAreaHandler = TextAreaHandler;
    exports.TextAreaHandler = TextAreaHandler = __decorate([
        __param(3, keybinding_1.IKeybindingService),
        __param(4, instantiation_1.IInstantiationService)
    ], TextAreaHandler);
    function measureText(targetDocument, text, fontInfo, tabSize) {
        if (text.length === 0) {
            return 0;
        }
        const container = targetDocument.createElement('div');
        container.style.position = 'absolute';
        container.style.top = '-50000px';
        container.style.width = '50000px';
        const regularDomNode = targetDocument.createElement('span');
        (0, domFontInfo_1.applyFontInfo)(regularDomNode, fontInfo);
        regularDomNode.style.whiteSpace = 'pre'; // just like the textarea
        regularDomNode.style.tabSize = `${tabSize * fontInfo.spaceWidth}px`; // just like the textarea
        regularDomNode.append(text);
        container.appendChild(regularDomNode);
        targetDocument.body.appendChild(container);
        const res = regularDomNode.offsetWidth;
        container.remove();
        return res;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[779/*vs/editor/browser/viewParts/overviewRuler/decorationsOverviewRuler*/], __M([1/*require*/,0/*exports*/,39/*vs/base/browser/fastDomNode*/,33/*vs/base/common/color*/,56/*vs/editor/browser/view/viewPart*/,9/*vs/editor/common/core/position*/,27/*vs/editor/common/languages*/,80/*vs/editor/common/core/editorColorRegistry*/,95/*vs/editor/common/viewModel*/,13/*vs/base/common/arrays*/]), function (require, exports, fastDomNode_1, color_1, viewPart_1, position_1, languages_1, editorColorRegistry_1, viewModel_1, arrays_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DecorationsOverviewRuler = void 0;
    class Settings {
        constructor(config, theme) {
            const options = config.options;
            this.lineHeight = options.get(67 /* EditorOption.lineHeight */);
            this.pixelRatio = options.get(144 /* EditorOption.pixelRatio */);
            this.overviewRulerLanes = options.get(83 /* EditorOption.overviewRulerLanes */);
            this.renderBorder = options.get(82 /* EditorOption.overviewRulerBorder */);
            const borderColor = theme.getColor(editorColorRegistry_1.editorOverviewRulerBorder);
            this.borderColor = borderColor ? borderColor.toString() : null;
            this.hideCursor = options.get(59 /* EditorOption.hideCursorInOverviewRuler */);
            const cursorColorSingle = theme.getColor(editorColorRegistry_1.editorCursorForeground);
            this.cursorColorSingle = cursorColorSingle ? cursorColorSingle.transparent(0.7).toString() : null;
            const cursorColorPrimary = theme.getColor(editorColorRegistry_1.editorMultiCursorPrimaryForeground);
            this.cursorColorPrimary = cursorColorPrimary ? cursorColorPrimary.transparent(0.7).toString() : null;
            const cursorColorSecondary = theme.getColor(editorColorRegistry_1.editorMultiCursorSecondaryForeground);
            this.cursorColorSecondary = cursorColorSecondary ? cursorColorSecondary.transparent(0.7).toString() : null;
            this.themeType = theme.type;
            const minimapOpts = options.get(73 /* EditorOption.minimap */);
            const minimapEnabled = minimapOpts.enabled;
            const minimapSide = minimapOpts.side;
            const themeColor = theme.getColor(editorColorRegistry_1.editorOverviewRulerBackground);
            const defaultBackground = languages_1.TokenizationRegistry.getDefaultBackground();
            if (themeColor) {
                this.backgroundColor = themeColor;
            }
            else if (minimapEnabled && minimapSide === 'right') {
                this.backgroundColor = defaultBackground;
            }
            else {
                this.backgroundColor = null;
            }
            const layoutInfo = options.get(146 /* EditorOption.layoutInfo */);
            const position = layoutInfo.overviewRuler;
            this.top = position.top;
            this.right = position.right;
            this.domWidth = position.width;
            this.domHeight = position.height;
            if (this.overviewRulerLanes === 0) {
                // overview ruler is off
                this.canvasWidth = 0;
                this.canvasHeight = 0;
            }
            else {
                this.canvasWidth = (this.domWidth * this.pixelRatio) | 0;
                this.canvasHeight = (this.domHeight * this.pixelRatio) | 0;
            }
            const [x, w] = this._initLanes(1, this.canvasWidth, this.overviewRulerLanes);
            this.x = x;
            this.w = w;
        }
        _initLanes(canvasLeftOffset, canvasWidth, laneCount) {
            const remainingWidth = canvasWidth - canvasLeftOffset;
            if (laneCount >= 3) {
                const leftWidth = Math.floor(remainingWidth / 3);
                const rightWidth = Math.floor(remainingWidth / 3);
                const centerWidth = remainingWidth - leftWidth - rightWidth;
                const leftOffset = canvasLeftOffset;
                const centerOffset = leftOffset + leftWidth;
                const rightOffset = leftOffset + leftWidth + centerWidth;
                return [
                    [
                        0,
                        leftOffset, // Left
                        centerOffset, // Center
                        leftOffset, // Left | Center
                        rightOffset, // Right
                        leftOffset, // Left | Right
                        centerOffset, // Center | Right
                        leftOffset, // Left | Center | Right
                    ], [
                        0,
                        leftWidth, // Left
                        centerWidth, // Center
                        leftWidth + centerWidth, // Left | Center
                        rightWidth, // Right
                        leftWidth + centerWidth + rightWidth, // Left | Right
                        centerWidth + rightWidth, // Center | Right
                        leftWidth + centerWidth + rightWidth, // Left | Center | Right
                    ]
                ];
            }
            else if (laneCount === 2) {
                const leftWidth = Math.floor(remainingWidth / 2);
                const rightWidth = remainingWidth - leftWidth;
                const leftOffset = canvasLeftOffset;
                const rightOffset = leftOffset + leftWidth;
                return [
                    [
                        0,
                        leftOffset, // Left
                        leftOffset, // Center
                        leftOffset, // Left | Center
                        rightOffset, // Right
                        leftOffset, // Left | Right
                        leftOffset, // Center | Right
                        leftOffset, // Left | Center | Right
                    ], [
                        0,
                        leftWidth, // Left
                        leftWidth, // Center
                        leftWidth, // Left | Center
                        rightWidth, // Right
                        leftWidth + rightWidth, // Left | Right
                        leftWidth + rightWidth, // Center | Right
                        leftWidth + rightWidth, // Left | Center | Right
                    ]
                ];
            }
            else {
                const offset = canvasLeftOffset;
                const width = remainingWidth;
                return [
                    [
                        0,
                        offset, // Left
                        offset, // Center
                        offset, // Left | Center
                        offset, // Right
                        offset, // Left | Right
                        offset, // Center | Right
                        offset, // Left | Center | Right
                    ], [
                        0,
                        width, // Left
                        width, // Center
                        width, // Left | Center
                        width, // Right
                        width, // Left | Right
                        width, // Center | Right
                        width, // Left | Center | Right
                    ]
                ];
            }
        }
        equals(other) {
            return (this.lineHeight === other.lineHeight
                && this.pixelRatio === other.pixelRatio
                && this.overviewRulerLanes === other.overviewRulerLanes
                && this.renderBorder === other.renderBorder
                && this.borderColor === other.borderColor
                && this.hideCursor === other.hideCursor
                && this.cursorColorSingle === other.cursorColorSingle
                && this.cursorColorPrimary === other.cursorColorPrimary
                && this.cursorColorSecondary === other.cursorColorSecondary
                && this.themeType === other.themeType
                && color_1.Color.equals(this.backgroundColor, other.backgroundColor)
                && this.top === other.top
                && this.right === other.right
                && this.domWidth === other.domWidth
                && this.domHeight === other.domHeight
                && this.canvasWidth === other.canvasWidth
                && this.canvasHeight === other.canvasHeight);
        }
    }
    class DecorationsOverviewRuler extends viewPart_1.ViewPart {
        constructor(context) {
            super(context);
            this._actualShouldRender = 0 /* ShouldRenderValue.NotNeeded */;
            this._renderedDecorations = [];
            this._renderedCursorPositions = [];
            this._domNode = (0, fastDomNode_1.createFastDomNode)(document.createElement('canvas'));
            this._domNode.setClassName('decorationsOverviewRuler');
            this._domNode.setPosition('absolute');
            this._domNode.setLayerHinting(true);
            this._domNode.setContain('strict');
            this._domNode.setAttribute('aria-hidden', 'true');
            this._updateSettings(false);
            this._tokensColorTrackerListener = languages_1.TokenizationRegistry.onDidChange((e) => {
                if (e.changedColorMap) {
                    this._updateSettings(true);
                }
            });
            this._cursorPositions = [{ position: new position_1.Position(1, 1), color: this._settings.cursorColorSingle }];
        }
        dispose() {
            super.dispose();
            this._tokensColorTrackerListener.dispose();
        }
        _updateSettings(renderNow) {
            const newSettings = new Settings(this._context.configuration, this._context.theme);
            if (this._settings && this._settings.equals(newSettings)) {
                // nothing to do
                return false;
            }
            this._settings = newSettings;
            this._domNode.setTop(this._settings.top);
            this._domNode.setRight(this._settings.right);
            this._domNode.setWidth(this._settings.domWidth);
            this._domNode.setHeight(this._settings.domHeight);
            this._domNode.domNode.width = this._settings.canvasWidth;
            this._domNode.domNode.height = this._settings.canvasHeight;
            if (renderNow) {
                this._render();
            }
            return true;
        }
        // ---- begin view event handlers
        _markRenderingIsNeeded() {
            this._actualShouldRender = 2 /* ShouldRenderValue.Needed */;
            return true;
        }
        _markRenderingIsMaybeNeeded() {
            this._actualShouldRender = 1 /* ShouldRenderValue.Maybe */;
            return true;
        }
        onConfigurationChanged(e) {
            return this._updateSettings(false) ? this._markRenderingIsNeeded() : false;
        }
        onCursorStateChanged(e) {
            this._cursorPositions = [];
            for (let i = 0, len = e.selections.length; i < len; i++) {
                let color = this._settings.cursorColorSingle;
                if (len > 1) {
                    color = i === 0 ? this._settings.cursorColorPrimary : this._settings.cursorColorSecondary;
                }
                this._cursorPositions.push({ position: e.selections[i].getPosition(), color });
            }
            this._cursorPositions.sort((a, b) => position_1.Position.compare(a.position, b.position));
            return this._markRenderingIsMaybeNeeded();
        }
        onDecorationsChanged(e) {
            if (e.affectsOverviewRuler) {
                return this._markRenderingIsMaybeNeeded();
            }
            return false;
        }
        onFlushed(e) {
            return this._markRenderingIsNeeded();
        }
        onScrollChanged(e) {
            return e.scrollHeightChanged ? this._markRenderingIsNeeded() : false;
        }
        onZonesChanged(e) {
            return this._markRenderingIsNeeded();
        }
        onThemeChanged(e) {
            return this._updateSettings(false) ? this._markRenderingIsNeeded() : false;
        }
        // ---- end view event handlers
        getDomNode() {
            return this._domNode.domNode;
        }
        prepareRender(ctx) {
            // Nothing to read
        }
        render(editorCtx) {
            this._render();
            this._actualShouldRender = 0 /* ShouldRenderValue.NotNeeded */;
        }
        _render() {
            const backgroundColor = this._settings.backgroundColor;
            if (this._settings.overviewRulerLanes === 0) {
                // overview ruler is off
                this._domNode.setBackgroundColor(backgroundColor ? color_1.Color.Format.CSS.formatHexA(backgroundColor) : '');
                this._domNode.setDisplay('none');
                return;
            }
            const decorations = this._context.viewModel.getAllOverviewRulerDecorations(this._context.theme);
            decorations.sort(viewModel_1.OverviewRulerDecorationsGroup.compareByRenderingProps);
            if (this._actualShouldRender === 1 /* ShouldRenderValue.Maybe */ && !viewModel_1.OverviewRulerDecorationsGroup.equalsArr(this._renderedDecorations, decorations)) {
                this._actualShouldRender = 2 /* ShouldRenderValue.Needed */;
            }
            if (this._actualShouldRender === 1 /* ShouldRenderValue.Maybe */ && !(0, arrays_1.equals)(this._renderedCursorPositions, this._cursorPositions, (a, b) => a.position.lineNumber === b.position.lineNumber && a.color === b.color)) {
                this._actualShouldRender = 2 /* ShouldRenderValue.Needed */;
            }
            if (this._actualShouldRender === 1 /* ShouldRenderValue.Maybe */) {
                // both decorations and cursor positions are unchanged, nothing to do
                return;
            }
            this._renderedDecorations = decorations;
            this._renderedCursorPositions = this._cursorPositions;
            this._domNode.setDisplay('block');
            const canvasWidth = this._settings.canvasWidth;
            const canvasHeight = this._settings.canvasHeight;
            const lineHeight = this._settings.lineHeight;
            const viewLayout = this._context.viewLayout;
            const outerHeight = this._context.viewLayout.getScrollHeight();
            const heightRatio = canvasHeight / outerHeight;
            const minDecorationHeight = (6 /* Constants.MIN_DECORATION_HEIGHT */ * this._settings.pixelRatio) | 0;
            const halfMinDecorationHeight = (minDecorationHeight / 2) | 0;
            const canvasCtx = this._domNode.domNode.getContext('2d');
            if (backgroundColor) {
                if (backgroundColor.isOpaque()) {
                    // We have a background color which is opaque, we can just paint the entire surface with it
                    canvasCtx.fillStyle = color_1.Color.Format.CSS.formatHexA(backgroundColor);
                    canvasCtx.fillRect(0, 0, canvasWidth, canvasHeight);
                }
                else {
                    // We have a background color which is transparent, we need to first clear the surface and
                    // then fill it
                    canvasCtx.clearRect(0, 0, canvasWidth, canvasHeight);
                    canvasCtx.fillStyle = color_1.Color.Format.CSS.formatHexA(backgroundColor);
                    canvasCtx.fillRect(0, 0, canvasWidth, canvasHeight);
                }
            }
            else {
                // We don't have a background color
                canvasCtx.clearRect(0, 0, canvasWidth, canvasHeight);
            }
            const x = this._settings.x;
            const w = this._settings.w;
            for (const decorationGroup of decorations) {
                const color = decorationGroup.color;
                const decorationGroupData = decorationGroup.data;
                canvasCtx.fillStyle = color;
                let prevLane = 0;
                let prevY1 = 0;
                let prevY2 = 0;
                for (let i = 0, len = decorationGroupData.length / 3; i < len; i++) {
                    const lane = decorationGroupData[3 * i];
                    const startLineNumber = decorationGroupData[3 * i + 1];
                    const endLineNumber = decorationGroupData[3 * i + 2];
                    let y1 = (viewLayout.getVerticalOffsetForLineNumber(startLineNumber) * heightRatio) | 0;
                    let y2 = ((viewLayout.getVerticalOffsetForLineNumber(endLineNumber) + lineHeight) * heightRatio) | 0;
                    const height = y2 - y1;
                    if (height < minDecorationHeight) {
                        let yCenter = ((y1 + y2) / 2) | 0;
                        if (yCenter < halfMinDecorationHeight) {
                            yCenter = halfMinDecorationHeight;
                        }
                        else if (yCenter + halfMinDecorationHeight > canvasHeight) {
                            yCenter = canvasHeight - halfMinDecorationHeight;
                        }
                        y1 = yCenter - halfMinDecorationHeight;
                        y2 = yCenter + halfMinDecorationHeight;
                    }
                    if (y1 > prevY2 + 1 || lane !== prevLane) {
                        // flush prev
                        if (i !== 0) {
                            canvasCtx.fillRect(x[prevLane], prevY1, w[prevLane], prevY2 - prevY1);
                        }
                        prevLane = lane;
                        prevY1 = y1;
                        prevY2 = y2;
                    }
                    else {
                        // merge into prev
                        if (y2 > prevY2) {
                            prevY2 = y2;
                        }
                    }
                }
                canvasCtx.fillRect(x[prevLane], prevY1, w[prevLane], prevY2 - prevY1);
            }
            // Draw cursors
            if (!this._settings.hideCursor) {
                const cursorHeight = (2 * this._settings.pixelRatio) | 0;
                const halfCursorHeight = (cursorHeight / 2) | 0;
                const cursorX = this._settings.x[7 /* OverviewRulerLane.Full */];
                const cursorW = this._settings.w[7 /* OverviewRulerLane.Full */];
                let prevY1 = -100;
                let prevY2 = -100;
                let prevColor = null;
                for (let i = 0, len = this._cursorPositions.length; i < len; i++) {
                    const color = this._cursorPositions[i].color;
                    if (!color) {
                        continue;
                    }
                    const cursor = this._cursorPositions[i].position;
                    let yCenter = (viewLayout.getVerticalOffsetForLineNumber(cursor.lineNumber) * heightRatio) | 0;
                    if (yCenter < halfCursorHeight) {
                        yCenter = halfCursorHeight;
                    }
                    else if (yCenter + halfCursorHeight > canvasHeight) {
                        yCenter = canvasHeight - halfCursorHeight;
                    }
                    const y1 = yCenter - halfCursorHeight;
                    const y2 = y1 + cursorHeight;
                    if (y1 > prevY2 + 1 || color !== prevColor) {
                        // flush prev
                        if (i !== 0 && prevColor) {
                            canvasCtx.fillRect(cursorX, prevY1, cursorW, prevY2 - prevY1);
                        }
                        prevY1 = y1;
                        prevY2 = y2;
                    }
                    else {
                        // merge into prev
                        if (y2 > prevY2) {
                            prevY2 = y2;
                        }
                    }
                    prevColor = color;
                    canvasCtx.fillStyle = color;
                }
                if (prevColor) {
                    canvasCtx.fillRect(cursorX, prevY1, cursorW, prevY2 - prevY1);
                }
            }
            if (this._settings.renderBorder && this._settings.borderColor && this._settings.overviewRulerLanes > 0) {
                canvasCtx.beginPath();
                canvasCtx.lineWidth = 1;
                canvasCtx.strokeStyle = this._settings.borderColor;
                canvasCtx.moveTo(0, 0);
                canvasCtx.lineTo(0, canvasHeight);
                canvasCtx.moveTo(1, 0);
                canvasCtx.lineTo(canvasWidth, 0);
                canvasCtx.stroke();
            }
        }
    }
    exports.DecorationsOverviewRuler = DecorationsOverviewRuler;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[780/*vs/editor/browser/viewParts/viewCursors/viewCursors*/], __M([1/*require*/,0/*exports*/,39/*vs/base/browser/fastDomNode*/,14/*vs/base/common/async*/,56/*vs/editor/browser/view/viewPart*/,655/*vs/editor/browser/viewParts/viewCursors/viewCursor*/,37/*vs/editor/common/config/editorOptions*/,80/*vs/editor/common/core/editorColorRegistry*/,25/*vs/platform/theme/common/themeService*/,97/*vs/platform/theme/common/theme*/,5/*vs/base/browser/dom*/,496/*vs/css!vs/editor/browser/viewParts/viewCursors/viewCursors*/]), function (require, exports, fastDomNode_1, async_1, viewPart_1, viewCursor_1, editorOptions_1, editorColorRegistry_1, themeService_1, theme_1, dom_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ViewCursors = void 0;
    class ViewCursors extends viewPart_1.ViewPart {
        static { this.BLINK_INTERVAL = 500; }
        constructor(context) {
            super(context);
            const options = this._context.configuration.options;
            this._readOnly = options.get(92 /* EditorOption.readOnly */);
            this._cursorBlinking = options.get(26 /* EditorOption.cursorBlinking */);
            this._cursorStyle = options.get(28 /* EditorOption.cursorStyle */);
            this._cursorSmoothCaretAnimation = options.get(27 /* EditorOption.cursorSmoothCaretAnimation */);
            this._selectionIsEmpty = true;
            this._isComposingInput = false;
            this._isVisible = false;
            this._primaryCursor = new viewCursor_1.ViewCursor(this._context, viewCursor_1.CursorPlurality.Single);
            this._secondaryCursors = [];
            this._renderData = [];
            this._domNode = (0, fastDomNode_1.createFastDomNode)(document.createElement('div'));
            this._domNode.setAttribute('role', 'presentation');
            this._domNode.setAttribute('aria-hidden', 'true');
            this._updateDomClassName();
            this._domNode.appendChild(this._primaryCursor.getDomNode());
            this._startCursorBlinkAnimation = new async_1.TimeoutTimer();
            this._cursorFlatBlinkInterval = new dom_1.WindowIntervalTimer();
            this._blinkingEnabled = false;
            this._editorHasFocus = false;
            this._updateBlinking();
        }
        dispose() {
            super.dispose();
            this._startCursorBlinkAnimation.dispose();
            this._cursorFlatBlinkInterval.dispose();
        }
        getDomNode() {
            return this._domNode;
        }
        // --- begin event handlers
        onCompositionStart(e) {
            this._isComposingInput = true;
            this._updateBlinking();
            return true;
        }
        onCompositionEnd(e) {
            this._isComposingInput = false;
            this._updateBlinking();
            return true;
        }
        onConfigurationChanged(e) {
            const options = this._context.configuration.options;
            this._readOnly = options.get(92 /* EditorOption.readOnly */);
            this._cursorBlinking = options.get(26 /* EditorOption.cursorBlinking */);
            this._cursorStyle = options.get(28 /* EditorOption.cursorStyle */);
            this._cursorSmoothCaretAnimation = options.get(27 /* EditorOption.cursorSmoothCaretAnimation */);
            this._updateBlinking();
            this._updateDomClassName();
            this._primaryCursor.onConfigurationChanged(e);
            for (let i = 0, len = this._secondaryCursors.length; i < len; i++) {
                this._secondaryCursors[i].onConfigurationChanged(e);
            }
            return true;
        }
        _onCursorPositionChanged(position, secondaryPositions, reason) {
            const pauseAnimation = (this._secondaryCursors.length !== secondaryPositions.length
                || (this._cursorSmoothCaretAnimation === 'explicit' && reason !== 3 /* CursorChangeReason.Explicit */));
            this._primaryCursor.setPlurality(secondaryPositions.length ? viewCursor_1.CursorPlurality.MultiPrimary : viewCursor_1.CursorPlurality.Single);
            this._primaryCursor.onCursorPositionChanged(position, pauseAnimation);
            this._updateBlinking();
            if (this._secondaryCursors.length < secondaryPositions.length) {
                // Create new cursors
                const addCnt = secondaryPositions.length - this._secondaryCursors.length;
                for (let i = 0; i < addCnt; i++) {
                    const newCursor = new viewCursor_1.ViewCursor(this._context, viewCursor_1.CursorPlurality.MultiSecondary);
                    this._domNode.domNode.insertBefore(newCursor.getDomNode().domNode, this._primaryCursor.getDomNode().domNode.nextSibling);
                    this._secondaryCursors.push(newCursor);
                }
            }
            else if (this._secondaryCursors.length > secondaryPositions.length) {
                // Remove some cursors
                const removeCnt = this._secondaryCursors.length - secondaryPositions.length;
                for (let i = 0; i < removeCnt; i++) {
                    this._domNode.removeChild(this._secondaryCursors[0].getDomNode());
                    this._secondaryCursors.splice(0, 1);
                }
            }
            for (let i = 0; i < secondaryPositions.length; i++) {
                this._secondaryCursors[i].onCursorPositionChanged(secondaryPositions[i], pauseAnimation);
            }
        }
        onCursorStateChanged(e) {
            const positions = [];
            for (let i = 0, len = e.selections.length; i < len; i++) {
                positions[i] = e.selections[i].getPosition();
            }
            this._onCursorPositionChanged(positions[0], positions.slice(1), e.reason);
            const selectionIsEmpty = e.selections[0].isEmpty();
            if (this._selectionIsEmpty !== selectionIsEmpty) {
                this._selectionIsEmpty = selectionIsEmpty;
                this._updateDomClassName();
            }
            return true;
        }
        onDecorationsChanged(e) {
            // true for inline decorations that can end up relayouting text
            return true;
        }
        onFlushed(e) {
            return true;
        }
        onFocusChanged(e) {
            this._editorHasFocus = e.isFocused;
            this._updateBlinking();
            return false;
        }
        onLinesChanged(e) {
            return true;
        }
        onLinesDeleted(e) {
            return true;
        }
        onLinesInserted(e) {
            return true;
        }
        onScrollChanged(e) {
            return true;
        }
        onTokensChanged(e) {
            const shouldRender = (position) => {
                for (let i = 0, len = e.ranges.length; i < len; i++) {
                    if (e.ranges[i].fromLineNumber <= position.lineNumber && position.lineNumber <= e.ranges[i].toLineNumber) {
                        return true;
                    }
                }
                return false;
            };
            if (shouldRender(this._primaryCursor.getPosition())) {
                return true;
            }
            for (const secondaryCursor of this._secondaryCursors) {
                if (shouldRender(secondaryCursor.getPosition())) {
                    return true;
                }
            }
            return false;
        }
        onZonesChanged(e) {
            return true;
        }
        // --- end event handlers
        // ---- blinking logic
        _getCursorBlinking() {
            if (this._isComposingInput) {
                // avoid double cursors
                return 0 /* TextEditorCursorBlinkingStyle.Hidden */;
            }
            if (!this._editorHasFocus) {
                return 0 /* TextEditorCursorBlinkingStyle.Hidden */;
            }
            if (this._readOnly) {
                return 5 /* TextEditorCursorBlinkingStyle.Solid */;
            }
            return this._cursorBlinking;
        }
        _updateBlinking() {
            this._startCursorBlinkAnimation.cancel();
            this._cursorFlatBlinkInterval.cancel();
            const blinkingStyle = this._getCursorBlinking();
            // hidden and solid are special as they involve no animations
            const isHidden = (blinkingStyle === 0 /* TextEditorCursorBlinkingStyle.Hidden */);
            const isSolid = (blinkingStyle === 5 /* TextEditorCursorBlinkingStyle.Solid */);
            if (isHidden) {
                this._hide();
            }
            else {
                this._show();
            }
            this._blinkingEnabled = false;
            this._updateDomClassName();
            if (!isHidden && !isSolid) {
                if (blinkingStyle === 1 /* TextEditorCursorBlinkingStyle.Blink */) {
                    // flat blinking is handled by JavaScript to save battery life due to Chromium step timing issue https://bugs.chromium.org/p/chromium/issues/detail?id=361587
                    this._cursorFlatBlinkInterval.cancelAndSet(() => {
                        if (this._isVisible) {
                            this._hide();
                        }
                        else {
                            this._show();
                        }
                    }, ViewCursors.BLINK_INTERVAL, (0, dom_1.getWindow)(this._domNode.domNode));
                }
                else {
                    this._startCursorBlinkAnimation.setIfNotSet(() => {
                        this._blinkingEnabled = true;
                        this._updateDomClassName();
                    }, ViewCursors.BLINK_INTERVAL);
                }
            }
        }
        // --- end blinking logic
        _updateDomClassName() {
            this._domNode.setClassName(this._getClassName());
        }
        _getClassName() {
            let result = 'cursors-layer';
            if (!this._selectionIsEmpty) {
                result += ' has-selection';
            }
            switch (this._cursorStyle) {
                case editorOptions_1.TextEditorCursorStyle.Line:
                    result += ' cursor-line-style';
                    break;
                case editorOptions_1.TextEditorCursorStyle.Block:
                    result += ' cursor-block-style';
                    break;
                case editorOptions_1.TextEditorCursorStyle.Underline:
                    result += ' cursor-underline-style';
                    break;
                case editorOptions_1.TextEditorCursorStyle.LineThin:
                    result += ' cursor-line-thin-style';
                    break;
                case editorOptions_1.TextEditorCursorStyle.BlockOutline:
                    result += ' cursor-block-outline-style';
                    break;
                case editorOptions_1.TextEditorCursorStyle.UnderlineThin:
                    result += ' cursor-underline-thin-style';
                    break;
                default:
                    result += ' cursor-line-style';
            }
            if (this._blinkingEnabled) {
                switch (this._getCursorBlinking()) {
                    case 1 /* TextEditorCursorBlinkingStyle.Blink */:
                        result += ' cursor-blink';
                        break;
                    case 2 /* TextEditorCursorBlinkingStyle.Smooth */:
                        result += ' cursor-smooth';
                        break;
                    case 3 /* TextEditorCursorBlinkingStyle.Phase */:
                        result += ' cursor-phase';
                        break;
                    case 4 /* TextEditorCursorBlinkingStyle.Expand */:
                        result += ' cursor-expand';
                        break;
                    case 5 /* TextEditorCursorBlinkingStyle.Solid */:
                        result += ' cursor-solid';
                        break;
                    default:
                        result += ' cursor-solid';
                }
            }
            else {
                result += ' cursor-solid';
            }
            if (this._cursorSmoothCaretAnimation === 'on' || this._cursorSmoothCaretAnimation === 'explicit') {
                result += ' cursor-smooth-caret-animation';
            }
            return result;
        }
        _show() {
            this._primaryCursor.show();
            for (let i = 0, len = this._secondaryCursors.length; i < len; i++) {
                this._secondaryCursors[i].show();
            }
            this._isVisible = true;
        }
        _hide() {
            this._primaryCursor.hide();
            for (let i = 0, len = this._secondaryCursors.length; i < len; i++) {
                this._secondaryCursors[i].hide();
            }
            this._isVisible = false;
        }
        // ---- IViewPart implementation
        prepareRender(ctx) {
            this._primaryCursor.prepareRender(ctx);
            for (let i = 0, len = this._secondaryCursors.length; i < len; i++) {
                this._secondaryCursors[i].prepareRender(ctx);
            }
        }
        render(ctx) {
            const renderData = [];
            let renderDataLen = 0;
            const primaryRenderData = this._primaryCursor.render(ctx);
            if (primaryRenderData) {
                renderData[renderDataLen++] = primaryRenderData;
            }
            for (let i = 0, len = this._secondaryCursors.length; i < len; i++) {
                const secondaryRenderData = this._secondaryCursors[i].render(ctx);
                if (secondaryRenderData) {
                    renderData[renderDataLen++] = secondaryRenderData;
                }
            }
            this._renderData = renderData;
        }
        getLastRenderData() {
            return this._renderData;
        }
    }
    exports.ViewCursors = ViewCursors;
    (0, themeService_1.registerThemingParticipant)((theme, collector) => {
        const cursorThemes = [
            { class: '.cursor', foreground: editorColorRegistry_1.editorCursorForeground, background: editorColorRegistry_1.editorCursorBackground },
            { class: '.cursor-primary', foreground: editorColorRegistry_1.editorMultiCursorPrimaryForeground, background: editorColorRegistry_1.editorMultiCursorPrimaryBackground },
            { class: '.cursor-secondary', foreground: editorColorRegistry_1.editorMultiCursorSecondaryForeground, background: editorColorRegistry_1.editorMultiCursorSecondaryBackground },
        ];
        for (const cursorTheme of cursorThemes) {
            const caret = theme.getColor(cursorTheme.foreground);
            if (caret) {
                let caretBackground = theme.getColor(cursorTheme.background);
                if (!caretBackground) {
                    caretBackground = caret.opposite();
                }
                collector.addRule(`.monaco-editor .cursors-layer ${cursorTheme.class} { background-color: ${caret}; border-color: ${caret}; color: ${caretBackground}; }`);
                if ((0, theme_1.isHighContrast)(theme.type)) {
                    collector.addRule(`.monaco-editor .cursors-layer.has-selection ${cursorTheme.class} { border-left: 1px solid ${caretBackground}; border-right: 1px solid ${caretBackground}; }`);
                }
            }
        }
    });
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[781/*vs/editor/browser/viewParts/whitespace/whitespace*/], __M([1/*require*/,0/*exports*/,133/*vs/editor/browser/view/dynamicViewOverlay*/,11/*vs/base/common/strings*/,136/*vs/editor/common/viewLayout/viewLineRenderer*/,9/*vs/editor/common/core/position*/,80/*vs/editor/common/core/editorColorRegistry*/,497/*vs/css!vs/editor/browser/viewParts/whitespace/whitespace*/]), function (require, exports, dynamicViewOverlay_1, strings, viewLineRenderer_1, position_1, editorColorRegistry_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.WhitespaceOverlay = void 0;
    class WhitespaceOverlay extends dynamicViewOverlay_1.DynamicViewOverlay {
        constructor(context) {
            super();
            this._context = context;
            this._options = new WhitespaceOptions(this._context.configuration);
            this._selection = [];
            this._renderResult = null;
            this._context.addEventHandler(this);
        }
        dispose() {
            this._context.removeEventHandler(this);
            this._renderResult = null;
            super.dispose();
        }
        // --- begin event handlers
        onConfigurationChanged(e) {
            const newOptions = new WhitespaceOptions(this._context.configuration);
            if (this._options.equals(newOptions)) {
                return e.hasChanged(146 /* EditorOption.layoutInfo */);
            }
            this._options = newOptions;
            return true;
        }
        onCursorStateChanged(e) {
            this._selection = e.selections;
            if (this._options.renderWhitespace === 'selection') {
                return true;
            }
            return false;
        }
        onDecorationsChanged(e) {
            return true;
        }
        onFlushed(e) {
            return true;
        }
        onLinesChanged(e) {
            return true;
        }
        onLinesDeleted(e) {
            return true;
        }
        onLinesInserted(e) {
            return true;
        }
        onScrollChanged(e) {
            return e.scrollTopChanged;
        }
        onZonesChanged(e) {
            return true;
        }
        // --- end event handlers
        prepareRender(ctx) {
            if (this._options.renderWhitespace === 'none') {
                this._renderResult = null;
                return;
            }
            const startLineNumber = ctx.visibleRange.startLineNumber;
            const endLineNumber = ctx.visibleRange.endLineNumber;
            const lineCount = endLineNumber - startLineNumber + 1;
            const needed = new Array(lineCount);
            for (let i = 0; i < lineCount; i++) {
                needed[i] = true;
            }
            const viewportData = this._context.viewModel.getMinimapLinesRenderingData(ctx.viewportData.startLineNumber, ctx.viewportData.endLineNumber, needed);
            this._renderResult = [];
            for (let lineNumber = ctx.viewportData.startLineNumber; lineNumber <= ctx.viewportData.endLineNumber; lineNumber++) {
                const lineIndex = lineNumber - ctx.viewportData.startLineNumber;
                const lineData = viewportData.data[lineIndex];
                let selectionsOnLine = null;
                if (this._options.renderWhitespace === 'selection') {
                    const selections = this._selection;
                    for (const selection of selections) {
                        if (selection.endLineNumber < lineNumber || selection.startLineNumber > lineNumber) {
                            // Selection does not intersect line
                            continue;
                        }
                        const startColumn = (selection.startLineNumber === lineNumber ? selection.startColumn : lineData.minColumn);
                        const endColumn = (selection.endLineNumber === lineNumber ? selection.endColumn : lineData.maxColumn);
                        if (startColumn < endColumn) {
                            if (!selectionsOnLine) {
                                selectionsOnLine = [];
                            }
                            selectionsOnLine.push(new viewLineRenderer_1.LineRange(startColumn - 1, endColumn - 1));
                        }
                    }
                }
                this._renderResult[lineIndex] = this._applyRenderWhitespace(ctx, lineNumber, selectionsOnLine, lineData);
            }
        }
        _applyRenderWhitespace(ctx, lineNumber, selections, lineData) {
            if (this._options.renderWhitespace === 'selection' && !selections) {
                return '';
            }
            if (this._options.renderWhitespace === 'trailing' && lineData.continuesWithWrappedLine) {
                return '';
            }
            const color = this._context.theme.getColor(editorColorRegistry_1.editorWhitespaces);
            const USE_SVG = this._options.renderWithSVG;
            const lineContent = lineData.content;
            const len = (this._options.stopRenderingLineAfter === -1 ? lineContent.length : Math.min(this._options.stopRenderingLineAfter, lineContent.length));
            const continuesWithWrappedLine = lineData.continuesWithWrappedLine;
            const fauxIndentLength = lineData.minColumn - 1;
            const onlyBoundary = (this._options.renderWhitespace === 'boundary');
            const onlyTrailing = (this._options.renderWhitespace === 'trailing');
            const lineHeight = this._options.lineHeight;
            const middotWidth = this._options.middotWidth;
            const wsmiddotWidth = this._options.wsmiddotWidth;
            const spaceWidth = this._options.spaceWidth;
            const wsmiddotDiff = Math.abs(wsmiddotWidth - spaceWidth);
            const middotDiff = Math.abs(middotWidth - spaceWidth);
            // U+2E31 - WORD SEPARATOR MIDDLE DOT
            // U+00B7 - MIDDLE DOT
            const renderSpaceCharCode = (wsmiddotDiff < middotDiff ? 0x2E31 : 0xB7);
            const canUseHalfwidthRightwardsArrow = this._options.canUseHalfwidthRightwardsArrow;
            let result = '';
            let lineIsEmptyOrWhitespace = false;
            let firstNonWhitespaceIndex = strings.firstNonWhitespaceIndex(lineContent);
            let lastNonWhitespaceIndex;
            if (firstNonWhitespaceIndex === -1) {
                lineIsEmptyOrWhitespace = true;
                firstNonWhitespaceIndex = len;
                lastNonWhitespaceIndex = len;
            }
            else {
                lastNonWhitespaceIndex = strings.lastNonWhitespaceIndex(lineContent);
            }
            let currentSelectionIndex = 0;
            let currentSelection = selections && selections[currentSelectionIndex];
            let maxLeft = 0;
            for (let charIndex = fauxIndentLength; charIndex < len; charIndex++) {
                const chCode = lineContent.charCodeAt(charIndex);
                if (currentSelection && charIndex >= currentSelection.endOffset) {
                    currentSelectionIndex++;
                    currentSelection = selections && selections[currentSelectionIndex];
                }
                if (chCode !== 9 /* CharCode.Tab */ && chCode !== 32 /* CharCode.Space */) {
                    continue;
                }
                if (onlyTrailing && !lineIsEmptyOrWhitespace && charIndex <= lastNonWhitespaceIndex) {
                    // If rendering only trailing whitespace, check that the charIndex points to trailing whitespace.
                    continue;
                }
                if (onlyBoundary && charIndex >= firstNonWhitespaceIndex && charIndex <= lastNonWhitespaceIndex && chCode === 32 /* CharCode.Space */) {
                    // rendering only boundary whitespace
                    const prevChCode = (charIndex - 1 >= 0 ? lineContent.charCodeAt(charIndex - 1) : 0 /* CharCode.Null */);
                    const nextChCode = (charIndex + 1 < len ? lineContent.charCodeAt(charIndex + 1) : 0 /* CharCode.Null */);
                    if (prevChCode !== 32 /* CharCode.Space */ && nextChCode !== 32 /* CharCode.Space */) {
                        continue;
                    }
                }
                if (onlyBoundary && continuesWithWrappedLine && charIndex === len - 1) {
                    const prevCharCode = (charIndex - 1 >= 0 ? lineContent.charCodeAt(charIndex - 1) : 0 /* CharCode.Null */);
                    const isSingleTrailingSpace = (chCode === 32 /* CharCode.Space */ && (prevCharCode !== 32 /* CharCode.Space */ && prevCharCode !== 9 /* CharCode.Tab */));
                    if (isSingleTrailingSpace) {
                        continue;
                    }
                }
                if (selections && (!currentSelection || currentSelection.startOffset > charIndex || currentSelection.endOffset <= charIndex)) {
                    // If rendering whitespace on selection, check that the charIndex falls within a selection
                    continue;
                }
                const visibleRange = ctx.visibleRangeForPosition(new position_1.Position(lineNumber, charIndex + 1));
                if (!visibleRange) {
                    continue;
                }
                if (USE_SVG) {
                    maxLeft = Math.max(maxLeft, visibleRange.left);
                    if (chCode === 9 /* CharCode.Tab */) {
                        result += this._renderArrow(lineHeight, spaceWidth, visibleRange.left);
                    }
                    else {
                        result += `<circle cx="${(visibleRange.left + spaceWidth / 2).toFixed(2)}" cy="${(lineHeight / 2).toFixed(2)}" r="${(spaceWidth / 7).toFixed(2)}" />`;
                    }
                }
                else {
                    if (chCode === 9 /* CharCode.Tab */) {
                        result += `<div class="mwh" style="left:${visibleRange.left}px;height:${lineHeight}px;">${canUseHalfwidthRightwardsArrow ? String.fromCharCode(0xFFEB) : String.fromCharCode(0x2192)}</div>`;
                    }
                    else {
                        result += `<div class="mwh" style="left:${visibleRange.left}px;height:${lineHeight}px;">${String.fromCharCode(renderSpaceCharCode)}</div>`;
                    }
                }
            }
            if (USE_SVG) {
                maxLeft = Math.round(maxLeft + spaceWidth);
                return (`<svg style="bottom:0;position:absolute;width:${maxLeft}px;height:${lineHeight}px" viewBox="0 0 ${maxLeft} ${lineHeight}" xmlns="http://www.w3.org/2000/svg" fill="${color}">`
                    + result
                    + `</svg>`);
            }
            return result;
        }
        _renderArrow(lineHeight, spaceWidth, left) {
            const strokeWidth = spaceWidth / 7;
            const width = spaceWidth;
            const dy = lineHeight / 2;
            const dx = left;
            const p1 = { x: 0, y: strokeWidth / 2 };
            const p2 = { x: 100 / 125 * width, y: p1.y };
            const p3 = { x: p2.x - 0.2 * p2.x, y: p2.y + 0.2 * p2.x };
            const p4 = { x: p3.x + 0.1 * p2.x, y: p3.y + 0.1 * p2.x };
            const p5 = { x: p4.x + 0.35 * p2.x, y: p4.y - 0.35 * p2.x };
            const p6 = { x: p5.x, y: -p5.y };
            const p7 = { x: p4.x, y: -p4.y };
            const p8 = { x: p3.x, y: -p3.y };
            const p9 = { x: p2.x, y: -p2.y };
            const p10 = { x: p1.x, y: -p1.y };
            const p = [p1, p2, p3, p4, p5, p6, p7, p8, p9, p10];
            const parts = p.map((p) => `${(dx + p.x).toFixed(2)} ${(dy + p.y).toFixed(2)}`).join(' L ');
            return `<path d="M ${parts}" />`;
        }
        render(startLineNumber, lineNumber) {
            if (!this._renderResult) {
                return '';
            }
            const lineIndex = lineNumber - startLineNumber;
            if (lineIndex < 0 || lineIndex >= this._renderResult.length) {
                return '';
            }
            return this._renderResult[lineIndex];
        }
    }
    exports.WhitespaceOverlay = WhitespaceOverlay;
    class WhitespaceOptions {
        constructor(config) {
            const options = config.options;
            const fontInfo = options.get(50 /* EditorOption.fontInfo */);
            const experimentalWhitespaceRendering = options.get(38 /* EditorOption.experimentalWhitespaceRendering */);
            if (experimentalWhitespaceRendering === 'off') {
                // whitespace is rendered in the view line
                this.renderWhitespace = 'none';
                this.renderWithSVG = false;
            }
            else if (experimentalWhitespaceRendering === 'svg') {
                this.renderWhitespace = options.get(100 /* EditorOption.renderWhitespace */);
                this.renderWithSVG = true;
            }
            else {
                this.renderWhitespace = options.get(100 /* EditorOption.renderWhitespace */);
                this.renderWithSVG = false;
            }
            this.spaceWidth = fontInfo.spaceWidth;
            this.middotWidth = fontInfo.middotWidth;
            this.wsmiddotWidth = fontInfo.wsmiddotWidth;
            this.canUseHalfwidthRightwardsArrow = fontInfo.canUseHalfwidthRightwardsArrow;
            this.lineHeight = options.get(67 /* EditorOption.lineHeight */);
            this.stopRenderingLineAfter = options.get(118 /* EditorOption.stopRenderingLineAfter */);
        }
        equals(other) {
            return (this.renderWhitespace === other.renderWhitespace
                && this.renderWithSVG === other.renderWithSVG
                && this.spaceWidth === other.spaceWidth
                && this.middotWidth === other.middotWidth
                && this.wsmiddotWidth === other.wsmiddotWidth
                && this.canUseHalfwidthRightwardsArrow === other.canUseHalfwidthRightwardsArrow
                && this.lineHeight === other.lineHeight
                && this.stopRenderingLineAfter === other.stopRenderingLineAfter);
        }
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[782/*vs/editor/browser/view*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,39/*vs/base/browser/fastDomNode*/,296/*vs/base/browser/performance*/,8/*vs/base/common/errors*/,414/*vs/editor/browser/controller/mouseTarget*/,769/*vs/editor/browser/controller/pointerHandler*/,778/*vs/editor/browser/controller/textAreaHandler*/,164/*vs/editor/browser/view/renderingContext*/,726/*vs/editor/browser/view/viewController*/,657/*vs/editor/browser/view/viewOverlays*/,56/*vs/editor/browser/view/viewPart*/,309/*vs/editor/browser/view/viewUserInputEvents*/,591/*vs/editor/browser/viewParts/blockDecorations/blockDecorations*/,649/*vs/editor/browser/viewParts/contentWidgets/contentWidgets*/,776/*vs/editor/browser/viewParts/currentLineHighlight/currentLineHighlight*/,592/*vs/editor/browser/viewParts/decorations/decorations*/,773/*vs/editor/browser/viewParts/editorScrollbar/editorScrollbar*/,242/*vs/editor/browser/viewParts/glyphMargin/glyphMargin*/,777/*vs/editor/browser/viewParts/indentGuides/indentGuides*/,416/*vs/editor/browser/viewParts/lineNumbers/lineNumbers*/,770/*vs/editor/browser/viewParts/lines/viewLines*/,593/*vs/editor/browser/viewParts/linesDecorations/linesDecorations*/,331/*vs/editor/browser/viewParts/margin/margin*/,594/*vs/editor/browser/viewParts/marginDecorations/marginDecorations*/,755/*vs/editor/browser/viewParts/minimap/minimap*/,650/*vs/editor/browser/viewParts/overlayWidgets/overlayWidgets*/,779/*vs/editor/browser/viewParts/overviewRuler/decorationsOverviewRuler*/,604/*vs/editor/browser/viewParts/overviewRuler/overviewRuler*/,595/*vs/editor/browser/viewParts/rulers/rulers*/,596/*vs/editor/browser/viewParts/scrollDecoration/scrollDecoration*/,774/*vs/editor/browser/viewParts/selections/selections*/,780/*vs/editor/browser/viewParts/viewCursors/viewCursors*/,597/*vs/editor/browser/viewParts/viewZones/viewZones*/,781/*vs/editor/browser/viewParts/whitespace/whitespace*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/,23/*vs/editor/common/core/selection*/,40/*vs/editor/common/model*/,170/*vs/editor/common/viewEventHandler*/,600/*vs/editor/common/viewLayout/viewLinesViewportData*/,605/*vs/editor/common/viewModel/viewContext*/,7/*vs/platform/instantiation/common/instantiation*/,25/*vs/platform/theme/common/themeService*/]), function (require, exports, dom, fastDomNode_1, performance_1, errors_1, mouseTarget_1, pointerHandler_1, textAreaHandler_1, renderingContext_1, viewController_1, viewOverlays_1, viewPart_1, viewUserInputEvents_1, blockDecorations_1, contentWidgets_1, currentLineHighlight_1, decorations_1, editorScrollbar_1, glyphMargin_1, indentGuides_1, lineNumbers_1, viewLines_1, linesDecorations_1, margin_1, marginDecorations_1, minimap_1, overlayWidgets_1, decorationsOverviewRuler_1, overviewRuler_1, rulers_1, scrollDecoration_1, selections_1, viewCursors_1, viewZones_1, whitespace_1, position_1, range_1, selection_1, model_1, viewEventHandler_1, viewLinesViewportData_1, viewContext_1, instantiation_1, themeService_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.View = void 0;
    let View = class View extends viewEventHandler_1.ViewEventHandler {
        constructor(commandDelegate, configuration, colorTheme, model, userInputEvents, overflowWidgetsDomNode, _instantiationService) {
            super();
            this._instantiationService = _instantiationService;
            // Actual mutable state
            this._shouldRecomputeGlyphMarginLanes = false;
            this._selections = [new selection_1.Selection(1, 1, 1, 1)];
            this._renderAnimationFrame = null;
            const viewController = new viewController_1.ViewController(configuration, model, userInputEvents, commandDelegate);
            // The view context is passed on to most classes (basically to reduce param. counts in ctors)
            this._context = new viewContext_1.ViewContext(configuration, colorTheme, model);
            // Ensure the view is the first event handler in order to update the layout
            this._context.addEventHandler(this);
            this._viewParts = [];
            // Keyboard handler
            this._textAreaHandler = this._instantiationService.createInstance(textAreaHandler_1.TextAreaHandler, this._context, viewController, this._createTextAreaHandlerHelper());
            this._viewParts.push(this._textAreaHandler);
            // These two dom nodes must be constructed up front, since references are needed in the layout provider (scrolling & co.)
            this._linesContent = (0, fastDomNode_1.createFastDomNode)(document.createElement('div'));
            this._linesContent.setClassName('lines-content' + ' monaco-editor-background');
            this._linesContent.setPosition('absolute');
            this.domNode = (0, fastDomNode_1.createFastDomNode)(document.createElement('div'));
            this.domNode.setClassName(this._getEditorClassName());
            // Set role 'code' for better screen reader support https://github.com/microsoft/vscode/issues/93438
            this.domNode.setAttribute('role', 'code');
            this._overflowGuardContainer = (0, fastDomNode_1.createFastDomNode)(document.createElement('div'));
            viewPart_1.PartFingerprints.write(this._overflowGuardContainer, 3 /* PartFingerprint.OverflowGuard */);
            this._overflowGuardContainer.setClassName('overflow-guard');
            this._scrollbar = new editorScrollbar_1.EditorScrollbar(this._context, this._linesContent, this.domNode, this._overflowGuardContainer);
            this._viewParts.push(this._scrollbar);
            // View Lines
            this._viewLines = new viewLines_1.ViewLines(this._context, this._linesContent);
            // View Zones
            this._viewZones = new viewZones_1.ViewZones(this._context);
            this._viewParts.push(this._viewZones);
            // Decorations overview ruler
            const decorationsOverviewRuler = new decorationsOverviewRuler_1.DecorationsOverviewRuler(this._context);
            this._viewParts.push(decorationsOverviewRuler);
            const scrollDecoration = new scrollDecoration_1.ScrollDecorationViewPart(this._context);
            this._viewParts.push(scrollDecoration);
            const contentViewOverlays = new viewOverlays_1.ContentViewOverlays(this._context);
            this._viewParts.push(contentViewOverlays);
            contentViewOverlays.addDynamicOverlay(new currentLineHighlight_1.CurrentLineHighlightOverlay(this._context));
            contentViewOverlays.addDynamicOverlay(new selections_1.SelectionsOverlay(this._context));
            contentViewOverlays.addDynamicOverlay(new indentGuides_1.IndentGuidesOverlay(this._context));
            contentViewOverlays.addDynamicOverlay(new decorations_1.DecorationsOverlay(this._context));
            contentViewOverlays.addDynamicOverlay(new whitespace_1.WhitespaceOverlay(this._context));
            const marginViewOverlays = new viewOverlays_1.MarginViewOverlays(this._context);
            this._viewParts.push(marginViewOverlays);
            marginViewOverlays.addDynamicOverlay(new currentLineHighlight_1.CurrentLineMarginHighlightOverlay(this._context));
            marginViewOverlays.addDynamicOverlay(new marginDecorations_1.MarginViewLineDecorationsOverlay(this._context));
            marginViewOverlays.addDynamicOverlay(new linesDecorations_1.LinesDecorationsOverlay(this._context));
            marginViewOverlays.addDynamicOverlay(new lineNumbers_1.LineNumbersOverlay(this._context));
            // Glyph margin widgets
            this._glyphMarginWidgets = new glyphMargin_1.GlyphMarginWidgets(this._context);
            this._viewParts.push(this._glyphMarginWidgets);
            const margin = new margin_1.Margin(this._context);
            margin.getDomNode().appendChild(this._viewZones.marginDomNode);
            margin.getDomNode().appendChild(marginViewOverlays.getDomNode());
            margin.getDomNode().appendChild(this._glyphMarginWidgets.domNode);
            this._viewParts.push(margin);
            // Content widgets
            this._contentWidgets = new contentWidgets_1.ViewContentWidgets(this._context, this.domNode);
            this._viewParts.push(this._contentWidgets);
            this._viewCursors = new viewCursors_1.ViewCursors(this._context);
            this._viewParts.push(this._viewCursors);
            // Overlay widgets
            this._overlayWidgets = new overlayWidgets_1.ViewOverlayWidgets(this._context, this.domNode);
            this._viewParts.push(this._overlayWidgets);
            const rulers = new rulers_1.Rulers(this._context);
            this._viewParts.push(rulers);
            const blockOutline = new blockDecorations_1.BlockDecorations(this._context);
            this._viewParts.push(blockOutline);
            const minimap = new minimap_1.Minimap(this._context);
            this._viewParts.push(minimap);
            // -------------- Wire dom nodes up
            if (decorationsOverviewRuler) {
                const overviewRulerData = this._scrollbar.getOverviewRulerLayoutInfo();
                overviewRulerData.parent.insertBefore(decorationsOverviewRuler.getDomNode(), overviewRulerData.insertBefore);
            }
            this._linesContent.appendChild(contentViewOverlays.getDomNode());
            this._linesContent.appendChild(rulers.domNode);
            this._linesContent.appendChild(this._viewZones.domNode);
            this._linesContent.appendChild(this._viewLines.getDomNode());
            this._linesContent.appendChild(this._contentWidgets.domNode);
            this._linesContent.appendChild(this._viewCursors.getDomNode());
            this._overflowGuardContainer.appendChild(margin.getDomNode());
            this._overflowGuardContainer.appendChild(this._scrollbar.getDomNode());
            this._overflowGuardContainer.appendChild(scrollDecoration.getDomNode());
            this._overflowGuardContainer.appendChild(this._textAreaHandler.textArea);
            this._overflowGuardContainer.appendChild(this._textAreaHandler.textAreaCover);
            this._overflowGuardContainer.appendChild(this._overlayWidgets.getDomNode());
            this._overflowGuardContainer.appendChild(minimap.getDomNode());
            this._overflowGuardContainer.appendChild(blockOutline.domNode);
            this.domNode.appendChild(this._overflowGuardContainer);
            if (overflowWidgetsDomNode) {
                overflowWidgetsDomNode.appendChild(this._contentWidgets.overflowingContentWidgetsDomNode.domNode);
                overflowWidgetsDomNode.appendChild(this._overlayWidgets.overflowingOverlayWidgetsDomNode.domNode);
            }
            else {
                this.domNode.appendChild(this._contentWidgets.overflowingContentWidgetsDomNode);
                this.domNode.appendChild(this._overlayWidgets.overflowingOverlayWidgetsDomNode);
            }
            this._applyLayout();
            // Pointer handler
            this._pointerHandler = this._register(new pointerHandler_1.PointerHandler(this._context, viewController, this._createPointerHandlerHelper()));
        }
        _computeGlyphMarginLanes() {
            const model = this._context.viewModel.model;
            const laneModel = this._context.viewModel.glyphLanes;
            let glyphs = [];
            let maxLineNumber = 0;
            // Add all margin decorations
            glyphs = glyphs.concat(model.getAllMarginDecorations().map((decoration) => {
                const lane = decoration.options.glyphMargin?.position ?? model_1.GlyphMarginLane.Center;
                maxLineNumber = Math.max(maxLineNumber, decoration.range.endLineNumber);
                return { range: decoration.range, lane, persist: decoration.options.glyphMargin?.persistLane };
            }));
            // Add all glyph margin widgets
            glyphs = glyphs.concat(this._glyphMarginWidgets.getWidgets().map((widget) => {
                const range = model.validateRange(widget.preference.range);
                maxLineNumber = Math.max(maxLineNumber, range.endLineNumber);
                return { range, lane: widget.preference.lane };
            }));
            // Sorted by their start position
            glyphs.sort((a, b) => range_1.Range.compareRangesUsingStarts(a.range, b.range));
            laneModel.reset(maxLineNumber);
            for (const glyph of glyphs) {
                laneModel.push(glyph.lane, glyph.range, glyph.persist);
            }
            return laneModel;
        }
        _createPointerHandlerHelper() {
            return {
                viewDomNode: this.domNode.domNode,
                linesContentDomNode: this._linesContent.domNode,
                viewLinesDomNode: this._viewLines.getDomNode().domNode,
                focusTextArea: () => {
                    this.focus();
                },
                dispatchTextAreaEvent: (event) => {
                    this._textAreaHandler.textArea.domNode.dispatchEvent(event);
                },
                getLastRenderData: () => {
                    const lastViewCursorsRenderData = this._viewCursors.getLastRenderData() || [];
                    const lastTextareaPosition = this._textAreaHandler.getLastRenderData();
                    return new mouseTarget_1.PointerHandlerLastRenderData(lastViewCursorsRenderData, lastTextareaPosition);
                },
                renderNow: () => {
                    this.render(true, false);
                },
                shouldSuppressMouseDownOnViewZone: (viewZoneId) => {
                    return this._viewZones.shouldSuppressMouseDownOnViewZone(viewZoneId);
                },
                shouldSuppressMouseDownOnWidget: (widgetId) => {
                    return this._contentWidgets.shouldSuppressMouseDownOnWidget(widgetId);
                },
                getPositionFromDOMInfo: (spanNode, offset) => {
                    this._flushAccumulatedAndRenderNow();
                    return this._viewLines.getPositionFromDOMInfo(spanNode, offset);
                },
                visibleRangeForPosition: (lineNumber, column) => {
                    this._flushAccumulatedAndRenderNow();
                    return this._viewLines.visibleRangeForPosition(new position_1.Position(lineNumber, column));
                },
                getLineWidth: (lineNumber) => {
                    this._flushAccumulatedAndRenderNow();
                    return this._viewLines.getLineWidth(lineNumber);
                }
            };
        }
        _createTextAreaHandlerHelper() {
            return {
                visibleRangeForPosition: (position) => {
                    this._flushAccumulatedAndRenderNow();
                    return this._viewLines.visibleRangeForPosition(position);
                }
            };
        }
        _applyLayout() {
            const options = this._context.configuration.options;
            const layoutInfo = options.get(146 /* EditorOption.layoutInfo */);
            this.domNode.setWidth(layoutInfo.width);
            this.domNode.setHeight(layoutInfo.height);
            this._overflowGuardContainer.setWidth(layoutInfo.width);
            this._overflowGuardContainer.setHeight(layoutInfo.height);
            // https://stackoverflow.com/questions/38905916/content-in-google-chrome-larger-than-16777216-px-not-being-rendered
            this._linesContent.setWidth(16777216);
            this._linesContent.setHeight(16777216);
        }
        _getEditorClassName() {
            const focused = this._textAreaHandler.isFocused() ? ' focused' : '';
            return this._context.configuration.options.get(143 /* EditorOption.editorClassName */) + ' ' + (0, themeService_1.getThemeTypeSelector)(this._context.theme.type) + focused;
        }
        // --- begin event handlers
        handleEvents(events) {
            super.handleEvents(events);
            this._scheduleRender();
        }
        onConfigurationChanged(e) {
            this.domNode.setClassName(this._getEditorClassName());
            this._applyLayout();
            return false;
        }
        onCursorStateChanged(e) {
            this._selections = e.selections;
            return false;
        }
        onDecorationsChanged(e) {
            if (e.affectsGlyphMargin) {
                this._shouldRecomputeGlyphMarginLanes = true;
            }
            return false;
        }
        onFocusChanged(e) {
            this.domNode.setClassName(this._getEditorClassName());
            return false;
        }
        onThemeChanged(e) {
            this._context.theme.update(e.theme);
            this.domNode.setClassName(this._getEditorClassName());
            return false;
        }
        // --- end event handlers
        dispose() {
            if (this._renderAnimationFrame !== null) {
                this._renderAnimationFrame.dispose();
                this._renderAnimationFrame = null;
            }
            this._contentWidgets.overflowingContentWidgetsDomNode.domNode.remove();
            this._context.removeEventHandler(this);
            this._viewLines.dispose();
            // Destroy view parts
            for (const viewPart of this._viewParts) {
                viewPart.dispose();
            }
            super.dispose();
        }
        _scheduleRender() {
            if (this._store.isDisposed) {
                throw new errors_1.BugIndicatingError();
            }
            if (this._renderAnimationFrame === null) {
                const rendering = this._createCoordinatedRendering();
                this._renderAnimationFrame = EditorRenderingCoordinator.INSTANCE.scheduleCoordinatedRendering({
                    window: dom.getWindow(this.domNode?.domNode),
                    prepareRenderText: () => {
                        if (this._store.isDisposed) {
                            throw new errors_1.BugIndicatingError();
                        }
                        try {
                            return rendering.prepareRenderText();
                        }
                        finally {
                            this._renderAnimationFrame = null;
                        }
                    },
                    renderText: () => {
                        if (this._store.isDisposed) {
                            throw new errors_1.BugIndicatingError();
                        }
                        return rendering.renderText();
                    },
                    prepareRender: (viewParts, ctx) => {
                        if (this._store.isDisposed) {
                            throw new errors_1.BugIndicatingError();
                        }
                        return rendering.prepareRender(viewParts, ctx);
                    },
                    render: (viewParts, ctx) => {
                        if (this._store.isDisposed) {
                            throw new errors_1.BugIndicatingError();
                        }
                        return rendering.render(viewParts, ctx);
                    }
                });
            }
        }
        _flushAccumulatedAndRenderNow() {
            const rendering = this._createCoordinatedRendering();
            safeInvokeNoArg(() => rendering.prepareRenderText());
            const data = safeInvokeNoArg(() => rendering.renderText());
            if (data) {
                const [viewParts, ctx] = data;
                safeInvokeNoArg(() => rendering.prepareRender(viewParts, ctx));
                safeInvokeNoArg(() => rendering.render(viewParts, ctx));
            }
        }
        _getViewPartsToRender() {
            const result = [];
            let resultLen = 0;
            for (const viewPart of this._viewParts) {
                if (viewPart.shouldRender()) {
                    result[resultLen++] = viewPart;
                }
            }
            return result;
        }
        _createCoordinatedRendering() {
            return {
                prepareRenderText: () => {
                    if (this._shouldRecomputeGlyphMarginLanes) {
                        this._shouldRecomputeGlyphMarginLanes = false;
                        const model = this._computeGlyphMarginLanes();
                        this._context.configuration.setGlyphMarginDecorationLaneCount(model.requiredLanes);
                    }
                    performance_1.inputLatency.onRenderStart();
                },
                renderText: () => {
                    if (!this.domNode.domNode.isConnected) {
                        return null;
                    }
                    let viewPartsToRender = this._getViewPartsToRender();
                    if (!this._viewLines.shouldRender() && viewPartsToRender.length === 0) {
                        // Nothing to render
                        return null;
                    }
                    const partialViewportData = this._context.viewLayout.getLinesViewportData();
                    this._context.viewModel.setViewport(partialViewportData.startLineNumber, partialViewportData.endLineNumber, partialViewportData.centeredLineNumber);
                    const viewportData = new viewLinesViewportData_1.ViewportData(this._selections, partialViewportData, this._context.viewLayout.getWhitespaceViewportData(), this._context.viewModel);
                    if (this._contentWidgets.shouldRender()) {
                        // Give the content widgets a chance to set their max width before a possible synchronous layout
                        this._contentWidgets.onBeforeRender(viewportData);
                    }
                    if (this._viewLines.shouldRender()) {
                        this._viewLines.renderText(viewportData);
                        this._viewLines.onDidRender();
                        // Rendering of viewLines might cause scroll events to occur, so collect view parts to render again
                        viewPartsToRender = this._getViewPartsToRender();
                    }
                    return [viewPartsToRender, new renderingContext_1.RenderingContext(this._context.viewLayout, viewportData, this._viewLines)];
                },
                prepareRender: (viewPartsToRender, ctx) => {
                    for (const viewPart of viewPartsToRender) {
                        viewPart.prepareRender(ctx);
                    }
                },
                render: (viewPartsToRender, ctx) => {
                    for (const viewPart of viewPartsToRender) {
                        viewPart.render(ctx);
                        viewPart.onDidRender();
                    }
                }
            };
        }
        // --- BEGIN CodeEditor helpers
        delegateVerticalScrollbarPointerDown(browserEvent) {
            this._scrollbar.delegateVerticalScrollbarPointerDown(browserEvent);
        }
        delegateScrollFromMouseWheelEvent(browserEvent) {
            this._scrollbar.delegateScrollFromMouseWheelEvent(browserEvent);
        }
        restoreState(scrollPosition) {
            this._context.viewModel.viewLayout.setScrollPosition({
                scrollTop: scrollPosition.scrollTop,
                scrollLeft: scrollPosition.scrollLeft
            }, 1 /* ScrollType.Immediate */);
            this._context.viewModel.visibleLinesStabilized();
        }
        getOffsetForColumn(modelLineNumber, modelColumn) {
            const modelPosition = this._context.viewModel.model.validatePosition({
                lineNumber: modelLineNumber,
                column: modelColumn
            });
            const viewPosition = this._context.viewModel.coordinatesConverter.convertModelPositionToViewPosition(modelPosition);
            this._flushAccumulatedAndRenderNow();
            const visibleRange = this._viewLines.visibleRangeForPosition(new position_1.Position(viewPosition.lineNumber, viewPosition.column));
            if (!visibleRange) {
                return -1;
            }
            return visibleRange.left;
        }
        getTargetAtClientPoint(clientX, clientY) {
            const mouseTarget = this._pointerHandler.getTargetAtClientPoint(clientX, clientY);
            if (!mouseTarget) {
                return null;
            }
            return viewUserInputEvents_1.ViewUserInputEvents.convertViewToModelMouseTarget(mouseTarget, this._context.viewModel.coordinatesConverter);
        }
        createOverviewRuler(cssClassName) {
            return new overviewRuler_1.OverviewRuler(this._context, cssClassName);
        }
        change(callback) {
            this._viewZones.changeViewZones(callback);
            this._scheduleRender();
        }
        render(now, everything) {
            if (everything) {
                // Force everything to render...
                this._viewLines.forceShouldRender();
                for (const viewPart of this._viewParts) {
                    viewPart.forceShouldRender();
                }
            }
            if (now) {
                this._flushAccumulatedAndRenderNow();
            }
            else {
                this._scheduleRender();
            }
        }
        writeScreenReaderContent(reason) {
            this._textAreaHandler.writeScreenReaderContent(reason);
        }
        focus() {
            this._textAreaHandler.focusTextArea();
        }
        isFocused() {
            return this._textAreaHandler.isFocused();
        }
        setAriaOptions(options) {
            this._textAreaHandler.setAriaOptions(options);
        }
        addContentWidget(widgetData) {
            this._contentWidgets.addWidget(widgetData.widget);
            this.layoutContentWidget(widgetData);
            this._scheduleRender();
        }
        layoutContentWidget(widgetData) {
            this._contentWidgets.setWidgetPosition(widgetData.widget, widgetData.position?.position ?? null, widgetData.position?.secondaryPosition ?? null, widgetData.position?.preference ?? null, widgetData.position?.positionAffinity ?? null);
            this._scheduleRender();
        }
        removeContentWidget(widgetData) {
            this._contentWidgets.removeWidget(widgetData.widget);
            this._scheduleRender();
        }
        addOverlayWidget(widgetData) {
            this._overlayWidgets.addWidget(widgetData.widget);
            this.layoutOverlayWidget(widgetData);
            this._scheduleRender();
        }
        layoutOverlayWidget(widgetData) {
            const shouldRender = this._overlayWidgets.setWidgetPosition(widgetData.widget, widgetData.position);
            if (shouldRender) {
                this._scheduleRender();
            }
        }
        removeOverlayWidget(widgetData) {
            this._overlayWidgets.removeWidget(widgetData.widget);
            this._scheduleRender();
        }
        addGlyphMarginWidget(widgetData) {
            this._glyphMarginWidgets.addWidget(widgetData.widget);
            this._shouldRecomputeGlyphMarginLanes = true;
            this._scheduleRender();
        }
        layoutGlyphMarginWidget(widgetData) {
            const newPreference = widgetData.position;
            const shouldRender = this._glyphMarginWidgets.setWidgetPosition(widgetData.widget, newPreference);
            if (shouldRender) {
                this._shouldRecomputeGlyphMarginLanes = true;
                this._scheduleRender();
            }
        }
        removeGlyphMarginWidget(widgetData) {
            this._glyphMarginWidgets.removeWidget(widgetData.widget);
            this._shouldRecomputeGlyphMarginLanes = true;
            this._scheduleRender();
        }
    };
    exports.View = View;
    exports.View = View = __decorate([
        __param(6, instantiation_1.IInstantiationService)
    ], View);
    function safeInvokeNoArg(func) {
        try {
            return func();
        }
        catch (e) {
            (0, errors_1.onUnexpectedError)(e);
            return null;
        }
    }
    class EditorRenderingCoordinator {
        static { this.INSTANCE = new EditorRenderingCoordinator(); }
        constructor() {
            this._coordinatedRenderings = [];
            this._animationFrameRunners = new Map();
        }
        scheduleCoordinatedRendering(rendering) {
            this._coordinatedRenderings.push(rendering);
            this._scheduleRender(rendering.window);
            return {
                dispose: () => {
                    const renderingIndex = this._coordinatedRenderings.indexOf(rendering);
                    if (renderingIndex === -1) {
                        return;
                    }
                    this._coordinatedRenderings.splice(renderingIndex, 1);
                    if (this._coordinatedRenderings.length === 0) {
                        // There are no more renderings to coordinate => cancel animation frames
                        for (const [_, disposable] of this._animationFrameRunners) {
                            disposable.dispose();
                        }
                        this._animationFrameRunners.clear();
                    }
                }
            };
        }
        _scheduleRender(window) {
            if (!this._animationFrameRunners.has(window)) {
                const runner = () => {
                    this._animationFrameRunners.delete(window);
                    this._onRenderScheduled();
                };
                this._animationFrameRunners.set(window, dom.runAtThisOrScheduleAtNextAnimationFrame(window, runner, 100));
            }
        }
        _onRenderScheduled() {
            const coordinatedRenderings = this._coordinatedRenderings.slice(0);
            this._coordinatedRenderings = [];
            for (const rendering of coordinatedRenderings) {
                safeInvokeNoArg(() => rendering.prepareRenderText());
            }
            const datas = [];
            for (let i = 0, len = coordinatedRenderings.length; i < len; i++) {
                const rendering = coordinatedRenderings[i];
                datas[i] = safeInvokeNoArg(() => rendering.renderText());
            }
            for (let i = 0, len = coordinatedRenderings.length; i < len; i++) {
                const rendering = coordinatedRenderings[i];
                const data = datas[i];
                if (!data) {
                    continue;
                }
                const [viewParts, ctx] = data;
                safeInvokeNoArg(() => rendering.prepareRender(viewParts, ctx));
            }
            for (let i = 0, len = coordinatedRenderings.length; i < len; i++) {
                const rendering = coordinatedRenderings[i];
                const data = datas[i];
                if (!data) {
                    continue;
                }
                const [viewParts, ctx] = data;
                safeInvokeNoArg(() => rendering.render(viewParts, ctx));
            }
        }
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[783/*vs/editor/common/model/bracketPairsTextModelPart/colorizedBracketPairsDecorationProvider*/], __M([1/*require*/,0/*exports*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,4/*vs/editor/common/core/range*/,80/*vs/editor/common/core/editorColorRegistry*/,25/*vs/platform/theme/common/themeService*/]), function (require, exports, event_1, lifecycle_1, range_1, editorColorRegistry_1, themeService_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ColorizedBracketPairsDecorationProvider = void 0;
    class ColorizedBracketPairsDecorationProvider extends lifecycle_1.Disposable {
        constructor(textModel) {
            super();
            this.textModel = textModel;
            this.colorProvider = new ColorProvider();
            this.onDidChangeEmitter = new event_1.Emitter();
            this.onDidChange = this.onDidChangeEmitter.event;
            this.colorizationOptions = textModel.getOptions().bracketPairColorizationOptions;
            this._register(textModel.bracketPairs.onDidChange(e => {
                this.onDidChangeEmitter.fire();
            }));
        }
        //#region TextModel events
        handleDidChangeOptions(e) {
            this.colorizationOptions = this.textModel.getOptions().bracketPairColorizationOptions;
        }
        //#endregion
        getDecorationsInRange(range, ownerId, filterOutValidation, onlyMinimapDecorations) {
            if (onlyMinimapDecorations) {
                // Bracket pair colorization decorations are not rendered in the minimap
                return [];
            }
            if (ownerId === undefined) {
                return [];
            }
            if (!this.colorizationOptions.enabled) {
                return [];
            }
            const result = this.textModel.bracketPairs.getBracketsInRange(range, true).map(bracket => ({
                id: `bracket${bracket.range.toString()}-${bracket.nestingLevel}`,
                options: {
                    description: 'BracketPairColorization',
                    inlineClassName: this.colorProvider.getInlineClassName(bracket, this.colorizationOptions.independentColorPoolPerBracketType),
                },
                ownerId: 0,
                range: bracket.range,
            })).toArray();
            return result;
        }
        getAllDecorations(ownerId, filterOutValidation) {
            if (ownerId === undefined) {
                return [];
            }
            if (!this.colorizationOptions.enabled) {
                return [];
            }
            return this.getDecorationsInRange(new range_1.Range(1, 1, this.textModel.getLineCount(), 1), ownerId, filterOutValidation);
        }
    }
    exports.ColorizedBracketPairsDecorationProvider = ColorizedBracketPairsDecorationProvider;
    class ColorProvider {
        constructor() {
            this.unexpectedClosingBracketClassName = 'unexpected-closing-bracket';
        }
        getInlineClassName(bracket, independentColorPoolPerBracketType) {
            if (bracket.isInvalid) {
                return this.unexpectedClosingBracketClassName;
            }
            return this.getInlineClassNameOfLevel(independentColorPoolPerBracketType ? bracket.nestingLevelOfEqualBracketType : bracket.nestingLevel);
        }
        getInlineClassNameOfLevel(level) {
            // To support a dynamic amount of colors up to 6 colors,
            // we use a number that is a lcm of all numbers from 1 to 6.
            return `bracket-highlighting-${level % 30}`;
        }
    }
    (0, themeService_1.registerThemingParticipant)((theme, collector) => {
        const colors = [
            editorColorRegistry_1.editorBracketHighlightingForeground1,
            editorColorRegistry_1.editorBracketHighlightingForeground2,
            editorColorRegistry_1.editorBracketHighlightingForeground3,
            editorColorRegistry_1.editorBracketHighlightingForeground4,
            editorColorRegistry_1.editorBracketHighlightingForeground5,
            editorColorRegistry_1.editorBracketHighlightingForeground6
        ];
        const colorProvider = new ColorProvider();
        collector.addRule(`.monaco-editor .${colorProvider.unexpectedClosingBracketClassName} { color: ${theme.getColor(editorColorRegistry_1.editorBracketHighlightingUnexpectedBracketForeground)}; }`);
        const colorValues = colors
            .map(c => theme.getColor(c))
            .filter((c) => !!c)
            .filter(c => !c.isTransparent());
        for (let level = 0; level < 30; level++) {
            const color = colorValues[level % colorValues.length];
            collector.addRule(`.monaco-editor .${colorProvider.getInlineClassNameOfLevel(level)} { color: ${color}; }`);
        }
    });
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[784/*vs/editor/common/services/markerDecorationsService*/], __M([1/*require*/,0/*exports*/,108/*vs/platform/markers/common/markers*/,2/*vs/base/common/lifecycle*/,40/*vs/editor/common/model*/,25/*vs/platform/theme/common/themeService*/,80/*vs/editor/common/core/editorColorRegistry*/,51/*vs/editor/common/services/model*/,4/*vs/editor/common/core/range*/,42/*vs/base/common/network*/,6/*vs/base/common/event*/,32/*vs/platform/theme/common/colorRegistry*/,45/*vs/base/common/map*/,298/*vs/base/common/collections*/]), function (require, exports, markers_1, lifecycle_1, model_1, themeService_1, editorColorRegistry_1, model_2, range_1, network_1, event_1, colorRegistry_1, map_1, collections_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MarkerDecorationsService = void 0;
    let MarkerDecorationsService = class MarkerDecorationsService extends lifecycle_1.Disposable {
        constructor(modelService, _markerService) {
            super();
            this._markerService = _markerService;
            this._onDidChangeMarker = this._register(new event_1.Emitter());
            this._markerDecorations = new map_1.ResourceMap();
            modelService.getModels().forEach(model => this._onModelAdded(model));
            this._register(modelService.onModelAdded(this._onModelAdded, this));
            this._register(modelService.onModelRemoved(this._onModelRemoved, this));
            this._register(this._markerService.onMarkerChanged(this._handleMarkerChange, this));
        }
        dispose() {
            super.dispose();
            this._markerDecorations.forEach(value => value.dispose());
            this._markerDecorations.clear();
        }
        getMarker(uri, decoration) {
            const markerDecorations = this._markerDecorations.get(uri);
            return markerDecorations ? (markerDecorations.getMarker(decoration) || null) : null;
        }
        _handleMarkerChange(changedResources) {
            changedResources.forEach((resource) => {
                const markerDecorations = this._markerDecorations.get(resource);
                if (markerDecorations) {
                    this._updateDecorations(markerDecorations);
                }
            });
        }
        _onModelAdded(model) {
            const markerDecorations = new MarkerDecorations(model);
            this._markerDecorations.set(model.uri, markerDecorations);
            this._updateDecorations(markerDecorations);
        }
        _onModelRemoved(model) {
            const markerDecorations = this._markerDecorations.get(model.uri);
            if (markerDecorations) {
                markerDecorations.dispose();
                this._markerDecorations.delete(model.uri);
            }
            // clean up markers for internal, transient models
            if (model.uri.scheme === network_1.Schemas.inMemory
                || model.uri.scheme === network_1.Schemas.internal
                || model.uri.scheme === network_1.Schemas.vscode) {
                this._markerService?.read({ resource: model.uri }).map(marker => marker.owner).forEach(owner => this._markerService.remove(owner, [model.uri]));
            }
        }
        _updateDecorations(markerDecorations) {
            // Limit to the first 500 errors/warnings
            const markers = this._markerService.read({ resource: markerDecorations.model.uri, take: 500 });
            if (markerDecorations.update(markers)) {
                this._onDidChangeMarker.fire(markerDecorations.model);
            }
        }
    };
    exports.MarkerDecorationsService = MarkerDecorationsService;
    exports.MarkerDecorationsService = MarkerDecorationsService = __decorate([
        __param(0, model_2.IModelService),
        __param(1, markers_1.IMarkerService)
    ], MarkerDecorationsService);
    class MarkerDecorations extends lifecycle_1.Disposable {
        constructor(model) {
            super();
            this.model = model;
            this._map = new map_1.BidirectionalMap();
            this._register((0, lifecycle_1.toDisposable)(() => {
                this.model.deltaDecorations([...this._map.values()], []);
                this._map.clear();
            }));
        }
        update(markers) {
            // We use the fact that marker instances are not recreated when different owners
            // update. So we can compare references to find out what changed since the last update.
            const { added, removed } = (0, collections_1.diffSets)(new Set(this._map.keys()), new Set(markers));
            if (added.length === 0 && removed.length === 0) {
                return false;
            }
            const oldIds = removed.map(marker => this._map.get(marker));
            const newDecorations = added.map(marker => {
                return {
                    range: this._createDecorationRange(this.model, marker),
                    options: this._createDecorationOption(marker)
                };
            });
            const ids = this.model.deltaDecorations(oldIds, newDecorations);
            for (const removedMarker of removed) {
                this._map.delete(removedMarker);
            }
            for (let index = 0; index < ids.length; index++) {
                this._map.set(added[index], ids[index]);
            }
            return true;
        }
        getMarker(decoration) {
            return this._map.getKey(decoration.id);
        }
        _createDecorationRange(model, rawMarker) {
            let ret = range_1.Range.lift(rawMarker);
            if (rawMarker.severity === markers_1.MarkerSeverity.Hint && !this._hasMarkerTag(rawMarker, 1 /* MarkerTag.Unnecessary */) && !this._hasMarkerTag(rawMarker, 2 /* MarkerTag.Deprecated */)) {
                // * never render hints on multiple lines
                // * make enough space for three dots
                ret = ret.setEndPosition(ret.startLineNumber, ret.startColumn + 2);
            }
            ret = model.validateRange(ret);
            if (ret.isEmpty()) {
                const maxColumn = model.getLineLastNonWhitespaceColumn(ret.startLineNumber) ||
                    model.getLineMaxColumn(ret.startLineNumber);
                if (maxColumn === 1 || ret.endColumn >= maxColumn) {
                    // empty line or behind eol
                    // keep the range as is, it will be rendered 1ch wide
                    return ret;
                }
                const word = model.getWordAtPosition(ret.getStartPosition());
                if (word) {
                    ret = new range_1.Range(ret.startLineNumber, word.startColumn, ret.endLineNumber, word.endColumn);
                }
            }
            else if (rawMarker.endColumn === Number.MAX_VALUE && rawMarker.startColumn === 1 && ret.startLineNumber === ret.endLineNumber) {
                const minColumn = model.getLineFirstNonWhitespaceColumn(rawMarker.startLineNumber);
                if (minColumn < ret.endColumn) {
                    ret = new range_1.Range(ret.startLineNumber, minColumn, ret.endLineNumber, ret.endColumn);
                    rawMarker.startColumn = minColumn;
                }
            }
            return ret;
        }
        _createDecorationOption(marker) {
            let className;
            let color = undefined;
            let zIndex;
            let inlineClassName = undefined;
            let minimap;
            switch (marker.severity) {
                case markers_1.MarkerSeverity.Hint:
                    if (this._hasMarkerTag(marker, 2 /* MarkerTag.Deprecated */)) {
                        className = undefined;
                    }
                    else if (this._hasMarkerTag(marker, 1 /* MarkerTag.Unnecessary */)) {
                        className = "squiggly-unnecessary" /* ClassName.EditorUnnecessaryDecoration */;
                    }
                    else {
                        className = "squiggly-hint" /* ClassName.EditorHintDecoration */;
                    }
                    zIndex = 0;
                    break;
                case markers_1.MarkerSeverity.Info:
                    className = "squiggly-info" /* ClassName.EditorInfoDecoration */;
                    color = (0, themeService_1.themeColorFromId)(editorColorRegistry_1.overviewRulerInfo);
                    zIndex = 10;
                    minimap = {
                        color: (0, themeService_1.themeColorFromId)(colorRegistry_1.minimapInfo),
                        position: 1 /* MinimapPosition.Inline */
                    };
                    break;
                case markers_1.MarkerSeverity.Warning:
                    className = "squiggly-warning" /* ClassName.EditorWarningDecoration */;
                    color = (0, themeService_1.themeColorFromId)(editorColorRegistry_1.overviewRulerWarning);
                    zIndex = 20;
                    minimap = {
                        color: (0, themeService_1.themeColorFromId)(colorRegistry_1.minimapWarning),
                        position: 1 /* MinimapPosition.Inline */
                    };
                    break;
                case markers_1.MarkerSeverity.Error:
                default:
                    className = "squiggly-error" /* ClassName.EditorErrorDecoration */;
                    color = (0, themeService_1.themeColorFromId)(editorColorRegistry_1.overviewRulerError);
                    zIndex = 30;
                    minimap = {
                        color: (0, themeService_1.themeColorFromId)(colorRegistry_1.minimapError),
                        position: 1 /* MinimapPosition.Inline */
                    };
                    break;
            }
            if (marker.tags) {
                if (marker.tags.indexOf(1 /* MarkerTag.Unnecessary */) !== -1) {
                    inlineClassName = "squiggly-inline-unnecessary" /* ClassName.EditorUnnecessaryInlineDecoration */;
                }
                if (marker.tags.indexOf(2 /* MarkerTag.Deprecated */) !== -1) {
                    inlineClassName = "squiggly-inline-deprecated" /* ClassName.EditorDeprecatedInlineDecoration */;
                }
            }
            return {
                description: 'marker-decoration',
                stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */,
                className,
                showIfCollapsed: true,
                overviewRuler: {
                    color,
                    position: model_1.OverviewRulerLane.Right
                },
                minimap,
                zIndex,
                inlineClassName,
            };
        }
        _hasMarkerTag(marker, tag) {
            if (marker.tags) {
                return marker.tags.indexOf(tag) >= 0;
            }
            return false;
        }
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[282/*vs/editor/common/services/semanticTokensProviderStyling*/], __M([1/*require*/,0/*exports*/,148/*vs/editor/common/encodedTokenAttributes*/,25/*vs/platform/theme/common/themeService*/,62/*vs/platform/log/common/log*/,589/*vs/editor/common/tokens/sparseMultilineTokens*/,43/*vs/editor/common/languages/language*/]), function (require, exports, encodedTokenAttributes_1, themeService_1, log_1, sparseMultilineTokens_1, language_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SemanticTokensProviderStyling = void 0;
    exports.toMultilineTokens2 = toMultilineTokens2;
    const ENABLE_TRACE = false;
    let SemanticTokensProviderStyling = class SemanticTokensProviderStyling {
        constructor(_legend, _themeService, _languageService, _logService) {
            this._legend = _legend;
            this._themeService = _themeService;
            this._languageService = _languageService;
            this._logService = _logService;
            this._hasWarnedOverlappingTokens = false;
            this._hasWarnedInvalidLengthTokens = false;
            this._hasWarnedInvalidEditStart = false;
            this._hashTable = new HashTable();
        }
        getMetadata(tokenTypeIndex, tokenModifierSet, languageId) {
            const encodedLanguageId = this._languageService.languageIdCodec.encodeLanguageId(languageId);
            const entry = this._hashTable.get(tokenTypeIndex, tokenModifierSet, encodedLanguageId);
            let metadata;
            if (entry) {
                metadata = entry.metadata;
                if (ENABLE_TRACE && this._logService.getLevel() === log_1.LogLevel.Trace) {
                    this._logService.trace(`SemanticTokensProviderStyling [CACHED] ${tokenTypeIndex} / ${tokenModifierSet}: foreground ${encodedTokenAttributes_1.TokenMetadata.getForeground(metadata)}, fontStyle ${encodedTokenAttributes_1.TokenMetadata.getFontStyle(metadata).toString(2)}`);
                }
            }
            else {
                let tokenType = this._legend.tokenTypes[tokenTypeIndex];
                const tokenModifiers = [];
                if (tokenType) {
                    let modifierSet = tokenModifierSet;
                    for (let modifierIndex = 0; modifierSet > 0 && modifierIndex < this._legend.tokenModifiers.length; modifierIndex++) {
                        if (modifierSet & 1) {
                            tokenModifiers.push(this._legend.tokenModifiers[modifierIndex]);
                        }
                        modifierSet = modifierSet >> 1;
                    }
                    if (ENABLE_TRACE && modifierSet > 0 && this._logService.getLevel() === log_1.LogLevel.Trace) {
                        this._logService.trace(`SemanticTokensProviderStyling: unknown token modifier index: ${tokenModifierSet.toString(2)} for legend: ${JSON.stringify(this._legend.tokenModifiers)}`);
                        tokenModifiers.push('not-in-legend');
                    }
                    const tokenStyle = this._themeService.getColorTheme().getTokenStyleMetadata(tokenType, tokenModifiers, languageId);
                    if (typeof tokenStyle === 'undefined') {
                        metadata = 2147483647 /* SemanticTokensProviderStylingConstants.NO_STYLING */;
                    }
                    else {
                        metadata = 0;
                        if (typeof tokenStyle.italic !== 'undefined') {
                            const italicBit = (tokenStyle.italic ? 1 /* FontStyle.Italic */ : 0) << 11 /* MetadataConsts.FONT_STYLE_OFFSET */;
                            metadata |= italicBit | 1 /* MetadataConsts.SEMANTIC_USE_ITALIC */;
                        }
                        if (typeof tokenStyle.bold !== 'undefined') {
                            const boldBit = (tokenStyle.bold ? 2 /* FontStyle.Bold */ : 0) << 11 /* MetadataConsts.FONT_STYLE_OFFSET */;
                            metadata |= boldBit | 2 /* MetadataConsts.SEMANTIC_USE_BOLD */;
                        }
                        if (typeof tokenStyle.underline !== 'undefined') {
                            const underlineBit = (tokenStyle.underline ? 4 /* FontStyle.Underline */ : 0) << 11 /* MetadataConsts.FONT_STYLE_OFFSET */;
                            metadata |= underlineBit | 4 /* MetadataConsts.SEMANTIC_USE_UNDERLINE */;
                        }
                        if (typeof tokenStyle.strikethrough !== 'undefined') {
                            const strikethroughBit = (tokenStyle.strikethrough ? 8 /* FontStyle.Strikethrough */ : 0) << 11 /* MetadataConsts.FONT_STYLE_OFFSET */;
                            metadata |= strikethroughBit | 8 /* MetadataConsts.SEMANTIC_USE_STRIKETHROUGH */;
                        }
                        if (tokenStyle.foreground) {
                            const foregroundBits = (tokenStyle.foreground) << 15 /* MetadataConsts.FOREGROUND_OFFSET */;
                            metadata |= foregroundBits | 16 /* MetadataConsts.SEMANTIC_USE_FOREGROUND */;
                        }
                        if (metadata === 0) {
                            // Nothing!
                            metadata = 2147483647 /* SemanticTokensProviderStylingConstants.NO_STYLING */;
                        }
                    }
                }
                else {
                    if (ENABLE_TRACE && this._logService.getLevel() === log_1.LogLevel.Trace) {
                        this._logService.trace(`SemanticTokensProviderStyling: unknown token type index: ${tokenTypeIndex} for legend: ${JSON.stringify(this._legend.tokenTypes)}`);
                    }
                    metadata = 2147483647 /* SemanticTokensProviderStylingConstants.NO_STYLING */;
                    tokenType = 'not-in-legend';
                }
                this._hashTable.add(tokenTypeIndex, tokenModifierSet, encodedLanguageId, metadata);
                if (ENABLE_TRACE && this._logService.getLevel() === log_1.LogLevel.Trace) {
                    this._logService.trace(`SemanticTokensProviderStyling ${tokenTypeIndex} (${tokenType}) / ${tokenModifierSet} (${tokenModifiers.join(' ')}): foreground ${encodedTokenAttributes_1.TokenMetadata.getForeground(metadata)}, fontStyle ${encodedTokenAttributes_1.TokenMetadata.getFontStyle(metadata).toString(2)}`);
                }
            }
            return metadata;
        }
        warnOverlappingSemanticTokens(lineNumber, startColumn) {
            if (!this._hasWarnedOverlappingTokens) {
                this._hasWarnedOverlappingTokens = true;
                this._logService.warn(`Overlapping semantic tokens detected at lineNumber ${lineNumber}, column ${startColumn}`);
            }
        }
        warnInvalidLengthSemanticTokens(lineNumber, startColumn) {
            if (!this._hasWarnedInvalidLengthTokens) {
                this._hasWarnedInvalidLengthTokens = true;
                this._logService.warn(`Semantic token with invalid length detected at lineNumber ${lineNumber}, column ${startColumn}`);
            }
        }
        warnInvalidEditStart(previousResultId, resultId, editIndex, editStart, maxExpectedStart) {
            if (!this._hasWarnedInvalidEditStart) {
                this._hasWarnedInvalidEditStart = true;
                this._logService.warn(`Invalid semantic tokens edit detected (previousResultId: ${previousResultId}, resultId: ${resultId}) at edit #${editIndex}: The provided start offset ${editStart} is outside the previous data (length ${maxExpectedStart}).`);
            }
        }
    };
    exports.SemanticTokensProviderStyling = SemanticTokensProviderStyling;
    exports.SemanticTokensProviderStyling = SemanticTokensProviderStyling = __decorate([
        __param(1, themeService_1.IThemeService),
        __param(2, language_1.ILanguageService),
        __param(3, log_1.ILogService)
    ], SemanticTokensProviderStyling);
    function toMultilineTokens2(tokens, styling, languageId) {
        const srcData = tokens.data;
        const tokenCount = (tokens.data.length / 5) | 0;
        const tokensPerArea = Math.max(Math.ceil(tokenCount / 1024 /* SemanticColoringConstants.DesiredMaxAreas */), 400 /* SemanticColoringConstants.DesiredTokensPerArea */);
        const result = [];
        let tokenIndex = 0;
        let lastLineNumber = 1;
        let lastStartCharacter = 0;
        while (tokenIndex < tokenCount) {
            const tokenStartIndex = tokenIndex;
            let tokenEndIndex = Math.min(tokenStartIndex + tokensPerArea, tokenCount);
            // Keep tokens on the same line in the same area...
            if (tokenEndIndex < tokenCount) {
                let smallTokenEndIndex = tokenEndIndex;
                while (smallTokenEndIndex - 1 > tokenStartIndex && srcData[5 * smallTokenEndIndex] === 0) {
                    smallTokenEndIndex--;
                }
                if (smallTokenEndIndex - 1 === tokenStartIndex) {
                    // there are so many tokens on this line that our area would be empty, we must now go right
                    let bigTokenEndIndex = tokenEndIndex;
                    while (bigTokenEndIndex + 1 < tokenCount && srcData[5 * bigTokenEndIndex] === 0) {
                        bigTokenEndIndex++;
                    }
                    tokenEndIndex = bigTokenEndIndex;
                }
                else {
                    tokenEndIndex = smallTokenEndIndex;
                }
            }
            let destData = new Uint32Array((tokenEndIndex - tokenStartIndex) * 4);
            let destOffset = 0;
            let areaLine = 0;
            let prevLineNumber = 0;
            let prevEndCharacter = 0;
            while (tokenIndex < tokenEndIndex) {
                const srcOffset = 5 * tokenIndex;
                const deltaLine = srcData[srcOffset];
                const deltaCharacter = srcData[srcOffset + 1];
                // Casting both `lineNumber`, `startCharacter` and `endCharacter` here to uint32 using `|0`
                // to validate below with the actual values that will be inserted in the Uint32Array result
                const lineNumber = (lastLineNumber + deltaLine) | 0;
                const startCharacter = (deltaLine === 0 ? (lastStartCharacter + deltaCharacter) | 0 : deltaCharacter);
                const length = srcData[srcOffset + 2];
                const endCharacter = (startCharacter + length) | 0;
                const tokenTypeIndex = srcData[srcOffset + 3];
                const tokenModifierSet = srcData[srcOffset + 4];
                if (endCharacter <= startCharacter) {
                    // this token is invalid (most likely a negative length casted to uint32)
                    styling.warnInvalidLengthSemanticTokens(lineNumber, startCharacter + 1);
                }
                else if (prevLineNumber === lineNumber && prevEndCharacter > startCharacter) {
                    // this token overlaps with the previous token
                    styling.warnOverlappingSemanticTokens(lineNumber, startCharacter + 1);
                }
                else {
                    const metadata = styling.getMetadata(tokenTypeIndex, tokenModifierSet, languageId);
                    if (metadata !== 2147483647 /* SemanticTokensProviderStylingConstants.NO_STYLING */) {
                        if (areaLine === 0) {
                            areaLine = lineNumber;
                        }
                        destData[destOffset] = lineNumber - areaLine;
                        destData[destOffset + 1] = startCharacter;
                        destData[destOffset + 2] = endCharacter;
                        destData[destOffset + 3] = metadata;
                        destOffset += 4;
                        prevLineNumber = lineNumber;
                        prevEndCharacter = endCharacter;
                    }
                }
                lastLineNumber = lineNumber;
                lastStartCharacter = startCharacter;
                tokenIndex++;
            }
            if (destOffset !== destData.length) {
                destData = destData.subarray(0, destOffset);
            }
            const tokens = sparseMultilineTokens_1.SparseMultilineTokens.create(areaLine, destData);
            result.push(tokens);
        }
        return result;
    }
    class HashTableEntry {
        constructor(tokenTypeIndex, tokenModifierSet, languageId, metadata) {
            this.tokenTypeIndex = tokenTypeIndex;
            this.tokenModifierSet = tokenModifierSet;
            this.languageId = languageId;
            this.metadata = metadata;
            this.next = null;
        }
    }
    class HashTable {
        static { this._SIZES = [3, 7, 13, 31, 61, 127, 251, 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071, 262139, 524287, 1048573, 2097143]; }
        constructor() {
            this._elementsCount = 0;
            this._currentLengthIndex = 0;
            this._currentLength = HashTable._SIZES[this._currentLengthIndex];
            this._growCount = Math.round(this._currentLengthIndex + 1 < HashTable._SIZES.length ? 2 / 3 * this._currentLength : 0);
            this._elements = [];
            HashTable._nullOutEntries(this._elements, this._currentLength);
        }
        static _nullOutEntries(entries, length) {
            for (let i = 0; i < length; i++) {
                entries[i] = null;
            }
        }
        _hash2(n1, n2) {
            return (((n1 << 5) - n1) + n2) | 0; // n1 * 31 + n2, keep as int32
        }
        _hashFunc(tokenTypeIndex, tokenModifierSet, languageId) {
            return this._hash2(this._hash2(tokenTypeIndex, tokenModifierSet), languageId) % this._currentLength;
        }
        get(tokenTypeIndex, tokenModifierSet, languageId) {
            const hash = this._hashFunc(tokenTypeIndex, tokenModifierSet, languageId);
            let p = this._elements[hash];
            while (p) {
                if (p.tokenTypeIndex === tokenTypeIndex && p.tokenModifierSet === tokenModifierSet && p.languageId === languageId) {
                    return p;
                }
                p = p.next;
            }
            return null;
        }
        add(tokenTypeIndex, tokenModifierSet, languageId, metadata) {
            this._elementsCount++;
            if (this._growCount !== 0 && this._elementsCount >= this._growCount) {
                // expand!
                const oldElements = this._elements;
                this._currentLengthIndex++;
                this._currentLength = HashTable._SIZES[this._currentLengthIndex];
                this._growCount = Math.round(this._currentLengthIndex + 1 < HashTable._SIZES.length ? 2 / 3 * this._currentLength : 0);
                this._elements = [];
                HashTable._nullOutEntries(this._elements, this._currentLength);
                for (const first of oldElements) {
                    let p = first;
                    while (p) {
                        const oldNext = p.next;
                        p.next = null;
                        this._add(p);
                        p = oldNext;
                    }
                }
            }
            this._add(new HashTableEntry(tokenTypeIndex, tokenModifierSet, languageId, metadata));
        }
        _add(element) {
            const hash = this._hashFunc(element.tokenTypeIndex, element.tokenModifierSet, element.languageId);
            element.next = this._elements[hash];
            this._elements[hash] = element;
        }
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[785/*vs/editor/common/services/semanticTokensStylingService*/], __M([1/*require*/,0/*exports*/,2/*vs/base/common/lifecycle*/,43/*vs/editor/common/languages/language*/,25/*vs/platform/theme/common/themeService*/,62/*vs/platform/log/common/log*/,282/*vs/editor/common/services/semanticTokensProviderStyling*/,267/*vs/editor/common/services/semanticTokensStyling*/,49/*vs/platform/instantiation/common/extensions*/]), function (require, exports, lifecycle_1, language_1, themeService_1, log_1, semanticTokensProviderStyling_1, semanticTokensStyling_1, extensions_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SemanticTokensStylingService = void 0;
    let SemanticTokensStylingService = class SemanticTokensStylingService extends lifecycle_1.Disposable {
        constructor(_themeService, _logService, _languageService) {
            super();
            this._themeService = _themeService;
            this._logService = _logService;
            this._languageService = _languageService;
            this._caches = new WeakMap();
            this._register(this._themeService.onDidColorThemeChange(() => {
                this._caches = new WeakMap();
            }));
        }
        getStyling(provider) {
            if (!this._caches.has(provider)) {
                this._caches.set(provider, new semanticTokensProviderStyling_1.SemanticTokensProviderStyling(provider.getLegend(), this._themeService, this._languageService, this._logService));
            }
            return this._caches.get(provider);
        }
    };
    exports.SemanticTokensStylingService = SemanticTokensStylingService;
    exports.SemanticTokensStylingService = SemanticTokensStylingService = __decorate([
        __param(0, themeService_1.IThemeService),
        __param(1, log_1.ILogService),
        __param(2, language_1.ILanguageService)
    ], SemanticTokensStylingService);
    (0, extensions_1.registerSingleton)(semanticTokensStyling_1.ISemanticTokensStylingService, SemanticTokensStylingService, 1 /* InstantiationType.Delayed */);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[786/*vs/editor/contrib/placeholderText/browser/placeholderText.contribution*/], __M([1/*require*/,0/*exports*/,15/*vs/editor/browser/editorExtensions*/,80/*vs/editor/common/core/editorColorRegistry*/,3/*vs/nls*/,89/*vs/platform/theme/common/colorUtils*/,379/*vs/editor/contrib/placeholderText/browser/placeholderTextContribution*/,700/*vs/platform/observable/common/wrapInReloadableClass*/,528/*vs/css!vs/editor/contrib/placeholderText/browser/placeholderText*/]), function (require, exports, editorExtensions_1, editorColorRegistry_1, nls_1, colorUtils_1, placeholderTextContribution_1, wrapInReloadableClass_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    (0, editorExtensions_1.registerEditorContribution)(placeholderTextContribution_1.PlaceholderTextContribution.ID, (0, wrapInReloadableClass_1.wrapInReloadableClass1)(() => placeholderTextContribution_1.PlaceholderTextContribution), 0 /* EditorContributionInstantiation.Eager */);
    (0, colorUtils_1.registerColor)('editor.placeholder.foreground', editorColorRegistry_1.ghostTextForeground, (0, nls_1.localize)(1194, 'Foreground color of the placeholder text in the editor.'));
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[417/*vs/editor/contrib/quickAccess/browser/editorNavigationQuickAccess*/], __M([1/*require*/,0/*exports*/,127/*vs/base/common/functional*/,2/*vs/base/common/lifecycle*/,168/*vs/editor/browser/editorBrowser*/,40/*vs/editor/common/model*/,80/*vs/editor/common/core/editorColorRegistry*/,25/*vs/platform/theme/common/themeService*/,46/*vs/base/browser/ui/aria/aria*/]), function (require, exports, functional_1, lifecycle_1, editorBrowser_1, model_1, editorColorRegistry_1, themeService_1, aria_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AbstractEditorNavigationQuickAccessProvider = void 0;
    /**
     * A reusable quick access provider for the editor with support
     * for adding decorations for navigating in the currently active file
     * (for example "Go to line", "Go to symbol").
     */
    class AbstractEditorNavigationQuickAccessProvider {
        constructor(options) {
            this.options = options;
            //#endregion
            //#region Decorations Utils
            this.rangeHighlightDecorationId = undefined;
        }
        //#region Provider methods
        provide(picker, token, runOptions) {
            const disposables = new lifecycle_1.DisposableStore();
            // Apply options if any
            picker.canAcceptInBackground = !!this.options?.canAcceptInBackground;
            // Disable filtering & sorting, we control the results
            picker.matchOnLabel = picker.matchOnDescription = picker.matchOnDetail = picker.sortByLabel = false;
            // Provide based on current active editor
            const pickerDisposable = disposables.add(new lifecycle_1.MutableDisposable());
            pickerDisposable.value = this.doProvide(picker, token, runOptions);
            // Re-create whenever the active editor changes
            disposables.add(this.onDidActiveTextEditorControlChange(() => {
                // Clear old
                pickerDisposable.value = undefined;
                // Add new
                pickerDisposable.value = this.doProvide(picker, token);
            }));
            return disposables;
        }
        doProvide(picker, token, runOptions) {
            const disposables = new lifecycle_1.DisposableStore();
            // With text control
            const editor = this.activeTextEditorControl;
            if (editor && this.canProvideWithTextEditor(editor)) {
                const context = { editor };
                // Restore any view state if this picker was closed
                // without actually going to a line
                const codeEditor = (0, editorBrowser_1.getCodeEditor)(editor);
                if (codeEditor) {
                    // Remember view state and update it when the cursor position
                    // changes even later because it could be that the user has
                    // configured quick access to remain open when focus is lost and
                    // we always want to restore the current location.
                    let lastKnownEditorViewState = editor.saveViewState() ?? undefined;
                    disposables.add(codeEditor.onDidChangeCursorPosition(() => {
                        lastKnownEditorViewState = editor.saveViewState() ?? undefined;
                    }));
                    context.restoreViewState = () => {
                        if (lastKnownEditorViewState && editor === this.activeTextEditorControl) {
                            editor.restoreViewState(lastKnownEditorViewState);
                        }
                    };
                    disposables.add((0, functional_1.createSingleCallFunction)(token.onCancellationRequested)(() => context.restoreViewState?.()));
                }
                // Clean up decorations on dispose
                disposables.add((0, lifecycle_1.toDisposable)(() => this.clearDecorations(editor)));
                // Ask subclass for entries
                disposables.add(this.provideWithTextEditor(context, picker, token, runOptions));
            }
            // Without text control
            else {
                disposables.add(this.provideWithoutTextEditor(picker, token));
            }
            return disposables;
        }
        /**
         * Subclasses to implement if they can operate on the text editor.
         */
        canProvideWithTextEditor(editor) {
            return true;
        }
        gotoLocation({ editor }, options) {
            editor.setSelection(options.range, "code.jump" /* TextEditorSelectionSource.JUMP */);
            editor.revealRangeInCenter(options.range, 0 /* ScrollType.Smooth */);
            if (!options.preserveFocus) {
                editor.focus();
            }
            const model = editor.getModel();
            if (model && 'getLineContent' in model) {
                (0, aria_1.status)(`${model.getLineContent(options.range.startLineNumber)}`);
            }
        }
        getModel(editor) {
            return (0, editorBrowser_1.isDiffEditor)(editor) ?
                editor.getModel()?.modified :
                editor.getModel();
        }
        addDecorations(editor, range) {
            editor.changeDecorations(changeAccessor => {
                // Reset old decorations if any
                const deleteDecorations = [];
                if (this.rangeHighlightDecorationId) {
                    deleteDecorations.push(this.rangeHighlightDecorationId.overviewRulerDecorationId);
                    deleteDecorations.push(this.rangeHighlightDecorationId.rangeHighlightId);
                    this.rangeHighlightDecorationId = undefined;
                }
                // Add new decorations for the range
                const newDecorations = [
                    // highlight the entire line on the range
                    {
                        range,
                        options: {
                            description: 'quick-access-range-highlight',
                            className: 'rangeHighlight',
                            isWholeLine: true
                        }
                    },
                    // also add overview ruler highlight
                    {
                        range,
                        options: {
                            description: 'quick-access-range-highlight-overview',
                            overviewRuler: {
                                color: (0, themeService_1.themeColorFromId)(editorColorRegistry_1.overviewRulerRangeHighlight),
                                position: model_1.OverviewRulerLane.Full
                            }
                        }
                    }
                ];
                const [rangeHighlightId, overviewRulerDecorationId] = changeAccessor.deltaDecorations(deleteDecorations, newDecorations);
                this.rangeHighlightDecorationId = { rangeHighlightId, overviewRulerDecorationId };
            });
        }
        clearDecorations(editor) {
            const rangeHighlightDecorationId = this.rangeHighlightDecorationId;
            if (rangeHighlightDecorationId) {
                editor.changeDecorations(changeAccessor => {
                    changeAccessor.deltaDecorations([
                        rangeHighlightDecorationId.overviewRulerDecorationId,
                        rangeHighlightDecorationId.rangeHighlightId
                    ], []);
                });
                this.rangeHighlightDecorationId = undefined;
            }
        }
    }
    exports.AbstractEditorNavigationQuickAccessProvider = AbstractEditorNavigationQuickAccessProvider;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[787/*vs/editor/contrib/quickAccess/browser/gotoLineQuickAccess*/], __M([1/*require*/,0/*exports*/,2/*vs/base/common/lifecycle*/,168/*vs/editor/browser/editorBrowser*/,417/*vs/editor/contrib/quickAccess/browser/editorNavigationQuickAccess*/,3/*vs/nls*/]), function (require, exports, lifecycle_1, editorBrowser_1, editorNavigationQuickAccess_1, nls_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AbstractGotoLineQuickAccessProvider = void 0;
    class AbstractGotoLineQuickAccessProvider extends editorNavigationQuickAccess_1.AbstractEditorNavigationQuickAccessProvider {
        static { this.PREFIX = ':'; }
        constructor() {
            super({ canAcceptInBackground: true });
        }
        provideWithoutTextEditor(picker) {
            const label = (0, nls_1.localize)(1195, "Open a text editor first to go to a line.");
            picker.items = [{ label }];
            picker.ariaLabel = label;
            return lifecycle_1.Disposable.None;
        }
        provideWithTextEditor(context, picker, token) {
            const editor = context.editor;
            const disposables = new lifecycle_1.DisposableStore();
            // Goto line once picked
            disposables.add(picker.onDidAccept(event => {
                const [item] = picker.selectedItems;
                if (item) {
                    if (!this.isValidLineNumber(editor, item.lineNumber)) {
                        return;
                    }
                    this.gotoLocation(context, { range: this.toRange(item.lineNumber, item.column), keyMods: picker.keyMods, preserveFocus: event.inBackground });
                    if (!event.inBackground) {
                        picker.hide();
                    }
                }
            }));
            // React to picker changes
            const updatePickerAndEditor = () => {
                const position = this.parsePosition(editor, picker.value.trim().substr(AbstractGotoLineQuickAccessProvider.PREFIX.length));
                const label = this.getPickLabel(editor, position.lineNumber, position.column);
                // Picker
                picker.items = [{
                        lineNumber: position.lineNumber,
                        column: position.column,
                        label
                    }];
                // ARIA Label
                picker.ariaLabel = label;
                // Clear decorations for invalid range
                if (!this.isValidLineNumber(editor, position.lineNumber)) {
                    this.clearDecorations(editor);
                    return;
                }
                // Reveal
                const range = this.toRange(position.lineNumber, position.column);
                editor.revealRangeInCenter(range, 0 /* ScrollType.Smooth */);
                // Decorate
                this.addDecorations(editor, range);
            };
            updatePickerAndEditor();
            disposables.add(picker.onDidChangeValue(() => updatePickerAndEditor()));
            // Adjust line number visibility as needed
            const codeEditor = (0, editorBrowser_1.getCodeEditor)(editor);
            if (codeEditor) {
                const options = codeEditor.getOptions();
                const lineNumbers = options.get(68 /* EditorOption.lineNumbers */);
                if (lineNumbers.renderType === 2 /* RenderLineNumbersType.Relative */) {
                    codeEditor.updateOptions({ lineNumbers: 'on' });
                    disposables.add((0, lifecycle_1.toDisposable)(() => codeEditor.updateOptions({ lineNumbers: 'relative' })));
                }
            }
            return disposables;
        }
        toRange(lineNumber = 1, column = 1) {
            return {
                startLineNumber: lineNumber,
                startColumn: column,
                endLineNumber: lineNumber,
                endColumn: column
            };
        }
        parsePosition(editor, value) {
            // Support line-col formats of `line,col`, `line:col`, `line#col`
            const numbers = value.split(/,|:|#/).map(part => parseInt(part, 10)).filter(part => !isNaN(part));
            const endLine = this.lineCount(editor) + 1;
            return {
                lineNumber: numbers[0] > 0 ? numbers[0] : endLine + numbers[0],
                column: numbers[1]
            };
        }
        getPickLabel(editor, lineNumber, column) {
            // Location valid: indicate this as picker label
            if (this.isValidLineNumber(editor, lineNumber)) {
                if (this.isValidColumn(editor, lineNumber, column)) {
                    return (0, nls_1.localize)(1196, "Go to line {0} and character {1}.", lineNumber, column);
                }
                return (0, nls_1.localize)(1197, "Go to line {0}.", lineNumber);
            }
            // Location invalid: show generic label
            const position = editor.getPosition() || { lineNumber: 1, column: 1 };
            const lineCount = this.lineCount(editor);
            if (lineCount > 1) {
                return (0, nls_1.localize)(1198, "Current Line: {0}, Character: {1}. Type a line number between 1 and {2} to navigate to.", position.lineNumber, position.column, lineCount);
            }
            return (0, nls_1.localize)(1199, "Current Line: {0}, Character: {1}. Type a line number to navigate to.", position.lineNumber, position.column);
        }
        isValidLineNumber(editor, lineNumber) {
            if (!lineNumber || typeof lineNumber !== 'number') {
                return false;
            }
            return lineNumber > 0 && lineNumber <= this.lineCount(editor);
        }
        isValidColumn(editor, lineNumber, column) {
            if (!column || typeof column !== 'number') {
                return false;
            }
            const model = this.getModel(editor);
            if (!model) {
                return false;
            }
            const positionCandidate = { lineNumber, column };
            return model.validatePosition(positionCandidate).equals(positionCandidate);
        }
        lineCount(editor) {
            return this.getModel(editor)?.getLineCount() ?? 0;
        }
    }
    exports.AbstractGotoLineQuickAccessProvider = AbstractGotoLineQuickAccessProvider;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[788/*vs/editor/contrib/quickAccess/browser/gotoSymbolQuickAccess*/], __M([1/*require*/,0/*exports*/,14/*vs/base/common/async*/,18/*vs/base/common/cancellation*/,26/*vs/base/common/codicons*/,30/*vs/base/common/themables*/,628/*vs/base/common/fuzzyScorer*/,2/*vs/base/common/lifecycle*/,11/*vs/base/common/strings*/,4/*vs/editor/common/core/range*/,27/*vs/editor/common/languages*/,182/*vs/editor/contrib/documentSymbols/browser/outlineModel*/,417/*vs/editor/contrib/quickAccess/browser/editorNavigationQuickAccess*/,3/*vs/nls*/,17/*vs/editor/common/services/languageFeatures*/,67/*vs/base/common/arraysFind*/]), function (require, exports, async_1, cancellation_1, codicons_1, themables_1, fuzzyScorer_1, lifecycle_1, strings_1, range_1, languages_1, outlineModel_1, editorNavigationQuickAccess_1, nls_1, languageFeatures_1, arraysFind_1) {
    "use strict";
    var AbstractGotoSymbolQuickAccessProvider_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AbstractGotoSymbolQuickAccessProvider = void 0;
    let AbstractGotoSymbolQuickAccessProvider = class AbstractGotoSymbolQuickAccessProvider extends editorNavigationQuickAccess_1.AbstractEditorNavigationQuickAccessProvider {
        static { AbstractGotoSymbolQuickAccessProvider_1 = this; }
        static { this.PREFIX = '@'; }
        static { this.SCOPE_PREFIX = ':'; }
        static { this.PREFIX_BY_CATEGORY = `${this.PREFIX}${this.SCOPE_PREFIX}`; }
        constructor(_languageFeaturesService, _outlineModelService, options = Object.create(null)) {
            super(options);
            this._languageFeaturesService = _languageFeaturesService;
            this._outlineModelService = _outlineModelService;
            this.options = options;
            this.options.canAcceptInBackground = true;
        }
        provideWithoutTextEditor(picker) {
            this.provideLabelPick(picker, (0, nls_1.localize)(1200, "To go to a symbol, first open a text editor with symbol information."));
            return lifecycle_1.Disposable.None;
        }
        provideWithTextEditor(context, picker, token, runOptions) {
            const editor = context.editor;
            const model = this.getModel(editor);
            if (!model) {
                return lifecycle_1.Disposable.None;
            }
            // Provide symbols from model if available in registry
            if (this._languageFeaturesService.documentSymbolProvider.has(model)) {
                return this.doProvideWithEditorSymbols(context, model, picker, token, runOptions);
            }
            // Otherwise show an entry for a model without registry
            // But give a chance to resolve the symbols at a later
            // point if possible
            return this.doProvideWithoutEditorSymbols(context, model, picker, token);
        }
        doProvideWithoutEditorSymbols(context, model, picker, token) {
            const disposables = new lifecycle_1.DisposableStore();
            // Generic pick for not having any symbol information
            this.provideLabelPick(picker, (0, nls_1.localize)(1201, "The active text editor does not provide symbol information."));
            // Wait for changes to the registry and see if eventually
            // we do get symbols. This can happen if the picker is opened
            // very early after the model has loaded but before the
            // language registry is ready.
            // https://github.com/microsoft/vscode/issues/70607
            (async () => {
                const result = await this.waitForLanguageSymbolRegistry(model, disposables);
                if (!result || token.isCancellationRequested) {
                    return;
                }
                disposables.add(this.doProvideWithEditorSymbols(context, model, picker, token));
            })();
            return disposables;
        }
        provideLabelPick(picker, label) {
            picker.items = [{ label, index: 0, kind: 14 /* SymbolKind.String */ }];
            picker.ariaLabel = label;
        }
        async waitForLanguageSymbolRegistry(model, disposables) {
            if (this._languageFeaturesService.documentSymbolProvider.has(model)) {
                return true;
            }
            const symbolProviderRegistryPromise = new async_1.DeferredPromise();
            // Resolve promise when registry knows model
            const symbolProviderListener = disposables.add(this._languageFeaturesService.documentSymbolProvider.onDidChange(() => {
                if (this._languageFeaturesService.documentSymbolProvider.has(model)) {
                    symbolProviderListener.dispose();
                    symbolProviderRegistryPromise.complete(true);
                }
            }));
            // Resolve promise when we get disposed too
            disposables.add((0, lifecycle_1.toDisposable)(() => symbolProviderRegistryPromise.complete(false)));
            return symbolProviderRegistryPromise.p;
        }
        doProvideWithEditorSymbols(context, model, picker, token, runOptions) {
            const editor = context.editor;
            const disposables = new lifecycle_1.DisposableStore();
            // Goto symbol once picked
            disposables.add(picker.onDidAccept(event => {
                const [item] = picker.selectedItems;
                if (item && item.range) {
                    this.gotoLocation(context, { range: item.range.selection, keyMods: picker.keyMods, preserveFocus: event.inBackground });
                    runOptions?.handleAccept?.(item);
                    if (!event.inBackground) {
                        picker.hide();
                    }
                }
            }));
            // Goto symbol side by side if enabled
            disposables.add(picker.onDidTriggerItemButton(({ item }) => {
                if (item && item.range) {
                    this.gotoLocation(context, { range: item.range.selection, keyMods: picker.keyMods, forceSideBySide: true });
                    picker.hide();
                }
            }));
            // Resolve symbols from document once and reuse this
            // request for all filtering and typing then on
            const symbolsPromise = this.getDocumentSymbols(model, token);
            // Set initial picks and update on type
            let picksCts = undefined;
            const updatePickerItems = async (positionToEnclose) => {
                // Cancel any previous ask for picks and busy
                picksCts?.dispose(true);
                picker.busy = false;
                // Create new cancellation source for this run
                picksCts = new cancellation_1.CancellationTokenSource(token);
                // Collect symbol picks
                picker.busy = true;
                try {
                    const query = (0, fuzzyScorer_1.prepareQuery)(picker.value.substr(AbstractGotoSymbolQuickAccessProvider_1.PREFIX.length).trim());
                    const items = await this.doGetSymbolPicks(symbolsPromise, query, undefined, picksCts.token, model);
                    if (token.isCancellationRequested) {
                        return;
                    }
                    if (items.length > 0) {
                        picker.items = items;
                        if (positionToEnclose && query.original.length === 0) {
                            const candidate = (0, arraysFind_1.findLast)(items, item => Boolean(item.type !== 'separator' && item.range && range_1.Range.containsPosition(item.range.decoration, positionToEnclose)));
                            if (candidate) {
                                picker.activeItems = [candidate];
                            }
                        }
                    }
                    else {
                        if (query.original.length > 0) {
                            this.provideLabelPick(picker, (0, nls_1.localize)(1202, "No matching editor symbols"));
                        }
                        else {
                            this.provideLabelPick(picker, (0, nls_1.localize)(1203, "No editor symbols"));
                        }
                    }
                }
                finally {
                    if (!token.isCancellationRequested) {
                        picker.busy = false;
                    }
                }
            };
            disposables.add(picker.onDidChangeValue(() => updatePickerItems(undefined)));
            updatePickerItems(editor.getSelection()?.getPosition());
            // Reveal and decorate when active item changes
            disposables.add(picker.onDidChangeActive(() => {
                const [item] = picker.activeItems;
                if (item && item.range) {
                    // Reveal
                    editor.revealRangeInCenter(item.range.selection, 0 /* ScrollType.Smooth */);
                    // Decorate
                    this.addDecorations(editor, item.range.decoration);
                }
            }));
            return disposables;
        }
        async doGetSymbolPicks(symbolsPromise, query, options, token, model) {
            const symbols = await symbolsPromise;
            if (token.isCancellationRequested) {
                return [];
            }
            const filterBySymbolKind = query.original.indexOf(AbstractGotoSymbolQuickAccessProvider_1.SCOPE_PREFIX) === 0;
            const filterPos = filterBySymbolKind ? 1 : 0;
            // Split between symbol and container query
            let symbolQuery;
            let containerQuery;
            if (query.values && query.values.length > 1) {
                symbolQuery = (0, fuzzyScorer_1.pieceToQuery)(query.values[0]); // symbol: only match on first part
                containerQuery = (0, fuzzyScorer_1.pieceToQuery)(query.values.slice(1)); // container: match on all but first parts
            }
            else {
                symbolQuery = query;
            }
            // Convert to symbol picks and apply filtering
            let buttons;
            const openSideBySideDirection = this.options?.openSideBySideDirection?.();
            if (openSideBySideDirection) {
                buttons = [{
                        iconClass: openSideBySideDirection === 'right' ? themables_1.ThemeIcon.asClassName(codicons_1.Codicon.splitHorizontal) : themables_1.ThemeIcon.asClassName(codicons_1.Codicon.splitVertical),
                        tooltip: openSideBySideDirection === 'right' ? (0, nls_1.localize)(1204, "Open to the Side") : (0, nls_1.localize)(1205, "Open to the Bottom")
                    }];
            }
            const filteredSymbolPicks = [];
            for (let index = 0; index < symbols.length; index++) {
                const symbol = symbols[index];
                const symbolLabel = (0, strings_1.trim)(symbol.name);
                const symbolLabelWithIcon = `$(${languages_1.SymbolKinds.toIcon(symbol.kind).id}) ${symbolLabel}`;
                const symbolLabelIconOffset = symbolLabelWithIcon.length - symbolLabel.length;
                let containerLabel = symbol.containerName;
                if (options?.extraContainerLabel) {
                    if (containerLabel) {
                        containerLabel = `${options.extraContainerLabel} • ${containerLabel}`;
                    }
                    else {
                        containerLabel = options.extraContainerLabel;
                    }
                }
                let symbolScore = undefined;
                let symbolMatches = undefined;
                let containerScore = undefined;
                let containerMatches = undefined;
                if (query.original.length > filterPos) {
                    // First: try to score on the entire query, it is possible that
                    // the symbol matches perfectly (e.g. searching for "change log"
                    // can be a match on a markdown symbol "change log"). In that
                    // case we want to skip the container query altogether.
                    let skipContainerQuery = false;
                    if (symbolQuery !== query) {
                        [symbolScore, symbolMatches] = (0, fuzzyScorer_1.scoreFuzzy2)(symbolLabelWithIcon, { ...query, values: undefined /* disable multi-query support */ }, filterPos, symbolLabelIconOffset);
                        if (typeof symbolScore === 'number') {
                            skipContainerQuery = true; // since we consumed the query, skip any container matching
                        }
                    }
                    // Otherwise: score on the symbol query and match on the container later
                    if (typeof symbolScore !== 'number') {
                        [symbolScore, symbolMatches] = (0, fuzzyScorer_1.scoreFuzzy2)(symbolLabelWithIcon, symbolQuery, filterPos, symbolLabelIconOffset);
                        if (typeof symbolScore !== 'number') {
                            continue;
                        }
                    }
                    // Score by container if specified
                    if (!skipContainerQuery && containerQuery) {
                        if (containerLabel && containerQuery.original.length > 0) {
                            [containerScore, containerMatches] = (0, fuzzyScorer_1.scoreFuzzy2)(containerLabel, containerQuery);
                        }
                        if (typeof containerScore !== 'number') {
                            continue;
                        }
                        if (typeof symbolScore === 'number') {
                            symbolScore += containerScore; // boost symbolScore by containerScore
                        }
                    }
                }
                const deprecated = symbol.tags && symbol.tags.indexOf(1 /* SymbolTag.Deprecated */) >= 0;
                filteredSymbolPicks.push({
                    index,
                    kind: symbol.kind,
                    score: symbolScore,
                    label: symbolLabelWithIcon,
                    ariaLabel: (0, languages_1.getAriaLabelForSymbol)(symbol.name, symbol.kind),
                    description: containerLabel,
                    highlights: deprecated ? undefined : {
                        label: symbolMatches,
                        description: containerMatches
                    },
                    range: {
                        selection: range_1.Range.collapseToStart(symbol.selectionRange),
                        decoration: symbol.range
                    },
                    uri: model.uri,
                    symbolName: symbolLabel,
                    strikethrough: deprecated,
                    buttons
                });
            }
            // Sort by score
            const sortedFilteredSymbolPicks = filteredSymbolPicks.sort((symbolA, symbolB) => filterBySymbolKind ?
                this.compareByKindAndScore(symbolA, symbolB) :
                this.compareByScore(symbolA, symbolB));
            // Add separator for types
            // - @  only total number of symbols
            // - @: grouped by symbol kind
            let symbolPicks = [];
            if (filterBySymbolKind) {
                let lastSymbolKind = undefined;
                let lastSeparator = undefined;
                let lastSymbolKindCounter = 0;
                function updateLastSeparatorLabel() {
                    if (lastSeparator && typeof lastSymbolKind === 'number' && lastSymbolKindCounter > 0) {
                        lastSeparator.label = (0, strings_1.format)(NLS_SYMBOL_KIND_CACHE[lastSymbolKind] || FALLBACK_NLS_SYMBOL_KIND, lastSymbolKindCounter);
                    }
                }
                for (const symbolPick of sortedFilteredSymbolPicks) {
                    // Found new kind
                    if (lastSymbolKind !== symbolPick.kind) {
                        // Update last separator with number of symbols we found for kind
                        updateLastSeparatorLabel();
                        lastSymbolKind = symbolPick.kind;
                        lastSymbolKindCounter = 1;
                        // Add new separator for new kind
                        lastSeparator = { type: 'separator' };
                        symbolPicks.push(lastSeparator);
                    }
                    // Existing kind, keep counting
                    else {
                        lastSymbolKindCounter++;
                    }
                    // Add to final result
                    symbolPicks.push(symbolPick);
                }
                // Update last separator with number of symbols we found for kind
                updateLastSeparatorLabel();
            }
            else if (sortedFilteredSymbolPicks.length > 0) {
                symbolPicks = [
                    { label: (0, nls_1.localize)(1206, "symbols ({0})", filteredSymbolPicks.length), type: 'separator' },
                    ...sortedFilteredSymbolPicks
                ];
            }
            return symbolPicks;
        }
        compareByScore(symbolA, symbolB) {
            if (typeof symbolA.score !== 'number' && typeof symbolB.score === 'number') {
                return 1;
            }
            else if (typeof symbolA.score === 'number' && typeof symbolB.score !== 'number') {
                return -1;
            }
            if (typeof symbolA.score === 'number' && typeof symbolB.score === 'number') {
                if (symbolA.score > symbolB.score) {
                    return -1;
                }
                else if (symbolA.score < symbolB.score) {
                    return 1;
                }
            }
            if (symbolA.index < symbolB.index) {
                return -1;
            }
            else if (symbolA.index > symbolB.index) {
                return 1;
            }
            return 0;
        }
        compareByKindAndScore(symbolA, symbolB) {
            const kindA = NLS_SYMBOL_KIND_CACHE[symbolA.kind] || FALLBACK_NLS_SYMBOL_KIND;
            const kindB = NLS_SYMBOL_KIND_CACHE[symbolB.kind] || FALLBACK_NLS_SYMBOL_KIND;
            // Sort by type first if scoped search
            const result = kindA.localeCompare(kindB);
            if (result === 0) {
                return this.compareByScore(symbolA, symbolB);
            }
            return result;
        }
        async getDocumentSymbols(document, token) {
            const model = await this._outlineModelService.getOrCreate(document, token);
            return token.isCancellationRequested ? [] : model.asListOfDocumentSymbols();
        }
    };
    exports.AbstractGotoSymbolQuickAccessProvider = AbstractGotoSymbolQuickAccessProvider;
    exports.AbstractGotoSymbolQuickAccessProvider = AbstractGotoSymbolQuickAccessProvider = AbstractGotoSymbolQuickAccessProvider_1 = __decorate([
        __param(0, languageFeatures_1.ILanguageFeaturesService),
        __param(1, outlineModel_1.IOutlineModelService)
    ], AbstractGotoSymbolQuickAccessProvider);
    // #region NLS Helpers
    const FALLBACK_NLS_SYMBOL_KIND = (0, nls_1.localize)(1207, "properties ({0})");
    const NLS_SYMBOL_KIND_CACHE = {
        [5 /* SymbolKind.Method */]: (0, nls_1.localize)(1208, "methods ({0})"),
        [11 /* SymbolKind.Function */]: (0, nls_1.localize)(1209, "functions ({0})"),
        [8 /* SymbolKind.Constructor */]: (0, nls_1.localize)(1210, "constructors ({0})"),
        [12 /* SymbolKind.Variable */]: (0, nls_1.localize)(1211, "variables ({0})"),
        [4 /* SymbolKind.Class */]: (0, nls_1.localize)(1212, "classes ({0})"),
        [22 /* SymbolKind.Struct */]: (0, nls_1.localize)(1213, "structs ({0})"),
        [23 /* SymbolKind.Event */]: (0, nls_1.localize)(1214, "events ({0})"),
        [24 /* SymbolKind.Operator */]: (0, nls_1.localize)(1215, "operators ({0})"),
        [10 /* SymbolKind.Interface */]: (0, nls_1.localize)(1216, "interfaces ({0})"),
        [2 /* SymbolKind.Namespace */]: (0, nls_1.localize)(1217, "namespaces ({0})"),
        [3 /* SymbolKind.Package */]: (0, nls_1.localize)(1218, "packages ({0})"),
        [25 /* SymbolKind.TypeParameter */]: (0, nls_1.localize)(1219, "type parameters ({0})"),
        [1 /* SymbolKind.Module */]: (0, nls_1.localize)(1220, "modules ({0})"),
        [6 /* SymbolKind.Property */]: (0, nls_1.localize)(1221, "properties ({0})"),
        [9 /* SymbolKind.Enum */]: (0, nls_1.localize)(1222, "enumerations ({0})"),
        [21 /* SymbolKind.EnumMember */]: (0, nls_1.localize)(1223, "enumeration members ({0})"),
        [14 /* SymbolKind.String */]: (0, nls_1.localize)(1224, "strings ({0})"),
        [0 /* SymbolKind.File */]: (0, nls_1.localize)(1225, "files ({0})"),
        [17 /* SymbolKind.Array */]: (0, nls_1.localize)(1226, "arrays ({0})"),
        [15 /* SymbolKind.Number */]: (0, nls_1.localize)(1227, "numbers ({0})"),
        [16 /* SymbolKind.Boolean */]: (0, nls_1.localize)(1228, "booleans ({0})"),
        [18 /* SymbolKind.Object */]: (0, nls_1.localize)(1229, "objects ({0})"),
        [19 /* SymbolKind.Key */]: (0, nls_1.localize)(1230, "keys ({0})"),
        [7 /* SymbolKind.Field */]: (0, nls_1.localize)(1231, "fields ({0})"),
        [13 /* SymbolKind.Constant */]: (0, nls_1.localize)(1232, "constants ({0})")
    };
});
//#endregion

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[789/*vs/editor/contrib/rename/browser/renameWidget*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,47/*vs/base/browser/keyboardEvent*/,46/*vs/base/browser/ui/aria/aria*/,81/*vs/base/browser/ui/hover/hoverDelegate2*/,44/*vs/base/browser/ui/hover/hoverDelegateFactory*/,114/*vs/base/browser/ui/iconLabel/iconLabels*/,115/*vs/base/browser/ui/list/listWidget*/,13/*vs/base/common/arrays*/,14/*vs/base/common/async*/,18/*vs/base/common/cancellation*/,26/*vs/base/common/codicons*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,54/*vs/base/common/stopwatch*/,19/*vs/base/common/types*/,74/*vs/editor/browser/config/domFontInfo*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/,27/*vs/editor/common/languages*/,3/*vs/nls*/,12/*vs/platform/contextkey/common/contextkey*/,31/*vs/platform/keybinding/common/keybinding*/,62/*vs/platform/log/common/log*/,110/*vs/platform/theme/browser/defaultStyles*/,32/*vs/platform/theme/common/colorRegistry*/,25/*vs/platform/theme/common/themeService*/,529/*vs/css!vs/editor/contrib/rename/browser/renameWidget*/]), function (require, exports, dom, keyboardEvent_1, aria, hoverDelegate2_1, hoverDelegateFactory_1, iconLabels_1, listWidget_1, arrays, async_1, cancellation_1, codicons_1, event_1, lifecycle_1, stopwatch_1, types_1, domFontInfo, position_1, range_1, languages_1, nls, contextkey_1, keybinding_1, log_1, defaultStyles_1, colorRegistry_1, themeService_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.RenameWidget = exports.CONTEXT_RENAME_INPUT_FOCUSED = exports.CONTEXT_RENAME_INPUT_VISIBLE = void 0;
    /** for debugging */
    const _sticky = false;
    exports.CONTEXT_RENAME_INPUT_VISIBLE = new contextkey_1.RawContextKey('renameInputVisible', false, nls.localize(1246, "Whether the rename input widget is visible"));
    exports.CONTEXT_RENAME_INPUT_FOCUSED = new contextkey_1.RawContextKey('renameInputFocused', false, nls.localize(1247, "Whether the rename input widget is focused"));
    let RenameWidget = class RenameWidget {
        constructor(_editor, _acceptKeybindings, _themeService, _keybindingService, contextKeyService, _logService) {
            this._editor = _editor;
            this._acceptKeybindings = _acceptKeybindings;
            this._themeService = _themeService;
            this._keybindingService = _keybindingService;
            this._logService = _logService;
            // implement IContentWidget
            this.allowEditorOverflow = true;
            this._disposables = new lifecycle_1.DisposableStore();
            this._visibleContextKey = exports.CONTEXT_RENAME_INPUT_VISIBLE.bindTo(contextKeyService);
            this._isEditingRenameCandidate = false;
            this._nRenameSuggestionsInvocations = 0;
            this._hadAutomaticRenameSuggestionsInvocation = false;
            this._candidates = new Set();
            this._beforeFirstInputFieldEditSW = new stopwatch_1.StopWatch();
            this._inputWithButton = new InputWithButton();
            this._disposables.add(this._inputWithButton);
            this._editor.addContentWidget(this);
            this._disposables.add(this._editor.onDidChangeConfiguration(e => {
                if (e.hasChanged(50 /* EditorOption.fontInfo */)) {
                    this._updateFont();
                }
            }));
            this._disposables.add(_themeService.onDidColorThemeChange(this._updateStyles, this));
        }
        dispose() {
            this._disposables.dispose();
            this._editor.removeContentWidget(this);
        }
        getId() {
            return '__renameInputWidget';
        }
        getDomNode() {
            if (!this._domNode) {
                this._domNode = document.createElement('div');
                this._domNode.className = 'monaco-editor rename-box';
                this._domNode.appendChild(this._inputWithButton.domNode);
                this._renameCandidateListView = this._disposables.add(new RenameCandidateListView(this._domNode, {
                    fontInfo: this._editor.getOption(50 /* EditorOption.fontInfo */),
                    onFocusChange: (newSymbolName) => {
                        this._inputWithButton.input.value = newSymbolName;
                        this._isEditingRenameCandidate = false; // @ulugbekna: reset
                    },
                    onSelectionChange: () => {
                        this._isEditingRenameCandidate = false; // @ulugbekna: because user picked a rename suggestion
                        this.acceptInput(false); // we don't allow preview with mouse click for now
                    }
                }));
                this._disposables.add(this._inputWithButton.onDidInputChange(() => {
                    if (this._renameCandidateListView?.focusedCandidate !== undefined) {
                        this._isEditingRenameCandidate = true;
                    }
                    this._timeBeforeFirstInputFieldEdit ??= this._beforeFirstInputFieldEditSW.elapsed();
                    if (this._renameCandidateProvidersCts?.token.isCancellationRequested === false) {
                        this._renameCandidateProvidersCts.cancel();
                    }
                    this._renameCandidateListView?.clearFocus();
                }));
                this._label = document.createElement('div');
                this._label.className = 'rename-label';
                this._domNode.appendChild(this._label);
                this._updateFont();
                this._updateStyles(this._themeService.getColorTheme());
            }
            return this._domNode;
        }
        _updateStyles(theme) {
            if (!this._domNode) {
                return;
            }
            const widgetShadowColor = theme.getColor(colorRegistry_1.widgetShadow);
            const widgetBorderColor = theme.getColor(colorRegistry_1.widgetBorder);
            this._domNode.style.backgroundColor = String(theme.getColor(colorRegistry_1.editorWidgetBackground) ?? '');
            this._domNode.style.boxShadow = widgetShadowColor ? ` 0 0 8px 2px ${widgetShadowColor}` : '';
            this._domNode.style.border = widgetBorderColor ? `1px solid ${widgetBorderColor}` : '';
            this._domNode.style.color = String(theme.getColor(colorRegistry_1.inputForeground) ?? '');
            const border = theme.getColor(colorRegistry_1.inputBorder);
            this._inputWithButton.domNode.style.backgroundColor = String(theme.getColor(colorRegistry_1.inputBackground) ?? '');
            this._inputWithButton.input.style.backgroundColor = String(theme.getColor(colorRegistry_1.inputBackground) ?? '');
            this._inputWithButton.domNode.style.borderWidth = border ? '1px' : '0px';
            this._inputWithButton.domNode.style.borderStyle = border ? 'solid' : 'none';
            this._inputWithButton.domNode.style.borderColor = border?.toString() ?? 'none';
        }
        _updateFont() {
            if (this._domNode === undefined) {
                return;
            }
            (0, types_1.assertType)(this._label !== undefined, 'RenameWidget#_updateFont: _label must not be undefined given _domNode is defined');
            this._editor.applyFontInfo(this._inputWithButton.input);
            const fontInfo = this._editor.getOption(50 /* EditorOption.fontInfo */);
            this._label.style.fontSize = `${this._computeLabelFontSize(fontInfo.fontSize)}px`;
        }
        _computeLabelFontSize(editorFontSize) {
            return editorFontSize * 0.8;
        }
        getPosition() {
            if (!this._visible) {
                return null;
            }
            if (!this._editor.hasModel() || // @ulugbekna: shouldn't happen
                !this._editor.getDomNode() // @ulugbekna: can happen during tests based on suggestWidget's similar predicate check
            ) {
                return null;
            }
            const bodyBox = dom.getClientArea(this.getDomNode().ownerDocument.body);
            const editorBox = dom.getDomNodePagePosition(this._editor.getDomNode());
            const cursorBoxTop = this._getTopForPosition();
            this._nPxAvailableAbove = cursorBoxTop + editorBox.top;
            this._nPxAvailableBelow = bodyBox.height - this._nPxAvailableAbove;
            const lineHeight = this._editor.getOption(67 /* EditorOption.lineHeight */);
            const { totalHeight: candidateViewHeight } = RenameCandidateView.getLayoutInfo({ lineHeight });
            const positionPreference = this._nPxAvailableBelow > candidateViewHeight * 6 /* approximate # of candidates to fit in (inclusive of rename input box & rename label) */
                ? [2 /* ContentWidgetPositionPreference.BELOW */, 1 /* ContentWidgetPositionPreference.ABOVE */]
                : [1 /* ContentWidgetPositionPreference.ABOVE */, 2 /* ContentWidgetPositionPreference.BELOW */];
            return {
                position: this._position,
                preference: positionPreference,
            };
        }
        beforeRender() {
            const [accept, preview] = this._acceptKeybindings;
            this._label.innerText = nls.localize(1248, "{0} to Rename, {1} to Preview", this._keybindingService.lookupKeybinding(accept)?.getLabel(), this._keybindingService.lookupKeybinding(preview)?.getLabel());
            this._domNode.style.minWidth = `200px`; // to prevent from widening when candidates come in
            return null;
        }
        afterRender(position) {
            // FIXME@ulugbekna: commenting trace log out until we start unmounting the widget from editor properly - https://github.com/microsoft/vscode/issues/226975
            // this._trace('invoking afterRender, position: ', position ? 'not null' : 'null');
            if (position === null) {
                // cancel rename when input widget isn't rendered anymore
                this.cancelInput(true, 'afterRender (because position is null)');
                return;
            }
            if (!this._editor.hasModel() || // shouldn't happen
                !this._editor.getDomNode() // can happen during tests based on suggestWidget's similar predicate check
            ) {
                return;
            }
            (0, types_1.assertType)(this._renameCandidateListView);
            (0, types_1.assertType)(this._nPxAvailableAbove !== undefined);
            (0, types_1.assertType)(this._nPxAvailableBelow !== undefined);
            const inputBoxHeight = dom.getTotalHeight(this._inputWithButton.domNode);
            const labelHeight = dom.getTotalHeight(this._label);
            let totalHeightAvailable;
            if (position === 2 /* ContentWidgetPositionPreference.BELOW */) {
                totalHeightAvailable = this._nPxAvailableBelow;
            }
            else {
                totalHeightAvailable = this._nPxAvailableAbove;
            }
            this._renameCandidateListView.layout({
                height: totalHeightAvailable - labelHeight - inputBoxHeight,
                width: dom.getTotalWidth(this._inputWithButton.domNode),
            });
        }
        acceptInput(wantsPreview) {
            this._trace(`invoking acceptInput`);
            this._currentAcceptInput?.(wantsPreview);
        }
        cancelInput(focusEditor, caller) {
            // this._trace(`invoking cancelInput, caller: ${caller}, _currentCancelInput: ${this._currentAcceptInput ? 'not undefined' : 'undefined'}`);
            this._currentCancelInput?.(focusEditor);
        }
        focusNextRenameSuggestion() {
            if (!this._renameCandidateListView?.focusNext()) {
                this._inputWithButton.input.value = this._currentName;
            }
        }
        focusPreviousRenameSuggestion() {
            if (!this._renameCandidateListView?.focusPrevious()) {
                this._inputWithButton.input.value = this._currentName;
            }
        }
        /**
         * @param requestRenameCandidates is `undefined` when there are no rename suggestion providers
         */
        getInput(where, currentName, supportPreview, requestRenameCandidates, cts) {
            const { start: selectionStart, end: selectionEnd } = this._getSelection(where, currentName);
            this._renameCts = cts;
            const disposeOnDone = new lifecycle_1.DisposableStore();
            this._nRenameSuggestionsInvocations = 0;
            this._hadAutomaticRenameSuggestionsInvocation = false;
            if (requestRenameCandidates === undefined) {
                this._inputWithButton.button.style.display = 'none';
            }
            else {
                this._inputWithButton.button.style.display = 'flex';
                this._requestRenameCandidatesOnce = requestRenameCandidates;
                this._requestRenameCandidates(currentName, false);
                disposeOnDone.add(dom.addDisposableListener(this._inputWithButton.button, 'click', () => this._requestRenameCandidates(currentName, true)));
                disposeOnDone.add(dom.addDisposableListener(this._inputWithButton.button, dom.EventType.KEY_DOWN, (e) => {
                    const keyEvent = new keyboardEvent_1.StandardKeyboardEvent(e);
                    if (keyEvent.equals(3 /* KeyCode.Enter */) || keyEvent.equals(10 /* KeyCode.Space */)) {
                        keyEvent.stopPropagation();
                        keyEvent.preventDefault();
                        this._requestRenameCandidates(currentName, true);
                    }
                }));
            }
            this._isEditingRenameCandidate = false;
            this._domNode.classList.toggle('preview', supportPreview);
            this._position = new position_1.Position(where.startLineNumber, where.startColumn);
            this._currentName = currentName;
            this._inputWithButton.input.value = currentName;
            this._inputWithButton.input.setAttribute('selectionStart', selectionStart.toString());
            this._inputWithButton.input.setAttribute('selectionEnd', selectionEnd.toString());
            this._inputWithButton.input.size = Math.max((where.endColumn - where.startColumn) * 1.1, 20); // determines width
            this._beforeFirstInputFieldEditSW.reset();
            disposeOnDone.add((0, lifecycle_1.toDisposable)(() => {
                this._renameCts = undefined;
                cts.dispose(true);
            })); // @ulugbekna: this may result in `this.cancelInput` being called twice, but it should be safe since we set it to undefined after 1st call
            disposeOnDone.add((0, lifecycle_1.toDisposable)(() => {
                if (this._renameCandidateProvidersCts !== undefined) {
                    this._renameCandidateProvidersCts.dispose(true);
                    this._renameCandidateProvidersCts = undefined;
                }
            }));
            disposeOnDone.add((0, lifecycle_1.toDisposable)(() => this._candidates.clear()));
            const inputResult = new async_1.DeferredPromise();
            inputResult.p.finally(() => {
                disposeOnDone.dispose();
                this._hide();
            });
            this._currentCancelInput = (focusEditor) => {
                this._trace('invoking _currentCancelInput');
                this._currentAcceptInput = undefined;
                this._currentCancelInput = undefined;
                // fixme session cleanup
                this._renameCandidateListView?.clearCandidates();
                inputResult.complete(focusEditor);
                return true;
            };
            this._currentAcceptInput = (wantsPreview) => {
                this._trace('invoking _currentAcceptInput');
                (0, types_1.assertType)(this._renameCandidateListView !== undefined);
                const nRenameSuggestions = this._renameCandidateListView.nCandidates;
                let newName;
                let source;
                const focusedCandidate = this._renameCandidateListView.focusedCandidate;
                if (focusedCandidate !== undefined) {
                    this._trace('using new name from renameSuggestion');
                    newName = focusedCandidate;
                    source = { k: 'renameSuggestion' };
                }
                else {
                    this._trace('using new name from inputField');
                    newName = this._inputWithButton.input.value;
                    source = this._isEditingRenameCandidate ? { k: 'userEditedRenameSuggestion' } : { k: 'inputField' };
                }
                if (newName === currentName || newName.trim().length === 0 /* is just whitespace */) {
                    this.cancelInput(true, '_currentAcceptInput (because newName === value || newName.trim().length === 0)');
                    return;
                }
                this._currentAcceptInput = undefined;
                this._currentCancelInput = undefined;
                this._renameCandidateListView.clearCandidates();
                // fixme session cleanup
                inputResult.complete({
                    newName,
                    wantsPreview: supportPreview && wantsPreview,
                    stats: {
                        source,
                        nRenameSuggestions,
                        timeBeforeFirstInputFieldEdit: this._timeBeforeFirstInputFieldEdit,
                        nRenameSuggestionsInvocations: this._nRenameSuggestionsInvocations,
                        hadAutomaticRenameSuggestionsInvocation: this._hadAutomaticRenameSuggestionsInvocation,
                    }
                });
            };
            disposeOnDone.add(cts.token.onCancellationRequested(() => this.cancelInput(true, 'cts.token.onCancellationRequested')));
            if (!_sticky) {
                disposeOnDone.add(this._editor.onDidBlurEditorWidget(() => this.cancelInput(!this._domNode?.ownerDocument.hasFocus(), 'editor.onDidBlurEditorWidget')));
            }
            this._show();
            return inputResult.p;
        }
        _requestRenameCandidates(currentName, isManuallyTriggered) {
            if (this._requestRenameCandidatesOnce === undefined) {
                return;
            }
            if (this._renameCandidateProvidersCts !== undefined) {
                this._renameCandidateProvidersCts.dispose(true);
            }
            (0, types_1.assertType)(this._renameCts);
            if (this._inputWithButton.buttonState !== 'stop') {
                this._renameCandidateProvidersCts = new cancellation_1.CancellationTokenSource();
                const triggerKind = isManuallyTriggered ? languages_1.NewSymbolNameTriggerKind.Invoke : languages_1.NewSymbolNameTriggerKind.Automatic;
                const candidates = this._requestRenameCandidatesOnce(triggerKind, this._renameCandidateProvidersCts.token);
                if (candidates.length === 0) {
                    this._inputWithButton.setSparkleButton();
                    return;
                }
                if (!isManuallyTriggered) {
                    this._hadAutomaticRenameSuggestionsInvocation = true;
                }
                this._nRenameSuggestionsInvocations += 1;
                this._inputWithButton.setStopButton();
                this._updateRenameCandidates(candidates, currentName, this._renameCts.token);
            }
        }
        /**
         * This allows selecting only part of the symbol name in the input field based on the selection in the editor
         */
        _getSelection(where, currentName) {
            (0, types_1.assertType)(this._editor.hasModel());
            const selection = this._editor.getSelection();
            let start = 0;
            let end = currentName.length;
            if (!range_1.Range.isEmpty(selection) && !range_1.Range.spansMultipleLines(selection) && range_1.Range.containsRange(where, selection)) {
                start = Math.max(0, selection.startColumn - where.startColumn);
                end = Math.min(where.endColumn, selection.endColumn) - where.startColumn;
            }
            return { start, end };
        }
        _show() {
            this._trace('invoking _show');
            this._editor.revealLineInCenterIfOutsideViewport(this._position.lineNumber, 0 /* ScrollType.Smooth */);
            this._visible = true;
            this._visibleContextKey.set(true);
            this._editor.layoutContentWidget(this);
            // TODO@ulugbekna: could this be simply run in `afterRender`?
            setTimeout(() => {
                this._inputWithButton.input.focus();
                this._inputWithButton.input.setSelectionRange(parseInt(this._inputWithButton.input.getAttribute('selectionStart')), parseInt(this._inputWithButton.input.getAttribute('selectionEnd')));
            }, 100);
        }
        async _updateRenameCandidates(candidates, currentName, token) {
            const trace = (...args) => this._trace('_updateRenameCandidates', ...args);
            trace('start');
            const namesListResults = await (0, async_1.raceCancellation)(Promise.allSettled(candidates), token);
            this._inputWithButton.setSparkleButton();
            if (namesListResults === undefined) {
                trace('returning early - received updateRenameCandidates results - undefined');
                return;
            }
            const newNames = namesListResults.flatMap(namesListResult => namesListResult.status === 'fulfilled' && (0, types_1.isDefined)(namesListResult.value)
                ? namesListResult.value
                : []);
            trace(`received updateRenameCandidates results - total (unfiltered) ${newNames.length} candidates.`);
            // deduplicate and filter out the current value
            const distinctNames = arrays.distinct(newNames, v => v.newSymbolName);
            trace(`distinct candidates - ${distinctNames.length} candidates.`);
            const validDistinctNames = distinctNames.filter(({ newSymbolName }) => newSymbolName.trim().length > 0 && newSymbolName !== this._inputWithButton.input.value && newSymbolName !== currentName && !this._candidates.has(newSymbolName));
            trace(`valid distinct candidates - ${newNames.length} candidates.`);
            validDistinctNames.forEach(n => this._candidates.add(n.newSymbolName));
            if (validDistinctNames.length < 1) {
                trace('returning early - no valid distinct candidates');
                return;
            }
            // show the candidates
            trace('setting candidates');
            this._renameCandidateListView.setCandidates(validDistinctNames);
            // ask editor to re-layout given that the widget is now of a different size after rendering rename candidates
            trace('asking editor to re-layout');
            this._editor.layoutContentWidget(this);
        }
        _hide() {
            this._trace('invoked _hide');
            this._visible = false;
            this._visibleContextKey.reset();
            this._editor.layoutContentWidget(this);
        }
        _getTopForPosition() {
            const visibleRanges = this._editor.getVisibleRanges();
            let firstLineInViewport;
            if (visibleRanges.length > 0) {
                firstLineInViewport = visibleRanges[0].startLineNumber;
            }
            else {
                this._logService.warn('RenameWidget#_getTopForPosition: this should not happen - visibleRanges is empty');
                firstLineInViewport = Math.max(1, this._position.lineNumber - 5); // @ulugbekna: fallback to current line minus 5
            }
            return this._editor.getTopForLineNumber(this._position.lineNumber) - this._editor.getTopForLineNumber(firstLineInViewport);
        }
        _trace(...args) {
            this._logService.trace('RenameWidget', ...args);
        }
    };
    exports.RenameWidget = RenameWidget;
    exports.RenameWidget = RenameWidget = __decorate([
        __param(2, themeService_1.IThemeService),
        __param(3, keybinding_1.IKeybindingService),
        __param(4, contextkey_1.IContextKeyService),
        __param(5, log_1.ILogService)
    ], RenameWidget);
    class RenameCandidateListView {
        // FIXME@ulugbekna: rewrite using event emitters
        constructor(parent, opts) {
            this._disposables = new lifecycle_1.DisposableStore();
            this._availableHeight = 0;
            this._minimumWidth = 0;
            this._lineHeight = opts.fontInfo.lineHeight;
            this._typicalHalfwidthCharacterWidth = opts.fontInfo.typicalHalfwidthCharacterWidth;
            this._listContainer = document.createElement('div');
            this._listContainer.className = 'rename-box rename-candidate-list-container';
            parent.appendChild(this._listContainer);
            this._listWidget = RenameCandidateListView._createListWidget(this._listContainer, this._candidateViewHeight, opts.fontInfo);
            this._listWidget.onDidChangeFocus(e => {
                if (e.elements.length === 1) {
                    opts.onFocusChange(e.elements[0].newSymbolName);
                }
            }, this._disposables);
            this._listWidget.onDidChangeSelection(e => {
                if (e.elements.length === 1) {
                    opts.onSelectionChange();
                }
            }, this._disposables);
            this._disposables.add(this._listWidget.onDidBlur(e => {
                this._listWidget.setFocus([]);
            }));
            this._listWidget.style((0, defaultStyles_1.getListStyles)({
                listInactiveFocusForeground: colorRegistry_1.quickInputListFocusForeground,
                listInactiveFocusBackground: colorRegistry_1.quickInputListFocusBackground,
            }));
        }
        dispose() {
            this._listWidget.dispose();
            this._disposables.dispose();
        }
        // height - max height allowed by parent element
        layout({ height, width }) {
            this._availableHeight = height;
            this._minimumWidth = width;
        }
        setCandidates(candidates) {
            // insert candidates into list widget
            this._listWidget.splice(0, 0, candidates);
            // adjust list widget layout
            const height = this._pickListHeight(this._listWidget.length);
            const width = this._pickListWidth(candidates);
            this._listWidget.layout(height, width);
            // adjust list container layout
            this._listContainer.style.height = `${height}px`;
            this._listContainer.style.width = `${width}px`;
            aria.status(nls.localize(1249, "Received {0} rename suggestions", candidates.length));
        }
        clearCandidates() {
            this._listContainer.style.height = '0px';
            this._listContainer.style.width = '0px';
            this._listWidget.splice(0, this._listWidget.length, []);
        }
        get nCandidates() {
            return this._listWidget.length;
        }
        get focusedCandidate() {
            if (this._listWidget.length === 0) {
                return;
            }
            const selectedElement = this._listWidget.getSelectedElements()[0];
            if (selectedElement !== undefined) {
                return selectedElement.newSymbolName;
            }
            const focusedElement = this._listWidget.getFocusedElements()[0];
            if (focusedElement !== undefined) {
                return focusedElement.newSymbolName;
            }
            return;
        }
        focusNext() {
            if (this._listWidget.length === 0) {
                return false;
            }
            const focusedIxs = this._listWidget.getFocus();
            if (focusedIxs.length === 0) {
                this._listWidget.focusFirst();
                this._listWidget.reveal(0);
                return true;
            }
            else {
                if (focusedIxs[0] === this._listWidget.length - 1) {
                    this._listWidget.setFocus([]);
                    this._listWidget.reveal(0); // @ulugbekna: without this, it seems like focused element is obstructed
                    return false;
                }
                else {
                    this._listWidget.focusNext();
                    const focused = this._listWidget.getFocus()[0];
                    this._listWidget.reveal(focused);
                    return true;
                }
            }
        }
        /**
         * @returns true if focus is moved to previous element
         */
        focusPrevious() {
            if (this._listWidget.length === 0) {
                return false;
            }
            const focusedIxs = this._listWidget.getFocus();
            if (focusedIxs.length === 0) {
                this._listWidget.focusLast();
                const focused = this._listWidget.getFocus()[0];
                this._listWidget.reveal(focused);
                return true;
            }
            else {
                if (focusedIxs[0] === 0) {
                    this._listWidget.setFocus([]);
                    return false;
                }
                else {
                    this._listWidget.focusPrevious();
                    const focused = this._listWidget.getFocus()[0];
                    this._listWidget.reveal(focused);
                    return true;
                }
            }
        }
        clearFocus() {
            this._listWidget.setFocus([]);
        }
        get _candidateViewHeight() {
            const { totalHeight } = RenameCandidateView.getLayoutInfo({ lineHeight: this._lineHeight });
            return totalHeight;
        }
        _pickListHeight(nCandidates) {
            const heightToFitAllCandidates = this._candidateViewHeight * nCandidates;
            const MAX_N_CANDIDATES = 7; // @ulugbekna: max # of candidates we want to show at once
            const height = Math.min(heightToFitAllCandidates, this._availableHeight, this._candidateViewHeight * MAX_N_CANDIDATES);
            return height;
        }
        _pickListWidth(candidates) {
            const longestCandidateWidth = Math.ceil(Math.max(...candidates.map(c => c.newSymbolName.length)) * this._typicalHalfwidthCharacterWidth);
            const width = Math.max(this._minimumWidth, 4 /* padding */ + 16 /* sparkle icon */ + 5 /* margin-left */ + longestCandidateWidth + 10 /* (possibly visible) scrollbar width */ // TODO@ulugbekna: approximate calc - clean this up
            );
            return width;
        }
        static _createListWidget(container, candidateViewHeight, fontInfo) {
            const virtualDelegate = new class {
                getTemplateId(element) {
                    return 'candidate';
                }
                getHeight(element) {
                    return candidateViewHeight;
                }
            };
            const renderer = new class {
                constructor() {
                    this.templateId = 'candidate';
                }
                renderTemplate(container) {
                    return new RenameCandidateView(container, fontInfo);
                }
                renderElement(candidate, index, templateData) {
                    templateData.populate(candidate);
                }
                disposeTemplate(templateData) {
                    templateData.dispose();
                }
            };
            return new listWidget_1.List('NewSymbolNameCandidates', container, virtualDelegate, [renderer], {
                keyboardSupport: false, // @ulugbekna: because we handle keyboard events through proper commands & keybinding service, see `rename.ts`
                mouseSupport: true,
                multipleSelectionSupport: false,
            });
        }
    }
    class InputWithButton {
        constructor() {
            this._onDidInputChange = new event_1.Emitter();
            this.onDidInputChange = this._onDidInputChange.event;
            this._disposables = new lifecycle_1.DisposableStore();
        }
        get domNode() {
            if (!this._domNode) {
                this._domNode = document.createElement('div');
                this._domNode.className = 'rename-input-with-button';
                this._domNode.style.display = 'flex';
                this._domNode.style.flexDirection = 'row';
                this._domNode.style.alignItems = 'center';
                this._inputNode = document.createElement('input');
                this._inputNode.className = 'rename-input';
                this._inputNode.type = 'text';
                this._inputNode.style.border = 'none';
                this._inputNode.setAttribute('aria-label', nls.localize(1250, "Rename input. Type new name and press Enter to commit."));
                this._domNode.appendChild(this._inputNode);
                this._buttonNode = document.createElement('div');
                this._buttonNode.className = 'rename-suggestions-button';
                this._buttonNode.setAttribute('tabindex', '0');
                this._buttonGenHoverText = nls.localize(1251, "Generate new name suggestions");
                this._buttonCancelHoverText = nls.localize(1252, "Cancel");
                this._buttonHover = (0, hoverDelegate2_1.getBaseLayerHoverDelegate)().setupManagedHover((0, hoverDelegateFactory_1.getDefaultHoverDelegate)('element'), this._buttonNode, this._buttonGenHoverText);
                this._disposables.add(this._buttonHover);
                this._domNode.appendChild(this._buttonNode);
                // notify if selection changes to cancel request to rename-suggestion providers
                this._disposables.add(dom.addDisposableListener(this.input, dom.EventType.INPUT, () => this._onDidInputChange.fire()));
                this._disposables.add(dom.addDisposableListener(this.input, dom.EventType.KEY_DOWN, (e) => {
                    const keyEvent = new keyboardEvent_1.StandardKeyboardEvent(e);
                    if (keyEvent.keyCode === 15 /* KeyCode.LeftArrow */ || keyEvent.keyCode === 17 /* KeyCode.RightArrow */) {
                        this._onDidInputChange.fire();
                    }
                }));
                this._disposables.add(dom.addDisposableListener(this.input, dom.EventType.CLICK, () => this._onDidInputChange.fire()));
                // focus "container" border instead of input box
                this._disposables.add(dom.addDisposableListener(this.input, dom.EventType.FOCUS, () => {
                    this.domNode.style.outlineWidth = '1px';
                    this.domNode.style.outlineStyle = 'solid';
                    this.domNode.style.outlineOffset = '-1px';
                    this.domNode.style.outlineColor = 'var(--vscode-focusBorder)';
                }));
                this._disposables.add(dom.addDisposableListener(this.input, dom.EventType.BLUR, () => {
                    this.domNode.style.outline = 'none';
                }));
            }
            return this._domNode;
        }
        get input() {
            (0, types_1.assertType)(this._inputNode);
            return this._inputNode;
        }
        get button() {
            (0, types_1.assertType)(this._buttonNode);
            return this._buttonNode;
        }
        get buttonState() {
            return this._buttonState;
        }
        setSparkleButton() {
            this._buttonState = 'sparkle';
            this._sparkleIcon ??= (0, iconLabels_1.renderIcon)(codicons_1.Codicon.sparkle);
            dom.clearNode(this.button);
            this.button.appendChild(this._sparkleIcon);
            this.button.setAttribute('aria-label', 'Generating new name suggestions');
            this._buttonHover?.update(this._buttonGenHoverText);
            this.input.focus();
        }
        setStopButton() {
            this._buttonState = 'stop';
            this._stopIcon ??= (0, iconLabels_1.renderIcon)(codicons_1.Codicon.primitiveSquare);
            dom.clearNode(this.button);
            this.button.appendChild(this._stopIcon);
            this.button.setAttribute('aria-label', 'Cancel generating new name suggestions');
            this._buttonHover?.update(this._buttonCancelHoverText);
            this.input.focus();
        }
        dispose() {
            this._disposables.dispose();
        }
    }
    class RenameCandidateView {
        static { this._PADDING = 2; }
        constructor(parent, fontInfo) {
            this._domNode = document.createElement('div');
            this._domNode.className = 'rename-box rename-candidate';
            this._domNode.style.display = `flex`;
            this._domNode.style.columnGap = `5px`;
            this._domNode.style.alignItems = `center`;
            this._domNode.style.height = `${fontInfo.lineHeight}px`;
            this._domNode.style.padding = `${RenameCandidateView._PADDING}px`;
            // @ulugbekna: needed to keep space when the `icon.style.display` is set to `none`
            const iconContainer = document.createElement('div');
            iconContainer.style.display = `flex`;
            iconContainer.style.alignItems = `center`;
            iconContainer.style.width = iconContainer.style.height = `${fontInfo.lineHeight * 0.8}px`;
            this._domNode.appendChild(iconContainer);
            this._icon = (0, iconLabels_1.renderIcon)(codicons_1.Codicon.sparkle);
            this._icon.style.display = `none`;
            iconContainer.appendChild(this._icon);
            this._label = document.createElement('div');
            domFontInfo.applyFontInfo(this._label, fontInfo);
            this._domNode.appendChild(this._label);
            parent.appendChild(this._domNode);
        }
        populate(value) {
            this._updateIcon(value);
            this._updateLabel(value);
        }
        _updateIcon(value) {
            const isAIGenerated = !!value.tags?.includes(languages_1.NewSymbolNameTag.AIGenerated);
            this._icon.style.display = isAIGenerated ? 'inherit' : 'none';
        }
        _updateLabel(value) {
            this._label.innerText = value.newSymbolName;
        }
        static getLayoutInfo({ lineHeight }) {
            const totalHeight = lineHeight + RenameCandidateView._PADDING * 2 /* top & bottom padding */;
            return { totalHeight };
        }
        dispose() {
        }
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[790/*vs/editor/contrib/rename/browser/rename*/], __M([1/*require*/,0/*exports*/,46/*vs/base/browser/ui/aria/aria*/,14/*vs/base/common/async*/,18/*vs/base/common/cancellation*/,8/*vs/base/common/errors*/,57/*vs/base/common/htmlContent*/,2/*vs/base/common/lifecycle*/,19/*vs/base/common/types*/,22/*vs/base/common/uri*/,15/*vs/editor/browser/editorExtensions*/,152/*vs/editor/browser/services/bulkEditService*/,34/*vs/editor/browser/services/codeEditorService*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/,20/*vs/editor/common/editorContextKeys*/,27/*vs/editor/common/languages*/,17/*vs/editor/common/services/languageFeatures*/,211/*vs/editor/common/services/textResourceConfiguration*/,122/*vs/editor/contrib/editorState/browser/editorState*/,184/*vs/editor/contrib/message/browser/messageController*/,3/*vs/nls*/,29/*vs/platform/actions/common/actions*/,109/*vs/platform/configuration/common/configurationRegistry*/,12/*vs/platform/contextkey/common/contextkey*/,7/*vs/platform/instantiation/common/instantiation*/,62/*vs/platform/log/common/log*/,50/*vs/platform/notification/common/notification*/,96/*vs/platform/progress/common/progress*/,38/*vs/platform/registry/common/platform*/,63/*vs/platform/telemetry/common/telemetry*/,789/*vs/editor/contrib/rename/browser/renameWidget*/]), function (require, exports, aria_1, async_1, cancellation_1, errors_1, htmlContent_1, lifecycle_1, types_1, uri_1, editorExtensions_1, bulkEditService_1, codeEditorService_1, position_1, range_1, editorContextKeys_1, languages_1, languageFeatures_1, textResourceConfiguration_1, editorState_1, messageController_1, nls, actions_1, configurationRegistry_1, contextkey_1, instantiation_1, log_1, notification_1, progress_1, platform_1, telemetry_1, renameWidget_1) {
    "use strict";
    var RenameController_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.RenameAction = void 0;
    exports.rename = rename;
    class RenameSkeleton {
        constructor(model, position, registry) {
            this.model = model;
            this.position = position;
            this._providerRenameIdx = 0;
            this._providers = registry.ordered(model);
        }
        hasProvider() {
            return this._providers.length > 0;
        }
        async resolveRenameLocation(token) {
            const rejects = [];
            for (this._providerRenameIdx = 0; this._providerRenameIdx < this._providers.length; this._providerRenameIdx++) {
                const provider = this._providers[this._providerRenameIdx];
                if (!provider.resolveRenameLocation) {
                    break;
                }
                const res = await provider.resolveRenameLocation(this.model, this.position, token);
                if (!res) {
                    continue;
                }
                if (res.rejectReason) {
                    rejects.push(res.rejectReason);
                    continue;
                }
                return res;
            }
            // we are here when no provider prepared a location which means we can
            // just rely on the word under cursor and start with the first provider
            this._providerRenameIdx = 0;
            const word = this.model.getWordAtPosition(this.position);
            if (!word) {
                return {
                    range: range_1.Range.fromPositions(this.position),
                    text: '',
                    rejectReason: rejects.length > 0 ? rejects.join('\n') : undefined
                };
            }
            return {
                range: new range_1.Range(this.position.lineNumber, word.startColumn, this.position.lineNumber, word.endColumn),
                text: word.word,
                rejectReason: rejects.length > 0 ? rejects.join('\n') : undefined
            };
        }
        async provideRenameEdits(newName, token) {
            return this._provideRenameEdits(newName, this._providerRenameIdx, [], token);
        }
        async _provideRenameEdits(newName, i, rejects, token) {
            const provider = this._providers[i];
            if (!provider) {
                return {
                    edits: [],
                    rejectReason: rejects.join('\n')
                };
            }
            const result = await provider.provideRenameEdits(this.model, this.position, newName, token);
            if (!result) {
                return this._provideRenameEdits(newName, i + 1, rejects.concat(nls.localize(1235, "No result.")), token);
            }
            else if (result.rejectReason) {
                return this._provideRenameEdits(newName, i + 1, rejects.concat(result.rejectReason), token);
            }
            return result;
        }
    }
    async function rename(registry, model, position, newName) {
        const skeleton = new RenameSkeleton(model, position, registry);
        const loc = await skeleton.resolveRenameLocation(cancellation_1.CancellationToken.None);
        if (loc?.rejectReason) {
            return { edits: [], rejectReason: loc.rejectReason };
        }
        return skeleton.provideRenameEdits(newName, cancellation_1.CancellationToken.None);
    }
    // ---  register actions and commands
    let RenameController = class RenameController {
        static { RenameController_1 = this; }
        static { this.ID = 'editor.contrib.renameController'; }
        static get(editor) {
            return editor.getContribution(RenameController_1.ID);
        }
        constructor(editor, _instaService, _notificationService, _bulkEditService, _progressService, _logService, _configService, _languageFeaturesService, _telemetryService) {
            this.editor = editor;
            this._instaService = _instaService;
            this._notificationService = _notificationService;
            this._bulkEditService = _bulkEditService;
            this._progressService = _progressService;
            this._logService = _logService;
            this._configService = _configService;
            this._languageFeaturesService = _languageFeaturesService;
            this._telemetryService = _telemetryService;
            this._disposableStore = new lifecycle_1.DisposableStore();
            this._cts = new cancellation_1.CancellationTokenSource();
            this._renameWidget = this._disposableStore.add(this._instaService.createInstance(renameWidget_1.RenameWidget, this.editor, ['acceptRenameInput', 'acceptRenameInputWithPreview']));
        }
        dispose() {
            this._disposableStore.dispose();
            this._cts.dispose(true);
        }
        async run() {
            const trace = this._logService.trace.bind(this._logService, '[rename]');
            // set up cancellation token to prevent reentrant rename, this
            // is the parent to the resolve- and rename-tokens
            this._cts.dispose(true);
            this._cts = new cancellation_1.CancellationTokenSource();
            if (!this.editor.hasModel()) {
                trace('editor has no model');
                return undefined;
            }
            const position = this.editor.getPosition();
            const skeleton = new RenameSkeleton(this.editor.getModel(), position, this._languageFeaturesService.renameProvider);
            if (!skeleton.hasProvider()) {
                trace('skeleton has no provider');
                return undefined;
            }
            // part 1 - resolve rename location
            const cts1 = new editorState_1.EditorStateCancellationTokenSource(this.editor, 4 /* CodeEditorStateFlag.Position */ | 1 /* CodeEditorStateFlag.Value */, undefined, this._cts.token);
            let loc;
            try {
                trace('resolving rename location');
                const resolveLocationOperation = skeleton.resolveRenameLocation(cts1.token);
                this._progressService.showWhile(resolveLocationOperation, 250);
                loc = await resolveLocationOperation;
                trace('resolved rename location');
            }
            catch (e) {
                if (e instanceof errors_1.CancellationError) {
                    trace('resolve rename location cancelled', JSON.stringify(e, null, '\t'));
                }
                else {
                    trace('resolve rename location failed', e instanceof Error ? e : JSON.stringify(e, null, '\t'));
                    if (typeof e === 'string' || (0, htmlContent_1.isMarkdownString)(e)) {
                        messageController_1.MessageController.get(this.editor)?.showMessage(e || nls.localize(1236, "An unknown error occurred while resolving rename location"), position);
                    }
                }
                return undefined;
            }
            finally {
                cts1.dispose();
            }
            if (!loc) {
                trace('returning early - no loc');
                return undefined;
            }
            if (loc.rejectReason) {
                trace(`returning early - rejected with reason: ${loc.rejectReason}`, loc.rejectReason);
                messageController_1.MessageController.get(this.editor)?.showMessage(loc.rejectReason, position);
                return undefined;
            }
            if (cts1.token.isCancellationRequested) {
                trace('returning early - cts1 cancelled');
                return undefined;
            }
            // part 2 - do rename at location
            const cts2 = new editorState_1.EditorStateCancellationTokenSource(this.editor, 4 /* CodeEditorStateFlag.Position */ | 1 /* CodeEditorStateFlag.Value */, loc.range, this._cts.token);
            const model = this.editor.getModel(); // @ulugbekna: assumes editor still has a model, otherwise, cts1 should've been cancelled
            const newSymbolNamesProviders = this._languageFeaturesService.newSymbolNamesProvider.all(model);
            const resolvedNewSymbolnamesProviders = await Promise.all(newSymbolNamesProviders.map(async (p) => [p, await p.supportsAutomaticNewSymbolNamesTriggerKind ?? false]));
            const requestRenameSuggestions = (triggerKind, cts) => {
                let providers = resolvedNewSymbolnamesProviders.slice();
                if (triggerKind === languages_1.NewSymbolNameTriggerKind.Automatic) {
                    providers = providers.filter(([_, supportsAutomatic]) => supportsAutomatic);
                }
                return providers.map(([p,]) => p.provideNewSymbolNames(model, loc.range, triggerKind, cts));
            };
            trace('creating rename input field and awaiting its result');
            const supportPreview = this._bulkEditService.hasPreviewHandler() && this._configService.getValue(this.editor.getModel().uri, 'editor.rename.enablePreview');
            const inputFieldResult = await this._renameWidget.getInput(loc.range, loc.text, supportPreview, newSymbolNamesProviders.length > 0 ? requestRenameSuggestions : undefined, cts2);
            trace('received response from rename input field');
            if (newSymbolNamesProviders.length > 0) { // @ulugbekna: we're interested only in telemetry for rename suggestions currently
                this._reportTelemetry(newSymbolNamesProviders.length, model.getLanguageId(), inputFieldResult);
            }
            // no result, only hint to focus the editor or not
            if (typeof inputFieldResult === 'boolean') {
                trace(`returning early - rename input field response - ${inputFieldResult}`);
                if (inputFieldResult) {
                    this.editor.focus();
                }
                cts2.dispose();
                return undefined;
            }
            this.editor.focus();
            trace('requesting rename edits');
            const renameOperation = (0, async_1.raceCancellation)(skeleton.provideRenameEdits(inputFieldResult.newName, cts2.token), cts2.token).then(async (renameResult) => {
                if (!renameResult) {
                    trace('returning early - no rename edits result');
                    return;
                }
                if (!this.editor.hasModel()) {
                    trace('returning early - no model after rename edits are provided');
                    return;
                }
                if (renameResult.rejectReason) {
                    trace(`returning early - rejected with reason: ${renameResult.rejectReason}`);
                    this._notificationService.info(renameResult.rejectReason);
                    return;
                }
                // collapse selection to active end
                this.editor.setSelection(range_1.Range.fromPositions(this.editor.getSelection().getPosition()));
                trace('applying edits');
                this._bulkEditService.apply(renameResult, {
                    editor: this.editor,
                    showPreview: inputFieldResult.wantsPreview,
                    label: nls.localize(1237, "Renaming '{0}' to '{1}'", loc?.text, inputFieldResult.newName),
                    code: 'undoredo.rename',
                    quotableLabel: nls.localize(1238, "Renaming {0} to {1}", loc?.text, inputFieldResult.newName),
                    respectAutoSaveConfig: true
                }).then(result => {
                    trace('edits applied');
                    if (result.ariaSummary) {
                        (0, aria_1.alert)(nls.localize(1239, "Successfully renamed '{0}' to '{1}'. Summary: {2}", loc.text, inputFieldResult.newName, result.ariaSummary));
                    }
                }).catch(err => {
                    trace(`error when applying edits ${JSON.stringify(err, null, '\t')}`);
                    this._notificationService.error(nls.localize(1240, "Rename failed to apply edits"));
                    this._logService.error(err);
                });
            }, err => {
                trace('error when providing rename edits', JSON.stringify(err, null, '\t'));
                this._notificationService.error(nls.localize(1241, "Rename failed to compute edits"));
                this._logService.error(err);
            }).finally(() => {
                cts2.dispose();
            });
            trace('returning rename operation');
            this._progressService.showWhile(renameOperation, 250);
            return renameOperation;
        }
        acceptRenameInput(wantsPreview) {
            this._renameWidget.acceptInput(wantsPreview);
        }
        cancelRenameInput() {
            this._renameWidget.cancelInput(true, 'cancelRenameInput command');
        }
        focusNextRenameSuggestion() {
            this._renameWidget.focusNextRenameSuggestion();
        }
        focusPreviousRenameSuggestion() {
            this._renameWidget.focusPreviousRenameSuggestion();
        }
        _reportTelemetry(nRenameSuggestionProviders, languageId, inputFieldResult) {
            const value = typeof inputFieldResult === 'boolean'
                ? {
                    kind: 'cancelled',
                    languageId,
                    nRenameSuggestionProviders,
                }
                : {
                    kind: 'accepted',
                    languageId,
                    nRenameSuggestionProviders,
                    source: inputFieldResult.stats.source.k,
                    nRenameSuggestions: inputFieldResult.stats.nRenameSuggestions,
                    timeBeforeFirstInputFieldEdit: inputFieldResult.stats.timeBeforeFirstInputFieldEdit,
                    wantsPreview: inputFieldResult.wantsPreview,
                    nRenameSuggestionsInvocations: inputFieldResult.stats.nRenameSuggestionsInvocations,
                    hadAutomaticRenameSuggestionsInvocation: inputFieldResult.stats.hadAutomaticRenameSuggestionsInvocation,
                };
            this._telemetryService.publicLog2('renameInvokedEvent', value);
        }
    };
    RenameController = RenameController_1 = __decorate([
        __param(1, instantiation_1.IInstantiationService),
        __param(2, notification_1.INotificationService),
        __param(3, bulkEditService_1.IBulkEditService),
        __param(4, progress_1.IEditorProgressService),
        __param(5, log_1.ILogService),
        __param(6, textResourceConfiguration_1.ITextResourceConfigurationService),
        __param(7, languageFeatures_1.ILanguageFeaturesService),
        __param(8, telemetry_1.ITelemetryService)
    ], RenameController);
    // ---- action implementation
    class RenameAction extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: 'editor.action.rename',
                label: nls.localize(1242, "Rename Symbol"),
                alias: 'Rename Symbol',
                precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, editorContextKeys_1.EditorContextKeys.hasRenameProvider),
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    primary: 60 /* KeyCode.F2 */,
                    weight: 100 /* KeybindingWeight.EditorContrib */
                },
                contextMenuOpts: {
                    group: '1_modification',
                    order: 1.1
                }
            });
        }
        runCommand(accessor, args) {
            const editorService = accessor.get(codeEditorService_1.ICodeEditorService);
            const [uri, pos] = Array.isArray(args) && args || [undefined, undefined];
            if (uri_1.URI.isUri(uri) && position_1.Position.isIPosition(pos)) {
                return editorService.openCodeEditor({ resource: uri }, editorService.getActiveCodeEditor()).then(editor => {
                    if (!editor) {
                        return;
                    }
                    editor.setPosition(pos);
                    editor.invokeWithinContext(accessor => {
                        this.reportTelemetry(accessor, editor);
                        return this.run(accessor, editor);
                    });
                }, errors_1.onUnexpectedError);
            }
            return super.runCommand(accessor, args);
        }
        run(accessor, editor) {
            const logService = accessor.get(log_1.ILogService);
            const controller = RenameController.get(editor);
            if (controller) {
                logService.trace('[RenameAction] got controller, running...');
                return controller.run();
            }
            logService.trace('[RenameAction] returning early - controller missing');
            return Promise.resolve();
        }
    }
    exports.RenameAction = RenameAction;
    (0, editorExtensions_1.registerEditorContribution)(RenameController.ID, RenameController, 4 /* EditorContributionInstantiation.Lazy */);
    (0, editorExtensions_1.registerEditorAction)(RenameAction);
    const RenameCommand = editorExtensions_1.EditorCommand.bindToContribution(RenameController.get);
    (0, editorExtensions_1.registerEditorCommand)(new RenameCommand({
        id: 'acceptRenameInput',
        precondition: renameWidget_1.CONTEXT_RENAME_INPUT_VISIBLE,
        handler: x => x.acceptRenameInput(false),
        kbOpts: {
            weight: 100 /* KeybindingWeight.EditorContrib */ + 99,
            kbExpr: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.focus, contextkey_1.ContextKeyExpr.not('isComposing')),
            primary: 3 /* KeyCode.Enter */
        }
    }));
    (0, editorExtensions_1.registerEditorCommand)(new RenameCommand({
        id: 'acceptRenameInputWithPreview',
        precondition: contextkey_1.ContextKeyExpr.and(renameWidget_1.CONTEXT_RENAME_INPUT_VISIBLE, contextkey_1.ContextKeyExpr.has('config.editor.rename.enablePreview')),
        handler: x => x.acceptRenameInput(true),
        kbOpts: {
            weight: 100 /* KeybindingWeight.EditorContrib */ + 99,
            kbExpr: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.focus, contextkey_1.ContextKeyExpr.not('isComposing')),
            primary: 2048 /* KeyMod.CtrlCmd */ + 3 /* KeyCode.Enter */
        }
    }));
    (0, editorExtensions_1.registerEditorCommand)(new RenameCommand({
        id: 'cancelRenameInput',
        precondition: renameWidget_1.CONTEXT_RENAME_INPUT_VISIBLE,
        handler: x => x.cancelRenameInput(),
        kbOpts: {
            weight: 100 /* KeybindingWeight.EditorContrib */ + 99,
            kbExpr: editorContextKeys_1.EditorContextKeys.focus,
            primary: 9 /* KeyCode.Escape */,
            secondary: [1024 /* KeyMod.Shift */ | 9 /* KeyCode.Escape */]
        }
    }));
    (0, actions_1.registerAction2)(class FocusNextRenameSuggestion extends actions_1.Action2 {
        constructor() {
            super({
                id: 'focusNextRenameSuggestion',
                title: {
                    ...nls.localize2(1244, "Focus Next Rename Suggestion"),
                },
                precondition: renameWidget_1.CONTEXT_RENAME_INPUT_VISIBLE,
                keybinding: [
                    {
                        primary: 18 /* KeyCode.DownArrow */,
                        weight: 100 /* KeybindingWeight.EditorContrib */ + 99,
                    }
                ]
            });
        }
        run(accessor) {
            const currentEditor = accessor.get(codeEditorService_1.ICodeEditorService).getFocusedCodeEditor();
            if (!currentEditor) {
                return;
            }
            const controller = RenameController.get(currentEditor);
            if (!controller) {
                return;
            }
            controller.focusNextRenameSuggestion();
        }
    });
    (0, actions_1.registerAction2)(class FocusPreviousRenameSuggestion extends actions_1.Action2 {
        constructor() {
            super({
                id: 'focusPreviousRenameSuggestion',
                title: {
                    ...nls.localize2(1245, "Focus Previous Rename Suggestion"),
                },
                precondition: renameWidget_1.CONTEXT_RENAME_INPUT_VISIBLE,
                keybinding: [
                    {
                        primary: 16 /* KeyCode.UpArrow */,
                        weight: 100 /* KeybindingWeight.EditorContrib */ + 99,
                    }
                ]
            });
        }
        run(accessor) {
            const currentEditor = accessor.get(codeEditorService_1.ICodeEditorService).getFocusedCodeEditor();
            if (!currentEditor) {
                return;
            }
            const controller = RenameController.get(currentEditor);
            if (!controller) {
                return;
            }
            controller.focusPreviousRenameSuggestion();
        }
    });
    // ---- api bridge command
    (0, editorExtensions_1.registerModelAndPositionCommand)('_executeDocumentRenameProvider', function (accessor, model, position, ...args) {
        const [newName] = args;
        (0, types_1.assertType)(typeof newName === 'string');
        const { renameProvider } = accessor.get(languageFeatures_1.ILanguageFeaturesService);
        return rename(renameProvider, model, position, newName);
    });
    (0, editorExtensions_1.registerModelAndPositionCommand)('_executePrepareRename', async function (accessor, model, position) {
        const { renameProvider } = accessor.get(languageFeatures_1.ILanguageFeaturesService);
        const skeleton = new RenameSkeleton(model, position, renameProvider);
        const loc = await skeleton.resolveRenameLocation(cancellation_1.CancellationToken.None);
        if (loc?.rejectReason) {
            throw new Error(loc.rejectReason);
        }
        return loc;
    });
    //todo@jrieken use editor options world
    platform_1.Registry.as(configurationRegistry_1.Extensions.Configuration).registerConfiguration({
        id: 'editor',
        properties: {
            'editor.rename.enablePreview': {
                scope: 5 /* ConfigurationScope.LANGUAGE_OVERRIDABLE */,
                description: nls.localize(1243, "Enable/disable the ability to preview changes before renaming"),
                default: true,
                type: 'boolean'
            }
        }
    });
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[791/*vs/editor/contrib/semanticTokens/browser/documentSemanticTokens*/], __M([1/*require*/,0/*exports*/,2/*vs/base/common/lifecycle*/,8/*vs/base/common/errors*/,51/*vs/editor/common/services/model*/,28/*vs/platform/configuration/common/configuration*/,14/*vs/base/common/async*/,18/*vs/base/common/cancellation*/,25/*vs/platform/theme/common/themeService*/,282/*vs/editor/common/services/semanticTokensProviderStyling*/,387/*vs/editor/contrib/semanticTokens/common/getSemanticTokens*/,79/*vs/editor/common/services/languageFeatureDebounce*/,54/*vs/base/common/stopwatch*/,17/*vs/editor/common/services/languageFeatures*/,267/*vs/editor/common/services/semanticTokensStyling*/,130/*vs/editor/common/editorFeatures*/,339/*vs/editor/contrib/semanticTokens/common/semanticTokensConfig*/]), function (require, exports, lifecycle_1, errors, model_1, configuration_1, async_1, cancellation_1, themeService_1, semanticTokensProviderStyling_1, getSemanticTokens_1, languageFeatureDebounce_1, stopwatch_1, languageFeatures_1, semanticTokensStyling_1, editorFeatures_1, semanticTokensConfig_1) {
    "use strict";
    var ModelSemanticColoring_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DocumentSemanticTokensFeature = void 0;
    let DocumentSemanticTokensFeature = class DocumentSemanticTokensFeature extends lifecycle_1.Disposable {
        constructor(semanticTokensStylingService, modelService, themeService, configurationService, languageFeatureDebounceService, languageFeaturesService) {
            super();
            this._watchers = Object.create(null);
            const register = (model) => {
                this._watchers[model.uri.toString()] = new ModelSemanticColoring(model, semanticTokensStylingService, themeService, languageFeatureDebounceService, languageFeaturesService);
            };
            const deregister = (model, modelSemanticColoring) => {
                modelSemanticColoring.dispose();
                delete this._watchers[model.uri.toString()];
            };
            const handleSettingOrThemeChange = () => {
                for (const model of modelService.getModels()) {
                    const curr = this._watchers[model.uri.toString()];
                    if ((0, semanticTokensConfig_1.isSemanticColoringEnabled)(model, themeService, configurationService)) {
                        if (!curr) {
                            register(model);
                        }
                    }
                    else {
                        if (curr) {
                            deregister(model, curr);
                        }
                    }
                }
            };
            modelService.getModels().forEach(model => {
                if ((0, semanticTokensConfig_1.isSemanticColoringEnabled)(model, themeService, configurationService)) {
                    register(model);
                }
            });
            this._register(modelService.onModelAdded((model) => {
                if ((0, semanticTokensConfig_1.isSemanticColoringEnabled)(model, themeService, configurationService)) {
                    register(model);
                }
            }));
            this._register(modelService.onModelRemoved((model) => {
                const curr = this._watchers[model.uri.toString()];
                if (curr) {
                    deregister(model, curr);
                }
            }));
            this._register(configurationService.onDidChangeConfiguration(e => {
                if (e.affectsConfiguration(semanticTokensConfig_1.SEMANTIC_HIGHLIGHTING_SETTING_ID)) {
                    handleSettingOrThemeChange();
                }
            }));
            this._register(themeService.onDidColorThemeChange(handleSettingOrThemeChange));
        }
        dispose() {
            // Dispose all watchers
            for (const watcher of Object.values(this._watchers)) {
                watcher.dispose();
            }
            super.dispose();
        }
    };
    exports.DocumentSemanticTokensFeature = DocumentSemanticTokensFeature;
    exports.DocumentSemanticTokensFeature = DocumentSemanticTokensFeature = __decorate([
        __param(0, semanticTokensStyling_1.ISemanticTokensStylingService),
        __param(1, model_1.IModelService),
        __param(2, themeService_1.IThemeService),
        __param(3, configuration_1.IConfigurationService),
        __param(4, languageFeatureDebounce_1.ILanguageFeatureDebounceService),
        __param(5, languageFeatures_1.ILanguageFeaturesService)
    ], DocumentSemanticTokensFeature);
    let ModelSemanticColoring = class ModelSemanticColoring extends lifecycle_1.Disposable {
        static { ModelSemanticColoring_1 = this; }
        static { this.REQUEST_MIN_DELAY = 300; }
        static { this.REQUEST_MAX_DELAY = 2000; }
        constructor(model, _semanticTokensStylingService, themeService, languageFeatureDebounceService, languageFeaturesService) {
            super();
            this._semanticTokensStylingService = _semanticTokensStylingService;
            this._isDisposed = false;
            this._model = model;
            this._provider = languageFeaturesService.documentSemanticTokensProvider;
            this._debounceInformation = languageFeatureDebounceService.for(this._provider, 'DocumentSemanticTokens', { min: ModelSemanticColoring_1.REQUEST_MIN_DELAY, max: ModelSemanticColoring_1.REQUEST_MAX_DELAY });
            this._fetchDocumentSemanticTokens = this._register(new async_1.RunOnceScheduler(() => this._fetchDocumentSemanticTokensNow(), ModelSemanticColoring_1.REQUEST_MIN_DELAY));
            this._currentDocumentResponse = null;
            this._currentDocumentRequestCancellationTokenSource = null;
            this._documentProvidersChangeListeners = [];
            this._providersChangedDuringRequest = false;
            this._register(this._model.onDidChangeContent(() => {
                if (!this._fetchDocumentSemanticTokens.isScheduled()) {
                    this._fetchDocumentSemanticTokens.schedule(this._debounceInformation.get(this._model));
                }
            }));
            this._register(this._model.onDidChangeAttached(() => {
                if (!this._fetchDocumentSemanticTokens.isScheduled()) {
                    this._fetchDocumentSemanticTokens.schedule(this._debounceInformation.get(this._model));
                }
            }));
            this._register(this._model.onDidChangeLanguage(() => {
                // clear any outstanding state
                if (this._currentDocumentResponse) {
                    this._currentDocumentResponse.dispose();
                    this._currentDocumentResponse = null;
                }
                if (this._currentDocumentRequestCancellationTokenSource) {
                    this._currentDocumentRequestCancellationTokenSource.cancel();
                    this._currentDocumentRequestCancellationTokenSource = null;
                }
                this._setDocumentSemanticTokens(null, null, null, []);
                this._fetchDocumentSemanticTokens.schedule(0);
            }));
            const bindDocumentChangeListeners = () => {
                (0, lifecycle_1.dispose)(this._documentProvidersChangeListeners);
                this._documentProvidersChangeListeners = [];
                for (const provider of this._provider.all(model)) {
                    if (typeof provider.onDidChange === 'function') {
                        this._documentProvidersChangeListeners.push(provider.onDidChange(() => {
                            if (this._currentDocumentRequestCancellationTokenSource) {
                                // there is already a request running,
                                this._providersChangedDuringRequest = true;
                                return;
                            }
                            this._fetchDocumentSemanticTokens.schedule(0);
                        }));
                    }
                }
            };
            bindDocumentChangeListeners();
            this._register(this._provider.onDidChange(() => {
                bindDocumentChangeListeners();
                this._fetchDocumentSemanticTokens.schedule(this._debounceInformation.get(this._model));
            }));
            this._register(themeService.onDidColorThemeChange(_ => {
                // clear out existing tokens
                this._setDocumentSemanticTokens(null, null, null, []);
                this._fetchDocumentSemanticTokens.schedule(this._debounceInformation.get(this._model));
            }));
            this._fetchDocumentSemanticTokens.schedule(0);
        }
        dispose() {
            if (this._currentDocumentResponse) {
                this._currentDocumentResponse.dispose();
                this._currentDocumentResponse = null;
            }
            if (this._currentDocumentRequestCancellationTokenSource) {
                this._currentDocumentRequestCancellationTokenSource.cancel();
                this._currentDocumentRequestCancellationTokenSource = null;
            }
            (0, lifecycle_1.dispose)(this._documentProvidersChangeListeners);
            this._documentProvidersChangeListeners = [];
            this._setDocumentSemanticTokens(null, null, null, []);
            this._isDisposed = true;
            super.dispose();
        }
        _fetchDocumentSemanticTokensNow() {
            if (this._currentDocumentRequestCancellationTokenSource) {
                // there is already a request running, let it finish...
                return;
            }
            if (!(0, getSemanticTokens_1.hasDocumentSemanticTokensProvider)(this._provider, this._model)) {
                // there is no provider
                if (this._currentDocumentResponse) {
                    // there are semantic tokens set
                    this._model.tokenization.setSemanticTokens(null, false);
                }
                return;
            }
            if (!this._model.isAttachedToEditor()) {
                // this document is not visible, there is no need to fetch semantic tokens for it
                return;
            }
            const cancellationTokenSource = new cancellation_1.CancellationTokenSource();
            const lastProvider = this._currentDocumentResponse ? this._currentDocumentResponse.provider : null;
            const lastResultId = this._currentDocumentResponse ? this._currentDocumentResponse.resultId || null : null;
            const request = (0, getSemanticTokens_1.getDocumentSemanticTokens)(this._provider, this._model, lastProvider, lastResultId, cancellationTokenSource.token);
            this._currentDocumentRequestCancellationTokenSource = cancellationTokenSource;
            this._providersChangedDuringRequest = false;
            const pendingChanges = [];
            const contentChangeListener = this._model.onDidChangeContent((e) => {
                pendingChanges.push(e);
            });
            const sw = new stopwatch_1.StopWatch(false);
            request.then((res) => {
                this._debounceInformation.update(this._model, sw.elapsed());
                this._currentDocumentRequestCancellationTokenSource = null;
                contentChangeListener.dispose();
                if (!res) {
                    this._setDocumentSemanticTokens(null, null, null, pendingChanges);
                }
                else {
                    const { provider, tokens } = res;
                    const styling = this._semanticTokensStylingService.getStyling(provider);
                    this._setDocumentSemanticTokens(provider, tokens || null, styling, pendingChanges);
                }
            }, (err) => {
                const isExpectedError = err && (errors.isCancellationError(err) || (typeof err.message === 'string' && err.message.indexOf('busy') !== -1));
                if (!isExpectedError) {
                    errors.onUnexpectedError(err);
                }
                // Semantic tokens eats up all errors and considers errors to mean that the result is temporarily not available
                // The API does not have a special error kind to express this...
                this._currentDocumentRequestCancellationTokenSource = null;
                contentChangeListener.dispose();
                if (pendingChanges.length > 0 || this._providersChangedDuringRequest) {
                    // More changes occurred while the request was running
                    if (!this._fetchDocumentSemanticTokens.isScheduled()) {
                        this._fetchDocumentSemanticTokens.schedule(this._debounceInformation.get(this._model));
                    }
                }
            });
        }
        static _copy(src, srcOffset, dest, destOffset, length) {
            // protect against overflows
            length = Math.min(length, dest.length - destOffset, src.length - srcOffset);
            for (let i = 0; i < length; i++) {
                dest[destOffset + i] = src[srcOffset + i];
            }
        }
        _setDocumentSemanticTokens(provider, tokens, styling, pendingChanges) {
            const currentResponse = this._currentDocumentResponse;
            const rescheduleIfNeeded = () => {
                if ((pendingChanges.length > 0 || this._providersChangedDuringRequest) && !this._fetchDocumentSemanticTokens.isScheduled()) {
                    this._fetchDocumentSemanticTokens.schedule(this._debounceInformation.get(this._model));
                }
            };
            if (this._currentDocumentResponse) {
                this._currentDocumentResponse.dispose();
                this._currentDocumentResponse = null;
            }
            if (this._isDisposed) {
                // disposed!
                if (provider && tokens) {
                    provider.releaseDocumentSemanticTokens(tokens.resultId);
                }
                return;
            }
            if (!provider || !styling) {
                this._model.tokenization.setSemanticTokens(null, false);
                return;
            }
            if (!tokens) {
                this._model.tokenization.setSemanticTokens(null, true);
                rescheduleIfNeeded();
                return;
            }
            if ((0, getSemanticTokens_1.isSemanticTokensEdits)(tokens)) {
                if (!currentResponse) {
                    // not possible!
                    this._model.tokenization.setSemanticTokens(null, true);
                    return;
                }
                if (tokens.edits.length === 0) {
                    // nothing to do!
                    tokens = {
                        resultId: tokens.resultId,
                        data: currentResponse.data
                    };
                }
                else {
                    let deltaLength = 0;
                    for (const edit of tokens.edits) {
                        deltaLength += (edit.data ? edit.data.length : 0) - edit.deleteCount;
                    }
                    const srcData = currentResponse.data;
                    const destData = new Uint32Array(srcData.length + deltaLength);
                    let srcLastStart = srcData.length;
                    let destLastStart = destData.length;
                    for (let i = tokens.edits.length - 1; i >= 0; i--) {
                        const edit = tokens.edits[i];
                        if (edit.start > srcData.length) {
                            styling.warnInvalidEditStart(currentResponse.resultId, tokens.resultId, i, edit.start, srcData.length);
                            // The edits are invalid and there's no way to recover
                            this._model.tokenization.setSemanticTokens(null, true);
                            return;
                        }
                        const copyCount = srcLastStart - (edit.start + edit.deleteCount);
                        if (copyCount > 0) {
                            ModelSemanticColoring_1._copy(srcData, srcLastStart - copyCount, destData, destLastStart - copyCount, copyCount);
                            destLastStart -= copyCount;
                        }
                        if (edit.data) {
                            ModelSemanticColoring_1._copy(edit.data, 0, destData, destLastStart - edit.data.length, edit.data.length);
                            destLastStart -= edit.data.length;
                        }
                        srcLastStart = edit.start;
                    }
                    if (srcLastStart > 0) {
                        ModelSemanticColoring_1._copy(srcData, 0, destData, 0, srcLastStart);
                    }
                    tokens = {
                        resultId: tokens.resultId,
                        data: destData
                    };
                }
            }
            if ((0, getSemanticTokens_1.isSemanticTokens)(tokens)) {
                this._currentDocumentResponse = new SemanticTokensResponse(provider, tokens.resultId, tokens.data);
                const result = (0, semanticTokensProviderStyling_1.toMultilineTokens2)(tokens, styling, this._model.getLanguageId());
                // Adjust incoming semantic tokens
                if (pendingChanges.length > 0) {
                    // More changes occurred while the request was running
                    // We need to:
                    // 1. Adjust incoming semantic tokens
                    // 2. Request them again
                    for (const change of pendingChanges) {
                        for (const area of result) {
                            for (const singleChange of change.changes) {
                                area.applyEdit(singleChange.range, singleChange.text);
                            }
                        }
                    }
                }
                this._model.tokenization.setSemanticTokens(result, true);
            }
            else {
                this._model.tokenization.setSemanticTokens(null, true);
            }
            rescheduleIfNeeded();
        }
    };
    ModelSemanticColoring = ModelSemanticColoring_1 = __decorate([
        __param(1, semanticTokensStyling_1.ISemanticTokensStylingService),
        __param(2, themeService_1.IThemeService),
        __param(3, languageFeatureDebounce_1.ILanguageFeatureDebounceService),
        __param(4, languageFeatures_1.ILanguageFeaturesService)
    ], ModelSemanticColoring);
    class SemanticTokensResponse {
        constructor(provider, resultId, data) {
            this.provider = provider;
            this.resultId = resultId;
            this.data = data;
        }
        dispose() {
            this.provider.releaseDocumentSemanticTokens(this.resultId);
        }
    }
    (0, editorFeatures_1.registerEditorFeature)(DocumentSemanticTokensFeature);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[792/*vs/editor/contrib/semanticTokens/browser/viewportSemanticTokens*/], __M([1/*require*/,0/*exports*/,14/*vs/base/common/async*/,2/*vs/base/common/lifecycle*/,15/*vs/editor/browser/editorExtensions*/,387/*vs/editor/contrib/semanticTokens/common/getSemanticTokens*/,339/*vs/editor/contrib/semanticTokens/common/semanticTokensConfig*/,282/*vs/editor/common/services/semanticTokensProviderStyling*/,28/*vs/platform/configuration/common/configuration*/,25/*vs/platform/theme/common/themeService*/,79/*vs/editor/common/services/languageFeatureDebounce*/,54/*vs/base/common/stopwatch*/,17/*vs/editor/common/services/languageFeatures*/,267/*vs/editor/common/services/semanticTokensStyling*/]), function (require, exports, async_1, lifecycle_1, editorExtensions_1, getSemanticTokens_1, semanticTokensConfig_1, semanticTokensProviderStyling_1, configuration_1, themeService_1, languageFeatureDebounce_1, stopwatch_1, languageFeatures_1, semanticTokensStyling_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ViewportSemanticTokensContribution = void 0;
    let ViewportSemanticTokensContribution = class ViewportSemanticTokensContribution extends lifecycle_1.Disposable {
        static { this.ID = 'editor.contrib.viewportSemanticTokens'; }
        constructor(editor, _semanticTokensStylingService, _themeService, _configurationService, languageFeatureDebounceService, languageFeaturesService) {
            super();
            this._semanticTokensStylingService = _semanticTokensStylingService;
            this._themeService = _themeService;
            this._configurationService = _configurationService;
            this._editor = editor;
            this._provider = languageFeaturesService.documentRangeSemanticTokensProvider;
            this._debounceInformation = languageFeatureDebounceService.for(this._provider, 'DocumentRangeSemanticTokens', { min: 100, max: 500 });
            this._tokenizeViewport = this._register(new async_1.RunOnceScheduler(() => this._tokenizeViewportNow(), 100));
            this._outstandingRequests = [];
            const scheduleTokenizeViewport = () => {
                if (this._editor.hasModel()) {
                    this._tokenizeViewport.schedule(this._debounceInformation.get(this._editor.getModel()));
                }
            };
            this._register(this._editor.onDidScrollChange(() => {
                scheduleTokenizeViewport();
            }));
            this._register(this._editor.onDidChangeModel(() => {
                this._cancelAll();
                scheduleTokenizeViewport();
            }));
            this._register(this._editor.onDidChangeModelContent((e) => {
                this._cancelAll();
                scheduleTokenizeViewport();
            }));
            this._register(this._provider.onDidChange(() => {
                this._cancelAll();
                scheduleTokenizeViewport();
            }));
            this._register(this._configurationService.onDidChangeConfiguration(e => {
                if (e.affectsConfiguration(semanticTokensConfig_1.SEMANTIC_HIGHLIGHTING_SETTING_ID)) {
                    this._cancelAll();
                    scheduleTokenizeViewport();
                }
            }));
            this._register(this._themeService.onDidColorThemeChange(() => {
                this._cancelAll();
                scheduleTokenizeViewport();
            }));
            scheduleTokenizeViewport();
        }
        _cancelAll() {
            for (const request of this._outstandingRequests) {
                request.cancel();
            }
            this._outstandingRequests = [];
        }
        _removeOutstandingRequest(req) {
            for (let i = 0, len = this._outstandingRequests.length; i < len; i++) {
                if (this._outstandingRequests[i] === req) {
                    this._outstandingRequests.splice(i, 1);
                    return;
                }
            }
        }
        _tokenizeViewportNow() {
            if (!this._editor.hasModel()) {
                return;
            }
            const model = this._editor.getModel();
            if (model.tokenization.hasCompleteSemanticTokens()) {
                return;
            }
            if (!(0, semanticTokensConfig_1.isSemanticColoringEnabled)(model, this._themeService, this._configurationService)) {
                if (model.tokenization.hasSomeSemanticTokens()) {
                    model.tokenization.setSemanticTokens(null, false);
                }
                return;
            }
            if (!(0, getSemanticTokens_1.hasDocumentRangeSemanticTokensProvider)(this._provider, model)) {
                if (model.tokenization.hasSomeSemanticTokens()) {
                    model.tokenization.setSemanticTokens(null, false);
                }
                return;
            }
            const visibleRanges = this._editor.getVisibleRangesPlusViewportAboveBelow();
            this._outstandingRequests = this._outstandingRequests.concat(visibleRanges.map(range => this._requestRange(model, range)));
        }
        _requestRange(model, range) {
            const requestVersionId = model.getVersionId();
            const request = (0, async_1.createCancelablePromise)(token => Promise.resolve((0, getSemanticTokens_1.getDocumentRangeSemanticTokens)(this._provider, model, range, token)));
            const sw = new stopwatch_1.StopWatch(false);
            request.then((r) => {
                this._debounceInformation.update(model, sw.elapsed());
                if (!r || !r.tokens || model.isDisposed() || model.getVersionId() !== requestVersionId) {
                    return;
                }
                const { provider, tokens: result } = r;
                const styling = this._semanticTokensStylingService.getStyling(provider);
                model.tokenization.setPartialSemanticTokens(range, (0, semanticTokensProviderStyling_1.toMultilineTokens2)(result, styling, model.getLanguageId()));
            }).then(() => this._removeOutstandingRequest(request), () => this._removeOutstandingRequest(request));
            return request;
        }
    };
    exports.ViewportSemanticTokensContribution = ViewportSemanticTokensContribution;
    exports.ViewportSemanticTokensContribution = ViewportSemanticTokensContribution = __decorate([
        __param(1, semanticTokensStyling_1.ISemanticTokensStylingService),
        __param(2, themeService_1.IThemeService),
        __param(3, configuration_1.IConfigurationService),
        __param(4, languageFeatureDebounce_1.ILanguageFeatureDebounceService),
        __param(5, languageFeatures_1.ILanguageFeaturesService)
    ], ViewportSemanticTokensContribution);
    (0, editorExtensions_1.registerEditorContribution)(ViewportSemanticTokensContribution.ID, ViewportSemanticTokensContribution, 1 /* EditorContributionInstantiation.AfterFirstRender */);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[793/*vs/editor/contrib/suggest/browser/suggestWidgetRenderer*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,254/*vs/base/browser/ui/iconLabel/iconLabel*/,26/*vs/base/common/codicons*/,30/*vs/base/common/themables*/,6/*vs/base/common/event*/,82/*vs/base/common/filters*/,2/*vs/base/common/lifecycle*/,22/*vs/base/common/uri*/,27/*vs/editor/common/languages*/,708/*vs/editor/common/services/getIconClasses*/,51/*vs/editor/common/services/model*/,43/*vs/editor/common/languages/language*/,3/*vs/nls*/,382/*vs/platform/files/common/files*/,71/*vs/platform/theme/common/iconRegistry*/,25/*vs/platform/theme/common/themeService*/,402/*vs/editor/contrib/suggest/browser/suggestWidgetDetails*/]), function (require, exports, dom_1, iconLabel_1, codicons_1, themables_1, event_1, filters_1, lifecycle_1, uri_1, languages_1, getIconClasses_1, model_1, language_1, nls, files_1, iconRegistry_1, themeService_1, suggestWidgetDetails_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ItemRenderer = void 0;
    exports.getAriaId = getAriaId;
    function getAriaId(index) {
        return `suggest-aria-id:${index}`;
    }
    const suggestMoreInfoIcon = (0, iconRegistry_1.registerIcon)('suggest-more-info', codicons_1.Codicon.chevronRight, nls.localize(1346, 'Icon for more information in the suggest widget.'));
    const _completionItemColor = new class ColorExtractor {
        static { this._regexRelaxed = /(#([\da-fA-F]{3}){1,2}|(rgb|hsl)a\(\s*(\d{1,3}%?\s*,\s*){3}(1|0?\.\d+)\)|(rgb|hsl)\(\s*\d{1,3}%?(\s*,\s*\d{1,3}%?){2}\s*\))/; }
        static { this._regexStrict = new RegExp(`^${ColorExtractor._regexRelaxed.source}$`, 'i'); }
        extract(item, out) {
            if (item.textLabel.match(ColorExtractor._regexStrict)) {
                out[0] = item.textLabel;
                return true;
            }
            if (item.completion.detail && item.completion.detail.match(ColorExtractor._regexStrict)) {
                out[0] = item.completion.detail;
                return true;
            }
            if (item.completion.documentation) {
                const value = typeof item.completion.documentation === 'string'
                    ? item.completion.documentation
                    : item.completion.documentation.value;
                const match = ColorExtractor._regexRelaxed.exec(value);
                if (match && (match.index === 0 || match.index + match[0].length === value.length)) {
                    out[0] = match[0];
                    return true;
                }
            }
            return false;
        }
    };
    let ItemRenderer = class ItemRenderer {
        constructor(_editor, _modelService, _languageService, _themeService) {
            this._editor = _editor;
            this._modelService = _modelService;
            this._languageService = _languageService;
            this._themeService = _themeService;
            this._onDidToggleDetails = new event_1.Emitter();
            this.onDidToggleDetails = this._onDidToggleDetails.event;
            this.templateId = 'suggestion';
        }
        dispose() {
            this._onDidToggleDetails.dispose();
        }
        renderTemplate(container) {
            const disposables = new lifecycle_1.DisposableStore();
            const root = container;
            root.classList.add('show-file-icons');
            const icon = (0, dom_1.append)(container, (0, dom_1.$)('.icon'));
            const colorspan = (0, dom_1.append)(icon, (0, dom_1.$)('span.colorspan'));
            const text = (0, dom_1.append)(container, (0, dom_1.$)('.contents'));
            const main = (0, dom_1.append)(text, (0, dom_1.$)('.main'));
            const iconContainer = (0, dom_1.append)(main, (0, dom_1.$)('.icon-label.codicon'));
            const left = (0, dom_1.append)(main, (0, dom_1.$)('span.left'));
            const right = (0, dom_1.append)(main, (0, dom_1.$)('span.right'));
            const iconLabel = new iconLabel_1.IconLabel(left, { supportHighlights: true, supportIcons: true });
            disposables.add(iconLabel);
            const parametersLabel = (0, dom_1.append)(left, (0, dom_1.$)('span.signature-label'));
            const qualifierLabel = (0, dom_1.append)(left, (0, dom_1.$)('span.qualifier-label'));
            const detailsLabel = (0, dom_1.append)(right, (0, dom_1.$)('span.details-label'));
            const readMore = (0, dom_1.append)(right, (0, dom_1.$)('span.readMore' + themables_1.ThemeIcon.asCSSSelector(suggestMoreInfoIcon)));
            readMore.title = nls.localize(1347, "Read More");
            const configureFont = () => {
                const options = this._editor.getOptions();
                const fontInfo = options.get(50 /* EditorOption.fontInfo */);
                const fontFamily = fontInfo.getMassagedFontFamily();
                const fontFeatureSettings = fontInfo.fontFeatureSettings;
                const fontSize = options.get(120 /* EditorOption.suggestFontSize */) || fontInfo.fontSize;
                const lineHeight = options.get(121 /* EditorOption.suggestLineHeight */) || fontInfo.lineHeight;
                const fontWeight = fontInfo.fontWeight;
                const letterSpacing = fontInfo.letterSpacing;
                const fontSizePx = `${fontSize}px`;
                const lineHeightPx = `${lineHeight}px`;
                const letterSpacingPx = `${letterSpacing}px`;
                root.style.fontSize = fontSizePx;
                root.style.fontWeight = fontWeight;
                root.style.letterSpacing = letterSpacingPx;
                main.style.fontFamily = fontFamily;
                main.style.fontFeatureSettings = fontFeatureSettings;
                main.style.lineHeight = lineHeightPx;
                icon.style.height = lineHeightPx;
                icon.style.width = lineHeightPx;
                readMore.style.height = lineHeightPx;
                readMore.style.width = lineHeightPx;
            };
            return { root, left, right, icon, colorspan, iconLabel, iconContainer, parametersLabel, qualifierLabel, detailsLabel, readMore, disposables, configureFont };
        }
        renderElement(element, index, data) {
            data.configureFont();
            const { completion } = element;
            data.root.id = getAriaId(index);
            data.colorspan.style.backgroundColor = '';
            const labelOptions = {
                labelEscapeNewLines: true,
                matches: (0, filters_1.createMatches)(element.score)
            };
            const color = [];
            if (completion.kind === 19 /* CompletionItemKind.Color */ && _completionItemColor.extract(element, color)) {
                // special logic for 'color' completion items
                data.icon.className = 'icon customcolor';
                data.iconContainer.className = 'icon hide';
                data.colorspan.style.backgroundColor = color[0];
            }
            else if (completion.kind === 20 /* CompletionItemKind.File */ && this._themeService.getFileIconTheme().hasFileIcons) {
                // special logic for 'file' completion items
                data.icon.className = 'icon hide';
                data.iconContainer.className = 'icon hide';
                const labelClasses = (0, getIconClasses_1.getIconClasses)(this._modelService, this._languageService, uri_1.URI.from({ scheme: 'fake', path: element.textLabel }), files_1.FileKind.FILE);
                const detailClasses = (0, getIconClasses_1.getIconClasses)(this._modelService, this._languageService, uri_1.URI.from({ scheme: 'fake', path: completion.detail }), files_1.FileKind.FILE);
                labelOptions.extraClasses = labelClasses.length > detailClasses.length ? labelClasses : detailClasses;
            }
            else if (completion.kind === 23 /* CompletionItemKind.Folder */ && this._themeService.getFileIconTheme().hasFolderIcons) {
                // special logic for 'folder' completion items
                data.icon.className = 'icon hide';
                data.iconContainer.className = 'icon hide';
                labelOptions.extraClasses = [
                    (0, getIconClasses_1.getIconClasses)(this._modelService, this._languageService, uri_1.URI.from({ scheme: 'fake', path: element.textLabel }), files_1.FileKind.FOLDER),
                    (0, getIconClasses_1.getIconClasses)(this._modelService, this._languageService, uri_1.URI.from({ scheme: 'fake', path: completion.detail }), files_1.FileKind.FOLDER)
                ].flat();
            }
            else {
                // normal icon
                data.icon.className = 'icon hide';
                data.iconContainer.className = '';
                data.iconContainer.classList.add('suggest-icon', ...themables_1.ThemeIcon.asClassNameArray(languages_1.CompletionItemKinds.toIcon(completion.kind)));
            }
            if (completion.tags && completion.tags.indexOf(1 /* CompletionItemTag.Deprecated */) >= 0) {
                labelOptions.extraClasses = (labelOptions.extraClasses || []).concat(['deprecated']);
                labelOptions.matches = [];
            }
            data.iconLabel.setLabel(element.textLabel, undefined, labelOptions);
            if (typeof completion.label === 'string') {
                data.parametersLabel.textContent = '';
                data.detailsLabel.textContent = stripNewLines(completion.detail || '');
                data.root.classList.add('string-label');
            }
            else {
                data.parametersLabel.textContent = stripNewLines(completion.label.detail || '');
                data.detailsLabel.textContent = stripNewLines(completion.label.description || '');
                data.root.classList.remove('string-label');
            }
            if (this._editor.getOption(119 /* EditorOption.suggest */).showInlineDetails) {
                (0, dom_1.show)(data.detailsLabel);
            }
            else {
                (0, dom_1.hide)(data.detailsLabel);
            }
            if ((0, suggestWidgetDetails_1.canExpandCompletionItem)(element)) {
                data.right.classList.add('can-expand-details');
                (0, dom_1.show)(data.readMore);
                data.readMore.onmousedown = e => {
                    e.stopPropagation();
                    e.preventDefault();
                };
                data.readMore.onclick = e => {
                    e.stopPropagation();
                    e.preventDefault();
                    this._onDidToggleDetails.fire();
                };
            }
            else {
                data.right.classList.remove('can-expand-details');
                (0, dom_1.hide)(data.readMore);
                data.readMore.onmousedown = null;
                data.readMore.onclick = null;
            }
        }
        disposeTemplate(templateData) {
            templateData.disposables.dispose();
        }
    };
    exports.ItemRenderer = ItemRenderer;
    exports.ItemRenderer = ItemRenderer = __decorate([
        __param(1, model_1.IModelService),
        __param(2, language_1.ILanguageService),
        __param(3, themeService_1.IThemeService)
    ], ItemRenderer);
    function stripNewLines(str) {
        return str.replace(/\r\n|\r|\n/g, '');
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[794/*vs/editor/standalone/browser/quickAccess/standaloneGotoLineQuickAccess*/], __M([1/*require*/,0/*exports*/,787/*vs/editor/contrib/quickAccess/browser/gotoLineQuickAccess*/,38/*vs/platform/registry/common/platform*/,156/*vs/platform/quickinput/common/quickAccess*/,34/*vs/editor/browser/services/codeEditorService*/,107/*vs/editor/common/standaloneStrings*/,6/*vs/base/common/event*/,15/*vs/editor/browser/editorExtensions*/,20/*vs/editor/common/editorContextKeys*/,66/*vs/platform/quickinput/common/quickInput*/]), function (require, exports, gotoLineQuickAccess_1, platform_1, quickAccess_1, codeEditorService_1, standaloneStrings_1, event_1, editorExtensions_1, editorContextKeys_1, quickInput_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.GotoLineAction = exports.StandaloneGotoLineQuickAccessProvider = void 0;
    let StandaloneGotoLineQuickAccessProvider = class StandaloneGotoLineQuickAccessProvider extends gotoLineQuickAccess_1.AbstractGotoLineQuickAccessProvider {
        constructor(editorService) {
            super();
            this.editorService = editorService;
            this.onDidActiveTextEditorControlChange = event_1.Event.None;
        }
        get activeTextEditorControl() {
            return this.editorService.getFocusedCodeEditor() ?? undefined;
        }
    };
    exports.StandaloneGotoLineQuickAccessProvider = StandaloneGotoLineQuickAccessProvider;
    exports.StandaloneGotoLineQuickAccessProvider = StandaloneGotoLineQuickAccessProvider = __decorate([
        __param(0, codeEditorService_1.ICodeEditorService)
    ], StandaloneGotoLineQuickAccessProvider);
    class GotoLineAction extends editorExtensions_1.EditorAction {
        static { this.ID = 'editor.action.gotoLine'; }
        constructor() {
            super({
                id: GotoLineAction.ID,
                label: standaloneStrings_1.GoToLineNLS.gotoLineActionLabel,
                alias: 'Go to Line/Column...',
                precondition: undefined,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.focus,
                    primary: 2048 /* KeyMod.CtrlCmd */ | 37 /* KeyCode.KeyG */,
                    mac: { primary: 256 /* KeyMod.WinCtrl */ | 37 /* KeyCode.KeyG */ },
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
        run(accessor) {
            accessor.get(quickInput_1.IQuickInputService).quickAccess.show(StandaloneGotoLineQuickAccessProvider.PREFIX);
        }
    }
    exports.GotoLineAction = GotoLineAction;
    (0, editorExtensions_1.registerEditorAction)(GotoLineAction);
    platform_1.Registry.as(quickAccess_1.Extensions.Quickaccess).registerQuickAccessProvider({
        ctor: StandaloneGotoLineQuickAccessProvider,
        prefix: StandaloneGotoLineQuickAccessProvider.PREFIX,
        helpEntries: [{ description: standaloneStrings_1.GoToLineNLS.gotoLineActionLabel, commandId: GotoLineAction.ID }]
    });
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[795/*vs/editor/standalone/browser/quickAccess/standaloneGotoSymbolQuickAccess*/], __M([1/*require*/,0/*exports*/,788/*vs/editor/contrib/quickAccess/browser/gotoSymbolQuickAccess*/,38/*vs/platform/registry/common/platform*/,156/*vs/platform/quickinput/common/quickAccess*/,34/*vs/editor/browser/services/codeEditorService*/,107/*vs/editor/common/standaloneStrings*/,6/*vs/base/common/event*/,15/*vs/editor/browser/editorExtensions*/,20/*vs/editor/common/editorContextKeys*/,66/*vs/platform/quickinput/common/quickInput*/,182/*vs/editor/contrib/documentSymbols/browser/outlineModel*/,17/*vs/editor/common/services/languageFeatures*/,195/*vs/base/browser/ui/codicons/codiconStyles*/,280/*vs/editor/contrib/symbolIcons/browser/symbolIcons*/]), function (require, exports, gotoSymbolQuickAccess_1, platform_1, quickAccess_1, codeEditorService_1, standaloneStrings_1, event_1, editorExtensions_1, editorContextKeys_1, quickInput_1, outlineModel_1, languageFeatures_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.GotoSymbolAction = exports.StandaloneGotoSymbolQuickAccessProvider = void 0;
    let StandaloneGotoSymbolQuickAccessProvider = class StandaloneGotoSymbolQuickAccessProvider extends gotoSymbolQuickAccess_1.AbstractGotoSymbolQuickAccessProvider {
        constructor(editorService, languageFeaturesService, outlineModelService) {
            super(languageFeaturesService, outlineModelService);
            this.editorService = editorService;
            this.onDidActiveTextEditorControlChange = event_1.Event.None;
        }
        get activeTextEditorControl() {
            return this.editorService.getFocusedCodeEditor() ?? undefined;
        }
    };
    exports.StandaloneGotoSymbolQuickAccessProvider = StandaloneGotoSymbolQuickAccessProvider;
    exports.StandaloneGotoSymbolQuickAccessProvider = StandaloneGotoSymbolQuickAccessProvider = __decorate([
        __param(0, codeEditorService_1.ICodeEditorService),
        __param(1, languageFeatures_1.ILanguageFeaturesService),
        __param(2, outlineModel_1.IOutlineModelService)
    ], StandaloneGotoSymbolQuickAccessProvider);
    class GotoSymbolAction extends editorExtensions_1.EditorAction {
        static { this.ID = 'editor.action.quickOutline'; }
        constructor() {
            super({
                id: GotoSymbolAction.ID,
                label: standaloneStrings_1.QuickOutlineNLS.quickOutlineActionLabel,
                alias: 'Go to Symbol...',
                precondition: editorContextKeys_1.EditorContextKeys.hasDocumentSymbolProvider,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.focus,
                    primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 45 /* KeyCode.KeyO */,
                    weight: 100 /* KeybindingWeight.EditorContrib */
                },
                contextMenuOpts: {
                    group: 'navigation',
                    order: 3
                }
            });
        }
        run(accessor) {
            accessor.get(quickInput_1.IQuickInputService).quickAccess.show(gotoSymbolQuickAccess_1.AbstractGotoSymbolQuickAccessProvider.PREFIX, { itemActivation: quickInput_1.ItemActivation.NONE });
        }
    }
    exports.GotoSymbolAction = GotoSymbolAction;
    (0, editorExtensions_1.registerEditorAction)(GotoSymbolAction);
    platform_1.Registry.as(quickAccess_1.Extensions.Quickaccess).registerQuickAccessProvider({
        ctor: StandaloneGotoSymbolQuickAccessProvider,
        prefix: gotoSymbolQuickAccess_1.AbstractGotoSymbolQuickAccessProvider.PREFIX,
        helpEntries: [
            { description: standaloneStrings_1.QuickOutlineNLS.quickOutlineActionLabel, prefix: gotoSymbolQuickAccess_1.AbstractGotoSymbolQuickAccessProvider.PREFIX, commandId: GotoSymbolAction.ID },
            { description: standaloneStrings_1.QuickOutlineNLS.quickOutlineByCategoryActionLabel, prefix: gotoSymbolQuickAccess_1.AbstractGotoSymbolQuickAccessProvider.PREFIX_BY_CATEGORY }
        ]
    });
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[418/*vs/editor/standalone/browser/standaloneCodeEditorService*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,42/*vs/base/common/network*/,771/*vs/editor/browser/services/abstractCodeEditorService*/,34/*vs/editor/browser/services/codeEditorService*/,12/*vs/platform/contextkey/common/contextkey*/,49/*vs/platform/instantiation/common/extensions*/,25/*vs/platform/theme/common/themeService*/]), function (require, exports, dom_1, network_1, abstractCodeEditorService_1, codeEditorService_1, contextkey_1, extensions_1, themeService_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.StandaloneCodeEditorService = void 0;
    let StandaloneCodeEditorService = class StandaloneCodeEditorService extends abstractCodeEditorService_1.AbstractCodeEditorService {
        constructor(contextKeyService, themeService) {
            super(themeService);
            this._register(this.onCodeEditorAdd(() => this._checkContextKey()));
            this._register(this.onCodeEditorRemove(() => this._checkContextKey()));
            this._editorIsOpen = contextKeyService.createKey('editorIsOpen', false);
            this._activeCodeEditor = null;
            this._register(this.registerCodeEditorOpenHandler(async (input, source, sideBySide) => {
                if (!source) {
                    return null;
                }
                return this.doOpenEditor(source, input);
            }));
        }
        _checkContextKey() {
            let hasCodeEditor = false;
            for (const editor of this.listCodeEditors()) {
                if (!editor.isSimpleWidget) {
                    hasCodeEditor = true;
                    break;
                }
            }
            this._editorIsOpen.set(hasCodeEditor);
        }
        setActiveCodeEditor(activeCodeEditor) {
            this._activeCodeEditor = activeCodeEditor;
        }
        getActiveCodeEditor() {
            return this._activeCodeEditor;
        }
        doOpenEditor(editor, input) {
            const model = this.findModel(editor, input.resource);
            if (!model) {
                if (input.resource) {
                    const schema = input.resource.scheme;
                    if (schema === network_1.Schemas.http || schema === network_1.Schemas.https) {
                        // This is a fully qualified http or https URL
                        (0, dom_1.windowOpenNoOpener)(input.resource.toString());
                        return editor;
                    }
                }
                return null;
            }
            const selection = (input.options ? input.options.selection : null);
            if (selection) {
                if (typeof selection.endLineNumber === 'number' && typeof selection.endColumn === 'number') {
                    editor.setSelection(selection);
                    editor.revealRangeInCenter(selection, 1 /* ScrollType.Immediate */);
                }
                else {
                    const pos = {
                        lineNumber: selection.startLineNumber,
                        column: selection.startColumn
                    };
                    editor.setPosition(pos);
                    editor.revealPositionInCenter(pos, 1 /* ScrollType.Immediate */);
                }
            }
            return editor;
        }
        findModel(editor, resource) {
            const model = editor.getModel();
            if (model && model.uri.toString() !== resource.toString()) {
                return null;
            }
            return model;
        }
    };
    exports.StandaloneCodeEditorService = StandaloneCodeEditorService;
    exports.StandaloneCodeEditorService = StandaloneCodeEditorService = __decorate([
        __param(0, contextkey_1.IContextKeyService),
        __param(1, themeService_1.IThemeService)
    ], StandaloneCodeEditorService);
    (0, extensions_1.registerSingleton)(codeEditorService_1.ICodeEditorService, StandaloneCodeEditorService, 0 /* InstantiationType.Eager */);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[796/*vs/editor/standalone/common/themes*/], __M([1/*require*/,0/*exports*/,80/*vs/editor/common/core/editorColorRegistry*/,32/*vs/platform/theme/common/colorRegistry*/]), function (require, exports, editorColorRegistry_1, colorRegistry_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.hc_light = exports.hc_black = exports.vs_dark = exports.vs = void 0;
    /* -------------------------------- Begin vs theme -------------------------------- */
    exports.vs = {
        base: 'vs',
        inherit: false,
        rules: [
            { token: '', foreground: '000000', background: 'fffffe' },
            { token: 'invalid', foreground: 'cd3131' },
            { token: 'emphasis', fontStyle: 'italic' },
            { token: 'strong', fontStyle: 'bold' },
            { token: 'variable', foreground: '001188' },
            { token: 'variable.predefined', foreground: '4864AA' },
            { token: 'constant', foreground: 'dd0000' },
            { token: 'comment', foreground: '008000' },
            { token: 'number', foreground: '098658' },
            { token: 'number.hex', foreground: '3030c0' },
            { token: 'regexp', foreground: '800000' },
            { token: 'annotation', foreground: '808080' },
            { token: 'type', foreground: '008080' },
            { token: 'delimiter', foreground: '000000' },
            { token: 'delimiter.html', foreground: '383838' },
            { token: 'delimiter.xml', foreground: '0000FF' },
            { token: 'tag', foreground: '800000' },
            { token: 'tag.id.pug', foreground: '4F76AC' },
            { token: 'tag.class.pug', foreground: '4F76AC' },
            { token: 'meta.scss', foreground: '800000' },
            { token: 'metatag', foreground: 'e00000' },
            { token: 'metatag.content.html', foreground: 'FF0000' },
            { token: 'metatag.html', foreground: '808080' },
            { token: 'metatag.xml', foreground: '808080' },
            { token: 'metatag.php', fontStyle: 'bold' },
            { token: 'key', foreground: '863B00' },
            { token: 'string.key.json', foreground: 'A31515' },
            { token: 'string.value.json', foreground: '0451A5' },
            { token: 'attribute.name', foreground: 'FF0000' },
            { token: 'attribute.value', foreground: '0451A5' },
            { token: 'attribute.value.number', foreground: '098658' },
            { token: 'attribute.value.unit', foreground: '098658' },
            { token: 'attribute.value.html', foreground: '0000FF' },
            { token: 'attribute.value.xml', foreground: '0000FF' },
            { token: 'string', foreground: 'A31515' },
            { token: 'string.html', foreground: '0000FF' },
            { token: 'string.sql', foreground: 'FF0000' },
            { token: 'string.yaml', foreground: '0451A5' },
            { token: 'keyword', foreground: '0000FF' },
            { token: 'keyword.json', foreground: '0451A5' },
            { token: 'keyword.flow', foreground: 'AF00DB' },
            { token: 'keyword.flow.scss', foreground: '0000FF' },
            { token: 'operator.scss', foreground: '666666' },
            { token: 'operator.sql', foreground: '778899' },
            { token: 'operator.swift', foreground: '666666' },
            { token: 'predefined.sql', foreground: 'C700C7' },
        ],
        colors: {
            [colorRegistry_1.editorBackground]: '#FFFFFE',
            [colorRegistry_1.editorForeground]: '#000000',
            [colorRegistry_1.editorInactiveSelection]: '#E5EBF1',
            [editorColorRegistry_1.editorIndentGuide1]: '#D3D3D3',
            [editorColorRegistry_1.editorActiveIndentGuide1]: '#939393',
            [colorRegistry_1.editorSelectionHighlight]: '#ADD6FF4D'
        }
    };
    /* -------------------------------- End vs theme -------------------------------- */
    /* -------------------------------- Begin vs-dark theme -------------------------------- */
    exports.vs_dark = {
        base: 'vs-dark',
        inherit: false,
        rules: [
            { token: '', foreground: 'D4D4D4', background: '1E1E1E' },
            { token: 'invalid', foreground: 'f44747' },
            { token: 'emphasis', fontStyle: 'italic' },
            { token: 'strong', fontStyle: 'bold' },
            { token: 'variable', foreground: '74B0DF' },
            { token: 'variable.predefined', foreground: '4864AA' },
            { token: 'variable.parameter', foreground: '9CDCFE' },
            { token: 'constant', foreground: '569CD6' },
            { token: 'comment', foreground: '608B4E' },
            { token: 'number', foreground: 'B5CEA8' },
            { token: 'number.hex', foreground: '5BB498' },
            { token: 'regexp', foreground: 'B46695' },
            { token: 'annotation', foreground: 'cc6666' },
            { token: 'type', foreground: '3DC9B0' },
            { token: 'delimiter', foreground: 'DCDCDC' },
            { token: 'delimiter.html', foreground: '808080' },
            { token: 'delimiter.xml', foreground: '808080' },
            { token: 'tag', foreground: '569CD6' },
            { token: 'tag.id.pug', foreground: '4F76AC' },
            { token: 'tag.class.pug', foreground: '4F76AC' },
            { token: 'meta.scss', foreground: 'A79873' },
            { token: 'meta.tag', foreground: 'CE9178' },
            { token: 'metatag', foreground: 'DD6A6F' },
            { token: 'metatag.content.html', foreground: '9CDCFE' },
            { token: 'metatag.html', foreground: '569CD6' },
            { token: 'metatag.xml', foreground: '569CD6' },
            { token: 'metatag.php', fontStyle: 'bold' },
            { token: 'key', foreground: '9CDCFE' },
            { token: 'string.key.json', foreground: '9CDCFE' },
            { token: 'string.value.json', foreground: 'CE9178' },
            { token: 'attribute.name', foreground: '9CDCFE' },
            { token: 'attribute.value', foreground: 'CE9178' },
            { token: 'attribute.value.number.css', foreground: 'B5CEA8' },
            { token: 'attribute.value.unit.css', foreground: 'B5CEA8' },
            { token: 'attribute.value.hex.css', foreground: 'D4D4D4' },
            { token: 'string', foreground: 'CE9178' },
            { token: 'string.sql', foreground: 'FF0000' },
            { token: 'keyword', foreground: '569CD6' },
            { token: 'keyword.flow', foreground: 'C586C0' },
            { token: 'keyword.json', foreground: 'CE9178' },
            { token: 'keyword.flow.scss', foreground: '569CD6' },
            { token: 'operator.scss', foreground: '909090' },
            { token: 'operator.sql', foreground: '778899' },
            { token: 'operator.swift', foreground: '909090' },
            { token: 'predefined.sql', foreground: 'FF00FF' },
        ],
        colors: {
            [colorRegistry_1.editorBackground]: '#1E1E1E',
            [colorRegistry_1.editorForeground]: '#D4D4D4',
            [colorRegistry_1.editorInactiveSelection]: '#3A3D41',
            [editorColorRegistry_1.editorIndentGuide1]: '#404040',
            [editorColorRegistry_1.editorActiveIndentGuide1]: '#707070',
            [colorRegistry_1.editorSelectionHighlight]: '#ADD6FF26'
        }
    };
    /* -------------------------------- End vs-dark theme -------------------------------- */
    /* -------------------------------- Begin hc-black theme -------------------------------- */
    exports.hc_black = {
        base: 'hc-black',
        inherit: false,
        rules: [
            { token: '', foreground: 'FFFFFF', background: '000000' },
            { token: 'invalid', foreground: 'f44747' },
            { token: 'emphasis', fontStyle: 'italic' },
            { token: 'strong', fontStyle: 'bold' },
            { token: 'variable', foreground: '1AEBFF' },
            { token: 'variable.parameter', foreground: '9CDCFE' },
            { token: 'constant', foreground: '569CD6' },
            { token: 'comment', foreground: '608B4E' },
            { token: 'number', foreground: 'FFFFFF' },
            { token: 'regexp', foreground: 'C0C0C0' },
            { token: 'annotation', foreground: '569CD6' },
            { token: 'type', foreground: '3DC9B0' },
            { token: 'delimiter', foreground: 'FFFF00' },
            { token: 'delimiter.html', foreground: 'FFFF00' },
            { token: 'tag', foreground: '569CD6' },
            { token: 'tag.id.pug', foreground: '4F76AC' },
            { token: 'tag.class.pug', foreground: '4F76AC' },
            { token: 'meta', foreground: 'D4D4D4' },
            { token: 'meta.tag', foreground: 'CE9178' },
            { token: 'metatag', foreground: '569CD6' },
            { token: 'metatag.content.html', foreground: '1AEBFF' },
            { token: 'metatag.html', foreground: '569CD6' },
            { token: 'metatag.xml', foreground: '569CD6' },
            { token: 'metatag.php', fontStyle: 'bold' },
            { token: 'key', foreground: '9CDCFE' },
            { token: 'string.key', foreground: '9CDCFE' },
            { token: 'string.value', foreground: 'CE9178' },
            { token: 'attribute.name', foreground: '569CD6' },
            { token: 'attribute.value', foreground: '3FF23F' },
            { token: 'string', foreground: 'CE9178' },
            { token: 'string.sql', foreground: 'FF0000' },
            { token: 'keyword', foreground: '569CD6' },
            { token: 'keyword.flow', foreground: 'C586C0' },
            { token: 'operator.sql', foreground: '778899' },
            { token: 'operator.swift', foreground: '909090' },
            { token: 'predefined.sql', foreground: 'FF00FF' },
        ],
        colors: {
            [colorRegistry_1.editorBackground]: '#000000',
            [colorRegistry_1.editorForeground]: '#FFFFFF',
            [editorColorRegistry_1.editorIndentGuide1]: '#FFFFFF',
            [editorColorRegistry_1.editorActiveIndentGuide1]: '#FFFFFF',
        }
    };
    /* -------------------------------- End hc-black theme -------------------------------- */
    /* -------------------------------- Begin hc-light theme -------------------------------- */
    exports.hc_light = {
        base: 'hc-light',
        inherit: false,
        rules: [
            { token: '', foreground: '292929', background: 'FFFFFF' },
            { token: 'invalid', foreground: 'B5200D' },
            { token: 'emphasis', fontStyle: 'italic' },
            { token: 'strong', fontStyle: 'bold' },
            { token: 'variable', foreground: '264F70' },
            { token: 'variable.predefined', foreground: '4864AA' },
            { token: 'constant', foreground: 'dd0000' },
            { token: 'comment', foreground: '008000' },
            { token: 'number', foreground: '098658' },
            { token: 'number.hex', foreground: '3030c0' },
            { token: 'regexp', foreground: '800000' },
            { token: 'annotation', foreground: '808080' },
            { token: 'type', foreground: '008080' },
            { token: 'delimiter', foreground: '000000' },
            { token: 'delimiter.html', foreground: '383838' },
            { token: 'tag', foreground: '800000' },
            { token: 'tag.id.pug', foreground: '4F76AC' },
            { token: 'tag.class.pug', foreground: '4F76AC' },
            { token: 'meta.scss', foreground: '800000' },
            { token: 'metatag', foreground: 'e00000' },
            { token: 'metatag.content.html', foreground: 'B5200D' },
            { token: 'metatag.html', foreground: '808080' },
            { token: 'metatag.xml', foreground: '808080' },
            { token: 'metatag.php', fontStyle: 'bold' },
            { token: 'key', foreground: '863B00' },
            { token: 'string.key.json', foreground: 'A31515' },
            { token: 'string.value.json', foreground: '0451A5' },
            { token: 'attribute.name', foreground: '264F78' },
            { token: 'attribute.value', foreground: '0451A5' },
            { token: 'string', foreground: 'A31515' },
            { token: 'string.sql', foreground: 'B5200D' },
            { token: 'keyword', foreground: '0000FF' },
            { token: 'keyword.flow', foreground: 'AF00DB' },
            { token: 'operator.sql', foreground: '778899' },
            { token: 'operator.swift', foreground: '666666' },
            { token: 'predefined.sql', foreground: 'C700C7' },
        ],
        colors: {
            [colorRegistry_1.editorBackground]: '#FFFFFF',
            [colorRegistry_1.editorForeground]: '#292929',
            [editorColorRegistry_1.editorIndentGuide1]: '#292929',
            [editorColorRegistry_1.editorActiveIndentGuide1]: '#292929',
        }
    };
});
/* -------------------------------- End hc-light theme -------------------------------- */

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[419/*vs/editor/standalone/browser/standaloneThemeService*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,64/*vs/base/browser/browser*/,33/*vs/base/common/color*/,6/*vs/base/common/event*/,27/*vs/editor/common/languages*/,148/*vs/editor/common/encodedTokenAttributes*/,572/*vs/editor/common/languages/supports/tokenization*/,796/*vs/editor/standalone/common/themes*/,38/*vs/platform/registry/common/platform*/,32/*vs/platform/theme/common/colorRegistry*/,25/*vs/platform/theme/common/themeService*/,2/*vs/base/common/lifecycle*/,97/*vs/platform/theme/common/theme*/,767/*vs/platform/theme/browser/iconsStyleSheet*/,52/*vs/base/browser/window*/]), function (require, exports, dom, browser_1, color_1, event_1, languages_1, encodedTokenAttributes_1, tokenization_1, themes_1, platform_1, colorRegistry_1, themeService_1, lifecycle_1, theme_1, iconsStyleSheet_1, window_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.StandaloneThemeService = exports.HC_LIGHT_THEME_NAME = exports.HC_BLACK_THEME_NAME = exports.VS_DARK_THEME_NAME = exports.VS_LIGHT_THEME_NAME = void 0;
    exports.VS_LIGHT_THEME_NAME = 'vs';
    exports.VS_DARK_THEME_NAME = 'vs-dark';
    exports.HC_BLACK_THEME_NAME = 'hc-black';
    exports.HC_LIGHT_THEME_NAME = 'hc-light';
    const colorRegistry = platform_1.Registry.as(colorRegistry_1.Extensions.ColorContribution);
    const themingRegistry = platform_1.Registry.as(themeService_1.Extensions.ThemingContribution);
    class StandaloneTheme {
        constructor(name, standaloneThemeData) {
            this.semanticHighlighting = false;
            this.themeData = standaloneThemeData;
            const base = standaloneThemeData.base;
            if (name.length > 0) {
                if (isBuiltinTheme(name)) {
                    this.id = name;
                }
                else {
                    this.id = base + ' ' + name;
                }
                this.themeName = name;
            }
            else {
                this.id = base;
                this.themeName = base;
            }
            this.colors = null;
            this.defaultColors = Object.create(null);
            this._tokenTheme = null;
        }
        get base() {
            return this.themeData.base;
        }
        notifyBaseUpdated() {
            if (this.themeData.inherit) {
                this.colors = null;
                this._tokenTheme = null;
            }
        }
        getColors() {
            if (!this.colors) {
                const colors = new Map();
                for (const id in this.themeData.colors) {
                    colors.set(id, color_1.Color.fromHex(this.themeData.colors[id]));
                }
                if (this.themeData.inherit) {
                    const baseData = getBuiltinRules(this.themeData.base);
                    for (const id in baseData.colors) {
                        if (!colors.has(id)) {
                            colors.set(id, color_1.Color.fromHex(baseData.colors[id]));
                        }
                    }
                }
                this.colors = colors;
            }
            return this.colors;
        }
        getColor(colorId, useDefault) {
            const color = this.getColors().get(colorId);
            if (color) {
                return color;
            }
            if (useDefault !== false) {
                return this.getDefault(colorId);
            }
            return undefined;
        }
        getDefault(colorId) {
            let color = this.defaultColors[colorId];
            if (color) {
                return color;
            }
            color = colorRegistry.resolveDefaultColor(colorId, this);
            this.defaultColors[colorId] = color;
            return color;
        }
        defines(colorId) {
            return this.getColors().has(colorId);
        }
        get type() {
            switch (this.base) {
                case exports.VS_LIGHT_THEME_NAME: return theme_1.ColorScheme.LIGHT;
                case exports.HC_BLACK_THEME_NAME: return theme_1.ColorScheme.HIGH_CONTRAST_DARK;
                case exports.HC_LIGHT_THEME_NAME: return theme_1.ColorScheme.HIGH_CONTRAST_LIGHT;
                default: return theme_1.ColorScheme.DARK;
            }
        }
        get tokenTheme() {
            if (!this._tokenTheme) {
                let rules = [];
                let encodedTokensColors = [];
                if (this.themeData.inherit) {
                    const baseData = getBuiltinRules(this.themeData.base);
                    rules = baseData.rules;
                    if (baseData.encodedTokensColors) {
                        encodedTokensColors = baseData.encodedTokensColors;
                    }
                }
                // Pick up default colors from `editor.foreground` and `editor.background` if available
                const editorForeground = this.themeData.colors['editor.foreground'];
                const editorBackground = this.themeData.colors['editor.background'];
                if (editorForeground || editorBackground) {
                    const rule = { token: '' };
                    if (editorForeground) {
                        rule.foreground = editorForeground;
                    }
                    if (editorBackground) {
                        rule.background = editorBackground;
                    }
                    rules.push(rule);
                }
                rules = rules.concat(this.themeData.rules);
                if (this.themeData.encodedTokensColors) {
                    encodedTokensColors = this.themeData.encodedTokensColors;
                }
                this._tokenTheme = tokenization_1.TokenTheme.createFromRawTokenTheme(rules, encodedTokensColors);
            }
            return this._tokenTheme;
        }
        getTokenStyleMetadata(type, modifiers, modelLanguage) {
            // use theme rules match
            const style = this.tokenTheme._match([type].concat(modifiers).join('.'));
            const metadata = style.metadata;
            const foreground = encodedTokenAttributes_1.TokenMetadata.getForeground(metadata);
            const fontStyle = encodedTokenAttributes_1.TokenMetadata.getFontStyle(metadata);
            return {
                foreground: foreground,
                italic: Boolean(fontStyle & 1 /* FontStyle.Italic */),
                bold: Boolean(fontStyle & 2 /* FontStyle.Bold */),
                underline: Boolean(fontStyle & 4 /* FontStyle.Underline */),
                strikethrough: Boolean(fontStyle & 8 /* FontStyle.Strikethrough */)
            };
        }
    }
    function isBuiltinTheme(themeName) {
        return (themeName === exports.VS_LIGHT_THEME_NAME
            || themeName === exports.VS_DARK_THEME_NAME
            || themeName === exports.HC_BLACK_THEME_NAME
            || themeName === exports.HC_LIGHT_THEME_NAME);
    }
    function getBuiltinRules(builtinTheme) {
        switch (builtinTheme) {
            case exports.VS_LIGHT_THEME_NAME:
                return themes_1.vs;
            case exports.VS_DARK_THEME_NAME:
                return themes_1.vs_dark;
            case exports.HC_BLACK_THEME_NAME:
                return themes_1.hc_black;
            case exports.HC_LIGHT_THEME_NAME:
                return themes_1.hc_light;
        }
    }
    function newBuiltInTheme(builtinTheme) {
        const themeData = getBuiltinRules(builtinTheme);
        return new StandaloneTheme(builtinTheme, themeData);
    }
    class StandaloneThemeService extends lifecycle_1.Disposable {
        constructor() {
            super();
            this._onColorThemeChange = this._register(new event_1.Emitter());
            this.onDidColorThemeChange = this._onColorThemeChange.event;
            this._onProductIconThemeChange = this._register(new event_1.Emitter());
            this.onDidProductIconThemeChange = this._onProductIconThemeChange.event;
            this._environment = Object.create(null);
            this._builtInProductIconTheme = new iconsStyleSheet_1.UnthemedProductIconTheme();
            this._autoDetectHighContrast = true;
            this._knownThemes = new Map();
            this._knownThemes.set(exports.VS_LIGHT_THEME_NAME, newBuiltInTheme(exports.VS_LIGHT_THEME_NAME));
            this._knownThemes.set(exports.VS_DARK_THEME_NAME, newBuiltInTheme(exports.VS_DARK_THEME_NAME));
            this._knownThemes.set(exports.HC_BLACK_THEME_NAME, newBuiltInTheme(exports.HC_BLACK_THEME_NAME));
            this._knownThemes.set(exports.HC_LIGHT_THEME_NAME, newBuiltInTheme(exports.HC_LIGHT_THEME_NAME));
            const iconsStyleSheet = this._register((0, iconsStyleSheet_1.getIconsStyleSheet)(this));
            this._codiconCSS = iconsStyleSheet.getCSS();
            this._themeCSS = '';
            this._allCSS = `${this._codiconCSS}\n${this._themeCSS}`;
            this._globalStyleElement = null;
            this._styleElements = [];
            this._colorMapOverride = null;
            this.setTheme(exports.VS_LIGHT_THEME_NAME);
            this._onOSSchemeChanged();
            this._register(iconsStyleSheet.onDidChange(() => {
                this._codiconCSS = iconsStyleSheet.getCSS();
                this._updateCSS();
            }));
            (0, browser_1.addMatchMediaChangeListener)(window_1.mainWindow, '(forced-colors: active)', () => {
                this._onOSSchemeChanged();
            });
        }
        registerEditorContainer(domNode) {
            if (dom.isInShadowDOM(domNode)) {
                return this._registerShadowDomContainer(domNode);
            }
            return this._registerRegularEditorContainer();
        }
        _registerRegularEditorContainer() {
            if (!this._globalStyleElement) {
                this._globalStyleElement = dom.createStyleSheet(undefined, style => {
                    style.className = 'monaco-colors';
                    style.textContent = this._allCSS;
                });
                this._styleElements.push(this._globalStyleElement);
            }
            return lifecycle_1.Disposable.None;
        }
        _registerShadowDomContainer(domNode) {
            const styleElement = dom.createStyleSheet(domNode, style => {
                style.className = 'monaco-colors';
                style.textContent = this._allCSS;
            });
            this._styleElements.push(styleElement);
            return {
                dispose: () => {
                    for (let i = 0; i < this._styleElements.length; i++) {
                        if (this._styleElements[i] === styleElement) {
                            this._styleElements.splice(i, 1);
                            return;
                        }
                    }
                }
            };
        }
        defineTheme(themeName, themeData) {
            if (!/^[a-z0-9\-]+$/i.test(themeName)) {
                throw new Error('Illegal theme name!');
            }
            if (!isBuiltinTheme(themeData.base) && !isBuiltinTheme(themeName)) {
                throw new Error('Illegal theme base!');
            }
            // set or replace theme
            this._knownThemes.set(themeName, new StandaloneTheme(themeName, themeData));
            if (isBuiltinTheme(themeName)) {
                this._knownThemes.forEach(theme => {
                    if (theme.base === themeName) {
                        theme.notifyBaseUpdated();
                    }
                });
            }
            if (this._theme.themeName === themeName) {
                this.setTheme(themeName); // refresh theme
            }
        }
        getColorTheme() {
            return this._theme;
        }
        setColorMapOverride(colorMapOverride) {
            this._colorMapOverride = colorMapOverride;
            this._updateThemeOrColorMap();
        }
        setTheme(themeName) {
            let theme;
            if (this._knownThemes.has(themeName)) {
                theme = this._knownThemes.get(themeName);
            }
            else {
                theme = this._knownThemes.get(exports.VS_LIGHT_THEME_NAME);
            }
            this._updateActualTheme(theme);
        }
        _updateActualTheme(desiredTheme) {
            if (!desiredTheme || this._theme === desiredTheme) {
                // Nothing to do
                return;
            }
            this._theme = desiredTheme;
            this._updateThemeOrColorMap();
        }
        _onOSSchemeChanged() {
            if (this._autoDetectHighContrast) {
                const wantsHighContrast = window_1.mainWindow.matchMedia(`(forced-colors: active)`).matches;
                if (wantsHighContrast !== (0, theme_1.isHighContrast)(this._theme.type)) {
                    // switch to high contrast or non-high contrast but stick to dark or light
                    let newThemeName;
                    if ((0, theme_1.isDark)(this._theme.type)) {
                        newThemeName = wantsHighContrast ? exports.HC_BLACK_THEME_NAME : exports.VS_DARK_THEME_NAME;
                    }
                    else {
                        newThemeName = wantsHighContrast ? exports.HC_LIGHT_THEME_NAME : exports.VS_LIGHT_THEME_NAME;
                    }
                    this._updateActualTheme(this._knownThemes.get(newThemeName));
                }
            }
        }
        setAutoDetectHighContrast(autoDetectHighContrast) {
            this._autoDetectHighContrast = autoDetectHighContrast;
            this._onOSSchemeChanged();
        }
        _updateThemeOrColorMap() {
            const cssRules = [];
            const hasRule = {};
            const ruleCollector = {
                addRule: (rule) => {
                    if (!hasRule[rule]) {
                        cssRules.push(rule);
                        hasRule[rule] = true;
                    }
                }
            };
            themingRegistry.getThemingParticipants().forEach(p => p(this._theme, ruleCollector, this._environment));
            const colorVariables = [];
            for (const item of colorRegistry.getColors()) {
                const color = this._theme.getColor(item.id, true);
                if (color) {
                    colorVariables.push(`${(0, colorRegistry_1.asCssVariableName)(item.id)}: ${color.toString()};`);
                }
            }
            ruleCollector.addRule(`.monaco-editor, .monaco-diff-editor, .monaco-component { ${colorVariables.join('\n')} }`);
            const colorMap = this._colorMapOverride || this._theme.tokenTheme.getColorMap();
            ruleCollector.addRule((0, tokenization_1.generateTokensCSSForColorMap)(colorMap));
            this._themeCSS = cssRules.join('\n');
            this._updateCSS();
            languages_1.TokenizationRegistry.setColorMap(colorMap);
            this._onColorThemeChange.fire(this._theme);
        }
        _updateCSS() {
            this._allCSS = `${this._codiconCSS}\n${this._themeCSS}`;
            this._styleElements.forEach(styleElement => styleElement.textContent = this._allCSS);
        }
        getFileIconTheme() {
            return {
                hasFileIcons: false,
                hasFolderIcons: false,
                hidesExplorerArrows: false
            };
        }
        getProductIconTheme() {
            return this._builtInProductIconTheme;
        }
    }
    exports.StandaloneThemeService = StandaloneThemeService;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[797/*vs/editor/standalone/browser/toggleHighContrast/toggleHighContrast*/], __M([1/*require*/,0/*exports*/,15/*vs/editor/browser/editorExtensions*/,153/*vs/editor/standalone/common/standaloneTheme*/,107/*vs/editor/common/standaloneStrings*/,97/*vs/platform/theme/common/theme*/,419/*vs/editor/standalone/browser/standaloneThemeService*/]), function (require, exports, editorExtensions_1, standaloneTheme_1, standaloneStrings_1, theme_1, standaloneThemeService_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    class ToggleHighContrast extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: 'editor.action.toggleHighContrast',
                label: standaloneStrings_1.ToggleHighContrastNLS.toggleHighContrast,
                alias: 'Toggle High Contrast Theme',
                precondition: undefined
            });
            this._originalThemeName = null;
        }
        run(accessor, editor) {
            const standaloneThemeService = accessor.get(standaloneTheme_1.IStandaloneThemeService);
            const currentTheme = standaloneThemeService.getColorTheme();
            if ((0, theme_1.isHighContrast)(currentTheme.type)) {
                // We must toggle back to the integrator's theme
                standaloneThemeService.setTheme(this._originalThemeName || ((0, theme_1.isDark)(currentTheme.type) ? standaloneThemeService_1.VS_DARK_THEME_NAME : standaloneThemeService_1.VS_LIGHT_THEME_NAME));
                this._originalThemeName = null;
            }
            else {
                standaloneThemeService.setTheme((0, theme_1.isDark)(currentTheme.type) ? standaloneThemeService_1.HC_BLACK_THEME_NAME : standaloneThemeService_1.HC_LIGHT_THEME_NAME);
                this._originalThemeName = currentTheme.themeName;
            }
        }
    }
    (0, editorExtensions_1.registerEditorAction)(ToggleHighContrast);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[124/*vs/platform/actions/browser/menuEntryActionViewItem*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,47/*vs/base/browser/keyboardEvent*/,151/*vs/base/browser/ui/actionbar/actionViewItems*/,359/*vs/base/browser/ui/dropdown/dropdownActionViewItem*/,41/*vs/base/common/actions*/,247/*vs/base/common/keybindingLabels*/,2/*vs/base/common/lifecycle*/,16/*vs/base/common/platform*/,3/*vs/nls*/,29/*vs/platform/actions/common/actions*/,381/*vs/platform/action/common/action*/,12/*vs/platform/contextkey/common/contextkey*/,58/*vs/platform/contextview/browser/contextView*/,7/*vs/platform/instantiation/common/instantiation*/,31/*vs/platform/keybinding/common/keybinding*/,50/*vs/platform/notification/common/notification*/,101/*vs/platform/storage/common/storage*/,25/*vs/platform/theme/common/themeService*/,30/*vs/base/common/themables*/,97/*vs/platform/theme/common/theme*/,19/*vs/base/common/types*/,32/*vs/platform/theme/common/colorRegistry*/,110/*vs/platform/theme/browser/defaultStyles*/,61/*vs/platform/accessibility/common/accessibility*/,542/*vs/css!vs/platform/actions/browser/menuEntryActionViewItem*/]), function (require, exports, dom_1, keyboardEvent_1, actionViewItems_1, dropdownActionViewItem_1, actions_1, keybindingLabels_1, lifecycle_1, platform_1, nls_1, actions_2, action_1, contextkey_1, contextView_1, instantiation_1, keybinding_1, notification_1, storage_1, themeService_1, themables_1, theme_1, types_1, colorRegistry_1, defaultStyles_1, accessibility_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DropdownWithDefaultActionViewItem = exports.SubmenuEntryActionViewItem = exports.TextOnlyMenuEntryActionViewItem = exports.MenuEntryActionViewItem = void 0;
    exports.createAndFillInContextMenuActions = createAndFillInContextMenuActions;
    exports.createAndFillInActionBarActions = createAndFillInActionBarActions;
    exports.createActionViewItem = createActionViewItem;
    function createAndFillInContextMenuActions(menu, optionsOrTarget, targetOrPrimaryGroup, primaryGroupOrUndefined) {
        let target;
        let primaryGroup;
        let groups;
        if (Array.isArray(menu)) {
            groups = menu;
            target = optionsOrTarget;
            primaryGroup = targetOrPrimaryGroup;
        }
        else {
            const options = optionsOrTarget;
            groups = menu.getActions(options);
            target = targetOrPrimaryGroup;
            primaryGroup = primaryGroupOrUndefined;
        }
        const modifierKeyEmitter = dom_1.ModifierKeyEmitter.getInstance();
        const useAlternativeActions = modifierKeyEmitter.keyStatus.altKey || ((platform_1.isWindows || platform_1.isLinux) && modifierKeyEmitter.keyStatus.shiftKey);
        fillInActions(groups, target, useAlternativeActions, primaryGroup ? actionGroup => actionGroup === primaryGroup : actionGroup => actionGroup === 'navigation');
    }
    function createAndFillInActionBarActions(menu, optionsOrTarget, targetOrPrimaryGroup, primaryGroupOrShouldInlineSubmenu, shouldInlineSubmenuOrUseSeparatorsInPrimaryActions, useSeparatorsInPrimaryActionsOrUndefined) {
        let target;
        let primaryGroup;
        let shouldInlineSubmenu;
        let useSeparatorsInPrimaryActions;
        let groups;
        if (Array.isArray(menu)) {
            groups = menu;
            target = optionsOrTarget;
            primaryGroup = targetOrPrimaryGroup;
            shouldInlineSubmenu = primaryGroupOrShouldInlineSubmenu;
            useSeparatorsInPrimaryActions = shouldInlineSubmenuOrUseSeparatorsInPrimaryActions;
        }
        else {
            const options = optionsOrTarget;
            groups = menu.getActions(options);
            target = targetOrPrimaryGroup;
            primaryGroup = primaryGroupOrShouldInlineSubmenu;
            shouldInlineSubmenu = shouldInlineSubmenuOrUseSeparatorsInPrimaryActions;
            useSeparatorsInPrimaryActions = useSeparatorsInPrimaryActionsOrUndefined;
        }
        const isPrimaryAction = typeof primaryGroup === 'string' ? (actionGroup) => actionGroup === primaryGroup : primaryGroup;
        // Action bars handle alternative actions on their own so the alternative actions should be ignored
        fillInActions(groups, target, false, isPrimaryAction, shouldInlineSubmenu, useSeparatorsInPrimaryActions);
    }
    function fillInActions(groups, target, useAlternativeActions, isPrimaryAction = actionGroup => actionGroup === 'navigation', shouldInlineSubmenu = () => false, useSeparatorsInPrimaryActions = false) {
        let primaryBucket;
        let secondaryBucket;
        if (Array.isArray(target)) {
            primaryBucket = target;
            secondaryBucket = target;
        }
        else {
            primaryBucket = target.primary;
            secondaryBucket = target.secondary;
        }
        const submenuInfo = new Set();
        for (const [group, actions] of groups) {
            let target;
            if (isPrimaryAction(group)) {
                target = primaryBucket;
                if (target.length > 0 && useSeparatorsInPrimaryActions) {
                    target.push(new actions_1.Separator());
                }
            }
            else {
                target = secondaryBucket;
                if (target.length > 0) {
                    target.push(new actions_1.Separator());
                }
            }
            for (let action of actions) {
                if (useAlternativeActions) {
                    action = action instanceof actions_2.MenuItemAction && action.alt ? action.alt : action;
                }
                const newLen = target.push(action);
                // keep submenu info for later inlining
                if (action instanceof actions_1.SubmenuAction) {
                    submenuInfo.add({ group, action, index: newLen - 1 });
                }
            }
        }
        // ask the outside if submenu should be inlined or not. only ask when
        // there would be enough space
        for (const { group, action, index } of submenuInfo) {
            const target = isPrimaryAction(group) ? primaryBucket : secondaryBucket;
            // inlining submenus with length 0 or 1 is easy,
            // larger submenus need to be checked with the overall limit
            const submenuActions = action.actions;
            if (shouldInlineSubmenu(action, group, target.length)) {
                target.splice(index, 1, ...submenuActions);
            }
        }
    }
    let MenuEntryActionViewItem = class MenuEntryActionViewItem extends actionViewItems_1.ActionViewItem {
        constructor(action, _options, _keybindingService, _notificationService, _contextKeyService, _themeService, _contextMenuService, _accessibilityService) {
            super(undefined, action, { icon: !!(action.class || action.item.icon), label: !action.class && !action.item.icon, draggable: _options?.draggable, keybinding: _options?.keybinding, hoverDelegate: _options?.hoverDelegate });
            this._options = _options;
            this._keybindingService = _keybindingService;
            this._notificationService = _notificationService;
            this._contextKeyService = _contextKeyService;
            this._themeService = _themeService;
            this._contextMenuService = _contextMenuService;
            this._accessibilityService = _accessibilityService;
            this._wantsAltCommand = false;
            this._itemClassDispose = this._register(new lifecycle_1.MutableDisposable());
            this._altKey = dom_1.ModifierKeyEmitter.getInstance();
        }
        get _menuItemAction() {
            return this._action;
        }
        get _commandAction() {
            return this._wantsAltCommand && this._menuItemAction.alt || this._menuItemAction;
        }
        async onClick(event) {
            event.preventDefault();
            event.stopPropagation();
            try {
                await this.actionRunner.run(this._commandAction, this._context);
            }
            catch (err) {
                this._notificationService.error(err);
            }
        }
        render(container) {
            super.render(container);
            container.classList.add('menu-entry');
            if (this.options.icon) {
                this._updateItemClass(this._menuItemAction.item);
            }
            if (this._menuItemAction.alt) {
                let isMouseOver = false;
                const updateAltState = () => {
                    const wantsAltCommand = !!this._menuItemAction.alt?.enabled &&
                        (!this._accessibilityService.isMotionReduced() || isMouseOver) && (this._altKey.keyStatus.altKey ||
                        (this._altKey.keyStatus.shiftKey && isMouseOver));
                    if (wantsAltCommand !== this._wantsAltCommand) {
                        this._wantsAltCommand = wantsAltCommand;
                        this.updateLabel();
                        this.updateTooltip();
                        this.updateClass();
                    }
                };
                this._register(this._altKey.event(updateAltState));
                this._register((0, dom_1.addDisposableListener)(container, 'mouseleave', _ => {
                    isMouseOver = false;
                    updateAltState();
                }));
                this._register((0, dom_1.addDisposableListener)(container, 'mouseenter', _ => {
                    isMouseOver = true;
                    updateAltState();
                }));
                updateAltState();
            }
        }
        updateLabel() {
            if (this.options.label && this.label) {
                this.label.textContent = this._commandAction.label;
            }
        }
        getTooltip() {
            const keybinding = this._keybindingService.lookupKeybinding(this._commandAction.id, this._contextKeyService);
            const keybindingLabel = keybinding && keybinding.getLabel();
            const tooltip = this._commandAction.tooltip || this._commandAction.label;
            let title = keybindingLabel
                ? (0, nls_1.localize)(1483, "{0} ({1})", tooltip, keybindingLabel)
                : tooltip;
            if (!this._wantsAltCommand && this._menuItemAction.alt?.enabled) {
                const altTooltip = this._menuItemAction.alt.tooltip || this._menuItemAction.alt.label;
                const altKeybinding = this._keybindingService.lookupKeybinding(this._menuItemAction.alt.id, this._contextKeyService);
                const altKeybindingLabel = altKeybinding && altKeybinding.getLabel();
                const altTitleSection = altKeybindingLabel
                    ? (0, nls_1.localize)(1484, "{0} ({1})", altTooltip, altKeybindingLabel)
                    : altTooltip;
                title = (0, nls_1.localize)(1485, "{0}\n[{1}] {2}", title, keybindingLabels_1.UILabelProvider.modifierLabels[platform_1.OS].altKey, altTitleSection);
            }
            return title;
        }
        updateClass() {
            if (this.options.icon) {
                if (this._commandAction !== this._menuItemAction) {
                    if (this._menuItemAction.alt) {
                        this._updateItemClass(this._menuItemAction.alt.item);
                    }
                }
                else {
                    this._updateItemClass(this._menuItemAction.item);
                }
            }
        }
        _updateItemClass(item) {
            this._itemClassDispose.value = undefined;
            const { element, label } = this;
            if (!element || !label) {
                return;
            }
            const icon = this._commandAction.checked && (0, action_1.isICommandActionToggleInfo)(item.toggled) && item.toggled.icon ? item.toggled.icon : item.icon;
            if (!icon) {
                return;
            }
            if (themables_1.ThemeIcon.isThemeIcon(icon)) {
                // theme icons
                const iconClasses = themables_1.ThemeIcon.asClassNameArray(icon);
                label.classList.add(...iconClasses);
                this._itemClassDispose.value = (0, lifecycle_1.toDisposable)(() => {
                    label.classList.remove(...iconClasses);
                });
            }
            else {
                // icon path/url
                label.style.backgroundImage = ((0, theme_1.isDark)(this._themeService.getColorTheme().type)
                    ? (0, dom_1.asCSSUrl)(icon.dark)
                    : (0, dom_1.asCSSUrl)(icon.light));
                label.classList.add('icon');
                this._itemClassDispose.value = (0, lifecycle_1.combinedDisposable)((0, lifecycle_1.toDisposable)(() => {
                    label.style.backgroundImage = '';
                    label.classList.remove('icon');
                }), this._themeService.onDidColorThemeChange(() => {
                    // refresh when the theme changes in case we go between dark <-> light
                    this.updateClass();
                }));
            }
        }
    };
    exports.MenuEntryActionViewItem = MenuEntryActionViewItem;
    exports.MenuEntryActionViewItem = MenuEntryActionViewItem = __decorate([
        __param(2, keybinding_1.IKeybindingService),
        __param(3, notification_1.INotificationService),
        __param(4, contextkey_1.IContextKeyService),
        __param(5, themeService_1.IThemeService),
        __param(6, contextView_1.IContextMenuService),
        __param(7, accessibility_1.IAccessibilityService)
    ], MenuEntryActionViewItem);
    class TextOnlyMenuEntryActionViewItem extends MenuEntryActionViewItem {
        render(container) {
            this.options.label = true;
            this.options.icon = false;
            super.render(container);
            container.classList.add('text-only');
            container.classList.toggle('use-comma', this._options?.useComma ?? false);
        }
        updateLabel() {
            const kb = this._keybindingService.lookupKeybinding(this._action.id, this._contextKeyService);
            if (!kb) {
                return super.updateLabel();
            }
            if (this.label) {
                const kb2 = TextOnlyMenuEntryActionViewItem._symbolPrintEnter(kb);
                if (this._options?.conversational) {
                    this.label.textContent = (0, nls_1.localize)(1486, '{1} to {0}', this._action.label, kb2);
                }
                else {
                    this.label.textContent = (0, nls_1.localize)(1487, '{0} ({1})', this._action.label, kb2);
                }
            }
        }
        static _symbolPrintEnter(kb) {
            return kb.getLabel()
                ?.replace(/\benter\b/gi, '\u23CE')
                .replace(/\bEscape\b/gi, 'Esc');
        }
    }
    exports.TextOnlyMenuEntryActionViewItem = TextOnlyMenuEntryActionViewItem;
    let SubmenuEntryActionViewItem = class SubmenuEntryActionViewItem extends dropdownActionViewItem_1.DropdownMenuActionViewItem {
        constructor(action, options, _keybindingService, _contextMenuService, _themeService) {
            const dropdownOptions = {
                ...options,
                menuAsChild: options?.menuAsChild ?? false,
                classNames: options?.classNames ?? (themables_1.ThemeIcon.isThemeIcon(action.item.icon) ? themables_1.ThemeIcon.asClassName(action.item.icon) : undefined),
                keybindingProvider: options?.keybindingProvider ?? (action => _keybindingService.lookupKeybinding(action.id))
            };
            super(action, { getActions: () => action.actions }, _contextMenuService, dropdownOptions);
            this._keybindingService = _keybindingService;
            this._contextMenuService = _contextMenuService;
            this._themeService = _themeService;
        }
        render(container) {
            super.render(container);
            (0, types_1.assertType)(this.element);
            container.classList.add('menu-entry');
            const action = this._action;
            const { icon } = action.item;
            if (icon && !themables_1.ThemeIcon.isThemeIcon(icon)) {
                this.element.classList.add('icon');
                const setBackgroundImage = () => {
                    if (this.element) {
                        this.element.style.backgroundImage = ((0, theme_1.isDark)(this._themeService.getColorTheme().type)
                            ? (0, dom_1.asCSSUrl)(icon.dark)
                            : (0, dom_1.asCSSUrl)(icon.light));
                    }
                };
                setBackgroundImage();
                this._register(this._themeService.onDidColorThemeChange(() => {
                    // refresh when the theme changes in case we go between dark <-> light
                    setBackgroundImage();
                }));
            }
        }
    };
    exports.SubmenuEntryActionViewItem = SubmenuEntryActionViewItem;
    exports.SubmenuEntryActionViewItem = SubmenuEntryActionViewItem = __decorate([
        __param(2, keybinding_1.IKeybindingService),
        __param(3, contextView_1.IContextMenuService),
        __param(4, themeService_1.IThemeService)
    ], SubmenuEntryActionViewItem);
    let DropdownWithDefaultActionViewItem = class DropdownWithDefaultActionViewItem extends actionViewItems_1.BaseActionViewItem {
        constructor(submenuAction, options, _keybindingService, _notificationService, _contextMenuService, _menuService, _instaService, _storageService) {
            super(null, submenuAction);
            this._keybindingService = _keybindingService;
            this._notificationService = _notificationService;
            this._contextMenuService = _contextMenuService;
            this._menuService = _menuService;
            this._instaService = _instaService;
            this._storageService = _storageService;
            this._container = null;
            this._options = options;
            this._storageKey = `${submenuAction.item.submenu.id}_lastActionId`;
            // determine default action
            let defaultAction;
            const defaultActionId = options?.persistLastActionId ? _storageService.get(this._storageKey, 1 /* StorageScope.WORKSPACE */) : undefined;
            if (defaultActionId) {
                defaultAction = submenuAction.actions.find(a => defaultActionId === a.id);
            }
            if (!defaultAction) {
                defaultAction = submenuAction.actions[0];
            }
            this._defaultAction = this._instaService.createInstance(MenuEntryActionViewItem, defaultAction, { keybinding: this._getDefaultActionKeybindingLabel(defaultAction) });
            const dropdownOptions = {
                keybindingProvider: action => this._keybindingService.lookupKeybinding(action.id),
                ...options,
                menuAsChild: options?.menuAsChild ?? true,
                classNames: options?.classNames ?? ['codicon', 'codicon-chevron-down'],
                actionRunner: options?.actionRunner ?? new actions_1.ActionRunner(),
            };
            this._dropdown = new dropdownActionViewItem_1.DropdownMenuActionViewItem(submenuAction, submenuAction.actions, this._contextMenuService, dropdownOptions);
            this._register(this._dropdown.actionRunner.onDidRun((e) => {
                if (e.action instanceof actions_2.MenuItemAction) {
                    this.update(e.action);
                }
            }));
        }
        update(lastAction) {
            if (this._options?.persistLastActionId) {
                this._storageService.store(this._storageKey, lastAction.id, 1 /* StorageScope.WORKSPACE */, 1 /* StorageTarget.MACHINE */);
            }
            this._defaultAction.dispose();
            this._defaultAction = this._instaService.createInstance(MenuEntryActionViewItem, lastAction, { keybinding: this._getDefaultActionKeybindingLabel(lastAction) });
            this._defaultAction.actionRunner = new class extends actions_1.ActionRunner {
                async runAction(action, context) {
                    await action.run(undefined);
                }
            }();
            if (this._container) {
                this._defaultAction.render((0, dom_1.prepend)(this._container, (0, dom_1.$)('.action-container')));
            }
        }
        _getDefaultActionKeybindingLabel(defaultAction) {
            let defaultActionKeybinding;
            if (this._options?.renderKeybindingWithDefaultActionLabel) {
                const kb = this._keybindingService.lookupKeybinding(defaultAction.id);
                if (kb) {
                    defaultActionKeybinding = `(${kb.getLabel()})`;
                }
            }
            return defaultActionKeybinding;
        }
        setActionContext(newContext) {
            super.setActionContext(newContext);
            this._defaultAction.setActionContext(newContext);
            this._dropdown.setActionContext(newContext);
        }
        render(container) {
            this._container = container;
            super.render(this._container);
            this._container.classList.add('monaco-dropdown-with-default');
            const primaryContainer = (0, dom_1.$)('.action-container');
            this._defaultAction.render((0, dom_1.append)(this._container, primaryContainer));
            this._register((0, dom_1.addDisposableListener)(primaryContainer, dom_1.EventType.KEY_DOWN, (e) => {
                const event = new keyboardEvent_1.StandardKeyboardEvent(e);
                if (event.equals(17 /* KeyCode.RightArrow */)) {
                    this._defaultAction.element.tabIndex = -1;
                    this._dropdown.focus();
                    event.stopPropagation();
                }
            }));
            const dropdownContainer = (0, dom_1.$)('.dropdown-action-container');
            this._dropdown.render((0, dom_1.append)(this._container, dropdownContainer));
            this._register((0, dom_1.addDisposableListener)(dropdownContainer, dom_1.EventType.KEY_DOWN, (e) => {
                const event = new keyboardEvent_1.StandardKeyboardEvent(e);
                if (event.equals(15 /* KeyCode.LeftArrow */)) {
                    this._defaultAction.element.tabIndex = 0;
                    this._dropdown.setFocusable(false);
                    this._defaultAction.element?.focus();
                    event.stopPropagation();
                }
            }));
        }
        focus(fromRight) {
            if (fromRight) {
                this._dropdown.focus();
            }
            else {
                this._defaultAction.element.tabIndex = 0;
                this._defaultAction.element.focus();
            }
        }
        blur() {
            this._defaultAction.element.tabIndex = -1;
            this._dropdown.blur();
            this._container.blur();
        }
        setFocusable(focusable) {
            if (focusable) {
                this._defaultAction.element.tabIndex = 0;
            }
            else {
                this._defaultAction.element.tabIndex = -1;
                this._dropdown.setFocusable(false);
            }
        }
        dispose() {
            this._defaultAction.dispose();
            this._dropdown.dispose();
            super.dispose();
        }
    };
    exports.DropdownWithDefaultActionViewItem = DropdownWithDefaultActionViewItem;
    exports.DropdownWithDefaultActionViewItem = DropdownWithDefaultActionViewItem = __decorate([
        __param(2, keybinding_1.IKeybindingService),
        __param(3, notification_1.INotificationService),
        __param(4, contextView_1.IContextMenuService),
        __param(5, actions_2.IMenuService),
        __param(6, instantiation_1.IInstantiationService),
        __param(7, storage_1.IStorageService)
    ], DropdownWithDefaultActionViewItem);
    let SubmenuEntrySelectActionViewItem = class SubmenuEntrySelectActionViewItem extends actionViewItems_1.SelectActionViewItem {
        constructor(action, contextViewService) {
            super(null, action, action.actions.map(a => ({
                text: a.id === actions_1.Separator.ID ? '\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500' : a.label,
                isDisabled: !a.enabled,
            })), 0, contextViewService, defaultStyles_1.defaultSelectBoxStyles, { ariaLabel: action.tooltip, optionsAsChildren: true });
            this.select(Math.max(0, action.actions.findIndex(a => a.checked)));
        }
        render(container) {
            super.render(container);
            container.style.borderColor = (0, colorRegistry_1.asCssVariable)(colorRegistry_1.selectBorder);
        }
        runAction(option, index) {
            const action = this.action.actions[index];
            if (action) {
                this.actionRunner.run(action);
            }
        }
    };
    SubmenuEntrySelectActionViewItem = __decorate([
        __param(1, contextView_1.IContextViewService)
    ], SubmenuEntrySelectActionViewItem);
    /**
     * Creates action view items for menu actions or submenu actions.
     */
    function createActionViewItem(instaService, action, options) {
        if (action instanceof actions_2.MenuItemAction) {
            return instaService.createInstance(MenuEntryActionViewItem, action, options);
        }
        else if (action instanceof actions_2.SubmenuItemAction) {
            if (action.item.isSelection) {
                return instaService.createInstance(SubmenuEntrySelectActionViewItem, action);
            }
            else {
                if (action.item.rememberDefaultAction) {
                    return instaService.createInstance(DropdownWithDefaultActionViewItem, action, { ...options, persistLastActionId: true });
                }
                else {
                    return instaService.createInstance(SubmenuEntryActionViewItem, action, options);
                }
            }
        }
        else {
            return undefined;
        }
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[798/*vs/editor/contrib/suggest/browser/suggestWidgetStatus*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,87/*vs/base/browser/ui/actionbar/actionbar*/,2/*vs/base/common/lifecycle*/,124/*vs/platform/actions/browser/menuEntryActionViewItem*/,29/*vs/platform/actions/common/actions*/,12/*vs/platform/contextkey/common/contextkey*/,7/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, dom, actionbar_1, lifecycle_1, menuEntryActionViewItem_1, actions_1, contextkey_1, instantiation_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SuggestWidgetStatus = void 0;
    let SuggestWidgetStatus = class SuggestWidgetStatus {
        constructor(container, _menuId, instantiationService, _menuService, _contextKeyService) {
            this._menuId = _menuId;
            this._menuService = _menuService;
            this._contextKeyService = _contextKeyService;
            this._menuDisposables = new lifecycle_1.DisposableStore();
            this.element = dom.append(container, dom.$('.suggest-status-bar'));
            const actionViewItemProvider = (action => {
                return action instanceof actions_1.MenuItemAction ? instantiationService.createInstance(menuEntryActionViewItem_1.TextOnlyMenuEntryActionViewItem, action, { useComma: true }) : undefined;
            });
            this._leftActions = new actionbar_1.ActionBar(this.element, { actionViewItemProvider });
            this._rightActions = new actionbar_1.ActionBar(this.element, { actionViewItemProvider });
            this._leftActions.domNode.classList.add('left');
            this._rightActions.domNode.classList.add('right');
        }
        dispose() {
            this._menuDisposables.dispose();
            this._leftActions.dispose();
            this._rightActions.dispose();
            this.element.remove();
        }
        show() {
            const menu = this._menuService.createMenu(this._menuId, this._contextKeyService);
            const renderMenu = () => {
                const left = [];
                const right = [];
                for (const [group, actions] of menu.getActions()) {
                    if (group === 'left') {
                        left.push(...actions);
                    }
                    else {
                        right.push(...actions);
                    }
                }
                this._leftActions.clear();
                this._leftActions.push(left);
                this._rightActions.clear();
                this._rightActions.push(right);
            };
            this._menuDisposables.add(menu.onDidChange(() => renderMenu()));
            this._menuDisposables.add(menu);
        }
        hide() {
            this._menuDisposables.clear();
        }
    };
    exports.SuggestWidgetStatus = SuggestWidgetStatus;
    exports.SuggestWidgetStatus = SuggestWidgetStatus = __decorate([
        __param(2, instantiation_1.IInstantiationService),
        __param(3, actions_1.IMenuService),
        __param(4, contextkey_1.IContextKeyService)
    ], SuggestWidgetStatus);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[218/*vs/platform/actions/browser/toolbar*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,77/*vs/base/browser/mouseEvent*/,643/*vs/base/browser/ui/toolbar/toolbar*/,41/*vs/base/common/actions*/,13/*vs/base/common/arrays*/,298/*vs/base/common/collections*/,8/*vs/base/common/errors*/,6/*vs/base/common/event*/,53/*vs/base/common/iterator*/,2/*vs/base/common/lifecycle*/,3/*vs/nls*/,124/*vs/platform/actions/browser/menuEntryActionViewItem*/,29/*vs/platform/actions/common/actions*/,406/*vs/platform/actions/common/menuService*/,24/*vs/platform/commands/common/commands*/,12/*vs/platform/contextkey/common/contextkey*/,58/*vs/platform/contextview/browser/contextView*/,31/*vs/platform/keybinding/common/keybinding*/,63/*vs/platform/telemetry/common/telemetry*/]), function (require, exports, dom_1, mouseEvent_1, toolbar_1, actions_1, arrays_1, collections_1, errors_1, event_1, iterator_1, lifecycle_1, nls_1, menuEntryActionViewItem_1, actions_2, menuService_1, commands_1, contextkey_1, contextView_1, keybinding_1, telemetry_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MenuWorkbenchToolBar = exports.WorkbenchToolBar = void 0;
    /**
     * The `WorkbenchToolBar` does
     * - support hiding of menu items
     * - lookup keybindings for each actions automatically
     * - send `workbenchActionExecuted`-events for each action
     *
     * See {@link MenuWorkbenchToolBar} for a toolbar that is backed by a menu.
     */
    let WorkbenchToolBar = class WorkbenchToolBar extends toolbar_1.ToolBar {
        constructor(container, _options, _menuService, _contextKeyService, _contextMenuService, _keybindingService, _commandService, telemetryService) {
            super(container, _contextMenuService, {
                // defaults
                getKeyBinding: (action) => _keybindingService.lookupKeybinding(action.id) ?? undefined,
                // options (override defaults)
                ..._options,
                // mandatory (overide options)
                allowContextMenu: true,
                skipTelemetry: typeof _options?.telemetrySource === 'string',
            });
            this._options = _options;
            this._menuService = _menuService;
            this._contextKeyService = _contextKeyService;
            this._contextMenuService = _contextMenuService;
            this._keybindingService = _keybindingService;
            this._commandService = _commandService;
            this._sessionDisposables = this._store.add(new lifecycle_1.DisposableStore());
            // telemetry logic
            const telemetrySource = _options?.telemetrySource;
            if (telemetrySource) {
                this._store.add(this.actionBar.onDidRun(e => telemetryService.publicLog2('workbenchActionExecuted', { id: e.action.id, from: telemetrySource })));
            }
        }
        setActions(_primary, _secondary = [], menuIds) {
            this._sessionDisposables.clear();
            const primary = _primary.slice(); // for hiding and overflow we set some items to undefined
            const secondary = _secondary.slice();
            const toggleActions = [];
            let toggleActionsCheckedCount = 0;
            const extraSecondary = [];
            let someAreHidden = false;
            // unless disabled, move all hidden items to secondary group or ignore them
            if (this._options?.hiddenItemStrategy !== -1 /* HiddenItemStrategy.NoHide */) {
                for (let i = 0; i < primary.length; i++) {
                    const action = primary[i];
                    if (!(action instanceof actions_2.MenuItemAction) && !(action instanceof actions_2.SubmenuItemAction)) {
                        // console.warn(`Action ${action.id}/${action.label} is not a MenuItemAction`);
                        continue;
                    }
                    if (!action.hideActions) {
                        continue;
                    }
                    // collect all toggle actions
                    toggleActions.push(action.hideActions.toggle);
                    if (action.hideActions.toggle.checked) {
                        toggleActionsCheckedCount++;
                    }
                    // hidden items move into overflow or ignore
                    if (action.hideActions.isHidden) {
                        someAreHidden = true;
                        primary[i] = undefined;
                        if (this._options?.hiddenItemStrategy !== 0 /* HiddenItemStrategy.Ignore */) {
                            extraSecondary[i] = action;
                        }
                    }
                }
            }
            // count for max
            if (this._options?.overflowBehavior !== undefined) {
                const exemptedIds = (0, collections_1.intersection)(new Set(this._options.overflowBehavior.exempted), iterator_1.Iterable.map(primary, a => a?.id));
                const maxItems = this._options.overflowBehavior.maxItems - exemptedIds.size;
                let count = 0;
                for (let i = 0; i < primary.length; i++) {
                    const action = primary[i];
                    if (!action) {
                        continue;
                    }
                    count++;
                    if (exemptedIds.has(action.id)) {
                        continue;
                    }
                    if (count >= maxItems) {
                        primary[i] = undefined;
                        extraSecondary[i] = action;
                    }
                }
            }
            // coalesce turns Array<IAction|undefined> into IAction[]
            (0, arrays_1.coalesceInPlace)(primary);
            (0, arrays_1.coalesceInPlace)(extraSecondary);
            super.setActions(primary, actions_1.Separator.join(extraSecondary, secondary));
            // add context menu for toggle and configure keybinding actions
            if (toggleActions.length > 0 || primary.length > 0) {
                this._sessionDisposables.add((0, dom_1.addDisposableListener)(this.getElement(), 'contextmenu', e => {
                    const event = new mouseEvent_1.StandardMouseEvent((0, dom_1.getWindow)(this.getElement()), e);
                    const action = this.getItemAction(event.target);
                    if (!(action)) {
                        return;
                    }
                    event.preventDefault();
                    event.stopPropagation();
                    const primaryActions = [];
                    // -- Configure Keybinding Action --
                    if (action instanceof actions_2.MenuItemAction && action.menuKeybinding) {
                        primaryActions.push(action.menuKeybinding);
                    }
                    else if (!(action instanceof actions_2.SubmenuItemAction || action instanceof toolbar_1.ToggleMenuAction)) {
                        // only enable the configure keybinding action for actions that support keybindings
                        const supportsKeybindings = !!this._keybindingService.lookupKeybinding(action.id);
                        primaryActions.push((0, menuService_1.createConfigureKeybindingAction)(this._commandService, this._keybindingService, action.id, undefined, supportsKeybindings));
                    }
                    // -- Hide Actions --
                    if (toggleActions.length > 0) {
                        let noHide = false;
                        // last item cannot be hidden when using ignore strategy
                        if (toggleActionsCheckedCount === 1 && this._options?.hiddenItemStrategy === 0 /* HiddenItemStrategy.Ignore */) {
                            noHide = true;
                            for (let i = 0; i < toggleActions.length; i++) {
                                if (toggleActions[i].checked) {
                                    toggleActions[i] = (0, actions_1.toAction)({
                                        id: action.id,
                                        label: action.label,
                                        checked: true,
                                        enabled: false,
                                        run() { }
                                    });
                                    break; // there is only one
                                }
                            }
                        }
                        // add "hide foo" actions
                        if (!noHide && (action instanceof actions_2.MenuItemAction || action instanceof actions_2.SubmenuItemAction)) {
                            if (!action.hideActions) {
                                // no context menu for MenuItemAction instances that support no hiding
                                // those are fake actions and need to be cleaned up
                                return;
                            }
                            primaryActions.push(action.hideActions.hide);
                        }
                        else {
                            primaryActions.push((0, actions_1.toAction)({
                                id: 'label',
                                label: (0, nls_1.localize)(1488, "Hide"),
                                enabled: false,
                                run() { }
                            }));
                        }
                    }
                    const actions = actions_1.Separator.join(primaryActions, toggleActions);
                    // add "Reset Menu" action
                    if (this._options?.resetMenu && !menuIds) {
                        menuIds = [this._options.resetMenu];
                    }
                    if (someAreHidden && menuIds) {
                        actions.push(new actions_1.Separator());
                        actions.push((0, actions_1.toAction)({
                            id: 'resetThisMenu',
                            label: (0, nls_1.localize)(1489, "Reset Menu"),
                            run: () => this._menuService.resetHiddenStates(menuIds)
                        }));
                    }
                    if (actions.length === 0) {
                        return;
                    }
                    this._contextMenuService.showContextMenu({
                        getAnchor: () => event,
                        getActions: () => actions,
                        // add context menu actions (iff appicable)
                        menuId: this._options?.contextMenu,
                        menuActionOptions: { renderShortTitle: true, ...this._options?.menuOptions },
                        skipTelemetry: typeof this._options?.telemetrySource === 'string',
                        contextKeyService: this._contextKeyService,
                    });
                }));
            }
        }
    };
    exports.WorkbenchToolBar = WorkbenchToolBar;
    exports.WorkbenchToolBar = WorkbenchToolBar = __decorate([
        __param(2, actions_2.IMenuService),
        __param(3, contextkey_1.IContextKeyService),
        __param(4, contextView_1.IContextMenuService),
        __param(5, keybinding_1.IKeybindingService),
        __param(6, commands_1.ICommandService),
        __param(7, telemetry_1.ITelemetryService)
    ], WorkbenchToolBar);
    /**
     * A {@link WorkbenchToolBar workbench toolbar} that is purely driven from a {@link MenuId menu}-identifier.
     *
     * *Note* that Manual updates via `setActions` are NOT supported.
     */
    let MenuWorkbenchToolBar = class MenuWorkbenchToolBar extends WorkbenchToolBar {
        constructor(container, menuId, options, menuService, contextKeyService, contextMenuService, keybindingService, commandService, telemetryService) {
            super(container, { resetMenu: menuId, ...options }, menuService, contextKeyService, contextMenuService, keybindingService, commandService, telemetryService);
            this._onDidChangeMenuItems = this._store.add(new event_1.Emitter());
            this.onDidChangeMenuItems = this._onDidChangeMenuItems.event;
            // update logic
            const menu = this._store.add(menuService.createMenu(menuId, contextKeyService, { emitEventsForSubmenuChanges: true }));
            const updateToolbar = () => {
                const primary = [];
                const secondary = [];
                (0, menuEntryActionViewItem_1.createAndFillInActionBarActions)(menu, options?.menuOptions, { primary, secondary }, options?.toolbarOptions?.primaryGroup, options?.toolbarOptions?.shouldInlineSubmenu, options?.toolbarOptions?.useSeparatorsInPrimaryActions);
                container.classList.toggle('has-no-actions', primary.length === 0 && secondary.length === 0);
                super.setActions(primary, secondary);
            };
            this._store.add(menu.onDidChange(() => {
                updateToolbar();
                this._onDidChangeMenuItems.fire(this);
            }));
            updateToolbar();
        }
        /**
         * @deprecated The WorkbenchToolBar does not support this method because it works with menus.
         */
        setActions() {
            throw new errors_1.BugIndicatingError('This toolbar is populated from a menu.');
        }
    };
    exports.MenuWorkbenchToolBar = MenuWorkbenchToolBar;
    exports.MenuWorkbenchToolBar = MenuWorkbenchToolBar = __decorate([
        __param(3, actions_2.IMenuService),
        __param(4, contextkey_1.IContextKeyService),
        __param(5, contextView_1.IContextMenuService),
        __param(6, keybinding_1.IKeybindingService),
        __param(7, commands_1.ICommandService),
        __param(8, telemetry_1.ITelemetryService)
    ], MenuWorkbenchToolBar);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[799/*vs/editor/browser/widget/diffEditor/features/gutterFeature*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,2/*vs/base/common/lifecycle*/,21/*vs/base/common/observable*/,65/*vs/base/common/observableInternal/derived*/,363/*vs/editor/browser/widget/diffEditor/components/diffEditorSash*/,88/*vs/editor/browser/widget/diffEditor/utils*/,654/*vs/editor/browser/widget/diffEditor/utils/editorGutter*/,365/*vs/editor/browser/widget/multiDiffEditor/utils*/,55/*vs/editor/common/core/lineRange*/,68/*vs/editor/common/core/offsetRange*/,4/*vs/editor/common/core/range*/,104/*vs/editor/common/core/textEdit*/,105/*vs/editor/common/diff/rangeMapping*/,581/*vs/editor/common/model/textModelText*/,218/*vs/platform/actions/browser/toolbar*/,29/*vs/platform/actions/common/actions*/,12/*vs/platform/contextkey/common/contextkey*/,118/*vs/platform/hover/browser/hover*/,7/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, dom_1, lifecycle_1, observable_1, derived_1, diffEditorSash_1, utils_1, editorGutter_1, utils_2, lineRange_1, offsetRange_1, range_1, textEdit_1, rangeMapping_1, textModelText_1, toolbar_1, actions_1, contextkey_1, hover_1, instantiation_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DiffEditorGutter = void 0;
    const emptyArr = [];
    const width = 35;
    let DiffEditorGutter = class DiffEditorGutter extends lifecycle_1.Disposable {
        constructor(diffEditorRoot, _diffModel, _editors, _options, _sashLayout, _boundarySashes, _instantiationService, _contextKeyService, _menuService) {
            super();
            this._diffModel = _diffModel;
            this._editors = _editors;
            this._options = _options;
            this._sashLayout = _sashLayout;
            this._boundarySashes = _boundarySashes;
            this._instantiationService = _instantiationService;
            this._contextKeyService = _contextKeyService;
            this._menuService = _menuService;
            this._menu = this._register(this._menuService.createMenu(actions_1.MenuId.DiffEditorHunkToolbar, this._contextKeyService));
            this._actions = (0, observable_1.observableFromEvent)(this, this._menu.onDidChange, () => this._menu.getActions());
            this._hasActions = this._actions.map(a => a.length > 0);
            this._showSash = (0, observable_1.derived)(this, reader => this._options.renderSideBySide.read(reader) && this._hasActions.read(reader));
            this.width = (0, observable_1.derived)(this, reader => this._hasActions.read(reader) ? width : 0);
            this.elements = (0, dom_1.h)('div.gutter@gutter', { style: { position: 'absolute', height: '100%', width: width + 'px' } }, []);
            this._currentDiff = (0, observable_1.derived)(this, (reader) => {
                const model = this._diffModel.read(reader);
                if (!model) {
                    return undefined;
                }
                const mappings = model.diff.read(reader)?.mappings;
                const cursorPosition = this._editors.modifiedCursor.read(reader);
                if (!cursorPosition) {
                    return undefined;
                }
                return mappings?.find(m => m.lineRangeMapping.modified.contains(cursorPosition.lineNumber));
            });
            this._selectedDiffs = (0, observable_1.derived)(this, (reader) => {
                /** @description selectedDiffs */
                const model = this._diffModel.read(reader);
                const diff = model?.diff.read(reader);
                // Return `emptyArr` because it is a constant. [] is always a new array and would trigger a change.
                if (!diff) {
                    return emptyArr;
                }
                const selections = this._editors.modifiedSelections.read(reader);
                if (selections.every(s => s.isEmpty())) {
                    return emptyArr;
                }
                const selectedLineNumbers = new lineRange_1.LineRangeSet(selections.map(s => lineRange_1.LineRange.fromRangeInclusive(s)));
                const selectedMappings = diff.mappings.filter(m => m.lineRangeMapping.innerChanges && selectedLineNumbers.intersects(m.lineRangeMapping.modified));
                const result = selectedMappings.map(mapping => ({
                    mapping,
                    rangeMappings: mapping.lineRangeMapping.innerChanges.filter(c => selections.some(s => range_1.Range.areIntersecting(c.modifiedRange, s)))
                }));
                if (result.length === 0 || result.every(r => r.rangeMappings.length === 0)) {
                    return emptyArr;
                }
                return result;
            });
            this._register((0, utils_1.prependRemoveOnDispose)(diffEditorRoot, this.elements.root));
            this._register((0, dom_1.addDisposableListener)(this.elements.root, 'click', () => {
                this._editors.modified.focus();
            }));
            this._register((0, utils_1.applyStyle)(this.elements.root, { display: this._hasActions.map(a => a ? 'block' : 'none') }));
            (0, derived_1.derivedDisposable)(this, reader => {
                const showSash = this._showSash.read(reader);
                return !showSash ? undefined : new diffEditorSash_1.DiffEditorSash(diffEditorRoot, this._sashLayout.dimensions, this._options.enableSplitViewResizing, this._boundarySashes, (0, derived_1.derivedWithSetter)(this, reader => this._sashLayout.sashLeft.read(reader) - width, (v, tx) => this._sashLayout.sashLeft.set(v + width, tx)), () => this._sashLayout.resetSash());
            }).recomputeInitiallyAndOnChange(this._store);
            this._register(new editorGutter_1.EditorGutter(this._editors.modified, this.elements.root, {
                getIntersectingGutterItems: (range, reader) => {
                    const model = this._diffModel.read(reader);
                    if (!model) {
                        return [];
                    }
                    const diffs = model.diff.read(reader);
                    if (!diffs) {
                        return [];
                    }
                    const selection = this._selectedDiffs.read(reader);
                    if (selection.length > 0) {
                        const m = rangeMapping_1.DetailedLineRangeMapping.fromRangeMappings(selection.flatMap(s => s.rangeMappings));
                        return [
                            new DiffGutterItem(m, true, actions_1.MenuId.DiffEditorSelectionToolbar, undefined, model.model.original.uri, model.model.modified.uri)
                        ];
                    }
                    const currentDiff = this._currentDiff.read(reader);
                    return diffs.mappings.map(m => new DiffGutterItem(m.lineRangeMapping.withInnerChangesFromLineRanges(), m.lineRangeMapping === currentDiff?.lineRangeMapping, actions_1.MenuId.DiffEditorHunkToolbar, undefined, model.model.original.uri, model.model.modified.uri));
                },
                createView: (item, target) => {
                    return this._instantiationService.createInstance(DiffToolBar, item, target, this);
                },
            }));
            this._register((0, dom_1.addDisposableListener)(this.elements.gutter, dom_1.EventType.MOUSE_WHEEL, (e) => {
                if (this._editors.modified.getOption(104 /* EditorOption.scrollbar */).handleMouseWheel) {
                    this._editors.modified.delegateScrollFromMouseWheelEvent(e);
                }
            }, { passive: false }));
        }
        computeStagedValue(mapping) {
            const c = mapping.innerChanges ?? [];
            const modified = new textModelText_1.TextModelText(this._editors.modifiedModel.get());
            const original = new textModelText_1.TextModelText(this._editors.original.getModel());
            const edit = new textEdit_1.TextEdit(c.map(c => c.toTextEdit(modified)));
            const value = edit.apply(original);
            return value;
        }
        layout(left) {
            this.elements.gutter.style.left = left + 'px';
        }
    };
    exports.DiffEditorGutter = DiffEditorGutter;
    exports.DiffEditorGutter = DiffEditorGutter = __decorate([
        __param(6, instantiation_1.IInstantiationService),
        __param(7, contextkey_1.IContextKeyService),
        __param(8, actions_1.IMenuService)
    ], DiffEditorGutter);
    class DiffGutterItem {
        constructor(mapping, showAlways, menuId, rangeOverride, originalUri, modifiedUri) {
            this.mapping = mapping;
            this.showAlways = showAlways;
            this.menuId = menuId;
            this.rangeOverride = rangeOverride;
            this.originalUri = originalUri;
            this.modifiedUri = modifiedUri;
        }
        get id() { return this.mapping.modified.toString(); }
        get range() { return this.rangeOverride ?? this.mapping.modified; }
    }
    let DiffToolBar = class DiffToolBar extends lifecycle_1.Disposable {
        constructor(_item, target, gutter, instantiationService) {
            super();
            this._item = _item;
            this._elements = (0, dom_1.h)('div.gutterItem', { style: { height: '20px', width: '34px' } }, [
                (0, dom_1.h)('div.background@background', {}, []),
                (0, dom_1.h)('div.buttons@buttons', {}, []),
            ]);
            this._showAlways = this._item.map(this, item => item.showAlways);
            this._menuId = this._item.map(this, item => item.menuId);
            this._isSmall = (0, observable_1.observableValue)(this, false);
            this._lastItemRange = undefined;
            this._lastViewRange = undefined;
            const hoverDelegate = this._register(instantiationService.createInstance(hover_1.WorkbenchHoverDelegate, 'element', true, { position: { hoverPosition: 1 /* HoverPosition.RIGHT */ } }));
            this._register((0, utils_1.appendRemoveOnDispose)(target, this._elements.root));
            this._register((0, observable_1.autorun)(reader => {
                /** @description update showAlways */
                const showAlways = this._showAlways.read(reader);
                this._elements.root.classList.toggle('noTransition', true);
                this._elements.root.classList.toggle('showAlways', showAlways);
                setTimeout(() => {
                    this._elements.root.classList.toggle('noTransition', false);
                }, 0);
            }));
            this._register((0, observable_1.autorunWithStore)((reader, store) => {
                this._elements.buttons.replaceChildren();
                const i = store.add(instantiationService.createInstance(toolbar_1.MenuWorkbenchToolBar, this._elements.buttons, this._menuId.read(reader), {
                    orientation: 1 /* ActionsOrientation.VERTICAL */,
                    hoverDelegate,
                    toolbarOptions: {
                        primaryGroup: g => g.startsWith('primary'),
                    },
                    overflowBehavior: { maxItems: this._isSmall.read(reader) ? 1 : 3 },
                    hiddenItemStrategy: 0 /* HiddenItemStrategy.Ignore */,
                    actionRunner: new utils_2.ActionRunnerWithContext(() => {
                        const item = this._item.get();
                        const mapping = item.mapping;
                        return {
                            mapping,
                            originalWithModifiedChanges: gutter.computeStagedValue(mapping),
                            originalUri: item.originalUri,
                            modifiedUri: item.modifiedUri,
                        };
                    }),
                    menuOptions: {
                        shouldForwardArgs: true,
                    },
                }));
                store.add(i.onDidChangeMenuItems(() => {
                    if (this._lastItemRange) {
                        this.layout(this._lastItemRange, this._lastViewRange);
                    }
                }));
            }));
        }
        layout(itemRange, viewRange) {
            this._lastItemRange = itemRange;
            this._lastViewRange = viewRange;
            let itemHeight = this._elements.buttons.clientHeight;
            this._isSmall.set(this._item.get().mapping.original.startLineNumber === 1 && itemRange.length < 30, undefined);
            // Item might have changed
            itemHeight = this._elements.buttons.clientHeight;
            const middleHeight = itemRange.length / 2 - itemHeight / 2;
            const margin = itemHeight;
            let effectiveCheckboxTop = itemRange.start + middleHeight;
            const preferredViewPortRange = offsetRange_1.OffsetRange.tryCreate(margin, viewRange.endExclusive - margin - itemHeight);
            const preferredParentRange = offsetRange_1.OffsetRange.tryCreate(itemRange.start + margin, itemRange.endExclusive - itemHeight - margin);
            if (preferredParentRange && preferredViewPortRange && preferredParentRange.start < preferredParentRange.endExclusive) {
                effectiveCheckboxTop = preferredViewPortRange.clip(effectiveCheckboxTop);
                effectiveCheckboxTop = preferredParentRange.clip(effectiveCheckboxTop);
            }
            this._elements.buttons.style.top = `${effectiveCheckboxTop - itemRange.start}px`;
        }
    };
    DiffToolBar = __decorate([
        __param(3, instantiation_1.IInstantiationService)
    ], DiffToolBar);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[283/*vs/editor/contrib/inlineCompletions/browser/hintsWidget/inlineCompletionsHintsWidget*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,151/*vs/base/browser/ui/actionbar/actionViewItems*/,206/*vs/base/browser/ui/keybindingLabel/keybindingLabel*/,41/*vs/base/common/actions*/,13/*vs/base/common/arrays*/,14/*vs/base/common/async*/,26/*vs/base/common/codicons*/,2/*vs/base/common/lifecycle*/,21/*vs/base/common/observable*/,65/*vs/base/common/observableInternal/derived*/,16/*vs/base/common/platform*/,30/*vs/base/common/themables*/,9/*vs/editor/common/core/position*/,27/*vs/editor/common/languages*/,245/*vs/editor/contrib/inlineCompletions/browser/controller/commandIds*/,3/*vs/nls*/,124/*vs/platform/actions/browser/menuEntryActionViewItem*/,218/*vs/platform/actions/browser/toolbar*/,29/*vs/platform/actions/common/actions*/,24/*vs/platform/commands/common/commands*/,12/*vs/platform/contextkey/common/contextkey*/,58/*vs/platform/contextview/browser/contextView*/,7/*vs/platform/instantiation/common/instantiation*/,31/*vs/platform/keybinding/common/keybinding*/,63/*vs/platform/telemetry/common/telemetry*/,71/*vs/platform/theme/common/iconRegistry*/,516/*vs/css!vs/editor/contrib/inlineCompletions/browser/hintsWidget/inlineCompletionsHintsWidget*/]), function (require, exports, dom_1, actionViewItems_1, keybindingLabel_1, actions_1, arrays_1, async_1, codicons_1, lifecycle_1, observable_1, derived_1, platform_1, themables_1, position_1, languages_1, commandIds_1, nls_1, menuEntryActionViewItem_1, toolbar_1, actions_2, commands_1, contextkey_1, contextView_1, instantiation_1, keybinding_1, telemetry_1, iconRegistry_1) {
    "use strict";
    var InlineSuggestionHintsContentWidget_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CustomizedMenuWorkbenchToolBar = exports.InlineSuggestionHintsContentWidget = exports.InlineCompletionsHintsWidget = void 0;
    let InlineCompletionsHintsWidget = class InlineCompletionsHintsWidget extends lifecycle_1.Disposable {
        constructor(editor, model, instantiationService) {
            super();
            this.editor = editor;
            this.model = model;
            this.instantiationService = instantiationService;
            this.alwaysShowToolbar = (0, observable_1.observableFromEvent)(this, this.editor.onDidChangeConfiguration, () => this.editor.getOption(62 /* EditorOption.inlineSuggest */).showToolbar === 'always');
            this.sessionPosition = undefined;
            this.position = (0, observable_1.derived)(this, reader => {
                const ghostText = this.model.read(reader)?.primaryGhostText.read(reader);
                if (!this.alwaysShowToolbar.read(reader) || !ghostText || ghostText.parts.length === 0) {
                    this.sessionPosition = undefined;
                    return null;
                }
                const firstColumn = ghostText.parts[0].column;
                if (this.sessionPosition && this.sessionPosition.lineNumber !== ghostText.lineNumber) {
                    this.sessionPosition = undefined;
                }
                const position = new position_1.Position(ghostText.lineNumber, Math.min(firstColumn, this.sessionPosition?.column ?? Number.MAX_SAFE_INTEGER));
                this.sessionPosition = position;
                return position;
            });
            this._register((0, observable_1.autorunWithStore)((reader, store) => {
                /** @description setup content widget */
                const model = this.model.read(reader);
                if (!model || !this.alwaysShowToolbar.read(reader)) {
                    return;
                }
                const contentWidgetValue = (0, derived_1.derivedWithStore)((reader, store) => {
                    const contentWidget = store.add(this.instantiationService.createInstance(InlineSuggestionHintsContentWidget, this.editor, true, this.position, model.selectedInlineCompletionIndex, model.inlineCompletionsCount, model.activeCommands));
                    editor.addContentWidget(contentWidget);
                    store.add((0, lifecycle_1.toDisposable)(() => editor.removeContentWidget(contentWidget)));
                    store.add((0, observable_1.autorun)(reader => {
                        /** @description request explicit */
                        const position = this.position.read(reader);
                        if (!position) {
                            return;
                        }
                        if (model.lastTriggerKind.read(reader) !== languages_1.InlineCompletionTriggerKind.Explicit) {
                            model.triggerExplicitly();
                        }
                    }));
                    return contentWidget;
                });
                const hadPosition = (0, observable_1.derivedObservableWithCache)(this, (reader, lastValue) => !!this.position.read(reader) || !!lastValue);
                store.add((0, observable_1.autorun)(reader => {
                    if (hadPosition.read(reader)) {
                        contentWidgetValue.read(reader);
                    }
                }));
            }));
        }
    };
    exports.InlineCompletionsHintsWidget = InlineCompletionsHintsWidget;
    exports.InlineCompletionsHintsWidget = InlineCompletionsHintsWidget = __decorate([
        __param(2, instantiation_1.IInstantiationService)
    ], InlineCompletionsHintsWidget);
    const inlineSuggestionHintsNextIcon = (0, iconRegistry_1.registerIcon)('inline-suggestion-hints-next', codicons_1.Codicon.chevronRight, (0, nls_1.localize)(1090, 'Icon for show next parameter hint.'));
    const inlineSuggestionHintsPreviousIcon = (0, iconRegistry_1.registerIcon)('inline-suggestion-hints-previous', codicons_1.Codicon.chevronLeft, (0, nls_1.localize)(1091, 'Icon for show previous parameter hint.'));
    let InlineSuggestionHintsContentWidget = class InlineSuggestionHintsContentWidget extends lifecycle_1.Disposable {
        static { InlineSuggestionHintsContentWidget_1 = this; }
        static { this._dropDownVisible = false; }
        static get dropDownVisible() { return this._dropDownVisible; }
        static { this.id = 0; }
        createCommandAction(commandId, label, iconClassName) {
            const action = new actions_1.Action(commandId, label, iconClassName, true, () => this._commandService.executeCommand(commandId));
            const kb = this.keybindingService.lookupKeybinding(commandId, this._contextKeyService);
            let tooltip = label;
            if (kb) {
                tooltip = (0, nls_1.localize)(1092, '{0} ({1})', label, kb.getLabel());
            }
            action.tooltip = tooltip;
            return action;
        }
        constructor(editor, withBorder, _position, _currentSuggestionIdx, _suggestionCount, _extraCommands, _commandService, instantiationService, keybindingService, _contextKeyService, _menuService) {
            super();
            this.editor = editor;
            this.withBorder = withBorder;
            this._position = _position;
            this._currentSuggestionIdx = _currentSuggestionIdx;
            this._suggestionCount = _suggestionCount;
            this._extraCommands = _extraCommands;
            this._commandService = _commandService;
            this.keybindingService = keybindingService;
            this._contextKeyService = _contextKeyService;
            this._menuService = _menuService;
            this.id = `InlineSuggestionHintsContentWidget${InlineSuggestionHintsContentWidget_1.id++}`;
            this.allowEditorOverflow = true;
            this.suppressMouseDown = false;
            this.nodes = (0, dom_1.h)('div.inlineSuggestionsHints', { className: this.withBorder ? '.withBorder' : '' }, [
                (0, dom_1.h)('div@toolBar'),
            ]);
            this.previousAction = this.createCommandAction(commandIds_1.showPreviousInlineSuggestionActionId, (0, nls_1.localize)(1093, 'Previous'), themables_1.ThemeIcon.asClassName(inlineSuggestionHintsPreviousIcon));
            this.availableSuggestionCountAction = new actions_1.Action('inlineSuggestionHints.availableSuggestionCount', '', undefined, false);
            this.nextAction = this.createCommandAction(commandIds_1.showNextInlineSuggestionActionId, (0, nls_1.localize)(1094, 'Next'), themables_1.ThemeIcon.asClassName(inlineSuggestionHintsNextIcon));
            // TODO@hediet: deprecate MenuId.InlineCompletionsActions
            this.inlineCompletionsActionsMenus = this._register(this._menuService.createMenu(actions_2.MenuId.InlineCompletionsActions, this._contextKeyService));
            this.clearAvailableSuggestionCountLabelDebounced = this._register(new async_1.RunOnceScheduler(() => {
                this.availableSuggestionCountAction.label = '';
            }, 100));
            this.disableButtonsDebounced = this._register(new async_1.RunOnceScheduler(() => {
                this.previousAction.enabled = this.nextAction.enabled = false;
            }, 100));
            this.toolBar = this._register(instantiationService.createInstance(CustomizedMenuWorkbenchToolBar, this.nodes.toolBar, actions_2.MenuId.InlineSuggestionToolbar, {
                menuOptions: { renderShortTitle: true },
                toolbarOptions: { primaryGroup: g => g.startsWith('primary') },
                actionViewItemProvider: (action, options) => {
                    if (action instanceof actions_2.MenuItemAction) {
                        return instantiationService.createInstance(StatusBarViewItem, action, undefined);
                    }
                    if (action === this.availableSuggestionCountAction) {
                        const a = new ActionViewItemWithClassName(undefined, action, { label: true, icon: false });
                        a.setClass('availableSuggestionCount');
                        return a;
                    }
                    return undefined;
                },
                telemetrySource: 'InlineSuggestionToolbar',
            }));
            this.toolBar.setPrependedPrimaryActions([
                this.previousAction,
                this.availableSuggestionCountAction,
                this.nextAction,
            ]);
            this._register(this.toolBar.onDidChangeDropdownVisibility(e => {
                InlineSuggestionHintsContentWidget_1._dropDownVisible = e;
            }));
            this._register((0, observable_1.autorun)(reader => {
                /** @description update position */
                this._position.read(reader);
                this.editor.layoutContentWidget(this);
            }));
            this._register((0, observable_1.autorun)(reader => {
                /** @description counts */
                const suggestionCount = this._suggestionCount.read(reader);
                const currentSuggestionIdx = this._currentSuggestionIdx.read(reader);
                if (suggestionCount !== undefined) {
                    this.clearAvailableSuggestionCountLabelDebounced.cancel();
                    this.availableSuggestionCountAction.label = `${currentSuggestionIdx + 1}/${suggestionCount}`;
                }
                else {
                    this.clearAvailableSuggestionCountLabelDebounced.schedule();
                }
                if (suggestionCount !== undefined && suggestionCount > 1) {
                    this.disableButtonsDebounced.cancel();
                    this.previousAction.enabled = this.nextAction.enabled = true;
                }
                else {
                    this.disableButtonsDebounced.schedule();
                }
            }));
            this._register((0, observable_1.autorun)(reader => {
                /** @description extra commands */
                const extraCommands = this._extraCommands.read(reader);
                const extraActions = extraCommands.map(c => ({
                    class: undefined,
                    id: c.id,
                    enabled: true,
                    tooltip: c.tooltip || '',
                    label: c.title,
                    run: (event) => {
                        return this._commandService.executeCommand(c.id);
                    },
                }));
                for (const [_, group] of this.inlineCompletionsActionsMenus.getActions()) {
                    for (const action of group) {
                        if (action instanceof actions_2.MenuItemAction) {
                            extraActions.push(action);
                        }
                    }
                }
                if (extraActions.length > 0) {
                    extraActions.unshift(new actions_1.Separator());
                }
                this.toolBar.setAdditionalSecondaryActions(extraActions);
            }));
        }
        getId() { return this.id; }
        getDomNode() {
            return this.nodes.root;
        }
        getPosition() {
            return {
                position: this._position.get(),
                preference: [1 /* ContentWidgetPositionPreference.ABOVE */, 2 /* ContentWidgetPositionPreference.BELOW */],
                positionAffinity: 3 /* PositionAffinity.LeftOfInjectedText */,
            };
        }
    };
    exports.InlineSuggestionHintsContentWidget = InlineSuggestionHintsContentWidget;
    exports.InlineSuggestionHintsContentWidget = InlineSuggestionHintsContentWidget = InlineSuggestionHintsContentWidget_1 = __decorate([
        __param(6, commands_1.ICommandService),
        __param(7, instantiation_1.IInstantiationService),
        __param(8, keybinding_1.IKeybindingService),
        __param(9, contextkey_1.IContextKeyService),
        __param(10, actions_2.IMenuService)
    ], InlineSuggestionHintsContentWidget);
    class ActionViewItemWithClassName extends actionViewItems_1.ActionViewItem {
        constructor() {
            super(...arguments);
            this._className = undefined;
        }
        setClass(className) {
            this._className = className;
        }
        render(container) {
            super.render(container);
            if (this._className) {
                container.classList.add(this._className);
            }
        }
        updateTooltip() {
            // NOOP, disable tooltip
        }
    }
    class StatusBarViewItem extends menuEntryActionViewItem_1.MenuEntryActionViewItem {
        updateLabel() {
            const kb = this._keybindingService.lookupKeybinding(this._action.id, this._contextKeyService);
            if (!kb) {
                return super.updateLabel();
            }
            if (this.label) {
                const div = (0, dom_1.h)('div.keybinding').root;
                const k = this._register(new keybindingLabel_1.KeybindingLabel(div, platform_1.OS, { disableTitle: true, ...keybindingLabel_1.unthemedKeybindingLabelOptions }));
                k.set(kb);
                this.label.textContent = this._action.label;
                this.label.appendChild(div);
                this.label.classList.add('inlineSuggestionStatusBarItemLabel');
            }
        }
        updateTooltip() {
            // NOOP, disable tooltip
        }
    }
    let CustomizedMenuWorkbenchToolBar = class CustomizedMenuWorkbenchToolBar extends toolbar_1.WorkbenchToolBar {
        constructor(container, menuId, options2, menuService, contextKeyService, contextMenuService, keybindingService, commandService, telemetryService) {
            super(container, { resetMenu: menuId, ...options2 }, menuService, contextKeyService, contextMenuService, keybindingService, commandService, telemetryService);
            this.menuId = menuId;
            this.options2 = options2;
            this.menuService = menuService;
            this.contextKeyService = contextKeyService;
            this.menu = this._store.add(this.menuService.createMenu(this.menuId, this.contextKeyService, { emitEventsForSubmenuChanges: true }));
            this.additionalActions = [];
            this.prependedPrimaryActions = [];
            this._store.add(this.menu.onDidChange(() => this.updateToolbar()));
            this.updateToolbar();
        }
        updateToolbar() {
            const primary = [];
            const secondary = [];
            (0, menuEntryActionViewItem_1.createAndFillInActionBarActions)(this.menu, this.options2?.menuOptions, { primary, secondary }, this.options2?.toolbarOptions?.primaryGroup, this.options2?.toolbarOptions?.shouldInlineSubmenu, this.options2?.toolbarOptions?.useSeparatorsInPrimaryActions);
            secondary.push(...this.additionalActions);
            primary.unshift(...this.prependedPrimaryActions);
            this.setActions(primary, secondary);
        }
        setPrependedPrimaryActions(actions) {
            if ((0, arrays_1.equals)(this.prependedPrimaryActions, actions, (a, b) => a === b)) {
                return;
            }
            this.prependedPrimaryActions = actions;
            this.updateToolbar();
        }
        setAdditionalSecondaryActions(actions) {
            if ((0, arrays_1.equals)(this.additionalActions, actions, (a, b) => a === b)) {
                return;
            }
            this.additionalActions = actions;
            this.updateToolbar();
        }
    };
    exports.CustomizedMenuWorkbenchToolBar = CustomizedMenuWorkbenchToolBar;
    exports.CustomizedMenuWorkbenchToolBar = CustomizedMenuWorkbenchToolBar = __decorate([
        __param(3, actions_2.IMenuService),
        __param(4, contextkey_1.IContextKeyService),
        __param(5, contextView_1.IContextMenuService),
        __param(6, keybinding_1.IKeybindingService),
        __param(7, commands_1.ICommandService),
        __param(8, telemetry_1.ITelemetryService)
    ], CustomizedMenuWorkbenchToolBar);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[800/*vs/editor/contrib/inlineEdit/browser/inlineEditHintsWidget*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,206/*vs/base/browser/ui/keybindingLabel/keybindingLabel*/,41/*vs/base/common/actions*/,13/*vs/base/common/arrays*/,2/*vs/base/common/lifecycle*/,21/*vs/base/common/observable*/,16/*vs/base/common/platform*/,9/*vs/editor/common/core/position*/,124/*vs/platform/actions/browser/menuEntryActionViewItem*/,218/*vs/platform/actions/browser/toolbar*/,29/*vs/platform/actions/common/actions*/,24/*vs/platform/commands/common/commands*/,12/*vs/platform/contextkey/common/contextkey*/,58/*vs/platform/contextview/browser/contextView*/,7/*vs/platform/instantiation/common/instantiation*/,31/*vs/platform/keybinding/common/keybinding*/,63/*vs/platform/telemetry/common/telemetry*/,519/*vs/css!vs/editor/contrib/inlineEdit/browser/inlineEditHintsWidget*/]), function (require, exports, dom_1, keybindingLabel_1, actions_1, arrays_1, lifecycle_1, observable_1, platform_1, position_1, menuEntryActionViewItem_1, toolbar_1, actions_2, commands_1, contextkey_1, contextView_1, instantiation_1, keybinding_1, telemetry_1) {
    "use strict";
    var InlineEditHintsContentWidget_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CustomizedMenuWorkbenchToolBar = exports.InlineEditHintsContentWidget = exports.InlineEditHintsWidget = void 0;
    let InlineEditHintsWidget = class InlineEditHintsWidget extends lifecycle_1.Disposable {
        constructor(editor, model, instantiationService) {
            super();
            this.editor = editor;
            this.model = model;
            this.instantiationService = instantiationService;
            this.alwaysShowToolbar = (0, observable_1.observableFromEvent)(this, this.editor.onDidChangeConfiguration, () => this.editor.getOption(63 /* EditorOption.inlineEdit */).showToolbar === 'always');
            this.sessionPosition = undefined;
            this.position = (0, observable_1.derived)(this, reader => {
                const ghostText = this.model.read(reader)?.model.ghostText.read(reader);
                if (!this.alwaysShowToolbar.read(reader) || !ghostText || ghostText.parts.length === 0) {
                    this.sessionPosition = undefined;
                    return null;
                }
                const firstColumn = ghostText.parts[0].column;
                if (this.sessionPosition && this.sessionPosition.lineNumber !== ghostText.lineNumber) {
                    this.sessionPosition = undefined;
                }
                const position = new position_1.Position(ghostText.lineNumber, Math.min(firstColumn, this.sessionPosition?.column ?? Number.MAX_SAFE_INTEGER));
                this.sessionPosition = position;
                return position;
            });
            this._register((0, observable_1.autorunWithStore)((reader, store) => {
                /** @description setup content widget */
                const model = this.model.read(reader);
                if (!model || !this.alwaysShowToolbar.read(reader)) {
                    return;
                }
                const contentWidget = store.add(this.instantiationService.createInstance(InlineEditHintsContentWidget, this.editor, true, this.position));
                editor.addContentWidget(contentWidget);
                store.add((0, lifecycle_1.toDisposable)(() => editor.removeContentWidget(contentWidget)));
            }));
        }
    };
    exports.InlineEditHintsWidget = InlineEditHintsWidget;
    exports.InlineEditHintsWidget = InlineEditHintsWidget = __decorate([
        __param(2, instantiation_1.IInstantiationService)
    ], InlineEditHintsWidget);
    let InlineEditHintsContentWidget = class InlineEditHintsContentWidget extends lifecycle_1.Disposable {
        static { InlineEditHintsContentWidget_1 = this; }
        static { this._dropDownVisible = false; }
        static { this.id = 0; }
        constructor(editor, withBorder, _position, instantiationService, _contextKeyService, _menuService) {
            super();
            this.editor = editor;
            this.withBorder = withBorder;
            this._position = _position;
            this._contextKeyService = _contextKeyService;
            this._menuService = _menuService;
            this.id = `InlineEditHintsContentWidget${InlineEditHintsContentWidget_1.id++}`;
            this.allowEditorOverflow = true;
            this.suppressMouseDown = false;
            this.nodes = (0, dom_1.h)('div.inlineEditHints', { className: this.withBorder ? '.withBorder' : '' }, [
                (0, dom_1.h)('div@toolBar'),
            ]);
            this.inlineCompletionsActionsMenus = this._register(this._menuService.createMenu(actions_2.MenuId.InlineEditActions, this._contextKeyService));
            this.toolBar = this._register(instantiationService.createInstance(CustomizedMenuWorkbenchToolBar, this.nodes.toolBar, this.editor, actions_2.MenuId.InlineEditToolbar, {
                menuOptions: { renderShortTitle: true },
                toolbarOptions: { primaryGroup: g => g.startsWith('primary') },
                actionViewItemProvider: (action, options) => {
                    if (action instanceof actions_2.MenuItemAction) {
                        return instantiationService.createInstance(StatusBarViewItem, action, undefined);
                    }
                    return undefined;
                },
                telemetrySource: 'InlineEditToolbar',
            }));
            this._register(this.toolBar.onDidChangeDropdownVisibility(e => {
                InlineEditHintsContentWidget_1._dropDownVisible = e;
            }));
            this._register((0, observable_1.autorun)(reader => {
                /** @description update position */
                this._position.read(reader);
                this.editor.layoutContentWidget(this);
            }));
            this._register((0, observable_1.autorun)(reader => {
                /** @description actions menu */
                const extraActions = [];
                for (const [_, group] of this.inlineCompletionsActionsMenus.getActions()) {
                    for (const action of group) {
                        if (action instanceof actions_2.MenuItemAction) {
                            extraActions.push(action);
                        }
                    }
                }
                if (extraActions.length > 0) {
                    extraActions.unshift(new actions_1.Separator());
                }
                this.toolBar.setAdditionalSecondaryActions(extraActions);
            }));
        }
        getId() { return this.id; }
        getDomNode() {
            return this.nodes.root;
        }
        getPosition() {
            return {
                position: this._position.get(),
                preference: [1 /* ContentWidgetPositionPreference.ABOVE */, 2 /* ContentWidgetPositionPreference.BELOW */],
                positionAffinity: 3 /* PositionAffinity.LeftOfInjectedText */,
            };
        }
    };
    exports.InlineEditHintsContentWidget = InlineEditHintsContentWidget;
    exports.InlineEditHintsContentWidget = InlineEditHintsContentWidget = InlineEditHintsContentWidget_1 = __decorate([
        __param(3, instantiation_1.IInstantiationService),
        __param(4, contextkey_1.IContextKeyService),
        __param(5, actions_2.IMenuService)
    ], InlineEditHintsContentWidget);
    class StatusBarViewItem extends menuEntryActionViewItem_1.MenuEntryActionViewItem {
        updateLabel() {
            const kb = this._keybindingService.lookupKeybinding(this._action.id, this._contextKeyService);
            if (!kb) {
                return super.updateLabel();
            }
            if (this.label) {
                const div = (0, dom_1.h)('div.keybinding').root;
                const k = this._register(new keybindingLabel_1.KeybindingLabel(div, platform_1.OS, { disableTitle: true, ...keybindingLabel_1.unthemedKeybindingLabelOptions }));
                k.set(kb);
                this.label.textContent = this._action.label;
                this.label.appendChild(div);
                this.label.classList.add('inlineEditStatusBarItemLabel');
            }
        }
        updateTooltip() {
            // NOOP, disable tooltip
        }
    }
    let CustomizedMenuWorkbenchToolBar = class CustomizedMenuWorkbenchToolBar extends toolbar_1.WorkbenchToolBar {
        constructor(container, editor, menuId, options2, menuService, contextKeyService, contextMenuService, keybindingService, commandService, telemetryService) {
            super(container, { resetMenu: menuId, ...options2 }, menuService, contextKeyService, contextMenuService, keybindingService, commandService, telemetryService);
            this.editor = editor;
            this.menuId = menuId;
            this.options2 = options2;
            this.menuService = menuService;
            this.contextKeyService = contextKeyService;
            this.menu = this._store.add(this.menuService.createMenu(this.menuId, this.contextKeyService, { emitEventsForSubmenuChanges: true }));
            this.additionalActions = [];
            this.prependedPrimaryActions = [];
            this._store.add(this.menu.onDidChange(() => this.updateToolbar()));
            this._store.add(this.editor.onDidChangeCursorPosition(() => this.updateToolbar()));
            this.updateToolbar();
        }
        updateToolbar() {
            const primary = [];
            const secondary = [];
            (0, menuEntryActionViewItem_1.createAndFillInActionBarActions)(this.menu, this.options2?.menuOptions, { primary, secondary }, this.options2?.toolbarOptions?.primaryGroup, this.options2?.toolbarOptions?.shouldInlineSubmenu, this.options2?.toolbarOptions?.useSeparatorsInPrimaryActions);
            secondary.push(...this.additionalActions);
            primary.unshift(...this.prependedPrimaryActions);
            this.setActions(primary, secondary);
        }
        setAdditionalSecondaryActions(actions) {
            if ((0, arrays_1.equals)(this.additionalActions, actions, (a, b) => a === b)) {
                return;
            }
            this.additionalActions = actions;
            this.updateToolbar();
        }
    };
    exports.CustomizedMenuWorkbenchToolBar = CustomizedMenuWorkbenchToolBar;
    exports.CustomizedMenuWorkbenchToolBar = CustomizedMenuWorkbenchToolBar = __decorate([
        __param(4, actions_2.IMenuService),
        __param(5, contextkey_1.IContextKeyService),
        __param(6, contextView_1.IContextMenuService),
        __param(7, keybinding_1.IKeybindingService),
        __param(8, commands_1.ICommandService),
        __param(9, telemetry_1.ITelemetryService)
    ], CustomizedMenuWorkbenchToolBar);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[801/*vs/platform/contextview/browser/contextMenuService*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,41/*vs/base/common/actions*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,124/*vs/platform/actions/browser/menuEntryActionViewItem*/,29/*vs/platform/actions/common/actions*/,12/*vs/platform/contextkey/common/contextkey*/,31/*vs/platform/keybinding/common/keybinding*/,50/*vs/platform/notification/common/notification*/,63/*vs/platform/telemetry/common/telemetry*/,761/*vs/platform/contextview/browser/contextMenuHandler*/,58/*vs/platform/contextview/browser/contextView*/]), function (require, exports, dom_1, actions_1, event_1, lifecycle_1, menuEntryActionViewItem_1, actions_2, contextkey_1, keybinding_1, notification_1, telemetry_1, contextMenuHandler_1, contextView_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ContextMenuMenuDelegate = exports.ContextMenuService = void 0;
    let ContextMenuService = class ContextMenuService extends lifecycle_1.Disposable {
        get contextMenuHandler() {
            if (!this._contextMenuHandler) {
                this._contextMenuHandler = new contextMenuHandler_1.ContextMenuHandler(this.contextViewService, this.telemetryService, this.notificationService, this.keybindingService);
            }
            return this._contextMenuHandler;
        }
        constructor(telemetryService, notificationService, contextViewService, keybindingService, menuService, contextKeyService) {
            super();
            this.telemetryService = telemetryService;
            this.notificationService = notificationService;
            this.contextViewService = contextViewService;
            this.keybindingService = keybindingService;
            this.menuService = menuService;
            this.contextKeyService = contextKeyService;
            this._contextMenuHandler = undefined;
            this._onDidShowContextMenu = this._store.add(new event_1.Emitter());
            this.onDidShowContextMenu = this._onDidShowContextMenu.event;
            this._onDidHideContextMenu = this._store.add(new event_1.Emitter());
        }
        configure(options) {
            this.contextMenuHandler.configure(options);
        }
        // ContextMenu
        showContextMenu(delegate) {
            delegate = ContextMenuMenuDelegate.transform(delegate, this.menuService, this.contextKeyService);
            this.contextMenuHandler.showContextMenu({
                ...delegate,
                onHide: (didCancel) => {
                    delegate.onHide?.(didCancel);
                    this._onDidHideContextMenu.fire();
                }
            });
            dom_1.ModifierKeyEmitter.getInstance().resetKeyStatus();
            this._onDidShowContextMenu.fire();
        }
    };
    exports.ContextMenuService = ContextMenuService;
    exports.ContextMenuService = ContextMenuService = __decorate([
        __param(0, telemetry_1.ITelemetryService),
        __param(1, notification_1.INotificationService),
        __param(2, contextView_1.IContextViewService),
        __param(3, keybinding_1.IKeybindingService),
        __param(4, actions_2.IMenuService),
        __param(5, contextkey_1.IContextKeyService)
    ], ContextMenuService);
    var ContextMenuMenuDelegate;
    (function (ContextMenuMenuDelegate) {
        function is(thing) {
            return thing && thing.menuId instanceof actions_2.MenuId;
        }
        function transform(delegate, menuService, globalContextKeyService) {
            if (!is(delegate)) {
                return delegate;
            }
            const { menuId, menuActionOptions, contextKeyService } = delegate;
            return {
                ...delegate,
                getActions: () => {
                    const target = [];
                    if (menuId) {
                        const menu = menuService.getMenuActions(menuId, contextKeyService ?? globalContextKeyService, menuActionOptions);
                        (0, menuEntryActionViewItem_1.createAndFillInContextMenuActions)(menu, target);
                    }
                    if (!delegate.getActions) {
                        return target;
                    }
                    else {
                        return actions_1.Separator.join(delegate.getActions(), target);
                    }
                }
            };
        }
        ContextMenuMenuDelegate.transform = transform;
    })(ContextMenuMenuDelegate || (exports.ContextMenuMenuDelegate = ContextMenuMenuDelegate = {}));
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[802/*vs/platform/quickinput/browser/quickInputTree*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,6/*vs/base/common/event*/,3/*vs/nls*/,7/*vs/platform/instantiation/common/instantiation*/,216/*vs/platform/list/browser/listService*/,25/*vs/platform/theme/common/themeService*/,2/*vs/base/common/lifecycle*/,66/*vs/platform/quickinput/common/quickInput*/,47/*vs/base/browser/keyboardEvent*/,16/*vs/base/common/platform*/,126/*vs/base/common/decorators*/,254/*vs/base/browser/ui/iconLabel/iconLabel*/,206/*vs/base/browser/ui/keybindingLabel/keybindingLabel*/,87/*vs/base/browser/ui/actionbar/actionbar*/,97/*vs/platform/theme/common/theme*/,22/*vs/base/common/uri*/,398/*vs/platform/quickinput/browser/quickInputUtils*/,98/*vs/base/common/lazy*/,142/*vs/base/common/iconLabels*/,445/*vs/base/common/comparers*/,11/*vs/base/common/strings*/,176/*vs/base/browser/ui/tree/abstractTree*/,14/*vs/base/common/async*/,8/*vs/base/common/errors*/,61/*vs/platform/accessibility/common/accessibility*/,21/*vs/base/common/observable*/,13/*vs/base/common/arrays*/]), function (require, exports, dom, event_1, nls_1, instantiation_1, listService_1, themeService_1, lifecycle_1, quickInput_1, keyboardEvent_1, platform_1, decorators_1, iconLabel_1, keybindingLabel_1, actionbar_1, theme_1, uri_1, quickInputUtils_1, lazy_1, iconLabels_1, comparers_1, strings_1, abstractTree_1, async_1, errors_1, accessibility_1, observable_1, arrays_1) {
    "use strict";
    var QuickPickItemElementRenderer_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.QuickInputTree = void 0;
    const $ = dom.$;
    class BaseQuickPickItemElement {
        constructor(index, hasCheckbox, mainItem) {
            this.index = index;
            this.hasCheckbox = hasCheckbox;
            this._hidden = false;
            this._init = new lazy_1.Lazy(() => {
                const saneLabel = mainItem.label ?? '';
                const saneSortLabel = (0, iconLabels_1.parseLabelWithIcons)(saneLabel).text.trim();
                const saneAriaLabel = mainItem.ariaLabel || [saneLabel, this.saneDescription, this.saneDetail]
                    .map(s => (0, iconLabels_1.getCodiconAriaLabel)(s))
                    .filter(s => !!s)
                    .join(', ');
                return {
                    saneLabel,
                    saneSortLabel,
                    saneAriaLabel
                };
            });
            this._saneDescription = mainItem.description;
            this._saneTooltip = mainItem.tooltip;
        }
        // #region Lazy Getters
        get saneLabel() {
            return this._init.value.saneLabel;
        }
        get saneSortLabel() {
            return this._init.value.saneSortLabel;
        }
        get saneAriaLabel() {
            return this._init.value.saneAriaLabel;
        }
        get element() {
            return this._element;
        }
        set element(value) {
            this._element = value;
        }
        get hidden() {
            return this._hidden;
        }
        set hidden(value) {
            this._hidden = value;
        }
        get saneDescription() {
            return this._saneDescription;
        }
        set saneDescription(value) {
            this._saneDescription = value;
        }
        get saneDetail() {
            return this._saneDetail;
        }
        set saneDetail(value) {
            this._saneDetail = value;
        }
        get saneTooltip() {
            return this._saneTooltip;
        }
        set saneTooltip(value) {
            this._saneTooltip = value;
        }
        get labelHighlights() {
            return this._labelHighlights;
        }
        set labelHighlights(value) {
            this._labelHighlights = value;
        }
        get descriptionHighlights() {
            return this._descriptionHighlights;
        }
        set descriptionHighlights(value) {
            this._descriptionHighlights = value;
        }
        get detailHighlights() {
            return this._detailHighlights;
        }
        set detailHighlights(value) {
            this._detailHighlights = value;
        }
    }
    class QuickPickItemElement extends BaseQuickPickItemElement {
        constructor(index, hasCheckbox, fireButtonTriggered, _onChecked, item, _separator) {
            super(index, hasCheckbox, item);
            this.fireButtonTriggered = fireButtonTriggered;
            this._onChecked = _onChecked;
            this.item = item;
            this._separator = _separator;
            this._checked = false;
            this.onChecked = hasCheckbox
                ? event_1.Event.map(event_1.Event.filter(this._onChecked.event, e => e.element === this), e => e.checked)
                : event_1.Event.None;
            this._saneDetail = item.detail;
            this._labelHighlights = item.highlights?.label;
            this._descriptionHighlights = item.highlights?.description;
            this._detailHighlights = item.highlights?.detail;
        }
        get separator() {
            return this._separator;
        }
        set separator(value) {
            this._separator = value;
        }
        get checked() {
            return this._checked;
        }
        set checked(value) {
            if (value !== this._checked) {
                this._checked = value;
                this._onChecked.fire({ element: this, checked: value });
            }
        }
        get checkboxDisabled() {
            return !!this.item.disabled;
        }
    }
    var QuickPickSeparatorFocusReason;
    (function (QuickPickSeparatorFocusReason) {
        /**
         * No item is hovered or active
         */
        QuickPickSeparatorFocusReason[QuickPickSeparatorFocusReason["NONE"] = 0] = "NONE";
        /**
         * Some item within this section is hovered
         */
        QuickPickSeparatorFocusReason[QuickPickSeparatorFocusReason["MOUSE_HOVER"] = 1] = "MOUSE_HOVER";
        /**
         * Some item within this section is active
         */
        QuickPickSeparatorFocusReason[QuickPickSeparatorFocusReason["ACTIVE_ITEM"] = 2] = "ACTIVE_ITEM";
    })(QuickPickSeparatorFocusReason || (QuickPickSeparatorFocusReason = {}));
    class QuickPickSeparatorElement extends BaseQuickPickItemElement {
        constructor(index, fireSeparatorButtonTriggered, separator) {
            super(index, false, separator);
            this.fireSeparatorButtonTriggered = fireSeparatorButtonTriggered;
            this.separator = separator;
            this.children = new Array();
            /**
             * If this item is >0, it means that there is some item in the list that is either:
             * * hovered over
             * * active
             */
            this.focusInsideSeparator = QuickPickSeparatorFocusReason.NONE;
        }
    }
    class QuickInputItemDelegate {
        getHeight(element) {
            if (element instanceof QuickPickSeparatorElement) {
                return 30;
            }
            return element.saneDetail ? 44 : 22;
        }
        getTemplateId(element) {
            if (element instanceof QuickPickItemElement) {
                return QuickPickItemElementRenderer.ID;
            }
            else {
                return QuickPickSeparatorElementRenderer.ID;
            }
        }
    }
    class QuickInputAccessibilityProvider {
        getWidgetAriaLabel() {
            return (0, nls_1.localize)(1597, "Quick Input");
        }
        getAriaLabel(element) {
            return element.separator?.label
                ? `${element.saneAriaLabel}, ${element.separator.label}`
                : element.saneAriaLabel;
        }
        getWidgetRole() {
            return 'listbox';
        }
        getRole(element) {
            return element.hasCheckbox ? 'checkbox' : 'option';
        }
        isChecked(element) {
            if (!element.hasCheckbox || !(element instanceof QuickPickItemElement)) {
                return undefined;
            }
            return {
                get value() { return element.checked; },
                onDidChange: e => element.onChecked(() => e()),
            };
        }
    }
    class BaseQuickInputListRenderer {
        constructor(hoverDelegate) {
            this.hoverDelegate = hoverDelegate;
        }
        // TODO: only do the common stuff here and have a subclass handle their specific stuff
        renderTemplate(container) {
            const data = Object.create(null);
            data.toDisposeElement = new lifecycle_1.DisposableStore();
            data.toDisposeTemplate = new lifecycle_1.DisposableStore();
            data.entry = dom.append(container, $('.quick-input-list-entry'));
            // Checkbox
            const label = dom.append(data.entry, $('label.quick-input-list-label'));
            data.toDisposeTemplate.add(dom.addStandardDisposableListener(label, dom.EventType.CLICK, e => {
                if (!data.checkbox.offsetParent) { // If checkbox not visible:
                    e.preventDefault(); // Prevent toggle of checkbox when it is immediately shown afterwards. #91740
                }
            }));
            data.checkbox = dom.append(label, $('input.quick-input-list-checkbox'));
            data.checkbox.type = 'checkbox';
            // Rows
            const rows = dom.append(label, $('.quick-input-list-rows'));
            const row1 = dom.append(rows, $('.quick-input-list-row'));
            const row2 = dom.append(rows, $('.quick-input-list-row'));
            // Label
            data.label = new iconLabel_1.IconLabel(row1, { supportHighlights: true, supportDescriptionHighlights: true, supportIcons: true, hoverDelegate: this.hoverDelegate });
            data.toDisposeTemplate.add(data.label);
            data.icon = dom.prepend(data.label.element, $('.quick-input-list-icon'));
            // Keybinding
            const keybindingContainer = dom.append(row1, $('.quick-input-list-entry-keybinding'));
            data.keybinding = new keybindingLabel_1.KeybindingLabel(keybindingContainer, platform_1.OS);
            data.toDisposeTemplate.add(data.keybinding);
            // Detail
            const detailContainer = dom.append(row2, $('.quick-input-list-label-meta'));
            data.detail = new iconLabel_1.IconLabel(detailContainer, { supportHighlights: true, supportIcons: true, hoverDelegate: this.hoverDelegate });
            data.toDisposeTemplate.add(data.detail);
            // Separator
            data.separator = dom.append(data.entry, $('.quick-input-list-separator'));
            // Actions
            data.actionBar = new actionbar_1.ActionBar(data.entry, this.hoverDelegate ? { hoverDelegate: this.hoverDelegate } : undefined);
            data.actionBar.domNode.classList.add('quick-input-list-entry-action-bar');
            data.toDisposeTemplate.add(data.actionBar);
            return data;
        }
        disposeTemplate(data) {
            data.toDisposeElement.dispose();
            data.toDisposeTemplate.dispose();
        }
        disposeElement(_element, _index, data) {
            data.toDisposeElement.clear();
            data.actionBar.clear();
        }
    }
    let QuickPickItemElementRenderer = class QuickPickItemElementRenderer extends BaseQuickInputListRenderer {
        static { QuickPickItemElementRenderer_1 = this; }
        static { this.ID = 'quickpickitem'; }
        constructor(hoverDelegate, themeService) {
            super(hoverDelegate);
            this.themeService = themeService;
            // Follow what we do in the separator renderer
            this._itemsWithSeparatorsFrequency = new Map();
        }
        get templateId() {
            return QuickPickItemElementRenderer_1.ID;
        }
        renderTemplate(container) {
            const data = super.renderTemplate(container);
            data.toDisposeTemplate.add(dom.addStandardDisposableListener(data.checkbox, dom.EventType.CHANGE, e => {
                data.element.checked = data.checkbox.checked;
            }));
            return data;
        }
        renderElement(node, index, data) {
            const element = node.element;
            data.element = element;
            element.element = data.entry ?? undefined;
            const mainItem = element.item;
            data.checkbox.checked = element.checked;
            data.toDisposeElement.add(element.onChecked(checked => data.checkbox.checked = checked));
            data.checkbox.disabled = element.checkboxDisabled;
            const { labelHighlights, descriptionHighlights, detailHighlights } = element;
            // Icon
            if (mainItem.iconPath) {
                const icon = (0, theme_1.isDark)(this.themeService.getColorTheme().type) ? mainItem.iconPath.dark : (mainItem.iconPath.light ?? mainItem.iconPath.dark);
                const iconUrl = uri_1.URI.revive(icon);
                data.icon.className = 'quick-input-list-icon';
                data.icon.style.backgroundImage = dom.asCSSUrl(iconUrl);
            }
            else {
                data.icon.style.backgroundImage = '';
                data.icon.className = mainItem.iconClass ? `quick-input-list-icon ${mainItem.iconClass}` : '';
            }
            // Label
            let descriptionTitle;
            // if we have a tooltip, that will be the hover,
            // with the saneDescription as fallback if it
            // is defined
            if (!element.saneTooltip && element.saneDescription) {
                descriptionTitle = {
                    markdown: {
                        value: element.saneDescription,
                        supportThemeIcons: true
                    },
                    markdownNotSupportedFallback: element.saneDescription
                };
            }
            const options = {
                matches: labelHighlights || [],
                // If we have a tooltip, we want that to be shown and not any other hover
                descriptionTitle,
                descriptionMatches: descriptionHighlights || [],
                labelEscapeNewLines: true
            };
            options.extraClasses = mainItem.iconClasses;
            options.italic = mainItem.italic;
            options.strikethrough = mainItem.strikethrough;
            data.entry.classList.remove('quick-input-list-separator-as-item');
            data.label.setLabel(element.saneLabel, element.saneDescription, options);
            // Keybinding
            data.keybinding.set(mainItem.keybinding);
            // Detail
            if (element.saneDetail) {
                let title;
                // If we have a tooltip, we want that to be shown and not any other hover
                if (!element.saneTooltip) {
                    title = {
                        markdown: {
                            value: element.saneDetail,
                            supportThemeIcons: true
                        },
                        markdownNotSupportedFallback: element.saneDetail
                    };
                }
                data.detail.element.style.display = '';
                data.detail.setLabel(element.saneDetail, undefined, {
                    matches: detailHighlights,
                    title,
                    labelEscapeNewLines: true
                });
            }
            else {
                data.detail.element.style.display = 'none';
            }
            // Separator
            if (element.separator?.label) {
                data.separator.textContent = element.separator.label;
                data.separator.style.display = '';
                this.addItemWithSeparator(element);
            }
            else {
                data.separator.style.display = 'none';
            }
            data.entry.classList.toggle('quick-input-list-separator-border', !!element.separator);
            // Actions
            const buttons = mainItem.buttons;
            if (buttons && buttons.length) {
                data.actionBar.push(buttons.map((button, index) => (0, quickInputUtils_1.quickInputButtonToAction)(button, `id-${index}`, () => element.fireButtonTriggered({ button, item: element.item }))), { icon: true, label: false });
                data.entry.classList.add('has-actions');
            }
            else {
                data.entry.classList.remove('has-actions');
            }
        }
        disposeElement(element, _index, data) {
            this.removeItemWithSeparator(element.element);
            super.disposeElement(element, _index, data);
        }
        isItemWithSeparatorVisible(item) {
            return this._itemsWithSeparatorsFrequency.has(item);
        }
        addItemWithSeparator(item) {
            this._itemsWithSeparatorsFrequency.set(item, (this._itemsWithSeparatorsFrequency.get(item) || 0) + 1);
        }
        removeItemWithSeparator(item) {
            const frequency = this._itemsWithSeparatorsFrequency.get(item) || 0;
            if (frequency > 1) {
                this._itemsWithSeparatorsFrequency.set(item, frequency - 1);
            }
            else {
                this._itemsWithSeparatorsFrequency.delete(item);
            }
        }
    };
    QuickPickItemElementRenderer = QuickPickItemElementRenderer_1 = __decorate([
        __param(1, themeService_1.IThemeService)
    ], QuickPickItemElementRenderer);
    class QuickPickSeparatorElementRenderer extends BaseQuickInputListRenderer {
        constructor() {
            super(...arguments);
            // This is a frequency map because sticky scroll re-uses the same renderer to render a second
            // instance of the same separator.
            this._visibleSeparatorsFrequency = new Map();
        }
        static { this.ID = 'quickpickseparator'; }
        get templateId() {
            return QuickPickSeparatorElementRenderer.ID;
        }
        get visibleSeparators() {
            return [...this._visibleSeparatorsFrequency.keys()];
        }
        isSeparatorVisible(separator) {
            return this._visibleSeparatorsFrequency.has(separator);
        }
        renderTemplate(container) {
            const data = super.renderTemplate(container);
            data.checkbox.style.display = 'none';
            return data;
        }
        renderElement(node, index, data) {
            const element = node.element;
            data.element = element;
            element.element = data.entry ?? undefined;
            element.element.classList.toggle('focus-inside', !!element.focusInsideSeparator);
            const mainItem = element.separator;
            const { labelHighlights, descriptionHighlights, detailHighlights } = element;
            // Icon
            data.icon.style.backgroundImage = '';
            data.icon.className = '';
            // Label
            let descriptionTitle;
            // if we have a tooltip, that will be the hover,
            // with the saneDescription as fallback if it
            // is defined
            if (!element.saneTooltip && element.saneDescription) {
                descriptionTitle = {
                    markdown: {
                        value: element.saneDescription,
                        supportThemeIcons: true
                    },
                    markdownNotSupportedFallback: element.saneDescription
                };
            }
            const options = {
                matches: labelHighlights || [],
                // If we have a tooltip, we want that to be shown and not any other hover
                descriptionTitle,
                descriptionMatches: descriptionHighlights || [],
                labelEscapeNewLines: true
            };
            data.entry.classList.add('quick-input-list-separator-as-item');
            data.label.setLabel(element.saneLabel, element.saneDescription, options);
            // Detail
            if (element.saneDetail) {
                let title;
                // If we have a tooltip, we want that to be shown and not any other hover
                if (!element.saneTooltip) {
                    title = {
                        markdown: {
                            value: element.saneDetail,
                            supportThemeIcons: true
                        },
                        markdownNotSupportedFallback: element.saneDetail
                    };
                }
                data.detail.element.style.display = '';
                data.detail.setLabel(element.saneDetail, undefined, {
                    matches: detailHighlights,
                    title,
                    labelEscapeNewLines: true
                });
            }
            else {
                data.detail.element.style.display = 'none';
            }
            // Separator
            data.separator.style.display = 'none';
            data.entry.classList.add('quick-input-list-separator-border');
            // Actions
            const buttons = mainItem.buttons;
            if (buttons && buttons.length) {
                data.actionBar.push(buttons.map((button, index) => (0, quickInputUtils_1.quickInputButtonToAction)(button, `id-${index}`, () => element.fireSeparatorButtonTriggered({ button, separator: element.separator }))), { icon: true, label: false });
                data.entry.classList.add('has-actions');
            }
            else {
                data.entry.classList.remove('has-actions');
            }
            this.addSeparator(element);
        }
        disposeElement(element, _index, data) {
            this.removeSeparator(element.element);
            if (!this.isSeparatorVisible(element.element)) {
                element.element.element?.classList.remove('focus-inside');
            }
            super.disposeElement(element, _index, data);
        }
        addSeparator(separator) {
            this._visibleSeparatorsFrequency.set(separator, (this._visibleSeparatorsFrequency.get(separator) || 0) + 1);
        }
        removeSeparator(separator) {
            const frequency = this._visibleSeparatorsFrequency.get(separator) || 0;
            if (frequency > 1) {
                this._visibleSeparatorsFrequency.set(separator, frequency - 1);
            }
            else {
                this._visibleSeparatorsFrequency.delete(separator);
            }
        }
    }
    let QuickInputTree = class QuickInputTree extends lifecycle_1.Disposable {
        constructor(parent, hoverDelegate, linkOpenerDelegate, id, instantiationService, accessibilityService) {
            super();
            this.parent = parent;
            this.hoverDelegate = hoverDelegate;
            this.linkOpenerDelegate = linkOpenerDelegate;
            this.accessibilityService = accessibilityService;
            //#region QuickInputTree Events
            this._onKeyDown = new event_1.Emitter();
            this._onLeave = new event_1.Emitter();
            /**
             * Event that is fired when the tree would no longer have focus.
            */
            this.onLeave = this._onLeave.event;
            this._visibleCountObservable = (0, observable_1.observableValue)('VisibleCount', 0);
            this.onChangedVisibleCount = event_1.Event.fromObservable(this._visibleCountObservable, this._store);
            this._allVisibleCheckedObservable = (0, observable_1.observableValue)('AllVisibleChecked', false);
            this.onChangedAllVisibleChecked = event_1.Event.fromObservable(this._allVisibleCheckedObservable, this._store);
            this._checkedCountObservable = (0, observable_1.observableValue)('CheckedCount', 0);
            this.onChangedCheckedCount = event_1.Event.fromObservable(this._checkedCountObservable, this._store);
            this._checkedElementsObservable = (0, observable_1.observableValueOpts)({ equalsFn: arrays_1.equals }, new Array());
            this.onChangedCheckedElements = event_1.Event.fromObservable(this._checkedElementsObservable, this._store);
            this._onButtonTriggered = new event_1.Emitter();
            this.onButtonTriggered = this._onButtonTriggered.event;
            this._onSeparatorButtonTriggered = new event_1.Emitter();
            this.onSeparatorButtonTriggered = this._onSeparatorButtonTriggered.event;
            this._elementChecked = new event_1.Emitter();
            this._elementCheckedEventBufferer = new event_1.EventBufferer();
            //#endregion
            this._hasCheckboxes = false;
            this._inputElements = new Array();
            this._elementTree = new Array();
            this._itemElements = new Array();
            // Elements that apply to the current set of elements
            this._elementDisposable = this._register(new lifecycle_1.DisposableStore());
            this._matchOnDescription = false;
            this._matchOnDetail = false;
            this._matchOnLabel = true;
            this._matchOnLabelMode = 'fuzzy';
            this._sortByLabel = true;
            this._shouldLoop = true;
            this._container = dom.append(this.parent, $('.quick-input-list'));
            this._separatorRenderer = new QuickPickSeparatorElementRenderer(hoverDelegate);
            this._itemRenderer = instantiationService.createInstance(QuickPickItemElementRenderer, hoverDelegate);
            this._tree = this._register(instantiationService.createInstance((listService_1.WorkbenchObjectTree), 'QuickInput', this._container, new QuickInputItemDelegate(), [this._itemRenderer, this._separatorRenderer], {
                filter: {
                    filter(element) {
                        return element.hidden
                            ? 0 /* TreeVisibility.Hidden */
                            : element instanceof QuickPickSeparatorElement
                                ? 2 /* TreeVisibility.Recurse */
                                : 1 /* TreeVisibility.Visible */;
                    },
                },
                sorter: {
                    compare: (element, otherElement) => {
                        if (!this.sortByLabel || !this._lastQueryString) {
                            return 0;
                        }
                        const normalizedSearchValue = this._lastQueryString.toLowerCase();
                        return compareEntries(element, otherElement, normalizedSearchValue);
                    },
                },
                accessibilityProvider: new QuickInputAccessibilityProvider(),
                setRowLineHeight: false,
                multipleSelectionSupport: false,
                hideTwistiesOfChildlessElements: true,
                renderIndentGuides: abstractTree_1.RenderIndentGuides.None,
                findWidgetEnabled: false,
                indent: 0,
                horizontalScrolling: false,
                allowNonCollapsibleParents: true,
                alwaysConsumeMouseWheel: true
            }));
            this._tree.getHTMLElement().id = id;
            this._registerListeners();
        }
        //#region public getters/setters
        get onDidChangeFocus() {
            return event_1.Event.map(this._tree.onDidChangeFocus, e => e.elements.filter((e) => e instanceof QuickPickItemElement).map(e => e.item), this._store);
        }
        get onDidChangeSelection() {
            return event_1.Event.map(this._tree.onDidChangeSelection, e => ({
                items: e.elements.filter((e) => e instanceof QuickPickItemElement).map(e => e.item),
                event: e.browserEvent
            }), this._store);
        }
        get displayed() {
            return this._container.style.display !== 'none';
        }
        set displayed(value) {
            this._container.style.display = value ? '' : 'none';
        }
        get scrollTop() {
            return this._tree.scrollTop;
        }
        set scrollTop(scrollTop) {
            this._tree.scrollTop = scrollTop;
        }
        get ariaLabel() {
            return this._tree.ariaLabel;
        }
        set ariaLabel(label) {
            this._tree.ariaLabel = label ?? '';
        }
        set enabled(value) {
            this._tree.getHTMLElement().style.pointerEvents = value ? '' : 'none';
        }
        get matchOnDescription() {
            return this._matchOnDescription;
        }
        set matchOnDescription(value) {
            this._matchOnDescription = value;
        }
        get matchOnDetail() {
            return this._matchOnDetail;
        }
        set matchOnDetail(value) {
            this._matchOnDetail = value;
        }
        get matchOnLabel() {
            return this._matchOnLabel;
        }
        set matchOnLabel(value) {
            this._matchOnLabel = value;
        }
        get matchOnLabelMode() {
            return this._matchOnLabelMode;
        }
        set matchOnLabelMode(value) {
            this._matchOnLabelMode = value;
        }
        get sortByLabel() {
            return this._sortByLabel;
        }
        set sortByLabel(value) {
            this._sortByLabel = value;
        }
        get shouldLoop() {
            return this._shouldLoop;
        }
        set shouldLoop(value) {
            this._shouldLoop = value;
        }
        //#endregion
        //#region register listeners
        _registerListeners() {
            this._registerOnKeyDown();
            this._registerOnContainerClick();
            this._registerOnMouseMiddleClick();
            this._registerOnTreeModelChanged();
            this._registerOnElementChecked();
            this._registerOnContextMenu();
            this._registerHoverListeners();
            this._registerSelectionChangeListener();
            this._registerSeparatorActionShowingListeners();
        }
        _registerOnKeyDown() {
            // TODO: Should this be added at a higher level?
            this._register(this._tree.onKeyDown(e => {
                const event = new keyboardEvent_1.StandardKeyboardEvent(e);
                switch (event.keyCode) {
                    case 10 /* KeyCode.Space */:
                        this.toggleCheckbox();
                        break;
                }
                this._onKeyDown.fire(event);
            }));
        }
        _registerOnContainerClick() {
            this._register(dom.addDisposableListener(this._container, dom.EventType.CLICK, e => {
                if (e.x || e.y) { // Avoid 'click' triggered by 'space' on checkbox.
                    this._onLeave.fire();
                }
            }));
        }
        _registerOnMouseMiddleClick() {
            this._register(dom.addDisposableListener(this._container, dom.EventType.AUXCLICK, e => {
                if (e.button === 1) {
                    this._onLeave.fire();
                }
            }));
        }
        _registerOnTreeModelChanged() {
            this._register(this._tree.onDidChangeModel(() => {
                const visibleCount = this._itemElements.filter(e => !e.hidden).length;
                this._visibleCountObservable.set(visibleCount, undefined);
                if (this._hasCheckboxes) {
                    this._updateCheckedObservables();
                }
            }));
        }
        _registerOnElementChecked() {
            // Only fire the last event when buffered
            this._register(this._elementCheckedEventBufferer.wrapEvent(this._elementChecked.event, (_, e) => e)(_ => this._updateCheckedObservables()));
        }
        _registerOnContextMenu() {
            this._register(this._tree.onContextMenu(e => {
                if (e.element) {
                    e.browserEvent.preventDefault();
                    // we want to treat a context menu event as
                    // a gesture to open the item at the index
                    // since we do not have any context menu
                    // this enables for example macOS to Ctrl-
                    // click on an item to open it.
                    this._tree.setSelection([e.element]);
                }
            }));
        }
        _registerHoverListeners() {
            const delayer = this._register(new async_1.ThrottledDelayer(this.hoverDelegate.delay));
            this._register(this._tree.onMouseOver(async (e) => {
                // If we hover over an anchor element, we don't want to show the hover because
                // the anchor may have a tooltip that we want to show instead.
                if (dom.isHTMLAnchorElement(e.browserEvent.target)) {
                    delayer.cancel();
                    return;
                }
                if (
                // anchors are an exception as called out above so we skip them here
                !(dom.isHTMLAnchorElement(e.browserEvent.relatedTarget)) &&
                    // check if the mouse is still over the same element
                    dom.isAncestor(e.browserEvent.relatedTarget, e.element?.element)) {
                    return;
                }
                try {
                    await delayer.trigger(async () => {
                        if (e.element instanceof QuickPickItemElement) {
                            this.showHover(e.element);
                        }
                    });
                }
                catch (e) {
                    // Ignore cancellation errors due to mouse out
                    if (!(0, errors_1.isCancellationError)(e)) {
                        throw e;
                    }
                }
            }));
            this._register(this._tree.onMouseOut(e => {
                // onMouseOut triggers every time a new element has been moused over
                // even if it's on the same list item. We only want one event, so we
                // check if the mouse is still over the same element.
                if (dom.isAncestor(e.browserEvent.relatedTarget, e.element?.element)) {
                    return;
                }
                delayer.cancel();
            }));
        }
        /**
         * Register's focus change and mouse events so that we can track when items inside of a
         * separator's section are focused or hovered so that we can display the separator's actions
         */
        _registerSeparatorActionShowingListeners() {
            this._register(this._tree.onDidChangeFocus(e => {
                const parent = e.elements[0]
                    ? this._tree.getParentElement(e.elements[0])
                    // treat null as focus lost and when we have no separators
                    : null;
                for (const separator of this._separatorRenderer.visibleSeparators) {
                    const value = separator === parent;
                    // get bitness of ACTIVE_ITEM and check if it changed
                    const currentActive = !!(separator.focusInsideSeparator & QuickPickSeparatorFocusReason.ACTIVE_ITEM);
                    if (currentActive !== value) {
                        if (value) {
                            separator.focusInsideSeparator |= QuickPickSeparatorFocusReason.ACTIVE_ITEM;
                        }
                        else {
                            separator.focusInsideSeparator &= ~QuickPickSeparatorFocusReason.ACTIVE_ITEM;
                        }
                        this._tree.rerender(separator);
                    }
                }
            }));
            this._register(this._tree.onMouseOver(e => {
                const parent = e.element
                    ? this._tree.getParentElement(e.element)
                    : null;
                for (const separator of this._separatorRenderer.visibleSeparators) {
                    if (separator !== parent) {
                        continue;
                    }
                    const currentMouse = !!(separator.focusInsideSeparator & QuickPickSeparatorFocusReason.MOUSE_HOVER);
                    if (!currentMouse) {
                        separator.focusInsideSeparator |= QuickPickSeparatorFocusReason.MOUSE_HOVER;
                        this._tree.rerender(separator);
                    }
                }
            }));
            this._register(this._tree.onMouseOut(e => {
                const parent = e.element
                    ? this._tree.getParentElement(e.element)
                    : null;
                for (const separator of this._separatorRenderer.visibleSeparators) {
                    if (separator !== parent) {
                        continue;
                    }
                    const currentMouse = !!(separator.focusInsideSeparator & QuickPickSeparatorFocusReason.MOUSE_HOVER);
                    if (currentMouse) {
                        separator.focusInsideSeparator &= ~QuickPickSeparatorFocusReason.MOUSE_HOVER;
                        this._tree.rerender(separator);
                    }
                }
            }));
        }
        _registerSelectionChangeListener() {
            // When the user selects a separator, the separator will move to the top and focus will be
            // set to the first element after the separator.
            this._register(this._tree.onDidChangeSelection(e => {
                const elementsWithoutSeparators = e.elements.filter((e) => e instanceof QuickPickItemElement);
                if (elementsWithoutSeparators.length !== e.elements.length) {
                    if (e.elements.length === 1 && e.elements[0] instanceof QuickPickSeparatorElement) {
                        this._tree.setFocus([e.elements[0].children[0]]);
                        this._tree.reveal(e.elements[0], 0);
                    }
                    this._tree.setSelection(elementsWithoutSeparators);
                }
            }));
        }
        //#endregion
        //#region public methods
        setAllVisibleChecked(checked) {
            this._elementCheckedEventBufferer.bufferEvents(() => {
                this._itemElements.forEach(element => {
                    if (!element.hidden && !element.checkboxDisabled) {
                        // Would fire an event if we didn't beffer the events
                        element.checked = checked;
                    }
                });
            });
        }
        setElements(inputElements) {
            this._elementDisposable.clear();
            this._lastQueryString = undefined;
            this._inputElements = inputElements;
            this._hasCheckboxes = this.parent.classList.contains('show-checkboxes');
            let currentSeparatorElement;
            this._itemElements = new Array();
            this._elementTree = inputElements.reduce((result, item, index) => {
                let element;
                if (item.type === 'separator') {
                    if (!item.buttons) {
                        // This separator will be rendered as a part of the list item
                        return result;
                    }
                    currentSeparatorElement = new QuickPickSeparatorElement(index, e => this._onSeparatorButtonTriggered.fire(e), item);
                    element = currentSeparatorElement;
                }
                else {
                    const previous = index > 0 ? inputElements[index - 1] : undefined;
                    let separator;
                    if (previous && previous.type === 'separator' && !previous.buttons) {
                        // Found an inline separator so we clear out the current separator element
                        currentSeparatorElement = undefined;
                        separator = previous;
                    }
                    const qpi = new QuickPickItemElement(index, this._hasCheckboxes, e => this._onButtonTriggered.fire(e), this._elementChecked, item, separator);
                    this._itemElements.push(qpi);
                    if (currentSeparatorElement) {
                        currentSeparatorElement.children.push(qpi);
                        return result;
                    }
                    element = qpi;
                }
                result.push(element);
                return result;
            }, new Array());
            this._setElementsToTree(this._elementTree);
            // Accessibility hack, unfortunately on next tick
            // https://github.com/microsoft/vscode/issues/211976
            if (this.accessibilityService.isScreenReaderOptimized()) {
                setTimeout(() => {
                    const focusedElement = this._tree.getHTMLElement().querySelector(`.monaco-list-row.focused`);
                    const parent = focusedElement?.parentNode;
                    if (focusedElement && parent) {
                        const nextSibling = focusedElement.nextSibling;
                        focusedElement.remove();
                        parent.insertBefore(focusedElement, nextSibling);
                    }
                }, 0);
            }
        }
        setFocusedElements(items) {
            const elements = items.map(item => this._itemElements.find(e => e.item === item))
                .filter((e) => !!e)
                .filter(e => !e.hidden);
            this._tree.setFocus(elements);
            if (items.length > 0) {
                const focused = this._tree.getFocus()[0];
                if (focused) {
                    this._tree.reveal(focused);
                }
            }
        }
        getActiveDescendant() {
            return this._tree.getHTMLElement().getAttribute('aria-activedescendant');
        }
        setSelectedElements(items) {
            const elements = items.map(item => this._itemElements.find(e => e.item === item))
                .filter((e) => !!e);
            this._tree.setSelection(elements);
        }
        getCheckedElements() {
            return this._itemElements.filter(e => e.checked)
                .map(e => e.item);
        }
        setCheckedElements(items) {
            this._elementCheckedEventBufferer.bufferEvents(() => {
                const checked = new Set();
                for (const item of items) {
                    checked.add(item);
                }
                for (const element of this._itemElements) {
                    // Would fire an event if we didn't beffer the events
                    element.checked = checked.has(element.item);
                }
            });
        }
        focus(what) {
            if (!this._itemElements.length) {
                return;
            }
            if (what === quickInput_1.QuickPickFocus.Second && this._itemElements.length < 2) {
                what = quickInput_1.QuickPickFocus.First;
            }
            switch (what) {
                case quickInput_1.QuickPickFocus.First:
                    this._tree.scrollTop = 0;
                    this._tree.focusFirst(undefined, (e) => e.element instanceof QuickPickItemElement);
                    break;
                case quickInput_1.QuickPickFocus.Second: {
                    this._tree.scrollTop = 0;
                    let isSecondItem = false;
                    this._tree.focusFirst(undefined, (e) => {
                        if (!(e.element instanceof QuickPickItemElement)) {
                            return false;
                        }
                        if (isSecondItem) {
                            return true;
                        }
                        isSecondItem = !isSecondItem;
                        return false;
                    });
                    break;
                }
                case quickInput_1.QuickPickFocus.Last:
                    this._tree.scrollTop = this._tree.scrollHeight;
                    this._tree.focusLast(undefined, (e) => e.element instanceof QuickPickItemElement);
                    break;
                case quickInput_1.QuickPickFocus.Next: {
                    const prevFocus = this._tree.getFocus();
                    this._tree.focusNext(undefined, this._shouldLoop, undefined, (e) => {
                        if (!(e.element instanceof QuickPickItemElement)) {
                            return false;
                        }
                        this._tree.reveal(e.element);
                        return true;
                    });
                    const currentFocus = this._tree.getFocus();
                    if (prevFocus.length && prevFocus[0] === currentFocus[0] && prevFocus[0] === this._itemElements[this._itemElements.length - 1]) {
                        this._onLeave.fire();
                    }
                    break;
                }
                case quickInput_1.QuickPickFocus.Previous: {
                    const prevFocus = this._tree.getFocus();
                    this._tree.focusPrevious(undefined, this._shouldLoop, undefined, (e) => {
                        if (!(e.element instanceof QuickPickItemElement)) {
                            return false;
                        }
                        const parent = this._tree.getParentElement(e.element);
                        if (parent === null || parent.children[0] !== e.element) {
                            this._tree.reveal(e.element);
                        }
                        else {
                            // Only if we are the first child of a separator do we reveal the separator
                            this._tree.reveal(parent);
                        }
                        return true;
                    });
                    const currentFocus = this._tree.getFocus();
                    if (prevFocus.length && prevFocus[0] === currentFocus[0] && prevFocus[0] === this._itemElements[0]) {
                        this._onLeave.fire();
                    }
                    break;
                }
                case quickInput_1.QuickPickFocus.NextPage:
                    this._tree.focusNextPage(undefined, (e) => {
                        if (!(e.element instanceof QuickPickItemElement)) {
                            return false;
                        }
                        this._tree.reveal(e.element);
                        return true;
                    });
                    break;
                case quickInput_1.QuickPickFocus.PreviousPage:
                    this._tree.focusPreviousPage(undefined, (e) => {
                        if (!(e.element instanceof QuickPickItemElement)) {
                            return false;
                        }
                        const parent = this._tree.getParentElement(e.element);
                        if (parent === null || parent.children[0] !== e.element) {
                            this._tree.reveal(e.element);
                        }
                        else {
                            this._tree.reveal(parent);
                        }
                        return true;
                    });
                    break;
                case quickInput_1.QuickPickFocus.NextSeparator: {
                    let foundSeparatorAsItem = false;
                    const before = this._tree.getFocus()[0];
                    this._tree.focusNext(undefined, true, undefined, (e) => {
                        if (foundSeparatorAsItem) {
                            // This should be the index right after the separator so it
                            // is the item we want to focus.
                            return true;
                        }
                        if (e.element instanceof QuickPickSeparatorElement) {
                            foundSeparatorAsItem = true;
                            // If the separator is visible, then we should just reveal its first child so it's not as jarring.
                            if (this._separatorRenderer.isSeparatorVisible(e.element)) {
                                this._tree.reveal(e.element.children[0]);
                            }
                            else {
                                // If the separator is not visible, then we should
                                // push it up to the top of the list.
                                this._tree.reveal(e.element, 0);
                            }
                        }
                        else if (e.element instanceof QuickPickItemElement) {
                            if (e.element.separator) {
                                if (this._itemRenderer.isItemWithSeparatorVisible(e.element)) {
                                    this._tree.reveal(e.element);
                                }
                                else {
                                    this._tree.reveal(e.element, 0);
                                }
                                return true;
                            }
                            else if (e.element === this._elementTree[0]) {
                                // We should stop at the first item in the list if it's a regular item.
                                this._tree.reveal(e.element, 0);
                                return true;
                            }
                        }
                        return false;
                    });
                    const after = this._tree.getFocus()[0];
                    if (before === after) {
                        // If we didn't move, then we should just move to the end
                        // of the list.
                        this._tree.scrollTop = this._tree.scrollHeight;
                        this._tree.focusLast(undefined, (e) => e.element instanceof QuickPickItemElement);
                    }
                    break;
                }
                case quickInput_1.QuickPickFocus.PreviousSeparator: {
                    let focusElement;
                    // If we are already sitting on an inline separator, then we
                    // have already found the _current_ separator and need to
                    // move to the previous one.
                    let foundSeparator = !!this._tree.getFocus()[0]?.separator;
                    this._tree.focusPrevious(undefined, true, undefined, (e) => {
                        if (e.element instanceof QuickPickSeparatorElement) {
                            if (foundSeparator) {
                                if (!focusElement) {
                                    if (this._separatorRenderer.isSeparatorVisible(e.element)) {
                                        this._tree.reveal(e.element);
                                    }
                                    else {
                                        this._tree.reveal(e.element, 0);
                                    }
                                    focusElement = e.element.children[0];
                                }
                            }
                            else {
                                foundSeparator = true;
                            }
                        }
                        else if (e.element instanceof QuickPickItemElement) {
                            if (!focusElement) {
                                if (e.element.separator) {
                                    if (this._itemRenderer.isItemWithSeparatorVisible(e.element)) {
                                        this._tree.reveal(e.element);
                                    }
                                    else {
                                        this._tree.reveal(e.element, 0);
                                    }
                                    focusElement = e.element;
                                }
                                else if (e.element === this._elementTree[0]) {
                                    // We should stop at the first item in the list if it's a regular item.
                                    this._tree.reveal(e.element, 0);
                                    return true;
                                }
                            }
                        }
                        return false;
                    });
                    if (focusElement) {
                        this._tree.setFocus([focusElement]);
                    }
                    break;
                }
            }
        }
        clearFocus() {
            this._tree.setFocus([]);
        }
        domFocus() {
            this._tree.domFocus();
        }
        layout(maxHeight) {
            this._tree.getHTMLElement().style.maxHeight = maxHeight ? `${
            // Make sure height aligns with list item heights
            Math.floor(maxHeight / 44) * 44
                // Add some extra height so that it's clear there's more to scroll
                + 6}px` : '';
            this._tree.layout();
        }
        filter(query) {
            this._lastQueryString = query;
            if (!(this._sortByLabel || this._matchOnLabel || this._matchOnDescription || this._matchOnDetail)) {
                this._tree.layout();
                return false;
            }
            const queryWithWhitespace = query;
            query = query.trim();
            // Reset filtering
            if (!query || !(this.matchOnLabel || this.matchOnDescription || this.matchOnDetail)) {
                this._itemElements.forEach(element => {
                    element.labelHighlights = undefined;
                    element.descriptionHighlights = undefined;
                    element.detailHighlights = undefined;
                    element.hidden = false;
                    const previous = element.index && this._inputElements[element.index - 1];
                    if (element.item) {
                        element.separator = previous && previous.type === 'separator' && !previous.buttons ? previous : undefined;
                    }
                });
            }
            // Filter by value (since we support icons in labels, use $(..) aware fuzzy matching)
            else {
                let currentSeparator;
                this._itemElements.forEach(element => {
                    let labelHighlights;
                    if (this.matchOnLabelMode === 'fuzzy') {
                        labelHighlights = this.matchOnLabel ? (0, iconLabels_1.matchesFuzzyIconAware)(query, (0, iconLabels_1.parseLabelWithIcons)(element.saneLabel)) ?? undefined : undefined;
                    }
                    else {
                        labelHighlights = this.matchOnLabel ? matchesContiguousIconAware(queryWithWhitespace, (0, iconLabels_1.parseLabelWithIcons)(element.saneLabel)) ?? undefined : undefined;
                    }
                    const descriptionHighlights = this.matchOnDescription ? (0, iconLabels_1.matchesFuzzyIconAware)(query, (0, iconLabels_1.parseLabelWithIcons)(element.saneDescription || '')) ?? undefined : undefined;
                    const detailHighlights = this.matchOnDetail ? (0, iconLabels_1.matchesFuzzyIconAware)(query, (0, iconLabels_1.parseLabelWithIcons)(element.saneDetail || '')) ?? undefined : undefined;
                    if (labelHighlights || descriptionHighlights || detailHighlights) {
                        element.labelHighlights = labelHighlights;
                        element.descriptionHighlights = descriptionHighlights;
                        element.detailHighlights = detailHighlights;
                        element.hidden = false;
                    }
                    else {
                        element.labelHighlights = undefined;
                        element.descriptionHighlights = undefined;
                        element.detailHighlights = undefined;
                        element.hidden = element.item ? !element.item.alwaysShow : true;
                    }
                    // Ensure separators are filtered out first before deciding if we need to bring them back
                    if (element.item) {
                        element.separator = undefined;
                    }
                    else if (element.separator) {
                        element.hidden = true;
                    }
                    // we can show the separator unless the list gets sorted by match
                    if (!this.sortByLabel) {
                        const previous = element.index && this._inputElements[element.index - 1] || undefined;
                        if (previous?.type === 'separator' && !previous.buttons) {
                            currentSeparator = previous;
                        }
                        if (currentSeparator && !element.hidden) {
                            element.separator = currentSeparator;
                            currentSeparator = undefined;
                        }
                    }
                });
            }
            this._setElementsToTree(this._sortByLabel && query
                // We don't render any separators if we're sorting so just render the elements
                ? this._itemElements
                // Render the full tree
                : this._elementTree);
            this._tree.layout();
            return true;
        }
        toggleCheckbox() {
            this._elementCheckedEventBufferer.bufferEvents(() => {
                const elements = this._tree.getFocus().filter((e) => e instanceof QuickPickItemElement);
                const allChecked = this._allVisibleChecked(elements);
                for (const element of elements) {
                    if (!element.checkboxDisabled) {
                        // Would fire an event if we didn't have the flag set
                        element.checked = !allChecked;
                    }
                }
            });
        }
        style(styles) {
            this._tree.style(styles);
        }
        toggleHover() {
            const focused = this._tree.getFocus()[0];
            if (!focused?.saneTooltip || !(focused instanceof QuickPickItemElement)) {
                return;
            }
            // if there's a hover already, hide it (toggle off)
            if (this._lastHover && !this._lastHover.isDisposed) {
                this._lastHover.dispose();
                return;
            }
            // If there is no hover, show it (toggle on)
            this.showHover(focused);
            const store = new lifecycle_1.DisposableStore();
            store.add(this._tree.onDidChangeFocus(e => {
                if (e.elements[0] instanceof QuickPickItemElement) {
                    this.showHover(e.elements[0]);
                }
            }));
            if (this._lastHover) {
                store.add(this._lastHover);
            }
            this._elementDisposable.add(store);
        }
        //#endregion
        //#region private methods
        _setElementsToTree(elements) {
            const treeElements = new Array();
            for (const element of elements) {
                if (element instanceof QuickPickSeparatorElement) {
                    treeElements.push({
                        element,
                        collapsible: false,
                        collapsed: false,
                        children: element.children.map(e => ({
                            element: e,
                            collapsible: false,
                            collapsed: false,
                        })),
                    });
                }
                else {
                    treeElements.push({
                        element,
                        collapsible: false,
                        collapsed: false,
                    });
                }
            }
            this._tree.setChildren(null, treeElements);
        }
        _allVisibleChecked(elements, whenNoneVisible = true) {
            for (let i = 0, n = elements.length; i < n; i++) {
                const element = elements[i];
                if (!element.hidden) {
                    if (!element.checked) {
                        return false;
                    }
                    else {
                        whenNoneVisible = true;
                    }
                }
            }
            return whenNoneVisible;
        }
        _updateCheckedObservables() {
            (0, observable_1.transaction)((tx) => {
                this._allVisibleCheckedObservable.set(this._allVisibleChecked(this._itemElements, false), tx);
                const checkedCount = this._itemElements.filter(element => element.checked).length;
                this._checkedCountObservable.set(checkedCount, tx);
                this._checkedElementsObservable.set(this.getCheckedElements(), tx);
            });
        }
        /**
         * Disposes of the hover and shows a new one for the given index if it has a tooltip.
         * @param element The element to show the hover for
         */
        showHover(element) {
            if (this._lastHover && !this._lastHover.isDisposed) {
                this.hoverDelegate.onDidHideHover?.();
                this._lastHover?.dispose();
            }
            if (!element.element || !element.saneTooltip) {
                return;
            }
            this._lastHover = this.hoverDelegate.showHover({
                content: element.saneTooltip,
                target: element.element,
                linkHandler: (url) => {
                    this.linkOpenerDelegate(url);
                },
                appearance: {
                    showPointer: true,
                },
                container: this._container,
                position: {
                    hoverPosition: 1 /* HoverPosition.RIGHT */
                }
            }, false);
        }
    };
    exports.QuickInputTree = QuickInputTree;
    __decorate([
        decorators_1.memoize
    ], QuickInputTree.prototype, "onDidChangeFocus", null);
    __decorate([
        decorators_1.memoize
    ], QuickInputTree.prototype, "onDidChangeSelection", null);
    exports.QuickInputTree = QuickInputTree = __decorate([
        __param(4, instantiation_1.IInstantiationService),
        __param(5, accessibility_1.IAccessibilityService)
    ], QuickInputTree);
    function matchesContiguousIconAware(query, target) {
        const { text, iconOffsets } = target;
        // Return early if there are no icon markers in the word to match against
        if (!iconOffsets || iconOffsets.length === 0) {
            return matchesContiguous(query, text);
        }
        // Trim the word to match against because it could have leading
        // whitespace now if the word started with an icon
        const wordToMatchAgainstWithoutIconsTrimmed = (0, strings_1.ltrim)(text, ' ');
        const leadingWhitespaceOffset = text.length - wordToMatchAgainstWithoutIconsTrimmed.length;
        // match on value without icon
        const matches = matchesContiguous(query, wordToMatchAgainstWithoutIconsTrimmed);
        // Map matches back to offsets with icon and trimming
        if (matches) {
            for (const match of matches) {
                const iconOffset = iconOffsets[match.start + leadingWhitespaceOffset] /* icon offsets at index */ + leadingWhitespaceOffset /* overall leading whitespace offset */;
                match.start += iconOffset;
                match.end += iconOffset;
            }
        }
        return matches;
    }
    function matchesContiguous(word, wordToMatchAgainst) {
        const matchIndex = wordToMatchAgainst.toLowerCase().indexOf(word.toLowerCase());
        if (matchIndex !== -1) {
            return [{ start: matchIndex, end: matchIndex + word.length }];
        }
        return null;
    }
    function compareEntries(elementA, elementB, lookFor) {
        const labelHighlightsA = elementA.labelHighlights || [];
        const labelHighlightsB = elementB.labelHighlights || [];
        if (labelHighlightsA.length && !labelHighlightsB.length) {
            return -1;
        }
        if (!labelHighlightsA.length && labelHighlightsB.length) {
            return 1;
        }
        if (labelHighlightsA.length === 0 && labelHighlightsB.length === 0) {
            return 0;
        }
        return (0, comparers_1.compareAnything)(elementA.saneSortLabel, elementB.saneSortLabel, lookFor);
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[803/*vs/platform/quickinput/browser/quickInputController*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,87/*vs/base/browser/ui/actionbar/actionbar*/,258/*vs/base/browser/ui/button/button*/,354/*vs/base/browser/ui/countBadge/countBadge*/,633/*vs/base/browser/ui/progressbar/progressbar*/,18/*vs/base/common/cancellation*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,111/*vs/base/common/severity*/,3/*vs/nls*/,66/*vs/platform/quickinput/common/quickInput*/,704/*vs/platform/quickinput/browser/quickInputBox*/,272/*vs/platform/quickinput/browser/quickInput*/,119/*vs/platform/layout/browser/layoutService*/,52/*vs/base/browser/window*/,7/*vs/platform/instantiation/common/instantiation*/,802/*vs/platform/quickinput/browser/quickInputTree*/,12/*vs/platform/contextkey/common/contextkey*/,719/*vs/platform/quickinput/browser/quickInputActions*/]), function (require, exports, dom, actionbar_1, button_1, countBadge_1, progressbar_1, cancellation_1, event_1, lifecycle_1, severity_1, nls_1, quickInput_1, quickInputBox_1, quickInput_2, layoutService_1, window_1, instantiation_1, quickInputTree_1, contextkey_1) {
    "use strict";
    var QuickInputController_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.QuickInputController = void 0;
    const $ = dom.$;
    let QuickInputController = class QuickInputController extends lifecycle_1.Disposable {
        static { QuickInputController_1 = this; }
        static { this.MAX_WIDTH = 600; } // Max total width of quick input widget
        get currentQuickInput() { return this.controller ?? undefined; }
        get container() { return this._container; }
        constructor(options, layoutService, instantiationService, contextKeyService) {
            super();
            this.options = options;
            this.layoutService = layoutService;
            this.instantiationService = instantiationService;
            this.contextKeyService = contextKeyService;
            this.enabled = true;
            this.onDidAcceptEmitter = this._register(new event_1.Emitter());
            this.onDidCustomEmitter = this._register(new event_1.Emitter());
            this.onDidTriggerButtonEmitter = this._register(new event_1.Emitter());
            this.keyMods = { ctrlCmd: false, alt: false };
            this.controller = null;
            this.onShowEmitter = this._register(new event_1.Emitter());
            this.onShow = this.onShowEmitter.event;
            this.onHideEmitter = this._register(new event_1.Emitter());
            this.onHide = this.onHideEmitter.event;
            this.inQuickInputContext = quickInput_2.InQuickInputContextKey.bindTo(this.contextKeyService);
            this.quickInputTypeContext = quickInput_2.QuickInputTypeContextKey.bindTo(this.contextKeyService);
            this.endOfQuickInputBoxContext = quickInput_2.EndOfQuickInputBoxContextKey.bindTo(this.contextKeyService);
            this.idPrefix = options.idPrefix;
            this._container = options.container;
            this.styles = options.styles;
            this._register(event_1.Event.runAndSubscribe(dom.onDidRegisterWindow, ({ window, disposables }) => this.registerKeyModsListeners(window, disposables), { window: window_1.mainWindow, disposables: this._store }));
            this._register(dom.onWillUnregisterWindow(window => {
                if (this.ui && dom.getWindow(this.ui.container) === window) {
                    // The window this quick input is contained in is about to
                    // close, so we have to make sure to reparent it back to an
                    // existing parent to not loose functionality.
                    // (https://github.com/microsoft/vscode/issues/195870)
                    this.reparentUI(this.layoutService.mainContainer);
                    this.layout(this.layoutService.mainContainerDimension, this.layoutService.mainContainerOffset.quickPickTop);
                }
            }));
        }
        registerKeyModsListeners(window, disposables) {
            const listener = (e) => {
                this.keyMods.ctrlCmd = e.ctrlKey || e.metaKey;
                this.keyMods.alt = e.altKey;
            };
            for (const event of [dom.EventType.KEY_DOWN, dom.EventType.KEY_UP, dom.EventType.MOUSE_DOWN]) {
                disposables.add(dom.addDisposableListener(window, event, listener, true));
            }
        }
        getUI(showInActiveContainer) {
            if (this.ui) {
                // In order to support aux windows, re-parent the controller
                // if the original event is from a different document
                if (showInActiveContainer) {
                    if (dom.getWindow(this._container) !== dom.getWindow(this.layoutService.activeContainer)) {
                        this.reparentUI(this.layoutService.activeContainer);
                        this.layout(this.layoutService.activeContainerDimension, this.layoutService.activeContainerOffset.quickPickTop);
                    }
                }
                return this.ui;
            }
            const container = dom.append(this._container, $('.quick-input-widget.show-file-icons'));
            container.tabIndex = -1;
            container.style.display = 'none';
            const styleSheet = dom.createStyleSheet(container);
            const titleBar = dom.append(container, $('.quick-input-titlebar'));
            const leftActionBar = this._register(new actionbar_1.ActionBar(titleBar, { hoverDelegate: this.options.hoverDelegate }));
            leftActionBar.domNode.classList.add('quick-input-left-action-bar');
            const title = dom.append(titleBar, $('.quick-input-title'));
            const rightActionBar = this._register(new actionbar_1.ActionBar(titleBar, { hoverDelegate: this.options.hoverDelegate }));
            rightActionBar.domNode.classList.add('quick-input-right-action-bar');
            const headerContainer = dom.append(container, $('.quick-input-header'));
            const checkAll = dom.append(headerContainer, $('input.quick-input-check-all'));
            checkAll.type = 'checkbox';
            checkAll.setAttribute('aria-label', (0, nls_1.localize)(1590, "Toggle all checkboxes"));
            this._register(dom.addStandardDisposableListener(checkAll, dom.EventType.CHANGE, e => {
                const checked = checkAll.checked;
                list.setAllVisibleChecked(checked);
            }));
            this._register(dom.addDisposableListener(checkAll, dom.EventType.CLICK, e => {
                if (e.x || e.y) { // Avoid 'click' triggered by 'space'...
                    inputBox.setFocus();
                }
            }));
            const description2 = dom.append(headerContainer, $('.quick-input-description'));
            const inputContainer = dom.append(headerContainer, $('.quick-input-and-message'));
            const filterContainer = dom.append(inputContainer, $('.quick-input-filter'));
            const inputBox = this._register(new quickInputBox_1.QuickInputBox(filterContainer, this.styles.inputBox, this.styles.toggle));
            inputBox.setAttribute('aria-describedby', `${this.idPrefix}message`);
            const visibleCountContainer = dom.append(filterContainer, $('.quick-input-visible-count'));
            visibleCountContainer.setAttribute('aria-live', 'polite');
            visibleCountContainer.setAttribute('aria-atomic', 'true');
            const visibleCount = new countBadge_1.CountBadge(visibleCountContainer, { countFormat: (0, nls_1.localize)(1591, "{0} Results") }, this.styles.countBadge);
            const countContainer = dom.append(filterContainer, $('.quick-input-count'));
            countContainer.setAttribute('aria-live', 'polite');
            const count = new countBadge_1.CountBadge(countContainer, { countFormat: (0, nls_1.localize)(1592, "{0} Selected") }, this.styles.countBadge);
            const inlineActionBar = this._register(new actionbar_1.ActionBar(headerContainer, { hoverDelegate: this.options.hoverDelegate }));
            inlineActionBar.domNode.classList.add('quick-input-inline-action-bar');
            const okContainer = dom.append(headerContainer, $('.quick-input-action'));
            const ok = this._register(new button_1.Button(okContainer, this.styles.button));
            ok.label = (0, nls_1.localize)(1593, "OK");
            this._register(ok.onDidClick(e => {
                this.onDidAcceptEmitter.fire();
            }));
            const customButtonContainer = dom.append(headerContainer, $('.quick-input-action'));
            const customButton = this._register(new button_1.Button(customButtonContainer, { ...this.styles.button, supportIcons: true }));
            customButton.label = (0, nls_1.localize)(1594, "Custom");
            this._register(customButton.onDidClick(e => {
                this.onDidCustomEmitter.fire();
            }));
            const message = dom.append(inputContainer, $(`#${this.idPrefix}message.quick-input-message`));
            const progressBar = this._register(new progressbar_1.ProgressBar(container, this.styles.progressBar));
            progressBar.getContainer().classList.add('quick-input-progress');
            const widget = dom.append(container, $('.quick-input-html-widget'));
            widget.tabIndex = -1;
            const description1 = dom.append(container, $('.quick-input-description'));
            const listId = this.idPrefix + 'list';
            const list = this._register(this.instantiationService.createInstance(quickInputTree_1.QuickInputTree, container, this.options.hoverDelegate, this.options.linkOpenerDelegate, listId));
            inputBox.setAttribute('aria-controls', listId);
            this._register(list.onDidChangeFocus(() => {
                inputBox.setAttribute('aria-activedescendant', list.getActiveDescendant() ?? '');
            }));
            this._register(list.onChangedAllVisibleChecked(checked => {
                checkAll.checked = checked;
            }));
            this._register(list.onChangedVisibleCount(c => {
                visibleCount.setCount(c);
            }));
            this._register(list.onChangedCheckedCount(c => {
                count.setCount(c);
            }));
            this._register(list.onLeave(() => {
                // Defer to avoid the input field reacting to the triggering key.
                // TODO@TylerLeonhardt https://github.com/microsoft/vscode/issues/203675
                setTimeout(() => {
                    if (!this.controller) {
                        return;
                    }
                    inputBox.setFocus();
                    if (this.controller instanceof quickInput_2.QuickPick && this.controller.canSelectMany) {
                        list.clearFocus();
                    }
                }, 0);
            }));
            const focusTracker = dom.trackFocus(container);
            this._register(focusTracker);
            this._register(dom.addDisposableListener(container, dom.EventType.FOCUS, e => {
                const ui = this.getUI();
                if (dom.isAncestor(e.relatedTarget, ui.inputContainer)) {
                    const value = ui.inputBox.isSelectionAtEnd();
                    if (this.endOfQuickInputBoxContext.get() !== value) {
                        this.endOfQuickInputBoxContext.set(value);
                    }
                }
                // Ignore focus events within container
                if (dom.isAncestor(e.relatedTarget, ui.container)) {
                    return;
                }
                this.inQuickInputContext.set(true);
                this.previousFocusElement = dom.isHTMLElement(e.relatedTarget) ? e.relatedTarget : undefined;
            }, true));
            this._register(focusTracker.onDidBlur(() => {
                if (!this.getUI().ignoreFocusOut && !this.options.ignoreFocusOut()) {
                    this.hide(quickInput_1.QuickInputHideReason.Blur);
                }
                this.inQuickInputContext.set(false);
                this.endOfQuickInputBoxContext.set(false);
                this.previousFocusElement = undefined;
            }));
            this._register(inputBox.onKeyDown(_ => {
                const value = this.getUI().inputBox.isSelectionAtEnd();
                if (this.endOfQuickInputBoxContext.get() !== value) {
                    this.endOfQuickInputBoxContext.set(value);
                }
            }));
            this._register(dom.addDisposableListener(container, dom.EventType.FOCUS, (e) => {
                inputBox.setFocus();
            }));
            // TODO: Turn into commands instead of handling KEY_DOWN
            // Keybindings for the quickinput widget as a whole
            this._register(dom.addStandardDisposableListener(container, dom.EventType.KEY_DOWN, (event) => {
                if (dom.isAncestor(event.target, widget)) {
                    return; // Ignore event if target is inside widget to allow the widget to handle the event.
                }
                switch (event.keyCode) {
                    case 3 /* KeyCode.Enter */:
                        dom.EventHelper.stop(event, true);
                        if (this.enabled) {
                            this.onDidAcceptEmitter.fire();
                        }
                        break;
                    case 9 /* KeyCode.Escape */:
                        dom.EventHelper.stop(event, true);
                        this.hide(quickInput_1.QuickInputHideReason.Gesture);
                        break;
                    case 2 /* KeyCode.Tab */:
                        if (!event.altKey && !event.ctrlKey && !event.metaKey) {
                            // detect only visible actions
                            const selectors = [
                                '.quick-input-list .monaco-action-bar .always-visible',
                                '.quick-input-list-entry:hover .monaco-action-bar',
                                '.monaco-list-row.focused .monaco-action-bar'
                            ];
                            if (container.classList.contains('show-checkboxes')) {
                                selectors.push('input');
                            }
                            else {
                                selectors.push('input[type=text]');
                            }
                            if (this.getUI().list.displayed) {
                                selectors.push('.monaco-list');
                            }
                            // focus links if there are any
                            if (this.getUI().message) {
                                selectors.push('.quick-input-message a');
                            }
                            if (this.getUI().widget) {
                                if (dom.isAncestor(event.target, this.getUI().widget)) {
                                    // let the widget control tab
                                    break;
                                }
                                selectors.push('.quick-input-html-widget');
                            }
                            const stops = container.querySelectorAll(selectors.join(', '));
                            if (event.shiftKey && event.target === stops[0]) {
                                // Clear the focus from the list in order to allow
                                // screen readers to read operations in the input box.
                                dom.EventHelper.stop(event, true);
                                list.clearFocus();
                            }
                            else if (!event.shiftKey && dom.isAncestor(event.target, stops[stops.length - 1])) {
                                dom.EventHelper.stop(event, true);
                                stops[0].focus();
                            }
                        }
                        break;
                    case 10 /* KeyCode.Space */:
                        if (event.ctrlKey) {
                            dom.EventHelper.stop(event, true);
                            this.getUI().list.toggleHover();
                        }
                        break;
                }
            }));
            this.ui = {
                container,
                styleSheet,
                leftActionBar,
                titleBar,
                title,
                description1,
                description2,
                widget,
                rightActionBar,
                inlineActionBar,
                checkAll,
                inputContainer,
                filterContainer,
                inputBox,
                visibleCountContainer,
                visibleCount,
                countContainer,
                count,
                okContainer,
                ok,
                message,
                customButtonContainer,
                customButton,
                list,
                progressBar,
                onDidAccept: this.onDidAcceptEmitter.event,
                onDidCustom: this.onDidCustomEmitter.event,
                onDidTriggerButton: this.onDidTriggerButtonEmitter.event,
                ignoreFocusOut: false,
                keyMods: this.keyMods,
                show: controller => this.show(controller),
                hide: () => this.hide(),
                setVisibilities: visibilities => this.setVisibilities(visibilities),
                setEnabled: enabled => this.setEnabled(enabled),
                setContextKey: contextKey => this.options.setContextKey(contextKey),
                linkOpenerDelegate: content => this.options.linkOpenerDelegate(content)
            };
            this.updateStyles();
            return this.ui;
        }
        reparentUI(container) {
            if (this.ui) {
                this._container = container;
                dom.append(this._container, this.ui.container);
            }
        }
        pick(picks, options = {}, token = cancellation_1.CancellationToken.None) {
            return new Promise((doResolve, reject) => {
                let resolve = (result) => {
                    resolve = doResolve;
                    options.onKeyMods?.(input.keyMods);
                    doResolve(result);
                };
                if (token.isCancellationRequested) {
                    resolve(undefined);
                    return;
                }
                const input = this.createQuickPick({ useSeparators: true });
                let activeItem;
                const disposables = [
                    input,
                    input.onDidAccept(() => {
                        if (input.canSelectMany) {
                            resolve(input.selectedItems.slice());
                            input.hide();
                        }
                        else {
                            const result = input.activeItems[0];
                            if (result) {
                                resolve(result);
                                input.hide();
                            }
                        }
                    }),
                    input.onDidChangeActive(items => {
                        const focused = items[0];
                        if (focused && options.onDidFocus) {
                            options.onDidFocus(focused);
                        }
                    }),
                    input.onDidChangeSelection(items => {
                        if (!input.canSelectMany) {
                            const result = items[0];
                            if (result) {
                                resolve(result);
                                input.hide();
                            }
                        }
                    }),
                    input.onDidTriggerItemButton(event => options.onDidTriggerItemButton && options.onDidTriggerItemButton({
                        ...event,
                        removeItem: () => {
                            const index = input.items.indexOf(event.item);
                            if (index !== -1) {
                                const items = input.items.slice();
                                const removed = items.splice(index, 1);
                                const activeItems = input.activeItems.filter(activeItem => activeItem !== removed[0]);
                                const keepScrollPositionBefore = input.keepScrollPosition;
                                input.keepScrollPosition = true;
                                input.items = items;
                                if (activeItems) {
                                    input.activeItems = activeItems;
                                }
                                input.keepScrollPosition = keepScrollPositionBefore;
                            }
                        }
                    })),
                    input.onDidTriggerSeparatorButton(event => options.onDidTriggerSeparatorButton?.(event)),
                    input.onDidChangeValue(value => {
                        if (activeItem && !value && (input.activeItems.length !== 1 || input.activeItems[0] !== activeItem)) {
                            input.activeItems = [activeItem];
                        }
                    }),
                    token.onCancellationRequested(() => {
                        input.hide();
                    }),
                    input.onDidHide(() => {
                        (0, lifecycle_1.dispose)(disposables);
                        resolve(undefined);
                    }),
                ];
                input.title = options.title;
                if (options.value) {
                    input.value = options.value;
                }
                input.canSelectMany = !!options.canPickMany;
                input.placeholder = options.placeHolder;
                input.ignoreFocusOut = !!options.ignoreFocusLost;
                input.matchOnDescription = !!options.matchOnDescription;
                input.matchOnDetail = !!options.matchOnDetail;
                input.matchOnLabel = (options.matchOnLabel === undefined) || options.matchOnLabel; // default to true
                input.quickNavigate = options.quickNavigate;
                input.hideInput = !!options.hideInput;
                input.contextKey = options.contextKey;
                input.busy = true;
                Promise.all([picks, options.activeItem])
                    .then(([items, _activeItem]) => {
                    activeItem = _activeItem;
                    input.busy = false;
                    input.items = items;
                    if (input.canSelectMany) {
                        input.selectedItems = items.filter(item => item.type !== 'separator' && item.picked);
                    }
                    if (activeItem) {
                        input.activeItems = [activeItem];
                    }
                });
                input.show();
                Promise.resolve(picks).then(undefined, err => {
                    reject(err);
                    input.hide();
                });
            });
        }
        createQuickPick(options = { useSeparators: false }) {
            const ui = this.getUI(true);
            return new quickInput_2.QuickPick(ui);
        }
        createInputBox() {
            const ui = this.getUI(true);
            return new quickInput_2.InputBox(ui);
        }
        show(controller) {
            const ui = this.getUI(true);
            this.onShowEmitter.fire();
            const oldController = this.controller;
            this.controller = controller;
            oldController?.didHide();
            this.setEnabled(true);
            ui.leftActionBar.clear();
            ui.title.textContent = '';
            ui.description1.textContent = '';
            ui.description2.textContent = '';
            dom.reset(ui.widget);
            ui.rightActionBar.clear();
            ui.inlineActionBar.clear();
            ui.checkAll.checked = false;
            // ui.inputBox.value = ''; Avoid triggering an event.
            ui.inputBox.placeholder = '';
            ui.inputBox.password = false;
            ui.inputBox.showDecoration(severity_1.default.Ignore);
            ui.visibleCount.setCount(0);
            ui.count.setCount(0);
            dom.reset(ui.message);
            ui.progressBar.stop();
            ui.list.setElements([]);
            ui.list.matchOnDescription = false;
            ui.list.matchOnDetail = false;
            ui.list.matchOnLabel = true;
            ui.list.sortByLabel = true;
            ui.ignoreFocusOut = false;
            ui.inputBox.toggles = undefined;
            const backKeybindingLabel = this.options.backKeybindingLabel();
            quickInput_2.backButton.tooltip = backKeybindingLabel ? (0, nls_1.localize)(1595, "Back ({0})", backKeybindingLabel) : (0, nls_1.localize)(1596, "Back");
            ui.container.style.display = '';
            this.updateLayout();
            ui.inputBox.setFocus();
            this.quickInputTypeContext.set(controller.type);
        }
        isVisible() {
            return !!this.ui && this.ui.container.style.display !== 'none';
        }
        setVisibilities(visibilities) {
            const ui = this.getUI();
            ui.title.style.display = visibilities.title ? '' : 'none';
            ui.description1.style.display = visibilities.description && (visibilities.inputBox || visibilities.checkAll) ? '' : 'none';
            ui.description2.style.display = visibilities.description && !(visibilities.inputBox || visibilities.checkAll) ? '' : 'none';
            ui.checkAll.style.display = visibilities.checkAll ? '' : 'none';
            ui.inputContainer.style.display = visibilities.inputBox ? '' : 'none';
            ui.filterContainer.style.display = visibilities.inputBox ? '' : 'none';
            ui.visibleCountContainer.style.display = visibilities.visibleCount ? '' : 'none';
            ui.countContainer.style.display = visibilities.count ? '' : 'none';
            ui.okContainer.style.display = visibilities.ok ? '' : 'none';
            ui.customButtonContainer.style.display = visibilities.customButton ? '' : 'none';
            ui.message.style.display = visibilities.message ? '' : 'none';
            ui.progressBar.getContainer().style.display = visibilities.progressBar ? '' : 'none';
            ui.list.displayed = !!visibilities.list;
            ui.container.classList.toggle('show-checkboxes', !!visibilities.checkBox);
            ui.container.classList.toggle('hidden-input', !visibilities.inputBox && !visibilities.description);
            this.updateLayout(); // TODO
        }
        setEnabled(enabled) {
            if (enabled !== this.enabled) {
                this.enabled = enabled;
                for (const item of this.getUI().leftActionBar.viewItems) {
                    item.action.enabled = enabled;
                }
                for (const item of this.getUI().rightActionBar.viewItems) {
                    item.action.enabled = enabled;
                }
                this.getUI().checkAll.disabled = !enabled;
                this.getUI().inputBox.enabled = enabled;
                this.getUI().ok.enabled = enabled;
                this.getUI().list.enabled = enabled;
            }
        }
        hide(reason) {
            const controller = this.controller;
            if (!controller) {
                return;
            }
            controller.willHide(reason);
            const container = this.ui?.container;
            const focusChanged = container && !dom.isAncestorOfActiveElement(container);
            this.controller = null;
            this.onHideEmitter.fire();
            if (container) {
                container.style.display = 'none';
            }
            if (!focusChanged) {
                let currentElement = this.previousFocusElement;
                while (currentElement && !currentElement.offsetParent) {
                    currentElement = currentElement.parentElement ?? undefined;
                }
                if (currentElement?.offsetParent) {
                    currentElement.focus();
                    this.previousFocusElement = undefined;
                }
                else {
                    this.options.returnFocus();
                }
            }
            controller.didHide(reason);
        }
        layout(dimension, titleBarOffset) {
            this.dimension = dimension;
            this.titleBarOffset = titleBarOffset;
            this.updateLayout();
        }
        updateLayout() {
            if (this.ui && this.isVisible()) {
                this.ui.container.style.top = `${this.titleBarOffset}px`;
                const style = this.ui.container.style;
                const width = Math.min(this.dimension.width * 0.62 /* golden cut */, QuickInputController_1.MAX_WIDTH);
                style.width = width + 'px';
                style.marginLeft = '-' + (width / 2) + 'px';
                this.ui.inputBox.layout();
                this.ui.list.layout(this.dimension && this.dimension.height * 0.4);
            }
        }
        applyStyles(styles) {
            this.styles = styles;
            this.updateStyles();
        }
        updateStyles() {
            if (this.ui) {
                const { quickInputTitleBackground, quickInputBackground, quickInputForeground, widgetBorder, widgetShadow, } = this.styles.widget;
                this.ui.titleBar.style.backgroundColor = quickInputTitleBackground ?? '';
                this.ui.container.style.backgroundColor = quickInputBackground ?? '';
                this.ui.container.style.color = quickInputForeground ?? '';
                this.ui.container.style.border = widgetBorder ? `1px solid ${widgetBorder}` : '';
                this.ui.container.style.boxShadow = widgetShadow ? `0 0 8px 2px ${widgetShadow}` : '';
                this.ui.list.style(this.styles.list);
                const content = [];
                if (this.styles.pickerGroup.pickerGroupBorder) {
                    content.push(`.quick-input-list .quick-input-list-entry { border-top-color:  ${this.styles.pickerGroup.pickerGroupBorder}; }`);
                }
                if (this.styles.pickerGroup.pickerGroupForeground) {
                    content.push(`.quick-input-list .quick-input-list-separator { color:  ${this.styles.pickerGroup.pickerGroupForeground}; }`);
                }
                if (this.styles.pickerGroup.pickerGroupForeground) {
                    content.push(`.quick-input-list .quick-input-list-separator-as-item { color: var(--vscode-descriptionForeground); }`);
                }
                if (this.styles.keybindingLabel.keybindingLabelBackground ||
                    this.styles.keybindingLabel.keybindingLabelBorder ||
                    this.styles.keybindingLabel.keybindingLabelBottomBorder ||
                    this.styles.keybindingLabel.keybindingLabelShadow ||
                    this.styles.keybindingLabel.keybindingLabelForeground) {
                    content.push('.quick-input-list .monaco-keybinding > .monaco-keybinding-key {');
                    if (this.styles.keybindingLabel.keybindingLabelBackground) {
                        content.push(`background-color: ${this.styles.keybindingLabel.keybindingLabelBackground};`);
                    }
                    if (this.styles.keybindingLabel.keybindingLabelBorder) {
                        // Order matters here. `border-color` must come before `border-bottom-color`.
                        content.push(`border-color: ${this.styles.keybindingLabel.keybindingLabelBorder};`);
                    }
                    if (this.styles.keybindingLabel.keybindingLabelBottomBorder) {
                        content.push(`border-bottom-color: ${this.styles.keybindingLabel.keybindingLabelBottomBorder};`);
                    }
                    if (this.styles.keybindingLabel.keybindingLabelShadow) {
                        content.push(`box-shadow: inset 0 -1px 0 ${this.styles.keybindingLabel.keybindingLabelShadow};`);
                    }
                    if (this.styles.keybindingLabel.keybindingLabelForeground) {
                        content.push(`color: ${this.styles.keybindingLabel.keybindingLabelForeground};`);
                    }
                    content.push('}');
                }
                const newStyles = content.join('\n');
                if (newStyles !== this.ui.styleSheet.textContent) {
                    this.ui.styleSheet.textContent = newStyles;
                }
            }
        }
    };
    exports.QuickInputController = QuickInputController;
    exports.QuickInputController = QuickInputController = QuickInputController_1 = __decorate([
        __param(1, layoutService_1.ILayoutService),
        __param(2, instantiation_1.IInstantiationService),
        __param(3, contextkey_1.IContextKeyService)
    ], QuickInputController);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[804/*vs/platform/quickinput/browser/quickInputService*/], __M([1/*require*/,0/*exports*/,18/*vs/base/common/cancellation*/,6/*vs/base/common/event*/,12/*vs/platform/contextkey/common/contextkey*/,7/*vs/platform/instantiation/common/instantiation*/,119/*vs/platform/layout/browser/layoutService*/,59/*vs/platform/opener/common/opener*/,722/*vs/platform/quickinput/browser/quickAccess*/,110/*vs/platform/theme/browser/defaultStyles*/,32/*vs/platform/theme/common/colorRegistry*/,25/*vs/platform/theme/common/themeService*/,272/*vs/platform/quickinput/browser/quickInput*/,803/*vs/platform/quickinput/browser/quickInputController*/,28/*vs/platform/configuration/common/configuration*/,5/*vs/base/browser/dom*/]), function (require, exports, cancellation_1, event_1, contextkey_1, instantiation_1, layoutService_1, opener_1, quickAccess_1, defaultStyles_1, colorRegistry_1, themeService_1, quickInput_1, quickInputController_1, configuration_1, dom_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.QuickInputService = void 0;
    let QuickInputService = class QuickInputService extends themeService_1.Themable {
        get controller() {
            if (!this._controller) {
                this._controller = this._register(this.createController());
            }
            return this._controller;
        }
        get hasController() { return !!this._controller; }
        get currentQuickInput() { return this.controller.currentQuickInput; }
        get quickAccess() {
            if (!this._quickAccess) {
                this._quickAccess = this._register(this.instantiationService.createInstance(quickAccess_1.QuickAccessController));
            }
            return this._quickAccess;
        }
        constructor(instantiationService, contextKeyService, themeService, layoutService, configurationService) {
            super(themeService);
            this.instantiationService = instantiationService;
            this.contextKeyService = contextKeyService;
            this.layoutService = layoutService;
            this.configurationService = configurationService;
            this._onShow = this._register(new event_1.Emitter());
            this._onHide = this._register(new event_1.Emitter());
            this.contexts = new Map();
        }
        createController(host = this.layoutService, options) {
            const defaultOptions = {
                idPrefix: 'quickInput_',
                container: host.activeContainer,
                ignoreFocusOut: () => false,
                backKeybindingLabel: () => undefined,
                setContextKey: (id) => this.setContextKey(id),
                linkOpenerDelegate: (content) => {
                    // HACK: https://github.com/microsoft/vscode/issues/173691
                    this.instantiationService.invokeFunction(accessor => {
                        const openerService = accessor.get(opener_1.IOpenerService);
                        openerService.open(content, { allowCommands: true, fromUserGesture: true });
                    });
                },
                returnFocus: () => host.focus(),
                styles: this.computeStyles(),
                hoverDelegate: this._register(this.instantiationService.createInstance(quickInput_1.QuickInputHoverDelegate))
            };
            const controller = this._register(this.instantiationService.createInstance(quickInputController_1.QuickInputController, {
                ...defaultOptions,
                ...options
            }));
            controller.layout(host.activeContainerDimension, host.activeContainerOffset.quickPickTop);
            // Layout changes
            this._register(host.onDidLayoutActiveContainer(dimension => {
                if ((0, dom_1.getWindow)(host.activeContainer) === (0, dom_1.getWindow)(controller.container)) {
                    controller.layout(dimension, host.activeContainerOffset.quickPickTop);
                }
            }));
            this._register(host.onDidChangeActiveContainer(() => {
                if (controller.isVisible()) {
                    return;
                }
                controller.layout(host.activeContainerDimension, host.activeContainerOffset.quickPickTop);
            }));
            // Context keys
            this._register(controller.onShow(() => {
                this.resetContextKeys();
                this._onShow.fire();
            }));
            this._register(controller.onHide(() => {
                this.resetContextKeys();
                this._onHide.fire();
            }));
            return controller;
        }
        setContextKey(id) {
            let key;
            if (id) {
                key = this.contexts.get(id);
                if (!key) {
                    key = new contextkey_1.RawContextKey(id, false)
                        .bindTo(this.contextKeyService);
                    this.contexts.set(id, key);
                }
            }
            if (key && key.get()) {
                return; // already active context
            }
            this.resetContextKeys();
            key?.set(true);
        }
        resetContextKeys() {
            this.contexts.forEach(context => {
                if (context.get()) {
                    context.reset();
                }
            });
        }
        pick(picks, options, token = cancellation_1.CancellationToken.None) {
            return this.controller.pick(picks, options, token);
        }
        createQuickPick(options = { useSeparators: false }) {
            return this.controller.createQuickPick(options);
        }
        createInputBox() {
            return this.controller.createInputBox();
        }
        updateStyles() {
            if (this.hasController) {
                this.controller.applyStyles(this.computeStyles());
            }
        }
        computeStyles() {
            return {
                widget: {
                    quickInputBackground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.quickInputBackground),
                    quickInputForeground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.quickInputForeground),
                    quickInputTitleBackground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.quickInputTitleBackground),
                    widgetBorder: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.widgetBorder),
                    widgetShadow: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.widgetShadow),
                },
                inputBox: defaultStyles_1.defaultInputBoxStyles,
                toggle: defaultStyles_1.defaultToggleStyles,
                countBadge: defaultStyles_1.defaultCountBadgeStyles,
                button: defaultStyles_1.defaultButtonStyles,
                progressBar: defaultStyles_1.defaultProgressBarStyles,
                keybindingLabel: defaultStyles_1.defaultKeybindingLabelStyles,
                list: (0, defaultStyles_1.getListStyles)({
                    listBackground: colorRegistry_1.quickInputBackground,
                    listFocusBackground: colorRegistry_1.quickInputListFocusBackground,
                    listFocusForeground: colorRegistry_1.quickInputListFocusForeground,
                    // Look like focused when inactive.
                    listInactiveFocusForeground: colorRegistry_1.quickInputListFocusForeground,
                    listInactiveSelectionIconForeground: colorRegistry_1.quickInputListFocusIconForeground,
                    listInactiveFocusBackground: colorRegistry_1.quickInputListFocusBackground,
                    listFocusOutline: colorRegistry_1.activeContrastBorder,
                    listInactiveFocusOutline: colorRegistry_1.activeContrastBorder,
                }),
                pickerGroup: {
                    pickerGroupBorder: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.pickerGroupBorder),
                    pickerGroupForeground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.pickerGroupForeground),
                }
            };
        }
    };
    exports.QuickInputService = QuickInputService;
    exports.QuickInputService = QuickInputService = __decorate([
        __param(0, instantiation_1.IInstantiationService),
        __param(1, contextkey_1.IContextKeyService),
        __param(2, themeService_1.IThemeService),
        __param(3, layoutService_1.ILayoutService),
        __param(4, configuration_1.IConfigurationService)
    ], QuickInputService);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[805/*vs/editor/standalone/browser/quickInput/standaloneQuickInputService*/], __M([1/*require*/,0/*exports*/,6/*vs/base/common/event*/,15/*vs/editor/browser/editorExtensions*/,25/*vs/platform/theme/common/themeService*/,18/*vs/base/common/cancellation*/,7/*vs/platform/instantiation/common/instantiation*/,12/*vs/platform/contextkey/common/contextkey*/,394/*vs/editor/standalone/browser/standaloneLayoutService*/,34/*vs/editor/browser/services/codeEditorService*/,804/*vs/platform/quickinput/browser/quickInputService*/,127/*vs/base/common/functional*/,28/*vs/platform/configuration/common/configuration*/,540/*vs/css!vs/editor/standalone/browser/quickInput/standaloneQuickInput*/]), function (require, exports, event_1, editorExtensions_1, themeService_1, cancellation_1, instantiation_1, contextkey_1, standaloneLayoutService_1, codeEditorService_1, quickInputService_1, functional_1, configuration_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.QuickInputEditorWidget = exports.QuickInputEditorContribution = exports.StandaloneQuickInputService = void 0;
    let EditorScopedQuickInputService = class EditorScopedQuickInputService extends quickInputService_1.QuickInputService {
        constructor(editor, instantiationService, contextKeyService, themeService, codeEditorService, configurationService) {
            super(instantiationService, contextKeyService, themeService, new standaloneLayoutService_1.EditorScopedLayoutService(editor.getContainerDomNode(), codeEditorService), configurationService);
            this.host = undefined;
            // Use the passed in code editor as host for the quick input widget
            const contribution = QuickInputEditorContribution.get(editor);
            if (contribution) {
                const widget = contribution.widget;
                this.host = {
                    _serviceBrand: undefined,
                    get mainContainer() { return widget.getDomNode(); },
                    getContainer() { return widget.getDomNode(); },
                    whenContainerStylesLoaded() { return undefined; },
                    get containers() { return [widget.getDomNode()]; },
                    get activeContainer() { return widget.getDomNode(); },
                    get mainContainerDimension() { return editor.getLayoutInfo(); },
                    get activeContainerDimension() { return editor.getLayoutInfo(); },
                    get onDidLayoutMainContainer() { return editor.onDidLayoutChange; },
                    get onDidLayoutActiveContainer() { return editor.onDidLayoutChange; },
                    get onDidLayoutContainer() { return event_1.Event.map(editor.onDidLayoutChange, dimension => ({ container: widget.getDomNode(), dimension })); },
                    get onDidChangeActiveContainer() { return event_1.Event.None; },
                    get onDidAddContainer() { return event_1.Event.None; },
                    get mainContainerOffset() { return { top: 0, quickPickTop: 0 }; },
                    get activeContainerOffset() { return { top: 0, quickPickTop: 0 }; },
                    focus: () => editor.focus()
                };
            }
            else {
                this.host = undefined;
            }
        }
        createController() {
            return super.createController(this.host);
        }
    };
    EditorScopedQuickInputService = __decorate([
        __param(1, instantiation_1.IInstantiationService),
        __param(2, contextkey_1.IContextKeyService),
        __param(3, themeService_1.IThemeService),
        __param(4, codeEditorService_1.ICodeEditorService),
        __param(5, configuration_1.IConfigurationService)
    ], EditorScopedQuickInputService);
    let StandaloneQuickInputService = class StandaloneQuickInputService {
        get activeService() {
            const editor = this.codeEditorService.getFocusedCodeEditor();
            if (!editor) {
                throw new Error('Quick input service needs a focused editor to work.');
            }
            // Find the quick input implementation for the focused
            // editor or create it lazily if not yet created
            let quickInputService = this.mapEditorToService.get(editor);
            if (!quickInputService) {
                const newQuickInputService = quickInputService = this.instantiationService.createInstance(EditorScopedQuickInputService, editor);
                this.mapEditorToService.set(editor, quickInputService);
                (0, functional_1.createSingleCallFunction)(editor.onDidDispose)(() => {
                    newQuickInputService.dispose();
                    this.mapEditorToService.delete(editor);
                });
            }
            return quickInputService;
        }
        get currentQuickInput() { return this.activeService.currentQuickInput; }
        get quickAccess() { return this.activeService.quickAccess; }
        constructor(instantiationService, codeEditorService) {
            this.instantiationService = instantiationService;
            this.codeEditorService = codeEditorService;
            this.mapEditorToService = new Map();
        }
        pick(picks, options, token = cancellation_1.CancellationToken.None) {
            return this.activeService /* TS fail */.pick(picks, options, token);
        }
        createQuickPick(options = { useSeparators: false }) {
            return this.activeService.createQuickPick(options);
        }
        createInputBox() {
            return this.activeService.createInputBox();
        }
    };
    exports.StandaloneQuickInputService = StandaloneQuickInputService;
    exports.StandaloneQuickInputService = StandaloneQuickInputService = __decorate([
        __param(0, instantiation_1.IInstantiationService),
        __param(1, codeEditorService_1.ICodeEditorService)
    ], StandaloneQuickInputService);
    class QuickInputEditorContribution {
        static { this.ID = 'editor.controller.quickInput'; }
        static get(editor) {
            return editor.getContribution(QuickInputEditorContribution.ID);
        }
        constructor(editor) {
            this.editor = editor;
            this.widget = new QuickInputEditorWidget(this.editor);
        }
        dispose() {
            this.widget.dispose();
        }
    }
    exports.QuickInputEditorContribution = QuickInputEditorContribution;
    class QuickInputEditorWidget {
        static { this.ID = 'editor.contrib.quickInputWidget'; }
        constructor(codeEditor) {
            this.codeEditor = codeEditor;
            this.domNode = document.createElement('div');
            this.codeEditor.addOverlayWidget(this);
        }
        getId() {
            return QuickInputEditorWidget.ID;
        }
        getDomNode() {
            return this.domNode;
        }
        getPosition() {
            return { preference: 2 /* OverlayWidgetPositionPreference.TOP_CENTER */ };
        }
        dispose() {
            this.codeEditor.removeOverlayWidget(this);
        }
    }
    exports.QuickInputEditorWidget = QuickInputEditorWidget;
    (0, editorExtensions_1.registerEditorContribution)(QuickInputEditorContribution.ID, QuickInputEditorContribution, 4 /* EditorContributionInstantiation.Lazy */);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[284/*vs/platform/undoRedo/common/undoRedo*/], __M([1/*require*/,0/*exports*/,7/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.UndoRedoSource = exports.UndoRedoGroup = exports.ResourceEditStackSnapshot = exports.IUndoRedoService = void 0;
    exports.IUndoRedoService = (0, instantiation_1.createDecorator)('undoRedoService');
    class ResourceEditStackSnapshot {
        constructor(resource, elements) {
            this.resource = resource;
            this.elements = elements;
        }
    }
    exports.ResourceEditStackSnapshot = ResourceEditStackSnapshot;
    class UndoRedoGroup {
        static { this._ID = 0; }
        constructor() {
            this.id = UndoRedoGroup._ID++;
            this.order = 1;
        }
        nextOrder() {
            if (this.id === 0) {
                return 0;
            }
            return this.order++;
        }
        static { this.None = new UndoRedoGroup(); }
    }
    exports.UndoRedoGroup = UndoRedoGroup;
    class UndoRedoSource {
        static { this._ID = 0; }
        constructor() {
            this.id = UndoRedoSource._ID++;
            this.order = 1;
        }
        nextOrder() {
            if (this.id === 0) {
                return 0;
            }
            return this.order++;
        }
        static { this.None = new UndoRedoSource(); }
    }
    exports.UndoRedoSource = UndoRedoSource;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[35/*vs/editor/common/model/textModel*/], __M([1/*require*/,0/*exports*/,13/*vs/base/common/arrays*/,33/*vs/base/common/color*/,8/*vs/base/common/errors*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,11/*vs/base/common/strings*/,22/*vs/base/common/uri*/,145/*vs/editor/common/core/eolCounter*/,230/*vs/editor/common/core/indentation*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/,23/*vs/editor/common/core/selection*/,197/*vs/editor/common/core/textModelDefaults*/,43/*vs/editor/common/languages/language*/,36/*vs/editor/common/languages/languageConfigurationRegistry*/,40/*vs/editor/common/model*/,661/*vs/editor/common/model/bracketPairsTextModelPart/bracketPairsImpl*/,783/*vs/editor/common/model/bracketPairsTextModelPart/colorizedBracketPairsDecorationProvider*/,370/*vs/editor/common/model/editStack*/,329/*vs/editor/common/model/guidesTextModelPart*/,577/*vs/editor/common/model/indentationGuesser*/,578/*vs/editor/common/model/intervalTree*/,371/*vs/editor/common/model/pieceTreeTextBuffer/pieceTreeTextBuffer*/,662/*vs/editor/common/model/pieceTreeTextBuffer/pieceTreeTextBufferBuilder*/,202/*vs/editor/common/model/textModelSearch*/,707/*vs/editor/common/model/tokenizationTextModelPart*/,263/*vs/editor/common/model/tokens*/,132/*vs/editor/common/textModelEvents*/,7/*vs/platform/instantiation/common/instantiation*/,284/*vs/platform/undoRedo/common/undoRedo*/]), function (require, exports, arrays_1, color_1, errors_1, event_1, lifecycle_1, strings, uri_1, eolCounter_1, indentation_1, position_1, range_1, selection_1, textModelDefaults_1, language_1, languageConfigurationRegistry_1, model, bracketPairsImpl_1, colorizedBracketPairsDecorationProvider_1, editStack_1, guidesTextModelPart_1, indentationGuesser_1, intervalTree_1, pieceTreeTextBuffer_1, pieceTreeTextBufferBuilder_1, textModelSearch_1, tokenizationTextModelPart_1, tokens_1, textModelEvents_1, instantiation_1, undoRedo_1) {
    "use strict";
    var TextModel_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ModelDecorationOptions = exports.ModelDecorationInjectedTextOptions = exports.ModelDecorationMinimapOptions = exports.ModelDecorationGlyphMarginOptions = exports.ModelDecorationOverviewRulerOptions = exports.TextModel = void 0;
    exports.createTextBufferFactory = createTextBufferFactory;
    exports.createTextBufferFactoryFromSnapshot = createTextBufferFactoryFromSnapshot;
    exports.createTextBuffer = createTextBuffer;
    exports.indentOfLine = indentOfLine;
    function createTextBufferFactory(text) {
        const builder = new pieceTreeTextBufferBuilder_1.PieceTreeTextBufferBuilder();
        builder.acceptChunk(text);
        return builder.finish();
    }
    function createTextBufferFactoryFromSnapshot(snapshot) {
        const builder = new pieceTreeTextBufferBuilder_1.PieceTreeTextBufferBuilder();
        let chunk;
        while (typeof (chunk = snapshot.read()) === 'string') {
            builder.acceptChunk(chunk);
        }
        return builder.finish();
    }
    function createTextBuffer(value, defaultEOL) {
        let factory;
        if (typeof value === 'string') {
            factory = createTextBufferFactory(value);
        }
        else if (model.isITextSnapshot(value)) {
            factory = createTextBufferFactoryFromSnapshot(value);
        }
        else {
            factory = value;
        }
        return factory.create(defaultEOL);
    }
    let MODEL_ID = 0;
    const LIMIT_FIND_COUNT = 999;
    const LONG_LINE_BOUNDARY = 10000;
    class TextModelSnapshot {
        constructor(source) {
            this._source = source;
            this._eos = false;
        }
        read() {
            if (this._eos) {
                return null;
            }
            const result = [];
            let resultCnt = 0;
            let resultLength = 0;
            do {
                const tmp = this._source.read();
                if (tmp === null) {
                    // end-of-stream
                    this._eos = true;
                    if (resultCnt === 0) {
                        return null;
                    }
                    else {
                        return result.join('');
                    }
                }
                if (tmp.length > 0) {
                    result[resultCnt++] = tmp;
                    resultLength += tmp.length;
                }
                if (resultLength >= 64 * 1024) {
                    return result.join('');
                }
            } while (true);
        }
    }
    const invalidFunc = () => { throw new Error(`Invalid change accessor`); };
    let TextModel = class TextModel extends lifecycle_1.Disposable {
        static { TextModel_1 = this; }
        static { this._MODEL_SYNC_LIMIT = 50 * 1024 * 1024; } // 50 MB,  // used in tests
        static { this.LARGE_FILE_SIZE_THRESHOLD = 20 * 1024 * 1024; } // 20 MB;
        static { this.LARGE_FILE_LINE_COUNT_THRESHOLD = 300 * 1000; } // 300K lines
        static { this.LARGE_FILE_HEAP_OPERATION_THRESHOLD = 256 * 1024 * 1024; } // 256M characters, usually ~> 512MB memory usage
        static { this.DEFAULT_CREATION_OPTIONS = {
            isForSimpleWidget: false,
            tabSize: textModelDefaults_1.EDITOR_MODEL_DEFAULTS.tabSize,
            indentSize: textModelDefaults_1.EDITOR_MODEL_DEFAULTS.indentSize,
            insertSpaces: textModelDefaults_1.EDITOR_MODEL_DEFAULTS.insertSpaces,
            detectIndentation: false,
            defaultEOL: 1 /* model.DefaultEndOfLine.LF */,
            trimAutoWhitespace: textModelDefaults_1.EDITOR_MODEL_DEFAULTS.trimAutoWhitespace,
            largeFileOptimizations: textModelDefaults_1.EDITOR_MODEL_DEFAULTS.largeFileOptimizations,
            bracketPairColorizationOptions: textModelDefaults_1.EDITOR_MODEL_DEFAULTS.bracketPairColorizationOptions,
        }; }
        static resolveOptions(textBuffer, options) {
            if (options.detectIndentation) {
                const guessedIndentation = (0, indentationGuesser_1.guessIndentation)(textBuffer, options.tabSize, options.insertSpaces);
                return new model.TextModelResolvedOptions({
                    tabSize: guessedIndentation.tabSize,
                    indentSize: 'tabSize', // TODO@Alex: guess indentSize independent of tabSize
                    insertSpaces: guessedIndentation.insertSpaces,
                    trimAutoWhitespace: options.trimAutoWhitespace,
                    defaultEOL: options.defaultEOL,
                    bracketPairColorizationOptions: options.bracketPairColorizationOptions,
                });
            }
            return new model.TextModelResolvedOptions(options);
        }
        get onDidChangeLanguage() { return this._tokenizationTextModelPart.onDidChangeLanguage; }
        get onDidChangeLanguageConfiguration() { return this._tokenizationTextModelPart.onDidChangeLanguageConfiguration; }
        get onDidChangeTokens() { return this._tokenizationTextModelPart.onDidChangeTokens; }
        onDidChangeContent(listener) {
            return this._eventEmitter.slowEvent((e) => listener(e.contentChangedEvent));
        }
        onDidChangeContentOrInjectedText(listener) {
            return (0, lifecycle_1.combinedDisposable)(this._eventEmitter.fastEvent(e => listener(e)), this._onDidChangeInjectedText.event(e => listener(e)));
        }
        _isDisposing() { return this.__isDisposing; }
        get tokenization() { return this._tokenizationTextModelPart; }
        get bracketPairs() { return this._bracketPairs; }
        get guides() { return this._guidesTextModelPart; }
        constructor(source, languageIdOrSelection, creationOptions, associatedResource = null, _undoRedoService, _languageService, _languageConfigurationService, instantiationService) {
            super();
            this._undoRedoService = _undoRedoService;
            this._languageService = _languageService;
            this._languageConfigurationService = _languageConfigurationService;
            this.instantiationService = instantiationService;
            //#region Events
            this._onWillDispose = this._register(new event_1.Emitter());
            this.onWillDispose = this._onWillDispose.event;
            this._onDidChangeDecorations = this._register(new DidChangeDecorationsEmitter(affectedInjectedTextLines => this.handleBeforeFireDecorationsChangedEvent(affectedInjectedTextLines)));
            this.onDidChangeDecorations = this._onDidChangeDecorations.event;
            this._onDidChangeOptions = this._register(new event_1.Emitter());
            this.onDidChangeOptions = this._onDidChangeOptions.event;
            this._onDidChangeAttached = this._register(new event_1.Emitter());
            this.onDidChangeAttached = this._onDidChangeAttached.event;
            this._onDidChangeInjectedText = this._register(new event_1.Emitter());
            this._eventEmitter = this._register(new DidChangeContentEmitter());
            this._languageSelectionListener = this._register(new lifecycle_1.MutableDisposable());
            this._deltaDecorationCallCnt = 0;
            this._attachedViews = new tokens_1.AttachedViews();
            // Generate a new unique model id
            MODEL_ID++;
            this.id = '$model' + MODEL_ID;
            this.isForSimpleWidget = creationOptions.isForSimpleWidget;
            if (typeof associatedResource === 'undefined' || associatedResource === null) {
                this._associatedResource = uri_1.URI.parse('inmemory://model/' + MODEL_ID);
            }
            else {
                this._associatedResource = associatedResource;
            }
            this._attachedEditorCount = 0;
            const { textBuffer, disposable } = createTextBuffer(source, creationOptions.defaultEOL);
            this._buffer = textBuffer;
            this._bufferDisposable = disposable;
            this._options = TextModel_1.resolveOptions(this._buffer, creationOptions);
            const languageId = (typeof languageIdOrSelection === 'string' ? languageIdOrSelection : languageIdOrSelection.languageId);
            if (typeof languageIdOrSelection !== 'string') {
                this._languageSelectionListener.value = languageIdOrSelection.onDidChange(() => this._setLanguage(languageIdOrSelection.languageId));
            }
            this._bracketPairs = this._register(new bracketPairsImpl_1.BracketPairsTextModelPart(this, this._languageConfigurationService));
            this._guidesTextModelPart = this._register(new guidesTextModelPart_1.GuidesTextModelPart(this, this._languageConfigurationService));
            this._decorationProvider = this._register(new colorizedBracketPairsDecorationProvider_1.ColorizedBracketPairsDecorationProvider(this));
            this._tokenizationTextModelPart = this.instantiationService.createInstance(tokenizationTextModelPart_1.TokenizationTextModelPart, this, this._bracketPairs, languageId, this._attachedViews);
            const bufferLineCount = this._buffer.getLineCount();
            const bufferTextLength = this._buffer.getValueLengthInRange(new range_1.Range(1, 1, bufferLineCount, this._buffer.getLineLength(bufferLineCount) + 1), 0 /* model.EndOfLinePreference.TextDefined */);
            // !!! Make a decision in the ctor and permanently respect this decision !!!
            // If a model is too large at construction time, it will never get tokenized,
            // under no circumstances.
            if (creationOptions.largeFileOptimizations) {
                this._isTooLargeForTokenization = ((bufferTextLength > TextModel_1.LARGE_FILE_SIZE_THRESHOLD)
                    || (bufferLineCount > TextModel_1.LARGE_FILE_LINE_COUNT_THRESHOLD));
                this._isTooLargeForHeapOperation = bufferTextLength > TextModel_1.LARGE_FILE_HEAP_OPERATION_THRESHOLD;
            }
            else {
                this._isTooLargeForTokenization = false;
                this._isTooLargeForHeapOperation = false;
            }
            this._isTooLargeForSyncing = (bufferTextLength > TextModel_1._MODEL_SYNC_LIMIT);
            this._versionId = 1;
            this._alternativeVersionId = 1;
            this._initialUndoRedoSnapshot = null;
            this._isDisposed = false;
            this.__isDisposing = false;
            this._instanceId = strings.singleLetterHash(MODEL_ID);
            this._lastDecorationId = 0;
            this._decorations = Object.create(null);
            this._decorationsTree = new DecorationsTrees();
            this._commandManager = new editStack_1.EditStack(this, this._undoRedoService);
            this._isUndoing = false;
            this._isRedoing = false;
            this._trimAutoWhitespaceLines = null;
            this._register(this._decorationProvider.onDidChange(() => {
                this._onDidChangeDecorations.beginDeferredEmit();
                this._onDidChangeDecorations.fire();
                this._onDidChangeDecorations.endDeferredEmit();
            }));
            this._languageService.requestRichLanguageFeatures(languageId);
            this._register(this._languageConfigurationService.onDidChange(e => {
                this._bracketPairs.handleLanguageConfigurationServiceChange(e);
                this._tokenizationTextModelPart.handleLanguageConfigurationServiceChange(e);
            }));
        }
        dispose() {
            this.__isDisposing = true;
            this._onWillDispose.fire();
            this._tokenizationTextModelPart.dispose();
            this._isDisposed = true;
            super.dispose();
            this._bufferDisposable.dispose();
            this.__isDisposing = false;
            // Manually release reference to previous text buffer to avoid large leaks
            // in case someone leaks a TextModel reference
            const emptyDisposedTextBuffer = new pieceTreeTextBuffer_1.PieceTreeTextBuffer([], '', '\n', false, false, true, true);
            emptyDisposedTextBuffer.dispose();
            this._buffer = emptyDisposedTextBuffer;
            this._bufferDisposable = lifecycle_1.Disposable.None;
        }
        _assertNotDisposed() {
            if (this._isDisposed) {
                throw new errors_1.BugIndicatingError('Model is disposed!');
            }
        }
        _emitContentChangedEvent(rawChange, change) {
            if (this.__isDisposing) {
                // Do not confuse listeners by emitting any event after disposing
                return;
            }
            this._tokenizationTextModelPart.handleDidChangeContent(change);
            this._bracketPairs.handleDidChangeContent(change);
            this._eventEmitter.fire(new textModelEvents_1.InternalModelContentChangeEvent(rawChange, change));
        }
        setValue(value) {
            this._assertNotDisposed();
            if (value === null || value === undefined) {
                throw (0, errors_1.illegalArgument)();
            }
            const { textBuffer, disposable } = createTextBuffer(value, this._options.defaultEOL);
            this._setValueFromTextBuffer(textBuffer, disposable);
        }
        _createContentChanged2(range, rangeOffset, rangeLength, text, isUndoing, isRedoing, isFlush, isEolChange) {
            return {
                changes: [{
                        range: range,
                        rangeOffset: rangeOffset,
                        rangeLength: rangeLength,
                        text: text,
                    }],
                eol: this._buffer.getEOL(),
                isEolChange: isEolChange,
                versionId: this.getVersionId(),
                isUndoing: isUndoing,
                isRedoing: isRedoing,
                isFlush: isFlush
            };
        }
        _setValueFromTextBuffer(textBuffer, textBufferDisposable) {
            this._assertNotDisposed();
            const oldFullModelRange = this.getFullModelRange();
            const oldModelValueLength = this.getValueLengthInRange(oldFullModelRange);
            const endLineNumber = this.getLineCount();
            const endColumn = this.getLineMaxColumn(endLineNumber);
            this._buffer = textBuffer;
            this._bufferDisposable.dispose();
            this._bufferDisposable = textBufferDisposable;
            this._increaseVersionId();
            // Destroy all my decorations
            this._decorations = Object.create(null);
            this._decorationsTree = new DecorationsTrees();
            // Destroy my edit history and settings
            this._commandManager.clear();
            this._trimAutoWhitespaceLines = null;
            this._emitContentChangedEvent(new textModelEvents_1.ModelRawContentChangedEvent([
                new textModelEvents_1.ModelRawFlush()
            ], this._versionId, false, false), this._createContentChanged2(new range_1.Range(1, 1, endLineNumber, endColumn), 0, oldModelValueLength, this.getValue(), false, false, true, false));
        }
        setEOL(eol) {
            this._assertNotDisposed();
            const newEOL = (eol === 1 /* model.EndOfLineSequence.CRLF */ ? '\r\n' : '\n');
            if (this._buffer.getEOL() === newEOL) {
                // Nothing to do
                return;
            }
            const oldFullModelRange = this.getFullModelRange();
            const oldModelValueLength = this.getValueLengthInRange(oldFullModelRange);
            const endLineNumber = this.getLineCount();
            const endColumn = this.getLineMaxColumn(endLineNumber);
            this._onBeforeEOLChange();
            this._buffer.setEOL(newEOL);
            this._increaseVersionId();
            this._onAfterEOLChange();
            this._emitContentChangedEvent(new textModelEvents_1.ModelRawContentChangedEvent([
                new textModelEvents_1.ModelRawEOLChanged()
            ], this._versionId, false, false), this._createContentChanged2(new range_1.Range(1, 1, endLineNumber, endColumn), 0, oldModelValueLength, this.getValue(), false, false, false, true));
        }
        _onBeforeEOLChange() {
            // Ensure all decorations get their `range` set.
            this._decorationsTree.ensureAllNodesHaveRanges(this);
        }
        _onAfterEOLChange() {
            // Transform back `range` to offsets
            const versionId = this.getVersionId();
            const allDecorations = this._decorationsTree.collectNodesPostOrder();
            for (let i = 0, len = allDecorations.length; i < len; i++) {
                const node = allDecorations[i];
                const range = node.range; // the range is defined due to `_onBeforeEOLChange`
                const delta = node.cachedAbsoluteStart - node.start;
                const startOffset = this._buffer.getOffsetAt(range.startLineNumber, range.startColumn);
                const endOffset = this._buffer.getOffsetAt(range.endLineNumber, range.endColumn);
                node.cachedAbsoluteStart = startOffset;
                node.cachedAbsoluteEnd = endOffset;
                node.cachedVersionId = versionId;
                node.start = startOffset - delta;
                node.end = endOffset - delta;
                (0, intervalTree_1.recomputeMaxEnd)(node);
            }
        }
        onBeforeAttached() {
            this._attachedEditorCount++;
            if (this._attachedEditorCount === 1) {
                this._tokenizationTextModelPart.handleDidChangeAttached();
                this._onDidChangeAttached.fire(undefined);
            }
            return this._attachedViews.attachView();
        }
        onBeforeDetached(view) {
            this._attachedEditorCount--;
            if (this._attachedEditorCount === 0) {
                this._tokenizationTextModelPart.handleDidChangeAttached();
                this._onDidChangeAttached.fire(undefined);
            }
            this._attachedViews.detachView(view);
        }
        isAttachedToEditor() {
            return this._attachedEditorCount > 0;
        }
        getAttachedEditorCount() {
            return this._attachedEditorCount;
        }
        isTooLargeForSyncing() {
            return this._isTooLargeForSyncing;
        }
        isTooLargeForTokenization() {
            return this._isTooLargeForTokenization;
        }
        isTooLargeForHeapOperation() {
            return this._isTooLargeForHeapOperation;
        }
        isDisposed() {
            return this._isDisposed;
        }
        isDominatedByLongLines() {
            this._assertNotDisposed();
            if (this.isTooLargeForTokenization()) {
                // Cannot word wrap huge files anyways, so it doesn't really matter
                return false;
            }
            let smallLineCharCount = 0;
            let longLineCharCount = 0;
            const lineCount = this._buffer.getLineCount();
            for (let lineNumber = 1; lineNumber <= lineCount; lineNumber++) {
                const lineLength = this._buffer.getLineLength(lineNumber);
                if (lineLength >= LONG_LINE_BOUNDARY) {
                    longLineCharCount += lineLength;
                }
                else {
                    smallLineCharCount += lineLength;
                }
            }
            return (longLineCharCount > smallLineCharCount);
        }
        get uri() {
            return this._associatedResource;
        }
        //#region Options
        getOptions() {
            this._assertNotDisposed();
            return this._options;
        }
        getFormattingOptions() {
            return {
                tabSize: this._options.indentSize,
                insertSpaces: this._options.insertSpaces
            };
        }
        updateOptions(_newOpts) {
            this._assertNotDisposed();
            const tabSize = (typeof _newOpts.tabSize !== 'undefined') ? _newOpts.tabSize : this._options.tabSize;
            const indentSize = (typeof _newOpts.indentSize !== 'undefined') ? _newOpts.indentSize : this._options.originalIndentSize;
            const insertSpaces = (typeof _newOpts.insertSpaces !== 'undefined') ? _newOpts.insertSpaces : this._options.insertSpaces;
            const trimAutoWhitespace = (typeof _newOpts.trimAutoWhitespace !== 'undefined') ? _newOpts.trimAutoWhitespace : this._options.trimAutoWhitespace;
            const bracketPairColorizationOptions = (typeof _newOpts.bracketColorizationOptions !== 'undefined') ? _newOpts.bracketColorizationOptions : this._options.bracketPairColorizationOptions;
            const newOpts = new model.TextModelResolvedOptions({
                tabSize: tabSize,
                indentSize: indentSize,
                insertSpaces: insertSpaces,
                defaultEOL: this._options.defaultEOL,
                trimAutoWhitespace: trimAutoWhitespace,
                bracketPairColorizationOptions,
            });
            if (this._options.equals(newOpts)) {
                return;
            }
            const e = this._options.createChangeEvent(newOpts);
            this._options = newOpts;
            this._bracketPairs.handleDidChangeOptions(e);
            this._decorationProvider.handleDidChangeOptions(e);
            this._onDidChangeOptions.fire(e);
        }
        detectIndentation(defaultInsertSpaces, defaultTabSize) {
            this._assertNotDisposed();
            const guessedIndentation = (0, indentationGuesser_1.guessIndentation)(this._buffer, defaultTabSize, defaultInsertSpaces);
            this.updateOptions({
                insertSpaces: guessedIndentation.insertSpaces,
                tabSize: guessedIndentation.tabSize,
                indentSize: guessedIndentation.tabSize, // TODO@Alex: guess indentSize independent of tabSize
            });
        }
        normalizeIndentation(str) {
            this._assertNotDisposed();
            return (0, indentation_1.normalizeIndentation)(str, this._options.indentSize, this._options.insertSpaces);
        }
        //#endregion
        //#region Reading
        getVersionId() {
            this._assertNotDisposed();
            return this._versionId;
        }
        mightContainRTL() {
            return this._buffer.mightContainRTL();
        }
        mightContainUnusualLineTerminators() {
            return this._buffer.mightContainUnusualLineTerminators();
        }
        removeUnusualLineTerminators(selections = null) {
            const matches = this.findMatches(strings.UNUSUAL_LINE_TERMINATORS.source, false, true, false, null, false, 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */);
            this._buffer.resetMightContainUnusualLineTerminators();
            this.pushEditOperations(selections, matches.map(m => ({ range: m.range, text: null })), () => null);
        }
        mightContainNonBasicASCII() {
            return this._buffer.mightContainNonBasicASCII();
        }
        getAlternativeVersionId() {
            this._assertNotDisposed();
            return this._alternativeVersionId;
        }
        getInitialUndoRedoSnapshot() {
            this._assertNotDisposed();
            return this._initialUndoRedoSnapshot;
        }
        getOffsetAt(rawPosition) {
            this._assertNotDisposed();
            const position = this._validatePosition(rawPosition.lineNumber, rawPosition.column, 0 /* StringOffsetValidationType.Relaxed */);
            return this._buffer.getOffsetAt(position.lineNumber, position.column);
        }
        getPositionAt(rawOffset) {
            this._assertNotDisposed();
            const offset = (Math.min(this._buffer.getLength(), Math.max(0, rawOffset)));
            return this._buffer.getPositionAt(offset);
        }
        _increaseVersionId() {
            this._versionId = this._versionId + 1;
            this._alternativeVersionId = this._versionId;
        }
        _overwriteVersionId(versionId) {
            this._versionId = versionId;
        }
        _overwriteAlternativeVersionId(newAlternativeVersionId) {
            this._alternativeVersionId = newAlternativeVersionId;
        }
        _overwriteInitialUndoRedoSnapshot(newInitialUndoRedoSnapshot) {
            this._initialUndoRedoSnapshot = newInitialUndoRedoSnapshot;
        }
        getValue(eol, preserveBOM = false) {
            this._assertNotDisposed();
            if (this.isTooLargeForHeapOperation()) {
                throw new errors_1.BugIndicatingError('Operation would exceed heap memory limits');
            }
            const fullModelRange = this.getFullModelRange();
            const fullModelValue = this.getValueInRange(fullModelRange, eol);
            if (preserveBOM) {
                return this._buffer.getBOM() + fullModelValue;
            }
            return fullModelValue;
        }
        createSnapshot(preserveBOM = false) {
            return new TextModelSnapshot(this._buffer.createSnapshot(preserveBOM));
        }
        getValueLength(eol, preserveBOM = false) {
            this._assertNotDisposed();
            const fullModelRange = this.getFullModelRange();
            const fullModelValue = this.getValueLengthInRange(fullModelRange, eol);
            if (preserveBOM) {
                return this._buffer.getBOM().length + fullModelValue;
            }
            return fullModelValue;
        }
        getValueInRange(rawRange, eol = 0 /* model.EndOfLinePreference.TextDefined */) {
            this._assertNotDisposed();
            return this._buffer.getValueInRange(this.validateRange(rawRange), eol);
        }
        getValueLengthInRange(rawRange, eol = 0 /* model.EndOfLinePreference.TextDefined */) {
            this._assertNotDisposed();
            return this._buffer.getValueLengthInRange(this.validateRange(rawRange), eol);
        }
        getCharacterCountInRange(rawRange, eol = 0 /* model.EndOfLinePreference.TextDefined */) {
            this._assertNotDisposed();
            return this._buffer.getCharacterCountInRange(this.validateRange(rawRange), eol);
        }
        getLineCount() {
            this._assertNotDisposed();
            return this._buffer.getLineCount();
        }
        getLineContent(lineNumber) {
            this._assertNotDisposed();
            if (lineNumber < 1 || lineNumber > this.getLineCount()) {
                throw new errors_1.BugIndicatingError('Illegal value for lineNumber');
            }
            return this._buffer.getLineContent(lineNumber);
        }
        getLineLength(lineNumber) {
            this._assertNotDisposed();
            if (lineNumber < 1 || lineNumber > this.getLineCount()) {
                throw new errors_1.BugIndicatingError('Illegal value for lineNumber');
            }
            return this._buffer.getLineLength(lineNumber);
        }
        getLinesContent() {
            this._assertNotDisposed();
            if (this.isTooLargeForHeapOperation()) {
                throw new errors_1.BugIndicatingError('Operation would exceed heap memory limits');
            }
            return this._buffer.getLinesContent();
        }
        getEOL() {
            this._assertNotDisposed();
            return this._buffer.getEOL();
        }
        getEndOfLineSequence() {
            this._assertNotDisposed();
            return (this._buffer.getEOL() === '\n'
                ? 0 /* model.EndOfLineSequence.LF */
                : 1 /* model.EndOfLineSequence.CRLF */);
        }
        getLineMinColumn(lineNumber) {
            this._assertNotDisposed();
            return 1;
        }
        getLineMaxColumn(lineNumber) {
            this._assertNotDisposed();
            if (lineNumber < 1 || lineNumber > this.getLineCount()) {
                throw new errors_1.BugIndicatingError('Illegal value for lineNumber');
            }
            return this._buffer.getLineLength(lineNumber) + 1;
        }
        getLineFirstNonWhitespaceColumn(lineNumber) {
            this._assertNotDisposed();
            if (lineNumber < 1 || lineNumber > this.getLineCount()) {
                throw new errors_1.BugIndicatingError('Illegal value for lineNumber');
            }
            return this._buffer.getLineFirstNonWhitespaceColumn(lineNumber);
        }
        getLineLastNonWhitespaceColumn(lineNumber) {
            this._assertNotDisposed();
            if (lineNumber < 1 || lineNumber > this.getLineCount()) {
                throw new errors_1.BugIndicatingError('Illegal value for lineNumber');
            }
            return this._buffer.getLineLastNonWhitespaceColumn(lineNumber);
        }
        /**
         * Validates `range` is within buffer bounds, but allows it to sit in between surrogate pairs, etc.
         * Will try to not allocate if possible.
         */
        _validateRangeRelaxedNoAllocations(range) {
            const linesCount = this._buffer.getLineCount();
            const initialStartLineNumber = range.startLineNumber;
            const initialStartColumn = range.startColumn;
            let startLineNumber = Math.floor((typeof initialStartLineNumber === 'number' && !isNaN(initialStartLineNumber)) ? initialStartLineNumber : 1);
            let startColumn = Math.floor((typeof initialStartColumn === 'number' && !isNaN(initialStartColumn)) ? initialStartColumn : 1);
            if (startLineNumber < 1) {
                startLineNumber = 1;
                startColumn = 1;
            }
            else if (startLineNumber > linesCount) {
                startLineNumber = linesCount;
                startColumn = this.getLineMaxColumn(startLineNumber);
            }
            else {
                if (startColumn <= 1) {
                    startColumn = 1;
                }
                else {
                    const maxColumn = this.getLineMaxColumn(startLineNumber);
                    if (startColumn >= maxColumn) {
                        startColumn = maxColumn;
                    }
                }
            }
            const initialEndLineNumber = range.endLineNumber;
            const initialEndColumn = range.endColumn;
            let endLineNumber = Math.floor((typeof initialEndLineNumber === 'number' && !isNaN(initialEndLineNumber)) ? initialEndLineNumber : 1);
            let endColumn = Math.floor((typeof initialEndColumn === 'number' && !isNaN(initialEndColumn)) ? initialEndColumn : 1);
            if (endLineNumber < 1) {
                endLineNumber = 1;
                endColumn = 1;
            }
            else if (endLineNumber > linesCount) {
                endLineNumber = linesCount;
                endColumn = this.getLineMaxColumn(endLineNumber);
            }
            else {
                if (endColumn <= 1) {
                    endColumn = 1;
                }
                else {
                    const maxColumn = this.getLineMaxColumn(endLineNumber);
                    if (endColumn >= maxColumn) {
                        endColumn = maxColumn;
                    }
                }
            }
            if (initialStartLineNumber === startLineNumber
                && initialStartColumn === startColumn
                && initialEndLineNumber === endLineNumber
                && initialEndColumn === endColumn
                && range instanceof range_1.Range
                && !(range instanceof selection_1.Selection)) {
                return range;
            }
            return new range_1.Range(startLineNumber, startColumn, endLineNumber, endColumn);
        }
        _isValidPosition(lineNumber, column, validationType) {
            if (typeof lineNumber !== 'number' || typeof column !== 'number') {
                return false;
            }
            if (isNaN(lineNumber) || isNaN(column)) {
                return false;
            }
            if (lineNumber < 1 || column < 1) {
                return false;
            }
            if ((lineNumber | 0) !== lineNumber || (column | 0) !== column) {
                return false;
            }
            const lineCount = this._buffer.getLineCount();
            if (lineNumber > lineCount) {
                return false;
            }
            if (column === 1) {
                return true;
            }
            const maxColumn = this.getLineMaxColumn(lineNumber);
            if (column > maxColumn) {
                return false;
            }
            if (validationType === 1 /* StringOffsetValidationType.SurrogatePairs */) {
                // !!At this point, column > 1
                const charCodeBefore = this._buffer.getLineCharCode(lineNumber, column - 2);
                if (strings.isHighSurrogate(charCodeBefore)) {
                    return false;
                }
            }
            return true;
        }
        _validatePosition(_lineNumber, _column, validationType) {
            const lineNumber = Math.floor((typeof _lineNumber === 'number' && !isNaN(_lineNumber)) ? _lineNumber : 1);
            const column = Math.floor((typeof _column === 'number' && !isNaN(_column)) ? _column : 1);
            const lineCount = this._buffer.getLineCount();
            if (lineNumber < 1) {
                return new position_1.Position(1, 1);
            }
            if (lineNumber > lineCount) {
                return new position_1.Position(lineCount, this.getLineMaxColumn(lineCount));
            }
            if (column <= 1) {
                return new position_1.Position(lineNumber, 1);
            }
            const maxColumn = this.getLineMaxColumn(lineNumber);
            if (column >= maxColumn) {
                return new position_1.Position(lineNumber, maxColumn);
            }
            if (validationType === 1 /* StringOffsetValidationType.SurrogatePairs */) {
                // If the position would end up in the middle of a high-low surrogate pair,
                // we move it to before the pair
                // !!At this point, column > 1
                const charCodeBefore = this._buffer.getLineCharCode(lineNumber, column - 2);
                if (strings.isHighSurrogate(charCodeBefore)) {
                    return new position_1.Position(lineNumber, column - 1);
                }
            }
            return new position_1.Position(lineNumber, column);
        }
        validatePosition(position) {
            const validationType = 1 /* StringOffsetValidationType.SurrogatePairs */;
            this._assertNotDisposed();
            // Avoid object allocation and cover most likely case
            if (position instanceof position_1.Position) {
                if (this._isValidPosition(position.lineNumber, position.column, validationType)) {
                    return position;
                }
            }
            return this._validatePosition(position.lineNumber, position.column, validationType);
        }
        _isValidRange(range, validationType) {
            const startLineNumber = range.startLineNumber;
            const startColumn = range.startColumn;
            const endLineNumber = range.endLineNumber;
            const endColumn = range.endColumn;
            if (!this._isValidPosition(startLineNumber, startColumn, 0 /* StringOffsetValidationType.Relaxed */)) {
                return false;
            }
            if (!this._isValidPosition(endLineNumber, endColumn, 0 /* StringOffsetValidationType.Relaxed */)) {
                return false;
            }
            if (validationType === 1 /* StringOffsetValidationType.SurrogatePairs */) {
                const charCodeBeforeStart = (startColumn > 1 ? this._buffer.getLineCharCode(startLineNumber, startColumn - 2) : 0);
                const charCodeBeforeEnd = (endColumn > 1 && endColumn <= this._buffer.getLineLength(endLineNumber) ? this._buffer.getLineCharCode(endLineNumber, endColumn - 2) : 0);
                const startInsideSurrogatePair = strings.isHighSurrogate(charCodeBeforeStart);
                const endInsideSurrogatePair = strings.isHighSurrogate(charCodeBeforeEnd);
                if (!startInsideSurrogatePair && !endInsideSurrogatePair) {
                    return true;
                }
                return false;
            }
            return true;
        }
        validateRange(_range) {
            const validationType = 1 /* StringOffsetValidationType.SurrogatePairs */;
            this._assertNotDisposed();
            // Avoid object allocation and cover most likely case
            if ((_range instanceof range_1.Range) && !(_range instanceof selection_1.Selection)) {
                if (this._isValidRange(_range, validationType)) {
                    return _range;
                }
            }
            const start = this._validatePosition(_range.startLineNumber, _range.startColumn, 0 /* StringOffsetValidationType.Relaxed */);
            const end = this._validatePosition(_range.endLineNumber, _range.endColumn, 0 /* StringOffsetValidationType.Relaxed */);
            const startLineNumber = start.lineNumber;
            const startColumn = start.column;
            const endLineNumber = end.lineNumber;
            const endColumn = end.column;
            if (validationType === 1 /* StringOffsetValidationType.SurrogatePairs */) {
                const charCodeBeforeStart = (startColumn > 1 ? this._buffer.getLineCharCode(startLineNumber, startColumn - 2) : 0);
                const charCodeBeforeEnd = (endColumn > 1 && endColumn <= this._buffer.getLineLength(endLineNumber) ? this._buffer.getLineCharCode(endLineNumber, endColumn - 2) : 0);
                const startInsideSurrogatePair = strings.isHighSurrogate(charCodeBeforeStart);
                const endInsideSurrogatePair = strings.isHighSurrogate(charCodeBeforeEnd);
                if (!startInsideSurrogatePair && !endInsideSurrogatePair) {
                    return new range_1.Range(startLineNumber, startColumn, endLineNumber, endColumn);
                }
                if (startLineNumber === endLineNumber && startColumn === endColumn) {
                    // do not expand a collapsed range, simply move it to a valid location
                    return new range_1.Range(startLineNumber, startColumn - 1, endLineNumber, endColumn - 1);
                }
                if (startInsideSurrogatePair && endInsideSurrogatePair) {
                    // expand range at both ends
                    return new range_1.Range(startLineNumber, startColumn - 1, endLineNumber, endColumn + 1);
                }
                if (startInsideSurrogatePair) {
                    // only expand range at the start
                    return new range_1.Range(startLineNumber, startColumn - 1, endLineNumber, endColumn);
                }
                // only expand range at the end
                return new range_1.Range(startLineNumber, startColumn, endLineNumber, endColumn + 1);
            }
            return new range_1.Range(startLineNumber, startColumn, endLineNumber, endColumn);
        }
        modifyPosition(rawPosition, offset) {
            this._assertNotDisposed();
            const candidate = this.getOffsetAt(rawPosition) + offset;
            return this.getPositionAt(Math.min(this._buffer.getLength(), Math.max(0, candidate)));
        }
        getFullModelRange() {
            this._assertNotDisposed();
            const lineCount = this.getLineCount();
            return new range_1.Range(1, 1, lineCount, this.getLineMaxColumn(lineCount));
        }
        findMatchesLineByLine(searchRange, searchData, captureMatches, limitResultCount) {
            return this._buffer.findMatchesLineByLine(searchRange, searchData, captureMatches, limitResultCount);
        }
        findMatches(searchString, rawSearchScope, isRegex, matchCase, wordSeparators, captureMatches, limitResultCount = LIMIT_FIND_COUNT) {
            this._assertNotDisposed();
            let searchRanges = null;
            if (rawSearchScope !== null) {
                if (!Array.isArray(rawSearchScope)) {
                    rawSearchScope = [rawSearchScope];
                }
                if (rawSearchScope.every((searchScope) => range_1.Range.isIRange(searchScope))) {
                    searchRanges = rawSearchScope.map((searchScope) => this.validateRange(searchScope));
                }
            }
            if (searchRanges === null) {
                searchRanges = [this.getFullModelRange()];
            }
            searchRanges = searchRanges.sort((d1, d2) => d1.startLineNumber - d2.startLineNumber || d1.startColumn - d2.startColumn);
            const uniqueSearchRanges = [];
            uniqueSearchRanges.push(searchRanges.reduce((prev, curr) => {
                if (range_1.Range.areIntersecting(prev, curr)) {
                    return prev.plusRange(curr);
                }
                uniqueSearchRanges.push(prev);
                return curr;
            }));
            let matchMapper;
            if (!isRegex && searchString.indexOf('\n') < 0) {
                // not regex, not multi line
                const searchParams = new textModelSearch_1.SearchParams(searchString, isRegex, matchCase, wordSeparators);
                const searchData = searchParams.parseSearchRequest();
                if (!searchData) {
                    return [];
                }
                matchMapper = (searchRange) => this.findMatchesLineByLine(searchRange, searchData, captureMatches, limitResultCount);
            }
            else {
                matchMapper = (searchRange) => textModelSearch_1.TextModelSearch.findMatches(this, new textModelSearch_1.SearchParams(searchString, isRegex, matchCase, wordSeparators), searchRange, captureMatches, limitResultCount);
            }
            return uniqueSearchRanges.map(matchMapper).reduce((arr, matches) => arr.concat(matches), []);
        }
        findNextMatch(searchString, rawSearchStart, isRegex, matchCase, wordSeparators, captureMatches) {
            this._assertNotDisposed();
            const searchStart = this.validatePosition(rawSearchStart);
            if (!isRegex && searchString.indexOf('\n') < 0) {
                const searchParams = new textModelSearch_1.SearchParams(searchString, isRegex, matchCase, wordSeparators);
                const searchData = searchParams.parseSearchRequest();
                if (!searchData) {
                    return null;
                }
                const lineCount = this.getLineCount();
                let searchRange = new range_1.Range(searchStart.lineNumber, searchStart.column, lineCount, this.getLineMaxColumn(lineCount));
                let ret = this.findMatchesLineByLine(searchRange, searchData, captureMatches, 1);
                textModelSearch_1.TextModelSearch.findNextMatch(this, new textModelSearch_1.SearchParams(searchString, isRegex, matchCase, wordSeparators), searchStart, captureMatches);
                if (ret.length > 0) {
                    return ret[0];
                }
                searchRange = new range_1.Range(1, 1, searchStart.lineNumber, this.getLineMaxColumn(searchStart.lineNumber));
                ret = this.findMatchesLineByLine(searchRange, searchData, captureMatches, 1);
                if (ret.length > 0) {
                    return ret[0];
                }
                return null;
            }
            return textModelSearch_1.TextModelSearch.findNextMatch(this, new textModelSearch_1.SearchParams(searchString, isRegex, matchCase, wordSeparators), searchStart, captureMatches);
        }
        findPreviousMatch(searchString, rawSearchStart, isRegex, matchCase, wordSeparators, captureMatches) {
            this._assertNotDisposed();
            const searchStart = this.validatePosition(rawSearchStart);
            return textModelSearch_1.TextModelSearch.findPreviousMatch(this, new textModelSearch_1.SearchParams(searchString, isRegex, matchCase, wordSeparators), searchStart, captureMatches);
        }
        //#endregion
        //#region Editing
        pushStackElement() {
            this._commandManager.pushStackElement();
        }
        popStackElement() {
            this._commandManager.popStackElement();
        }
        pushEOL(eol) {
            const currentEOL = (this.getEOL() === '\n' ? 0 /* model.EndOfLineSequence.LF */ : 1 /* model.EndOfLineSequence.CRLF */);
            if (currentEOL === eol) {
                return;
            }
            try {
                this._onDidChangeDecorations.beginDeferredEmit();
                this._eventEmitter.beginDeferredEmit();
                if (this._initialUndoRedoSnapshot === null) {
                    this._initialUndoRedoSnapshot = this._undoRedoService.createSnapshot(this.uri);
                }
                this._commandManager.pushEOL(eol);
            }
            finally {
                this._eventEmitter.endDeferredEmit();
                this._onDidChangeDecorations.endDeferredEmit();
            }
        }
        _validateEditOperation(rawOperation) {
            if (rawOperation instanceof model.ValidAnnotatedEditOperation) {
                return rawOperation;
            }
            return new model.ValidAnnotatedEditOperation(rawOperation.identifier || null, this.validateRange(rawOperation.range), rawOperation.text, rawOperation.forceMoveMarkers || false, rawOperation.isAutoWhitespaceEdit || false, rawOperation._isTracked || false);
        }
        _validateEditOperations(rawOperations) {
            const result = [];
            for (let i = 0, len = rawOperations.length; i < len; i++) {
                result[i] = this._validateEditOperation(rawOperations[i]);
            }
            return result;
        }
        pushEditOperations(beforeCursorState, editOperations, cursorStateComputer, group) {
            try {
                this._onDidChangeDecorations.beginDeferredEmit();
                this._eventEmitter.beginDeferredEmit();
                return this._pushEditOperations(beforeCursorState, this._validateEditOperations(editOperations), cursorStateComputer, group);
            }
            finally {
                this._eventEmitter.endDeferredEmit();
                this._onDidChangeDecorations.endDeferredEmit();
            }
        }
        _pushEditOperations(beforeCursorState, editOperations, cursorStateComputer, group) {
            if (this._options.trimAutoWhitespace && this._trimAutoWhitespaceLines) {
                // Go through each saved line number and insert a trim whitespace edit
                // if it is safe to do so (no conflicts with other edits).
                const incomingEdits = editOperations.map((op) => {
                    return {
                        range: this.validateRange(op.range),
                        text: op.text
                    };
                });
                // Sometimes, auto-formatters change ranges automatically which can cause undesired auto whitespace trimming near the cursor
                // We'll use the following heuristic: if the edits occur near the cursor, then it's ok to trim auto whitespace
                let editsAreNearCursors = true;
                if (beforeCursorState) {
                    for (let i = 0, len = beforeCursorState.length; i < len; i++) {
                        const sel = beforeCursorState[i];
                        let foundEditNearSel = false;
                        for (let j = 0, lenJ = incomingEdits.length; j < lenJ; j++) {
                            const editRange = incomingEdits[j].range;
                            const selIsAbove = editRange.startLineNumber > sel.endLineNumber;
                            const selIsBelow = sel.startLineNumber > editRange.endLineNumber;
                            if (!selIsAbove && !selIsBelow) {
                                foundEditNearSel = true;
                                break;
                            }
                        }
                        if (!foundEditNearSel) {
                            editsAreNearCursors = false;
                            break;
                        }
                    }
                }
                if (editsAreNearCursors) {
                    for (let i = 0, len = this._trimAutoWhitespaceLines.length; i < len; i++) {
                        const trimLineNumber = this._trimAutoWhitespaceLines[i];
                        const maxLineColumn = this.getLineMaxColumn(trimLineNumber);
                        let allowTrimLine = true;
                        for (let j = 0, lenJ = incomingEdits.length; j < lenJ; j++) {
                            const editRange = incomingEdits[j].range;
                            const editText = incomingEdits[j].text;
                            if (trimLineNumber < editRange.startLineNumber || trimLineNumber > editRange.endLineNumber) {
                                // `trimLine` is completely outside this edit
                                continue;
                            }
                            // At this point:
                            //   editRange.startLineNumber <= trimLine <= editRange.endLineNumber
                            if (trimLineNumber === editRange.startLineNumber && editRange.startColumn === maxLineColumn
                                && editRange.isEmpty() && editText && editText.length > 0 && editText.charAt(0) === '\n') {
                                // This edit inserts a new line (and maybe other text) after `trimLine`
                                continue;
                            }
                            if (trimLineNumber === editRange.startLineNumber && editRange.startColumn === 1
                                && editRange.isEmpty() && editText && editText.length > 0 && editText.charAt(editText.length - 1) === '\n') {
                                // This edit inserts a new line (and maybe other text) before `trimLine`
                                continue;
                            }
                            // Looks like we can't trim this line as it would interfere with an incoming edit
                            allowTrimLine = false;
                            break;
                        }
                        if (allowTrimLine) {
                            const trimRange = new range_1.Range(trimLineNumber, 1, trimLineNumber, maxLineColumn);
                            editOperations.push(new model.ValidAnnotatedEditOperation(null, trimRange, null, false, false, false));
                        }
                    }
                }
                this._trimAutoWhitespaceLines = null;
            }
            if (this._initialUndoRedoSnapshot === null) {
                this._initialUndoRedoSnapshot = this._undoRedoService.createSnapshot(this.uri);
            }
            return this._commandManager.pushEditOperation(beforeCursorState, editOperations, cursorStateComputer, group);
        }
        _applyUndo(changes, eol, resultingAlternativeVersionId, resultingSelection) {
            const edits = changes.map((change) => {
                const rangeStart = this.getPositionAt(change.newPosition);
                const rangeEnd = this.getPositionAt(change.newEnd);
                return {
                    range: new range_1.Range(rangeStart.lineNumber, rangeStart.column, rangeEnd.lineNumber, rangeEnd.column),
                    text: change.oldText
                };
            });
            this._applyUndoRedoEdits(edits, eol, true, false, resultingAlternativeVersionId, resultingSelection);
        }
        _applyRedo(changes, eol, resultingAlternativeVersionId, resultingSelection) {
            const edits = changes.map((change) => {
                const rangeStart = this.getPositionAt(change.oldPosition);
                const rangeEnd = this.getPositionAt(change.oldEnd);
                return {
                    range: new range_1.Range(rangeStart.lineNumber, rangeStart.column, rangeEnd.lineNumber, rangeEnd.column),
                    text: change.newText
                };
            });
            this._applyUndoRedoEdits(edits, eol, false, true, resultingAlternativeVersionId, resultingSelection);
        }
        _applyUndoRedoEdits(edits, eol, isUndoing, isRedoing, resultingAlternativeVersionId, resultingSelection) {
            try {
                this._onDidChangeDecorations.beginDeferredEmit();
                this._eventEmitter.beginDeferredEmit();
                this._isUndoing = isUndoing;
                this._isRedoing = isRedoing;
                this.applyEdits(edits, false);
                this.setEOL(eol);
                this._overwriteAlternativeVersionId(resultingAlternativeVersionId);
            }
            finally {
                this._isUndoing = false;
                this._isRedoing = false;
                this._eventEmitter.endDeferredEmit(resultingSelection);
                this._onDidChangeDecorations.endDeferredEmit();
            }
        }
        applyEdits(rawOperations, computeUndoEdits = false) {
            try {
                this._onDidChangeDecorations.beginDeferredEmit();
                this._eventEmitter.beginDeferredEmit();
                const operations = this._validateEditOperations(rawOperations);
                return this._doApplyEdits(operations, computeUndoEdits);
            }
            finally {
                this._eventEmitter.endDeferredEmit();
                this._onDidChangeDecorations.endDeferredEmit();
            }
        }
        _doApplyEdits(rawOperations, computeUndoEdits) {
            const oldLineCount = this._buffer.getLineCount();
            const result = this._buffer.applyEdits(rawOperations, this._options.trimAutoWhitespace, computeUndoEdits);
            const newLineCount = this._buffer.getLineCount();
            const contentChanges = result.changes;
            this._trimAutoWhitespaceLines = result.trimAutoWhitespaceLineNumbers;
            if (contentChanges.length !== 0) {
                // We do a first pass to update decorations
                // because we want to read decorations in the second pass
                // where we will emit content change events
                // and we want to read the final decorations
                for (let i = 0, len = contentChanges.length; i < len; i++) {
                    const change = contentChanges[i];
                    this._decorationsTree.acceptReplace(change.rangeOffset, change.rangeLength, change.text.length, change.forceMoveMarkers);
                }
                const rawContentChanges = [];
                this._increaseVersionId();
                let lineCount = oldLineCount;
                for (let i = 0, len = contentChanges.length; i < len; i++) {
                    const change = contentChanges[i];
                    const [eolCount] = (0, eolCounter_1.countEOL)(change.text);
                    this._onDidChangeDecorations.fire();
                    const startLineNumber = change.range.startLineNumber;
                    const endLineNumber = change.range.endLineNumber;
                    const deletingLinesCnt = endLineNumber - startLineNumber;
                    const insertingLinesCnt = eolCount;
                    const editingLinesCnt = Math.min(deletingLinesCnt, insertingLinesCnt);
                    const changeLineCountDelta = (insertingLinesCnt - deletingLinesCnt);
                    const currentEditStartLineNumber = newLineCount - lineCount - changeLineCountDelta + startLineNumber;
                    const firstEditLineNumber = currentEditStartLineNumber;
                    const lastInsertedLineNumber = currentEditStartLineNumber + insertingLinesCnt;
                    const decorationsWithInjectedTextInEditedRange = this._decorationsTree.getInjectedTextInInterval(this, this.getOffsetAt(new position_1.Position(firstEditLineNumber, 1)), this.getOffsetAt(new position_1.Position(lastInsertedLineNumber, this.getLineMaxColumn(lastInsertedLineNumber))), 0);
                    const injectedTextInEditedRange = textModelEvents_1.LineInjectedText.fromDecorations(decorationsWithInjectedTextInEditedRange);
                    const injectedTextInEditedRangeQueue = new arrays_1.ArrayQueue(injectedTextInEditedRange);
                    for (let j = editingLinesCnt; j >= 0; j--) {
                        const editLineNumber = startLineNumber + j;
                        const currentEditLineNumber = currentEditStartLineNumber + j;
                        injectedTextInEditedRangeQueue.takeFromEndWhile(r => r.lineNumber > currentEditLineNumber);
                        const decorationsInCurrentLine = injectedTextInEditedRangeQueue.takeFromEndWhile(r => r.lineNumber === currentEditLineNumber);
                        rawContentChanges.push(new textModelEvents_1.ModelRawLineChanged(editLineNumber, this.getLineContent(currentEditLineNumber), decorationsInCurrentLine));
                    }
                    if (editingLinesCnt < deletingLinesCnt) {
                        // Must delete some lines
                        const spliceStartLineNumber = startLineNumber + editingLinesCnt;
                        rawContentChanges.push(new textModelEvents_1.ModelRawLinesDeleted(spliceStartLineNumber + 1, endLineNumber));
                    }
                    if (editingLinesCnt < insertingLinesCnt) {
                        const injectedTextInEditedRangeQueue = new arrays_1.ArrayQueue(injectedTextInEditedRange);
                        // Must insert some lines
                        const spliceLineNumber = startLineNumber + editingLinesCnt;
                        const cnt = insertingLinesCnt - editingLinesCnt;
                        const fromLineNumber = newLineCount - lineCount - cnt + spliceLineNumber + 1;
                        const injectedTexts = [];
                        const newLines = [];
                        for (let i = 0; i < cnt; i++) {
                            const lineNumber = fromLineNumber + i;
                            newLines[i] = this.getLineContent(lineNumber);
                            injectedTextInEditedRangeQueue.takeWhile(r => r.lineNumber < lineNumber);
                            injectedTexts[i] = injectedTextInEditedRangeQueue.takeWhile(r => r.lineNumber === lineNumber);
                        }
                        rawContentChanges.push(new textModelEvents_1.ModelRawLinesInserted(spliceLineNumber + 1, startLineNumber + insertingLinesCnt, newLines, injectedTexts));
                    }
                    lineCount += changeLineCountDelta;
                }
                this._emitContentChangedEvent(new textModelEvents_1.ModelRawContentChangedEvent(rawContentChanges, this.getVersionId(), this._isUndoing, this._isRedoing), {
                    changes: contentChanges,
                    eol: this._buffer.getEOL(),
                    isEolChange: false,
                    versionId: this.getVersionId(),
                    isUndoing: this._isUndoing,
                    isRedoing: this._isRedoing,
                    isFlush: false
                });
            }
            return (result.reverseEdits === null ? undefined : result.reverseEdits);
        }
        undo() {
            return this._undoRedoService.undo(this.uri);
        }
        canUndo() {
            return this._undoRedoService.canUndo(this.uri);
        }
        redo() {
            return this._undoRedoService.redo(this.uri);
        }
        canRedo() {
            return this._undoRedoService.canRedo(this.uri);
        }
        //#endregion
        //#region Decorations
        handleBeforeFireDecorationsChangedEvent(affectedInjectedTextLines) {
            // This is called before the decoration changed event is fired.
            if (affectedInjectedTextLines === null || affectedInjectedTextLines.size === 0) {
                return;
            }
            const affectedLines = Array.from(affectedInjectedTextLines);
            const lineChangeEvents = affectedLines.map(lineNumber => new textModelEvents_1.ModelRawLineChanged(lineNumber, this.getLineContent(lineNumber), this._getInjectedTextInLine(lineNumber)));
            this._onDidChangeInjectedText.fire(new textModelEvents_1.ModelInjectedTextChangedEvent(lineChangeEvents));
        }
        changeDecorations(callback, ownerId = 0) {
            this._assertNotDisposed();
            try {
                this._onDidChangeDecorations.beginDeferredEmit();
                return this._changeDecorations(ownerId, callback);
            }
            finally {
                this._onDidChangeDecorations.endDeferredEmit();
            }
        }
        _changeDecorations(ownerId, callback) {
            const changeAccessor = {
                addDecoration: (range, options) => {
                    return this._deltaDecorationsImpl(ownerId, [], [{ range: range, options: options }])[0];
                },
                changeDecoration: (id, newRange) => {
                    this._changeDecorationImpl(id, newRange);
                },
                changeDecorationOptions: (id, options) => {
                    this._changeDecorationOptionsImpl(id, _normalizeOptions(options));
                },
                removeDecoration: (id) => {
                    this._deltaDecorationsImpl(ownerId, [id], []);
                },
                deltaDecorations: (oldDecorations, newDecorations) => {
                    if (oldDecorations.length === 0 && newDecorations.length === 0) {
                        // nothing to do
                        return [];
                    }
                    return this._deltaDecorationsImpl(ownerId, oldDecorations, newDecorations);
                }
            };
            let result = null;
            try {
                result = callback(changeAccessor);
            }
            catch (e) {
                (0, errors_1.onUnexpectedError)(e);
            }
            // Invalidate change accessor
            changeAccessor.addDecoration = invalidFunc;
            changeAccessor.changeDecoration = invalidFunc;
            changeAccessor.changeDecorationOptions = invalidFunc;
            changeAccessor.removeDecoration = invalidFunc;
            changeAccessor.deltaDecorations = invalidFunc;
            return result;
        }
        deltaDecorations(oldDecorations, newDecorations, ownerId = 0) {
            this._assertNotDisposed();
            if (!oldDecorations) {
                oldDecorations = [];
            }
            if (oldDecorations.length === 0 && newDecorations.length === 0) {
                // nothing to do
                return [];
            }
            try {
                this._deltaDecorationCallCnt++;
                if (this._deltaDecorationCallCnt > 1) {
                    console.warn(`Invoking deltaDecorations recursively could lead to leaking decorations.`);
                    (0, errors_1.onUnexpectedError)(new Error(`Invoking deltaDecorations recursively could lead to leaking decorations.`));
                }
                this._onDidChangeDecorations.beginDeferredEmit();
                return this._deltaDecorationsImpl(ownerId, oldDecorations, newDecorations);
            }
            finally {
                this._onDidChangeDecorations.endDeferredEmit();
                this._deltaDecorationCallCnt--;
            }
        }
        _getTrackedRange(id) {
            return this.getDecorationRange(id);
        }
        _setTrackedRange(id, newRange, newStickiness) {
            const node = (id ? this._decorations[id] : null);
            if (!node) {
                if (!newRange) {
                    // node doesn't exist, the request is to delete => nothing to do
                    return null;
                }
                // node doesn't exist, the request is to set => add the tracked range
                return this._deltaDecorationsImpl(0, [], [{ range: newRange, options: TRACKED_RANGE_OPTIONS[newStickiness] }], true)[0];
            }
            if (!newRange) {
                // node exists, the request is to delete => delete node
                this._decorationsTree.delete(node);
                delete this._decorations[node.id];
                return null;
            }
            // node exists, the request is to set => change the tracked range and its options
            const range = this._validateRangeRelaxedNoAllocations(newRange);
            const startOffset = this._buffer.getOffsetAt(range.startLineNumber, range.startColumn);
            const endOffset = this._buffer.getOffsetAt(range.endLineNumber, range.endColumn);
            this._decorationsTree.delete(node);
            node.reset(this.getVersionId(), startOffset, endOffset, range);
            node.setOptions(TRACKED_RANGE_OPTIONS[newStickiness]);
            this._decorationsTree.insert(node);
            return node.id;
        }
        removeAllDecorationsWithOwnerId(ownerId) {
            if (this._isDisposed) {
                return;
            }
            const nodes = this._decorationsTree.collectNodesFromOwner(ownerId);
            for (let i = 0, len = nodes.length; i < len; i++) {
                const node = nodes[i];
                this._decorationsTree.delete(node);
                delete this._decorations[node.id];
            }
        }
        getDecorationOptions(decorationId) {
            const node = this._decorations[decorationId];
            if (!node) {
                return null;
            }
            return node.options;
        }
        getDecorationRange(decorationId) {
            const node = this._decorations[decorationId];
            if (!node) {
                return null;
            }
            return this._decorationsTree.getNodeRange(this, node);
        }
        getLineDecorations(lineNumber, ownerId = 0, filterOutValidation = false) {
            if (lineNumber < 1 || lineNumber > this.getLineCount()) {
                return [];
            }
            return this.getLinesDecorations(lineNumber, lineNumber, ownerId, filterOutValidation);
        }
        getLinesDecorations(_startLineNumber, _endLineNumber, ownerId = 0, filterOutValidation = false, onlyMarginDecorations = false) {
            const lineCount = this.getLineCount();
            const startLineNumber = Math.min(lineCount, Math.max(1, _startLineNumber));
            const endLineNumber = Math.min(lineCount, Math.max(1, _endLineNumber));
            const endColumn = this.getLineMaxColumn(endLineNumber);
            const range = new range_1.Range(startLineNumber, 1, endLineNumber, endColumn);
            const decorations = this._getDecorationsInRange(range, ownerId, filterOutValidation, onlyMarginDecorations);
            (0, arrays_1.pushMany)(decorations, this._decorationProvider.getDecorationsInRange(range, ownerId, filterOutValidation));
            return decorations;
        }
        getDecorationsInRange(range, ownerId = 0, filterOutValidation = false, onlyMinimapDecorations = false, onlyMarginDecorations = false) {
            const validatedRange = this.validateRange(range);
            const decorations = this._getDecorationsInRange(validatedRange, ownerId, filterOutValidation, onlyMarginDecorations);
            (0, arrays_1.pushMany)(decorations, this._decorationProvider.getDecorationsInRange(validatedRange, ownerId, filterOutValidation, onlyMinimapDecorations));
            return decorations;
        }
        getOverviewRulerDecorations(ownerId = 0, filterOutValidation = false) {
            return this._decorationsTree.getAll(this, ownerId, filterOutValidation, true, false);
        }
        getInjectedTextDecorations(ownerId = 0) {
            return this._decorationsTree.getAllInjectedText(this, ownerId);
        }
        _getInjectedTextInLine(lineNumber) {
            const startOffset = this._buffer.getOffsetAt(lineNumber, 1);
            const endOffset = startOffset + this._buffer.getLineLength(lineNumber);
            const result = this._decorationsTree.getInjectedTextInInterval(this, startOffset, endOffset, 0);
            return textModelEvents_1.LineInjectedText.fromDecorations(result).filter(t => t.lineNumber === lineNumber);
        }
        getAllDecorations(ownerId = 0, filterOutValidation = false) {
            let result = this._decorationsTree.getAll(this, ownerId, filterOutValidation, false, false);
            result = result.concat(this._decorationProvider.getAllDecorations(ownerId, filterOutValidation));
            return result;
        }
        getAllMarginDecorations(ownerId = 0) {
            return this._decorationsTree.getAll(this, ownerId, false, false, true);
        }
        _getDecorationsInRange(filterRange, filterOwnerId, filterOutValidation, onlyMarginDecorations) {
            const startOffset = this._buffer.getOffsetAt(filterRange.startLineNumber, filterRange.startColumn);
            const endOffset = this._buffer.getOffsetAt(filterRange.endLineNumber, filterRange.endColumn);
            return this._decorationsTree.getAllInInterval(this, startOffset, endOffset, filterOwnerId, filterOutValidation, onlyMarginDecorations);
        }
        getRangeAt(start, end) {
            return this._buffer.getRangeAt(start, end - start);
        }
        _changeDecorationImpl(decorationId, _range) {
            const node = this._decorations[decorationId];
            if (!node) {
                return;
            }
            if (node.options.after) {
                const oldRange = this.getDecorationRange(decorationId);
                this._onDidChangeDecorations.recordLineAffectedByInjectedText(oldRange.endLineNumber);
            }
            if (node.options.before) {
                const oldRange = this.getDecorationRange(decorationId);
                this._onDidChangeDecorations.recordLineAffectedByInjectedText(oldRange.startLineNumber);
            }
            const range = this._validateRangeRelaxedNoAllocations(_range);
            const startOffset = this._buffer.getOffsetAt(range.startLineNumber, range.startColumn);
            const endOffset = this._buffer.getOffsetAt(range.endLineNumber, range.endColumn);
            this._decorationsTree.delete(node);
            node.reset(this.getVersionId(), startOffset, endOffset, range);
            this._decorationsTree.insert(node);
            this._onDidChangeDecorations.checkAffectedAndFire(node.options);
            if (node.options.after) {
                this._onDidChangeDecorations.recordLineAffectedByInjectedText(range.endLineNumber);
            }
            if (node.options.before) {
                this._onDidChangeDecorations.recordLineAffectedByInjectedText(range.startLineNumber);
            }
        }
        _changeDecorationOptionsImpl(decorationId, options) {
            const node = this._decorations[decorationId];
            if (!node) {
                return;
            }
            const nodeWasInOverviewRuler = (node.options.overviewRuler && node.options.overviewRuler.color ? true : false);
            const nodeIsInOverviewRuler = (options.overviewRuler && options.overviewRuler.color ? true : false);
            this._onDidChangeDecorations.checkAffectedAndFire(node.options);
            this._onDidChangeDecorations.checkAffectedAndFire(options);
            if (node.options.after || options.after) {
                const nodeRange = this._decorationsTree.getNodeRange(this, node);
                this._onDidChangeDecorations.recordLineAffectedByInjectedText(nodeRange.endLineNumber);
            }
            if (node.options.before || options.before) {
                const nodeRange = this._decorationsTree.getNodeRange(this, node);
                this._onDidChangeDecorations.recordLineAffectedByInjectedText(nodeRange.startLineNumber);
            }
            const movedInOverviewRuler = nodeWasInOverviewRuler !== nodeIsInOverviewRuler;
            const changedWhetherInjectedText = isOptionsInjectedText(options) !== isNodeInjectedText(node);
            if (movedInOverviewRuler || changedWhetherInjectedText) {
                this._decorationsTree.delete(node);
                node.setOptions(options);
                this._decorationsTree.insert(node);
            }
            else {
                node.setOptions(options);
            }
        }
        _deltaDecorationsImpl(ownerId, oldDecorationsIds, newDecorations, suppressEvents = false) {
            const versionId = this.getVersionId();
            const oldDecorationsLen = oldDecorationsIds.length;
            let oldDecorationIndex = 0;
            const newDecorationsLen = newDecorations.length;
            let newDecorationIndex = 0;
            this._onDidChangeDecorations.beginDeferredEmit();
            try {
                const result = new Array(newDecorationsLen);
                while (oldDecorationIndex < oldDecorationsLen || newDecorationIndex < newDecorationsLen) {
                    let node = null;
                    if (oldDecorationIndex < oldDecorationsLen) {
                        // (1) get ourselves an old node
                        do {
                            node = this._decorations[oldDecorationsIds[oldDecorationIndex++]];
                        } while (!node && oldDecorationIndex < oldDecorationsLen);
                        // (2) remove the node from the tree (if it exists)
                        if (node) {
                            if (node.options.after) {
                                const nodeRange = this._decorationsTree.getNodeRange(this, node);
                                this._onDidChangeDecorations.recordLineAffectedByInjectedText(nodeRange.endLineNumber);
                            }
                            if (node.options.before) {
                                const nodeRange = this._decorationsTree.getNodeRange(this, node);
                                this._onDidChangeDecorations.recordLineAffectedByInjectedText(nodeRange.startLineNumber);
                            }
                            this._decorationsTree.delete(node);
                            if (!suppressEvents) {
                                this._onDidChangeDecorations.checkAffectedAndFire(node.options);
                            }
                        }
                    }
                    if (newDecorationIndex < newDecorationsLen) {
                        // (3) create a new node if necessary
                        if (!node) {
                            const internalDecorationId = (++this._lastDecorationId);
                            const decorationId = `${this._instanceId};${internalDecorationId}`;
                            node = new intervalTree_1.IntervalNode(decorationId, 0, 0);
                            this._decorations[decorationId] = node;
                        }
                        // (4) initialize node
                        const newDecoration = newDecorations[newDecorationIndex];
                        const range = this._validateRangeRelaxedNoAllocations(newDecoration.range);
                        const options = _normalizeOptions(newDecoration.options);
                        const startOffset = this._buffer.getOffsetAt(range.startLineNumber, range.startColumn);
                        const endOffset = this._buffer.getOffsetAt(range.endLineNumber, range.endColumn);
                        node.ownerId = ownerId;
                        node.reset(versionId, startOffset, endOffset, range);
                        node.setOptions(options);
                        if (node.options.after) {
                            this._onDidChangeDecorations.recordLineAffectedByInjectedText(range.endLineNumber);
                        }
                        if (node.options.before) {
                            this._onDidChangeDecorations.recordLineAffectedByInjectedText(range.startLineNumber);
                        }
                        if (!suppressEvents) {
                            this._onDidChangeDecorations.checkAffectedAndFire(options);
                        }
                        this._decorationsTree.insert(node);
                        result[newDecorationIndex] = node.id;
                        newDecorationIndex++;
                    }
                    else {
                        if (node) {
                            delete this._decorations[node.id];
                        }
                    }
                }
                return result;
            }
            finally {
                this._onDidChangeDecorations.endDeferredEmit();
            }
        }
        //#endregion
        //#region Tokenization
        // TODO move them to the tokenization part.
        getLanguageId() {
            return this.tokenization.getLanguageId();
        }
        setLanguage(languageIdOrSelection, source) {
            if (typeof languageIdOrSelection === 'string') {
                this._languageSelectionListener.clear();
                this._setLanguage(languageIdOrSelection, source);
            }
            else {
                this._languageSelectionListener.value = languageIdOrSelection.onDidChange(() => this._setLanguage(languageIdOrSelection.languageId, source));
                this._setLanguage(languageIdOrSelection.languageId, source);
            }
        }
        _setLanguage(languageId, source) {
            this.tokenization.setLanguageId(languageId, source);
            this._languageService.requestRichLanguageFeatures(languageId);
        }
        getLanguageIdAtPosition(lineNumber, column) {
            return this.tokenization.getLanguageIdAtPosition(lineNumber, column);
        }
        getWordAtPosition(position) {
            return this._tokenizationTextModelPart.getWordAtPosition(position);
        }
        getWordUntilPosition(position) {
            return this._tokenizationTextModelPart.getWordUntilPosition(position);
        }
        //#endregion
        normalizePosition(position, affinity) {
            return position;
        }
        /**
         * Gets the column at which indentation stops at a given line.
         * @internal
        */
        getLineIndentColumn(lineNumber) {
            // Columns start with 1.
            return indentOfLine(this.getLineContent(lineNumber)) + 1;
        }
    };
    exports.TextModel = TextModel;
    exports.TextModel = TextModel = TextModel_1 = __decorate([
        __param(4, undoRedo_1.IUndoRedoService),
        __param(5, language_1.ILanguageService),
        __param(6, languageConfigurationRegistry_1.ILanguageConfigurationService),
        __param(7, instantiation_1.IInstantiationService)
    ], TextModel);
    function indentOfLine(line) {
        let indent = 0;
        for (const c of line) {
            if (c === ' ' || c === '\t') {
                indent++;
            }
            else {
                break;
            }
        }
        return indent;
    }
    //#region Decorations
    function isNodeInOverviewRuler(node) {
        return (node.options.overviewRuler && node.options.overviewRuler.color ? true : false);
    }
    function isOptionsInjectedText(options) {
        return !!options.after || !!options.before;
    }
    function isNodeInjectedText(node) {
        return !!node.options.after || !!node.options.before;
    }
    class DecorationsTrees {
        constructor() {
            this._decorationsTree0 = new intervalTree_1.IntervalTree();
            this._decorationsTree1 = new intervalTree_1.IntervalTree();
            this._injectedTextDecorationsTree = new intervalTree_1.IntervalTree();
        }
        ensureAllNodesHaveRanges(host) {
            this.getAll(host, 0, false, false, false);
        }
        _ensureNodesHaveRanges(host, nodes) {
            for (const node of nodes) {
                if (node.range === null) {
                    node.range = host.getRangeAt(node.cachedAbsoluteStart, node.cachedAbsoluteEnd);
                }
            }
            return nodes;
        }
        getAllInInterval(host, start, end, filterOwnerId, filterOutValidation, onlyMarginDecorations) {
            const versionId = host.getVersionId();
            const result = this._intervalSearch(start, end, filterOwnerId, filterOutValidation, versionId, onlyMarginDecorations);
            return this._ensureNodesHaveRanges(host, result);
        }
        _intervalSearch(start, end, filterOwnerId, filterOutValidation, cachedVersionId, onlyMarginDecorations) {
            const r0 = this._decorationsTree0.intervalSearch(start, end, filterOwnerId, filterOutValidation, cachedVersionId, onlyMarginDecorations);
            const r1 = this._decorationsTree1.intervalSearch(start, end, filterOwnerId, filterOutValidation, cachedVersionId, onlyMarginDecorations);
            const r2 = this._injectedTextDecorationsTree.intervalSearch(start, end, filterOwnerId, filterOutValidation, cachedVersionId, onlyMarginDecorations);
            return r0.concat(r1).concat(r2);
        }
        getInjectedTextInInterval(host, start, end, filterOwnerId) {
            const versionId = host.getVersionId();
            const result = this._injectedTextDecorationsTree.intervalSearch(start, end, filterOwnerId, false, versionId, false);
            return this._ensureNodesHaveRanges(host, result).filter((i) => i.options.showIfCollapsed || !i.range.isEmpty());
        }
        getAllInjectedText(host, filterOwnerId) {
            const versionId = host.getVersionId();
            const result = this._injectedTextDecorationsTree.search(filterOwnerId, false, versionId, false);
            return this._ensureNodesHaveRanges(host, result).filter((i) => i.options.showIfCollapsed || !i.range.isEmpty());
        }
        getAll(host, filterOwnerId, filterOutValidation, overviewRulerOnly, onlyMarginDecorations) {
            const versionId = host.getVersionId();
            const result = this._search(filterOwnerId, filterOutValidation, overviewRulerOnly, versionId, onlyMarginDecorations);
            return this._ensureNodesHaveRanges(host, result);
        }
        _search(filterOwnerId, filterOutValidation, overviewRulerOnly, cachedVersionId, onlyMarginDecorations) {
            if (overviewRulerOnly) {
                return this._decorationsTree1.search(filterOwnerId, filterOutValidation, cachedVersionId, onlyMarginDecorations);
            }
            else {
                const r0 = this._decorationsTree0.search(filterOwnerId, filterOutValidation, cachedVersionId, onlyMarginDecorations);
                const r1 = this._decorationsTree1.search(filterOwnerId, filterOutValidation, cachedVersionId, onlyMarginDecorations);
                const r2 = this._injectedTextDecorationsTree.search(filterOwnerId, filterOutValidation, cachedVersionId, onlyMarginDecorations);
                return r0.concat(r1).concat(r2);
            }
        }
        collectNodesFromOwner(ownerId) {
            const r0 = this._decorationsTree0.collectNodesFromOwner(ownerId);
            const r1 = this._decorationsTree1.collectNodesFromOwner(ownerId);
            const r2 = this._injectedTextDecorationsTree.collectNodesFromOwner(ownerId);
            return r0.concat(r1).concat(r2);
        }
        collectNodesPostOrder() {
            const r0 = this._decorationsTree0.collectNodesPostOrder();
            const r1 = this._decorationsTree1.collectNodesPostOrder();
            const r2 = this._injectedTextDecorationsTree.collectNodesPostOrder();
            return r0.concat(r1).concat(r2);
        }
        insert(node) {
            if (isNodeInjectedText(node)) {
                this._injectedTextDecorationsTree.insert(node);
            }
            else if (isNodeInOverviewRuler(node)) {
                this._decorationsTree1.insert(node);
            }
            else {
                this._decorationsTree0.insert(node);
            }
        }
        delete(node) {
            if (isNodeInjectedText(node)) {
                this._injectedTextDecorationsTree.delete(node);
            }
            else if (isNodeInOverviewRuler(node)) {
                this._decorationsTree1.delete(node);
            }
            else {
                this._decorationsTree0.delete(node);
            }
        }
        getNodeRange(host, node) {
            const versionId = host.getVersionId();
            if (node.cachedVersionId !== versionId) {
                this._resolveNode(node, versionId);
            }
            if (node.range === null) {
                node.range = host.getRangeAt(node.cachedAbsoluteStart, node.cachedAbsoluteEnd);
            }
            return node.range;
        }
        _resolveNode(node, cachedVersionId) {
            if (isNodeInjectedText(node)) {
                this._injectedTextDecorationsTree.resolveNode(node, cachedVersionId);
            }
            else if (isNodeInOverviewRuler(node)) {
                this._decorationsTree1.resolveNode(node, cachedVersionId);
            }
            else {
                this._decorationsTree0.resolveNode(node, cachedVersionId);
            }
        }
        acceptReplace(offset, length, textLength, forceMoveMarkers) {
            this._decorationsTree0.acceptReplace(offset, length, textLength, forceMoveMarkers);
            this._decorationsTree1.acceptReplace(offset, length, textLength, forceMoveMarkers);
            this._injectedTextDecorationsTree.acceptReplace(offset, length, textLength, forceMoveMarkers);
        }
    }
    function cleanClassName(className) {
        return className.replace(/[^a-z0-9\-_]/gi, ' ');
    }
    class DecorationOptions {
        constructor(options) {
            this.color = options.color || '';
            this.darkColor = options.darkColor || '';
        }
    }
    class ModelDecorationOverviewRulerOptions extends DecorationOptions {
        constructor(options) {
            super(options);
            this._resolvedColor = null;
            this.position = (typeof options.position === 'number' ? options.position : model.OverviewRulerLane.Center);
        }
        getColor(theme) {
            if (!this._resolvedColor) {
                if (theme.type !== 'light' && this.darkColor) {
                    this._resolvedColor = this._resolveColor(this.darkColor, theme);
                }
                else {
                    this._resolvedColor = this._resolveColor(this.color, theme);
                }
            }
            return this._resolvedColor;
        }
        invalidateCachedColor() {
            this._resolvedColor = null;
        }
        _resolveColor(color, theme) {
            if (typeof color === 'string') {
                return color;
            }
            const c = color ? theme.getColor(color.id) : null;
            if (!c) {
                return '';
            }
            return c.toString();
        }
    }
    exports.ModelDecorationOverviewRulerOptions = ModelDecorationOverviewRulerOptions;
    class ModelDecorationGlyphMarginOptions {
        constructor(options) {
            this.position = options?.position ?? model.GlyphMarginLane.Center;
            this.persistLane = options?.persistLane;
        }
    }
    exports.ModelDecorationGlyphMarginOptions = ModelDecorationGlyphMarginOptions;
    class ModelDecorationMinimapOptions extends DecorationOptions {
        constructor(options) {
            super(options);
            this.position = options.position;
            this.sectionHeaderStyle = options.sectionHeaderStyle ?? null;
            this.sectionHeaderText = options.sectionHeaderText ?? null;
        }
        getColor(theme) {
            if (!this._resolvedColor) {
                if (theme.type !== 'light' && this.darkColor) {
                    this._resolvedColor = this._resolveColor(this.darkColor, theme);
                }
                else {
                    this._resolvedColor = this._resolveColor(this.color, theme);
                }
            }
            return this._resolvedColor;
        }
        invalidateCachedColor() {
            this._resolvedColor = undefined;
        }
        _resolveColor(color, theme) {
            if (typeof color === 'string') {
                return color_1.Color.fromHex(color);
            }
            return theme.getColor(color.id);
        }
    }
    exports.ModelDecorationMinimapOptions = ModelDecorationMinimapOptions;
    class ModelDecorationInjectedTextOptions {
        static from(options) {
            if (options instanceof ModelDecorationInjectedTextOptions) {
                return options;
            }
            return new ModelDecorationInjectedTextOptions(options);
        }
        constructor(options) {
            this.content = options.content || '';
            this.inlineClassName = options.inlineClassName || null;
            this.inlineClassNameAffectsLetterSpacing = options.inlineClassNameAffectsLetterSpacing || false;
            this.attachedData = options.attachedData || null;
            this.cursorStops = options.cursorStops || null;
        }
    }
    exports.ModelDecorationInjectedTextOptions = ModelDecorationInjectedTextOptions;
    class ModelDecorationOptions {
        static register(options) {
            return new ModelDecorationOptions(options);
        }
        static createDynamic(options) {
            return new ModelDecorationOptions(options);
        }
        constructor(options) {
            this.description = options.description;
            this.blockClassName = options.blockClassName ? cleanClassName(options.blockClassName) : null;
            this.blockDoesNotCollapse = options.blockDoesNotCollapse ?? null;
            this.blockIsAfterEnd = options.blockIsAfterEnd ?? null;
            this.blockPadding = options.blockPadding ?? null;
            this.stickiness = options.stickiness || 0 /* model.TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges */;
            this.zIndex = options.zIndex || 0;
            this.className = options.className ? cleanClassName(options.className) : null;
            this.shouldFillLineOnLineBreak = options.shouldFillLineOnLineBreak ?? null;
            this.hoverMessage = options.hoverMessage || null;
            this.glyphMarginHoverMessage = options.glyphMarginHoverMessage || null;
            this.lineNumberHoverMessage = options.lineNumberHoverMessage || null;
            this.isWholeLine = options.isWholeLine || false;
            this.showIfCollapsed = options.showIfCollapsed || false;
            this.collapseOnReplaceEdit = options.collapseOnReplaceEdit || false;
            this.overviewRuler = options.overviewRuler ? new ModelDecorationOverviewRulerOptions(options.overviewRuler) : null;
            this.minimap = options.minimap ? new ModelDecorationMinimapOptions(options.minimap) : null;
            this.glyphMargin = options.glyphMarginClassName ? new ModelDecorationGlyphMarginOptions(options.glyphMargin) : null;
            this.glyphMarginClassName = options.glyphMarginClassName ? cleanClassName(options.glyphMarginClassName) : null;
            this.linesDecorationsClassName = options.linesDecorationsClassName ? cleanClassName(options.linesDecorationsClassName) : null;
            this.lineNumberClassName = options.lineNumberClassName ? cleanClassName(options.lineNumberClassName) : null;
            this.linesDecorationsTooltip = options.linesDecorationsTooltip ? strings.htmlAttributeEncodeValue(options.linesDecorationsTooltip) : null;
            this.firstLineDecorationClassName = options.firstLineDecorationClassName ? cleanClassName(options.firstLineDecorationClassName) : null;
            this.marginClassName = options.marginClassName ? cleanClassName(options.marginClassName) : null;
            this.inlineClassName = options.inlineClassName ? cleanClassName(options.inlineClassName) : null;
            this.inlineClassNameAffectsLetterSpacing = options.inlineClassNameAffectsLetterSpacing || false;
            this.beforeContentClassName = options.beforeContentClassName ? cleanClassName(options.beforeContentClassName) : null;
            this.afterContentClassName = options.afterContentClassName ? cleanClassName(options.afterContentClassName) : null;
            this.after = options.after ? ModelDecorationInjectedTextOptions.from(options.after) : null;
            this.before = options.before ? ModelDecorationInjectedTextOptions.from(options.before) : null;
            this.hideInCommentTokens = options.hideInCommentTokens ?? false;
            this.hideInStringTokens = options.hideInStringTokens ?? false;
        }
    }
    exports.ModelDecorationOptions = ModelDecorationOptions;
    ModelDecorationOptions.EMPTY = ModelDecorationOptions.register({ description: 'empty' });
    /**
     * The order carefully matches the values of the enum.
     */
    const TRACKED_RANGE_OPTIONS = [
        ModelDecorationOptions.register({ description: 'tracked-range-always-grows-when-typing-at-edges', stickiness: 0 /* model.TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges */ }),
        ModelDecorationOptions.register({ description: 'tracked-range-never-grows-when-typing-at-edges', stickiness: 1 /* model.TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */ }),
        ModelDecorationOptions.register({ description: 'tracked-range-grows-only-when-typing-before', stickiness: 2 /* model.TrackedRangeStickiness.GrowsOnlyWhenTypingBefore */ }),
        ModelDecorationOptions.register({ description: 'tracked-range-grows-only-when-typing-after', stickiness: 3 /* model.TrackedRangeStickiness.GrowsOnlyWhenTypingAfter */ }),
    ];
    function _normalizeOptions(options) {
        if (options instanceof ModelDecorationOptions) {
            return options;
        }
        return ModelDecorationOptions.createDynamic(options);
    }
    class DidChangeDecorationsEmitter extends lifecycle_1.Disposable {
        constructor(handleBeforeFire) {
            super();
            this.handleBeforeFire = handleBeforeFire;
            this._actual = this._register(new event_1.Emitter());
            this.event = this._actual.event;
            this._affectedInjectedTextLines = null;
            this._deferredCnt = 0;
            this._shouldFireDeferred = false;
            this._affectsMinimap = false;
            this._affectsOverviewRuler = false;
            this._affectsGlyphMargin = false;
            this._affectsLineNumber = false;
        }
        beginDeferredEmit() {
            this._deferredCnt++;
        }
        endDeferredEmit() {
            this._deferredCnt--;
            if (this._deferredCnt === 0) {
                if (this._shouldFireDeferred) {
                    this.doFire();
                }
                this._affectedInjectedTextLines?.clear();
                this._affectedInjectedTextLines = null;
            }
        }
        recordLineAffectedByInjectedText(lineNumber) {
            if (!this._affectedInjectedTextLines) {
                this._affectedInjectedTextLines = new Set();
            }
            this._affectedInjectedTextLines.add(lineNumber);
        }
        checkAffectedAndFire(options) {
            this._affectsMinimap ||= !!options.minimap?.position;
            this._affectsOverviewRuler ||= !!options.overviewRuler?.color;
            this._affectsGlyphMargin ||= !!options.glyphMarginClassName;
            this._affectsLineNumber ||= !!options.lineNumberClassName;
            this.tryFire();
        }
        fire() {
            this._affectsMinimap = true;
            this._affectsOverviewRuler = true;
            this._affectsGlyphMargin = true;
            this.tryFire();
        }
        tryFire() {
            if (this._deferredCnt === 0) {
                this.doFire();
            }
            else {
                this._shouldFireDeferred = true;
            }
        }
        doFire() {
            this.handleBeforeFire(this._affectedInjectedTextLines);
            const event = {
                affectsMinimap: this._affectsMinimap,
                affectsOverviewRuler: this._affectsOverviewRuler,
                affectsGlyphMargin: this._affectsGlyphMargin,
                affectsLineNumber: this._affectsLineNumber,
            };
            this._shouldFireDeferred = false;
            this._affectsMinimap = false;
            this._affectsOverviewRuler = false;
            this._affectsGlyphMargin = false;
            this._actual.fire(event);
        }
    }
    //#endregion
    class DidChangeContentEmitter extends lifecycle_1.Disposable {
        constructor() {
            super();
            /**
             * Both `fastEvent` and `slowEvent` work the same way and contain the same events, but first we invoke `fastEvent` and then `slowEvent`.
             */
            this._fastEmitter = this._register(new event_1.Emitter());
            this.fastEvent = this._fastEmitter.event;
            this._slowEmitter = this._register(new event_1.Emitter());
            this.slowEvent = this._slowEmitter.event;
            this._deferredCnt = 0;
            this._deferredEvent = null;
        }
        beginDeferredEmit() {
            this._deferredCnt++;
        }
        endDeferredEmit(resultingSelection = null) {
            this._deferredCnt--;
            if (this._deferredCnt === 0) {
                if (this._deferredEvent !== null) {
                    this._deferredEvent.rawContentChangedEvent.resultingSelection = resultingSelection;
                    const e = this._deferredEvent;
                    this._deferredEvent = null;
                    this._fastEmitter.fire(e);
                    this._slowEmitter.fire(e);
                }
            }
        }
        fire(e) {
            if (this._deferredCnt > 0) {
                if (this._deferredEvent) {
                    this._deferredEvent = this._deferredEvent.merge(e);
                }
                else {
                    this._deferredEvent = e;
                }
                return;
            }
            this._fastEmitter.fire(e);
            this._slowEmitter.fire(e);
        }
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[139/*vs/editor/browser/widget/diffEditor/registrations.contribution*/], __M([1/*require*/,0/*exports*/,26/*vs/base/common/codicons*/,30/*vs/base/common/themables*/,35/*vs/editor/common/model/textModel*/,3/*vs/nls*/,32/*vs/platform/theme/common/colorRegistry*/,71/*vs/platform/theme/common/iconRegistry*/]), function (require, exports, codicons_1, themables_1, textModel_1, nls_1, colorRegistry_1, iconRegistry_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.diffDeleteDecorationEmpty = exports.diffWholeLineDeleteDecoration = exports.diffDeleteDecoration = exports.diffAddDecorationEmpty = exports.diffWholeLineAddDecoration = exports.diffAddDecoration = exports.diffLineDeleteDecorationBackground = exports.diffLineAddDecorationBackground = exports.diffLineDeleteDecorationBackgroundWithIndicator = exports.diffLineAddDecorationBackgroundWithIndicator = exports.diffRemoveIcon = exports.diffInsertIcon = exports.diffEditorUnchangedRegionShadow = exports.diffMoveBorderActive = exports.diffMoveBorder = void 0;
    exports.diffMoveBorder = (0, colorRegistry_1.registerColor)('diffEditor.move.border', '#8b8b8b9c', (0, nls_1.localize)(124, 'The border color for text that got moved in the diff editor.'));
    exports.diffMoveBorderActive = (0, colorRegistry_1.registerColor)('diffEditor.moveActive.border', '#FFA500', (0, nls_1.localize)(125, 'The active border color for text that got moved in the diff editor.'));
    exports.diffEditorUnchangedRegionShadow = (0, colorRegistry_1.registerColor)('diffEditor.unchangedRegionShadow', { dark: '#000000', light: '#737373BF', hcDark: '#000000', hcLight: '#737373BF', }, (0, nls_1.localize)(126, 'The color of the shadow around unchanged region widgets.'));
    exports.diffInsertIcon = (0, iconRegistry_1.registerIcon)('diff-insert', codicons_1.Codicon.add, (0, nls_1.localize)(127, 'Line decoration for inserts in the diff editor.'));
    exports.diffRemoveIcon = (0, iconRegistry_1.registerIcon)('diff-remove', codicons_1.Codicon.remove, (0, nls_1.localize)(128, 'Line decoration for removals in the diff editor.'));
    exports.diffLineAddDecorationBackgroundWithIndicator = textModel_1.ModelDecorationOptions.register({
        className: 'line-insert',
        description: 'line-insert',
        isWholeLine: true,
        linesDecorationsClassName: 'insert-sign ' + themables_1.ThemeIcon.asClassName(exports.diffInsertIcon),
        marginClassName: 'gutter-insert',
    });
    exports.diffLineDeleteDecorationBackgroundWithIndicator = textModel_1.ModelDecorationOptions.register({
        className: 'line-delete',
        description: 'line-delete',
        isWholeLine: true,
        linesDecorationsClassName: 'delete-sign ' + themables_1.ThemeIcon.asClassName(exports.diffRemoveIcon),
        marginClassName: 'gutter-delete',
    });
    exports.diffLineAddDecorationBackground = textModel_1.ModelDecorationOptions.register({
        className: 'line-insert',
        description: 'line-insert',
        isWholeLine: true,
        marginClassName: 'gutter-insert',
    });
    exports.diffLineDeleteDecorationBackground = textModel_1.ModelDecorationOptions.register({
        className: 'line-delete',
        description: 'line-delete',
        isWholeLine: true,
        marginClassName: 'gutter-delete',
    });
    exports.diffAddDecoration = textModel_1.ModelDecorationOptions.register({
        className: 'char-insert',
        description: 'char-insert',
        shouldFillLineOnLineBreak: true,
    });
    exports.diffWholeLineAddDecoration = textModel_1.ModelDecorationOptions.register({
        className: 'char-insert',
        description: 'char-insert',
        isWholeLine: true,
    });
    exports.diffAddDecorationEmpty = textModel_1.ModelDecorationOptions.register({
        className: 'char-insert diff-range-empty',
        description: 'char-insert diff-range-empty',
    });
    exports.diffDeleteDecoration = textModel_1.ModelDecorationOptions.register({
        className: 'char-delete',
        description: 'char-delete',
        shouldFillLineOnLineBreak: true,
    });
    exports.diffWholeLineDeleteDecoration = textModel_1.ModelDecorationOptions.register({
        className: 'char-delete',
        description: 'char-delete',
        isWholeLine: true,
    });
    exports.diffDeleteDecorationEmpty = textModel_1.ModelDecorationOptions.register({
        className: 'char-delete diff-range-empty',
        description: 'char-delete diff-range-empty',
    });
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[285/*vs/editor/browser/widget/diffEditor/components/diffEditorViewZones/diffEditorViewZones*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,13/*vs/base/common/arrays*/,14/*vs/base/common/async*/,26/*vs/base/common/codicons*/,2/*vs/base/common/lifecycle*/,21/*vs/base/common/observable*/,30/*vs/base/common/themables*/,19/*vs/base/common/types*/,74/*vs/editor/browser/config/domFontInfo*/,139/*vs/editor/browser/widget/diffEditor/registrations.contribution*/,407/*vs/editor/browser/widget/diffEditor/diffEditorViewModel*/,652/*vs/editor/browser/widget/diffEditor/components/diffEditorViewZones/inlineDiffDeletedCodeMargin*/,667/*vs/editor/browser/widget/diffEditor/components/diffEditorViewZones/renderLines*/,88/*vs/editor/browser/widget/diffEditor/utils*/,55/*vs/editor/common/core/lineRange*/,9/*vs/editor/common/core/position*/,95/*vs/editor/common/viewModel*/,117/*vs/platform/clipboard/common/clipboardService*/,58/*vs/platform/contextview/browser/contextView*/,4/*vs/editor/common/core/range*/]), function (require, exports, dom_1, arrays_1, async_1, codicons_1, lifecycle_1, observable_1, themables_1, types_1, domFontInfo_1, registrations_contribution_1, diffEditorViewModel_1, inlineDiffDeletedCodeMargin_1, renderLines_1, utils_1, lineRange_1, position_1, viewModel_1, clipboardService_1, contextView_1, range_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DiffEditorViewZones = void 0;
    exports.allowsTrueInlineDiffRendering = allowsTrueInlineDiffRendering;
    /**
     * Ensures both editors have the same height by aligning unchanged lines.
     * In inline view mode, inserts viewzones to show deleted code from the original text model in the modified code editor.
     * Synchronizes scrolling.
     *
     * Make sure to add the view zones!
     */
    let DiffEditorViewZones = class DiffEditorViewZones extends lifecycle_1.Disposable {
        constructor(_targetWindow, _editors, _diffModel, _options, _diffEditorWidget, _canIgnoreViewZoneUpdateEvent, _origViewZonesToIgnore, _modViewZonesToIgnore, _clipboardService, _contextMenuService) {
            super();
            this._targetWindow = _targetWindow;
            this._editors = _editors;
            this._diffModel = _diffModel;
            this._options = _options;
            this._diffEditorWidget = _diffEditorWidget;
            this._canIgnoreViewZoneUpdateEvent = _canIgnoreViewZoneUpdateEvent;
            this._origViewZonesToIgnore = _origViewZonesToIgnore;
            this._modViewZonesToIgnore = _modViewZonesToIgnore;
            this._clipboardService = _clipboardService;
            this._contextMenuService = _contextMenuService;
            this._originalTopPadding = (0, observable_1.observableValue)(this, 0);
            this._originalScrollOffset = (0, observable_1.observableValue)(this, 0);
            this._originalScrollOffsetAnimated = (0, utils_1.animatedObservable)(this._targetWindow, this._originalScrollOffset, this._store);
            this._modifiedTopPadding = (0, observable_1.observableValue)(this, 0);
            this._modifiedScrollOffset = (0, observable_1.observableValue)(this, 0);
            this._modifiedScrollOffsetAnimated = (0, utils_1.animatedObservable)(this._targetWindow, this._modifiedScrollOffset, this._store);
            const state = (0, observable_1.observableValue)('invalidateAlignmentsState', 0);
            const updateImmediately = this._register(new async_1.RunOnceScheduler(() => {
                state.set(state.get() + 1, undefined);
            }, 0));
            this._register(this._editors.original.onDidChangeViewZones((_args) => { if (!this._canIgnoreViewZoneUpdateEvent()) {
                updateImmediately.schedule();
            } }));
            this._register(this._editors.modified.onDidChangeViewZones((_args) => { if (!this._canIgnoreViewZoneUpdateEvent()) {
                updateImmediately.schedule();
            } }));
            this._register(this._editors.original.onDidChangeConfiguration((args) => {
                if (args.hasChanged(147 /* EditorOption.wrappingInfo */) || args.hasChanged(67 /* EditorOption.lineHeight */)) {
                    updateImmediately.schedule();
                }
            }));
            this._register(this._editors.modified.onDidChangeConfiguration((args) => {
                if (args.hasChanged(147 /* EditorOption.wrappingInfo */) || args.hasChanged(67 /* EditorOption.lineHeight */)) {
                    updateImmediately.schedule();
                }
            }));
            const originalModelTokenizationCompleted = this._diffModel.map(m => m ? (0, observable_1.observableFromEvent)(this, m.model.original.onDidChangeTokens, () => m.model.original.tokenization.backgroundTokenizationState === 2 /* BackgroundTokenizationState.Completed */) : undefined).map((m, reader) => m?.read(reader));
            const alignments = (0, observable_1.derived)((reader) => {
                /** @description alignments */
                const diffModel = this._diffModel.read(reader);
                const diff = diffModel?.diff.read(reader);
                if (!diffModel || !diff) {
                    return null;
                }
                state.read(reader);
                const renderSideBySide = this._options.renderSideBySide.read(reader);
                const innerHunkAlignment = renderSideBySide;
                return computeRangeAlignment(this._editors.original, this._editors.modified, diff.mappings, this._origViewZonesToIgnore, this._modViewZonesToIgnore, innerHunkAlignment);
            });
            const alignmentsSyncedMovedText = (0, observable_1.derived)((reader) => {
                /** @description alignmentsSyncedMovedText */
                const syncedMovedText = this._diffModel.read(reader)?.movedTextToCompare.read(reader);
                if (!syncedMovedText) {
                    return null;
                }
                state.read(reader);
                const mappings = syncedMovedText.changes.map(c => new diffEditorViewModel_1.DiffMapping(c));
                // TODO dont include alignments outside syncedMovedText
                return computeRangeAlignment(this._editors.original, this._editors.modified, mappings, this._origViewZonesToIgnore, this._modViewZonesToIgnore, true);
            });
            function createFakeLinesDiv() {
                const r = document.createElement('div');
                r.className = 'diagonal-fill';
                return r;
            }
            const alignmentViewZonesDisposables = this._register(new lifecycle_1.DisposableStore());
            this.viewZones = (0, observable_1.derivedWithStore)(this, (reader, store) => {
                alignmentViewZonesDisposables.clear();
                const alignmentsVal = alignments.read(reader) || [];
                const origViewZones = [];
                const modViewZones = [];
                const modifiedTopPaddingVal = this._modifiedTopPadding.read(reader);
                if (modifiedTopPaddingVal > 0) {
                    modViewZones.push({
                        afterLineNumber: 0,
                        domNode: document.createElement('div'),
                        heightInPx: modifiedTopPaddingVal,
                        showInHiddenAreas: true,
                        suppressMouseDown: true,
                    });
                }
                const originalTopPaddingVal = this._originalTopPadding.read(reader);
                if (originalTopPaddingVal > 0) {
                    origViewZones.push({
                        afterLineNumber: 0,
                        domNode: document.createElement('div'),
                        heightInPx: originalTopPaddingVal,
                        showInHiddenAreas: true,
                        suppressMouseDown: true,
                    });
                }
                const renderSideBySide = this._options.renderSideBySide.read(reader);
                const deletedCodeLineBreaksComputer = !renderSideBySide ? this._editors.modified._getViewModel()?.createLineBreaksComputer() : undefined;
                if (deletedCodeLineBreaksComputer) {
                    const originalModel = this._editors.original.getModel();
                    for (const a of alignmentsVal) {
                        if (a.diff) {
                            for (let i = a.originalRange.startLineNumber; i < a.originalRange.endLineNumberExclusive; i++) {
                                // `i` can be out of bound when the diff has not been updated yet.
                                // In this case, we do an early return.
                                // TODO@hediet: Fix this by applying the edit directly to the diff model, so that the diff is always valid.
                                if (i > originalModel.getLineCount()) {
                                    return { orig: origViewZones, mod: modViewZones };
                                }
                                deletedCodeLineBreaksComputer?.addRequest(originalModel.getLineContent(i), null, null);
                            }
                        }
                    }
                }
                const lineBreakData = deletedCodeLineBreaksComputer?.finalize() ?? [];
                let lineBreakDataIdx = 0;
                const modLineHeight = this._editors.modified.getOption(67 /* EditorOption.lineHeight */);
                const syncedMovedText = this._diffModel.read(reader)?.movedTextToCompare.read(reader);
                const mightContainNonBasicASCII = this._editors.original.getModel()?.mightContainNonBasicASCII() ?? false;
                const mightContainRTL = this._editors.original.getModel()?.mightContainRTL() ?? false;
                const renderOptions = renderLines_1.RenderOptions.fromEditor(this._editors.modified);
                for (const a of alignmentsVal) {
                    if (a.diff && !renderSideBySide && (!this._options.useTrueInlineDiffRendering.read(reader) || !allowsTrueInlineDiffRendering(a.diff))) {
                        if (!a.originalRange.isEmpty) {
                            originalModelTokenizationCompleted.read(reader); // Update view-zones once tokenization completes
                            const deletedCodeDomNode = document.createElement('div');
                            deletedCodeDomNode.classList.add('view-lines', 'line-delete', 'monaco-mouse-cursor-text');
                            const originalModel = this._editors.original.getModel();
                            // `a.originalRange` can be out of bound when the diff has not been updated yet.
                            // In this case, we do an early return.
                            // TODO@hediet: Fix this by applying the edit directly to the diff model, so that the diff is always valid.
                            if (a.originalRange.endLineNumberExclusive - 1 > originalModel.getLineCount()) {
                                return { orig: origViewZones, mod: modViewZones };
                            }
                            const source = new renderLines_1.LineSource(a.originalRange.mapToLineArray(l => originalModel.tokenization.getLineTokens(l)), a.originalRange.mapToLineArray(_ => lineBreakData[lineBreakDataIdx++]), mightContainNonBasicASCII, mightContainRTL);
                            const decorations = [];
                            for (const i of a.diff.innerChanges || []) {
                                decorations.push(new viewModel_1.InlineDecoration(i.originalRange.delta(-(a.diff.original.startLineNumber - 1)), registrations_contribution_1.diffDeleteDecoration.className, 0 /* InlineDecorationType.Regular */));
                            }
                            const result = (0, renderLines_1.renderLines)(source, renderOptions, decorations, deletedCodeDomNode);
                            const marginDomNode = document.createElement('div');
                            marginDomNode.className = 'inline-deleted-margin-view-zone';
                            (0, domFontInfo_1.applyFontInfo)(marginDomNode, renderOptions.fontInfo);
                            if (this._options.renderIndicators.read(reader)) {
                                for (let i = 0; i < result.heightInLines; i++) {
                                    const marginElement = document.createElement('div');
                                    marginElement.className = `delete-sign ${themables_1.ThemeIcon.asClassName(registrations_contribution_1.diffRemoveIcon)}`;
                                    marginElement.setAttribute('style', `position:absolute;top:${i * modLineHeight}px;width:${renderOptions.lineDecorationsWidth}px;height:${modLineHeight}px;right:0;`);
                                    marginDomNode.appendChild(marginElement);
                                }
                            }
                            let zoneId = undefined;
                            alignmentViewZonesDisposables.add(new inlineDiffDeletedCodeMargin_1.InlineDiffDeletedCodeMargin(() => (0, types_1.assertIsDefined)(zoneId), marginDomNode, this._editors.modified, a.diff, this._diffEditorWidget, result.viewLineCounts, this._editors.original.getModel(), this._contextMenuService, this._clipboardService));
                            for (let i = 0; i < result.viewLineCounts.length; i++) {
                                const count = result.viewLineCounts[i];
                                // Account for wrapped lines in the (collapsed) original editor (which doesn't wrap lines).
                                if (count > 1) {
                                    origViewZones.push({
                                        afterLineNumber: a.originalRange.startLineNumber + i,
                                        domNode: createFakeLinesDiv(),
                                        heightInPx: (count - 1) * modLineHeight,
                                        showInHiddenAreas: true,
                                        suppressMouseDown: true,
                                    });
                                }
                            }
                            modViewZones.push({
                                afterLineNumber: a.modifiedRange.startLineNumber - 1,
                                domNode: deletedCodeDomNode,
                                heightInPx: result.heightInLines * modLineHeight,
                                minWidthInPx: result.minWidthInPx,
                                marginDomNode,
                                setZoneId(id) { zoneId = id; },
                                showInHiddenAreas: true,
                                suppressMouseDown: true,
                            });
                        }
                        const marginDomNode = document.createElement('div');
                        marginDomNode.className = 'gutter-delete';
                        origViewZones.push({
                            afterLineNumber: a.originalRange.endLineNumberExclusive - 1,
                            domNode: createFakeLinesDiv(),
                            heightInPx: a.modifiedHeightInPx,
                            marginDomNode,
                            showInHiddenAreas: true,
                            suppressMouseDown: true,
                        });
                    }
                    else {
                        const delta = a.modifiedHeightInPx - a.originalHeightInPx;
                        if (delta > 0) {
                            if (syncedMovedText?.lineRangeMapping.original.delta(-1).deltaLength(2).contains(a.originalRange.endLineNumberExclusive - 1)) {
                                continue;
                            }
                            origViewZones.push({
                                afterLineNumber: a.originalRange.endLineNumberExclusive - 1,
                                domNode: createFakeLinesDiv(),
                                heightInPx: delta,
                                showInHiddenAreas: true,
                                suppressMouseDown: true,
                            });
                        }
                        else {
                            if (syncedMovedText?.lineRangeMapping.modified.delta(-1).deltaLength(2).contains(a.modifiedRange.endLineNumberExclusive - 1)) {
                                continue;
                            }
                            function createViewZoneMarginArrow() {
                                const arrow = document.createElement('div');
                                arrow.className = 'arrow-revert-change ' + themables_1.ThemeIcon.asClassName(codicons_1.Codicon.arrowRight);
                                store.add((0, dom_1.addDisposableListener)(arrow, 'mousedown', e => e.stopPropagation()));
                                store.add((0, dom_1.addDisposableListener)(arrow, 'click', e => {
                                    e.stopPropagation();
                                    _diffEditorWidget.revert(a.diff);
                                }));
                                return (0, dom_1.$)('div', {}, arrow);
                            }
                            let marginDomNode = undefined;
                            if (a.diff && a.diff.modified.isEmpty && this._options.shouldRenderOldRevertArrows.read(reader)) {
                                marginDomNode = createViewZoneMarginArrow();
                            }
                            modViewZones.push({
                                afterLineNumber: a.modifiedRange.endLineNumberExclusive - 1,
                                domNode: createFakeLinesDiv(),
                                heightInPx: -delta,
                                marginDomNode,
                                showInHiddenAreas: true,
                                suppressMouseDown: true,
                            });
                        }
                    }
                }
                for (const a of alignmentsSyncedMovedText.read(reader) ?? []) {
                    if (!syncedMovedText?.lineRangeMapping.original.intersect(a.originalRange)
                        || !syncedMovedText?.lineRangeMapping.modified.intersect(a.modifiedRange)) {
                        // ignore unrelated alignments outside the synced moved text
                        continue;
                    }
                    const delta = a.modifiedHeightInPx - a.originalHeightInPx;
                    if (delta > 0) {
                        origViewZones.push({
                            afterLineNumber: a.originalRange.endLineNumberExclusive - 1,
                            domNode: createFakeLinesDiv(),
                            heightInPx: delta,
                            showInHiddenAreas: true,
                            suppressMouseDown: true,
                        });
                    }
                    else {
                        modViewZones.push({
                            afterLineNumber: a.modifiedRange.endLineNumberExclusive - 1,
                            domNode: createFakeLinesDiv(),
                            heightInPx: -delta,
                            showInHiddenAreas: true,
                            suppressMouseDown: true,
                        });
                    }
                }
                return { orig: origViewZones, mod: modViewZones };
            });
            let ignoreChange = false;
            this._register(this._editors.original.onDidScrollChange(e => {
                if (e.scrollLeftChanged && !ignoreChange) {
                    ignoreChange = true;
                    this._editors.modified.setScrollLeft(e.scrollLeft);
                    ignoreChange = false;
                }
            }));
            this._register(this._editors.modified.onDidScrollChange(e => {
                if (e.scrollLeftChanged && !ignoreChange) {
                    ignoreChange = true;
                    this._editors.original.setScrollLeft(e.scrollLeft);
                    ignoreChange = false;
                }
            }));
            this._originalScrollTop = (0, observable_1.observableFromEvent)(this._editors.original.onDidScrollChange, () => /** @description original.getScrollTop */ this._editors.original.getScrollTop());
            this._modifiedScrollTop = (0, observable_1.observableFromEvent)(this._editors.modified.onDidScrollChange, () => /** @description modified.getScrollTop */ this._editors.modified.getScrollTop());
            // origExtraHeight + origOffset - origScrollTop = modExtraHeight + modOffset - modScrollTop
            // origScrollTop = origExtraHeight + origOffset - modExtraHeight - modOffset + modScrollTop
            // modScrollTop = modExtraHeight + modOffset - origExtraHeight - origOffset + origScrollTop
            // origOffset - modOffset = heightOfLines(1..Y) - heightOfLines(1..X)
            // origScrollTop >= 0, modScrollTop >= 0
            this._register((0, observable_1.autorun)(reader => {
                /** @description update scroll modified */
                const newScrollTopModified = this._originalScrollTop.read(reader)
                    - (this._originalScrollOffsetAnimated.get() - this._modifiedScrollOffsetAnimated.read(reader))
                    - (this._originalTopPadding.get() - this._modifiedTopPadding.read(reader));
                if (newScrollTopModified !== this._editors.modified.getScrollTop()) {
                    this._editors.modified.setScrollTop(newScrollTopModified, 1 /* ScrollType.Immediate */);
                }
            }));
            this._register((0, observable_1.autorun)(reader => {
                /** @description update scroll original */
                const newScrollTopOriginal = this._modifiedScrollTop.read(reader)
                    - (this._modifiedScrollOffsetAnimated.get() - this._originalScrollOffsetAnimated.read(reader))
                    - (this._modifiedTopPadding.get() - this._originalTopPadding.read(reader));
                if (newScrollTopOriginal !== this._editors.original.getScrollTop()) {
                    this._editors.original.setScrollTop(newScrollTopOriginal, 1 /* ScrollType.Immediate */);
                }
            }));
            this._register((0, observable_1.autorun)(reader => {
                /** @description update editor top offsets */
                const m = this._diffModel.read(reader)?.movedTextToCompare.read(reader);
                let deltaOrigToMod = 0;
                if (m) {
                    const trueTopOriginal = this._editors.original.getTopForLineNumber(m.lineRangeMapping.original.startLineNumber, true) - this._originalTopPadding.get();
                    const trueTopModified = this._editors.modified.getTopForLineNumber(m.lineRangeMapping.modified.startLineNumber, true) - this._modifiedTopPadding.get();
                    deltaOrigToMod = trueTopModified - trueTopOriginal;
                }
                if (deltaOrigToMod > 0) {
                    this._modifiedTopPadding.set(0, undefined);
                    this._originalTopPadding.set(deltaOrigToMod, undefined);
                }
                else if (deltaOrigToMod < 0) {
                    this._modifiedTopPadding.set(-deltaOrigToMod, undefined);
                    this._originalTopPadding.set(0, undefined);
                }
                else {
                    setTimeout(() => {
                        this._modifiedTopPadding.set(0, undefined);
                        this._originalTopPadding.set(0, undefined);
                    }, 400);
                }
                if (this._editors.modified.hasTextFocus()) {
                    this._originalScrollOffset.set(this._modifiedScrollOffset.get() - deltaOrigToMod, undefined, true);
                }
                else {
                    this._modifiedScrollOffset.set(this._originalScrollOffset.get() + deltaOrigToMod, undefined, true);
                }
            }));
        }
    };
    exports.DiffEditorViewZones = DiffEditorViewZones;
    exports.DiffEditorViewZones = DiffEditorViewZones = __decorate([
        __param(8, clipboardService_1.IClipboardService),
        __param(9, contextView_1.IContextMenuService)
    ], DiffEditorViewZones);
    function computeRangeAlignment(originalEditor, modifiedEditor, diffs, originalEditorAlignmentViewZones, modifiedEditorAlignmentViewZones, innerHunkAlignment) {
        const originalLineHeightOverrides = new arrays_1.ArrayQueue(getAdditionalLineHeights(originalEditor, originalEditorAlignmentViewZones));
        const modifiedLineHeightOverrides = new arrays_1.ArrayQueue(getAdditionalLineHeights(modifiedEditor, modifiedEditorAlignmentViewZones));
        const origLineHeight = originalEditor.getOption(67 /* EditorOption.lineHeight */);
        const modLineHeight = modifiedEditor.getOption(67 /* EditorOption.lineHeight */);
        const result = [];
        let lastOriginalLineNumber = 0;
        let lastModifiedLineNumber = 0;
        function handleAlignmentsOutsideOfDiffs(untilOriginalLineNumberExclusive, untilModifiedLineNumberExclusive) {
            while (true) {
                let origNext = originalLineHeightOverrides.peek();
                let modNext = modifiedLineHeightOverrides.peek();
                if (origNext && origNext.lineNumber >= untilOriginalLineNumberExclusive) {
                    origNext = undefined;
                }
                if (modNext && modNext.lineNumber >= untilModifiedLineNumberExclusive) {
                    modNext = undefined;
                }
                if (!origNext && !modNext) {
                    break;
                }
                const distOrig = origNext ? origNext.lineNumber - lastOriginalLineNumber : Number.MAX_VALUE;
                const distNext = modNext ? modNext.lineNumber - lastModifiedLineNumber : Number.MAX_VALUE;
                if (distOrig < distNext) {
                    originalLineHeightOverrides.dequeue();
                    modNext = {
                        lineNumber: origNext.lineNumber - lastOriginalLineNumber + lastModifiedLineNumber,
                        heightInPx: 0,
                    };
                }
                else if (distOrig > distNext) {
                    modifiedLineHeightOverrides.dequeue();
                    origNext = {
                        lineNumber: modNext.lineNumber - lastModifiedLineNumber + lastOriginalLineNumber,
                        heightInPx: 0,
                    };
                }
                else {
                    originalLineHeightOverrides.dequeue();
                    modifiedLineHeightOverrides.dequeue();
                }
                result.push({
                    originalRange: lineRange_1.LineRange.ofLength(origNext.lineNumber, 1),
                    modifiedRange: lineRange_1.LineRange.ofLength(modNext.lineNumber, 1),
                    originalHeightInPx: origLineHeight + origNext.heightInPx,
                    modifiedHeightInPx: modLineHeight + modNext.heightInPx,
                    diff: undefined,
                });
            }
        }
        for (const m of diffs) {
            const c = m.lineRangeMapping;
            handleAlignmentsOutsideOfDiffs(c.original.startLineNumber, c.modified.startLineNumber);
            let first = true;
            let lastModLineNumber = c.modified.startLineNumber;
            let lastOrigLineNumber = c.original.startLineNumber;
            function emitAlignment(origLineNumberExclusive, modLineNumberExclusive, forceAlignment = false) {
                if (origLineNumberExclusive < lastOrigLineNumber || modLineNumberExclusive < lastModLineNumber) {
                    return;
                }
                if (first) {
                    first = false;
                }
                else if (!forceAlignment && (origLineNumberExclusive === lastOrigLineNumber || modLineNumberExclusive === lastModLineNumber)) {
                    // This causes a re-alignment of an already aligned line.
                    // However, we don't care for the final alignment.
                    return;
                }
                const originalRange = new lineRange_1.LineRange(lastOrigLineNumber, origLineNumberExclusive);
                const modifiedRange = new lineRange_1.LineRange(lastModLineNumber, modLineNumberExclusive);
                if (originalRange.isEmpty && modifiedRange.isEmpty) {
                    return;
                }
                const originalAdditionalHeight = originalLineHeightOverrides
                    .takeWhile(v => v.lineNumber < origLineNumberExclusive)
                    ?.reduce((p, c) => p + c.heightInPx, 0) ?? 0;
                const modifiedAdditionalHeight = modifiedLineHeightOverrides
                    .takeWhile(v => v.lineNumber < modLineNumberExclusive)
                    ?.reduce((p, c) => p + c.heightInPx, 0) ?? 0;
                result.push({
                    originalRange,
                    modifiedRange,
                    originalHeightInPx: originalRange.length * origLineHeight + originalAdditionalHeight,
                    modifiedHeightInPx: modifiedRange.length * modLineHeight + modifiedAdditionalHeight,
                    diff: m.lineRangeMapping,
                });
                lastOrigLineNumber = origLineNumberExclusive;
                lastModLineNumber = modLineNumberExclusive;
            }
            if (innerHunkAlignment) {
                for (const i of c.innerChanges || []) {
                    if (i.originalRange.startColumn > 1 && i.modifiedRange.startColumn > 1) {
                        // There is some unmodified text on this line before the diff
                        emitAlignment(i.originalRange.startLineNumber, i.modifiedRange.startLineNumber);
                    }
                    const originalModel = originalEditor.getModel();
                    // When the diff is invalid, the ranges might be out of bounds (this should be fixed in the diff model by applying edits directly).
                    const maxColumn = i.originalRange.endLineNumber <= originalModel.getLineCount() ? originalModel.getLineMaxColumn(i.originalRange.endLineNumber) : Number.MAX_SAFE_INTEGER;
                    if (i.originalRange.endColumn < maxColumn) {
                        // // There is some unmodified text on this line after the diff
                        emitAlignment(i.originalRange.endLineNumber, i.modifiedRange.endLineNumber);
                    }
                }
            }
            emitAlignment(c.original.endLineNumberExclusive, c.modified.endLineNumberExclusive, true);
            lastOriginalLineNumber = c.original.endLineNumberExclusive;
            lastModifiedLineNumber = c.modified.endLineNumberExclusive;
        }
        handleAlignmentsOutsideOfDiffs(Number.MAX_VALUE, Number.MAX_VALUE);
        return result;
    }
    function getAdditionalLineHeights(editor, viewZonesToIgnore) {
        const viewZoneHeights = [];
        const wrappingZoneHeights = [];
        const hasWrapping = editor.getOption(147 /* EditorOption.wrappingInfo */).wrappingColumn !== -1;
        const coordinatesConverter = editor._getViewModel().coordinatesConverter;
        const editorLineHeight = editor.getOption(67 /* EditorOption.lineHeight */);
        if (hasWrapping) {
            for (let i = 1; i <= editor.getModel().getLineCount(); i++) {
                const lineCount = coordinatesConverter.getModelLineViewLineCount(i);
                if (lineCount > 1) {
                    wrappingZoneHeights.push({ lineNumber: i, heightInPx: editorLineHeight * (lineCount - 1) });
                }
            }
        }
        for (const w of editor.getWhitespaces()) {
            if (viewZonesToIgnore.has(w.id)) {
                continue;
            }
            const modelLineNumber = w.afterLineNumber === 0 ? 0 : coordinatesConverter.convertViewPositionToModelPosition(new position_1.Position(w.afterLineNumber, 1)).lineNumber;
            viewZoneHeights.push({ lineNumber: modelLineNumber, heightInPx: w.height });
        }
        const result = (0, utils_1.joinCombine)(viewZoneHeights, wrappingZoneHeights, v => v.lineNumber, (v1, v2) => ({ lineNumber: v1.lineNumber, heightInPx: v1.heightInPx + v2.heightInPx }));
        return result;
    }
    function allowsTrueInlineDiffRendering(mapping) {
        if (!mapping.innerChanges) {
            return false;
        }
        return mapping.innerChanges.every(c => (rangeIsSingleLine(c.modifiedRange) && rangeIsSingleLine(c.originalRange))
            || c.originalRange.equalsRange(new range_1.Range(1, 1, 1, 1)));
    }
    function rangeIsSingleLine(range) {
        return range.startLineNumber === range.endLineNumber;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[806/*vs/editor/browser/widget/diffEditor/components/diffEditorDecorations*/], __M([1/*require*/,0/*exports*/,2/*vs/base/common/lifecycle*/,21/*vs/base/common/observable*/,285/*vs/editor/browser/widget/diffEditor/components/diffEditorViewZones/diffEditorViewZones*/,364/*vs/editor/browser/widget/diffEditor/features/movedBlocksLinesFeature*/,139/*vs/editor/browser/widget/diffEditor/registrations.contribution*/,88/*vs/editor/browser/widget/diffEditor/utils*/]), function (require, exports, lifecycle_1, observable_1, diffEditorViewZones_1, movedBlocksLinesFeature_1, registrations_contribution_1, utils_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DiffEditorDecorations = void 0;
    class DiffEditorDecorations extends lifecycle_1.Disposable {
        constructor(_editors, _diffModel, _options, widget) {
            super();
            this._editors = _editors;
            this._diffModel = _diffModel;
            this._options = _options;
            this._decorations = (0, observable_1.derived)(this, (reader) => {
                const diffModel = this._diffModel.read(reader);
                const diff = diffModel?.diff.read(reader);
                if (!diff) {
                    return null;
                }
                const movedTextToCompare = this._diffModel.read(reader).movedTextToCompare.read(reader);
                const renderIndicators = this._options.renderIndicators.read(reader);
                const showEmptyDecorations = this._options.showEmptyDecorations.read(reader);
                const originalDecorations = [];
                const modifiedDecorations = [];
                if (!movedTextToCompare) {
                    for (const m of diff.mappings) {
                        if (!m.lineRangeMapping.original.isEmpty) {
                            originalDecorations.push({ range: m.lineRangeMapping.original.toInclusiveRange(), options: renderIndicators ? registrations_contribution_1.diffLineDeleteDecorationBackgroundWithIndicator : registrations_contribution_1.diffLineDeleteDecorationBackground });
                        }
                        if (!m.lineRangeMapping.modified.isEmpty) {
                            modifiedDecorations.push({ range: m.lineRangeMapping.modified.toInclusiveRange(), options: renderIndicators ? registrations_contribution_1.diffLineAddDecorationBackgroundWithIndicator : registrations_contribution_1.diffLineAddDecorationBackground });
                        }
                        if (m.lineRangeMapping.modified.isEmpty || m.lineRangeMapping.original.isEmpty) {
                            if (!m.lineRangeMapping.original.isEmpty) {
                                originalDecorations.push({ range: m.lineRangeMapping.original.toInclusiveRange(), options: registrations_contribution_1.diffWholeLineDeleteDecoration });
                            }
                            if (!m.lineRangeMapping.modified.isEmpty) {
                                modifiedDecorations.push({ range: m.lineRangeMapping.modified.toInclusiveRange(), options: registrations_contribution_1.diffWholeLineAddDecoration });
                            }
                        }
                        else {
                            const useInlineDiff = this._options.useTrueInlineDiffRendering.read(reader) && (0, diffEditorViewZones_1.allowsTrueInlineDiffRendering)(m.lineRangeMapping);
                            for (const i of m.lineRangeMapping.innerChanges || []) {
                                // Don't show empty markers outside the line range
                                if (m.lineRangeMapping.original.contains(i.originalRange.startLineNumber)) {
                                    originalDecorations.push({ range: i.originalRange, options: (i.originalRange.isEmpty() && showEmptyDecorations) ? registrations_contribution_1.diffDeleteDecorationEmpty : registrations_contribution_1.diffDeleteDecoration });
                                }
                                if (m.lineRangeMapping.modified.contains(i.modifiedRange.startLineNumber)) {
                                    modifiedDecorations.push({ range: i.modifiedRange, options: (i.modifiedRange.isEmpty() && showEmptyDecorations && !useInlineDiff) ? registrations_contribution_1.diffAddDecorationEmpty : registrations_contribution_1.diffAddDecoration });
                                }
                                if (useInlineDiff) {
                                    const deletedText = diffModel.model.original.getValueInRange(i.originalRange);
                                    modifiedDecorations.push({
                                        range: i.modifiedRange,
                                        options: {
                                            description: 'deleted-text',
                                            before: {
                                                content: deletedText,
                                                inlineClassName: 'inline-deleted-text',
                                            },
                                            zIndex: 100000,
                                            showIfCollapsed: true,
                                        }
                                    });
                                }
                            }
                        }
                    }
                }
                if (movedTextToCompare) {
                    for (const m of movedTextToCompare.changes) {
                        const fullRangeOriginal = m.original.toInclusiveRange();
                        if (fullRangeOriginal) {
                            originalDecorations.push({ range: fullRangeOriginal, options: renderIndicators ? registrations_contribution_1.diffLineDeleteDecorationBackgroundWithIndicator : registrations_contribution_1.diffLineDeleteDecorationBackground });
                        }
                        const fullRangeModified = m.modified.toInclusiveRange();
                        if (fullRangeModified) {
                            modifiedDecorations.push({ range: fullRangeModified, options: renderIndicators ? registrations_contribution_1.diffLineAddDecorationBackgroundWithIndicator : registrations_contribution_1.diffLineAddDecorationBackground });
                        }
                        for (const i of m.innerChanges || []) {
                            originalDecorations.push({ range: i.originalRange, options: registrations_contribution_1.diffDeleteDecoration });
                            modifiedDecorations.push({ range: i.modifiedRange, options: registrations_contribution_1.diffAddDecoration });
                        }
                    }
                }
                const activeMovedText = this._diffModel.read(reader).activeMovedText.read(reader);
                for (const m of diff.movedTexts) {
                    originalDecorations.push({
                        range: m.lineRangeMapping.original.toInclusiveRange(), options: {
                            description: 'moved',
                            blockClassName: 'movedOriginal' + (m === activeMovedText ? ' currentMove' : ''),
                            blockPadding: [movedBlocksLinesFeature_1.MovedBlocksLinesFeature.movedCodeBlockPadding, 0, movedBlocksLinesFeature_1.MovedBlocksLinesFeature.movedCodeBlockPadding, movedBlocksLinesFeature_1.MovedBlocksLinesFeature.movedCodeBlockPadding],
                        }
                    });
                    modifiedDecorations.push({
                        range: m.lineRangeMapping.modified.toInclusiveRange(), options: {
                            description: 'moved',
                            blockClassName: 'movedModified' + (m === activeMovedText ? ' currentMove' : ''),
                            blockPadding: [4, 0, 4, 4],
                        }
                    });
                }
                return { originalDecorations, modifiedDecorations };
            });
            this._register((0, utils_1.applyObservableDecorations)(this._editors.original, this._decorations.map(d => d?.originalDecorations || [])));
            this._register((0, utils_1.applyObservableDecorations)(this._editors.modified, this._decorations.map(d => d?.modifiedDecorations || [])));
        }
    }
    exports.DiffEditorDecorations = DiffEditorDecorations;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[807/*vs/editor/browser/widget/diffEditor/diffEditorOptions*/], __M([1/*require*/,0/*exports*/,21/*vs/base/common/observable*/,189/*vs/base/common/observableInternal/utils*/,285/*vs/editor/browser/widget/diffEditor/components/diffEditorViewZones/diffEditorViewZones*/,308/*vs/editor/common/config/diffEditor*/,37/*vs/editor/common/config/editorOptions*/,61/*vs/platform/accessibility/common/accessibility*/]), function (require, exports, observable_1, utils_1, diffEditorViewZones_1, diffEditor_1, editorOptions_1, accessibility_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DiffEditorOptions = void 0;
    let DiffEditorOptions = class DiffEditorOptions {
        get editorOptions() { return this._options; }
        constructor(options, _accessibilityService) {
            this._accessibilityService = _accessibilityService;
            this._diffEditorWidth = (0, observable_1.observableValue)(this, 0);
            this._screenReaderMode = (0, observable_1.observableFromEvent)(this, this._accessibilityService.onDidChangeScreenReaderOptimized, () => this._accessibilityService.isScreenReaderOptimized());
            this.couldShowInlineViewBecauseOfSize = (0, observable_1.derived)(this, reader => this._options.read(reader).renderSideBySide && this._diffEditorWidth.read(reader) <= this._options.read(reader).renderSideBySideInlineBreakpoint);
            this.renderOverviewRuler = (0, observable_1.derived)(this, reader => this._options.read(reader).renderOverviewRuler);
            this.renderSideBySide = (0, observable_1.derived)(this, reader => {
                if (this.compactMode.read(reader)) {
                    if (this.shouldRenderInlineViewInSmartMode.read(reader)) {
                        return false;
                    }
                }
                return this._options.read(reader).renderSideBySide
                    && !(this._options.read(reader).useInlineViewWhenSpaceIsLimited && this.couldShowInlineViewBecauseOfSize.read(reader) && !this._screenReaderMode.read(reader));
            });
            this.readOnly = (0, observable_1.derived)(this, reader => this._options.read(reader).readOnly);
            this.shouldRenderOldRevertArrows = (0, observable_1.derived)(this, reader => {
                if (!this._options.read(reader).renderMarginRevertIcon) {
                    return false;
                }
                if (!this.renderSideBySide.read(reader)) {
                    return false;
                }
                if (this.readOnly.read(reader)) {
                    return false;
                }
                if (this.shouldRenderGutterMenu.read(reader)) {
                    return false;
                }
                return true;
            });
            this.shouldRenderGutterMenu = (0, observable_1.derived)(this, reader => this._options.read(reader).renderGutterMenu);
            this.renderIndicators = (0, observable_1.derived)(this, reader => this._options.read(reader).renderIndicators);
            this.enableSplitViewResizing = (0, observable_1.derived)(this, reader => this._options.read(reader).enableSplitViewResizing);
            this.splitViewDefaultRatio = (0, observable_1.derived)(this, reader => this._options.read(reader).splitViewDefaultRatio);
            this.ignoreTrimWhitespace = (0, observable_1.derived)(this, reader => this._options.read(reader).ignoreTrimWhitespace);
            this.maxComputationTimeMs = (0, observable_1.derived)(this, reader => this._options.read(reader).maxComputationTime);
            this.showMoves = (0, observable_1.derived)(this, reader => this._options.read(reader).experimental.showMoves && this.renderSideBySide.read(reader));
            this.isInEmbeddedEditor = (0, observable_1.derived)(this, reader => this._options.read(reader).isInEmbeddedEditor);
            this.diffWordWrap = (0, observable_1.derived)(this, reader => this._options.read(reader).diffWordWrap);
            this.originalEditable = (0, observable_1.derived)(this, reader => this._options.read(reader).originalEditable);
            this.diffCodeLens = (0, observable_1.derived)(this, reader => this._options.read(reader).diffCodeLens);
            this.accessibilityVerbose = (0, observable_1.derived)(this, reader => this._options.read(reader).accessibilityVerbose);
            this.diffAlgorithm = (0, observable_1.derived)(this, reader => this._options.read(reader).diffAlgorithm);
            this.showEmptyDecorations = (0, observable_1.derived)(this, reader => this._options.read(reader).experimental.showEmptyDecorations);
            this.onlyShowAccessibleDiffViewer = (0, observable_1.derived)(this, reader => this._options.read(reader).onlyShowAccessibleDiffViewer);
            this.compactMode = (0, observable_1.derived)(this, reader => this._options.read(reader).compactMode);
            this.trueInlineDiffRenderingEnabled = (0, observable_1.derived)(this, reader => this._options.read(reader).experimental.useTrueInlineView);
            this.useTrueInlineDiffRendering = (0, observable_1.derived)(this, reader => !this.renderSideBySide.read(reader) && this.trueInlineDiffRenderingEnabled.read(reader));
            this.hideUnchangedRegions = (0, observable_1.derived)(this, reader => this._options.read(reader).hideUnchangedRegions.enabled);
            this.hideUnchangedRegionsRevealLineCount = (0, observable_1.derived)(this, reader => this._options.read(reader).hideUnchangedRegions.revealLineCount);
            this.hideUnchangedRegionsContextLineCount = (0, observable_1.derived)(this, reader => this._options.read(reader).hideUnchangedRegions.contextLineCount);
            this.hideUnchangedRegionsMinimumLineCount = (0, observable_1.derived)(this, reader => this._options.read(reader).hideUnchangedRegions.minimumLineCount);
            this._model = (0, observable_1.observableValue)(this, undefined);
            this.shouldRenderInlineViewInSmartMode = this._model
                .map(this, model => (0, utils_1.derivedConstOnceDefined)(this, reader => {
                const diffs = model?.diff.read(reader);
                return diffs ? isSimpleDiff(diffs, this.trueInlineDiffRenderingEnabled.read(reader)) : undefined;
            }))
                .flatten()
                .map(this, v => !!v);
            this.inlineViewHideOriginalLineNumbers = this.compactMode;
            const optionsCopy = { ...options, ...validateDiffEditorOptions(options, diffEditor_1.diffEditorDefaultOptions) };
            this._options = (0, observable_1.observableValue)(this, optionsCopy);
        }
        updateOptions(changedOptions) {
            const newDiffEditorOptions = validateDiffEditorOptions(changedOptions, this._options.get());
            const newOptions = { ...this._options.get(), ...changedOptions, ...newDiffEditorOptions };
            this._options.set(newOptions, undefined, { changedOptions: changedOptions });
        }
        setWidth(width) {
            this._diffEditorWidth.set(width, undefined);
        }
        setModel(model) {
            this._model.set(model, undefined);
        }
    };
    exports.DiffEditorOptions = DiffEditorOptions;
    exports.DiffEditorOptions = DiffEditorOptions = __decorate([
        __param(1, accessibility_1.IAccessibilityService)
    ], DiffEditorOptions);
    function isSimpleDiff(diff, supportsTrueDiffRendering) {
        return diff.mappings.every(m => isInsertion(m.lineRangeMapping) || isDeletion(m.lineRangeMapping) || (supportsTrueDiffRendering && (0, diffEditorViewZones_1.allowsTrueInlineDiffRendering)(m.lineRangeMapping)));
    }
    function isInsertion(mapping) {
        return mapping.original.length === 0;
    }
    function isDeletion(mapping) {
        return mapping.modified.length === 0;
    }
    function validateDiffEditorOptions(options, defaults) {
        return {
            enableSplitViewResizing: (0, editorOptions_1.boolean)(options.enableSplitViewResizing, defaults.enableSplitViewResizing),
            splitViewDefaultRatio: (0, editorOptions_1.clampedFloat)(options.splitViewDefaultRatio, 0.5, 0.1, 0.9),
            renderSideBySide: (0, editorOptions_1.boolean)(options.renderSideBySide, defaults.renderSideBySide),
            renderMarginRevertIcon: (0, editorOptions_1.boolean)(options.renderMarginRevertIcon, defaults.renderMarginRevertIcon),
            maxComputationTime: (0, editorOptions_1.clampedInt)(options.maxComputationTime, defaults.maxComputationTime, 0, 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */),
            maxFileSize: (0, editorOptions_1.clampedInt)(options.maxFileSize, defaults.maxFileSize, 0, 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */),
            ignoreTrimWhitespace: (0, editorOptions_1.boolean)(options.ignoreTrimWhitespace, defaults.ignoreTrimWhitespace),
            renderIndicators: (0, editorOptions_1.boolean)(options.renderIndicators, defaults.renderIndicators),
            originalEditable: (0, editorOptions_1.boolean)(options.originalEditable, defaults.originalEditable),
            diffCodeLens: (0, editorOptions_1.boolean)(options.diffCodeLens, defaults.diffCodeLens),
            renderOverviewRuler: (0, editorOptions_1.boolean)(options.renderOverviewRuler, defaults.renderOverviewRuler),
            diffWordWrap: (0, editorOptions_1.stringSet)(options.diffWordWrap, defaults.diffWordWrap, ['off', 'on', 'inherit']),
            diffAlgorithm: (0, editorOptions_1.stringSet)(options.diffAlgorithm, defaults.diffAlgorithm, ['legacy', 'advanced'], { 'smart': 'legacy', 'experimental': 'advanced' }),
            accessibilityVerbose: (0, editorOptions_1.boolean)(options.accessibilityVerbose, defaults.accessibilityVerbose),
            experimental: {
                showMoves: (0, editorOptions_1.boolean)(options.experimental?.showMoves, defaults.experimental.showMoves),
                showEmptyDecorations: (0, editorOptions_1.boolean)(options.experimental?.showEmptyDecorations, defaults.experimental.showEmptyDecorations),
                useTrueInlineView: (0, editorOptions_1.boolean)(options.experimental?.useTrueInlineView, defaults.experimental.useTrueInlineView),
            },
            hideUnchangedRegions: {
                enabled: (0, editorOptions_1.boolean)(options.hideUnchangedRegions?.enabled ?? options.experimental?.collapseUnchangedRegions, defaults.hideUnchangedRegions.enabled),
                contextLineCount: (0, editorOptions_1.clampedInt)(options.hideUnchangedRegions?.contextLineCount, defaults.hideUnchangedRegions.contextLineCount, 0, 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */),
                minimumLineCount: (0, editorOptions_1.clampedInt)(options.hideUnchangedRegions?.minimumLineCount, defaults.hideUnchangedRegions.minimumLineCount, 0, 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */),
                revealLineCount: (0, editorOptions_1.clampedInt)(options.hideUnchangedRegions?.revealLineCount, defaults.hideUnchangedRegions.revealLineCount, 0, 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */),
            },
            isInEmbeddedEditor: (0, editorOptions_1.boolean)(options.isInEmbeddedEditor, defaults.isInEmbeddedEditor),
            onlyShowAccessibleDiffViewer: (0, editorOptions_1.boolean)(options.onlyShowAccessibleDiffViewer, defaults.onlyShowAccessibleDiffViewer),
            renderSideBySideInlineBreakpoint: (0, editorOptions_1.clampedInt)(options.renderSideBySideInlineBreakpoint, defaults.renderSideBySideInlineBreakpoint, 0, 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */),
            useInlineViewWhenSpaceIsLimited: (0, editorOptions_1.boolean)(options.useInlineViewWhenSpaceIsLimited, defaults.useInlineViewWhenSpaceIsLimited),
            renderGutterMenu: (0, editorOptions_1.boolean)(options.renderGutterMenu, defaults.renderGutterMenu),
            compactMode: (0, editorOptions_1.boolean)(options.compactMode, defaults.compactMode),
        };
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[808/*vs/editor/common/services/modelService*/], __M([1/*require*/,0/*exports*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,16/*vs/base/common/platform*/,35/*vs/editor/common/model/textModel*/,197/*vs/editor/common/core/textModelDefaults*/,70/*vs/editor/common/languages/modesRegistry*/,211/*vs/editor/common/services/textResourceConfiguration*/,28/*vs/platform/configuration/common/configuration*/,284/*vs/platform/undoRedo/common/undoRedo*/,129/*vs/base/common/hash*/,370/*vs/editor/common/model/editStack*/,42/*vs/base/common/network*/,60/*vs/base/common/objects*/,7/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, event_1, lifecycle_1, platform, textModel_1, textModelDefaults_1, modesRegistry_1, textResourceConfiguration_1, configuration_1, undoRedo_1, hash_1, editStack_1, network_1, objects_1, instantiation_1) {
    "use strict";
    var ModelService_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DefaultModelSHA1Computer = exports.ModelService = void 0;
    function MODEL_ID(resource) {
        return resource.toString();
    }
    class ModelData {
        constructor(model, onWillDispose, onDidChangeLanguage) {
            this.model = model;
            this._modelEventListeners = new lifecycle_1.DisposableStore();
            this.model = model;
            this._modelEventListeners.add(model.onWillDispose(() => onWillDispose(model)));
            this._modelEventListeners.add(model.onDidChangeLanguage((e) => onDidChangeLanguage(model, e)));
        }
        dispose() {
            this._modelEventListeners.dispose();
        }
    }
    const DEFAULT_EOL = (platform.isLinux || platform.isMacintosh) ? 1 /* DefaultEndOfLine.LF */ : 2 /* DefaultEndOfLine.CRLF */;
    class DisposedModelInfo {
        constructor(uri, initialUndoRedoSnapshot, time, sharesUndoRedoStack, heapSize, sha1, versionId, alternativeVersionId) {
            this.uri = uri;
            this.initialUndoRedoSnapshot = initialUndoRedoSnapshot;
            this.time = time;
            this.sharesUndoRedoStack = sharesUndoRedoStack;
            this.heapSize = heapSize;
            this.sha1 = sha1;
            this.versionId = versionId;
            this.alternativeVersionId = alternativeVersionId;
        }
    }
    let ModelService = class ModelService extends lifecycle_1.Disposable {
        static { ModelService_1 = this; }
        static { this.MAX_MEMORY_FOR_CLOSED_FILES_UNDO_STACK = 20 * 1024 * 1024; }
        constructor(_configurationService, _resourcePropertiesService, _undoRedoService, _instantiationService) {
            super();
            this._configurationService = _configurationService;
            this._resourcePropertiesService = _resourcePropertiesService;
            this._undoRedoService = _undoRedoService;
            this._instantiationService = _instantiationService;
            this._onModelAdded = this._register(new event_1.Emitter());
            this.onModelAdded = this._onModelAdded.event;
            this._onModelRemoved = this._register(new event_1.Emitter());
            this.onModelRemoved = this._onModelRemoved.event;
            this._onModelModeChanged = this._register(new event_1.Emitter());
            this.onModelLanguageChanged = this._onModelModeChanged.event;
            this._modelCreationOptionsByLanguageAndResource = Object.create(null);
            this._models = {};
            this._disposedModels = new Map();
            this._disposedModelsHeapSize = 0;
            this._register(this._configurationService.onDidChangeConfiguration(e => this._updateModelOptions(e)));
            this._updateModelOptions(undefined);
        }
        static _readModelOptions(config, isForSimpleWidget) {
            let tabSize = textModelDefaults_1.EDITOR_MODEL_DEFAULTS.tabSize;
            if (config.editor && typeof config.editor.tabSize !== 'undefined') {
                const parsedTabSize = parseInt(config.editor.tabSize, 10);
                if (!isNaN(parsedTabSize)) {
                    tabSize = parsedTabSize;
                }
                if (tabSize < 1) {
                    tabSize = 1;
                }
            }
            let indentSize = 'tabSize';
            if (config.editor && typeof config.editor.indentSize !== 'undefined' && config.editor.indentSize !== 'tabSize') {
                const parsedIndentSize = parseInt(config.editor.indentSize, 10);
                if (!isNaN(parsedIndentSize)) {
                    indentSize = Math.max(parsedIndentSize, 1);
                }
            }
            let insertSpaces = textModelDefaults_1.EDITOR_MODEL_DEFAULTS.insertSpaces;
            if (config.editor && typeof config.editor.insertSpaces !== 'undefined') {
                insertSpaces = (config.editor.insertSpaces === 'false' ? false : Boolean(config.editor.insertSpaces));
            }
            let newDefaultEOL = DEFAULT_EOL;
            const eol = config.eol;
            if (eol === '\r\n') {
                newDefaultEOL = 2 /* DefaultEndOfLine.CRLF */;
            }
            else if (eol === '\n') {
                newDefaultEOL = 1 /* DefaultEndOfLine.LF */;
            }
            let trimAutoWhitespace = textModelDefaults_1.EDITOR_MODEL_DEFAULTS.trimAutoWhitespace;
            if (config.editor && typeof config.editor.trimAutoWhitespace !== 'undefined') {
                trimAutoWhitespace = (config.editor.trimAutoWhitespace === 'false' ? false : Boolean(config.editor.trimAutoWhitespace));
            }
            let detectIndentation = textModelDefaults_1.EDITOR_MODEL_DEFAULTS.detectIndentation;
            if (config.editor && typeof config.editor.detectIndentation !== 'undefined') {
                detectIndentation = (config.editor.detectIndentation === 'false' ? false : Boolean(config.editor.detectIndentation));
            }
            let largeFileOptimizations = textModelDefaults_1.EDITOR_MODEL_DEFAULTS.largeFileOptimizations;
            if (config.editor && typeof config.editor.largeFileOptimizations !== 'undefined') {
                largeFileOptimizations = (config.editor.largeFileOptimizations === 'false' ? false : Boolean(config.editor.largeFileOptimizations));
            }
            let bracketPairColorizationOptions = textModelDefaults_1.EDITOR_MODEL_DEFAULTS.bracketPairColorizationOptions;
            if (config.editor?.bracketPairColorization && typeof config.editor.bracketPairColorization === 'object') {
                bracketPairColorizationOptions = {
                    enabled: !!config.editor.bracketPairColorization.enabled,
                    independentColorPoolPerBracketType: !!config.editor.bracketPairColorization.independentColorPoolPerBracketType
                };
            }
            return {
                isForSimpleWidget: isForSimpleWidget,
                tabSize: tabSize,
                indentSize: indentSize,
                insertSpaces: insertSpaces,
                detectIndentation: detectIndentation,
                defaultEOL: newDefaultEOL,
                trimAutoWhitespace: trimAutoWhitespace,
                largeFileOptimizations: largeFileOptimizations,
                bracketPairColorizationOptions
            };
        }
        _getEOL(resource, language) {
            if (resource) {
                return this._resourcePropertiesService.getEOL(resource, language);
            }
            const eol = this._configurationService.getValue('files.eol', { overrideIdentifier: language });
            if (eol && typeof eol === 'string' && eol !== 'auto') {
                return eol;
            }
            return platform.OS === 3 /* platform.OperatingSystem.Linux */ || platform.OS === 2 /* platform.OperatingSystem.Macintosh */ ? '\n' : '\r\n';
        }
        _shouldRestoreUndoStack() {
            const result = this._configurationService.getValue('files.restoreUndoStack');
            if (typeof result === 'boolean') {
                return result;
            }
            return true;
        }
        getCreationOptions(languageIdOrSelection, resource, isForSimpleWidget) {
            const language = (typeof languageIdOrSelection === 'string' ? languageIdOrSelection : languageIdOrSelection.languageId);
            let creationOptions = this._modelCreationOptionsByLanguageAndResource[language + resource];
            if (!creationOptions) {
                const editor = this._configurationService.getValue('editor', { overrideIdentifier: language, resource });
                const eol = this._getEOL(resource, language);
                creationOptions = ModelService_1._readModelOptions({ editor, eol }, isForSimpleWidget);
                this._modelCreationOptionsByLanguageAndResource[language + resource] = creationOptions;
            }
            return creationOptions;
        }
        _updateModelOptions(e) {
            const oldOptionsByLanguageAndResource = this._modelCreationOptionsByLanguageAndResource;
            this._modelCreationOptionsByLanguageAndResource = Object.create(null);
            // Update options on all models
            const keys = Object.keys(this._models);
            for (let i = 0, len = keys.length; i < len; i++) {
                const modelId = keys[i];
                const modelData = this._models[modelId];
                const language = modelData.model.getLanguageId();
                const uri = modelData.model.uri;
                if (e && !e.affectsConfiguration('editor', { overrideIdentifier: language, resource: uri }) && !e.affectsConfiguration('files.eol', { overrideIdentifier: language, resource: uri })) {
                    continue; // perf: skip if this model is not affected by configuration change
                }
                const oldOptions = oldOptionsByLanguageAndResource[language + uri];
                const newOptions = this.getCreationOptions(language, uri, modelData.model.isForSimpleWidget);
                ModelService_1._setModelOptionsForModel(modelData.model, newOptions, oldOptions);
            }
        }
        static _setModelOptionsForModel(model, newOptions, currentOptions) {
            if (currentOptions && currentOptions.defaultEOL !== newOptions.defaultEOL && model.getLineCount() === 1) {
                model.setEOL(newOptions.defaultEOL === 1 /* DefaultEndOfLine.LF */ ? 0 /* EndOfLineSequence.LF */ : 1 /* EndOfLineSequence.CRLF */);
            }
            if (currentOptions
                && (currentOptions.detectIndentation === newOptions.detectIndentation)
                && (currentOptions.insertSpaces === newOptions.insertSpaces)
                && (currentOptions.tabSize === newOptions.tabSize)
                && (currentOptions.indentSize === newOptions.indentSize)
                && (currentOptions.trimAutoWhitespace === newOptions.trimAutoWhitespace)
                && (0, objects_1.equals)(currentOptions.bracketPairColorizationOptions, newOptions.bracketPairColorizationOptions)) {
                // Same indent opts, no need to touch the model
                return;
            }
            if (newOptions.detectIndentation) {
                model.detectIndentation(newOptions.insertSpaces, newOptions.tabSize);
                model.updateOptions({
                    trimAutoWhitespace: newOptions.trimAutoWhitespace,
                    bracketColorizationOptions: newOptions.bracketPairColorizationOptions
                });
            }
            else {
                model.updateOptions({
                    insertSpaces: newOptions.insertSpaces,
                    tabSize: newOptions.tabSize,
                    indentSize: newOptions.indentSize,
                    trimAutoWhitespace: newOptions.trimAutoWhitespace,
                    bracketColorizationOptions: newOptions.bracketPairColorizationOptions
                });
            }
        }
        // --- begin IModelService
        _insertDisposedModel(disposedModelData) {
            this._disposedModels.set(MODEL_ID(disposedModelData.uri), disposedModelData);
            this._disposedModelsHeapSize += disposedModelData.heapSize;
        }
        _removeDisposedModel(resource) {
            const disposedModelData = this._disposedModels.get(MODEL_ID(resource));
            if (disposedModelData) {
                this._disposedModelsHeapSize -= disposedModelData.heapSize;
            }
            this._disposedModels.delete(MODEL_ID(resource));
            return disposedModelData;
        }
        _ensureDisposedModelsHeapSize(maxModelsHeapSize) {
            if (this._disposedModelsHeapSize > maxModelsHeapSize) {
                // we must remove some old undo stack elements to free up some memory
                const disposedModels = [];
                this._disposedModels.forEach(entry => {
                    if (!entry.sharesUndoRedoStack) {
                        disposedModels.push(entry);
                    }
                });
                disposedModels.sort((a, b) => a.time - b.time);
                while (disposedModels.length > 0 && this._disposedModelsHeapSize > maxModelsHeapSize) {
                    const disposedModel = disposedModels.shift();
                    this._removeDisposedModel(disposedModel.uri);
                    if (disposedModel.initialUndoRedoSnapshot !== null) {
                        this._undoRedoService.restoreSnapshot(disposedModel.initialUndoRedoSnapshot);
                    }
                }
            }
        }
        _createModelData(value, languageIdOrSelection, resource, isForSimpleWidget) {
            // create & save the model
            const options = this.getCreationOptions(languageIdOrSelection, resource, isForSimpleWidget);
            const model = this._instantiationService.createInstance(textModel_1.TextModel, value, languageIdOrSelection, options, resource);
            if (resource && this._disposedModels.has(MODEL_ID(resource))) {
                const disposedModelData = this._removeDisposedModel(resource);
                const elements = this._undoRedoService.getElements(resource);
                const sha1Computer = this._getSHA1Computer();
                const sha1IsEqual = (sha1Computer.canComputeSHA1(model)
                    ? sha1Computer.computeSHA1(model) === disposedModelData.sha1
                    : false);
                if (sha1IsEqual || disposedModelData.sharesUndoRedoStack) {
                    for (const element of elements.past) {
                        if ((0, editStack_1.isEditStackElement)(element) && element.matchesResource(resource)) {
                            element.setModel(model);
                        }
                    }
                    for (const element of elements.future) {
                        if ((0, editStack_1.isEditStackElement)(element) && element.matchesResource(resource)) {
                            element.setModel(model);
                        }
                    }
                    this._undoRedoService.setElementsValidFlag(resource, true, (element) => ((0, editStack_1.isEditStackElement)(element) && element.matchesResource(resource)));
                    if (sha1IsEqual) {
                        model._overwriteVersionId(disposedModelData.versionId);
                        model._overwriteAlternativeVersionId(disposedModelData.alternativeVersionId);
                        model._overwriteInitialUndoRedoSnapshot(disposedModelData.initialUndoRedoSnapshot);
                    }
                }
                else {
                    if (disposedModelData.initialUndoRedoSnapshot !== null) {
                        this._undoRedoService.restoreSnapshot(disposedModelData.initialUndoRedoSnapshot);
                    }
                }
            }
            const modelId = MODEL_ID(model.uri);
            if (this._models[modelId]) {
                // There already exists a model with this id => this is a programmer error
                throw new Error('ModelService: Cannot add model because it already exists!');
            }
            const modelData = new ModelData(model, (model) => this._onWillDispose(model), (model, e) => this._onDidChangeLanguage(model, e));
            this._models[modelId] = modelData;
            return modelData;
        }
        createModel(value, languageSelection, resource, isForSimpleWidget = false) {
            let modelData;
            if (languageSelection) {
                modelData = this._createModelData(value, languageSelection, resource, isForSimpleWidget);
            }
            else {
                modelData = this._createModelData(value, modesRegistry_1.PLAINTEXT_LANGUAGE_ID, resource, isForSimpleWidget);
            }
            this._onModelAdded.fire(modelData.model);
            return modelData.model;
        }
        getModels() {
            const ret = [];
            const keys = Object.keys(this._models);
            for (let i = 0, len = keys.length; i < len; i++) {
                const modelId = keys[i];
                ret.push(this._models[modelId].model);
            }
            return ret;
        }
        getModel(resource) {
            const modelId = MODEL_ID(resource);
            const modelData = this._models[modelId];
            if (!modelData) {
                return null;
            }
            return modelData.model;
        }
        // --- end IModelService
        _schemaShouldMaintainUndoRedoElements(resource) {
            return (resource.scheme === network_1.Schemas.file
                || resource.scheme === network_1.Schemas.vscodeRemote
                || resource.scheme === network_1.Schemas.vscodeUserData
                || resource.scheme === network_1.Schemas.vscodeNotebookCell
                || resource.scheme === 'fake-fs' // for tests
            );
        }
        _onWillDispose(model) {
            const modelId = MODEL_ID(model.uri);
            const modelData = this._models[modelId];
            const sharesUndoRedoStack = (this._undoRedoService.getUriComparisonKey(model.uri) !== model.uri.toString());
            let maintainUndoRedoStack = false;
            let heapSize = 0;
            if (sharesUndoRedoStack || (this._shouldRestoreUndoStack() && this._schemaShouldMaintainUndoRedoElements(model.uri))) {
                const elements = this._undoRedoService.getElements(model.uri);
                if (elements.past.length > 0 || elements.future.length > 0) {
                    for (const element of elements.past) {
                        if ((0, editStack_1.isEditStackElement)(element) && element.matchesResource(model.uri)) {
                            maintainUndoRedoStack = true;
                            heapSize += element.heapSize(model.uri);
                            element.setModel(model.uri); // remove reference from text buffer instance
                        }
                    }
                    for (const element of elements.future) {
                        if ((0, editStack_1.isEditStackElement)(element) && element.matchesResource(model.uri)) {
                            maintainUndoRedoStack = true;
                            heapSize += element.heapSize(model.uri);
                            element.setModel(model.uri); // remove reference from text buffer instance
                        }
                    }
                }
            }
            const maxMemory = ModelService_1.MAX_MEMORY_FOR_CLOSED_FILES_UNDO_STACK;
            const sha1Computer = this._getSHA1Computer();
            if (!maintainUndoRedoStack) {
                if (!sharesUndoRedoStack) {
                    const initialUndoRedoSnapshot = modelData.model.getInitialUndoRedoSnapshot();
                    if (initialUndoRedoSnapshot !== null) {
                        this._undoRedoService.restoreSnapshot(initialUndoRedoSnapshot);
                    }
                }
            }
            else if (!sharesUndoRedoStack && (heapSize > maxMemory || !sha1Computer.canComputeSHA1(model))) {
                // the undo stack for this file would never fit in the configured memory or the file is very large, so don't bother with it.
                const initialUndoRedoSnapshot = modelData.model.getInitialUndoRedoSnapshot();
                if (initialUndoRedoSnapshot !== null) {
                    this._undoRedoService.restoreSnapshot(initialUndoRedoSnapshot);
                }
            }
            else {
                this._ensureDisposedModelsHeapSize(maxMemory - heapSize);
                // We only invalidate the elements, but they remain in the undo-redo service.
                this._undoRedoService.setElementsValidFlag(model.uri, false, (element) => ((0, editStack_1.isEditStackElement)(element) && element.matchesResource(model.uri)));
                this._insertDisposedModel(new DisposedModelInfo(model.uri, modelData.model.getInitialUndoRedoSnapshot(), Date.now(), sharesUndoRedoStack, heapSize, sha1Computer.computeSHA1(model), model.getVersionId(), model.getAlternativeVersionId()));
            }
            delete this._models[modelId];
            modelData.dispose();
            // clean up cache
            delete this._modelCreationOptionsByLanguageAndResource[model.getLanguageId() + model.uri];
            this._onModelRemoved.fire(model);
        }
        _onDidChangeLanguage(model, e) {
            const oldLanguageId = e.oldLanguage;
            const newLanguageId = model.getLanguageId();
            const oldOptions = this.getCreationOptions(oldLanguageId, model.uri, model.isForSimpleWidget);
            const newOptions = this.getCreationOptions(newLanguageId, model.uri, model.isForSimpleWidget);
            ModelService_1._setModelOptionsForModel(model, newOptions, oldOptions);
            this._onModelModeChanged.fire({ model, oldLanguageId: oldLanguageId });
        }
        _getSHA1Computer() {
            return new DefaultModelSHA1Computer();
        }
    };
    exports.ModelService = ModelService;
    exports.ModelService = ModelService = ModelService_1 = __decorate([
        __param(0, configuration_1.IConfigurationService),
        __param(1, textResourceConfiguration_1.ITextResourcePropertiesService),
        __param(2, undoRedo_1.IUndoRedoService),
        __param(3, instantiation_1.IInstantiationService)
    ], ModelService);
    class DefaultModelSHA1Computer {
        static { this.MAX_MODEL_SIZE = 10 * 1024 * 1024; } // takes 200ms to compute a sha1 on a 10MB model on a new machine
        canComputeSHA1(model) {
            return (model.getValueLength() <= DefaultModelSHA1Computer.MAX_MODEL_SIZE);
        }
        computeSHA1(model) {
            // compute the sha1
            const shaComputer = new hash_1.StringSHA1();
            const snapshot = model.createSnapshot();
            let text;
            while ((text = snapshot.read())) {
                shaComputer.update(text);
            }
            return shaComputer.digest();
        }
    }
    exports.DefaultModelSHA1Computer = DefaultModelSHA1Computer;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[809/*vs/editor/common/viewModel/viewModelLines*/], __M([1/*require*/,0/*exports*/,13/*vs/base/common/arrays*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/,239/*vs/editor/common/textModelGuides*/,35/*vs/editor/common/model/textModel*/,132/*vs/editor/common/textModelEvents*/,243/*vs/editor/common/viewEvents*/,602/*vs/editor/common/viewModel/modelLineProjection*/,322/*vs/editor/common/model/prefixSumComputer*/,95/*vs/editor/common/viewModel*/]), function (require, exports, arrays, position_1, range_1, textModelGuides_1, textModel_1, textModelEvents_1, viewEvents, modelLineProjection_1, prefixSumComputer_1, viewModel_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ViewModelLinesFromModelAsIs = exports.ViewModelLinesFromProjectedModel = void 0;
    class ViewModelLinesFromProjectedModel {
        constructor(editorId, model, domLineBreaksComputerFactory, monospaceLineBreaksComputerFactory, fontInfo, tabSize, wrappingStrategy, wrappingColumn, wrappingIndent, wordBreak) {
            this._editorId = editorId;
            this.model = model;
            this._validModelVersionId = -1;
            this._domLineBreaksComputerFactory = domLineBreaksComputerFactory;
            this._monospaceLineBreaksComputerFactory = monospaceLineBreaksComputerFactory;
            this.fontInfo = fontInfo;
            this.tabSize = tabSize;
            this.wrappingStrategy = wrappingStrategy;
            this.wrappingColumn = wrappingColumn;
            this.wrappingIndent = wrappingIndent;
            this.wordBreak = wordBreak;
            this._constructLines(/*resetHiddenAreas*/ true, null);
        }
        dispose() {
            this.hiddenAreasDecorationIds = this.model.deltaDecorations(this.hiddenAreasDecorationIds, []);
        }
        createCoordinatesConverter() {
            return new CoordinatesConverter(this);
        }
        _constructLines(resetHiddenAreas, previousLineBreaks) {
            this.modelLineProjections = [];
            if (resetHiddenAreas) {
                this.hiddenAreasDecorationIds = this.model.deltaDecorations(this.hiddenAreasDecorationIds, []);
            }
            const linesContent = this.model.getLinesContent();
            const injectedTextDecorations = this.model.getInjectedTextDecorations(this._editorId);
            const lineCount = linesContent.length;
            const lineBreaksComputer = this.createLineBreaksComputer();
            const injectedTextQueue = new arrays.ArrayQueue(textModelEvents_1.LineInjectedText.fromDecorations(injectedTextDecorations));
            for (let i = 0; i < lineCount; i++) {
                const lineInjectedText = injectedTextQueue.takeWhile(t => t.lineNumber === i + 1);
                lineBreaksComputer.addRequest(linesContent[i], lineInjectedText, previousLineBreaks ? previousLineBreaks[i] : null);
            }
            const linesBreaks = lineBreaksComputer.finalize();
            const values = [];
            const hiddenAreas = this.hiddenAreasDecorationIds.map((areaId) => this.model.getDecorationRange(areaId)).sort(range_1.Range.compareRangesUsingStarts);
            let hiddenAreaStart = 1, hiddenAreaEnd = 0;
            let hiddenAreaIdx = -1;
            let nextLineNumberToUpdateHiddenArea = (hiddenAreaIdx + 1 < hiddenAreas.length) ? hiddenAreaEnd + 1 : lineCount + 2;
            for (let i = 0; i < lineCount; i++) {
                const lineNumber = i + 1;
                if (lineNumber === nextLineNumberToUpdateHiddenArea) {
                    hiddenAreaIdx++;
                    hiddenAreaStart = hiddenAreas[hiddenAreaIdx].startLineNumber;
                    hiddenAreaEnd = hiddenAreas[hiddenAreaIdx].endLineNumber;
                    nextLineNumberToUpdateHiddenArea = (hiddenAreaIdx + 1 < hiddenAreas.length) ? hiddenAreaEnd + 1 : lineCount + 2;
                }
                const isInHiddenArea = (lineNumber >= hiddenAreaStart && lineNumber <= hiddenAreaEnd);
                const line = (0, modelLineProjection_1.createModelLineProjection)(linesBreaks[i], !isInHiddenArea);
                values[i] = line.getViewLineCount();
                this.modelLineProjections[i] = line;
            }
            this._validModelVersionId = this.model.getVersionId();
            this.projectedModelLineLineCounts = new prefixSumComputer_1.ConstantTimePrefixSumComputer(values);
        }
        getHiddenAreas() {
            return this.hiddenAreasDecorationIds.map((decId) => this.model.getDecorationRange(decId));
        }
        setHiddenAreas(_ranges) {
            const validatedRanges = _ranges.map(r => this.model.validateRange(r));
            const newRanges = normalizeLineRanges(validatedRanges);
            // TODO@Martin: Please stop calling this method on each model change!
            // This checks if there really was a change
            const oldRanges = this.hiddenAreasDecorationIds.map((areaId) => this.model.getDecorationRange(areaId)).sort(range_1.Range.compareRangesUsingStarts);
            if (newRanges.length === oldRanges.length) {
                let hasDifference = false;
                for (let i = 0; i < newRanges.length; i++) {
                    if (!newRanges[i].equalsRange(oldRanges[i])) {
                        hasDifference = true;
                        break;
                    }
                }
                if (!hasDifference) {
                    return false;
                }
            }
            const newDecorations = newRanges.map((r) => ({
                range: r,
                options: textModel_1.ModelDecorationOptions.EMPTY,
            }));
            this.hiddenAreasDecorationIds = this.model.deltaDecorations(this.hiddenAreasDecorationIds, newDecorations);
            const hiddenAreas = newRanges;
            let hiddenAreaStart = 1, hiddenAreaEnd = 0;
            let hiddenAreaIdx = -1;
            let nextLineNumberToUpdateHiddenArea = (hiddenAreaIdx + 1 < hiddenAreas.length) ? hiddenAreaEnd + 1 : this.modelLineProjections.length + 2;
            let hasVisibleLine = false;
            for (let i = 0; i < this.modelLineProjections.length; i++) {
                const lineNumber = i + 1;
                if (lineNumber === nextLineNumberToUpdateHiddenArea) {
                    hiddenAreaIdx++;
                    hiddenAreaStart = hiddenAreas[hiddenAreaIdx].startLineNumber;
                    hiddenAreaEnd = hiddenAreas[hiddenAreaIdx].endLineNumber;
                    nextLineNumberToUpdateHiddenArea = (hiddenAreaIdx + 1 < hiddenAreas.length) ? hiddenAreaEnd + 1 : this.modelLineProjections.length + 2;
                }
                let lineChanged = false;
                if (lineNumber >= hiddenAreaStart && lineNumber <= hiddenAreaEnd) {
                    // Line should be hidden
                    if (this.modelLineProjections[i].isVisible()) {
                        this.modelLineProjections[i] = this.modelLineProjections[i].setVisible(false);
                        lineChanged = true;
                    }
                }
                else {
                    hasVisibleLine = true;
                    // Line should be visible
                    if (!this.modelLineProjections[i].isVisible()) {
                        this.modelLineProjections[i] = this.modelLineProjections[i].setVisible(true);
                        lineChanged = true;
                    }
                }
                if (lineChanged) {
                    const newOutputLineCount = this.modelLineProjections[i].getViewLineCount();
                    this.projectedModelLineLineCounts.setValue(i, newOutputLineCount);
                }
            }
            if (!hasVisibleLine) {
                // Cannot have everything be hidden => reveal everything!
                this.setHiddenAreas([]);
            }
            return true;
        }
        modelPositionIsVisible(modelLineNumber, _modelColumn) {
            if (modelLineNumber < 1 || modelLineNumber > this.modelLineProjections.length) {
                // invalid arguments
                return false;
            }
            return this.modelLineProjections[modelLineNumber - 1].isVisible();
        }
        getModelLineViewLineCount(modelLineNumber) {
            if (modelLineNumber < 1 || modelLineNumber > this.modelLineProjections.length) {
                // invalid arguments
                return 1;
            }
            return this.modelLineProjections[modelLineNumber - 1].getViewLineCount();
        }
        setTabSize(newTabSize) {
            if (this.tabSize === newTabSize) {
                return false;
            }
            this.tabSize = newTabSize;
            this._constructLines(/*resetHiddenAreas*/ false, null);
            return true;
        }
        setWrappingSettings(fontInfo, wrappingStrategy, wrappingColumn, wrappingIndent, wordBreak) {
            const equalFontInfo = this.fontInfo.equals(fontInfo);
            const equalWrappingStrategy = (this.wrappingStrategy === wrappingStrategy);
            const equalWrappingColumn = (this.wrappingColumn === wrappingColumn);
            const equalWrappingIndent = (this.wrappingIndent === wrappingIndent);
            const equalWordBreak = (this.wordBreak === wordBreak);
            if (equalFontInfo && equalWrappingStrategy && equalWrappingColumn && equalWrappingIndent && equalWordBreak) {
                return false;
            }
            const onlyWrappingColumnChanged = (equalFontInfo && equalWrappingStrategy && !equalWrappingColumn && equalWrappingIndent && equalWordBreak);
            this.fontInfo = fontInfo;
            this.wrappingStrategy = wrappingStrategy;
            this.wrappingColumn = wrappingColumn;
            this.wrappingIndent = wrappingIndent;
            this.wordBreak = wordBreak;
            let previousLineBreaks = null;
            if (onlyWrappingColumnChanged) {
                previousLineBreaks = [];
                for (let i = 0, len = this.modelLineProjections.length; i < len; i++) {
                    previousLineBreaks[i] = this.modelLineProjections[i].getProjectionData();
                }
            }
            this._constructLines(/*resetHiddenAreas*/ false, previousLineBreaks);
            return true;
        }
        createLineBreaksComputer() {
            const lineBreaksComputerFactory = (this.wrappingStrategy === 'advanced'
                ? this._domLineBreaksComputerFactory
                : this._monospaceLineBreaksComputerFactory);
            return lineBreaksComputerFactory.createLineBreaksComputer(this.fontInfo, this.tabSize, this.wrappingColumn, this.wrappingIndent, this.wordBreak);
        }
        onModelFlushed() {
            this._constructLines(/*resetHiddenAreas*/ true, null);
        }
        onModelLinesDeleted(versionId, fromLineNumber, toLineNumber) {
            if (!versionId || versionId <= this._validModelVersionId) {
                // Here we check for versionId in case the lines were reconstructed in the meantime.
                // We don't want to apply stale change events on top of a newer read model state.
                return null;
            }
            const outputFromLineNumber = (fromLineNumber === 1 ? 1 : this.projectedModelLineLineCounts.getPrefixSum(fromLineNumber - 1) + 1);
            const outputToLineNumber = this.projectedModelLineLineCounts.getPrefixSum(toLineNumber);
            this.modelLineProjections.splice(fromLineNumber - 1, toLineNumber - fromLineNumber + 1);
            this.projectedModelLineLineCounts.removeValues(fromLineNumber - 1, toLineNumber - fromLineNumber + 1);
            return new viewEvents.ViewLinesDeletedEvent(outputFromLineNumber, outputToLineNumber);
        }
        onModelLinesInserted(versionId, fromLineNumber, _toLineNumber, lineBreaks) {
            if (!versionId || versionId <= this._validModelVersionId) {
                // Here we check for versionId in case the lines were reconstructed in the meantime.
                // We don't want to apply stale change events on top of a newer read model state.
                return null;
            }
            // cannot use this.getHiddenAreas() because those decorations have already seen the effect of this model change
            const isInHiddenArea = (fromLineNumber > 2 && !this.modelLineProjections[fromLineNumber - 2].isVisible());
            const outputFromLineNumber = (fromLineNumber === 1 ? 1 : this.projectedModelLineLineCounts.getPrefixSum(fromLineNumber - 1) + 1);
            let totalOutputLineCount = 0;
            const insertLines = [];
            const insertPrefixSumValues = [];
            for (let i = 0, len = lineBreaks.length; i < len; i++) {
                const line = (0, modelLineProjection_1.createModelLineProjection)(lineBreaks[i], !isInHiddenArea);
                insertLines.push(line);
                const outputLineCount = line.getViewLineCount();
                totalOutputLineCount += outputLineCount;
                insertPrefixSumValues[i] = outputLineCount;
            }
            // TODO@Alex: use arrays.arrayInsert
            this.modelLineProjections =
                this.modelLineProjections.slice(0, fromLineNumber - 1)
                    .concat(insertLines)
                    .concat(this.modelLineProjections.slice(fromLineNumber - 1));
            this.projectedModelLineLineCounts.insertValues(fromLineNumber - 1, insertPrefixSumValues);
            return new viewEvents.ViewLinesInsertedEvent(outputFromLineNumber, outputFromLineNumber + totalOutputLineCount - 1);
        }
        onModelLineChanged(versionId, lineNumber, lineBreakData) {
            if (versionId !== null && versionId <= this._validModelVersionId) {
                // Here we check for versionId in case the lines were reconstructed in the meantime.
                // We don't want to apply stale change events on top of a newer read model state.
                return [false, null, null, null];
            }
            const lineIndex = lineNumber - 1;
            const oldOutputLineCount = this.modelLineProjections[lineIndex].getViewLineCount();
            const isVisible = this.modelLineProjections[lineIndex].isVisible();
            const line = (0, modelLineProjection_1.createModelLineProjection)(lineBreakData, isVisible);
            this.modelLineProjections[lineIndex] = line;
            const newOutputLineCount = this.modelLineProjections[lineIndex].getViewLineCount();
            let lineMappingChanged = false;
            let changeFrom = 0;
            let changeTo = -1;
            let insertFrom = 0;
            let insertTo = -1;
            let deleteFrom = 0;
            let deleteTo = -1;
            if (oldOutputLineCount > newOutputLineCount) {
                changeFrom = this.projectedModelLineLineCounts.getPrefixSum(lineNumber - 1) + 1;
                changeTo = changeFrom + newOutputLineCount - 1;
                deleteFrom = changeTo + 1;
                deleteTo = deleteFrom + (oldOutputLineCount - newOutputLineCount) - 1;
                lineMappingChanged = true;
            }
            else if (oldOutputLineCount < newOutputLineCount) {
                changeFrom = this.projectedModelLineLineCounts.getPrefixSum(lineNumber - 1) + 1;
                changeTo = changeFrom + oldOutputLineCount - 1;
                insertFrom = changeTo + 1;
                insertTo = insertFrom + (newOutputLineCount - oldOutputLineCount) - 1;
                lineMappingChanged = true;
            }
            else {
                changeFrom = this.projectedModelLineLineCounts.getPrefixSum(lineNumber - 1) + 1;
                changeTo = changeFrom + newOutputLineCount - 1;
            }
            this.projectedModelLineLineCounts.setValue(lineIndex, newOutputLineCount);
            const viewLinesChangedEvent = (changeFrom <= changeTo ? new viewEvents.ViewLinesChangedEvent(changeFrom, changeTo - changeFrom + 1) : null);
            const viewLinesInsertedEvent = (insertFrom <= insertTo ? new viewEvents.ViewLinesInsertedEvent(insertFrom, insertTo) : null);
            const viewLinesDeletedEvent = (deleteFrom <= deleteTo ? new viewEvents.ViewLinesDeletedEvent(deleteFrom, deleteTo) : null);
            return [lineMappingChanged, viewLinesChangedEvent, viewLinesInsertedEvent, viewLinesDeletedEvent];
        }
        acceptVersionId(versionId) {
            this._validModelVersionId = versionId;
            if (this.modelLineProjections.length === 1 && !this.modelLineProjections[0].isVisible()) {
                // At least one line must be visible => reset hidden areas
                this.setHiddenAreas([]);
            }
        }
        getViewLineCount() {
            return this.projectedModelLineLineCounts.getTotalSum();
        }
        _toValidViewLineNumber(viewLineNumber) {
            if (viewLineNumber < 1) {
                return 1;
            }
            const viewLineCount = this.getViewLineCount();
            if (viewLineNumber > viewLineCount) {
                return viewLineCount;
            }
            return viewLineNumber | 0;
        }
        getActiveIndentGuide(viewLineNumber, minLineNumber, maxLineNumber) {
            viewLineNumber = this._toValidViewLineNumber(viewLineNumber);
            minLineNumber = this._toValidViewLineNumber(minLineNumber);
            maxLineNumber = this._toValidViewLineNumber(maxLineNumber);
            const modelPosition = this.convertViewPositionToModelPosition(viewLineNumber, this.getViewLineMinColumn(viewLineNumber));
            const modelMinPosition = this.convertViewPositionToModelPosition(minLineNumber, this.getViewLineMinColumn(minLineNumber));
            const modelMaxPosition = this.convertViewPositionToModelPosition(maxLineNumber, this.getViewLineMinColumn(maxLineNumber));
            const result = this.model.guides.getActiveIndentGuide(modelPosition.lineNumber, modelMinPosition.lineNumber, modelMaxPosition.lineNumber);
            const viewStartPosition = this.convertModelPositionToViewPosition(result.startLineNumber, 1);
            const viewEndPosition = this.convertModelPositionToViewPosition(result.endLineNumber, this.model.getLineMaxColumn(result.endLineNumber));
            return {
                startLineNumber: viewStartPosition.lineNumber,
                endLineNumber: viewEndPosition.lineNumber,
                indent: result.indent
            };
        }
        // #region ViewLineInfo
        getViewLineInfo(viewLineNumber) {
            viewLineNumber = this._toValidViewLineNumber(viewLineNumber);
            const r = this.projectedModelLineLineCounts.getIndexOf(viewLineNumber - 1);
            const lineIndex = r.index;
            const remainder = r.remainder;
            return new ViewLineInfo(lineIndex + 1, remainder);
        }
        getMinColumnOfViewLine(viewLineInfo) {
            return this.modelLineProjections[viewLineInfo.modelLineNumber - 1].getViewLineMinColumn(this.model, viewLineInfo.modelLineNumber, viewLineInfo.modelLineWrappedLineIdx);
        }
        getMaxColumnOfViewLine(viewLineInfo) {
            return this.modelLineProjections[viewLineInfo.modelLineNumber - 1].getViewLineMaxColumn(this.model, viewLineInfo.modelLineNumber, viewLineInfo.modelLineWrappedLineIdx);
        }
        getModelStartPositionOfViewLine(viewLineInfo) {
            const line = this.modelLineProjections[viewLineInfo.modelLineNumber - 1];
            const minViewColumn = line.getViewLineMinColumn(this.model, viewLineInfo.modelLineNumber, viewLineInfo.modelLineWrappedLineIdx);
            const column = line.getModelColumnOfViewPosition(viewLineInfo.modelLineWrappedLineIdx, minViewColumn);
            return new position_1.Position(viewLineInfo.modelLineNumber, column);
        }
        getModelEndPositionOfViewLine(viewLineInfo) {
            const line = this.modelLineProjections[viewLineInfo.modelLineNumber - 1];
            const maxViewColumn = line.getViewLineMaxColumn(this.model, viewLineInfo.modelLineNumber, viewLineInfo.modelLineWrappedLineIdx);
            const column = line.getModelColumnOfViewPosition(viewLineInfo.modelLineWrappedLineIdx, maxViewColumn);
            return new position_1.Position(viewLineInfo.modelLineNumber, column);
        }
        getViewLineInfosGroupedByModelRanges(viewStartLineNumber, viewEndLineNumber) {
            const startViewLine = this.getViewLineInfo(viewStartLineNumber);
            const endViewLine = this.getViewLineInfo(viewEndLineNumber);
            const result = new Array();
            let lastVisibleModelPos = this.getModelStartPositionOfViewLine(startViewLine);
            let viewLines = new Array();
            for (let curModelLine = startViewLine.modelLineNumber; curModelLine <= endViewLine.modelLineNumber; curModelLine++) {
                const line = this.modelLineProjections[curModelLine - 1];
                if (line.isVisible()) {
                    const startOffset = curModelLine === startViewLine.modelLineNumber
                        ? startViewLine.modelLineWrappedLineIdx
                        : 0;
                    const endOffset = curModelLine === endViewLine.modelLineNumber
                        ? endViewLine.modelLineWrappedLineIdx + 1
                        : line.getViewLineCount();
                    for (let i = startOffset; i < endOffset; i++) {
                        viewLines.push(new ViewLineInfo(curModelLine, i));
                    }
                }
                if (!line.isVisible() && lastVisibleModelPos) {
                    const lastVisibleModelPos2 = new position_1.Position(curModelLine - 1, this.model.getLineMaxColumn(curModelLine - 1) + 1);
                    const modelRange = range_1.Range.fromPositions(lastVisibleModelPos, lastVisibleModelPos2);
                    result.push(new ViewLineInfoGroupedByModelRange(modelRange, viewLines));
                    viewLines = [];
                    lastVisibleModelPos = null;
                }
                else if (line.isVisible() && !lastVisibleModelPos) {
                    lastVisibleModelPos = new position_1.Position(curModelLine, 1);
                }
            }
            if (lastVisibleModelPos) {
                const modelRange = range_1.Range.fromPositions(lastVisibleModelPos, this.getModelEndPositionOfViewLine(endViewLine));
                result.push(new ViewLineInfoGroupedByModelRange(modelRange, viewLines));
            }
            return result;
        }
        // #endregion
        getViewLinesBracketGuides(viewStartLineNumber, viewEndLineNumber, activeViewPosition, options) {
            const modelActivePosition = activeViewPosition ? this.convertViewPositionToModelPosition(activeViewPosition.lineNumber, activeViewPosition.column) : null;
            const resultPerViewLine = [];
            for (const group of this.getViewLineInfosGroupedByModelRanges(viewStartLineNumber, viewEndLineNumber)) {
                const modelRangeStartLineNumber = group.modelRange.startLineNumber;
                const bracketGuidesPerModelLine = this.model.guides.getLinesBracketGuides(modelRangeStartLineNumber, group.modelRange.endLineNumber, modelActivePosition, options);
                for (const viewLineInfo of group.viewLines) {
                    const bracketGuides = bracketGuidesPerModelLine[viewLineInfo.modelLineNumber - modelRangeStartLineNumber];
                    // visibleColumns stay as they are (this is a bug and needs to be fixed, but it is not a regression)
                    // model-columns must be converted to view-model columns.
                    const result = bracketGuides.map(g => {
                        if (g.forWrappedLinesAfterColumn !== -1) {
                            const p = this.modelLineProjections[viewLineInfo.modelLineNumber - 1].getViewPositionOfModelPosition(0, g.forWrappedLinesAfterColumn);
                            if (p.lineNumber >= viewLineInfo.modelLineWrappedLineIdx) {
                                return undefined;
                            }
                        }
                        if (g.forWrappedLinesBeforeOrAtColumn !== -1) {
                            const p = this.modelLineProjections[viewLineInfo.modelLineNumber - 1].getViewPositionOfModelPosition(0, g.forWrappedLinesBeforeOrAtColumn);
                            if (p.lineNumber < viewLineInfo.modelLineWrappedLineIdx) {
                                return undefined;
                            }
                        }
                        if (!g.horizontalLine) {
                            return g;
                        }
                        let column = -1;
                        if (g.column !== -1) {
                            const p = this.modelLineProjections[viewLineInfo.modelLineNumber - 1].getViewPositionOfModelPosition(0, g.column);
                            if (p.lineNumber === viewLineInfo.modelLineWrappedLineIdx) {
                                column = p.column;
                            }
                            else if (p.lineNumber < viewLineInfo.modelLineWrappedLineIdx) {
                                column = this.getMinColumnOfViewLine(viewLineInfo);
                            }
                            else if (p.lineNumber > viewLineInfo.modelLineWrappedLineIdx) {
                                return undefined;
                            }
                        }
                        const viewPosition = this.convertModelPositionToViewPosition(viewLineInfo.modelLineNumber, g.horizontalLine.endColumn);
                        const p = this.modelLineProjections[viewLineInfo.modelLineNumber - 1].getViewPositionOfModelPosition(0, g.horizontalLine.endColumn);
                        if (p.lineNumber === viewLineInfo.modelLineWrappedLineIdx) {
                            return new textModelGuides_1.IndentGuide(g.visibleColumn, column, g.className, new textModelGuides_1.IndentGuideHorizontalLine(g.horizontalLine.top, viewPosition.column), -1, -1);
                        }
                        else if (p.lineNumber < viewLineInfo.modelLineWrappedLineIdx) {
                            return undefined;
                        }
                        else {
                            if (g.visibleColumn !== -1) {
                                // Don't repeat horizontal lines that use visibleColumn for unrelated lines.
                                return undefined;
                            }
                            return new textModelGuides_1.IndentGuide(g.visibleColumn, column, g.className, new textModelGuides_1.IndentGuideHorizontalLine(g.horizontalLine.top, this.getMaxColumnOfViewLine(viewLineInfo)), -1, -1);
                        }
                    });
                    resultPerViewLine.push(result.filter((r) => !!r));
                }
            }
            return resultPerViewLine;
        }
        getViewLinesIndentGuides(viewStartLineNumber, viewEndLineNumber) {
            // TODO: Use the same code as in `getViewLinesBracketGuides`.
            // Future TODO: Merge with `getViewLinesBracketGuides`.
            // However, this requires more refactoring of indent guides.
            viewStartLineNumber = this._toValidViewLineNumber(viewStartLineNumber);
            viewEndLineNumber = this._toValidViewLineNumber(viewEndLineNumber);
            const modelStart = this.convertViewPositionToModelPosition(viewStartLineNumber, this.getViewLineMinColumn(viewStartLineNumber));
            const modelEnd = this.convertViewPositionToModelPosition(viewEndLineNumber, this.getViewLineMaxColumn(viewEndLineNumber));
            let result = [];
            const resultRepeatCount = [];
            const resultRepeatOption = [];
            const modelStartLineIndex = modelStart.lineNumber - 1;
            const modelEndLineIndex = modelEnd.lineNumber - 1;
            let reqStart = null;
            for (let modelLineIndex = modelStartLineIndex; modelLineIndex <= modelEndLineIndex; modelLineIndex++) {
                const line = this.modelLineProjections[modelLineIndex];
                if (line.isVisible()) {
                    const viewLineStartIndex = line.getViewLineNumberOfModelPosition(0, modelLineIndex === modelStartLineIndex ? modelStart.column : 1);
                    const viewLineEndIndex = line.getViewLineNumberOfModelPosition(0, this.model.getLineMaxColumn(modelLineIndex + 1));
                    const count = viewLineEndIndex - viewLineStartIndex + 1;
                    let option = 0 /* IndentGuideRepeatOption.BlockNone */;
                    if (count > 1 && line.getViewLineMinColumn(this.model, modelLineIndex + 1, viewLineEndIndex) === 1) {
                        // wrapped lines should block indent guides
                        option = (viewLineStartIndex === 0 ? 1 /* IndentGuideRepeatOption.BlockSubsequent */ : 2 /* IndentGuideRepeatOption.BlockAll */);
                    }
                    resultRepeatCount.push(count);
                    resultRepeatOption.push(option);
                    // merge into previous request
                    if (reqStart === null) {
                        reqStart = new position_1.Position(modelLineIndex + 1, 0);
                    }
                }
                else {
                    // hit invisible line => flush request
                    if (reqStart !== null) {
                        result = result.concat(this.model.guides.getLinesIndentGuides(reqStart.lineNumber, modelLineIndex));
                        reqStart = null;
                    }
                }
            }
            if (reqStart !== null) {
                result = result.concat(this.model.guides.getLinesIndentGuides(reqStart.lineNumber, modelEnd.lineNumber));
                reqStart = null;
            }
            const viewLineCount = viewEndLineNumber - viewStartLineNumber + 1;
            const viewIndents = new Array(viewLineCount);
            let currIndex = 0;
            for (let i = 0, len = result.length; i < len; i++) {
                let value = result[i];
                const count = Math.min(viewLineCount - currIndex, resultRepeatCount[i]);
                const option = resultRepeatOption[i];
                let blockAtIndex;
                if (option === 2 /* IndentGuideRepeatOption.BlockAll */) {
                    blockAtIndex = 0;
                }
                else if (option === 1 /* IndentGuideRepeatOption.BlockSubsequent */) {
                    blockAtIndex = 1;
                }
                else {
                    blockAtIndex = count;
                }
                for (let j = 0; j < count; j++) {
                    if (j === blockAtIndex) {
                        value = 0;
                    }
                    viewIndents[currIndex++] = value;
                }
            }
            return viewIndents;
        }
        getViewLineContent(viewLineNumber) {
            const info = this.getViewLineInfo(viewLineNumber);
            return this.modelLineProjections[info.modelLineNumber - 1].getViewLineContent(this.model, info.modelLineNumber, info.modelLineWrappedLineIdx);
        }
        getViewLineLength(viewLineNumber) {
            const info = this.getViewLineInfo(viewLineNumber);
            return this.modelLineProjections[info.modelLineNumber - 1].getViewLineLength(this.model, info.modelLineNumber, info.modelLineWrappedLineIdx);
        }
        getViewLineMinColumn(viewLineNumber) {
            const info = this.getViewLineInfo(viewLineNumber);
            return this.modelLineProjections[info.modelLineNumber - 1].getViewLineMinColumn(this.model, info.modelLineNumber, info.modelLineWrappedLineIdx);
        }
        getViewLineMaxColumn(viewLineNumber) {
            const info = this.getViewLineInfo(viewLineNumber);
            return this.modelLineProjections[info.modelLineNumber - 1].getViewLineMaxColumn(this.model, info.modelLineNumber, info.modelLineWrappedLineIdx);
        }
        getViewLineData(viewLineNumber) {
            const info = this.getViewLineInfo(viewLineNumber);
            return this.modelLineProjections[info.modelLineNumber - 1].getViewLineData(this.model, info.modelLineNumber, info.modelLineWrappedLineIdx);
        }
        getViewLinesData(viewStartLineNumber, viewEndLineNumber, needed) {
            viewStartLineNumber = this._toValidViewLineNumber(viewStartLineNumber);
            viewEndLineNumber = this._toValidViewLineNumber(viewEndLineNumber);
            const start = this.projectedModelLineLineCounts.getIndexOf(viewStartLineNumber - 1);
            let viewLineNumber = viewStartLineNumber;
            const startModelLineIndex = start.index;
            const startRemainder = start.remainder;
            const result = [];
            for (let modelLineIndex = startModelLineIndex, len = this.model.getLineCount(); modelLineIndex < len; modelLineIndex++) {
                const line = this.modelLineProjections[modelLineIndex];
                if (!line.isVisible()) {
                    continue;
                }
                const fromViewLineIndex = (modelLineIndex === startModelLineIndex ? startRemainder : 0);
                let remainingViewLineCount = line.getViewLineCount() - fromViewLineIndex;
                let lastLine = false;
                if (viewLineNumber + remainingViewLineCount > viewEndLineNumber) {
                    lastLine = true;
                    remainingViewLineCount = viewEndLineNumber - viewLineNumber + 1;
                }
                line.getViewLinesData(this.model, modelLineIndex + 1, fromViewLineIndex, remainingViewLineCount, viewLineNumber - viewStartLineNumber, needed, result);
                viewLineNumber += remainingViewLineCount;
                if (lastLine) {
                    break;
                }
            }
            return result;
        }
        validateViewPosition(viewLineNumber, viewColumn, expectedModelPosition) {
            viewLineNumber = this._toValidViewLineNumber(viewLineNumber);
            const r = this.projectedModelLineLineCounts.getIndexOf(viewLineNumber - 1);
            const lineIndex = r.index;
            const remainder = r.remainder;
            const line = this.modelLineProjections[lineIndex];
            const minColumn = line.getViewLineMinColumn(this.model, lineIndex + 1, remainder);
            const maxColumn = line.getViewLineMaxColumn(this.model, lineIndex + 1, remainder);
            if (viewColumn < minColumn) {
                viewColumn = minColumn;
            }
            if (viewColumn > maxColumn) {
                viewColumn = maxColumn;
            }
            const computedModelColumn = line.getModelColumnOfViewPosition(remainder, viewColumn);
            const computedModelPosition = this.model.validatePosition(new position_1.Position(lineIndex + 1, computedModelColumn));
            if (computedModelPosition.equals(expectedModelPosition)) {
                return new position_1.Position(viewLineNumber, viewColumn);
            }
            return this.convertModelPositionToViewPosition(expectedModelPosition.lineNumber, expectedModelPosition.column);
        }
        validateViewRange(viewRange, expectedModelRange) {
            const validViewStart = this.validateViewPosition(viewRange.startLineNumber, viewRange.startColumn, expectedModelRange.getStartPosition());
            const validViewEnd = this.validateViewPosition(viewRange.endLineNumber, viewRange.endColumn, expectedModelRange.getEndPosition());
            return new range_1.Range(validViewStart.lineNumber, validViewStart.column, validViewEnd.lineNumber, validViewEnd.column);
        }
        convertViewPositionToModelPosition(viewLineNumber, viewColumn) {
            const info = this.getViewLineInfo(viewLineNumber);
            const inputColumn = this.modelLineProjections[info.modelLineNumber - 1].getModelColumnOfViewPosition(info.modelLineWrappedLineIdx, viewColumn);
            // console.log('out -> in ' + viewLineNumber + ',' + viewColumn + ' ===> ' + (lineIndex+1) + ',' + inputColumn);
            return this.model.validatePosition(new position_1.Position(info.modelLineNumber, inputColumn));
        }
        convertViewRangeToModelRange(viewRange) {
            const start = this.convertViewPositionToModelPosition(viewRange.startLineNumber, viewRange.startColumn);
            const end = this.convertViewPositionToModelPosition(viewRange.endLineNumber, viewRange.endColumn);
            return new range_1.Range(start.lineNumber, start.column, end.lineNumber, end.column);
        }
        convertModelPositionToViewPosition(_modelLineNumber, _modelColumn, affinity = 2 /* PositionAffinity.None */, allowZeroLineNumber = false, belowHiddenRanges = false) {
            const validPosition = this.model.validatePosition(new position_1.Position(_modelLineNumber, _modelColumn));
            const inputLineNumber = validPosition.lineNumber;
            const inputColumn = validPosition.column;
            let lineIndex = inputLineNumber - 1, lineIndexChanged = false;
            if (belowHiddenRanges) {
                while (lineIndex < this.modelLineProjections.length && !this.modelLineProjections[lineIndex].isVisible()) {
                    lineIndex++;
                    lineIndexChanged = true;
                }
            }
            else {
                while (lineIndex > 0 && !this.modelLineProjections[lineIndex].isVisible()) {
                    lineIndex--;
                    lineIndexChanged = true;
                }
            }
            if (lineIndex === 0 && !this.modelLineProjections[lineIndex].isVisible()) {
                // Could not reach a real line
                // console.log('in -> out ' + inputLineNumber + ',' + inputColumn + ' ===> ' + 1 + ',' + 1);
                // TODO@alexdima@hediet this isn't soo pretty
                return new position_1.Position(allowZeroLineNumber ? 0 : 1, 1);
            }
            const deltaLineNumber = 1 + this.projectedModelLineLineCounts.getPrefixSum(lineIndex);
            let r;
            if (lineIndexChanged) {
                if (belowHiddenRanges) {
                    r = this.modelLineProjections[lineIndex].getViewPositionOfModelPosition(deltaLineNumber, 1, affinity);
                }
                else {
                    r = this.modelLineProjections[lineIndex].getViewPositionOfModelPosition(deltaLineNumber, this.model.getLineMaxColumn(lineIndex + 1), affinity);
                }
            }
            else {
                r = this.modelLineProjections[inputLineNumber - 1].getViewPositionOfModelPosition(deltaLineNumber, inputColumn, affinity);
            }
            // console.log('in -> out ' + inputLineNumber + ',' + inputColumn + ' ===> ' + r.lineNumber + ',' + r);
            return r;
        }
        /**
         * @param affinity The affinity in case of an empty range. Has no effect for non-empty ranges.
        */
        convertModelRangeToViewRange(modelRange, affinity = 0 /* PositionAffinity.Left */) {
            if (modelRange.isEmpty()) {
                const start = this.convertModelPositionToViewPosition(modelRange.startLineNumber, modelRange.startColumn, affinity);
                return range_1.Range.fromPositions(start);
            }
            else {
                const start = this.convertModelPositionToViewPosition(modelRange.startLineNumber, modelRange.startColumn, 1 /* PositionAffinity.Right */);
                const end = this.convertModelPositionToViewPosition(modelRange.endLineNumber, modelRange.endColumn, 0 /* PositionAffinity.Left */);
                return new range_1.Range(start.lineNumber, start.column, end.lineNumber, end.column);
            }
        }
        getViewLineNumberOfModelPosition(modelLineNumber, modelColumn) {
            let lineIndex = modelLineNumber - 1;
            if (this.modelLineProjections[lineIndex].isVisible()) {
                // this model line is visible
                const deltaLineNumber = 1 + this.projectedModelLineLineCounts.getPrefixSum(lineIndex);
                return this.modelLineProjections[lineIndex].getViewLineNumberOfModelPosition(deltaLineNumber, modelColumn);
            }
            // this model line is not visible
            while (lineIndex > 0 && !this.modelLineProjections[lineIndex].isVisible()) {
                lineIndex--;
            }
            if (lineIndex === 0 && !this.modelLineProjections[lineIndex].isVisible()) {
                // Could not reach a real line
                return 1;
            }
            const deltaLineNumber = 1 + this.projectedModelLineLineCounts.getPrefixSum(lineIndex);
            return this.modelLineProjections[lineIndex].getViewLineNumberOfModelPosition(deltaLineNumber, this.model.getLineMaxColumn(lineIndex + 1));
        }
        getDecorationsInRange(range, ownerId, filterOutValidation, onlyMinimapDecorations, onlyMarginDecorations) {
            const modelStart = this.convertViewPositionToModelPosition(range.startLineNumber, range.startColumn);
            const modelEnd = this.convertViewPositionToModelPosition(range.endLineNumber, range.endColumn);
            if (modelEnd.lineNumber - modelStart.lineNumber <= range.endLineNumber - range.startLineNumber) {
                // most likely there are no hidden lines => fast path
                // fetch decorations from column 1 to cover the case of wrapped lines that have whole line decorations at column 1
                return this.model.getDecorationsInRange(new range_1.Range(modelStart.lineNumber, 1, modelEnd.lineNumber, modelEnd.column), ownerId, filterOutValidation, onlyMinimapDecorations, onlyMarginDecorations);
            }
            let result = [];
            const modelStartLineIndex = modelStart.lineNumber - 1;
            const modelEndLineIndex = modelEnd.lineNumber - 1;
            let reqStart = null;
            for (let modelLineIndex = modelStartLineIndex; modelLineIndex <= modelEndLineIndex; modelLineIndex++) {
                const line = this.modelLineProjections[modelLineIndex];
                if (line.isVisible()) {
                    // merge into previous request
                    if (reqStart === null) {
                        reqStart = new position_1.Position(modelLineIndex + 1, modelLineIndex === modelStartLineIndex ? modelStart.column : 1);
                    }
                }
                else {
                    // hit invisible line => flush request
                    if (reqStart !== null) {
                        const maxLineColumn = this.model.getLineMaxColumn(modelLineIndex);
                        result = result.concat(this.model.getDecorationsInRange(new range_1.Range(reqStart.lineNumber, reqStart.column, modelLineIndex, maxLineColumn), ownerId, filterOutValidation, onlyMinimapDecorations));
                        reqStart = null;
                    }
                }
            }
            if (reqStart !== null) {
                result = result.concat(this.model.getDecorationsInRange(new range_1.Range(reqStart.lineNumber, reqStart.column, modelEnd.lineNumber, modelEnd.column), ownerId, filterOutValidation, onlyMinimapDecorations));
                reqStart = null;
            }
            result.sort((a, b) => {
                const res = range_1.Range.compareRangesUsingStarts(a.range, b.range);
                if (res === 0) {
                    if (a.id < b.id) {
                        return -1;
                    }
                    if (a.id > b.id) {
                        return 1;
                    }
                    return 0;
                }
                return res;
            });
            // Eliminate duplicate decorations that might have intersected our visible ranges multiple times
            const finalResult = [];
            let finalResultLen = 0;
            let prevDecId = null;
            for (const dec of result) {
                const decId = dec.id;
                if (prevDecId === decId) {
                    // skip
                    continue;
                }
                prevDecId = decId;
                finalResult[finalResultLen++] = dec;
            }
            return finalResult;
        }
        getInjectedTextAt(position) {
            const info = this.getViewLineInfo(position.lineNumber);
            return this.modelLineProjections[info.modelLineNumber - 1].getInjectedTextAt(info.modelLineWrappedLineIdx, position.column);
        }
        normalizePosition(position, affinity) {
            const info = this.getViewLineInfo(position.lineNumber);
            return this.modelLineProjections[info.modelLineNumber - 1].normalizePosition(info.modelLineWrappedLineIdx, position, affinity);
        }
        getLineIndentColumn(lineNumber) {
            const info = this.getViewLineInfo(lineNumber);
            if (info.modelLineWrappedLineIdx === 0) {
                return this.model.getLineIndentColumn(info.modelLineNumber);
            }
            // wrapped lines have no indentation.
            // We deliberately don't handle the case that indentation is wrapped
            // to avoid two view lines reporting indentation for the very same model line.
            return 0;
        }
    }
    exports.ViewModelLinesFromProjectedModel = ViewModelLinesFromProjectedModel;
    /**
     * Overlapping unsorted ranges:
     * [   )      [ )       [  )
     *    [    )      [       )
     * ->
     * Non overlapping sorted ranges:
     * [       )  [ ) [        )
     *
     * Note: This function only considers line information! Columns are ignored.
    */
    function normalizeLineRanges(ranges) {
        if (ranges.length === 0) {
            return [];
        }
        const sortedRanges = ranges.slice();
        sortedRanges.sort(range_1.Range.compareRangesUsingStarts);
        const result = [];
        let currentRangeStart = sortedRanges[0].startLineNumber;
        let currentRangeEnd = sortedRanges[0].endLineNumber;
        for (let i = 1, len = sortedRanges.length; i < len; i++) {
            const range = sortedRanges[i];
            if (range.startLineNumber > currentRangeEnd + 1) {
                result.push(new range_1.Range(currentRangeStart, 1, currentRangeEnd, 1));
                currentRangeStart = range.startLineNumber;
                currentRangeEnd = range.endLineNumber;
            }
            else if (range.endLineNumber > currentRangeEnd) {
                currentRangeEnd = range.endLineNumber;
            }
        }
        result.push(new range_1.Range(currentRangeStart, 1, currentRangeEnd, 1));
        return result;
    }
    /**
     * Represents a view line. Can be used to efficiently query more information about it.
     */
    class ViewLineInfo {
        constructor(modelLineNumber, modelLineWrappedLineIdx) {
            this.modelLineNumber = modelLineNumber;
            this.modelLineWrappedLineIdx = modelLineWrappedLineIdx;
        }
    }
    /**
     * A list of view lines that have a contiguous span in the model.
    */
    class ViewLineInfoGroupedByModelRange {
        constructor(modelRange, viewLines) {
            this.modelRange = modelRange;
            this.viewLines = viewLines;
        }
    }
    class CoordinatesConverter {
        constructor(lines) {
            this._lines = lines;
        }
        // View -> Model conversion and related methods
        convertViewPositionToModelPosition(viewPosition) {
            return this._lines.convertViewPositionToModelPosition(viewPosition.lineNumber, viewPosition.column);
        }
        convertViewRangeToModelRange(viewRange) {
            return this._lines.convertViewRangeToModelRange(viewRange);
        }
        validateViewPosition(viewPosition, expectedModelPosition) {
            return this._lines.validateViewPosition(viewPosition.lineNumber, viewPosition.column, expectedModelPosition);
        }
        validateViewRange(viewRange, expectedModelRange) {
            return this._lines.validateViewRange(viewRange, expectedModelRange);
        }
        // Model -> View conversion and related methods
        convertModelPositionToViewPosition(modelPosition, affinity, allowZero, belowHiddenRanges) {
            return this._lines.convertModelPositionToViewPosition(modelPosition.lineNumber, modelPosition.column, affinity, allowZero, belowHiddenRanges);
        }
        convertModelRangeToViewRange(modelRange, affinity) {
            return this._lines.convertModelRangeToViewRange(modelRange, affinity);
        }
        modelPositionIsVisible(modelPosition) {
            return this._lines.modelPositionIsVisible(modelPosition.lineNumber, modelPosition.column);
        }
        getModelLineViewLineCount(modelLineNumber) {
            return this._lines.getModelLineViewLineCount(modelLineNumber);
        }
        getViewLineNumberOfModelPosition(modelLineNumber, modelColumn) {
            return this._lines.getViewLineNumberOfModelPosition(modelLineNumber, modelColumn);
        }
    }
    class ViewModelLinesFromModelAsIs {
        constructor(model) {
            this.model = model;
        }
        dispose() {
        }
        createCoordinatesConverter() {
            return new IdentityCoordinatesConverter(this);
        }
        getHiddenAreas() {
            return [];
        }
        setHiddenAreas(_ranges) {
            return false;
        }
        setTabSize(_newTabSize) {
            return false;
        }
        setWrappingSettings(_fontInfo, _wrappingStrategy, _wrappingColumn, _wrappingIndent) {
            return false;
        }
        createLineBreaksComputer() {
            const result = [];
            return {
                addRequest: (lineText, injectedText, previousLineBreakData) => {
                    result.push(null);
                },
                finalize: () => {
                    return result;
                }
            };
        }
        onModelFlushed() {
        }
        onModelLinesDeleted(_versionId, fromLineNumber, toLineNumber) {
            return new viewEvents.ViewLinesDeletedEvent(fromLineNumber, toLineNumber);
        }
        onModelLinesInserted(_versionId, fromLineNumber, toLineNumber, lineBreaks) {
            return new viewEvents.ViewLinesInsertedEvent(fromLineNumber, toLineNumber);
        }
        onModelLineChanged(_versionId, lineNumber, lineBreakData) {
            return [false, new viewEvents.ViewLinesChangedEvent(lineNumber, 1), null, null];
        }
        acceptVersionId(_versionId) {
        }
        getViewLineCount() {
            return this.model.getLineCount();
        }
        getActiveIndentGuide(viewLineNumber, _minLineNumber, _maxLineNumber) {
            return {
                startLineNumber: viewLineNumber,
                endLineNumber: viewLineNumber,
                indent: 0
            };
        }
        getViewLinesBracketGuides(startLineNumber, endLineNumber, activePosition) {
            return new Array(endLineNumber - startLineNumber + 1).fill([]);
        }
        getViewLinesIndentGuides(viewStartLineNumber, viewEndLineNumber) {
            const viewLineCount = viewEndLineNumber - viewStartLineNumber + 1;
            const result = new Array(viewLineCount);
            for (let i = 0; i < viewLineCount; i++) {
                result[i] = 0;
            }
            return result;
        }
        getViewLineContent(viewLineNumber) {
            return this.model.getLineContent(viewLineNumber);
        }
        getViewLineLength(viewLineNumber) {
            return this.model.getLineLength(viewLineNumber);
        }
        getViewLineMinColumn(viewLineNumber) {
            return this.model.getLineMinColumn(viewLineNumber);
        }
        getViewLineMaxColumn(viewLineNumber) {
            return this.model.getLineMaxColumn(viewLineNumber);
        }
        getViewLineData(viewLineNumber) {
            const lineTokens = this.model.tokenization.getLineTokens(viewLineNumber);
            const lineContent = lineTokens.getLineContent();
            return new viewModel_1.ViewLineData(lineContent, false, 1, lineContent.length + 1, 0, lineTokens.inflate(), null);
        }
        getViewLinesData(viewStartLineNumber, viewEndLineNumber, needed) {
            const lineCount = this.model.getLineCount();
            viewStartLineNumber = Math.min(Math.max(1, viewStartLineNumber), lineCount);
            viewEndLineNumber = Math.min(Math.max(1, viewEndLineNumber), lineCount);
            const result = [];
            for (let lineNumber = viewStartLineNumber; lineNumber <= viewEndLineNumber; lineNumber++) {
                const idx = lineNumber - viewStartLineNumber;
                result[idx] = needed[idx] ? this.getViewLineData(lineNumber) : null;
            }
            return result;
        }
        getDecorationsInRange(range, ownerId, filterOutValidation, onlyMinimapDecorations, onlyMarginDecorations) {
            return this.model.getDecorationsInRange(range, ownerId, filterOutValidation, onlyMinimapDecorations, onlyMarginDecorations);
        }
        normalizePosition(position, affinity) {
            return this.model.normalizePosition(position, affinity);
        }
        getLineIndentColumn(lineNumber) {
            return this.model.getLineIndentColumn(lineNumber);
        }
        getInjectedTextAt(position) {
            // Identity lines collection does not support injected text.
            return null;
        }
    }
    exports.ViewModelLinesFromModelAsIs = ViewModelLinesFromModelAsIs;
    class IdentityCoordinatesConverter {
        constructor(lines) {
            this._lines = lines;
        }
        _validPosition(pos) {
            return this._lines.model.validatePosition(pos);
        }
        _validRange(range) {
            return this._lines.model.validateRange(range);
        }
        // View -> Model conversion and related methods
        convertViewPositionToModelPosition(viewPosition) {
            return this._validPosition(viewPosition);
        }
        convertViewRangeToModelRange(viewRange) {
            return this._validRange(viewRange);
        }
        validateViewPosition(_viewPosition, expectedModelPosition) {
            return this._validPosition(expectedModelPosition);
        }
        validateViewRange(_viewRange, expectedModelRange) {
            return this._validRange(expectedModelRange);
        }
        // Model -> View conversion and related methods
        convertModelPositionToViewPosition(modelPosition) {
            return this._validPosition(modelPosition);
        }
        convertModelRangeToViewRange(modelRange) {
            return this._validRange(modelRange);
        }
        modelPositionIsVisible(modelPosition) {
            const lineCount = this._lines.model.getLineCount();
            if (modelPosition.lineNumber < 1 || modelPosition.lineNumber > lineCount) {
                // invalid arguments
                return false;
            }
            return true;
        }
        getModelLineViewLineCount(modelLineNumber) {
            return 1;
        }
        getViewLineNumberOfModelPosition(modelLineNumber, modelColumn) {
            return modelLineNumber;
        }
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[810/*vs/editor/common/viewModel/viewModelImpl*/], __M([1/*require*/,0/*exports*/,13/*vs/base/common/arrays*/,14/*vs/base/common/async*/,33/*vs/base/common/color*/,2/*vs/base/common/lifecycle*/,16/*vs/base/common/platform*/,11/*vs/base/common/strings*/,37/*vs/editor/common/config/editorOptions*/,706/*vs/editor/common/cursor/cursor*/,76/*vs/editor/common/cursorCommon*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/,132/*vs/editor/common/textModelEvents*/,27/*vs/editor/common/languages*/,70/*vs/editor/common/languages/modesRegistry*/,369/*vs/editor/common/languages/textToHtmlTokenizer*/,243/*vs/editor/common/viewEvents*/,606/*vs/editor/common/viewLayout/viewLayout*/,374/*vs/editor/common/viewModel/minimapTokensColorTracker*/,95/*vs/editor/common/viewModel*/,375/*vs/editor/common/viewModel/viewModelDecorations*/,244/*vs/editor/common/viewModelEventDispatcher*/,809/*vs/editor/common/viewModel/viewModelLines*/,601/*vs/editor/common/viewModel/glyphLanesModel*/]), function (require, exports, arrays_1, async_1, color_1, lifecycle_1, platform, strings, editorOptions_1, cursor_1, cursorCommon_1, position_1, range_1, textModelEvents, languages_1, modesRegistry_1, textToHtmlTokenizer_1, viewEvents, viewLayout_1, minimapTokensColorTracker_1, viewModel_1, viewModelDecorations_1, viewModelEventDispatcher_1, viewModelLines_1, glyphLanesModel_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ViewModel = void 0;
    const USE_IDENTITY_LINES_COLLECTION = true;
    class ViewModel extends lifecycle_1.Disposable {
        constructor(editorId, configuration, model, domLineBreaksComputerFactory, monospaceLineBreaksComputerFactory, scheduleAtNextAnimationFrame, languageConfigurationService, _themeService, _attachedView, _transactionalTarget) {
            super();
            this.languageConfigurationService = languageConfigurationService;
            this._themeService = _themeService;
            this._attachedView = _attachedView;
            this._transactionalTarget = _transactionalTarget;
            this.hiddenAreasModel = new HiddenAreasModel();
            this.previousHiddenAreas = [];
            this._editorId = editorId;
            this._configuration = configuration;
            this.model = model;
            this._eventDispatcher = new viewModelEventDispatcher_1.ViewModelEventDispatcher();
            this.onEvent = this._eventDispatcher.onEvent;
            this.cursorConfig = new cursorCommon_1.CursorConfiguration(this.model.getLanguageId(), this.model.getOptions(), this._configuration, this.languageConfigurationService);
            this._updateConfigurationViewLineCount = this._register(new async_1.RunOnceScheduler(() => this._updateConfigurationViewLineCountNow(), 0));
            this._hasFocus = false;
            this._viewportStart = ViewportStart.create(this.model);
            this.glyphLanes = new glyphLanesModel_1.GlyphMarginLanesModel(0);
            if (USE_IDENTITY_LINES_COLLECTION && this.model.isTooLargeForTokenization()) {
                this._lines = new viewModelLines_1.ViewModelLinesFromModelAsIs(this.model);
            }
            else {
                const options = this._configuration.options;
                const fontInfo = options.get(50 /* EditorOption.fontInfo */);
                const wrappingStrategy = options.get(140 /* EditorOption.wrappingStrategy */);
                const wrappingInfo = options.get(147 /* EditorOption.wrappingInfo */);
                const wrappingIndent = options.get(139 /* EditorOption.wrappingIndent */);
                const wordBreak = options.get(130 /* EditorOption.wordBreak */);
                this._lines = new viewModelLines_1.ViewModelLinesFromProjectedModel(this._editorId, this.model, domLineBreaksComputerFactory, monospaceLineBreaksComputerFactory, fontInfo, this.model.getOptions().tabSize, wrappingStrategy, wrappingInfo.wrappingColumn, wrappingIndent, wordBreak);
            }
            this.coordinatesConverter = this._lines.createCoordinatesConverter();
            this._cursor = this._register(new cursor_1.CursorsController(model, this, this.coordinatesConverter, this.cursorConfig));
            this.viewLayout = this._register(new viewLayout_1.ViewLayout(this._configuration, this.getLineCount(), scheduleAtNextAnimationFrame));
            this._register(this.viewLayout.onDidScroll((e) => {
                if (e.scrollTopChanged) {
                    this._handleVisibleLinesChanged();
                }
                if (e.scrollTopChanged) {
                    this._viewportStart.invalidate();
                }
                this._eventDispatcher.emitSingleViewEvent(new viewEvents.ViewScrollChangedEvent(e));
                this._eventDispatcher.emitOutgoingEvent(new viewModelEventDispatcher_1.ScrollChangedEvent(e.oldScrollWidth, e.oldScrollLeft, e.oldScrollHeight, e.oldScrollTop, e.scrollWidth, e.scrollLeft, e.scrollHeight, e.scrollTop));
            }));
            this._register(this.viewLayout.onDidContentSizeChange((e) => {
                this._eventDispatcher.emitOutgoingEvent(e);
            }));
            this._decorations = new viewModelDecorations_1.ViewModelDecorations(this._editorId, this.model, this._configuration, this._lines, this.coordinatesConverter);
            this._registerModelEvents();
            this._register(this._configuration.onDidChangeFast((e) => {
                try {
                    const eventsCollector = this._eventDispatcher.beginEmitViewEvents();
                    this._onConfigurationChanged(eventsCollector, e);
                }
                finally {
                    this._eventDispatcher.endEmitViewEvents();
                }
            }));
            this._register(minimapTokensColorTracker_1.MinimapTokensColorTracker.getInstance().onDidChange(() => {
                this._eventDispatcher.emitSingleViewEvent(new viewEvents.ViewTokensColorsChangedEvent());
            }));
            this._register(this._themeService.onDidColorThemeChange((theme) => {
                this._invalidateDecorationsColorCache();
                this._eventDispatcher.emitSingleViewEvent(new viewEvents.ViewThemeChangedEvent(theme));
            }));
            this._updateConfigurationViewLineCountNow();
        }
        dispose() {
            // First remove listeners, as disposing the lines might end up sending
            // model decoration changed events ... and we no longer care about them ...
            super.dispose();
            this._decorations.dispose();
            this._lines.dispose();
            this._viewportStart.dispose();
            this._eventDispatcher.dispose();
        }
        createLineBreaksComputer() {
            return this._lines.createLineBreaksComputer();
        }
        addViewEventHandler(eventHandler) {
            this._eventDispatcher.addViewEventHandler(eventHandler);
        }
        removeViewEventHandler(eventHandler) {
            this._eventDispatcher.removeViewEventHandler(eventHandler);
        }
        _updateConfigurationViewLineCountNow() {
            this._configuration.setViewLineCount(this._lines.getViewLineCount());
        }
        getModelVisibleRanges() {
            const linesViewportData = this.viewLayout.getLinesViewportData();
            const viewVisibleRange = new range_1.Range(linesViewportData.startLineNumber, this.getLineMinColumn(linesViewportData.startLineNumber), linesViewportData.endLineNumber, this.getLineMaxColumn(linesViewportData.endLineNumber));
            const modelVisibleRanges = this._toModelVisibleRanges(viewVisibleRange);
            return modelVisibleRanges;
        }
        visibleLinesStabilized() {
            const modelVisibleRanges = this.getModelVisibleRanges();
            this._attachedView.setVisibleLines(modelVisibleRanges, true);
        }
        _handleVisibleLinesChanged() {
            const modelVisibleRanges = this.getModelVisibleRanges();
            this._attachedView.setVisibleLines(modelVisibleRanges, false);
        }
        setHasFocus(hasFocus) {
            this._hasFocus = hasFocus;
            this._cursor.setHasFocus(hasFocus);
            this._eventDispatcher.emitSingleViewEvent(new viewEvents.ViewFocusChangedEvent(hasFocus));
            this._eventDispatcher.emitOutgoingEvent(new viewModelEventDispatcher_1.FocusChangedEvent(!hasFocus, hasFocus));
        }
        onCompositionStart() {
            this._eventDispatcher.emitSingleViewEvent(new viewEvents.ViewCompositionStartEvent());
        }
        onCompositionEnd() {
            this._eventDispatcher.emitSingleViewEvent(new viewEvents.ViewCompositionEndEvent());
        }
        _captureStableViewport() {
            // We might need to restore the current start view range, so save it (if available)
            // But only if the scroll position is not at the top of the file
            if (this._viewportStart.isValid && this.viewLayout.getCurrentScrollTop() > 0) {
                const previousViewportStartViewPosition = new position_1.Position(this._viewportStart.viewLineNumber, this.getLineMinColumn(this._viewportStart.viewLineNumber));
                const previousViewportStartModelPosition = this.coordinatesConverter.convertViewPositionToModelPosition(previousViewportStartViewPosition);
                return new StableViewport(previousViewportStartModelPosition, this._viewportStart.startLineDelta);
            }
            return new StableViewport(null, 0);
        }
        _onConfigurationChanged(eventsCollector, e) {
            const stableViewport = this._captureStableViewport();
            const options = this._configuration.options;
            const fontInfo = options.get(50 /* EditorOption.fontInfo */);
            const wrappingStrategy = options.get(140 /* EditorOption.wrappingStrategy */);
            const wrappingInfo = options.get(147 /* EditorOption.wrappingInfo */);
            const wrappingIndent = options.get(139 /* EditorOption.wrappingIndent */);
            const wordBreak = options.get(130 /* EditorOption.wordBreak */);
            if (this._lines.setWrappingSettings(fontInfo, wrappingStrategy, wrappingInfo.wrappingColumn, wrappingIndent, wordBreak)) {
                eventsCollector.emitViewEvent(new viewEvents.ViewFlushedEvent());
                eventsCollector.emitViewEvent(new viewEvents.ViewLineMappingChangedEvent());
                eventsCollector.emitViewEvent(new viewEvents.ViewDecorationsChangedEvent(null));
                this._cursor.onLineMappingChanged(eventsCollector);
                this._decorations.onLineMappingChanged();
                this.viewLayout.onFlushed(this.getLineCount());
                this._updateConfigurationViewLineCount.schedule();
            }
            if (e.hasChanged(92 /* EditorOption.readOnly */)) {
                // Must read again all decorations due to readOnly filtering
                this._decorations.reset();
                eventsCollector.emitViewEvent(new viewEvents.ViewDecorationsChangedEvent(null));
            }
            if (e.hasChanged(99 /* EditorOption.renderValidationDecorations */)) {
                this._decorations.reset();
                eventsCollector.emitViewEvent(new viewEvents.ViewDecorationsChangedEvent(null));
            }
            eventsCollector.emitViewEvent(new viewEvents.ViewConfigurationChangedEvent(e));
            this.viewLayout.onConfigurationChanged(e);
            stableViewport.recoverViewportStart(this.coordinatesConverter, this.viewLayout);
            if (cursorCommon_1.CursorConfiguration.shouldRecreate(e)) {
                this.cursorConfig = new cursorCommon_1.CursorConfiguration(this.model.getLanguageId(), this.model.getOptions(), this._configuration, this.languageConfigurationService);
                this._cursor.updateConfiguration(this.cursorConfig);
            }
        }
        _registerModelEvents() {
            this._register(this.model.onDidChangeContentOrInjectedText((e) => {
                try {
                    const eventsCollector = this._eventDispatcher.beginEmitViewEvents();
                    let hadOtherModelChange = false;
                    let hadModelLineChangeThatChangedLineMapping = false;
                    const changes = (e instanceof textModelEvents.InternalModelContentChangeEvent ? e.rawContentChangedEvent.changes : e.changes);
                    const versionId = (e instanceof textModelEvents.InternalModelContentChangeEvent ? e.rawContentChangedEvent.versionId : null);
                    // Do a first pass to compute line mappings, and a second pass to actually interpret them
                    const lineBreaksComputer = this._lines.createLineBreaksComputer();
                    for (const change of changes) {
                        switch (change.changeType) {
                            case 4 /* textModelEvents.RawContentChangedType.LinesInserted */: {
                                for (let lineIdx = 0; lineIdx < change.detail.length; lineIdx++) {
                                    const line = change.detail[lineIdx];
                                    let injectedText = change.injectedTexts[lineIdx];
                                    if (injectedText) {
                                        injectedText = injectedText.filter(element => (!element.ownerId || element.ownerId === this._editorId));
                                    }
                                    lineBreaksComputer.addRequest(line, injectedText, null);
                                }
                                break;
                            }
                            case 2 /* textModelEvents.RawContentChangedType.LineChanged */: {
                                let injectedText = null;
                                if (change.injectedText) {
                                    injectedText = change.injectedText.filter(element => (!element.ownerId || element.ownerId === this._editorId));
                                }
                                lineBreaksComputer.addRequest(change.detail, injectedText, null);
                                break;
                            }
                        }
                    }
                    const lineBreaks = lineBreaksComputer.finalize();
                    const lineBreakQueue = new arrays_1.ArrayQueue(lineBreaks);
                    for (const change of changes) {
                        switch (change.changeType) {
                            case 1 /* textModelEvents.RawContentChangedType.Flush */: {
                                this._lines.onModelFlushed();
                                eventsCollector.emitViewEvent(new viewEvents.ViewFlushedEvent());
                                this._decorations.reset();
                                this.viewLayout.onFlushed(this.getLineCount());
                                hadOtherModelChange = true;
                                break;
                            }
                            case 3 /* textModelEvents.RawContentChangedType.LinesDeleted */: {
                                const linesDeletedEvent = this._lines.onModelLinesDeleted(versionId, change.fromLineNumber, change.toLineNumber);
                                if (linesDeletedEvent !== null) {
                                    eventsCollector.emitViewEvent(linesDeletedEvent);
                                    this.viewLayout.onLinesDeleted(linesDeletedEvent.fromLineNumber, linesDeletedEvent.toLineNumber);
                                }
                                hadOtherModelChange = true;
                                break;
                            }
                            case 4 /* textModelEvents.RawContentChangedType.LinesInserted */: {
                                const insertedLineBreaks = lineBreakQueue.takeCount(change.detail.length);
                                const linesInsertedEvent = this._lines.onModelLinesInserted(versionId, change.fromLineNumber, change.toLineNumber, insertedLineBreaks);
                                if (linesInsertedEvent !== null) {
                                    eventsCollector.emitViewEvent(linesInsertedEvent);
                                    this.viewLayout.onLinesInserted(linesInsertedEvent.fromLineNumber, linesInsertedEvent.toLineNumber);
                                }
                                hadOtherModelChange = true;
                                break;
                            }
                            case 2 /* textModelEvents.RawContentChangedType.LineChanged */: {
                                const changedLineBreakData = lineBreakQueue.dequeue();
                                const [lineMappingChanged, linesChangedEvent, linesInsertedEvent, linesDeletedEvent] = this._lines.onModelLineChanged(versionId, change.lineNumber, changedLineBreakData);
                                hadModelLineChangeThatChangedLineMapping = lineMappingChanged;
                                if (linesChangedEvent) {
                                    eventsCollector.emitViewEvent(linesChangedEvent);
                                }
                                if (linesInsertedEvent) {
                                    eventsCollector.emitViewEvent(linesInsertedEvent);
                                    this.viewLayout.onLinesInserted(linesInsertedEvent.fromLineNumber, linesInsertedEvent.toLineNumber);
                                }
                                if (linesDeletedEvent) {
                                    eventsCollector.emitViewEvent(linesDeletedEvent);
                                    this.viewLayout.onLinesDeleted(linesDeletedEvent.fromLineNumber, linesDeletedEvent.toLineNumber);
                                }
                                break;
                            }
                            case 5 /* textModelEvents.RawContentChangedType.EOLChanged */: {
                                // Nothing to do. The new version will be accepted below
                                break;
                            }
                        }
                    }
                    if (versionId !== null) {
                        this._lines.acceptVersionId(versionId);
                    }
                    this.viewLayout.onHeightMaybeChanged();
                    if (!hadOtherModelChange && hadModelLineChangeThatChangedLineMapping) {
                        eventsCollector.emitViewEvent(new viewEvents.ViewLineMappingChangedEvent());
                        eventsCollector.emitViewEvent(new viewEvents.ViewDecorationsChangedEvent(null));
                        this._cursor.onLineMappingChanged(eventsCollector);
                        this._decorations.onLineMappingChanged();
                    }
                }
                finally {
                    this._eventDispatcher.endEmitViewEvents();
                }
                // Update the configuration and reset the centered view line
                const viewportStartWasValid = this._viewportStart.isValid;
                this._viewportStart.invalidate();
                this._configuration.setModelLineCount(this.model.getLineCount());
                this._updateConfigurationViewLineCountNow();
                // Recover viewport
                if (!this._hasFocus && this.model.getAttachedEditorCount() >= 2 && viewportStartWasValid) {
                    const modelRange = this.model._getTrackedRange(this._viewportStart.modelTrackedRange);
                    if (modelRange) {
                        const viewPosition = this.coordinatesConverter.convertModelPositionToViewPosition(modelRange.getStartPosition());
                        const viewPositionTop = this.viewLayout.getVerticalOffsetForLineNumber(viewPosition.lineNumber);
                        this.viewLayout.setScrollPosition({ scrollTop: viewPositionTop + this._viewportStart.startLineDelta }, 1 /* ScrollType.Immediate */);
                    }
                }
                try {
                    const eventsCollector = this._eventDispatcher.beginEmitViewEvents();
                    if (e instanceof textModelEvents.InternalModelContentChangeEvent) {
                        eventsCollector.emitOutgoingEvent(new viewModelEventDispatcher_1.ModelContentChangedEvent(e.contentChangedEvent));
                    }
                    this._cursor.onModelContentChanged(eventsCollector, e);
                }
                finally {
                    this._eventDispatcher.endEmitViewEvents();
                }
                this._handleVisibleLinesChanged();
            }));
            this._register(this.model.onDidChangeTokens((e) => {
                const viewRanges = [];
                for (let j = 0, lenJ = e.ranges.length; j < lenJ; j++) {
                    const modelRange = e.ranges[j];
                    const viewStartLineNumber = this.coordinatesConverter.convertModelPositionToViewPosition(new position_1.Position(modelRange.fromLineNumber, 1)).lineNumber;
                    const viewEndLineNumber = this.coordinatesConverter.convertModelPositionToViewPosition(new position_1.Position(modelRange.toLineNumber, this.model.getLineMaxColumn(modelRange.toLineNumber))).lineNumber;
                    viewRanges[j] = {
                        fromLineNumber: viewStartLineNumber,
                        toLineNumber: viewEndLineNumber
                    };
                }
                this._eventDispatcher.emitSingleViewEvent(new viewEvents.ViewTokensChangedEvent(viewRanges));
                this._eventDispatcher.emitOutgoingEvent(new viewModelEventDispatcher_1.ModelTokensChangedEvent(e));
            }));
            this._register(this.model.onDidChangeLanguageConfiguration((e) => {
                this._eventDispatcher.emitSingleViewEvent(new viewEvents.ViewLanguageConfigurationEvent());
                this.cursorConfig = new cursorCommon_1.CursorConfiguration(this.model.getLanguageId(), this.model.getOptions(), this._configuration, this.languageConfigurationService);
                this._cursor.updateConfiguration(this.cursorConfig);
                this._eventDispatcher.emitOutgoingEvent(new viewModelEventDispatcher_1.ModelLanguageConfigurationChangedEvent(e));
            }));
            this._register(this.model.onDidChangeLanguage((e) => {
                this.cursorConfig = new cursorCommon_1.CursorConfiguration(this.model.getLanguageId(), this.model.getOptions(), this._configuration, this.languageConfigurationService);
                this._cursor.updateConfiguration(this.cursorConfig);
                this._eventDispatcher.emitOutgoingEvent(new viewModelEventDispatcher_1.ModelLanguageChangedEvent(e));
            }));
            this._register(this.model.onDidChangeOptions((e) => {
                // A tab size change causes a line mapping changed event => all view parts will repaint OK, no further event needed here
                if (this._lines.setTabSize(this.model.getOptions().tabSize)) {
                    try {
                        const eventsCollector = this._eventDispatcher.beginEmitViewEvents();
                        eventsCollector.emitViewEvent(new viewEvents.ViewFlushedEvent());
                        eventsCollector.emitViewEvent(new viewEvents.ViewLineMappingChangedEvent());
                        eventsCollector.emitViewEvent(new viewEvents.ViewDecorationsChangedEvent(null));
                        this._cursor.onLineMappingChanged(eventsCollector);
                        this._decorations.onLineMappingChanged();
                        this.viewLayout.onFlushed(this.getLineCount());
                    }
                    finally {
                        this._eventDispatcher.endEmitViewEvents();
                    }
                    this._updateConfigurationViewLineCount.schedule();
                }
                this.cursorConfig = new cursorCommon_1.CursorConfiguration(this.model.getLanguageId(), this.model.getOptions(), this._configuration, this.languageConfigurationService);
                this._cursor.updateConfiguration(this.cursorConfig);
                this._eventDispatcher.emitOutgoingEvent(new viewModelEventDispatcher_1.ModelOptionsChangedEvent(e));
            }));
            this._register(this.model.onDidChangeDecorations((e) => {
                this._decorations.onModelDecorationsChanged();
                this._eventDispatcher.emitSingleViewEvent(new viewEvents.ViewDecorationsChangedEvent(e));
                this._eventDispatcher.emitOutgoingEvent(new viewModelEventDispatcher_1.ModelDecorationsChangedEvent(e));
            }));
        }
        setHiddenAreas(ranges, source) {
            this.hiddenAreasModel.setHiddenAreas(source, ranges);
            const mergedRanges = this.hiddenAreasModel.getMergedRanges();
            if (mergedRanges === this.previousHiddenAreas) {
                return;
            }
            this.previousHiddenAreas = mergedRanges;
            const stableViewport = this._captureStableViewport();
            let lineMappingChanged = false;
            try {
                const eventsCollector = this._eventDispatcher.beginEmitViewEvents();
                lineMappingChanged = this._lines.setHiddenAreas(mergedRanges);
                if (lineMappingChanged) {
                    eventsCollector.emitViewEvent(new viewEvents.ViewFlushedEvent());
                    eventsCollector.emitViewEvent(new viewEvents.ViewLineMappingChangedEvent());
                    eventsCollector.emitViewEvent(new viewEvents.ViewDecorationsChangedEvent(null));
                    this._cursor.onLineMappingChanged(eventsCollector);
                    this._decorations.onLineMappingChanged();
                    this.viewLayout.onFlushed(this.getLineCount());
                    this.viewLayout.onHeightMaybeChanged();
                }
                const firstModelLineInViewPort = stableViewport.viewportStartModelPosition?.lineNumber;
                const firstModelLineIsHidden = firstModelLineInViewPort && mergedRanges.some(range => range.startLineNumber <= firstModelLineInViewPort && firstModelLineInViewPort <= range.endLineNumber);
                if (!firstModelLineIsHidden) {
                    stableViewport.recoverViewportStart(this.coordinatesConverter, this.viewLayout);
                }
            }
            finally {
                this._eventDispatcher.endEmitViewEvents();
            }
            this._updateConfigurationViewLineCount.schedule();
            if (lineMappingChanged) {
                this._eventDispatcher.emitOutgoingEvent(new viewModelEventDispatcher_1.HiddenAreasChangedEvent());
            }
        }
        getVisibleRangesPlusViewportAboveBelow() {
            const layoutInfo = this._configuration.options.get(146 /* EditorOption.layoutInfo */);
            const lineHeight = this._configuration.options.get(67 /* EditorOption.lineHeight */);
            const linesAround = Math.max(20, Math.round(layoutInfo.height / lineHeight));
            const partialData = this.viewLayout.getLinesViewportData();
            const startViewLineNumber = Math.max(1, partialData.completelyVisibleStartLineNumber - linesAround);
            const endViewLineNumber = Math.min(this.getLineCount(), partialData.completelyVisibleEndLineNumber + linesAround);
            return this._toModelVisibleRanges(new range_1.Range(startViewLineNumber, this.getLineMinColumn(startViewLineNumber), endViewLineNumber, this.getLineMaxColumn(endViewLineNumber)));
        }
        getVisibleRanges() {
            const visibleViewRange = this.getCompletelyVisibleViewRange();
            return this._toModelVisibleRanges(visibleViewRange);
        }
        getHiddenAreas() {
            return this._lines.getHiddenAreas();
        }
        _toModelVisibleRanges(visibleViewRange) {
            const visibleRange = this.coordinatesConverter.convertViewRangeToModelRange(visibleViewRange);
            const hiddenAreas = this._lines.getHiddenAreas();
            if (hiddenAreas.length === 0) {
                return [visibleRange];
            }
            const result = [];
            let resultLen = 0;
            let startLineNumber = visibleRange.startLineNumber;
            let startColumn = visibleRange.startColumn;
            const endLineNumber = visibleRange.endLineNumber;
            const endColumn = visibleRange.endColumn;
            for (let i = 0, len = hiddenAreas.length; i < len; i++) {
                const hiddenStartLineNumber = hiddenAreas[i].startLineNumber;
                const hiddenEndLineNumber = hiddenAreas[i].endLineNumber;
                if (hiddenEndLineNumber < startLineNumber) {
                    continue;
                }
                if (hiddenStartLineNumber > endLineNumber) {
                    continue;
                }
                if (startLineNumber < hiddenStartLineNumber) {
                    result[resultLen++] = new range_1.Range(startLineNumber, startColumn, hiddenStartLineNumber - 1, this.model.getLineMaxColumn(hiddenStartLineNumber - 1));
                }
                startLineNumber = hiddenEndLineNumber + 1;
                startColumn = 1;
            }
            if (startLineNumber < endLineNumber || (startLineNumber === endLineNumber && startColumn < endColumn)) {
                result[resultLen++] = new range_1.Range(startLineNumber, startColumn, endLineNumber, endColumn);
            }
            return result;
        }
        getCompletelyVisibleViewRange() {
            const partialData = this.viewLayout.getLinesViewportData();
            const startViewLineNumber = partialData.completelyVisibleStartLineNumber;
            const endViewLineNumber = partialData.completelyVisibleEndLineNumber;
            return new range_1.Range(startViewLineNumber, this.getLineMinColumn(startViewLineNumber), endViewLineNumber, this.getLineMaxColumn(endViewLineNumber));
        }
        getCompletelyVisibleViewRangeAtScrollTop(scrollTop) {
            const partialData = this.viewLayout.getLinesViewportDataAtScrollTop(scrollTop);
            const startViewLineNumber = partialData.completelyVisibleStartLineNumber;
            const endViewLineNumber = partialData.completelyVisibleEndLineNumber;
            return new range_1.Range(startViewLineNumber, this.getLineMinColumn(startViewLineNumber), endViewLineNumber, this.getLineMaxColumn(endViewLineNumber));
        }
        saveState() {
            const compatViewState = this.viewLayout.saveState();
            const scrollTop = compatViewState.scrollTop;
            const firstViewLineNumber = this.viewLayout.getLineNumberAtVerticalOffset(scrollTop);
            const firstPosition = this.coordinatesConverter.convertViewPositionToModelPosition(new position_1.Position(firstViewLineNumber, this.getLineMinColumn(firstViewLineNumber)));
            const firstPositionDeltaTop = this.viewLayout.getVerticalOffsetForLineNumber(firstViewLineNumber) - scrollTop;
            return {
                scrollLeft: compatViewState.scrollLeft,
                firstPosition: firstPosition,
                firstPositionDeltaTop: firstPositionDeltaTop
            };
        }
        reduceRestoreState(state) {
            if (typeof state.firstPosition === 'undefined') {
                // This is a view state serialized by an older version
                return this._reduceRestoreStateCompatibility(state);
            }
            const modelPosition = this.model.validatePosition(state.firstPosition);
            const viewPosition = this.coordinatesConverter.convertModelPositionToViewPosition(modelPosition);
            const scrollTop = this.viewLayout.getVerticalOffsetForLineNumber(viewPosition.lineNumber) - state.firstPositionDeltaTop;
            return {
                scrollLeft: state.scrollLeft,
                scrollTop: scrollTop
            };
        }
        _reduceRestoreStateCompatibility(state) {
            return {
                scrollLeft: state.scrollLeft,
                scrollTop: state.scrollTopWithoutViewZones
            };
        }
        getTabSize() {
            return this.model.getOptions().tabSize;
        }
        getLineCount() {
            return this._lines.getViewLineCount();
        }
        /**
         * Gives a hint that a lot of requests are about to come in for these line numbers.
         */
        setViewport(startLineNumber, endLineNumber, centeredLineNumber) {
            this._viewportStart.update(this, startLineNumber);
        }
        getActiveIndentGuide(lineNumber, minLineNumber, maxLineNumber) {
            return this._lines.getActiveIndentGuide(lineNumber, minLineNumber, maxLineNumber);
        }
        getLinesIndentGuides(startLineNumber, endLineNumber) {
            return this._lines.getViewLinesIndentGuides(startLineNumber, endLineNumber);
        }
        getBracketGuidesInRangeByLine(startLineNumber, endLineNumber, activePosition, options) {
            return this._lines.getViewLinesBracketGuides(startLineNumber, endLineNumber, activePosition, options);
        }
        getLineContent(lineNumber) {
            return this._lines.getViewLineContent(lineNumber);
        }
        getLineLength(lineNumber) {
            return this._lines.getViewLineLength(lineNumber);
        }
        getLineMinColumn(lineNumber) {
            return this._lines.getViewLineMinColumn(lineNumber);
        }
        getLineMaxColumn(lineNumber) {
            return this._lines.getViewLineMaxColumn(lineNumber);
        }
        getLineFirstNonWhitespaceColumn(lineNumber) {
            const result = strings.firstNonWhitespaceIndex(this.getLineContent(lineNumber));
            if (result === -1) {
                return 0;
            }
            return result + 1;
        }
        getLineLastNonWhitespaceColumn(lineNumber) {
            const result = strings.lastNonWhitespaceIndex(this.getLineContent(lineNumber));
            if (result === -1) {
                return 0;
            }
            return result + 2;
        }
        getMinimapDecorationsInRange(range) {
            return this._decorations.getMinimapDecorationsInRange(range);
        }
        getDecorationsInViewport(visibleRange) {
            return this._decorations.getDecorationsViewportData(visibleRange).decorations;
        }
        getInjectedTextAt(viewPosition) {
            return this._lines.getInjectedTextAt(viewPosition);
        }
        getViewportViewLineRenderingData(visibleRange, lineNumber) {
            const allInlineDecorations = this._decorations.getDecorationsViewportData(visibleRange).inlineDecorations;
            const inlineDecorations = allInlineDecorations[lineNumber - visibleRange.startLineNumber];
            return this._getViewLineRenderingData(lineNumber, inlineDecorations);
        }
        getViewLineRenderingData(lineNumber) {
            const inlineDecorations = this._decorations.getInlineDecorationsOnLine(lineNumber);
            return this._getViewLineRenderingData(lineNumber, inlineDecorations);
        }
        _getViewLineRenderingData(lineNumber, inlineDecorations) {
            const mightContainRTL = this.model.mightContainRTL();
            const mightContainNonBasicASCII = this.model.mightContainNonBasicASCII();
            const tabSize = this.getTabSize();
            const lineData = this._lines.getViewLineData(lineNumber);
            if (lineData.inlineDecorations) {
                inlineDecorations = [
                    ...inlineDecorations,
                    ...lineData.inlineDecorations.map(d => d.toInlineDecoration(lineNumber))
                ];
            }
            return new viewModel_1.ViewLineRenderingData(lineData.minColumn, lineData.maxColumn, lineData.content, lineData.continuesWithWrappedLine, mightContainRTL, mightContainNonBasicASCII, lineData.tokens, inlineDecorations, tabSize, lineData.startVisibleColumn);
        }
        getViewLineData(lineNumber) {
            return this._lines.getViewLineData(lineNumber);
        }
        getMinimapLinesRenderingData(startLineNumber, endLineNumber, needed) {
            const result = this._lines.getViewLinesData(startLineNumber, endLineNumber, needed);
            return new viewModel_1.MinimapLinesRenderingData(this.getTabSize(), result);
        }
        getAllOverviewRulerDecorations(theme) {
            const decorations = this.model.getOverviewRulerDecorations(this._editorId, (0, editorOptions_1.filterValidationDecorations)(this._configuration.options));
            const result = new OverviewRulerDecorations();
            for (const decoration of decorations) {
                const decorationOptions = decoration.options;
                const opts = decorationOptions.overviewRuler;
                if (!opts) {
                    continue;
                }
                const lane = opts.position;
                if (lane === 0) {
                    continue;
                }
                const color = opts.getColor(theme.value);
                const viewStartLineNumber = this.coordinatesConverter.getViewLineNumberOfModelPosition(decoration.range.startLineNumber, decoration.range.startColumn);
                const viewEndLineNumber = this.coordinatesConverter.getViewLineNumberOfModelPosition(decoration.range.endLineNumber, decoration.range.endColumn);
                result.accept(color, decorationOptions.zIndex, viewStartLineNumber, viewEndLineNumber, lane);
            }
            return result.asArray;
        }
        _invalidateDecorationsColorCache() {
            const decorations = this.model.getOverviewRulerDecorations();
            for (const decoration of decorations) {
                const opts1 = decoration.options.overviewRuler;
                opts1?.invalidateCachedColor();
                const opts2 = decoration.options.minimap;
                opts2?.invalidateCachedColor();
            }
        }
        getValueInRange(range, eol) {
            const modelRange = this.coordinatesConverter.convertViewRangeToModelRange(range);
            return this.model.getValueInRange(modelRange, eol);
        }
        getValueLengthInRange(range, eol) {
            const modelRange = this.coordinatesConverter.convertViewRangeToModelRange(range);
            return this.model.getValueLengthInRange(modelRange, eol);
        }
        modifyPosition(position, offset) {
            const modelPosition = this.coordinatesConverter.convertViewPositionToModelPosition(position);
            const resultModelPosition = this.model.modifyPosition(modelPosition, offset);
            return this.coordinatesConverter.convertModelPositionToViewPosition(resultModelPosition);
        }
        deduceModelPositionRelativeToViewPosition(viewAnchorPosition, deltaOffset, lineFeedCnt) {
            const modelAnchor = this.coordinatesConverter.convertViewPositionToModelPosition(viewAnchorPosition);
            if (this.model.getEOL().length === 2) {
                // This model uses CRLF, so the delta must take that into account
                if (deltaOffset < 0) {
                    deltaOffset -= lineFeedCnt;
                }
                else {
                    deltaOffset += lineFeedCnt;
                }
            }
            const modelAnchorOffset = this.model.getOffsetAt(modelAnchor);
            const resultOffset = modelAnchorOffset + deltaOffset;
            return this.model.getPositionAt(resultOffset);
        }
        getPlainTextToCopy(modelRanges, emptySelectionClipboard, forceCRLF) {
            const newLineCharacter = forceCRLF ? '\r\n' : this.model.getEOL();
            modelRanges = modelRanges.slice(0);
            modelRanges.sort(range_1.Range.compareRangesUsingStarts);
            let hasEmptyRange = false;
            let hasNonEmptyRange = false;
            for (const range of modelRanges) {
                if (range.isEmpty()) {
                    hasEmptyRange = true;
                }
                else {
                    hasNonEmptyRange = true;
                }
            }
            if (!hasNonEmptyRange) {
                // all ranges are empty
                if (!emptySelectionClipboard) {
                    return '';
                }
                const modelLineNumbers = modelRanges.map((r) => r.startLineNumber);
                let result = '';
                for (let i = 0; i < modelLineNumbers.length; i++) {
                    if (i > 0 && modelLineNumbers[i - 1] === modelLineNumbers[i]) {
                        continue;
                    }
                    result += this.model.getLineContent(modelLineNumbers[i]) + newLineCharacter;
                }
                return result;
            }
            if (hasEmptyRange && emptySelectionClipboard) {
                // mixed empty selections and non-empty selections
                const result = [];
                let prevModelLineNumber = 0;
                for (const modelRange of modelRanges) {
                    const modelLineNumber = modelRange.startLineNumber;
                    if (modelRange.isEmpty()) {
                        if (modelLineNumber !== prevModelLineNumber) {
                            result.push(this.model.getLineContent(modelLineNumber));
                        }
                    }
                    else {
                        result.push(this.model.getValueInRange(modelRange, forceCRLF ? 2 /* EndOfLinePreference.CRLF */ : 0 /* EndOfLinePreference.TextDefined */));
                    }
                    prevModelLineNumber = modelLineNumber;
                }
                return result.length === 1 ? result[0] : result;
            }
            const result = [];
            for (const modelRange of modelRanges) {
                if (!modelRange.isEmpty()) {
                    result.push(this.model.getValueInRange(modelRange, forceCRLF ? 2 /* EndOfLinePreference.CRLF */ : 0 /* EndOfLinePreference.TextDefined */));
                }
            }
            return result.length === 1 ? result[0] : result;
        }
        getRichTextToCopy(modelRanges, emptySelectionClipboard) {
            const languageId = this.model.getLanguageId();
            if (languageId === modesRegistry_1.PLAINTEXT_LANGUAGE_ID) {
                return null;
            }
            if (modelRanges.length !== 1) {
                // no multiple selection support at this time
                return null;
            }
            let range = modelRanges[0];
            if (range.isEmpty()) {
                if (!emptySelectionClipboard) {
                    // nothing to copy
                    return null;
                }
                const lineNumber = range.startLineNumber;
                range = new range_1.Range(lineNumber, this.model.getLineMinColumn(lineNumber), lineNumber, this.model.getLineMaxColumn(lineNumber));
            }
            const fontInfo = this._configuration.options.get(50 /* EditorOption.fontInfo */);
            const colorMap = this._getColorMap();
            const hasBadChars = (/[:;\\\/<>]/.test(fontInfo.fontFamily));
            const useDefaultFontFamily = (hasBadChars || fontInfo.fontFamily === editorOptions_1.EDITOR_FONT_DEFAULTS.fontFamily);
            let fontFamily;
            if (useDefaultFontFamily) {
                fontFamily = editorOptions_1.EDITOR_FONT_DEFAULTS.fontFamily;
            }
            else {
                fontFamily = fontInfo.fontFamily;
                fontFamily = fontFamily.replace(/"/g, '\'');
                const hasQuotesOrIsList = /[,']/.test(fontFamily);
                if (!hasQuotesOrIsList) {
                    const needsQuotes = /[+ ]/.test(fontFamily);
                    if (needsQuotes) {
                        fontFamily = `'${fontFamily}'`;
                    }
                }
                fontFamily = `${fontFamily}, ${editorOptions_1.EDITOR_FONT_DEFAULTS.fontFamily}`;
            }
            return {
                mode: languageId,
                html: (`<div style="`
                    + `color: ${colorMap[1 /* ColorId.DefaultForeground */]};`
                    + `background-color: ${colorMap[2 /* ColorId.DefaultBackground */]};`
                    + `font-family: ${fontFamily};`
                    + `font-weight: ${fontInfo.fontWeight};`
                    + `font-size: ${fontInfo.fontSize}px;`
                    + `line-height: ${fontInfo.lineHeight}px;`
                    + `white-space: pre;`
                    + `">`
                    + this._getHTMLToCopy(range, colorMap)
                    + '</div>')
            };
        }
        _getHTMLToCopy(modelRange, colorMap) {
            const startLineNumber = modelRange.startLineNumber;
            const startColumn = modelRange.startColumn;
            const endLineNumber = modelRange.endLineNumber;
            const endColumn = modelRange.endColumn;
            const tabSize = this.getTabSize();
            let result = '';
            for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
                const lineTokens = this.model.tokenization.getLineTokens(lineNumber);
                const lineContent = lineTokens.getLineContent();
                const startOffset = (lineNumber === startLineNumber ? startColumn - 1 : 0);
                const endOffset = (lineNumber === endLineNumber ? endColumn - 1 : lineContent.length);
                if (lineContent === '') {
                    result += '<br>';
                }
                else {
                    result += (0, textToHtmlTokenizer_1.tokenizeLineToHTML)(lineContent, lineTokens.inflate(), colorMap, startOffset, endOffset, tabSize, platform.isWindows);
                }
            }
            return result;
        }
        _getColorMap() {
            const colorMap = languages_1.TokenizationRegistry.getColorMap();
            const result = ['#000000'];
            if (colorMap) {
                for (let i = 1, len = colorMap.length; i < len; i++) {
                    result[i] = color_1.Color.Format.CSS.formatHex(colorMap[i]);
                }
            }
            return result;
        }
        //#region cursor operations
        getPrimaryCursorState() {
            return this._cursor.getPrimaryCursorState();
        }
        getLastAddedCursorIndex() {
            return this._cursor.getLastAddedCursorIndex();
        }
        getCursorStates() {
            return this._cursor.getCursorStates();
        }
        setCursorStates(source, reason, states) {
            return this._withViewEventsCollector(eventsCollector => this._cursor.setStates(eventsCollector, source, reason, states));
        }
        getCursorColumnSelectData() {
            return this._cursor.getCursorColumnSelectData();
        }
        getCursorAutoClosedCharacters() {
            return this._cursor.getAutoClosedCharacters();
        }
        setCursorColumnSelectData(columnSelectData) {
            this._cursor.setCursorColumnSelectData(columnSelectData);
        }
        getPrevEditOperationType() {
            return this._cursor.getPrevEditOperationType();
        }
        setPrevEditOperationType(type) {
            this._cursor.setPrevEditOperationType(type);
        }
        getSelection() {
            return this._cursor.getSelection();
        }
        getSelections() {
            return this._cursor.getSelections();
        }
        getPosition() {
            return this._cursor.getPrimaryCursorState().modelState.position;
        }
        setSelections(source, selections, reason = 0 /* CursorChangeReason.NotSet */) {
            this._withViewEventsCollector(eventsCollector => this._cursor.setSelections(eventsCollector, source, selections, reason));
        }
        saveCursorState() {
            return this._cursor.saveState();
        }
        restoreCursorState(states) {
            this._withViewEventsCollector(eventsCollector => this._cursor.restoreState(eventsCollector, states));
        }
        _executeCursorEdit(callback) {
            if (this._cursor.context.cursorConfig.readOnly) {
                // we cannot edit when read only...
                this._eventDispatcher.emitOutgoingEvent(new viewModelEventDispatcher_1.ReadOnlyEditAttemptEvent());
                return;
            }
            this._withViewEventsCollector(callback);
        }
        executeEdits(source, edits, cursorStateComputer) {
            this._executeCursorEdit(eventsCollector => this._cursor.executeEdits(eventsCollector, source, edits, cursorStateComputer));
        }
        startComposition() {
            this._executeCursorEdit(eventsCollector => this._cursor.startComposition(eventsCollector));
        }
        endComposition(source) {
            this._executeCursorEdit(eventsCollector => this._cursor.endComposition(eventsCollector, source));
        }
        type(text, source) {
            this._executeCursorEdit(eventsCollector => this._cursor.type(eventsCollector, text, source));
        }
        compositionType(text, replacePrevCharCnt, replaceNextCharCnt, positionDelta, source) {
            this._executeCursorEdit(eventsCollector => this._cursor.compositionType(eventsCollector, text, replacePrevCharCnt, replaceNextCharCnt, positionDelta, source));
        }
        paste(text, pasteOnNewLine, multicursorText, source) {
            this._executeCursorEdit(eventsCollector => this._cursor.paste(eventsCollector, text, pasteOnNewLine, multicursorText, source));
        }
        cut(source) {
            this._executeCursorEdit(eventsCollector => this._cursor.cut(eventsCollector, source));
        }
        executeCommand(command, source) {
            this._executeCursorEdit(eventsCollector => this._cursor.executeCommand(eventsCollector, command, source));
        }
        executeCommands(commands, source) {
            this._executeCursorEdit(eventsCollector => this._cursor.executeCommands(eventsCollector, commands, source));
        }
        revealAllCursors(source, revealHorizontal, minimalReveal = false) {
            this._withViewEventsCollector(eventsCollector => this._cursor.revealAll(eventsCollector, source, minimalReveal, 0 /* viewEvents.VerticalRevealType.Simple */, revealHorizontal, 0 /* ScrollType.Smooth */));
        }
        revealPrimaryCursor(source, revealHorizontal, minimalReveal = false) {
            this._withViewEventsCollector(eventsCollector => this._cursor.revealPrimary(eventsCollector, source, minimalReveal, 0 /* viewEvents.VerticalRevealType.Simple */, revealHorizontal, 0 /* ScrollType.Smooth */));
        }
        revealTopMostCursor(source) {
            const viewPosition = this._cursor.getTopMostViewPosition();
            const viewRange = new range_1.Range(viewPosition.lineNumber, viewPosition.column, viewPosition.lineNumber, viewPosition.column);
            this._withViewEventsCollector(eventsCollector => eventsCollector.emitViewEvent(new viewEvents.ViewRevealRangeRequestEvent(source, false, viewRange, null, 0 /* viewEvents.VerticalRevealType.Simple */, true, 0 /* ScrollType.Smooth */)));
        }
        revealBottomMostCursor(source) {
            const viewPosition = this._cursor.getBottomMostViewPosition();
            const viewRange = new range_1.Range(viewPosition.lineNumber, viewPosition.column, viewPosition.lineNumber, viewPosition.column);
            this._withViewEventsCollector(eventsCollector => eventsCollector.emitViewEvent(new viewEvents.ViewRevealRangeRequestEvent(source, false, viewRange, null, 0 /* viewEvents.VerticalRevealType.Simple */, true, 0 /* ScrollType.Smooth */)));
        }
        revealRange(source, revealHorizontal, viewRange, verticalType, scrollType) {
            this._withViewEventsCollector(eventsCollector => eventsCollector.emitViewEvent(new viewEvents.ViewRevealRangeRequestEvent(source, false, viewRange, null, verticalType, revealHorizontal, scrollType)));
        }
        //#endregion
        //#region viewLayout
        changeWhitespace(callback) {
            const hadAChange = this.viewLayout.changeWhitespace(callback);
            if (hadAChange) {
                this._eventDispatcher.emitSingleViewEvent(new viewEvents.ViewZonesChangedEvent());
                this._eventDispatcher.emitOutgoingEvent(new viewModelEventDispatcher_1.ViewZonesChangedEvent());
            }
        }
        //#endregion
        _withViewEventsCollector(callback) {
            return this._transactionalTarget.batchChanges(() => {
                try {
                    const eventsCollector = this._eventDispatcher.beginEmitViewEvents();
                    return callback(eventsCollector);
                }
                finally {
                    this._eventDispatcher.endEmitViewEvents();
                }
            });
        }
        batchEvents(callback) {
            this._withViewEventsCollector(() => { callback(); });
        }
        normalizePosition(position, affinity) {
            return this._lines.normalizePosition(position, affinity);
        }
        /**
         * Gets the column at which indentation stops at a given line.
         * @internal
        */
        getLineIndentColumn(lineNumber) {
            return this._lines.getLineIndentColumn(lineNumber);
        }
    }
    exports.ViewModel = ViewModel;
    class ViewportStart {
        static create(model) {
            const viewportStartLineTrackedRange = model._setTrackedRange(null, new range_1.Range(1, 1, 1, 1), 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */);
            return new ViewportStart(model, 1, false, viewportStartLineTrackedRange, 0);
        }
        get viewLineNumber() {
            return this._viewLineNumber;
        }
        get isValid() {
            return this._isValid;
        }
        get modelTrackedRange() {
            return this._modelTrackedRange;
        }
        get startLineDelta() {
            return this._startLineDelta;
        }
        constructor(_model, _viewLineNumber, _isValid, _modelTrackedRange, _startLineDelta) {
            this._model = _model;
            this._viewLineNumber = _viewLineNumber;
            this._isValid = _isValid;
            this._modelTrackedRange = _modelTrackedRange;
            this._startLineDelta = _startLineDelta;
        }
        dispose() {
            this._model._setTrackedRange(this._modelTrackedRange, null, 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */);
        }
        update(viewModel, startLineNumber) {
            const position = viewModel.coordinatesConverter.convertViewPositionToModelPosition(new position_1.Position(startLineNumber, viewModel.getLineMinColumn(startLineNumber)));
            const viewportStartLineTrackedRange = viewModel.model._setTrackedRange(this._modelTrackedRange, new range_1.Range(position.lineNumber, position.column, position.lineNumber, position.column), 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */);
            const viewportStartLineTop = viewModel.viewLayout.getVerticalOffsetForLineNumber(startLineNumber);
            const scrollTop = viewModel.viewLayout.getCurrentScrollTop();
            this._viewLineNumber = startLineNumber;
            this._isValid = true;
            this._modelTrackedRange = viewportStartLineTrackedRange;
            this._startLineDelta = scrollTop - viewportStartLineTop;
        }
        invalidate() {
            this._isValid = false;
        }
    }
    class OverviewRulerDecorations {
        constructor() {
            this._asMap = Object.create(null);
            this.asArray = [];
        }
        accept(color, zIndex, startLineNumber, endLineNumber, lane) {
            const prevGroup = this._asMap[color];
            if (prevGroup) {
                const prevData = prevGroup.data;
                const prevLane = prevData[prevData.length - 3];
                const prevEndLineNumber = prevData[prevData.length - 1];
                if (prevLane === lane && prevEndLineNumber + 1 >= startLineNumber) {
                    // merge into prev
                    if (endLineNumber > prevEndLineNumber) {
                        prevData[prevData.length - 1] = endLineNumber;
                    }
                    return;
                }
                // push
                prevData.push(lane, startLineNumber, endLineNumber);
            }
            else {
                const group = new viewModel_1.OverviewRulerDecorationsGroup(color, zIndex, [lane, startLineNumber, endLineNumber]);
                this._asMap[color] = group;
                this.asArray.push(group);
            }
        }
    }
    class HiddenAreasModel {
        constructor() {
            this.hiddenAreas = new Map();
            this.shouldRecompute = false;
            this.ranges = [];
        }
        setHiddenAreas(source, ranges) {
            const existing = this.hiddenAreas.get(source);
            if (existing && rangeArraysEqual(existing, ranges)) {
                return;
            }
            this.hiddenAreas.set(source, ranges);
            this.shouldRecompute = true;
        }
        /**
         * The returned array is immutable.
        */
        getMergedRanges() {
            if (!this.shouldRecompute) {
                return this.ranges;
            }
            this.shouldRecompute = false;
            const newRanges = Array.from(this.hiddenAreas.values()).reduce((r, hiddenAreas) => mergeLineRangeArray(r, hiddenAreas), []);
            if (rangeArraysEqual(this.ranges, newRanges)) {
                return this.ranges;
            }
            this.ranges = newRanges;
            return this.ranges;
        }
    }
    function mergeLineRangeArray(arr1, arr2) {
        const result = [];
        let i = 0;
        let j = 0;
        while (i < arr1.length && j < arr2.length) {
            const item1 = arr1[i];
            const item2 = arr2[j];
            if (item1.endLineNumber < item2.startLineNumber - 1) {
                result.push(arr1[i++]);
            }
            else if (item2.endLineNumber < item1.startLineNumber - 1) {
                result.push(arr2[j++]);
            }
            else {
                const startLineNumber = Math.min(item1.startLineNumber, item2.startLineNumber);
                const endLineNumber = Math.max(item1.endLineNumber, item2.endLineNumber);
                result.push(new range_1.Range(startLineNumber, 1, endLineNumber, 1));
                i++;
                j++;
            }
        }
        while (i < arr1.length) {
            result.push(arr1[i++]);
        }
        while (j < arr2.length) {
            result.push(arr2[j++]);
        }
        return result;
    }
    function rangeArraysEqual(arr1, arr2) {
        if (arr1.length !== arr2.length) {
            return false;
        }
        for (let i = 0; i < arr1.length; i++) {
            if (!arr1[i].equalsRange(arr2[i])) {
                return false;
            }
        }
        return true;
    }
    /**
     * Maintain a stable viewport by trying to keep the first line in the viewport constant.
     */
    class StableViewport {
        constructor(viewportStartModelPosition, startLineDelta) {
            this.viewportStartModelPosition = viewportStartModelPosition;
            this.startLineDelta = startLineDelta;
        }
        recoverViewportStart(coordinatesConverter, viewLayout) {
            if (!this.viewportStartModelPosition) {
                return;
            }
            const viewPosition = coordinatesConverter.convertModelPositionToViewPosition(this.viewportStartModelPosition);
            const viewPositionTop = viewLayout.getVerticalOffsetForLineNumber(viewPosition.lineNumber);
            viewLayout.setScrollPosition({ scrollTop: viewPositionTop + this.startLineDelta }, 1 /* ScrollType.Immediate */);
        }
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[219/*vs/editor/browser/widget/codeEditor/codeEditorWidget*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,8/*vs/base/common/errors*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,42/*vs/base/common/network*/,74/*vs/editor/browser/config/domFontInfo*/,686/*vs/editor/browser/config/editorConfiguration*/,229/*vs/editor/browser/config/tabFocus*/,15/*vs/editor/browser/editorExtensions*/,34/*vs/editor/browser/services/codeEditorService*/,782/*vs/editor/browser/view*/,656/*vs/editor/browser/view/domLineBreaksComputer*/,309/*vs/editor/browser/view/viewUserInputEvents*/,651/*vs/editor/browser/widget/codeEditor/codeEditorContributions*/,37/*vs/editor/common/config/editorOptions*/,94/*vs/editor/common/core/cursorColumns*/,80/*vs/editor/common/core/editorColorRegistry*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/,23/*vs/editor/common/core/selection*/,199/*vs/editor/common/cursor/cursorWordOperations*/,318/*vs/editor/common/editorAction*/,198/*vs/editor/common/editorCommon*/,20/*vs/editor/common/editorContextKeys*/,36/*vs/editor/common/languages/languageConfigurationRegistry*/,35/*vs/editor/common/model/textModel*/,17/*vs/editor/common/services/languageFeatures*/,603/*vs/editor/common/viewModel/monospaceLineBreaksComputer*/,810/*vs/editor/common/viewModel/viewModelImpl*/,3/*vs/nls*/,61/*vs/platform/accessibility/common/accessibility*/,24/*vs/platform/commands/common/commands*/,12/*vs/platform/contextkey/common/contextkey*/,7/*vs/platform/instantiation/common/instantiation*/,154/*vs/platform/instantiation/common/serviceCollection*/,50/*vs/platform/notification/common/notification*/,32/*vs/platform/theme/common/colorRegistry*/,25/*vs/platform/theme/common/themeService*/,29/*vs/platform/actions/common/actions*/,725/*vs/editor/browser/services/markerDecorations*/,498/*vs/css!vs/editor/browser/widget/codeEditor/editor*/]), function (require, exports, dom, errors_1, event_1, lifecycle_1, network_1, domFontInfo_1, editorConfiguration_1, tabFocus_1, editorExtensions_1, codeEditorService_1, view_1, domLineBreaksComputer_1, viewUserInputEvents_1, codeEditorContributions_1, editorOptions_1, cursorColumns_1, editorColorRegistry_1, position_1, range_1, selection_1, cursorWordOperations_1, editorAction_1, editorCommon, editorContextKeys_1, languageConfigurationRegistry_1, textModel_1, languageFeatures_1, monospaceLineBreaksComputer_1, viewModelImpl_1, nls, accessibility_1, commands_1, contextkey_1, instantiation_1, serviceCollection_1, notification_1, colorRegistry_1, themeService_1, actions_1) {
    "use strict";
    var CodeEditorWidget_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.EditorModeContext = exports.BooleanEventEmitter = exports.CodeEditorWidget = void 0;
    let CodeEditorWidget = class CodeEditorWidget extends lifecycle_1.Disposable {
        static { CodeEditorWidget_1 = this; }
        static { this.dropIntoEditorDecorationOptions = textModel_1.ModelDecorationOptions.register({
            description: 'workbench-dnd-target',
            className: 'dnd-target'
        }); }
        //#endregion
        get isSimpleWidget() {
            return this._configuration.isSimpleWidget;
        }
        get contextMenuId() {
            return this._configuration.contextMenuId;
        }
        constructor(domElement, _options, codeEditorWidgetOptions, instantiationService, codeEditorService, commandService, contextKeyService, themeService, notificationService, accessibilityService, languageConfigurationService, languageFeaturesService) {
            super();
            this.languageConfigurationService = languageConfigurationService;
            //#region Eventing
            this._deliveryQueue = (0, event_1.createEventDeliveryQueue)();
            this._contributions = this._register(new codeEditorContributions_1.CodeEditorContributions());
            this._onDidDispose = this._register(new event_1.Emitter());
            this.onDidDispose = this._onDidDispose.event;
            this._onDidChangeModelContent = this._register(new event_1.Emitter({ deliveryQueue: this._deliveryQueue }));
            this.onDidChangeModelContent = this._onDidChangeModelContent.event;
            this._onDidChangeModelLanguage = this._register(new event_1.Emitter({ deliveryQueue: this._deliveryQueue }));
            this.onDidChangeModelLanguage = this._onDidChangeModelLanguage.event;
            this._onDidChangeModelLanguageConfiguration = this._register(new event_1.Emitter({ deliveryQueue: this._deliveryQueue }));
            this.onDidChangeModelLanguageConfiguration = this._onDidChangeModelLanguageConfiguration.event;
            this._onDidChangeModelOptions = this._register(new event_1.Emitter({ deliveryQueue: this._deliveryQueue }));
            this.onDidChangeModelOptions = this._onDidChangeModelOptions.event;
            this._onDidChangeModelDecorations = this._register(new event_1.Emitter({ deliveryQueue: this._deliveryQueue }));
            this.onDidChangeModelDecorations = this._onDidChangeModelDecorations.event;
            this._onDidChangeModelTokens = this._register(new event_1.Emitter({ deliveryQueue: this._deliveryQueue }));
            this.onDidChangeModelTokens = this._onDidChangeModelTokens.event;
            this._onDidChangeConfiguration = this._register(new event_1.Emitter({ deliveryQueue: this._deliveryQueue }));
            this.onDidChangeConfiguration = this._onDidChangeConfiguration.event;
            this._onWillChangeModel = this._register(new event_1.Emitter({ deliveryQueue: this._deliveryQueue }));
            this.onWillChangeModel = this._onWillChangeModel.event;
            this._onDidChangeModel = this._register(new event_1.Emitter({ deliveryQueue: this._deliveryQueue }));
            this.onDidChangeModel = this._onDidChangeModel.event;
            this._onDidChangeCursorPosition = this._register(new event_1.Emitter({ deliveryQueue: this._deliveryQueue }));
            this.onDidChangeCursorPosition = this._onDidChangeCursorPosition.event;
            this._onDidChangeCursorSelection = this._register(new event_1.Emitter({ deliveryQueue: this._deliveryQueue }));
            this.onDidChangeCursorSelection = this._onDidChangeCursorSelection.event;
            this._onDidAttemptReadOnlyEdit = this._register(new InteractionEmitter(this._contributions, this._deliveryQueue));
            this.onDidAttemptReadOnlyEdit = this._onDidAttemptReadOnlyEdit.event;
            this._onDidLayoutChange = this._register(new event_1.Emitter({ deliveryQueue: this._deliveryQueue }));
            this.onDidLayoutChange = this._onDidLayoutChange.event;
            this._editorTextFocus = this._register(new BooleanEventEmitter({ deliveryQueue: this._deliveryQueue }));
            this.onDidFocusEditorText = this._editorTextFocus.onDidChangeToTrue;
            this.onDidBlurEditorText = this._editorTextFocus.onDidChangeToFalse;
            this._editorWidgetFocus = this._register(new BooleanEventEmitter({ deliveryQueue: this._deliveryQueue }));
            this.onDidFocusEditorWidget = this._editorWidgetFocus.onDidChangeToTrue;
            this.onDidBlurEditorWidget = this._editorWidgetFocus.onDidChangeToFalse;
            this._onWillType = this._register(new InteractionEmitter(this._contributions, this._deliveryQueue));
            this.onWillType = this._onWillType.event;
            this._onDidType = this._register(new InteractionEmitter(this._contributions, this._deliveryQueue));
            this.onDidType = this._onDidType.event;
            this._onDidCompositionStart = this._register(new InteractionEmitter(this._contributions, this._deliveryQueue));
            this.onDidCompositionStart = this._onDidCompositionStart.event;
            this._onDidCompositionEnd = this._register(new InteractionEmitter(this._contributions, this._deliveryQueue));
            this.onDidCompositionEnd = this._onDidCompositionEnd.event;
            this._onDidPaste = this._register(new InteractionEmitter(this._contributions, this._deliveryQueue));
            this.onDidPaste = this._onDidPaste.event;
            this._onMouseUp = this._register(new InteractionEmitter(this._contributions, this._deliveryQueue));
            this.onMouseUp = this._onMouseUp.event;
            this._onMouseDown = this._register(new InteractionEmitter(this._contributions, this._deliveryQueue));
            this.onMouseDown = this._onMouseDown.event;
            this._onMouseDrag = this._register(new InteractionEmitter(this._contributions, this._deliveryQueue));
            this.onMouseDrag = this._onMouseDrag.event;
            this._onMouseDrop = this._register(new InteractionEmitter(this._contributions, this._deliveryQueue));
            this.onMouseDrop = this._onMouseDrop.event;
            this._onMouseDropCanceled = this._register(new InteractionEmitter(this._contributions, this._deliveryQueue));
            this.onMouseDropCanceled = this._onMouseDropCanceled.event;
            this._onDropIntoEditor = this._register(new InteractionEmitter(this._contributions, this._deliveryQueue));
            this.onDropIntoEditor = this._onDropIntoEditor.event;
            this._onContextMenu = this._register(new InteractionEmitter(this._contributions, this._deliveryQueue));
            this.onContextMenu = this._onContextMenu.event;
            this._onMouseMove = this._register(new InteractionEmitter(this._contributions, this._deliveryQueue));
            this.onMouseMove = this._onMouseMove.event;
            this._onMouseLeave = this._register(new InteractionEmitter(this._contributions, this._deliveryQueue));
            this.onMouseLeave = this._onMouseLeave.event;
            this._onMouseWheel = this._register(new InteractionEmitter(this._contributions, this._deliveryQueue));
            this.onMouseWheel = this._onMouseWheel.event;
            this._onKeyUp = this._register(new InteractionEmitter(this._contributions, this._deliveryQueue));
            this.onKeyUp = this._onKeyUp.event;
            this._onKeyDown = this._register(new InteractionEmitter(this._contributions, this._deliveryQueue));
            this.onKeyDown = this._onKeyDown.event;
            this._onDidContentSizeChange = this._register(new event_1.Emitter({ deliveryQueue: this._deliveryQueue }));
            this.onDidContentSizeChange = this._onDidContentSizeChange.event;
            this._onDidScrollChange = this._register(new event_1.Emitter({ deliveryQueue: this._deliveryQueue }));
            this.onDidScrollChange = this._onDidScrollChange.event;
            this._onDidChangeViewZones = this._register(new event_1.Emitter({ deliveryQueue: this._deliveryQueue }));
            this.onDidChangeViewZones = this._onDidChangeViewZones.event;
            this._onDidChangeHiddenAreas = this._register(new event_1.Emitter({ deliveryQueue: this._deliveryQueue }));
            this.onDidChangeHiddenAreas = this._onDidChangeHiddenAreas.event;
            this._updateCounter = 0;
            this._onBeginUpdate = this._register(new event_1.Emitter());
            this.onBeginUpdate = this._onBeginUpdate.event;
            this._onEndUpdate = this._register(new event_1.Emitter());
            this.onEndUpdate = this._onEndUpdate.event;
            this._actions = new Map();
            this._bannerDomNode = null;
            this._dropIntoEditorDecorations = this.createDecorationsCollection();
            codeEditorService.willCreateCodeEditor();
            const options = { ..._options };
            this._domElement = domElement;
            this._overflowWidgetsDomNode = options.overflowWidgetsDomNode;
            delete options.overflowWidgetsDomNode;
            this._id = (++EDITOR_ID);
            this._decorationTypeKeysToIds = {};
            this._decorationTypeSubtypes = {};
            this._telemetryData = codeEditorWidgetOptions.telemetryData;
            this._configuration = this._register(this._createConfiguration(codeEditorWidgetOptions.isSimpleWidget || false, codeEditorWidgetOptions.contextMenuId ?? (codeEditorWidgetOptions.isSimpleWidget ? actions_1.MenuId.SimpleEditorContext : actions_1.MenuId.EditorContext), options, accessibilityService));
            this._register(this._configuration.onDidChange((e) => {
                this._onDidChangeConfiguration.fire(e);
                const options = this._configuration.options;
                if (e.hasChanged(146 /* EditorOption.layoutInfo */)) {
                    const layoutInfo = options.get(146 /* EditorOption.layoutInfo */);
                    this._onDidLayoutChange.fire(layoutInfo);
                }
            }));
            this._contextKeyService = this._register(contextKeyService.createScoped(this._domElement));
            this._notificationService = notificationService;
            this._codeEditorService = codeEditorService;
            this._commandService = commandService;
            this._themeService = themeService;
            this._register(new EditorContextKeysManager(this, this._contextKeyService));
            this._register(new EditorModeContext(this, this._contextKeyService, languageFeaturesService));
            this._instantiationService = this._register(instantiationService.createChild(new serviceCollection_1.ServiceCollection([contextkey_1.IContextKeyService, this._contextKeyService])));
            this._modelData = null;
            this._focusTracker = new CodeEditorWidgetFocusTracker(domElement, this._overflowWidgetsDomNode);
            this._register(this._focusTracker.onChange(() => {
                this._editorWidgetFocus.setValue(this._focusTracker.hasFocus());
            }));
            this._contentWidgets = {};
            this._overlayWidgets = {};
            this._glyphMarginWidgets = {};
            let contributions;
            if (Array.isArray(codeEditorWidgetOptions.contributions)) {
                contributions = codeEditorWidgetOptions.contributions;
            }
            else {
                contributions = editorExtensions_1.EditorExtensionsRegistry.getEditorContributions();
            }
            this._contributions.initialize(this, contributions, this._instantiationService);
            for (const action of editorExtensions_1.EditorExtensionsRegistry.getEditorActions()) {
                if (this._actions.has(action.id)) {
                    (0, errors_1.onUnexpectedError)(new Error(`Cannot have two actions with the same id ${action.id}`));
                    continue;
                }
                const internalAction = new editorAction_1.InternalEditorAction(action.id, action.label, action.alias, action.metadata, action.precondition ?? undefined, (args) => {
                    return this._instantiationService.invokeFunction((accessor) => {
                        return Promise.resolve(action.runEditorCommand(accessor, this, args));
                    });
                }, this._contextKeyService);
                this._actions.set(internalAction.id, internalAction);
            }
            const isDropIntoEnabled = () => {
                return !this._configuration.options.get(92 /* EditorOption.readOnly */)
                    && this._configuration.options.get(36 /* EditorOption.dropIntoEditor */).enabled;
            };
            this._register(new dom.DragAndDropObserver(this._domElement, {
                onDragOver: e => {
                    if (!isDropIntoEnabled()) {
                        return;
                    }
                    const target = this.getTargetAtClientPoint(e.clientX, e.clientY);
                    if (target?.position) {
                        this.showDropIndicatorAt(target.position);
                    }
                },
                onDrop: async (e) => {
                    if (!isDropIntoEnabled()) {
                        return;
                    }
                    this.removeDropIndicator();
                    if (!e.dataTransfer) {
                        return;
                    }
                    const target = this.getTargetAtClientPoint(e.clientX, e.clientY);
                    if (target?.position) {
                        this._onDropIntoEditor.fire({ position: target.position, event: e });
                    }
                },
                onDragLeave: () => {
                    this.removeDropIndicator();
                },
                onDragEnd: () => {
                    this.removeDropIndicator();
                },
            }));
            this._codeEditorService.addCodeEditor(this);
        }
        writeScreenReaderContent(reason) {
            this._modelData?.view.writeScreenReaderContent(reason);
        }
        _createConfiguration(isSimpleWidget, contextMenuId, options, accessibilityService) {
            return new editorConfiguration_1.EditorConfiguration(isSimpleWidget, contextMenuId, options, this._domElement, accessibilityService);
        }
        getId() {
            return this.getEditorType() + ':' + this._id;
        }
        getEditorType() {
            return editorCommon.EditorType.ICodeEditor;
        }
        dispose() {
            this._codeEditorService.removeCodeEditor(this);
            this._focusTracker.dispose();
            this._actions.clear();
            this._contentWidgets = {};
            this._overlayWidgets = {};
            this._removeDecorationTypes();
            this._postDetachModelCleanup(this._detachModel());
            this._onDidDispose.fire();
            super.dispose();
        }
        invokeWithinContext(fn) {
            return this._instantiationService.invokeFunction(fn);
        }
        updateOptions(newOptions) {
            this._configuration.updateOptions(newOptions || {});
        }
        getOptions() {
            return this._configuration.options;
        }
        getOption(id) {
            return this._configuration.options.get(id);
        }
        getRawOptions() {
            return this._configuration.getRawOptions();
        }
        getOverflowWidgetsDomNode() {
            return this._overflowWidgetsDomNode;
        }
        getConfiguredWordAtPosition(position) {
            if (!this._modelData) {
                return null;
            }
            return cursorWordOperations_1.WordOperations.getWordAtPosition(this._modelData.model, this._configuration.options.get(132 /* EditorOption.wordSeparators */), this._configuration.options.get(131 /* EditorOption.wordSegmenterLocales */), position);
        }
        getValue(options = null) {
            if (!this._modelData) {
                return '';
            }
            const preserveBOM = (options && options.preserveBOM) ? true : false;
            let eolPreference = 0 /* EndOfLinePreference.TextDefined */;
            if (options && options.lineEnding && options.lineEnding === '\n') {
                eolPreference = 1 /* EndOfLinePreference.LF */;
            }
            else if (options && options.lineEnding && options.lineEnding === '\r\n') {
                eolPreference = 2 /* EndOfLinePreference.CRLF */;
            }
            return this._modelData.model.getValue(eolPreference, preserveBOM);
        }
        setValue(newValue) {
            try {
                this._beginUpdate();
                if (!this._modelData) {
                    return;
                }
                this._modelData.model.setValue(newValue);
            }
            finally {
                this._endUpdate();
            }
        }
        getModel() {
            if (!this._modelData) {
                return null;
            }
            return this._modelData.model;
        }
        setModel(_model = null) {
            try {
                this._beginUpdate();
                const model = _model;
                if (this._modelData === null && model === null) {
                    // Current model is the new model
                    return;
                }
                if (this._modelData && this._modelData.model === model) {
                    // Current model is the new model
                    return;
                }
                const e = {
                    oldModelUrl: this._modelData?.model.uri || null,
                    newModelUrl: model?.uri || null
                };
                this._onWillChangeModel.fire(e);
                const hasTextFocus = this.hasTextFocus();
                const detachedModel = this._detachModel();
                this._attachModel(model);
                if (hasTextFocus && this.hasModel()) {
                    this.focus();
                }
                this._removeDecorationTypes();
                this._onDidChangeModel.fire(e);
                this._postDetachModelCleanup(detachedModel);
                this._contributionsDisposable = this._contributions.onAfterModelAttached();
            }
            finally {
                this._endUpdate();
            }
        }
        _removeDecorationTypes() {
            this._decorationTypeKeysToIds = {};
            if (this._decorationTypeSubtypes) {
                for (const decorationType in this._decorationTypeSubtypes) {
                    const subTypes = this._decorationTypeSubtypes[decorationType];
                    for (const subType in subTypes) {
                        this._removeDecorationType(decorationType + '-' + subType);
                    }
                }
                this._decorationTypeSubtypes = {};
            }
        }
        getVisibleRanges() {
            if (!this._modelData) {
                return [];
            }
            return this._modelData.viewModel.getVisibleRanges();
        }
        getVisibleRangesPlusViewportAboveBelow() {
            if (!this._modelData) {
                return [];
            }
            return this._modelData.viewModel.getVisibleRangesPlusViewportAboveBelow();
        }
        getWhitespaces() {
            if (!this._modelData) {
                return [];
            }
            return this._modelData.viewModel.viewLayout.getWhitespaces();
        }
        static _getVerticalOffsetAfterPosition(modelData, modelLineNumber, modelColumn, includeViewZones) {
            const modelPosition = modelData.model.validatePosition({
                lineNumber: modelLineNumber,
                column: modelColumn
            });
            const viewPosition = modelData.viewModel.coordinatesConverter.convertModelPositionToViewPosition(modelPosition);
            return modelData.viewModel.viewLayout.getVerticalOffsetAfterLineNumber(viewPosition.lineNumber, includeViewZones);
        }
        getTopForLineNumber(lineNumber, includeViewZones = false) {
            if (!this._modelData) {
                return -1;
            }
            return CodeEditorWidget_1._getVerticalOffsetForPosition(this._modelData, lineNumber, 1, includeViewZones);
        }
        getTopForPosition(lineNumber, column) {
            if (!this._modelData) {
                return -1;
            }
            return CodeEditorWidget_1._getVerticalOffsetForPosition(this._modelData, lineNumber, column, false);
        }
        static _getVerticalOffsetForPosition(modelData, modelLineNumber, modelColumn, includeViewZones = false) {
            const modelPosition = modelData.model.validatePosition({
                lineNumber: modelLineNumber,
                column: modelColumn
            });
            const viewPosition = modelData.viewModel.coordinatesConverter.convertModelPositionToViewPosition(modelPosition);
            return modelData.viewModel.viewLayout.getVerticalOffsetForLineNumber(viewPosition.lineNumber, includeViewZones);
        }
        getBottomForLineNumber(lineNumber, includeViewZones = false) {
            if (!this._modelData) {
                return -1;
            }
            const maxCol = this._modelData.model.getLineMaxColumn(lineNumber);
            return CodeEditorWidget_1._getVerticalOffsetAfterPosition(this._modelData, lineNumber, maxCol, includeViewZones);
        }
        setHiddenAreas(ranges, source) {
            this._modelData?.viewModel.setHiddenAreas(ranges.map(r => range_1.Range.lift(r)), source);
        }
        getVisibleColumnFromPosition(rawPosition) {
            if (!this._modelData) {
                return rawPosition.column;
            }
            const position = this._modelData.model.validatePosition(rawPosition);
            const tabSize = this._modelData.model.getOptions().tabSize;
            return cursorColumns_1.CursorColumns.visibleColumnFromColumn(this._modelData.model.getLineContent(position.lineNumber), position.column, tabSize) + 1;
        }
        getPosition() {
            if (!this._modelData) {
                return null;
            }
            return this._modelData.viewModel.getPosition();
        }
        setPosition(position, source = 'api') {
            if (!this._modelData) {
                return;
            }
            if (!position_1.Position.isIPosition(position)) {
                throw new Error('Invalid arguments');
            }
            this._modelData.viewModel.setSelections(source, [{
                    selectionStartLineNumber: position.lineNumber,
                    selectionStartColumn: position.column,
                    positionLineNumber: position.lineNumber,
                    positionColumn: position.column
                }]);
        }
        _sendRevealRange(modelRange, verticalType, revealHorizontal, scrollType) {
            if (!this._modelData) {
                return;
            }
            if (!range_1.Range.isIRange(modelRange)) {
                throw new Error('Invalid arguments');
            }
            const validatedModelRange = this._modelData.model.validateRange(modelRange);
            const viewRange = this._modelData.viewModel.coordinatesConverter.convertModelRangeToViewRange(validatedModelRange);
            this._modelData.viewModel.revealRange('api', revealHorizontal, viewRange, verticalType, scrollType);
        }
        revealLine(lineNumber, scrollType = 0 /* editorCommon.ScrollType.Smooth */) {
            this._revealLine(lineNumber, 0 /* VerticalRevealType.Simple */, scrollType);
        }
        revealLineInCenter(lineNumber, scrollType = 0 /* editorCommon.ScrollType.Smooth */) {
            this._revealLine(lineNumber, 1 /* VerticalRevealType.Center */, scrollType);
        }
        revealLineInCenterIfOutsideViewport(lineNumber, scrollType = 0 /* editorCommon.ScrollType.Smooth */) {
            this._revealLine(lineNumber, 2 /* VerticalRevealType.CenterIfOutsideViewport */, scrollType);
        }
        revealLineNearTop(lineNumber, scrollType = 0 /* editorCommon.ScrollType.Smooth */) {
            this._revealLine(lineNumber, 5 /* VerticalRevealType.NearTop */, scrollType);
        }
        _revealLine(lineNumber, revealType, scrollType) {
            if (typeof lineNumber !== 'number') {
                throw new Error('Invalid arguments');
            }
            this._sendRevealRange(new range_1.Range(lineNumber, 1, lineNumber, 1), revealType, false, scrollType);
        }
        revealPosition(position, scrollType = 0 /* editorCommon.ScrollType.Smooth */) {
            this._revealPosition(position, 0 /* VerticalRevealType.Simple */, true, scrollType);
        }
        revealPositionInCenter(position, scrollType = 0 /* editorCommon.ScrollType.Smooth */) {
            this._revealPosition(position, 1 /* VerticalRevealType.Center */, true, scrollType);
        }
        revealPositionInCenterIfOutsideViewport(position, scrollType = 0 /* editorCommon.ScrollType.Smooth */) {
            this._revealPosition(position, 2 /* VerticalRevealType.CenterIfOutsideViewport */, true, scrollType);
        }
        revealPositionNearTop(position, scrollType = 0 /* editorCommon.ScrollType.Smooth */) {
            this._revealPosition(position, 5 /* VerticalRevealType.NearTop */, true, scrollType);
        }
        _revealPosition(position, verticalType, revealHorizontal, scrollType) {
            if (!position_1.Position.isIPosition(position)) {
                throw new Error('Invalid arguments');
            }
            this._sendRevealRange(new range_1.Range(position.lineNumber, position.column, position.lineNumber, position.column), verticalType, revealHorizontal, scrollType);
        }
        getSelection() {
            if (!this._modelData) {
                return null;
            }
            return this._modelData.viewModel.getSelection();
        }
        getSelections() {
            if (!this._modelData) {
                return null;
            }
            return this._modelData.viewModel.getSelections();
        }
        setSelection(something, source = 'api') {
            const isSelection = selection_1.Selection.isISelection(something);
            const isRange = range_1.Range.isIRange(something);
            if (!isSelection && !isRange) {
                throw new Error('Invalid arguments');
            }
            if (isSelection) {
                this._setSelectionImpl(something, source);
            }
            else if (isRange) {
                // act as if it was an IRange
                const selection = {
                    selectionStartLineNumber: something.startLineNumber,
                    selectionStartColumn: something.startColumn,
                    positionLineNumber: something.endLineNumber,
                    positionColumn: something.endColumn
                };
                this._setSelectionImpl(selection, source);
            }
        }
        _setSelectionImpl(sel, source) {
            if (!this._modelData) {
                return;
            }
            const selection = new selection_1.Selection(sel.selectionStartLineNumber, sel.selectionStartColumn, sel.positionLineNumber, sel.positionColumn);
            this._modelData.viewModel.setSelections(source, [selection]);
        }
        revealLines(startLineNumber, endLineNumber, scrollType = 0 /* editorCommon.ScrollType.Smooth */) {
            this._revealLines(startLineNumber, endLineNumber, 0 /* VerticalRevealType.Simple */, scrollType);
        }
        revealLinesInCenter(startLineNumber, endLineNumber, scrollType = 0 /* editorCommon.ScrollType.Smooth */) {
            this._revealLines(startLineNumber, endLineNumber, 1 /* VerticalRevealType.Center */, scrollType);
        }
        revealLinesInCenterIfOutsideViewport(startLineNumber, endLineNumber, scrollType = 0 /* editorCommon.ScrollType.Smooth */) {
            this._revealLines(startLineNumber, endLineNumber, 2 /* VerticalRevealType.CenterIfOutsideViewport */, scrollType);
        }
        revealLinesNearTop(startLineNumber, endLineNumber, scrollType = 0 /* editorCommon.ScrollType.Smooth */) {
            this._revealLines(startLineNumber, endLineNumber, 5 /* VerticalRevealType.NearTop */, scrollType);
        }
        _revealLines(startLineNumber, endLineNumber, verticalType, scrollType) {
            if (typeof startLineNumber !== 'number' || typeof endLineNumber !== 'number') {
                throw new Error('Invalid arguments');
            }
            this._sendRevealRange(new range_1.Range(startLineNumber, 1, endLineNumber, 1), verticalType, false, scrollType);
        }
        revealRange(range, scrollType = 0 /* editorCommon.ScrollType.Smooth */, revealVerticalInCenter = false, revealHorizontal = true) {
            this._revealRange(range, revealVerticalInCenter ? 1 /* VerticalRevealType.Center */ : 0 /* VerticalRevealType.Simple */, revealHorizontal, scrollType);
        }
        revealRangeInCenter(range, scrollType = 0 /* editorCommon.ScrollType.Smooth */) {
            this._revealRange(range, 1 /* VerticalRevealType.Center */, true, scrollType);
        }
        revealRangeInCenterIfOutsideViewport(range, scrollType = 0 /* editorCommon.ScrollType.Smooth */) {
            this._revealRange(range, 2 /* VerticalRevealType.CenterIfOutsideViewport */, true, scrollType);
        }
        revealRangeNearTop(range, scrollType = 0 /* editorCommon.ScrollType.Smooth */) {
            this._revealRange(range, 5 /* VerticalRevealType.NearTop */, true, scrollType);
        }
        revealRangeNearTopIfOutsideViewport(range, scrollType = 0 /* editorCommon.ScrollType.Smooth */) {
            this._revealRange(range, 6 /* VerticalRevealType.NearTopIfOutsideViewport */, true, scrollType);
        }
        revealRangeAtTop(range, scrollType = 0 /* editorCommon.ScrollType.Smooth */) {
            this._revealRange(range, 3 /* VerticalRevealType.Top */, true, scrollType);
        }
        _revealRange(range, verticalType, revealHorizontal, scrollType) {
            if (!range_1.Range.isIRange(range)) {
                throw new Error('Invalid arguments');
            }
            this._sendRevealRange(range_1.Range.lift(range), verticalType, revealHorizontal, scrollType);
        }
        setSelections(ranges, source = 'api', reason = 0 /* CursorChangeReason.NotSet */) {
            if (!this._modelData) {
                return;
            }
            if (!ranges || ranges.length === 0) {
                throw new Error('Invalid arguments');
            }
            for (let i = 0, len = ranges.length; i < len; i++) {
                if (!selection_1.Selection.isISelection(ranges[i])) {
                    throw new Error('Invalid arguments');
                }
            }
            this._modelData.viewModel.setSelections(source, ranges, reason);
        }
        getContentWidth() {
            if (!this._modelData) {
                return -1;
            }
            return this._modelData.viewModel.viewLayout.getContentWidth();
        }
        getScrollWidth() {
            if (!this._modelData) {
                return -1;
            }
            return this._modelData.viewModel.viewLayout.getScrollWidth();
        }
        getScrollLeft() {
            if (!this._modelData) {
                return -1;
            }
            return this._modelData.viewModel.viewLayout.getCurrentScrollLeft();
        }
        getContentHeight() {
            if (!this._modelData) {
                return -1;
            }
            return this._modelData.viewModel.viewLayout.getContentHeight();
        }
        getScrollHeight() {
            if (!this._modelData) {
                return -1;
            }
            return this._modelData.viewModel.viewLayout.getScrollHeight();
        }
        getScrollTop() {
            if (!this._modelData) {
                return -1;
            }
            return this._modelData.viewModel.viewLayout.getCurrentScrollTop();
        }
        setScrollLeft(newScrollLeft, scrollType = 1 /* editorCommon.ScrollType.Immediate */) {
            if (!this._modelData) {
                return;
            }
            if (typeof newScrollLeft !== 'number') {
                throw new Error('Invalid arguments');
            }
            this._modelData.viewModel.viewLayout.setScrollPosition({
                scrollLeft: newScrollLeft
            }, scrollType);
        }
        setScrollTop(newScrollTop, scrollType = 1 /* editorCommon.ScrollType.Immediate */) {
            if (!this._modelData) {
                return;
            }
            if (typeof newScrollTop !== 'number') {
                throw new Error('Invalid arguments');
            }
            this._modelData.viewModel.viewLayout.setScrollPosition({
                scrollTop: newScrollTop
            }, scrollType);
        }
        setScrollPosition(position, scrollType = 1 /* editorCommon.ScrollType.Immediate */) {
            if (!this._modelData) {
                return;
            }
            this._modelData.viewModel.viewLayout.setScrollPosition(position, scrollType);
        }
        hasPendingScrollAnimation() {
            if (!this._modelData) {
                return false;
            }
            return this._modelData.viewModel.viewLayout.hasPendingScrollAnimation();
        }
        saveViewState() {
            if (!this._modelData) {
                return null;
            }
            const contributionsState = this._contributions.saveViewState();
            const cursorState = this._modelData.viewModel.saveCursorState();
            const viewState = this._modelData.viewModel.saveState();
            return {
                cursorState: cursorState,
                viewState: viewState,
                contributionsState: contributionsState
            };
        }
        restoreViewState(s) {
            if (!this._modelData || !this._modelData.hasRealView) {
                return;
            }
            const codeEditorState = s;
            if (codeEditorState && codeEditorState.cursorState && codeEditorState.viewState) {
                const cursorState = codeEditorState.cursorState;
                if (Array.isArray(cursorState)) {
                    if (cursorState.length > 0) {
                        this._modelData.viewModel.restoreCursorState(cursorState);
                    }
                }
                else {
                    // Backwards compatibility
                    this._modelData.viewModel.restoreCursorState([cursorState]);
                }
                this._contributions.restoreViewState(codeEditorState.contributionsState || {});
                const reducedState = this._modelData.viewModel.reduceRestoreState(codeEditorState.viewState);
                this._modelData.view.restoreState(reducedState);
            }
        }
        handleInitialized() {
            this._getViewModel()?.visibleLinesStabilized();
        }
        getContribution(id) {
            return this._contributions.get(id);
        }
        getActions() {
            return Array.from(this._actions.values());
        }
        getSupportedActions() {
            let result = this.getActions();
            result = result.filter(action => action.isSupported());
            return result;
        }
        getAction(id) {
            return this._actions.get(id) || null;
        }
        trigger(source, handlerId, payload) {
            payload = payload || {};
            try {
                this._beginUpdate();
                switch (handlerId) {
                    case "compositionStart" /* editorCommon.Handler.CompositionStart */:
                        this._startComposition();
                        return;
                    case "compositionEnd" /* editorCommon.Handler.CompositionEnd */:
                        this._endComposition(source);
                        return;
                    case "type" /* editorCommon.Handler.Type */: {
                        const args = payload;
                        this._type(source, args.text || '');
                        return;
                    }
                    case "replacePreviousChar" /* editorCommon.Handler.ReplacePreviousChar */: {
                        const args = payload;
                        this._compositionType(source, args.text || '', args.replaceCharCnt || 0, 0, 0);
                        return;
                    }
                    case "compositionType" /* editorCommon.Handler.CompositionType */: {
                        const args = payload;
                        this._compositionType(source, args.text || '', args.replacePrevCharCnt || 0, args.replaceNextCharCnt || 0, args.positionDelta || 0);
                        return;
                    }
                    case "paste" /* editorCommon.Handler.Paste */: {
                        const args = payload;
                        this._paste(source, args.text || '', args.pasteOnNewLine || false, args.multicursorText || null, args.mode || null, args.clipboardEvent);
                        return;
                    }
                    case "cut" /* editorCommon.Handler.Cut */:
                        this._cut(source);
                        return;
                }
                const action = this.getAction(handlerId);
                if (action) {
                    Promise.resolve(action.run(payload)).then(undefined, errors_1.onUnexpectedError);
                    return;
                }
                if (!this._modelData) {
                    return;
                }
                if (this._triggerEditorCommand(source, handlerId, payload)) {
                    return;
                }
                this._triggerCommand(handlerId, payload);
            }
            finally {
                this._endUpdate();
            }
        }
        _triggerCommand(handlerId, payload) {
            this._commandService.executeCommand(handlerId, payload);
        }
        _startComposition() {
            if (!this._modelData) {
                return;
            }
            this._modelData.viewModel.startComposition();
            this._onDidCompositionStart.fire();
        }
        _endComposition(source) {
            if (!this._modelData) {
                return;
            }
            this._modelData.viewModel.endComposition(source);
            this._onDidCompositionEnd.fire();
        }
        _type(source, text) {
            if (!this._modelData || text.length === 0) {
                return;
            }
            if (source === 'keyboard') {
                this._onWillType.fire(text);
            }
            this._modelData.viewModel.type(text, source);
            if (source === 'keyboard') {
                this._onDidType.fire(text);
            }
        }
        _compositionType(source, text, replacePrevCharCnt, replaceNextCharCnt, positionDelta) {
            if (!this._modelData) {
                return;
            }
            this._modelData.viewModel.compositionType(text, replacePrevCharCnt, replaceNextCharCnt, positionDelta, source);
        }
        _paste(source, text, pasteOnNewLine, multicursorText, mode, clipboardEvent) {
            if (!this._modelData) {
                return;
            }
            const viewModel = this._modelData.viewModel;
            const startPosition = viewModel.getSelection().getStartPosition();
            viewModel.paste(text, pasteOnNewLine, multicursorText, source);
            const endPosition = viewModel.getSelection().getStartPosition();
            if (source === 'keyboard') {
                this._onDidPaste.fire({
                    clipboardEvent,
                    range: new range_1.Range(startPosition.lineNumber, startPosition.column, endPosition.lineNumber, endPosition.column),
                    languageId: mode
                });
            }
        }
        _cut(source) {
            if (!this._modelData) {
                return;
            }
            this._modelData.viewModel.cut(source);
        }
        _triggerEditorCommand(source, handlerId, payload) {
            const command = editorExtensions_1.EditorExtensionsRegistry.getEditorCommand(handlerId);
            if (command) {
                payload = payload || {};
                payload.source = source;
                this._instantiationService.invokeFunction((accessor) => {
                    Promise.resolve(command.runEditorCommand(accessor, this, payload)).then(undefined, errors_1.onUnexpectedError);
                });
                return true;
            }
            return false;
        }
        _getViewModel() {
            if (!this._modelData) {
                return null;
            }
            return this._modelData.viewModel;
        }
        pushUndoStop() {
            if (!this._modelData) {
                return false;
            }
            if (this._configuration.options.get(92 /* EditorOption.readOnly */)) {
                // read only editor => sorry!
                return false;
            }
            this._modelData.model.pushStackElement();
            return true;
        }
        popUndoStop() {
            if (!this._modelData) {
                return false;
            }
            if (this._configuration.options.get(92 /* EditorOption.readOnly */)) {
                // read only editor => sorry!
                return false;
            }
            this._modelData.model.popStackElement();
            return true;
        }
        executeEdits(source, edits, endCursorState) {
            if (!this._modelData) {
                return false;
            }
            if (this._configuration.options.get(92 /* EditorOption.readOnly */)) {
                // read only editor => sorry!
                return false;
            }
            let cursorStateComputer;
            if (!endCursorState) {
                cursorStateComputer = () => null;
            }
            else if (Array.isArray(endCursorState)) {
                cursorStateComputer = () => endCursorState;
            }
            else {
                cursorStateComputer = endCursorState;
            }
            this._modelData.viewModel.executeEdits(source, edits, cursorStateComputer);
            return true;
        }
        executeCommand(source, command) {
            if (!this._modelData) {
                return;
            }
            this._modelData.viewModel.executeCommand(command, source);
        }
        executeCommands(source, commands) {
            if (!this._modelData) {
                return;
            }
            this._modelData.viewModel.executeCommands(commands, source);
        }
        createDecorationsCollection(decorations) {
            return new EditorDecorationsCollection(this, decorations);
        }
        changeDecorations(callback) {
            if (!this._modelData) {
                // callback will not be called
                return null;
            }
            return this._modelData.model.changeDecorations(callback, this._id);
        }
        getLineDecorations(lineNumber) {
            if (!this._modelData) {
                return null;
            }
            return this._modelData.model.getLineDecorations(lineNumber, this._id, (0, editorOptions_1.filterValidationDecorations)(this._configuration.options));
        }
        getDecorationsInRange(range) {
            if (!this._modelData) {
                return null;
            }
            return this._modelData.model.getDecorationsInRange(range, this._id, (0, editorOptions_1.filterValidationDecorations)(this._configuration.options));
        }
        /**
         * @deprecated
         */
        deltaDecorations(oldDecorations, newDecorations) {
            if (!this._modelData) {
                return [];
            }
            if (oldDecorations.length === 0 && newDecorations.length === 0) {
                return oldDecorations;
            }
            return this._modelData.model.deltaDecorations(oldDecorations, newDecorations, this._id);
        }
        removeDecorations(decorationIds) {
            if (!this._modelData || decorationIds.length === 0) {
                return;
            }
            this._modelData.model.changeDecorations((changeAccessor) => {
                changeAccessor.deltaDecorations(decorationIds, []);
            });
        }
        removeDecorationsByType(decorationTypeKey) {
            // remove decorations for type and sub type
            const oldDecorationsIds = this._decorationTypeKeysToIds[decorationTypeKey];
            if (oldDecorationsIds) {
                this.changeDecorations(accessor => accessor.deltaDecorations(oldDecorationsIds, []));
            }
            if (this._decorationTypeKeysToIds.hasOwnProperty(decorationTypeKey)) {
                delete this._decorationTypeKeysToIds[decorationTypeKey];
            }
            if (this._decorationTypeSubtypes.hasOwnProperty(decorationTypeKey)) {
                delete this._decorationTypeSubtypes[decorationTypeKey];
            }
        }
        getLayoutInfo() {
            const options = this._configuration.options;
            const layoutInfo = options.get(146 /* EditorOption.layoutInfo */);
            return layoutInfo;
        }
        createOverviewRuler(cssClassName) {
            if (!this._modelData || !this._modelData.hasRealView) {
                return null;
            }
            return this._modelData.view.createOverviewRuler(cssClassName);
        }
        getContainerDomNode() {
            return this._domElement;
        }
        getDomNode() {
            if (!this._modelData || !this._modelData.hasRealView) {
                return null;
            }
            return this._modelData.view.domNode.domNode;
        }
        delegateVerticalScrollbarPointerDown(browserEvent) {
            if (!this._modelData || !this._modelData.hasRealView) {
                return;
            }
            this._modelData.view.delegateVerticalScrollbarPointerDown(browserEvent);
        }
        delegateScrollFromMouseWheelEvent(browserEvent) {
            if (!this._modelData || !this._modelData.hasRealView) {
                return;
            }
            this._modelData.view.delegateScrollFromMouseWheelEvent(browserEvent);
        }
        layout(dimension, postponeRendering = false) {
            this._configuration.observeContainer(dimension);
            if (!postponeRendering) {
                this.render();
            }
        }
        focus() {
            if (!this._modelData || !this._modelData.hasRealView) {
                return;
            }
            this._modelData.view.focus();
        }
        hasTextFocus() {
            if (!this._modelData || !this._modelData.hasRealView) {
                return false;
            }
            return this._modelData.view.isFocused();
        }
        hasWidgetFocus() {
            return this._focusTracker && this._focusTracker.hasFocus();
        }
        addContentWidget(widget) {
            const widgetData = {
                widget: widget,
                position: widget.getPosition()
            };
            if (this._contentWidgets.hasOwnProperty(widget.getId())) {
                console.warn('Overwriting a content widget with the same id:' + widget.getId());
            }
            this._contentWidgets[widget.getId()] = widgetData;
            if (this._modelData && this._modelData.hasRealView) {
                this._modelData.view.addContentWidget(widgetData);
            }
        }
        layoutContentWidget(widget) {
            const widgetId = widget.getId();
            if (this._contentWidgets.hasOwnProperty(widgetId)) {
                const widgetData = this._contentWidgets[widgetId];
                widgetData.position = widget.getPosition();
                if (this._modelData && this._modelData.hasRealView) {
                    this._modelData.view.layoutContentWidget(widgetData);
                }
            }
        }
        removeContentWidget(widget) {
            const widgetId = widget.getId();
            if (this._contentWidgets.hasOwnProperty(widgetId)) {
                const widgetData = this._contentWidgets[widgetId];
                delete this._contentWidgets[widgetId];
                if (this._modelData && this._modelData.hasRealView) {
                    this._modelData.view.removeContentWidget(widgetData);
                }
            }
        }
        addOverlayWidget(widget) {
            const widgetData = {
                widget: widget,
                position: widget.getPosition()
            };
            if (this._overlayWidgets.hasOwnProperty(widget.getId())) {
                console.warn('Overwriting an overlay widget with the same id.');
            }
            this._overlayWidgets[widget.getId()] = widgetData;
            if (this._modelData && this._modelData.hasRealView) {
                this._modelData.view.addOverlayWidget(widgetData);
            }
        }
        layoutOverlayWidget(widget) {
            const widgetId = widget.getId();
            if (this._overlayWidgets.hasOwnProperty(widgetId)) {
                const widgetData = this._overlayWidgets[widgetId];
                widgetData.position = widget.getPosition();
                if (this._modelData && this._modelData.hasRealView) {
                    this._modelData.view.layoutOverlayWidget(widgetData);
                }
            }
        }
        removeOverlayWidget(widget) {
            const widgetId = widget.getId();
            if (this._overlayWidgets.hasOwnProperty(widgetId)) {
                const widgetData = this._overlayWidgets[widgetId];
                delete this._overlayWidgets[widgetId];
                if (this._modelData && this._modelData.hasRealView) {
                    this._modelData.view.removeOverlayWidget(widgetData);
                }
            }
        }
        addGlyphMarginWidget(widget) {
            const widgetData = {
                widget: widget,
                position: widget.getPosition()
            };
            if (this._glyphMarginWidgets.hasOwnProperty(widget.getId())) {
                console.warn('Overwriting a glyph margin widget with the same id.');
            }
            this._glyphMarginWidgets[widget.getId()] = widgetData;
            if (this._modelData && this._modelData.hasRealView) {
                this._modelData.view.addGlyphMarginWidget(widgetData);
            }
        }
        layoutGlyphMarginWidget(widget) {
            const widgetId = widget.getId();
            if (this._glyphMarginWidgets.hasOwnProperty(widgetId)) {
                const widgetData = this._glyphMarginWidgets[widgetId];
                widgetData.position = widget.getPosition();
                if (this._modelData && this._modelData.hasRealView) {
                    this._modelData.view.layoutGlyphMarginWidget(widgetData);
                }
            }
        }
        removeGlyphMarginWidget(widget) {
            const widgetId = widget.getId();
            if (this._glyphMarginWidgets.hasOwnProperty(widgetId)) {
                const widgetData = this._glyphMarginWidgets[widgetId];
                delete this._glyphMarginWidgets[widgetId];
                if (this._modelData && this._modelData.hasRealView) {
                    this._modelData.view.removeGlyphMarginWidget(widgetData);
                }
            }
        }
        changeViewZones(callback) {
            if (!this._modelData || !this._modelData.hasRealView) {
                return;
            }
            this._modelData.view.change(callback);
        }
        getTargetAtClientPoint(clientX, clientY) {
            if (!this._modelData || !this._modelData.hasRealView) {
                return null;
            }
            return this._modelData.view.getTargetAtClientPoint(clientX, clientY);
        }
        getScrolledVisiblePosition(rawPosition) {
            if (!this._modelData || !this._modelData.hasRealView) {
                return null;
            }
            const position = this._modelData.model.validatePosition(rawPosition);
            const options = this._configuration.options;
            const layoutInfo = options.get(146 /* EditorOption.layoutInfo */);
            const top = CodeEditorWidget_1._getVerticalOffsetForPosition(this._modelData, position.lineNumber, position.column) - this.getScrollTop();
            const left = this._modelData.view.getOffsetForColumn(position.lineNumber, position.column) + layoutInfo.glyphMarginWidth + layoutInfo.lineNumbersWidth + layoutInfo.decorationsWidth - this.getScrollLeft();
            return {
                top: top,
                left: left,
                height: options.get(67 /* EditorOption.lineHeight */)
            };
        }
        getOffsetForColumn(lineNumber, column) {
            if (!this._modelData || !this._modelData.hasRealView) {
                return -1;
            }
            return this._modelData.view.getOffsetForColumn(lineNumber, column);
        }
        render(forceRedraw = false) {
            if (!this._modelData || !this._modelData.hasRealView) {
                return;
            }
            this._modelData.viewModel.batchEvents(() => {
                this._modelData.view.render(true, forceRedraw);
            });
        }
        setAriaOptions(options) {
            if (!this._modelData || !this._modelData.hasRealView) {
                return;
            }
            this._modelData.view.setAriaOptions(options);
        }
        applyFontInfo(target) {
            (0, domFontInfo_1.applyFontInfo)(target, this._configuration.options.get(50 /* EditorOption.fontInfo */));
        }
        setBanner(domNode, domNodeHeight) {
            if (this._bannerDomNode && this._domElement.contains(this._bannerDomNode)) {
                this._bannerDomNode.remove();
            }
            this._bannerDomNode = domNode;
            this._configuration.setReservedHeight(domNode ? domNodeHeight : 0);
            if (this._bannerDomNode) {
                this._domElement.prepend(this._bannerDomNode);
            }
        }
        _attachModel(model) {
            if (!model) {
                this._modelData = null;
                return;
            }
            const listenersToRemove = [];
            this._domElement.setAttribute('data-mode-id', model.getLanguageId());
            this._configuration.setIsDominatedByLongLines(model.isDominatedByLongLines());
            this._configuration.setModelLineCount(model.getLineCount());
            const attachedView = model.onBeforeAttached();
            const viewModel = new viewModelImpl_1.ViewModel(this._id, this._configuration, model, domLineBreaksComputer_1.DOMLineBreaksComputerFactory.create(dom.getWindow(this._domElement)), monospaceLineBreaksComputer_1.MonospaceLineBreaksComputerFactory.create(this._configuration.options), (callback) => dom.scheduleAtNextAnimationFrame(dom.getWindow(this._domElement), callback), this.languageConfigurationService, this._themeService, attachedView, {
                batchChanges: (cb) => {
                    try {
                        this._beginUpdate();
                        return cb();
                    }
                    finally {
                        this._endUpdate();
                    }
                },
            });
            // Someone might destroy the model from under the editor, so prevent any exceptions by setting a null model
            listenersToRemove.push(model.onWillDispose(() => this.setModel(null)));
            listenersToRemove.push(viewModel.onEvent((e) => {
                switch (e.kind) {
                    case 0 /* OutgoingViewModelEventKind.ContentSizeChanged */:
                        this._onDidContentSizeChange.fire(e);
                        break;
                    case 1 /* OutgoingViewModelEventKind.FocusChanged */:
                        this._editorTextFocus.setValue(e.hasFocus);
                        break;
                    case 2 /* OutgoingViewModelEventKind.ScrollChanged */:
                        this._onDidScrollChange.fire(e);
                        break;
                    case 3 /* OutgoingViewModelEventKind.ViewZonesChanged */:
                        this._onDidChangeViewZones.fire();
                        break;
                    case 4 /* OutgoingViewModelEventKind.HiddenAreasChanged */:
                        this._onDidChangeHiddenAreas.fire();
                        break;
                    case 5 /* OutgoingViewModelEventKind.ReadOnlyEditAttempt */:
                        this._onDidAttemptReadOnlyEdit.fire();
                        break;
                    case 6 /* OutgoingViewModelEventKind.CursorStateChanged */: {
                        if (e.reachedMaxCursorCount) {
                            const multiCursorLimit = this.getOption(80 /* EditorOption.multiCursorLimit */);
                            const message = nls.localize(70, "The number of cursors has been limited to {0}. Consider using [find and replace](https://code.visualstudio.com/docs/editor/codebasics#_find-and-replace) for larger changes or increase the editor multi cursor limit setting.", multiCursorLimit);
                            this._notificationService.prompt(notification_1.Severity.Warning, message, [
                                {
                                    label: 'Find and Replace',
                                    run: () => {
                                        this._commandService.executeCommand('editor.action.startFindReplaceAction');
                                    }
                                },
                                {
                                    label: nls.localize(71, 'Increase Multi Cursor Limit'),
                                    run: () => {
                                        this._commandService.executeCommand('workbench.action.openSettings2', {
                                            query: 'editor.multiCursorLimit'
                                        });
                                    }
                                }
                            ]);
                        }
                        const positions = [];
                        for (let i = 0, len = e.selections.length; i < len; i++) {
                            positions[i] = e.selections[i].getPosition();
                        }
                        const e1 = {
                            position: positions[0],
                            secondaryPositions: positions.slice(1),
                            reason: e.reason,
                            source: e.source
                        };
                        this._onDidChangeCursorPosition.fire(e1);
                        const e2 = {
                            selection: e.selections[0],
                            secondarySelections: e.selections.slice(1),
                            modelVersionId: e.modelVersionId,
                            oldSelections: e.oldSelections,
                            oldModelVersionId: e.oldModelVersionId,
                            source: e.source,
                            reason: e.reason
                        };
                        this._onDidChangeCursorSelection.fire(e2);
                        break;
                    }
                    case 7 /* OutgoingViewModelEventKind.ModelDecorationsChanged */:
                        this._onDidChangeModelDecorations.fire(e.event);
                        break;
                    case 8 /* OutgoingViewModelEventKind.ModelLanguageChanged */:
                        this._domElement.setAttribute('data-mode-id', model.getLanguageId());
                        this._onDidChangeModelLanguage.fire(e.event);
                        break;
                    case 9 /* OutgoingViewModelEventKind.ModelLanguageConfigurationChanged */:
                        this._onDidChangeModelLanguageConfiguration.fire(e.event);
                        break;
                    case 10 /* OutgoingViewModelEventKind.ModelContentChanged */:
                        this._onDidChangeModelContent.fire(e.event);
                        break;
                    case 11 /* OutgoingViewModelEventKind.ModelOptionsChanged */:
                        this._onDidChangeModelOptions.fire(e.event);
                        break;
                    case 12 /* OutgoingViewModelEventKind.ModelTokensChanged */:
                        this._onDidChangeModelTokens.fire(e.event);
                        break;
                }
            }));
            const [view, hasRealView] = this._createView(viewModel);
            if (hasRealView) {
                this._domElement.appendChild(view.domNode.domNode);
                let keys = Object.keys(this._contentWidgets);
                for (let i = 0, len = keys.length; i < len; i++) {
                    const widgetId = keys[i];
                    view.addContentWidget(this._contentWidgets[widgetId]);
                }
                keys = Object.keys(this._overlayWidgets);
                for (let i = 0, len = keys.length; i < len; i++) {
                    const widgetId = keys[i];
                    view.addOverlayWidget(this._overlayWidgets[widgetId]);
                }
                keys = Object.keys(this._glyphMarginWidgets);
                for (let i = 0, len = keys.length; i < len; i++) {
                    const widgetId = keys[i];
                    view.addGlyphMarginWidget(this._glyphMarginWidgets[widgetId]);
                }
                view.render(false, true);
                view.domNode.domNode.setAttribute('data-uri', model.uri.toString());
            }
            this._modelData = new ModelData(model, viewModel, view, hasRealView, listenersToRemove, attachedView);
        }
        _createView(viewModel) {
            let commandDelegate;
            if (this.isSimpleWidget) {
                commandDelegate = {
                    paste: (text, pasteOnNewLine, multicursorText, mode) => {
                        this._paste('keyboard', text, pasteOnNewLine, multicursorText, mode);
                    },
                    type: (text) => {
                        this._type('keyboard', text);
                    },
                    compositionType: (text, replacePrevCharCnt, replaceNextCharCnt, positionDelta) => {
                        this._compositionType('keyboard', text, replacePrevCharCnt, replaceNextCharCnt, positionDelta);
                    },
                    startComposition: () => {
                        this._startComposition();
                    },
                    endComposition: () => {
                        this._endComposition('keyboard');
                    },
                    cut: () => {
                        this._cut('keyboard');
                    }
                };
            }
            else {
                commandDelegate = {
                    paste: (text, pasteOnNewLine, multicursorText, mode) => {
                        const payload = { text, pasteOnNewLine, multicursorText, mode };
                        this._commandService.executeCommand("paste" /* editorCommon.Handler.Paste */, payload);
                    },
                    type: (text) => {
                        const payload = { text };
                        this._commandService.executeCommand("type" /* editorCommon.Handler.Type */, payload);
                    },
                    compositionType: (text, replacePrevCharCnt, replaceNextCharCnt, positionDelta) => {
                        // Try if possible to go through the existing `replacePreviousChar` command
                        if (replaceNextCharCnt || positionDelta) {
                            // must be handled through the new command
                            const payload = { text, replacePrevCharCnt, replaceNextCharCnt, positionDelta };
                            this._commandService.executeCommand("compositionType" /* editorCommon.Handler.CompositionType */, payload);
                        }
                        else {
                            const payload = { text, replaceCharCnt: replacePrevCharCnt };
                            this._commandService.executeCommand("replacePreviousChar" /* editorCommon.Handler.ReplacePreviousChar */, payload);
                        }
                    },
                    startComposition: () => {
                        this._commandService.executeCommand("compositionStart" /* editorCommon.Handler.CompositionStart */, {});
                    },
                    endComposition: () => {
                        this._commandService.executeCommand("compositionEnd" /* editorCommon.Handler.CompositionEnd */, {});
                    },
                    cut: () => {
                        this._commandService.executeCommand("cut" /* editorCommon.Handler.Cut */, {});
                    }
                };
            }
            const viewUserInputEvents = new viewUserInputEvents_1.ViewUserInputEvents(viewModel.coordinatesConverter);
            viewUserInputEvents.onKeyDown = (e) => this._onKeyDown.fire(e);
            viewUserInputEvents.onKeyUp = (e) => this._onKeyUp.fire(e);
            viewUserInputEvents.onContextMenu = (e) => this._onContextMenu.fire(e);
            viewUserInputEvents.onMouseMove = (e) => this._onMouseMove.fire(e);
            viewUserInputEvents.onMouseLeave = (e) => this._onMouseLeave.fire(e);
            viewUserInputEvents.onMouseDown = (e) => this._onMouseDown.fire(e);
            viewUserInputEvents.onMouseUp = (e) => this._onMouseUp.fire(e);
            viewUserInputEvents.onMouseDrag = (e) => this._onMouseDrag.fire(e);
            viewUserInputEvents.onMouseDrop = (e) => this._onMouseDrop.fire(e);
            viewUserInputEvents.onMouseDropCanceled = (e) => this._onMouseDropCanceled.fire(e);
            viewUserInputEvents.onMouseWheel = (e) => this._onMouseWheel.fire(e);
            const view = new view_1.View(commandDelegate, this._configuration, this._themeService.getColorTheme(), viewModel, viewUserInputEvents, this._overflowWidgetsDomNode, this._instantiationService);
            return [view, true];
        }
        _postDetachModelCleanup(detachedModel) {
            detachedModel?.removeAllDecorationsWithOwnerId(this._id);
        }
        _detachModel() {
            this._contributionsDisposable?.dispose();
            this._contributionsDisposable = undefined;
            if (!this._modelData) {
                return null;
            }
            const model = this._modelData.model;
            const removeDomNode = this._modelData.hasRealView ? this._modelData.view.domNode.domNode : null;
            this._modelData.dispose();
            this._modelData = null;
            this._domElement.removeAttribute('data-mode-id');
            if (removeDomNode && this._domElement.contains(removeDomNode)) {
                removeDomNode.remove();
            }
            if (this._bannerDomNode && this._domElement.contains(this._bannerDomNode)) {
                this._bannerDomNode.remove();
            }
            return model;
        }
        _removeDecorationType(key) {
            this._codeEditorService.removeDecorationType(key);
        }
        hasModel() {
            return (this._modelData !== null);
        }
        showDropIndicatorAt(position) {
            const newDecorations = [{
                    range: new range_1.Range(position.lineNumber, position.column, position.lineNumber, position.column),
                    options: CodeEditorWidget_1.dropIntoEditorDecorationOptions
                }];
            this._dropIntoEditorDecorations.set(newDecorations);
            this.revealPosition(position, 1 /* editorCommon.ScrollType.Immediate */);
        }
        removeDropIndicator() {
            this._dropIntoEditorDecorations.clear();
        }
        setContextValue(key, value) {
            this._contextKeyService.createKey(key, value);
        }
        _beginUpdate() {
            this._updateCounter++;
            if (this._updateCounter === 1) {
                this._onBeginUpdate.fire();
            }
        }
        _endUpdate() {
            this._updateCounter--;
            if (this._updateCounter === 0) {
                this._onEndUpdate.fire();
            }
        }
    };
    exports.CodeEditorWidget = CodeEditorWidget;
    exports.CodeEditorWidget = CodeEditorWidget = CodeEditorWidget_1 = __decorate([
        __param(3, instantiation_1.IInstantiationService),
        __param(4, codeEditorService_1.ICodeEditorService),
        __param(5, commands_1.ICommandService),
        __param(6, contextkey_1.IContextKeyService),
        __param(7, themeService_1.IThemeService),
        __param(8, notification_1.INotificationService),
        __param(9, accessibility_1.IAccessibilityService),
        __param(10, languageConfigurationRegistry_1.ILanguageConfigurationService),
        __param(11, languageFeatures_1.ILanguageFeaturesService)
    ], CodeEditorWidget);
    let EDITOR_ID = 0;
    class ModelData {
        constructor(model, viewModel, view, hasRealView, listenersToRemove, attachedView) {
            this.model = model;
            this.viewModel = viewModel;
            this.view = view;
            this.hasRealView = hasRealView;
            this.listenersToRemove = listenersToRemove;
            this.attachedView = attachedView;
        }
        dispose() {
            (0, lifecycle_1.dispose)(this.listenersToRemove);
            this.model.onBeforeDetached(this.attachedView);
            if (this.hasRealView) {
                this.view.dispose();
            }
            this.viewModel.dispose();
        }
    }
    class BooleanEventEmitter extends lifecycle_1.Disposable {
        constructor(_emitterOptions) {
            super();
            this._emitterOptions = _emitterOptions;
            this._onDidChangeToTrue = this._register(new event_1.Emitter(this._emitterOptions));
            this.onDidChangeToTrue = this._onDidChangeToTrue.event;
            this._onDidChangeToFalse = this._register(new event_1.Emitter(this._emitterOptions));
            this.onDidChangeToFalse = this._onDidChangeToFalse.event;
            this._value = 0 /* BooleanEventValue.NotSet */;
        }
        setValue(_value) {
            const value = (_value ? 2 /* BooleanEventValue.True */ : 1 /* BooleanEventValue.False */);
            if (this._value === value) {
                return;
            }
            this._value = value;
            if (this._value === 2 /* BooleanEventValue.True */) {
                this._onDidChangeToTrue.fire();
            }
            else if (this._value === 1 /* BooleanEventValue.False */) {
                this._onDidChangeToFalse.fire();
            }
        }
    }
    exports.BooleanEventEmitter = BooleanEventEmitter;
    /**
     * A regular event emitter that also makes sure contributions are instantiated if necessary
     */
    class InteractionEmitter extends event_1.Emitter {
        constructor(_contributions, deliveryQueue) {
            super({ deliveryQueue });
            this._contributions = _contributions;
        }
        fire(event) {
            this._contributions.onBeforeInteractionEvent();
            super.fire(event);
        }
    }
    class EditorContextKeysManager extends lifecycle_1.Disposable {
        constructor(editor, contextKeyService) {
            super();
            this._editor = editor;
            contextKeyService.createKey('editorId', editor.getId());
            this._editorSimpleInput = editorContextKeys_1.EditorContextKeys.editorSimpleInput.bindTo(contextKeyService);
            this._editorFocus = editorContextKeys_1.EditorContextKeys.focus.bindTo(contextKeyService);
            this._textInputFocus = editorContextKeys_1.EditorContextKeys.textInputFocus.bindTo(contextKeyService);
            this._editorTextFocus = editorContextKeys_1.EditorContextKeys.editorTextFocus.bindTo(contextKeyService);
            this._tabMovesFocus = editorContextKeys_1.EditorContextKeys.tabMovesFocus.bindTo(contextKeyService);
            this._editorReadonly = editorContextKeys_1.EditorContextKeys.readOnly.bindTo(contextKeyService);
            this._inDiffEditor = editorContextKeys_1.EditorContextKeys.inDiffEditor.bindTo(contextKeyService);
            this._editorColumnSelection = editorContextKeys_1.EditorContextKeys.columnSelection.bindTo(contextKeyService);
            this._hasMultipleSelections = editorContextKeys_1.EditorContextKeys.hasMultipleSelections.bindTo(contextKeyService);
            this._hasNonEmptySelection = editorContextKeys_1.EditorContextKeys.hasNonEmptySelection.bindTo(contextKeyService);
            this._canUndo = editorContextKeys_1.EditorContextKeys.canUndo.bindTo(contextKeyService);
            this._canRedo = editorContextKeys_1.EditorContextKeys.canRedo.bindTo(contextKeyService);
            this._register(this._editor.onDidChangeConfiguration(() => this._updateFromConfig()));
            this._register(this._editor.onDidChangeCursorSelection(() => this._updateFromSelection()));
            this._register(this._editor.onDidFocusEditorWidget(() => this._updateFromFocus()));
            this._register(this._editor.onDidBlurEditorWidget(() => this._updateFromFocus()));
            this._register(this._editor.onDidFocusEditorText(() => this._updateFromFocus()));
            this._register(this._editor.onDidBlurEditorText(() => this._updateFromFocus()));
            this._register(this._editor.onDidChangeModel(() => this._updateFromModel()));
            this._register(this._editor.onDidChangeConfiguration(() => this._updateFromModel()));
            this._register(tabFocus_1.TabFocus.onDidChangeTabFocus((tabFocusMode) => this._tabMovesFocus.set(tabFocusMode)));
            this._updateFromConfig();
            this._updateFromSelection();
            this._updateFromFocus();
            this._updateFromModel();
            this._editorSimpleInput.set(this._editor.isSimpleWidget);
        }
        _updateFromConfig() {
            const options = this._editor.getOptions();
            this._tabMovesFocus.set(tabFocus_1.TabFocus.getTabFocusMode());
            this._editorReadonly.set(options.get(92 /* EditorOption.readOnly */));
            this._inDiffEditor.set(options.get(61 /* EditorOption.inDiffEditor */));
            this._editorColumnSelection.set(options.get(22 /* EditorOption.columnSelection */));
        }
        _updateFromSelection() {
            const selections = this._editor.getSelections();
            if (!selections) {
                this._hasMultipleSelections.reset();
                this._hasNonEmptySelection.reset();
            }
            else {
                this._hasMultipleSelections.set(selections.length > 1);
                this._hasNonEmptySelection.set(selections.some(s => !s.isEmpty()));
            }
        }
        _updateFromFocus() {
            this._editorFocus.set(this._editor.hasWidgetFocus() && !this._editor.isSimpleWidget);
            this._editorTextFocus.set(this._editor.hasTextFocus() && !this._editor.isSimpleWidget);
            this._textInputFocus.set(this._editor.hasTextFocus());
        }
        _updateFromModel() {
            const model = this._editor.getModel();
            this._canUndo.set(Boolean(model && model.canUndo()));
            this._canRedo.set(Boolean(model && model.canRedo()));
        }
    }
    class EditorModeContext extends lifecycle_1.Disposable {
        constructor(_editor, _contextKeyService, _languageFeaturesService) {
            super();
            this._editor = _editor;
            this._contextKeyService = _contextKeyService;
            this._languageFeaturesService = _languageFeaturesService;
            this._langId = editorContextKeys_1.EditorContextKeys.languageId.bindTo(_contextKeyService);
            this._hasCompletionItemProvider = editorContextKeys_1.EditorContextKeys.hasCompletionItemProvider.bindTo(_contextKeyService);
            this._hasCodeActionsProvider = editorContextKeys_1.EditorContextKeys.hasCodeActionsProvider.bindTo(_contextKeyService);
            this._hasCodeLensProvider = editorContextKeys_1.EditorContextKeys.hasCodeLensProvider.bindTo(_contextKeyService);
            this._hasDefinitionProvider = editorContextKeys_1.EditorContextKeys.hasDefinitionProvider.bindTo(_contextKeyService);
            this._hasDeclarationProvider = editorContextKeys_1.EditorContextKeys.hasDeclarationProvider.bindTo(_contextKeyService);
            this._hasImplementationProvider = editorContextKeys_1.EditorContextKeys.hasImplementationProvider.bindTo(_contextKeyService);
            this._hasTypeDefinitionProvider = editorContextKeys_1.EditorContextKeys.hasTypeDefinitionProvider.bindTo(_contextKeyService);
            this._hasHoverProvider = editorContextKeys_1.EditorContextKeys.hasHoverProvider.bindTo(_contextKeyService);
            this._hasDocumentHighlightProvider = editorContextKeys_1.EditorContextKeys.hasDocumentHighlightProvider.bindTo(_contextKeyService);
            this._hasDocumentSymbolProvider = editorContextKeys_1.EditorContextKeys.hasDocumentSymbolProvider.bindTo(_contextKeyService);
            this._hasReferenceProvider = editorContextKeys_1.EditorContextKeys.hasReferenceProvider.bindTo(_contextKeyService);
            this._hasRenameProvider = editorContextKeys_1.EditorContextKeys.hasRenameProvider.bindTo(_contextKeyService);
            this._hasSignatureHelpProvider = editorContextKeys_1.EditorContextKeys.hasSignatureHelpProvider.bindTo(_contextKeyService);
            this._hasInlayHintsProvider = editorContextKeys_1.EditorContextKeys.hasInlayHintsProvider.bindTo(_contextKeyService);
            this._hasDocumentFormattingProvider = editorContextKeys_1.EditorContextKeys.hasDocumentFormattingProvider.bindTo(_contextKeyService);
            this._hasDocumentSelectionFormattingProvider = editorContextKeys_1.EditorContextKeys.hasDocumentSelectionFormattingProvider.bindTo(_contextKeyService);
            this._hasMultipleDocumentFormattingProvider = editorContextKeys_1.EditorContextKeys.hasMultipleDocumentFormattingProvider.bindTo(_contextKeyService);
            this._hasMultipleDocumentSelectionFormattingProvider = editorContextKeys_1.EditorContextKeys.hasMultipleDocumentSelectionFormattingProvider.bindTo(_contextKeyService);
            this._isInEmbeddedEditor = editorContextKeys_1.EditorContextKeys.isInEmbeddedEditor.bindTo(_contextKeyService);
            const update = () => this._update();
            // update when model/mode changes
            this._register(_editor.onDidChangeModel(update));
            this._register(_editor.onDidChangeModelLanguage(update));
            // update when registries change
            this._register(_languageFeaturesService.completionProvider.onDidChange(update));
            this._register(_languageFeaturesService.codeActionProvider.onDidChange(update));
            this._register(_languageFeaturesService.codeLensProvider.onDidChange(update));
            this._register(_languageFeaturesService.definitionProvider.onDidChange(update));
            this._register(_languageFeaturesService.declarationProvider.onDidChange(update));
            this._register(_languageFeaturesService.implementationProvider.onDidChange(update));
            this._register(_languageFeaturesService.typeDefinitionProvider.onDidChange(update));
            this._register(_languageFeaturesService.hoverProvider.onDidChange(update));
            this._register(_languageFeaturesService.documentHighlightProvider.onDidChange(update));
            this._register(_languageFeaturesService.documentSymbolProvider.onDidChange(update));
            this._register(_languageFeaturesService.referenceProvider.onDidChange(update));
            this._register(_languageFeaturesService.renameProvider.onDidChange(update));
            this._register(_languageFeaturesService.documentFormattingEditProvider.onDidChange(update));
            this._register(_languageFeaturesService.documentRangeFormattingEditProvider.onDidChange(update));
            this._register(_languageFeaturesService.signatureHelpProvider.onDidChange(update));
            this._register(_languageFeaturesService.inlayHintsProvider.onDidChange(update));
            update();
        }
        dispose() {
            super.dispose();
        }
        reset() {
            this._contextKeyService.bufferChangeEvents(() => {
                this._langId.reset();
                this._hasCompletionItemProvider.reset();
                this._hasCodeActionsProvider.reset();
                this._hasCodeLensProvider.reset();
                this._hasDefinitionProvider.reset();
                this._hasDeclarationProvider.reset();
                this._hasImplementationProvider.reset();
                this._hasTypeDefinitionProvider.reset();
                this._hasHoverProvider.reset();
                this._hasDocumentHighlightProvider.reset();
                this._hasDocumentSymbolProvider.reset();
                this._hasReferenceProvider.reset();
                this._hasRenameProvider.reset();
                this._hasDocumentFormattingProvider.reset();
                this._hasDocumentSelectionFormattingProvider.reset();
                this._hasSignatureHelpProvider.reset();
                this._isInEmbeddedEditor.reset();
            });
        }
        _update() {
            const model = this._editor.getModel();
            if (!model) {
                this.reset();
                return;
            }
            this._contextKeyService.bufferChangeEvents(() => {
                this._langId.set(model.getLanguageId());
                this._hasCompletionItemProvider.set(this._languageFeaturesService.completionProvider.has(model));
                this._hasCodeActionsProvider.set(this._languageFeaturesService.codeActionProvider.has(model));
                this._hasCodeLensProvider.set(this._languageFeaturesService.codeLensProvider.has(model));
                this._hasDefinitionProvider.set(this._languageFeaturesService.definitionProvider.has(model));
                this._hasDeclarationProvider.set(this._languageFeaturesService.declarationProvider.has(model));
                this._hasImplementationProvider.set(this._languageFeaturesService.implementationProvider.has(model));
                this._hasTypeDefinitionProvider.set(this._languageFeaturesService.typeDefinitionProvider.has(model));
                this._hasHoverProvider.set(this._languageFeaturesService.hoverProvider.has(model));
                this._hasDocumentHighlightProvider.set(this._languageFeaturesService.documentHighlightProvider.has(model));
                this._hasDocumentSymbolProvider.set(this._languageFeaturesService.documentSymbolProvider.has(model));
                this._hasReferenceProvider.set(this._languageFeaturesService.referenceProvider.has(model));
                this._hasRenameProvider.set(this._languageFeaturesService.renameProvider.has(model));
                this._hasSignatureHelpProvider.set(this._languageFeaturesService.signatureHelpProvider.has(model));
                this._hasInlayHintsProvider.set(this._languageFeaturesService.inlayHintsProvider.has(model));
                this._hasDocumentFormattingProvider.set(this._languageFeaturesService.documentFormattingEditProvider.has(model) || this._languageFeaturesService.documentRangeFormattingEditProvider.has(model));
                this._hasDocumentSelectionFormattingProvider.set(this._languageFeaturesService.documentRangeFormattingEditProvider.has(model));
                this._hasMultipleDocumentFormattingProvider.set(this._languageFeaturesService.documentFormattingEditProvider.all(model).length + this._languageFeaturesService.documentRangeFormattingEditProvider.all(model).length > 1);
                this._hasMultipleDocumentSelectionFormattingProvider.set(this._languageFeaturesService.documentRangeFormattingEditProvider.all(model).length > 1);
                this._isInEmbeddedEditor.set(model.uri.scheme === network_1.Schemas.walkThroughSnippet || model.uri.scheme === network_1.Schemas.vscodeChatCodeBlock);
            });
        }
    }
    exports.EditorModeContext = EditorModeContext;
    class CodeEditorWidgetFocusTracker extends lifecycle_1.Disposable {
        constructor(domElement, overflowWidgetsDomNode) {
            super();
            this._onChange = this._register(new event_1.Emitter());
            this.onChange = this._onChange.event;
            this._hadFocus = undefined;
            this._hasDomElementFocus = false;
            this._domFocusTracker = this._register(dom.trackFocus(domElement));
            this._overflowWidgetsDomNodeHasFocus = false;
            this._register(this._domFocusTracker.onDidFocus(() => {
                this._hasDomElementFocus = true;
                this._update();
            }));
            this._register(this._domFocusTracker.onDidBlur(() => {
                this._hasDomElementFocus = false;
                this._update();
            }));
            if (overflowWidgetsDomNode) {
                this._overflowWidgetsDomNode = this._register(dom.trackFocus(overflowWidgetsDomNode));
                this._register(this._overflowWidgetsDomNode.onDidFocus(() => {
                    this._overflowWidgetsDomNodeHasFocus = true;
                    this._update();
                }));
                this._register(this._overflowWidgetsDomNode.onDidBlur(() => {
                    this._overflowWidgetsDomNodeHasFocus = false;
                    this._update();
                }));
            }
        }
        _update() {
            const focused = this._hasDomElementFocus || this._overflowWidgetsDomNodeHasFocus;
            if (this._hadFocus !== focused) {
                this._hadFocus = focused;
                this._onChange.fire(undefined);
            }
        }
        hasFocus() {
            return this._hadFocus ?? false;
        }
    }
    class EditorDecorationsCollection {
        get length() {
            return this._decorationIds.length;
        }
        constructor(_editor, decorations) {
            this._editor = _editor;
            this._decorationIds = [];
            this._isChangingDecorations = false;
            if (Array.isArray(decorations) && decorations.length > 0) {
                this.set(decorations);
            }
        }
        onDidChange(listener, thisArgs, disposables) {
            return this._editor.onDidChangeModelDecorations((e) => {
                if (this._isChangingDecorations) {
                    return;
                }
                listener.call(thisArgs, e);
            }, disposables);
        }
        getRange(index) {
            if (!this._editor.hasModel()) {
                return null;
            }
            if (index >= this._decorationIds.length) {
                return null;
            }
            return this._editor.getModel().getDecorationRange(this._decorationIds[index]);
        }
        getRanges() {
            if (!this._editor.hasModel()) {
                return [];
            }
            const model = this._editor.getModel();
            const result = [];
            for (const decorationId of this._decorationIds) {
                const range = model.getDecorationRange(decorationId);
                if (range) {
                    result.push(range);
                }
            }
            return result;
        }
        has(decoration) {
            return this._decorationIds.includes(decoration.id);
        }
        clear() {
            if (this._decorationIds.length === 0) {
                // nothing to do
                return;
            }
            this.set([]);
        }
        set(newDecorations) {
            try {
                this._isChangingDecorations = true;
                this._editor.changeDecorations((accessor) => {
                    this._decorationIds = accessor.deltaDecorations(this._decorationIds, newDecorations);
                });
            }
            finally {
                this._isChangingDecorations = false;
            }
            return this._decorationIds;
        }
        append(newDecorations) {
            let newDecorationIds = [];
            try {
                this._isChangingDecorations = true;
                this._editor.changeDecorations((accessor) => {
                    newDecorationIds = accessor.deltaDecorations([], newDecorations);
                    this._decorationIds = this._decorationIds.concat(newDecorationIds);
                });
            }
            finally {
                this._isChangingDecorations = false;
            }
            return newDecorationIds;
        }
    }
    const squigglyStart = encodeURIComponent(`<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 6 3' enable-background='new 0 0 6 3' height='3' width='6'><g fill='`);
    const squigglyEnd = encodeURIComponent(`'><polygon points='5.5,0 2.5,3 1.1,3 4.1,0'/><polygon points='4,0 6,2 6,0.6 5.4,0'/><polygon points='0,2 1,3 2.4,3 0,0.6'/></g></svg>`);
    function getSquigglySVGData(color) {
        return squigglyStart + encodeURIComponent(color.toString()) + squigglyEnd;
    }
    const dotdotdotStart = encodeURIComponent(`<svg xmlns="http://www.w3.org/2000/svg" height="3" width="12"><g fill="`);
    const dotdotdotEnd = encodeURIComponent(`"><circle cx="1" cy="1" r="1"/><circle cx="5" cy="1" r="1"/><circle cx="9" cy="1" r="1"/></g></svg>`);
    function getDotDotDotSVGData(color) {
        return dotdotdotStart + encodeURIComponent(color.toString()) + dotdotdotEnd;
    }
    (0, themeService_1.registerThemingParticipant)((theme, collector) => {
        const errorForeground = theme.getColor(colorRegistry_1.editorErrorForeground);
        if (errorForeground) {
            collector.addRule(`.monaco-editor .${"squiggly-error" /* ClassName.EditorErrorDecoration */} { background: url("data:image/svg+xml,${getSquigglySVGData(errorForeground)}") repeat-x bottom left; }`);
        }
        const warningForeground = theme.getColor(colorRegistry_1.editorWarningForeground);
        if (warningForeground) {
            collector.addRule(`.monaco-editor .${"squiggly-warning" /* ClassName.EditorWarningDecoration */} { background: url("data:image/svg+xml,${getSquigglySVGData(warningForeground)}") repeat-x bottom left; }`);
        }
        const infoForeground = theme.getColor(colorRegistry_1.editorInfoForeground);
        if (infoForeground) {
            collector.addRule(`.monaco-editor .${"squiggly-info" /* ClassName.EditorInfoDecoration */} { background: url("data:image/svg+xml,${getSquigglySVGData(infoForeground)}") repeat-x bottom left; }`);
        }
        const hintForeground = theme.getColor(colorRegistry_1.editorHintForeground);
        if (hintForeground) {
            collector.addRule(`.monaco-editor .${"squiggly-hint" /* ClassName.EditorHintDecoration */} { background: url("data:image/svg+xml,${getDotDotDotSVGData(hintForeground)}") no-repeat bottom left; }`);
        }
        const unnecessaryForeground = theme.getColor(editorColorRegistry_1.editorUnnecessaryCodeOpacity);
        if (unnecessaryForeground) {
            collector.addRule(`.monaco-editor.showUnused .${"squiggly-inline-unnecessary" /* ClassName.EditorUnnecessaryInlineDecoration */} { opacity: ${unnecessaryForeground.rgba.a}; }`);
        }
    });
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[125/*vs/editor/browser/widget/codeEditor/embeddedCodeEditorWidget*/], __M([1/*require*/,0/*exports*/,60/*vs/base/common/objects*/,34/*vs/editor/browser/services/codeEditorService*/,219/*vs/editor/browser/widget/codeEditor/codeEditorWidget*/,36/*vs/editor/common/languages/languageConfigurationRegistry*/,17/*vs/editor/common/services/languageFeatures*/,61/*vs/platform/accessibility/common/accessibility*/,24/*vs/platform/commands/common/commands*/,12/*vs/platform/contextkey/common/contextkey*/,7/*vs/platform/instantiation/common/instantiation*/,50/*vs/platform/notification/common/notification*/,25/*vs/platform/theme/common/themeService*/]), function (require, exports, objects, codeEditorService_1, codeEditorWidget_1, languageConfigurationRegistry_1, languageFeatures_1, accessibility_1, commands_1, contextkey_1, instantiation_1, notification_1, themeService_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.EmbeddedCodeEditorWidget = void 0;
    let EmbeddedCodeEditorWidget = class EmbeddedCodeEditorWidget extends codeEditorWidget_1.CodeEditorWidget {
        constructor(domElement, options, codeEditorWidgetOptions, parentEditor, instantiationService, codeEditorService, commandService, contextKeyService, themeService, notificationService, accessibilityService, languageConfigurationService, languageFeaturesService) {
            super(domElement, { ...parentEditor.getRawOptions(), overflowWidgetsDomNode: parentEditor.getOverflowWidgetsDomNode() }, codeEditorWidgetOptions, instantiationService, codeEditorService, commandService, contextKeyService, themeService, notificationService, accessibilityService, languageConfigurationService, languageFeaturesService);
            this._parentEditor = parentEditor;
            this._overwriteOptions = options;
            // Overwrite parent's options
            super.updateOptions(this._overwriteOptions);
            this._register(parentEditor.onDidChangeConfiguration((e) => this._onParentConfigurationChanged(e)));
        }
        getParentEditor() {
            return this._parentEditor;
        }
        _onParentConfigurationChanged(e) {
            super.updateOptions(this._parentEditor.getRawOptions());
            super.updateOptions(this._overwriteOptions);
        }
        updateOptions(newOptions) {
            objects.mixin(this._overwriteOptions, newOptions, true);
            super.updateOptions(this._overwriteOptions);
        }
    };
    exports.EmbeddedCodeEditorWidget = EmbeddedCodeEditorWidget;
    exports.EmbeddedCodeEditorWidget = EmbeddedCodeEditorWidget = __decorate([
        __param(4, instantiation_1.IInstantiationService),
        __param(5, codeEditorService_1.ICodeEditorService),
        __param(6, commands_1.ICommandService),
        __param(7, contextkey_1.IContextKeyService),
        __param(8, themeService_1.IThemeService),
        __param(9, notification_1.INotificationService),
        __param(10, accessibility_1.IAccessibilityService),
        __param(11, languageConfigurationRegistry_1.ILanguageConfigurationService),
        __param(12, languageFeatures_1.ILanguageFeaturesService)
    ], EmbeddedCodeEditorWidget);
});










define(__m[286/*vs/editor/browser/widget/diffEditor/diffEditorWidget*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,67/*vs/base/common/arraysFind*/,8/*vs/base/common/errors*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,21/*vs/base/common/observable*/,65/*vs/base/common/observableInternal/derived*/,15/*vs/editor/browser/editorExtensions*/,34/*vs/editor/browser/services/codeEditorService*/,143/*vs/editor/browser/stableEditorScroll*/,219/*vs/editor/browser/widget/codeEditor/codeEditorWidget*/,762/*vs/editor/browser/widget/diffEditor/components/accessibleDiffViewer*/,806/*vs/editor/browser/widget/diffEditor/components/diffEditorDecorations*/,363/*vs/editor/browser/widget/diffEditor/components/diffEditorSash*/,285/*vs/editor/browser/widget/diffEditor/components/diffEditorViewZones/diffEditorViewZones*/,799/*vs/editor/browser/widget/diffEditor/features/gutterFeature*/,383/*vs/editor/browser/widget/diffEditor/features/hideUnchangedRegionsFeature*/,364/*vs/editor/browser/widget/diffEditor/features/movedBlocksLinesFeature*/,415/*vs/editor/browser/widget/diffEditor/features/overviewRulerFeature*/,653/*vs/editor/browser/widget/diffEditor/features/revertButtonsFeature*/,88/*vs/editor/browser/widget/diffEditor/utils*/,171/*vs/base/common/hotReloadHelpers*/,397/*vs/platform/observable/common/platformObservableUtils*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/,198/*vs/editor/common/editorCommon*/,20/*vs/editor/common/editorContextKeys*/,137/*vs/platform/accessibilitySignal/browser/accessibilitySignalService*/,12/*vs/platform/contextkey/common/contextkey*/,7/*vs/platform/instantiation/common/instantiation*/,154/*vs/platform/instantiation/common/serviceCollection*/,96/*vs/platform/progress/common/progress*/,775/*vs/editor/browser/widget/diffEditor/components/diffEditorEditors*/,552/*vs/editor/browser/widget/diffEditor/delegatingEditorImpl*/,807/*vs/editor/browser/widget/diffEditor/diffEditorOptions*/,407/*vs/editor/browser/widget/diffEditor/diffEditorViewModel*/,500/*vs/css!vs/editor/browser/widget/diffEditor/style*/]), function (require, exports, dom_1, arraysFind_1, errors_1, event_1, lifecycle_1, observable_1, derived_1, editorExtensions_1, codeEditorService_1, stableEditorScroll_1, codeEditorWidget_1, accessibleDiffViewer_1, diffEditorDecorations_1, diffEditorSash_1, diffEditorViewZones_1, gutterFeature_1, hideUnchangedRegionsFeature_1, movedBlocksLinesFeature_1, overviewRulerFeature_1, revertButtonsFeature_1, utils_1, hotReloadHelpers_1, platformObservableUtils_1, position_1, range_1, editorCommon_1, editorContextKeys_1, accessibilitySignalService_1, contextkey_1, instantiation_1, serviceCollection_1, progress_1, diffEditorEditors_1, delegatingEditorImpl_1, diffEditorOptions_1, diffEditorViewModel_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DiffEditorWidget = void 0;
    let DiffEditorWidget = class DiffEditorWidget extends delegatingEditorImpl_1.DelegatingEditor {
        get onDidContentSizeChange() { return this._editors.onDidContentSizeChange; }
        constructor(_domElement, options, codeEditorWidgetOptions, _parentContextKeyService, _parentInstantiationService, codeEditorService, _accessibilitySignalService, _editorProgressService) {
            super();
            this._domElement = _domElement;
            this._parentContextKeyService = _parentContextKeyService;
            this._parentInstantiationService = _parentInstantiationService;
            this._accessibilitySignalService = _accessibilitySignalService;
            this._editorProgressService = _editorProgressService;
            this.elements = (0, dom_1.h)('div.monaco-diff-editor.side-by-side', { style: { position: 'relative', height: '100%' } }, [
                (0, dom_1.h)('div.editor.original@original', { style: { position: 'absolute', height: '100%', } }),
                (0, dom_1.h)('div.editor.modified@modified', { style: { position: 'absolute', height: '100%', } }),
                (0, dom_1.h)('div.accessibleDiffViewer@accessibleDiffViewer', { style: { position: 'absolute', height: '100%' } }),
            ]);
            this._diffModelSrc = this._register((0, observable_1.disposableObservableValue)(this, undefined));
            this._diffModel = (0, observable_1.derived)(this, reader => this._diffModelSrc.read(reader)?.object);
            this.onDidChangeModel = event_1.Event.fromObservableLight(this._diffModel);
            this._contextKeyService = this._register(this._parentContextKeyService.createScoped(this._domElement));
            this._instantiationService = this._register(this._parentInstantiationService.createChild(new serviceCollection_1.ServiceCollection([contextkey_1.IContextKeyService, this._contextKeyService])));
            this._boundarySashes = (0, observable_1.observableValue)(this, undefined);
            this._accessibleDiffViewerShouldBeVisible = (0, observable_1.observableValue)(this, false);
            this._accessibleDiffViewerVisible = (0, observable_1.derived)(this, reader => this._options.onlyShowAccessibleDiffViewer.read(reader)
                ? true
                : this._accessibleDiffViewerShouldBeVisible.read(reader));
            this._movedBlocksLinesPart = (0, observable_1.observableValue)(this, undefined);
            this._layoutInfo = (0, observable_1.derived)(this, reader => {
                const fullWidth = this._rootSizeObserver.width.read(reader);
                const fullHeight = this._rootSizeObserver.height.read(reader);
                if (this._rootSizeObserver.automaticLayout) {
                    this.elements.root.style.height = '100%';
                }
                else {
                    this.elements.root.style.height = fullHeight + 'px';
                }
                const sash = this._sash.read(reader);
                const gutter = this._gutter.read(reader);
                const gutterWidth = gutter?.width.read(reader) ?? 0;
                const overviewRulerPartWidth = this._overviewRulerPart.read(reader)?.width ?? 0;
                let originalLeft, originalWidth, modifiedLeft, modifiedWidth, gutterLeft;
                const sideBySide = !!sash;
                if (sideBySide) {
                    const sashLeft = sash.sashLeft.read(reader);
                    const movedBlocksLinesWidth = this._movedBlocksLinesPart.read(reader)?.width.read(reader) ?? 0;
                    originalLeft = 0;
                    originalWidth = sashLeft - gutterWidth - movedBlocksLinesWidth;
                    gutterLeft = sashLeft - gutterWidth;
                    modifiedLeft = sashLeft;
                    modifiedWidth = fullWidth - modifiedLeft - overviewRulerPartWidth;
                }
                else {
                    gutterLeft = 0;
                    const shouldHideOriginalLineNumbers = this._options.inlineViewHideOriginalLineNumbers.read(reader);
                    originalLeft = gutterWidth;
                    if (shouldHideOriginalLineNumbers) {
                        originalWidth = 0;
                    }
                    else {
                        originalWidth = Math.max(5, this._editors.originalObs.layoutInfoDecorationsLeft.read(reader));
                    }
                    modifiedLeft = gutterWidth + originalWidth;
                    modifiedWidth = fullWidth - modifiedLeft - overviewRulerPartWidth;
                }
                this.elements.original.style.left = originalLeft + 'px';
                this.elements.original.style.width = originalWidth + 'px';
                this._editors.original.layout({ width: originalWidth, height: fullHeight }, true);
                gutter?.layout(gutterLeft);
                this.elements.modified.style.left = modifiedLeft + 'px';
                this.elements.modified.style.width = modifiedWidth + 'px';
                this._editors.modified.layout({ width: modifiedWidth, height: fullHeight }, true);
                return {
                    modifiedEditor: this._editors.modified.getLayoutInfo(),
                    originalEditor: this._editors.original.getLayoutInfo(),
                };
            });
            this._diffValue = this._diffModel.map((m, r) => m?.diff.read(r));
            this.onDidUpdateDiff = event_1.Event.fromObservableLight(this._diffValue);
            codeEditorService.willCreateDiffEditor();
            this._contextKeyService.createKey('isInDiffEditor', true);
            this._domElement.appendChild(this.elements.root);
            this._register((0, lifecycle_1.toDisposable)(() => this.elements.root.remove()));
            this._rootSizeObserver = this._register(new utils_1.ObservableElementSizeObserver(this.elements.root, options.dimension));
            this._rootSizeObserver.setAutomaticLayout(options.automaticLayout ?? false);
            this._options = this._instantiationService.createInstance(diffEditorOptions_1.DiffEditorOptions, options);
            this._register((0, observable_1.autorun)(reader => {
                this._options.setWidth(this._rootSizeObserver.width.read(reader));
            }));
            this._contextKeyService.createKey(editorContextKeys_1.EditorContextKeys.isEmbeddedDiffEditor.key, false);
            this._register((0, platformObservableUtils_1.bindContextKey)(editorContextKeys_1.EditorContextKeys.isEmbeddedDiffEditor, this._contextKeyService, reader => this._options.isInEmbeddedEditor.read(reader)));
            this._register((0, platformObservableUtils_1.bindContextKey)(editorContextKeys_1.EditorContextKeys.comparingMovedCode, this._contextKeyService, reader => !!this._diffModel.read(reader)?.movedTextToCompare.read(reader)));
            this._register((0, platformObservableUtils_1.bindContextKey)(editorContextKeys_1.EditorContextKeys.diffEditorRenderSideBySideInlineBreakpointReached, this._contextKeyService, reader => this._options.couldShowInlineViewBecauseOfSize.read(reader)));
            this._register((0, platformObservableUtils_1.bindContextKey)(editorContextKeys_1.EditorContextKeys.diffEditorInlineMode, this._contextKeyService, reader => !this._options.renderSideBySide.read(reader)));
            this._register((0, platformObservableUtils_1.bindContextKey)(editorContextKeys_1.EditorContextKeys.hasChanges, this._contextKeyService, reader => (this._diffModel.read(reader)?.diff.read(reader)?.mappings.length ?? 0) > 0));
            this._editors = this._register(this._instantiationService.createInstance(diffEditorEditors_1.DiffEditorEditors, this.elements.original, this.elements.modified, this._options, codeEditorWidgetOptions, (i, c, o, o2) => this._createInnerEditor(i, c, o, o2)));
            this._register((0, platformObservableUtils_1.bindContextKey)(editorContextKeys_1.EditorContextKeys.diffEditorOriginalWritable, this._contextKeyService, reader => this._options.originalEditable.read(reader)));
            this._register((0, platformObservableUtils_1.bindContextKey)(editorContextKeys_1.EditorContextKeys.diffEditorModifiedWritable, this._contextKeyService, reader => !this._options.readOnly.read(reader)));
            this._register((0, platformObservableUtils_1.bindContextKey)(editorContextKeys_1.EditorContextKeys.diffEditorOriginalUri, this._contextKeyService, reader => this._diffModel.read(reader)?.model.original.uri.toString() ?? ''));
            this._register((0, platformObservableUtils_1.bindContextKey)(editorContextKeys_1.EditorContextKeys.diffEditorModifiedUri, this._contextKeyService, reader => this._diffModel.read(reader)?.model.modified.uri.toString() ?? ''));
            this._overviewRulerPart = (0, derived_1.derivedDisposable)(this, reader => !this._options.renderOverviewRuler.read(reader)
                ? undefined
                : this._instantiationService.createInstance((0, hotReloadHelpers_1.readHotReloadableExport)(overviewRulerFeature_1.OverviewRulerFeature, reader), this._editors, this.elements.root, this._diffModel, this._rootSizeObserver.width, this._rootSizeObserver.height, this._layoutInfo.map(i => i.modifiedEditor))).recomputeInitiallyAndOnChange(this._store);
            const dimensions = {
                height: this._rootSizeObserver.height,
                width: this._rootSizeObserver.width.map((w, reader) => w - (this._overviewRulerPart.read(reader)?.width ?? 0)),
            };
            this._sashLayout = new diffEditorSash_1.SashLayout(this._options, dimensions);
            this._sash = (0, derived_1.derivedDisposable)(this, reader => {
                const showSash = this._options.renderSideBySide.read(reader);
                this.elements.root.classList.toggle('side-by-side', showSash);
                return !showSash ? undefined : new diffEditorSash_1.DiffEditorSash(this.elements.root, dimensions, this._options.enableSplitViewResizing, this._boundarySashes, this._sashLayout.sashLeft, () => this._sashLayout.resetSash());
            }).recomputeInitiallyAndOnChange(this._store);
            const unchangedRangesFeature = (0, derived_1.derivedDisposable)(this, reader => /** @description UnchangedRangesFeature */ this._instantiationService.createInstance((0, hotReloadHelpers_1.readHotReloadableExport)(hideUnchangedRegionsFeature_1.HideUnchangedRegionsFeature, reader), this._editors, this._diffModel, this._options)).recomputeInitiallyAndOnChange(this._store);
            (0, derived_1.derivedDisposable)(this, reader => /** @description DiffEditorDecorations */ this._instantiationService.createInstance((0, hotReloadHelpers_1.readHotReloadableExport)(diffEditorDecorations_1.DiffEditorDecorations, reader), this._editors, this._diffModel, this._options, this)).recomputeInitiallyAndOnChange(this._store);
            const origViewZoneIdsToIgnore = new Set();
            const modViewZoneIdsToIgnore = new Set();
            let isUpdatingViewZones = false;
            const viewZoneManager = (0, derived_1.derivedDisposable)(this, reader => /** @description ViewZoneManager */ this._instantiationService.createInstance((0, hotReloadHelpers_1.readHotReloadableExport)(diffEditorViewZones_1.DiffEditorViewZones, reader), (0, dom_1.getWindow)(this._domElement), this._editors, this._diffModel, this._options, this, () => isUpdatingViewZones || unchangedRangesFeature.get().isUpdatingHiddenAreas, origViewZoneIdsToIgnore, modViewZoneIdsToIgnore)).recomputeInitiallyAndOnChange(this._store);
            const originalViewZones = (0, observable_1.derived)(this, (reader) => {
                const orig = viewZoneManager.read(reader).viewZones.read(reader).orig;
                const orig2 = unchangedRangesFeature.read(reader).viewZones.read(reader).origViewZones;
                return orig.concat(orig2);
            });
            const modifiedViewZones = (0, observable_1.derived)(this, (reader) => {
                const mod = viewZoneManager.read(reader).viewZones.read(reader).mod;
                const mod2 = unchangedRangesFeature.read(reader).viewZones.read(reader).modViewZones;
                return mod.concat(mod2);
            });
            this._register((0, utils_1.applyViewZones)(this._editors.original, originalViewZones, isUpdatingOrigViewZones => {
                isUpdatingViewZones = isUpdatingOrigViewZones;
            }, origViewZoneIdsToIgnore));
            let scrollState;
            this._register((0, utils_1.applyViewZones)(this._editors.modified, modifiedViewZones, isUpdatingModViewZones => {
                isUpdatingViewZones = isUpdatingModViewZones;
                if (isUpdatingViewZones) {
                    scrollState = stableEditorScroll_1.StableEditorScrollState.capture(this._editors.modified);
                }
                else {
                    scrollState?.restore(this._editors.modified);
                    scrollState = undefined;
                }
            }, modViewZoneIdsToIgnore));
            this._accessibleDiffViewer = (0, derived_1.derivedDisposable)(this, reader => this._instantiationService.createInstance((0, hotReloadHelpers_1.readHotReloadableExport)(accessibleDiffViewer_1.AccessibleDiffViewer, reader), this.elements.accessibleDiffViewer, this._accessibleDiffViewerVisible, (visible, tx) => this._accessibleDiffViewerShouldBeVisible.set(visible, tx), this._options.onlyShowAccessibleDiffViewer.map(v => !v), this._rootSizeObserver.width, this._rootSizeObserver.height, this._diffModel.map((m, r) => m?.diff.read(r)?.mappings.map(m => m.lineRangeMapping)), new accessibleDiffViewer_1.AccessibleDiffViewerModelFromEditors(this._editors))).recomputeInitiallyAndOnChange(this._store);
            const visibility = this._accessibleDiffViewerVisible.map(v => v ? 'hidden' : 'visible');
            this._register((0, utils_1.applyStyle)(this.elements.modified, { visibility }));
            this._register((0, utils_1.applyStyle)(this.elements.original, { visibility }));
            this._createDiffEditorContributions();
            codeEditorService.addDiffEditor(this);
            this._gutter = (0, derived_1.derivedDisposable)(this, reader => {
                return this._options.shouldRenderGutterMenu.read(reader)
                    ? this._instantiationService.createInstance((0, hotReloadHelpers_1.readHotReloadableExport)(gutterFeature_1.DiffEditorGutter, reader), this.elements.root, this._diffModel, this._editors, this._options, this._sashLayout, this._boundarySashes)
                    : undefined;
            });
            this._register((0, observable_1.recomputeInitiallyAndOnChange)(this._layoutInfo));
            (0, derived_1.derivedDisposable)(this, reader => /** @description MovedBlocksLinesPart */ new ((0, hotReloadHelpers_1.readHotReloadableExport)(movedBlocksLinesFeature_1.MovedBlocksLinesFeature, reader))(this.elements.root, this._diffModel, this._layoutInfo.map(i => i.originalEditor), this._layoutInfo.map(i => i.modifiedEditor), this._editors)).recomputeInitiallyAndOnChange(this._store, value => {
                // This is to break the layout info <-> moved blocks lines part dependency cycle.
                this._movedBlocksLinesPart.set(value, undefined);
            });
            this._register(event_1.Event.runAndSubscribe(this._editors.modified.onDidChangeCursorPosition, e => this._handleCursorPositionChange(e, true)));
            this._register(event_1.Event.runAndSubscribe(this._editors.original.onDidChangeCursorPosition, e => this._handleCursorPositionChange(e, false)));
            const isInitializingDiff = this._diffModel.map(this, (m, reader) => {
                /** @isInitializingDiff isDiffUpToDate */
                if (!m) {
                    return undefined;
                }
                return m.diff.read(reader) === undefined && !m.isDiffUpToDate.read(reader);
            });
            this._register((0, observable_1.autorunWithStore)((reader, store) => {
                /** @description DiffEditorWidgetHelper.ShowProgress */
                if (isInitializingDiff.read(reader) === true) {
                    const r = this._editorProgressService.show(true, 1000);
                    store.add((0, lifecycle_1.toDisposable)(() => r.done()));
                }
            }));
            this._register((0, observable_1.autorunWithStore)((reader, store) => {
                store.add(new ((0, hotReloadHelpers_1.readHotReloadableExport)(revertButtonsFeature_1.RevertButtonsFeature, reader))(this._editors, this._diffModel, this._options, this));
            }));
            this._register((0, observable_1.autorunWithStore)((reader, store) => {
                const model = this._diffModel.read(reader);
                if (!model) {
                    return;
                }
                for (const m of [model.model.original, model.model.modified]) {
                    store.add(m.onWillDispose(e => {
                        (0, errors_1.onUnexpectedError)(new errors_1.BugIndicatingError('TextModel got disposed before DiffEditorWidget model got reset'));
                        this.setModel(null);
                    }));
                }
            }));
            this._register((0, observable_1.autorun)(reader => {
                this._options.setModel(this._diffModel.read(reader));
            }));
        }
        _createInnerEditor(instantiationService, container, options, editorWidgetOptions) {
            const editor = instantiationService.createInstance(codeEditorWidget_1.CodeEditorWidget, container, options, editorWidgetOptions);
            return editor;
        }
        _createDiffEditorContributions() {
            const contributions = editorExtensions_1.EditorExtensionsRegistry.getDiffEditorContributions();
            for (const desc of contributions) {
                try {
                    this._register(this._instantiationService.createInstance(desc.ctor, this));
                }
                catch (err) {
                    (0, errors_1.onUnexpectedError)(err);
                }
            }
        }
        get _targetEditor() { return this._editors.modified; }
        getEditorType() { return editorCommon_1.EditorType.IDiffEditor; }
        layout(dimension) {
            this._rootSizeObserver.observe(dimension);
        }
        hasTextFocus() { return this._editors.original.hasTextFocus() || this._editors.modified.hasTextFocus(); }
        saveViewState() {
            const originalViewState = this._editors.original.saveViewState();
            const modifiedViewState = this._editors.modified.saveViewState();
            return {
                original: originalViewState,
                modified: modifiedViewState,
                modelState: this._diffModel.get()?.serializeState(),
            };
        }
        restoreViewState(s) {
            if (s && s.original && s.modified) {
                const diffEditorState = s;
                this._editors.original.restoreViewState(diffEditorState.original);
                this._editors.modified.restoreViewState(diffEditorState.modified);
                if (diffEditorState.modelState) {
                    this._diffModel.get()?.restoreSerializedState(diffEditorState.modelState);
                }
            }
        }
        handleInitialized() {
            this._editors.original.handleInitialized();
            this._editors.modified.handleInitialized();
        }
        createViewModel(model) {
            return this._instantiationService.createInstance(diffEditorViewModel_1.DiffEditorViewModel, model, this._options);
        }
        getModel() { return this._diffModel.get()?.model ?? null; }
        setModel(model) {
            const vm = !model ? null
                : ('model' in model) ? utils_1.RefCounted.create(model).createNewRef(this)
                    : utils_1.RefCounted.create(this.createViewModel(model), this);
            this.setDiffModel(vm);
        }
        setDiffModel(viewModel, tx) {
            const currentModel = this._diffModel.get();
            if (!viewModel && currentModel) {
                // Transitioning from a model to no-model
                this._accessibleDiffViewer.get().close();
            }
            if (this._diffModel.get() !== viewModel?.object) {
                (0, observable_1.subtransaction)(tx, tx => {
                    const vm = viewModel?.object;
                    /** @description DiffEditorWidget.setModel */
                    observable_1.observableFromEvent.batchEventsGlobally(tx, () => {
                        this._editors.original.setModel(vm ? vm.model.original : null);
                        this._editors.modified.setModel(vm ? vm.model.modified : null);
                    });
                    const prevValueRef = this._diffModelSrc.get()?.createNewRef(this);
                    this._diffModelSrc.set(viewModel?.createNewRef(this), tx);
                    setTimeout(() => {
                        // async, so that this runs after the transaction finished.
                        // TODO: use the transaction to schedule disposal
                        prevValueRef?.dispose();
                    }, 0);
                });
            }
        }
        /**
         * @param changedOptions Only has values for top-level options that have actually changed.
         */
        updateOptions(changedOptions) {
            this._options.updateOptions(changedOptions);
        }
        getContainerDomNode() { return this._domElement; }
        getOriginalEditor() { return this._editors.original; }
        getModifiedEditor() { return this._editors.modified; }
        /**
         * @deprecated Use `this.getDiffComputationResult().changes2` instead.
         */
        getLineChanges() {
            const diffState = this._diffModel.get()?.diff.get();
            if (!diffState) {
                return null;
            }
            return toLineChanges(diffState);
        }
        revert(diff) {
            const model = this._diffModel.get();
            if (!model || !model.isDiffUpToDate.get()) {
                return;
            }
            this._editors.modified.executeEdits('diffEditor', [
                {
                    range: diff.modified.toExclusiveRange(),
                    text: model.model.original.getValueInRange(diff.original.toExclusiveRange())
                }
            ]);
        }
        revertRangeMappings(diffs) {
            const model = this._diffModel.get();
            if (!model || !model.isDiffUpToDate.get()) {
                return;
            }
            const changes = diffs.map(c => ({
                range: c.modifiedRange,
                text: model.model.original.getValueInRange(c.originalRange)
            }));
            this._editors.modified.executeEdits('diffEditor', changes);
        }
        _goTo(diff) {
            this._editors.modified.setPosition(new position_1.Position(diff.lineRangeMapping.modified.startLineNumber, 1));
            this._editors.modified.revealRangeInCenter(diff.lineRangeMapping.modified.toExclusiveRange());
        }
        goToDiff(target) {
            const diffs = this._diffModel.get()?.diff.get()?.mappings;
            if (!diffs || diffs.length === 0) {
                return;
            }
            const curLineNumber = this._editors.modified.getPosition().lineNumber;
            let diff;
            if (target === 'next') {
                diff = diffs.find(d => d.lineRangeMapping.modified.startLineNumber > curLineNumber) ?? diffs[0];
            }
            else {
                diff = (0, arraysFind_1.findLast)(diffs, d => d.lineRangeMapping.modified.startLineNumber < curLineNumber) ?? diffs[diffs.length - 1];
            }
            this._goTo(diff);
            if (diff.lineRangeMapping.modified.isEmpty) {
                this._accessibilitySignalService.playSignal(accessibilitySignalService_1.AccessibilitySignal.diffLineDeleted, { source: 'diffEditor.goToDiff' });
            }
            else if (diff.lineRangeMapping.original.isEmpty) {
                this._accessibilitySignalService.playSignal(accessibilitySignalService_1.AccessibilitySignal.diffLineInserted, { source: 'diffEditor.goToDiff' });
            }
            else if (diff) {
                this._accessibilitySignalService.playSignal(accessibilitySignalService_1.AccessibilitySignal.diffLineModified, { source: 'diffEditor.goToDiff' });
            }
        }
        revealFirstDiff() {
            const diffModel = this._diffModel.get();
            if (!diffModel) {
                return;
            }
            // wait for the diff computation to finish
            this.waitForDiff().then(() => {
                const diffs = diffModel.diff.get()?.mappings;
                if (!diffs || diffs.length === 0) {
                    return;
                }
                this._goTo(diffs[0]);
            });
        }
        accessibleDiffViewerNext() { this._accessibleDiffViewer.get().next(); }
        accessibleDiffViewerPrev() { this._accessibleDiffViewer.get().prev(); }
        async waitForDiff() {
            const diffModel = this._diffModel.get();
            if (!diffModel) {
                return;
            }
            await diffModel.waitForDiff();
        }
        mapToOtherSide() {
            const isModifiedFocus = this._editors.modified.hasWidgetFocus();
            const source = isModifiedFocus ? this._editors.modified : this._editors.original;
            const destination = isModifiedFocus ? this._editors.original : this._editors.modified;
            let destinationSelection;
            const sourceSelection = source.getSelection();
            if (sourceSelection) {
                const mappings = this._diffModel.get()?.diff.get()?.mappings.map(m => isModifiedFocus ? m.lineRangeMapping.flip() : m.lineRangeMapping);
                if (mappings) {
                    const newRange1 = (0, utils_1.translatePosition)(sourceSelection.getStartPosition(), mappings);
                    const newRange2 = (0, utils_1.translatePosition)(sourceSelection.getEndPosition(), mappings);
                    destinationSelection = range_1.Range.plusRange(newRange1, newRange2);
                }
            }
            return { destination, destinationSelection };
        }
        switchSide() {
            const { destination, destinationSelection } = this.mapToOtherSide();
            destination.focus();
            if (destinationSelection) {
                destination.setSelection(destinationSelection);
            }
        }
        exitCompareMove() {
            const model = this._diffModel.get();
            if (!model) {
                return;
            }
            model.movedTextToCompare.set(undefined, undefined);
        }
        collapseAllUnchangedRegions() {
            const unchangedRegions = this._diffModel.get()?.unchangedRegions.get();
            if (!unchangedRegions) {
                return;
            }
            (0, observable_1.transaction)(tx => {
                for (const region of unchangedRegions) {
                    region.collapseAll(tx);
                }
            });
        }
        showAllUnchangedRegions() {
            const unchangedRegions = this._diffModel.get()?.unchangedRegions.get();
            if (!unchangedRegions) {
                return;
            }
            (0, observable_1.transaction)(tx => {
                for (const region of unchangedRegions) {
                    region.showAll(tx);
                }
            });
        }
        _handleCursorPositionChange(e, isModifiedEditor) {
            if (e?.reason === 3 /* CursorChangeReason.Explicit */) {
                const diff = this._diffModel.get()?.diff.get()?.mappings.find(m => isModifiedEditor ? m.lineRangeMapping.modified.contains(e.position.lineNumber) : m.lineRangeMapping.original.contains(e.position.lineNumber));
                if (diff?.lineRangeMapping.modified.isEmpty) {
                    this._accessibilitySignalService.playSignal(accessibilitySignalService_1.AccessibilitySignal.diffLineDeleted, { source: 'diffEditor.cursorPositionChanged' });
                }
                else if (diff?.lineRangeMapping.original.isEmpty) {
                    this._accessibilitySignalService.playSignal(accessibilitySignalService_1.AccessibilitySignal.diffLineInserted, { source: 'diffEditor.cursorPositionChanged' });
                }
                else if (diff) {
                    this._accessibilitySignalService.playSignal(accessibilitySignalService_1.AccessibilitySignal.diffLineModified, { source: 'diffEditor.cursorPositionChanged' });
                }
            }
        }
    };
    exports.DiffEditorWidget = DiffEditorWidget;
    exports.DiffEditorWidget = DiffEditorWidget = __decorate([
        __param(3, contextkey_1.IContextKeyService),
        __param(4, instantiation_1.IInstantiationService),
        __param(5, codeEditorService_1.ICodeEditorService),
        __param(6, accessibilitySignalService_1.IAccessibilitySignalService),
        __param(7, progress_1.IEditorProgressService)
    ], DiffEditorWidget);
    function toLineChanges(state) {
        return state.mappings.map(x => {
            const m = x.lineRangeMapping;
            let originalStartLineNumber;
            let originalEndLineNumber;
            let modifiedStartLineNumber;
            let modifiedEndLineNumber;
            let innerChanges = m.innerChanges;
            if (m.original.isEmpty) {
                // Insertion
                originalStartLineNumber = m.original.startLineNumber - 1;
                originalEndLineNumber = 0;
                innerChanges = undefined;
            }
            else {
                originalStartLineNumber = m.original.startLineNumber;
                originalEndLineNumber = m.original.endLineNumberExclusive - 1;
            }
            if (m.modified.isEmpty) {
                // Deletion
                modifiedStartLineNumber = m.modified.startLineNumber - 1;
                modifiedEndLineNumber = 0;
                innerChanges = undefined;
            }
            else {
                modifiedStartLineNumber = m.modified.startLineNumber;
                modifiedEndLineNumber = m.modified.endLineNumberExclusive - 1;
            }
            return {
                originalStartLineNumber,
                originalEndLineNumber,
                modifiedStartLineNumber,
                modifiedEndLineNumber,
                charChanges: innerChanges?.map(m => ({
                    originalStartLineNumber: m.originalRange.startLineNumber,
                    originalStartColumn: m.originalRange.startColumn,
                    originalEndLineNumber: m.originalRange.endLineNumber,
                    originalEndColumn: m.originalRange.endColumn,
                    modifiedStartLineNumber: m.modifiedRange.startLineNumber,
                    modifiedStartColumn: m.modifiedRange.startColumn,
                    modifiedEndLineNumber: m.modifiedRange.endLineNumber,
                    modifiedEndColumn: m.modifiedRange.endColumn,
                }))
            };
        });
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[811/*vs/editor/browser/widget/diffEditor/commands*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,26/*vs/base/common/codicons*/,15/*vs/editor/browser/editorExtensions*/,34/*vs/editor/browser/services/codeEditorService*/,286/*vs/editor/browser/widget/diffEditor/diffEditorWidget*/,20/*vs/editor/common/editorContextKeys*/,3/*vs/nls*/,29/*vs/platform/actions/common/actions*/,28/*vs/platform/configuration/common/configuration*/,12/*vs/platform/contextkey/common/contextkey*/,139/*vs/editor/browser/widget/diffEditor/registrations.contribution*/]), function (require, exports, dom_1, codicons_1, editorExtensions_1, codeEditorService_1, diffEditorWidget_1, editorContextKeys_1, nls_1, actions_1, configuration_1, contextkey_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AccessibleDiffViewerPrev = exports.AccessibleDiffViewerNext = exports.RevertHunkOrSelection = exports.ShowAllUnchangedRegions = exports.CollapseAllUnchangedRegions = exports.ExitCompareMove = exports.SwitchSide = exports.ToggleUseInlineViewWhenSpaceIsLimited = exports.ToggleShowMovedCodeBlocks = exports.ToggleCollapseUnchangedRegions = void 0;
    exports.findDiffEditor = findDiffEditor;
    exports.findFocusedDiffEditor = findFocusedDiffEditor;
    class ToggleCollapseUnchangedRegions extends actions_1.Action2 {
        constructor() {
            super({
                id: 'diffEditor.toggleCollapseUnchangedRegions',
                title: (0, nls_1.localize2)(72, 'Toggle Collapse Unchanged Regions'),
                icon: codicons_1.Codicon.map,
                toggled: contextkey_1.ContextKeyExpr.has('config.diffEditor.hideUnchangedRegions.enabled'),
                precondition: contextkey_1.ContextKeyExpr.has('isInDiffEditor'),
                menu: {
                    when: contextkey_1.ContextKeyExpr.has('isInDiffEditor'),
                    id: actions_1.MenuId.EditorTitle,
                    order: 22,
                    group: 'navigation',
                },
            });
        }
        run(accessor, ...args) {
            const configurationService = accessor.get(configuration_1.IConfigurationService);
            const newValue = !configurationService.getValue('diffEditor.hideUnchangedRegions.enabled');
            configurationService.updateValue('diffEditor.hideUnchangedRegions.enabled', newValue);
        }
    }
    exports.ToggleCollapseUnchangedRegions = ToggleCollapseUnchangedRegions;
    class ToggleShowMovedCodeBlocks extends actions_1.Action2 {
        constructor() {
            super({
                id: 'diffEditor.toggleShowMovedCodeBlocks',
                title: (0, nls_1.localize2)(73, 'Toggle Show Moved Code Blocks'),
                precondition: contextkey_1.ContextKeyExpr.has('isInDiffEditor'),
            });
        }
        run(accessor, ...args) {
            const configurationService = accessor.get(configuration_1.IConfigurationService);
            const newValue = !configurationService.getValue('diffEditor.experimental.showMoves');
            configurationService.updateValue('diffEditor.experimental.showMoves', newValue);
        }
    }
    exports.ToggleShowMovedCodeBlocks = ToggleShowMovedCodeBlocks;
    class ToggleUseInlineViewWhenSpaceIsLimited extends actions_1.Action2 {
        constructor() {
            super({
                id: 'diffEditor.toggleUseInlineViewWhenSpaceIsLimited',
                title: (0, nls_1.localize2)(74, 'Toggle Use Inline View When Space Is Limited'),
                precondition: contextkey_1.ContextKeyExpr.has('isInDiffEditor'),
            });
        }
        run(accessor, ...args) {
            const configurationService = accessor.get(configuration_1.IConfigurationService);
            const newValue = !configurationService.getValue('diffEditor.useInlineViewWhenSpaceIsLimited');
            configurationService.updateValue('diffEditor.useInlineViewWhenSpaceIsLimited', newValue);
        }
    }
    exports.ToggleUseInlineViewWhenSpaceIsLimited = ToggleUseInlineViewWhenSpaceIsLimited;
    const diffEditorCategory = (0, nls_1.localize2)(75, "Diff Editor");
    class SwitchSide extends editorExtensions_1.EditorAction2 {
        constructor() {
            super({
                id: 'diffEditor.switchSide',
                title: (0, nls_1.localize2)(76, 'Switch Side'),
                icon: codicons_1.Codicon.arrowSwap,
                precondition: contextkey_1.ContextKeyExpr.has('isInDiffEditor'),
                f1: true,
                category: diffEditorCategory,
            });
        }
        runEditorCommand(accessor, editor, arg) {
            const diffEditor = findFocusedDiffEditor(accessor);
            if (diffEditor instanceof diffEditorWidget_1.DiffEditorWidget) {
                if (arg && arg.dryRun) {
                    return { destinationSelection: diffEditor.mapToOtherSide().destinationSelection };
                }
                else {
                    diffEditor.switchSide();
                }
            }
            return undefined;
        }
    }
    exports.SwitchSide = SwitchSide;
    class ExitCompareMove extends editorExtensions_1.EditorAction2 {
        constructor() {
            super({
                id: 'diffEditor.exitCompareMove',
                title: (0, nls_1.localize2)(77, 'Exit Compare Move'),
                icon: codicons_1.Codicon.close,
                precondition: editorContextKeys_1.EditorContextKeys.comparingMovedCode,
                f1: false,
                category: diffEditorCategory,
                keybinding: {
                    weight: 10000,
                    primary: 9 /* KeyCode.Escape */,
                }
            });
        }
        runEditorCommand(accessor, editor, ...args) {
            const diffEditor = findFocusedDiffEditor(accessor);
            if (diffEditor instanceof diffEditorWidget_1.DiffEditorWidget) {
                diffEditor.exitCompareMove();
            }
        }
    }
    exports.ExitCompareMove = ExitCompareMove;
    class CollapseAllUnchangedRegions extends editorExtensions_1.EditorAction2 {
        constructor() {
            super({
                id: 'diffEditor.collapseAllUnchangedRegions',
                title: (0, nls_1.localize2)(78, 'Collapse All Unchanged Regions'),
                icon: codicons_1.Codicon.fold,
                precondition: contextkey_1.ContextKeyExpr.has('isInDiffEditor'),
                f1: true,
                category: diffEditorCategory,
            });
        }
        runEditorCommand(accessor, editor, ...args) {
            const diffEditor = findFocusedDiffEditor(accessor);
            if (diffEditor instanceof diffEditorWidget_1.DiffEditorWidget) {
                diffEditor.collapseAllUnchangedRegions();
            }
        }
    }
    exports.CollapseAllUnchangedRegions = CollapseAllUnchangedRegions;
    class ShowAllUnchangedRegions extends editorExtensions_1.EditorAction2 {
        constructor() {
            super({
                id: 'diffEditor.showAllUnchangedRegions',
                title: (0, nls_1.localize2)(79, 'Show All Unchanged Regions'),
                icon: codicons_1.Codicon.unfold,
                precondition: contextkey_1.ContextKeyExpr.has('isInDiffEditor'),
                f1: true,
                category: diffEditorCategory,
            });
        }
        runEditorCommand(accessor, editor, ...args) {
            const diffEditor = findFocusedDiffEditor(accessor);
            if (diffEditor instanceof diffEditorWidget_1.DiffEditorWidget) {
                diffEditor.showAllUnchangedRegions();
            }
        }
    }
    exports.ShowAllUnchangedRegions = ShowAllUnchangedRegions;
    class RevertHunkOrSelection extends actions_1.Action2 {
        constructor() {
            super({
                id: 'diffEditor.revert',
                title: (0, nls_1.localize2)(80, 'Revert'),
                f1: false,
                category: diffEditorCategory,
            });
        }
        run(accessor, arg) {
            const diffEditor = findDiffEditor(accessor, arg.originalUri, arg.modifiedUri);
            if (diffEditor instanceof diffEditorWidget_1.DiffEditorWidget) {
                diffEditor.revertRangeMappings(arg.mapping.innerChanges ?? []);
            }
            return undefined;
        }
    }
    exports.RevertHunkOrSelection = RevertHunkOrSelection;
    const accessibleDiffViewerCategory = (0, nls_1.localize2)(81, "Accessible Diff Viewer");
    class AccessibleDiffViewerNext extends actions_1.Action2 {
        static { this.id = 'editor.action.accessibleDiffViewer.next'; }
        constructor() {
            super({
                id: AccessibleDiffViewerNext.id,
                title: (0, nls_1.localize2)(82, 'Go to Next Difference'),
                category: accessibleDiffViewerCategory,
                precondition: contextkey_1.ContextKeyExpr.has('isInDiffEditor'),
                keybinding: {
                    primary: 65 /* KeyCode.F7 */,
                    weight: 100 /* KeybindingWeight.EditorContrib */
                },
                f1: true,
            });
        }
        run(accessor) {
            const diffEditor = findFocusedDiffEditor(accessor);
            diffEditor?.accessibleDiffViewerNext();
        }
    }
    exports.AccessibleDiffViewerNext = AccessibleDiffViewerNext;
    class AccessibleDiffViewerPrev extends actions_1.Action2 {
        static { this.id = 'editor.action.accessibleDiffViewer.prev'; }
        constructor() {
            super({
                id: AccessibleDiffViewerPrev.id,
                title: (0, nls_1.localize2)(83, 'Go to Previous Difference'),
                category: accessibleDiffViewerCategory,
                precondition: contextkey_1.ContextKeyExpr.has('isInDiffEditor'),
                keybinding: {
                    primary: 1024 /* KeyMod.Shift */ | 65 /* KeyCode.F7 */,
                    weight: 100 /* KeybindingWeight.EditorContrib */
                },
                f1: true,
            });
        }
        run(accessor) {
            const diffEditor = findFocusedDiffEditor(accessor);
            diffEditor?.accessibleDiffViewerPrev();
        }
    }
    exports.AccessibleDiffViewerPrev = AccessibleDiffViewerPrev;
    function findDiffEditor(accessor, originalUri, modifiedUri) {
        const codeEditorService = accessor.get(codeEditorService_1.ICodeEditorService);
        const diffEditors = codeEditorService.listDiffEditors();
        return diffEditors.find(diffEditor => {
            const modified = diffEditor.getModifiedEditor();
            const original = diffEditor.getOriginalEditor();
            return modified && modified.getModel()?.uri.toString() === modifiedUri.toString()
                && original && original.getModel()?.uri.toString() === originalUri.toString();
        }) || null;
    }
    function findFocusedDiffEditor(accessor) {
        const codeEditorService = accessor.get(codeEditorService_1.ICodeEditorService);
        const diffEditors = codeEditorService.listDiffEditors();
        const activeElement = (0, dom_1.getActiveElement)();
        if (activeElement) {
            for (const d of diffEditors) {
                const container = d.getContainerDomNode();
                if (isElementOrParentOf(container, activeElement)) {
                    return d;
                }
            }
        }
        return null;
    }
    function isElementOrParentOf(elementOrParent, element) {
        let e = element;
        while (e) {
            if (e === elementOrParent) {
                return true;
            }
            e = e.parentElement;
        }
        return false;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[812/*vs/editor/browser/widget/diffEditor/diffEditor.contribution*/], __M([1/*require*/,0/*exports*/,26/*vs/base/common/codicons*/,811/*vs/editor/browser/widget/diffEditor/commands*/,20/*vs/editor/common/editorContextKeys*/,3/*vs/nls*/,29/*vs/platform/actions/common/actions*/,24/*vs/platform/commands/common/commands*/,12/*vs/platform/contextkey/common/contextkey*/,139/*vs/editor/browser/widget/diffEditor/registrations.contribution*/]), function (require, exports, codicons_1, commands_1, editorContextKeys_1, nls_1, actions_1, commands_2, contextkey_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    (0, actions_1.registerAction2)(commands_1.ToggleCollapseUnchangedRegions);
    (0, actions_1.registerAction2)(commands_1.ToggleShowMovedCodeBlocks);
    (0, actions_1.registerAction2)(commands_1.ToggleUseInlineViewWhenSpaceIsLimited);
    actions_1.MenuRegistry.appendMenuItem(actions_1.MenuId.EditorTitle, {
        command: {
            id: new commands_1.ToggleUseInlineViewWhenSpaceIsLimited().desc.id,
            title: (0, nls_1.localize)(106, "Use Inline View When Space Is Limited"),
            toggled: contextkey_1.ContextKeyExpr.has('config.diffEditor.useInlineViewWhenSpaceIsLimited'),
            precondition: contextkey_1.ContextKeyExpr.has('isInDiffEditor'),
        },
        order: 11,
        group: '1_diff',
        when: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.diffEditorRenderSideBySideInlineBreakpointReached, contextkey_1.ContextKeyExpr.has('isInDiffEditor')),
    });
    actions_1.MenuRegistry.appendMenuItem(actions_1.MenuId.EditorTitle, {
        command: {
            id: new commands_1.ToggleShowMovedCodeBlocks().desc.id,
            title: (0, nls_1.localize)(107, "Show Moved Code Blocks"),
            icon: codicons_1.Codicon.move,
            toggled: contextkey_1.ContextKeyEqualsExpr.create('config.diffEditor.experimental.showMoves', true),
            precondition: contextkey_1.ContextKeyExpr.has('isInDiffEditor'),
        },
        order: 10,
        group: '1_diff',
        when: contextkey_1.ContextKeyExpr.has('isInDiffEditor'),
    });
    (0, actions_1.registerAction2)(commands_1.RevertHunkOrSelection);
    for (const ctx of [
        { icon: codicons_1.Codicon.arrowRight, key: editorContextKeys_1.EditorContextKeys.diffEditorInlineMode.toNegated() },
        { icon: codicons_1.Codicon.discard, key: editorContextKeys_1.EditorContextKeys.diffEditorInlineMode }
    ]) {
        actions_1.MenuRegistry.appendMenuItem(actions_1.MenuId.DiffEditorHunkToolbar, {
            command: {
                id: new commands_1.RevertHunkOrSelection().desc.id,
                title: (0, nls_1.localize)(108, "Revert Block"),
                icon: ctx.icon,
            },
            when: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.diffEditorModifiedWritable, ctx.key),
            order: 5,
            group: 'primary',
        });
        actions_1.MenuRegistry.appendMenuItem(actions_1.MenuId.DiffEditorSelectionToolbar, {
            command: {
                id: new commands_1.RevertHunkOrSelection().desc.id,
                title: (0, nls_1.localize)(109, "Revert Selection"),
                icon: ctx.icon,
            },
            when: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.diffEditorModifiedWritable, ctx.key),
            order: 5,
            group: 'primary',
        });
    }
    (0, actions_1.registerAction2)(commands_1.SwitchSide);
    (0, actions_1.registerAction2)(commands_1.ExitCompareMove);
    (0, actions_1.registerAction2)(commands_1.CollapseAllUnchangedRegions);
    (0, actions_1.registerAction2)(commands_1.ShowAllUnchangedRegions);
    actions_1.MenuRegistry.appendMenuItem(actions_1.MenuId.EditorTitle, {
        command: {
            id: commands_1.AccessibleDiffViewerNext.id,
            title: (0, nls_1.localize)(110, "Open Accessible Diff Viewer"),
            precondition: contextkey_1.ContextKeyExpr.has('isInDiffEditor'),
        },
        order: 10,
        group: '2_diff',
        when: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.accessibleDiffViewerVisible.negate(), contextkey_1.ContextKeyExpr.has('isInDiffEditor')),
    });
    commands_2.CommandsRegistry.registerCommandAlias('editor.action.diffReview.next', commands_1.AccessibleDiffViewerNext.id);
    (0, actions_1.registerAction2)(commands_1.AccessibleDiffViewerNext);
    commands_2.CommandsRegistry.registerCommandAlias('editor.action.diffReview.prev', commands_1.AccessibleDiffViewerPrev.id);
    (0, actions_1.registerAction2)(commands_1.AccessibleDiffViewerPrev);
});










define(__m[420/*vs/editor/browser/widget/multiDiffEditor/diffEditorItemTemplate*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,258/*vs/base/browser/ui/button/button*/,26/*vs/base/common/codicons*/,2/*vs/base/common/lifecycle*/,21/*vs/base/common/observable*/,92/*vs/base/common/observableInternal/base*/,112/*vs/editor/browser/observableCodeEditor*/,286/*vs/editor/browser/widget/diffEditor/diffEditorWidget*/,124/*vs/platform/actions/browser/menuEntryActionViewItem*/,218/*vs/platform/actions/browser/toolbar*/,29/*vs/platform/actions/common/actions*/,7/*vs/platform/instantiation/common/instantiation*/,365/*vs/editor/browser/widget/multiDiffEditor/utils*/,12/*vs/platform/contextkey/common/contextkey*/,154/*vs/platform/instantiation/common/serviceCollection*/]), function (require, exports, dom_1, button_1, codicons_1, lifecycle_1, observable_1, base_1, observableCodeEditor_1, diffEditorWidget_1, menuEntryActionViewItem_1, toolbar_1, actions_1, instantiation_1, utils_1, contextkey_1, serviceCollection_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DiffEditorItemTemplate = exports.TemplateData = void 0;
    class TemplateData {
        constructor(viewModel, deltaScrollVertical) {
            this.viewModel = viewModel;
            this.deltaScrollVertical = deltaScrollVertical;
        }
        getId() {
            return this.viewModel;
        }
    }
    exports.TemplateData = TemplateData;
    let DiffEditorItemTemplate = class DiffEditorItemTemplate extends lifecycle_1.Disposable {
        constructor(_container, _overflowWidgetsDomNode, _workbenchUIElementFactory, _instantiationService, _parentContextKeyService) {
            super();
            this._container = _container;
            this._overflowWidgetsDomNode = _overflowWidgetsDomNode;
            this._workbenchUIElementFactory = _workbenchUIElementFactory;
            this._instantiationService = _instantiationService;
            this._viewModel = (0, base_1.observableValue)(this, undefined);
            this._collapsed = (0, observable_1.derived)(this, reader => this._viewModel.read(reader)?.collapsed.read(reader));
            this._editorContentHeight = (0, base_1.observableValue)(this, 500);
            this.contentHeight = (0, observable_1.derived)(this, reader => {
                const h = this._collapsed.read(reader) ? 0 : this._editorContentHeight.read(reader);
                return h + this._outerEditorHeight;
            });
            this._modifiedContentWidth = (0, base_1.observableValue)(this, 0);
            this._modifiedWidth = (0, base_1.observableValue)(this, 0);
            this._originalContentWidth = (0, base_1.observableValue)(this, 0);
            this._originalWidth = (0, base_1.observableValue)(this, 0);
            this.maxScroll = (0, observable_1.derived)(this, reader => {
                const scroll1 = this._modifiedContentWidth.read(reader) - this._modifiedWidth.read(reader);
                const scroll2 = this._originalContentWidth.read(reader) - this._originalWidth.read(reader);
                if (scroll1 > scroll2) {
                    return { maxScroll: scroll1, width: this._modifiedWidth.read(reader) };
                }
                else {
                    return { maxScroll: scroll2, width: this._originalWidth.read(reader) };
                }
            });
            this._elements = (0, dom_1.h)('div.multiDiffEntry', [
                (0, dom_1.h)('div.header@header', [
                    (0, dom_1.h)('div.header-content', [
                        (0, dom_1.h)('div.collapse-button@collapseButton'),
                        (0, dom_1.h)('div.file-path', [
                            (0, dom_1.h)('div.title.modified.show-file-icons@primaryPath', []),
                            (0, dom_1.h)('div.status.deleted@status', ['R']),
                            (0, dom_1.h)('div.title.original.show-file-icons@secondaryPath', []),
                        ]),
                        (0, dom_1.h)('div.actions@actions'),
                    ]),
                ]),
                (0, dom_1.h)('div.editorParent', [
                    (0, dom_1.h)('div.editorContainer@editor'),
                ])
            ]);
            this.editor = this._register(this._instantiationService.createInstance(diffEditorWidget_1.DiffEditorWidget, this._elements.editor, {
                overflowWidgetsDomNode: this._overflowWidgetsDomNode,
            }, {}));
            this.isModifedFocused = (0, observableCodeEditor_1.observableCodeEditor)(this.editor.getModifiedEditor()).isFocused;
            this.isOriginalFocused = (0, observableCodeEditor_1.observableCodeEditor)(this.editor.getOriginalEditor()).isFocused;
            this.isFocused = (0, observable_1.derived)(this, reader => this.isModifedFocused.read(reader) || this.isOriginalFocused.read(reader));
            this._resourceLabel = this._workbenchUIElementFactory.createResourceLabel
                ? this._register(this._workbenchUIElementFactory.createResourceLabel(this._elements.primaryPath))
                : undefined;
            this._resourceLabel2 = this._workbenchUIElementFactory.createResourceLabel
                ? this._register(this._workbenchUIElementFactory.createResourceLabel(this._elements.secondaryPath))
                : undefined;
            this._dataStore = this._register(new lifecycle_1.DisposableStore());
            this._headerHeight = 40;
            this._lastScrollTop = -1;
            this._isSettingScrollTop = false;
            const btn = new button_1.Button(this._elements.collapseButton, {});
            this._register((0, observable_1.autorun)(reader => {
                btn.element.className = '';
                btn.icon = this._collapsed.read(reader) ? codicons_1.Codicon.chevronRight : codicons_1.Codicon.chevronDown;
            }));
            this._register(btn.onDidClick(() => {
                this._viewModel.get()?.collapsed.set(!this._collapsed.get(), undefined);
            }));
            this._register((0, observable_1.autorun)(reader => {
                this._elements.editor.style.display = this._collapsed.read(reader) ? 'none' : 'block';
            }));
            this._register(this.editor.getModifiedEditor().onDidLayoutChange(e => {
                const width = this.editor.getModifiedEditor().getLayoutInfo().contentWidth;
                this._modifiedWidth.set(width, undefined);
            }));
            this._register(this.editor.getOriginalEditor().onDidLayoutChange(e => {
                const width = this.editor.getOriginalEditor().getLayoutInfo().contentWidth;
                this._originalWidth.set(width, undefined);
            }));
            this._register(this.editor.onDidContentSizeChange(e => {
                (0, base_1.globalTransaction)(tx => {
                    this._editorContentHeight.set(e.contentHeight, tx);
                    this._modifiedContentWidth.set(this.editor.getModifiedEditor().getContentWidth(), tx);
                    this._originalContentWidth.set(this.editor.getOriginalEditor().getContentWidth(), tx);
                });
            }));
            this._register(this.editor.getOriginalEditor().onDidScrollChange(e => {
                if (this._isSettingScrollTop) {
                    return;
                }
                if (!e.scrollTopChanged || !this._data) {
                    return;
                }
                const delta = e.scrollTop - this._lastScrollTop;
                this._data.deltaScrollVertical(delta);
            }));
            this._register((0, observable_1.autorun)(reader => {
                const isActive = this._viewModel.read(reader)?.isActive.read(reader);
                this._elements.root.classList.toggle('active', isActive);
            }));
            this._container.appendChild(this._elements.root);
            this._outerEditorHeight = this._headerHeight;
            this._contextKeyService = this._register(_parentContextKeyService.createScoped(this._elements.actions));
            const instantiationService = this._register(this._instantiationService.createChild(new serviceCollection_1.ServiceCollection([contextkey_1.IContextKeyService, this._contextKeyService])));
            this._register(instantiationService.createInstance(toolbar_1.MenuWorkbenchToolBar, this._elements.actions, actions_1.MenuId.MultiDiffEditorFileToolbar, {
                actionRunner: this._register(new utils_1.ActionRunnerWithContext(() => (this._viewModel.get()?.modifiedUri))),
                menuOptions: {
                    shouldForwardArgs: true,
                },
                toolbarOptions: { primaryGroup: g => g.startsWith('navigation') },
                actionViewItemProvider: (action, options) => (0, menuEntryActionViewItem_1.createActionViewItem)(instantiationService, action, options),
            }));
        }
        setScrollLeft(left) {
            if (this._modifiedContentWidth.get() - this._modifiedWidth.get() > this._originalContentWidth.get() - this._originalWidth.get()) {
                this.editor.getModifiedEditor().setScrollLeft(left);
            }
            else {
                this.editor.getOriginalEditor().setScrollLeft(left);
            }
        }
        setData(data) {
            this._data = data;
            function updateOptions(options) {
                return {
                    ...options,
                    scrollBeyondLastLine: false,
                    hideUnchangedRegions: {
                        enabled: true,
                    },
                    scrollbar: {
                        vertical: 'hidden',
                        horizontal: 'hidden',
                        handleMouseWheel: false,
                        useShadows: false,
                    },
                    renderOverviewRuler: false,
                    fixedOverflowWidgets: true,
                    overviewRulerBorder: false,
                };
            }
            if (!data) {
                (0, base_1.globalTransaction)(tx => {
                    this._viewModel.set(undefined, tx);
                    this.editor.setDiffModel(null, tx);
                    this._dataStore.clear();
                });
                return;
            }
            const value = data.viewModel.documentDiffItem;
            (0, base_1.globalTransaction)(tx => {
                this._resourceLabel?.setUri(data.viewModel.modifiedUri ?? data.viewModel.originalUri, { strikethrough: data.viewModel.modifiedUri === undefined });
                let isRenamed = false;
                let isDeleted = false;
                let isAdded = false;
                let flag = '';
                if (data.viewModel.modifiedUri && data.viewModel.originalUri && data.viewModel.modifiedUri.path !== data.viewModel.originalUri.path) {
                    flag = 'R';
                    isRenamed = true;
                }
                else if (!data.viewModel.modifiedUri) {
                    flag = 'D';
                    isDeleted = true;
                }
                else if (!data.viewModel.originalUri) {
                    flag = 'A';
                    isAdded = true;
                }
                this._elements.status.classList.toggle('renamed', isRenamed);
                this._elements.status.classList.toggle('deleted', isDeleted);
                this._elements.status.classList.toggle('added', isAdded);
                this._elements.status.innerText = flag;
                this._resourceLabel2?.setUri(isRenamed ? data.viewModel.originalUri : undefined, { strikethrough: true });
                this._dataStore.clear();
                this._viewModel.set(data.viewModel, tx);
                this.editor.setDiffModel(data.viewModel.diffEditorViewModelRef, tx);
                this.editor.updateOptions(updateOptions(value.options ?? {}));
            });
            if (value.onOptionsDidChange) {
                this._dataStore.add(value.onOptionsDidChange(() => {
                    this.editor.updateOptions(updateOptions(value.options ?? {}));
                }));
            }
            data.viewModel.isAlive.recomputeInitiallyAndOnChange(this._dataStore, value => {
                if (!value) {
                    this.setData(undefined);
                }
            });
            if (data.viewModel.documentDiffItem.contextKeys) {
                for (const [key, value] of Object.entries(data.viewModel.documentDiffItem.contextKeys)) {
                    this._contextKeyService.createKey(key, value);
                }
            }
        }
        render(verticalRange, width, editorScroll, viewPort) {
            this._elements.root.style.visibility = 'visible';
            this._elements.root.style.top = `${verticalRange.start}px`;
            this._elements.root.style.height = `${verticalRange.length}px`;
            this._elements.root.style.width = `${width}px`;
            this._elements.root.style.position = 'absolute';
            // For sticky scroll
            const maxDelta = verticalRange.length - this._headerHeight;
            const delta = Math.max(0, Math.min(viewPort.start - verticalRange.start, maxDelta));
            this._elements.header.style.transform = `translateY(${delta}px)`;
            (0, base_1.globalTransaction)(tx => {
                this.editor.layout({
                    width: width - 2 * 8 - 2 * 1,
                    height: verticalRange.length - this._outerEditorHeight,
                });
            });
            try {
                this._isSettingScrollTop = true;
                this._lastScrollTop = editorScroll;
                this.editor.getOriginalEditor().setScrollTop(editorScroll);
            }
            finally {
                this._isSettingScrollTop = false;
            }
            this._elements.header.classList.toggle('shadow', delta > 0 || editorScroll > 0);
            this._elements.header.classList.toggle('collapsed', delta === maxDelta);
        }
        hide() {
            this._elements.root.style.top = `-100000px`;
            this._elements.root.style.visibility = 'hidden'; // Some editor parts are still visible
        }
    };
    exports.DiffEditorItemTemplate = DiffEditorItemTemplate;
    exports.DiffEditorItemTemplate = DiffEditorItemTemplate = __decorate([
        __param(3, instantiation_1.IInstantiationService),
        __param(4, contextkey_1.IContextKeyService)
    ], DiffEditorItemTemplate);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[813/*vs/editor/browser/widget/multiDiffEditor/multiDiffEditorWidgetImpl*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,86/*vs/base/browser/ui/scrollbar/scrollableElement*/,13/*vs/base/common/arrays*/,67/*vs/base/common/arraysFind*/,8/*vs/base/common/errors*/,2/*vs/base/common/lifecycle*/,21/*vs/base/common/observable*/,92/*vs/base/common/observableInternal/base*/,163/*vs/base/common/scrollable*/,88/*vs/editor/browser/widget/diffEditor/utils*/,68/*vs/editor/common/core/offsetRange*/,23/*vs/editor/common/core/selection*/,20/*vs/editor/common/editorContextKeys*/,12/*vs/platform/contextkey/common/contextkey*/,7/*vs/platform/instantiation/common/instantiation*/,154/*vs/platform/instantiation/common/serviceCollection*/,420/*vs/editor/browser/widget/multiDiffEditor/diffEditorItemTemplate*/,553/*vs/editor/browser/widget/multiDiffEditor/objectPool*/,3/*vs/nls*/,502/*vs/css!vs/editor/browser/widget/multiDiffEditor/style*/]), function (require, exports, dom_1, scrollableElement_1, arrays_1, arraysFind_1, errors_1, lifecycle_1, observable_1, base_1, scrollable_1, utils_1, offsetRange_1, selection_1, editorContextKeys_1, contextkey_1, instantiation_1, serviceCollection_1, diffEditorItemTemplate_1, objectPool_1, nls_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MultiDiffEditorWidgetImpl = void 0;
    let MultiDiffEditorWidgetImpl = class MultiDiffEditorWidgetImpl extends lifecycle_1.Disposable {
        constructor(_element, _dimension, _viewModel, _workbenchUIElementFactory, _parentContextKeyService, _parentInstantiationService) {
            super();
            this._element = _element;
            this._dimension = _dimension;
            this._viewModel = _viewModel;
            this._workbenchUIElementFactory = _workbenchUIElementFactory;
            this._parentContextKeyService = _parentContextKeyService;
            this._parentInstantiationService = _parentInstantiationService;
            this._scrollableElements = (0, dom_1.h)('div.scrollContent', [
                (0, dom_1.h)('div@content', {
                    style: {
                        overflow: 'hidden',
                    }
                }),
                (0, dom_1.h)('div.monaco-editor@overflowWidgetsDomNode', {}),
            ]);
            this._scrollable = this._register(new scrollable_1.Scrollable({
                forceIntegerValues: false,
                scheduleAtNextAnimationFrame: (cb) => (0, dom_1.scheduleAtNextAnimationFrame)((0, dom_1.getWindow)(this._element), cb),
                smoothScrollDuration: 100,
            }));
            this._scrollableElement = this._register(new scrollableElement_1.SmoothScrollableElement(this._scrollableElements.root, {
                vertical: 1 /* ScrollbarVisibility.Auto */,
                horizontal: 1 /* ScrollbarVisibility.Auto */,
                useShadows: false,
            }, this._scrollable));
            this._elements = (0, dom_1.h)('div.monaco-component.multiDiffEditor', {}, [
                (0, dom_1.h)('div', {}, [this._scrollableElement.getDomNode()]),
                (0, dom_1.h)('div.placeholder@placeholder', {}, [(0, dom_1.h)('div', [(0, nls_1.localize)(132, 'No Changed Files')])]),
            ]);
            this._sizeObserver = this._register(new utils_1.ObservableElementSizeObserver(this._element, undefined));
            this._objectPool = this._register(new objectPool_1.ObjectPool((data) => {
                const template = this._instantiationService.createInstance(diffEditorItemTemplate_1.DiffEditorItemTemplate, this._scrollableElements.content, this._scrollableElements.overflowWidgetsDomNode, this._workbenchUIElementFactory);
                template.setData(data);
                return template;
            }));
            this.scrollTop = (0, observable_1.observableFromEvent)(this, this._scrollableElement.onScroll, () => /** @description scrollTop */ this._scrollableElement.getScrollPosition().scrollTop);
            this.scrollLeft = (0, observable_1.observableFromEvent)(this, this._scrollableElement.onScroll, () => /** @description scrollLeft */ this._scrollableElement.getScrollPosition().scrollLeft);
            this._viewItemsInfo = (0, observable_1.derivedWithStore)(this, (reader, store) => {
                const vm = this._viewModel.read(reader);
                if (!vm) {
                    return { items: [], getItem: _d => { throw new errors_1.BugIndicatingError(); } };
                }
                const viewModels = vm.items.read(reader);
                const map = new Map();
                const items = viewModels.map(d => {
                    const item = store.add(new VirtualizedViewItem(d, this._objectPool, this.scrollLeft, delta => {
                        this._scrollableElement.setScrollPosition({ scrollTop: this._scrollableElement.getScrollPosition().scrollTop + delta });
                    }));
                    const data = this._lastDocStates?.[item.getKey()];
                    if (data) {
                        (0, base_1.transaction)(tx => {
                            item.setViewState(data, tx);
                        });
                    }
                    map.set(d, item);
                    return item;
                });
                return { items, getItem: d => map.get(d) };
            });
            this._viewItems = this._viewItemsInfo.map(this, items => items.items);
            this._spaceBetweenPx = 0;
            this._totalHeight = this._viewItems.map(this, (items, reader) => items.reduce((r, i) => r + i.contentHeight.read(reader) + this._spaceBetweenPx, 0));
            this._contextKeyService = this._register(this._parentContextKeyService.createScoped(this._element));
            this._instantiationService = this._register(this._parentInstantiationService.createChild(new serviceCollection_1.ServiceCollection([contextkey_1.IContextKeyService, this._contextKeyService])));
            /** This accounts for documents that are not loaded yet. */
            this._lastDocStates = {};
            this._contextKeyService.createKey(editorContextKeys_1.EditorContextKeys.inMultiDiffEditor.key, true);
            this._register((0, observable_1.autorunWithStore)((reader, store) => {
                const viewModel = this._viewModel.read(reader);
                if (viewModel && viewModel.contextKeys) {
                    for (const [key, value] of Object.entries(viewModel.contextKeys)) {
                        const contextKey = this._contextKeyService.createKey(key, undefined);
                        contextKey.set(value);
                        store.add((0, lifecycle_1.toDisposable)(() => contextKey.reset()));
                    }
                }
            }));
            const ctxAllCollapsed = this._parentContextKeyService.createKey(editorContextKeys_1.EditorContextKeys.multiDiffEditorAllCollapsed.key, false);
            this._register((0, observable_1.autorun)((reader) => {
                const viewModel = this._viewModel.read(reader);
                if (viewModel) {
                    const allCollapsed = viewModel.items.read(reader).every(item => item.collapsed.read(reader));
                    ctxAllCollapsed.set(allCollapsed);
                }
            }));
            this._register((0, observable_1.autorun)((reader) => {
                /** @description Update widget dimension */
                const dimension = this._dimension.read(reader);
                this._sizeObserver.observe(dimension);
            }));
            this._register((0, observable_1.autorun)((reader) => {
                /** @description Update widget dimension */
                const items = this._viewItems.read(reader);
                this._elements.placeholder.classList.toggle('visible', items.length === 0);
            }));
            this._scrollableElements.content.style.position = 'relative';
            this._register((0, observable_1.autorun)((reader) => {
                /** @description Update scroll dimensions */
                const height = this._sizeObserver.height.read(reader);
                this._scrollableElements.root.style.height = `${height}px`;
                const totalHeight = this._totalHeight.read(reader);
                this._scrollableElements.content.style.height = `${totalHeight}px`;
                const width = this._sizeObserver.width.read(reader);
                let scrollWidth = width;
                const viewItems = this._viewItems.read(reader);
                const max = (0, arraysFind_1.findFirstMax)(viewItems, (0, arrays_1.compareBy)(i => i.maxScroll.read(reader).maxScroll, arrays_1.numberComparator));
                if (max) {
                    const maxScroll = max.maxScroll.read(reader);
                    scrollWidth = width + maxScroll.maxScroll;
                }
                this._scrollableElement.setScrollDimensions({
                    width: width,
                    height: height,
                    scrollHeight: totalHeight,
                    scrollWidth,
                });
            }));
            _element.replaceChildren(this._elements.root);
            this._register((0, lifecycle_1.toDisposable)(() => {
                _element.replaceChildren();
            }));
            this._register(this._register((0, observable_1.autorun)(reader => {
                /** @description Render all */
                (0, base_1.globalTransaction)(tx => {
                    this.render(reader);
                });
            })));
        }
        render(reader) {
            const scrollTop = this.scrollTop.read(reader);
            let contentScrollOffsetToScrollOffset = 0;
            let itemHeightSumBefore = 0;
            let itemContentHeightSumBefore = 0;
            const viewPortHeight = this._sizeObserver.height.read(reader);
            const contentViewPort = offsetRange_1.OffsetRange.ofStartAndLength(scrollTop, viewPortHeight);
            const width = this._sizeObserver.width.read(reader);
            for (const v of this._viewItems.read(reader)) {
                const itemContentHeight = v.contentHeight.read(reader);
                const itemHeight = Math.min(itemContentHeight, viewPortHeight);
                const itemRange = offsetRange_1.OffsetRange.ofStartAndLength(itemHeightSumBefore, itemHeight);
                const itemContentRange = offsetRange_1.OffsetRange.ofStartAndLength(itemContentHeightSumBefore, itemContentHeight);
                if (itemContentRange.isBefore(contentViewPort)) {
                    contentScrollOffsetToScrollOffset -= itemContentHeight - itemHeight;
                    v.hide();
                }
                else if (itemContentRange.isAfter(contentViewPort)) {
                    v.hide();
                }
                else {
                    const scroll = Math.max(0, Math.min(contentViewPort.start - itemContentRange.start, itemContentHeight - itemHeight));
                    contentScrollOffsetToScrollOffset -= scroll;
                    const viewPort = offsetRange_1.OffsetRange.ofStartAndLength(scrollTop + contentScrollOffsetToScrollOffset, viewPortHeight);
                    v.render(itemRange, scroll, width, viewPort);
                }
                itemHeightSumBefore += itemHeight + this._spaceBetweenPx;
                itemContentHeightSumBefore += itemContentHeight + this._spaceBetweenPx;
            }
            this._scrollableElements.content.style.transform = `translateY(${-(scrollTop + contentScrollOffsetToScrollOffset)}px)`;
        }
    };
    exports.MultiDiffEditorWidgetImpl = MultiDiffEditorWidgetImpl;
    exports.MultiDiffEditorWidgetImpl = MultiDiffEditorWidgetImpl = __decorate([
        __param(4, contextkey_1.IContextKeyService),
        __param(5, instantiation_1.IInstantiationService)
    ], MultiDiffEditorWidgetImpl);
    class VirtualizedViewItem extends lifecycle_1.Disposable {
        constructor(viewModel, _objectPool, _scrollLeft, _deltaScrollVertical) {
            super();
            this.viewModel = viewModel;
            this._objectPool = _objectPool;
            this._scrollLeft = _scrollLeft;
            this._deltaScrollVertical = _deltaScrollVertical;
            this._templateRef = this._register((0, base_1.disposableObservableValue)(this, undefined));
            this.contentHeight = (0, observable_1.derived)(this, reader => this._templateRef.read(reader)?.object.contentHeight?.read(reader) ?? this.viewModel.lastTemplateData.read(reader).contentHeight);
            this.maxScroll = (0, observable_1.derived)(this, reader => this._templateRef.read(reader)?.object.maxScroll.read(reader) ?? { maxScroll: 0, scrollWidth: 0 });
            this.template = (0, observable_1.derived)(this, reader => this._templateRef.read(reader)?.object);
            this._isHidden = (0, observable_1.observableValue)(this, false);
            this._isFocused = (0, observable_1.derived)(this, reader => this.template.read(reader)?.isFocused.read(reader) ?? false);
            this.viewModel.setIsFocused(this._isFocused, undefined);
            this._register((0, observable_1.autorun)((reader) => {
                const scrollLeft = this._scrollLeft.read(reader);
                this._templateRef.read(reader)?.object.setScrollLeft(scrollLeft);
            }));
            this._register((0, observable_1.autorun)(reader => {
                const ref = this._templateRef.read(reader);
                if (!ref) {
                    return;
                }
                const isHidden = this._isHidden.read(reader);
                if (!isHidden) {
                    return;
                }
                const isFocused = ref.object.isFocused.read(reader);
                if (isFocused) {
                    return;
                }
                this._clear();
            }));
        }
        dispose() {
            this._clear();
            super.dispose();
        }
        toString() {
            return `VirtualViewItem(${this.viewModel.documentDiffItem.modified?.uri.toString()})`;
        }
        getKey() {
            return this.viewModel.getKey();
        }
        setViewState(viewState, tx) {
            this.viewModel.collapsed.set(viewState.collapsed, tx);
            this._updateTemplateData(tx);
            const data = this.viewModel.lastTemplateData.get();
            const selections = viewState.selections?.map(selection_1.Selection.liftSelection);
            this.viewModel.lastTemplateData.set({
                ...data,
                selections,
            }, tx);
            const ref = this._templateRef.get();
            if (ref) {
                if (selections) {
                    ref.object.editor.setSelections(selections);
                }
            }
        }
        _updateTemplateData(tx) {
            const ref = this._templateRef.get();
            if (!ref) {
                return;
            }
            this.viewModel.lastTemplateData.set({
                contentHeight: ref.object.contentHeight.get(),
                selections: ref.object.editor.getSelections() ?? undefined,
            }, tx);
        }
        _clear() {
            const ref = this._templateRef.get();
            if (!ref) {
                return;
            }
            (0, base_1.transaction)(tx => {
                this._updateTemplateData(tx);
                ref.object.hide();
                this._templateRef.set(undefined, tx);
            });
        }
        hide() {
            this._isHidden.set(true, undefined);
        }
        render(verticalSpace, offset, width, viewPort) {
            this._isHidden.set(false, undefined);
            let ref = this._templateRef.get();
            if (!ref) {
                ref = this._objectPool.getUnusedObj(new diffEditorItemTemplate_1.TemplateData(this.viewModel, this._deltaScrollVertical));
                this._templateRef.set(ref, undefined);
                const selections = this.viewModel.lastTemplateData.get().selections;
                if (selections) {
                    ref.object.editor.setSelections(selections);
                }
            }
            ref.object.render(verticalSpace, width, offset, viewPort);
        }
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[814/*vs/editor/browser/widget/multiDiffEditor/multiDiffEditorWidget*/], __M([1/*require*/,0/*exports*/,2/*vs/base/common/lifecycle*/,21/*vs/base/common/observable*/,171/*vs/base/common/hotReloadHelpers*/,813/*vs/editor/browser/widget/multiDiffEditor/multiDiffEditorWidgetImpl*/,7/*vs/platform/instantiation/common/instantiation*/,420/*vs/editor/browser/widget/multiDiffEditor/diffEditorItemTemplate*/,756/*vs/editor/browser/widget/multiDiffEditor/colors*/]), function (require, exports, lifecycle_1, observable_1, hotReloadHelpers_1, multiDiffEditorWidgetImpl_1, instantiation_1, diffEditorItemTemplate_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MultiDiffEditorWidget = void 0;
    let MultiDiffEditorWidget = class MultiDiffEditorWidget extends lifecycle_1.Disposable {
        constructor(_element, _workbenchUIElementFactory, _instantiationService) {
            super();
            this._element = _element;
            this._workbenchUIElementFactory = _workbenchUIElementFactory;
            this._instantiationService = _instantiationService;
            this._dimension = (0, observable_1.observableValue)(this, undefined);
            this._viewModel = (0, observable_1.observableValue)(this, undefined);
            this._widgetImpl = (0, observable_1.derivedWithStore)(this, (reader, store) => {
                (0, hotReloadHelpers_1.readHotReloadableExport)(diffEditorItemTemplate_1.DiffEditorItemTemplate, reader);
                return store.add(this._instantiationService.createInstance(((0, hotReloadHelpers_1.readHotReloadableExport)(multiDiffEditorWidgetImpl_1.MultiDiffEditorWidgetImpl, reader)), this._element, this._dimension, this._viewModel, this._workbenchUIElementFactory));
            });
            this._register((0, observable_1.recomputeInitiallyAndOnChange)(this._widgetImpl));
        }
    };
    exports.MultiDiffEditorWidget = MultiDiffEditorWidget;
    exports.MultiDiffEditorWidget = MultiDiffEditorWidget = __decorate([
        __param(2, instantiation_1.IInstantiationService)
    ], MultiDiffEditorWidget);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[815/*vs/editor/contrib/bracketMatching/browser/bracketMatching*/], __M([1/*require*/,0/*exports*/,14/*vs/base/common/async*/,2/*vs/base/common/lifecycle*/,15/*vs/editor/browser/editorExtensions*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/,23/*vs/editor/common/core/selection*/,20/*vs/editor/common/editorContextKeys*/,40/*vs/editor/common/model*/,35/*vs/editor/common/model/textModel*/,3/*vs/nls*/,29/*vs/platform/actions/common/actions*/,32/*vs/platform/theme/common/colorRegistry*/,25/*vs/platform/theme/common/themeService*/,504/*vs/css!vs/editor/contrib/bracketMatching/browser/bracketMatching*/]), function (require, exports, async_1, lifecycle_1, editorExtensions_1, position_1, range_1, selection_1, editorContextKeys_1, model_1, textModel_1, nls, actions_1, colorRegistry_1, themeService_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.BracketMatchingController = void 0;
    const overviewRulerBracketMatchForeground = (0, colorRegistry_1.registerColor)('editorOverviewRuler.bracketMatchForeground', '#A0A0A0', nls.localize(716, 'Overview ruler marker color for matching brackets.'));
    class JumpToBracketAction extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: 'editor.action.jumpToBracket',
                label: nls.localize(717, "Go to Bracket"),
                alias: 'Go to Bracket',
                precondition: undefined,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 93 /* KeyCode.Backslash */,
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
        run(accessor, editor) {
            BracketMatchingController.get(editor)?.jumpToBracket();
        }
    }
    class SelectToBracketAction extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: 'editor.action.selectToBracket',
                label: nls.localize(718, "Select to Bracket"),
                alias: 'Select to Bracket',
                precondition: undefined,
                metadata: {
                    description: nls.localize2(721, "Select the text inside and including the brackets or curly braces"),
                    args: [{
                            name: 'args',
                            schema: {
                                type: 'object',
                                properties: {
                                    'selectBrackets': {
                                        type: 'boolean',
                                        default: true
                                    }
                                },
                            }
                        }]
                }
            });
        }
        run(accessor, editor, args) {
            let selectBrackets = true;
            if (args && args.selectBrackets === false) {
                selectBrackets = false;
            }
            BracketMatchingController.get(editor)?.selectToBracket(selectBrackets);
        }
    }
    class RemoveBracketsAction extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: 'editor.action.removeBrackets',
                label: nls.localize(719, "Remove Brackets"),
                alias: 'Remove Brackets',
                precondition: undefined,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    primary: 2048 /* KeyMod.CtrlCmd */ | 512 /* KeyMod.Alt */ | 1 /* KeyCode.Backspace */,
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
        run(accessor, editor) {
            BracketMatchingController.get(editor)?.removeBrackets(this.id);
        }
    }
    class BracketsData {
        constructor(position, brackets, options) {
            this.position = position;
            this.brackets = brackets;
            this.options = options;
        }
    }
    class BracketMatchingController extends lifecycle_1.Disposable {
        static { this.ID = 'editor.contrib.bracketMatchingController'; }
        static get(editor) {
            return editor.getContribution(BracketMatchingController.ID);
        }
        constructor(editor) {
            super();
            this._editor = editor;
            this._lastBracketsData = [];
            this._lastVersionId = 0;
            this._decorations = this._editor.createDecorationsCollection();
            this._updateBracketsSoon = this._register(new async_1.RunOnceScheduler(() => this._updateBrackets(), 50));
            this._matchBrackets = this._editor.getOption(72 /* EditorOption.matchBrackets */);
            this._updateBracketsSoon.schedule();
            this._register(editor.onDidChangeCursorPosition((e) => {
                if (this._matchBrackets === 'never') {
                    // Early exit if nothing needs to be done!
                    // Leave some form of early exit check here if you wish to continue being a cursor position change listener ;)
                    return;
                }
                this._updateBracketsSoon.schedule();
            }));
            this._register(editor.onDidChangeModelContent((e) => {
                this._updateBracketsSoon.schedule();
            }));
            this._register(editor.onDidChangeModel((e) => {
                this._lastBracketsData = [];
                this._updateBracketsSoon.schedule();
            }));
            this._register(editor.onDidChangeModelLanguageConfiguration((e) => {
                this._lastBracketsData = [];
                this._updateBracketsSoon.schedule();
            }));
            this._register(editor.onDidChangeConfiguration((e) => {
                if (e.hasChanged(72 /* EditorOption.matchBrackets */)) {
                    this._matchBrackets = this._editor.getOption(72 /* EditorOption.matchBrackets */);
                    this._decorations.clear();
                    this._lastBracketsData = [];
                    this._lastVersionId = 0;
                    this._updateBracketsSoon.schedule();
                }
            }));
            this._register(editor.onDidBlurEditorWidget(() => {
                this._updateBracketsSoon.schedule();
            }));
            this._register(editor.onDidFocusEditorWidget(() => {
                this._updateBracketsSoon.schedule();
            }));
        }
        jumpToBracket() {
            if (!this._editor.hasModel()) {
                return;
            }
            const model = this._editor.getModel();
            const newSelections = this._editor.getSelections().map(selection => {
                const position = selection.getStartPosition();
                // find matching brackets if position is on a bracket
                const brackets = model.bracketPairs.matchBracket(position);
                let newCursorPosition = null;
                if (brackets) {
                    if (brackets[0].containsPosition(position) && !brackets[1].containsPosition(position)) {
                        newCursorPosition = brackets[1].getStartPosition();
                    }
                    else if (brackets[1].containsPosition(position)) {
                        newCursorPosition = brackets[0].getStartPosition();
                    }
                }
                else {
                    // find the enclosing brackets if the position isn't on a matching bracket
                    const enclosingBrackets = model.bracketPairs.findEnclosingBrackets(position);
                    if (enclosingBrackets) {
                        newCursorPosition = enclosingBrackets[1].getStartPosition();
                    }
                    else {
                        // no enclosing brackets, try the very first next bracket
                        const nextBracket = model.bracketPairs.findNextBracket(position);
                        if (nextBracket && nextBracket.range) {
                            newCursorPosition = nextBracket.range.getStartPosition();
                        }
                    }
                }
                if (newCursorPosition) {
                    return new selection_1.Selection(newCursorPosition.lineNumber, newCursorPosition.column, newCursorPosition.lineNumber, newCursorPosition.column);
                }
                return new selection_1.Selection(position.lineNumber, position.column, position.lineNumber, position.column);
            });
            this._editor.setSelections(newSelections);
            this._editor.revealRange(newSelections[0]);
        }
        selectToBracket(selectBrackets) {
            if (!this._editor.hasModel()) {
                return;
            }
            const model = this._editor.getModel();
            const newSelections = [];
            this._editor.getSelections().forEach(selection => {
                const position = selection.getStartPosition();
                let brackets = model.bracketPairs.matchBracket(position);
                if (!brackets) {
                    brackets = model.bracketPairs.findEnclosingBrackets(position);
                    if (!brackets) {
                        const nextBracket = model.bracketPairs.findNextBracket(position);
                        if (nextBracket && nextBracket.range) {
                            brackets = model.bracketPairs.matchBracket(nextBracket.range.getStartPosition());
                        }
                    }
                }
                let selectFrom = null;
                let selectTo = null;
                if (brackets) {
                    brackets.sort(range_1.Range.compareRangesUsingStarts);
                    const [open, close] = brackets;
                    selectFrom = selectBrackets ? open.getStartPosition() : open.getEndPosition();
                    selectTo = selectBrackets ? close.getEndPosition() : close.getStartPosition();
                    if (close.containsPosition(position)) {
                        // select backwards if the cursor was on the closing bracket
                        const tmp = selectFrom;
                        selectFrom = selectTo;
                        selectTo = tmp;
                    }
                }
                if (selectFrom && selectTo) {
                    newSelections.push(new selection_1.Selection(selectFrom.lineNumber, selectFrom.column, selectTo.lineNumber, selectTo.column));
                }
            });
            if (newSelections.length > 0) {
                this._editor.setSelections(newSelections);
                this._editor.revealRange(newSelections[0]);
            }
        }
        removeBrackets(editSource) {
            if (!this._editor.hasModel()) {
                return;
            }
            const model = this._editor.getModel();
            this._editor.getSelections().forEach((selection) => {
                const position = selection.getPosition();
                let brackets = model.bracketPairs.matchBracket(position);
                if (!brackets) {
                    brackets = model.bracketPairs.findEnclosingBrackets(position);
                }
                if (brackets) {
                    this._editor.pushUndoStop();
                    this._editor.executeEdits(editSource, [
                        { range: brackets[0], text: '' },
                        { range: brackets[1], text: '' }
                    ]);
                    this._editor.pushUndoStop();
                }
            });
        }
        static { this._DECORATION_OPTIONS_WITH_OVERVIEW_RULER = textModel_1.ModelDecorationOptions.register({
            description: 'bracket-match-overview',
            stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */,
            className: 'bracket-match',
            overviewRuler: {
                color: (0, themeService_1.themeColorFromId)(overviewRulerBracketMatchForeground),
                position: model_1.OverviewRulerLane.Center
            }
        }); }
        static { this._DECORATION_OPTIONS_WITHOUT_OVERVIEW_RULER = textModel_1.ModelDecorationOptions.register({
            description: 'bracket-match-no-overview',
            stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */,
            className: 'bracket-match'
        }); }
        _updateBrackets() {
            if (this._matchBrackets === 'never') {
                return;
            }
            this._recomputeBrackets();
            const newDecorations = [];
            let newDecorationsLen = 0;
            for (const bracketData of this._lastBracketsData) {
                const brackets = bracketData.brackets;
                if (brackets) {
                    newDecorations[newDecorationsLen++] = { range: brackets[0], options: bracketData.options };
                    newDecorations[newDecorationsLen++] = { range: brackets[1], options: bracketData.options };
                }
            }
            this._decorations.set(newDecorations);
        }
        _recomputeBrackets() {
            if (!this._editor.hasModel() || !this._editor.hasWidgetFocus()) {
                // no model or no focus => no brackets!
                this._lastBracketsData = [];
                this._lastVersionId = 0;
                return;
            }
            const selections = this._editor.getSelections();
            if (selections.length > 100) {
                // no bracket matching for high numbers of selections
                this._lastBracketsData = [];
                this._lastVersionId = 0;
                return;
            }
            const model = this._editor.getModel();
            const versionId = model.getVersionId();
            let previousData = [];
            if (this._lastVersionId === versionId) {
                // use the previous data only if the model is at the same version id
                previousData = this._lastBracketsData;
            }
            const positions = [];
            let positionsLen = 0;
            for (let i = 0, len = selections.length; i < len; i++) {
                const selection = selections[i];
                if (selection.isEmpty()) {
                    // will bracket match a cursor only if the selection is collapsed
                    positions[positionsLen++] = selection.getStartPosition();
                }
            }
            // sort positions for `previousData` cache hits
            if (positions.length > 1) {
                positions.sort(position_1.Position.compare);
            }
            const newData = [];
            let newDataLen = 0;
            let previousIndex = 0;
            const previousLen = previousData.length;
            for (let i = 0, len = positions.length; i < len; i++) {
                const position = positions[i];
                while (previousIndex < previousLen && previousData[previousIndex].position.isBefore(position)) {
                    previousIndex++;
                }
                if (previousIndex < previousLen && previousData[previousIndex].position.equals(position)) {
                    newData[newDataLen++] = previousData[previousIndex];
                }
                else {
                    let brackets = model.bracketPairs.matchBracket(position, 20 /* give at most 20ms to compute */);
                    let options = BracketMatchingController._DECORATION_OPTIONS_WITH_OVERVIEW_RULER;
                    if (!brackets && this._matchBrackets === 'always') {
                        brackets = model.bracketPairs.findEnclosingBrackets(position, 20 /* give at most 20ms to compute */);
                        options = BracketMatchingController._DECORATION_OPTIONS_WITHOUT_OVERVIEW_RULER;
                    }
                    newData[newDataLen++] = new BracketsData(position, brackets, options);
                }
            }
            this._lastBracketsData = newData;
            this._lastVersionId = versionId;
        }
    }
    exports.BracketMatchingController = BracketMatchingController;
    (0, editorExtensions_1.registerEditorContribution)(BracketMatchingController.ID, BracketMatchingController, 1 /* EditorContributionInstantiation.AfterFirstRender */);
    (0, editorExtensions_1.registerEditorAction)(SelectToBracketAction);
    (0, editorExtensions_1.registerEditorAction)(JumpToBracketAction);
    (0, editorExtensions_1.registerEditorAction)(RemoveBracketsAction);
    // Go to menu
    actions_1.MenuRegistry.appendMenuItem(actions_1.MenuId.MenubarGoMenu, {
        group: '5_infile_nav',
        command: {
            id: 'editor.action.jumpToBracket',
            title: nls.localize(720, "Go to &&Bracket")
        },
        order: 2
    });
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[421/*vs/editor/contrib/codeAction/browser/lightBulbWidget*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,69/*vs/base/browser/touch*/,26/*vs/base/common/codicons*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,30/*vs/base/common/themables*/,40/*vs/editor/common/model*/,35/*vs/editor/common/model/textModel*/,237/*vs/editor/common/model/utils*/,157/*vs/editor/contrib/codeAction/browser/codeAction*/,3/*vs/nls*/,31/*vs/platform/keybinding/common/keybinding*/,71/*vs/platform/theme/common/iconRegistry*/,4/*vs/editor/common/core/range*/,505/*vs/css!vs/editor/contrib/codeAction/browser/lightBulbWidget*/]), function (require, exports, dom, touch_1, codicons_1, event_1, lifecycle_1, themables_1, model_1, textModel_1, utils_1, codeAction_1, nls, keybinding_1, iconRegistry_1, range_1) {
    "use strict";
    var LightBulbWidget_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.LightBulbWidget = void 0;
    const GUTTER_LIGHTBULB_ICON = (0, iconRegistry_1.registerIcon)('gutter-lightbulb', codicons_1.Codicon.lightBulb, nls.localize(785, 'Icon which spawns code actions menu from the gutter when there is no space in the editor.'));
    const GUTTER_LIGHTBULB_AUTO_FIX_ICON = (0, iconRegistry_1.registerIcon)('gutter-lightbulb-auto-fix', codicons_1.Codicon.lightbulbAutofix, nls.localize(786, 'Icon which spawns code actions menu from the gutter when there is no space in the editor and a quick fix is available.'));
    const GUTTER_LIGHTBULB_AIFIX_ICON = (0, iconRegistry_1.registerIcon)('gutter-lightbulb-sparkle', codicons_1.Codicon.lightbulbSparkle, nls.localize(787, 'Icon which spawns code actions menu from the gutter when there is no space in the editor and an AI fix is available.'));
    const GUTTER_LIGHTBULB_AIFIX_AUTO_FIX_ICON = (0, iconRegistry_1.registerIcon)('gutter-lightbulb-aifix-auto-fix', codicons_1.Codicon.lightbulbSparkleAutofix, nls.localize(788, 'Icon which spawns code actions menu from the gutter when there is no space in the editor and an AI fix and a quick fix is available.'));
    const GUTTER_SPARKLE_FILLED_ICON = (0, iconRegistry_1.registerIcon)('gutter-lightbulb-sparkle-filled', codicons_1.Codicon.sparkleFilled, nls.localize(789, 'Icon which spawns code actions menu from the gutter when there is no space in the editor and an AI fix and a quick fix is available.'));
    var LightBulbState;
    (function (LightBulbState) {
        LightBulbState.Hidden = { type: 0 /* Type.Hidden */ };
        class Showing {
            constructor(actions, trigger, editorPosition, widgetPosition) {
                this.actions = actions;
                this.trigger = trigger;
                this.editorPosition = editorPosition;
                this.widgetPosition = widgetPosition;
                this.type = 1 /* Type.Showing */;
            }
        }
        LightBulbState.Showing = Showing;
    })(LightBulbState || (LightBulbState = {}));
    let LightBulbWidget = class LightBulbWidget extends lifecycle_1.Disposable {
        static { LightBulbWidget_1 = this; }
        static { this.GUTTER_DECORATION = textModel_1.ModelDecorationOptions.register({
            description: 'codicon-gutter-lightbulb-decoration',
            glyphMarginClassName: themables_1.ThemeIcon.asClassName(codicons_1.Codicon.lightBulb),
            glyphMargin: { position: model_1.GlyphMarginLane.Left },
            stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */,
        }); }
        static { this.ID = 'editor.contrib.lightbulbWidget'; }
        static { this._posPref = [0 /* ContentWidgetPositionPreference.EXACT */]; }
        constructor(_editor, _keybindingService) {
            super();
            this._editor = _editor;
            this._keybindingService = _keybindingService;
            this._onClick = this._register(new event_1.Emitter());
            this.onClick = this._onClick.event;
            this._state = LightBulbState.Hidden;
            this._gutterState = LightBulbState.Hidden;
            this._iconClasses = [];
            this.lightbulbClasses = [
                'codicon-' + GUTTER_LIGHTBULB_ICON.id,
                'codicon-' + GUTTER_LIGHTBULB_AIFIX_AUTO_FIX_ICON.id,
                'codicon-' + GUTTER_LIGHTBULB_AUTO_FIX_ICON.id,
                'codicon-' + GUTTER_LIGHTBULB_AIFIX_ICON.id,
                'codicon-' + GUTTER_SPARKLE_FILLED_ICON.id
            ];
            this.gutterDecoration = LightBulbWidget_1.GUTTER_DECORATION;
            this._domNode = dom.$('div.lightBulbWidget');
            this._domNode.role = 'listbox';
            this._register(touch_1.Gesture.ignoreTarget(this._domNode));
            this._editor.addContentWidget(this);
            this._register(this._editor.onDidChangeModelContent(_ => {
                // cancel when the line in question has been removed
                const editorModel = this._editor.getModel();
                if (this.state.type !== 1 /* LightBulbState.Type.Showing */ || !editorModel || this.state.editorPosition.lineNumber >= editorModel.getLineCount()) {
                    this.hide();
                }
                if (this.gutterState.type !== 1 /* LightBulbState.Type.Showing */ || !editorModel || this.gutterState.editorPosition.lineNumber >= editorModel.getLineCount()) {
                    this.gutterHide();
                }
            }));
            this._register(dom.addStandardDisposableGenericMouseDownListener(this._domNode, e => {
                if (this.state.type !== 1 /* LightBulbState.Type.Showing */) {
                    return;
                }
                // Make sure that focus / cursor location is not lost when clicking widget icon
                this._editor.focus();
                e.preventDefault();
                // a bit of extra work to make sure the menu
                // doesn't cover the line-text
                const { top, height } = dom.getDomNodePagePosition(this._domNode);
                const lineHeight = this._editor.getOption(67 /* EditorOption.lineHeight */);
                let pad = Math.floor(lineHeight / 3);
                if (this.state.widgetPosition.position !== null && this.state.widgetPosition.position.lineNumber < this.state.editorPosition.lineNumber) {
                    pad += lineHeight;
                }
                this._onClick.fire({
                    x: e.posx,
                    y: top + height + pad,
                    actions: this.state.actions,
                    trigger: this.state.trigger,
                });
            }));
            this._register(dom.addDisposableListener(this._domNode, 'mouseenter', (e) => {
                if ((e.buttons & 1) !== 1) {
                    return;
                }
                // mouse enters lightbulb while the primary/left button
                // is being pressed -> hide the lightbulb
                this.hide();
            }));
            this._register(event_1.Event.runAndSubscribe(this._keybindingService.onDidUpdateKeybindings, () => {
                this._preferredKbLabel = this._keybindingService.lookupKeybinding(codeAction_1.autoFixCommandId)?.getLabel() ?? undefined;
                this._quickFixKbLabel = this._keybindingService.lookupKeybinding(codeAction_1.quickFixCommandId)?.getLabel() ?? undefined;
                this._updateLightBulbTitleAndIcon();
            }));
            this._register(this._editor.onMouseDown(async (e) => {
                if (!e.target.element || !this.lightbulbClasses.some(cls => e.target.element && e.target.element.classList.contains(cls))) {
                    return;
                }
                if (this.gutterState.type !== 1 /* LightBulbState.Type.Showing */) {
                    return;
                }
                // Make sure that focus / cursor location is not lost when clicking widget icon
                this._editor.focus();
                // a bit of extra work to make sure the menu
                // doesn't cover the line-text
                const { top, height } = dom.getDomNodePagePosition(e.target.element);
                const lineHeight = this._editor.getOption(67 /* EditorOption.lineHeight */);
                let pad = Math.floor(lineHeight / 3);
                if (this.gutterState.widgetPosition.position !== null && this.gutterState.widgetPosition.position.lineNumber < this.gutterState.editorPosition.lineNumber) {
                    pad += lineHeight;
                }
                this._onClick.fire({
                    x: e.event.posx,
                    y: top + height + pad,
                    actions: this.gutterState.actions,
                    trigger: this.gutterState.trigger,
                });
            }));
        }
        dispose() {
            super.dispose();
            this._editor.removeContentWidget(this);
            if (this._gutterDecorationID) {
                this._removeGutterDecoration(this._gutterDecorationID);
            }
        }
        getId() {
            return 'LightBulbWidget';
        }
        getDomNode() {
            return this._domNode;
        }
        getPosition() {
            return this._state.type === 1 /* LightBulbState.Type.Showing */ ? this._state.widgetPosition : null;
        }
        update(actions, trigger, atPosition) {
            if (actions.validActions.length <= 0) {
                this.gutterHide();
                return this.hide();
            }
            const hasTextFocus = this._editor.hasTextFocus();
            if (!hasTextFocus) {
                this.gutterHide();
                return this.hide();
            }
            const options = this._editor.getOptions();
            if (!options.get(65 /* EditorOption.lightbulb */).enabled) {
                this.gutterHide();
                return this.hide();
            }
            const model = this._editor.getModel();
            if (!model) {
                this.gutterHide();
                return this.hide();
            }
            const { lineNumber, column } = model.validatePosition(atPosition);
            const tabSize = model.getOptions().tabSize;
            const fontInfo = this._editor.getOptions().get(50 /* EditorOption.fontInfo */);
            const lineContent = model.getLineContent(lineNumber);
            const indent = (0, utils_1.computeIndentLevel)(lineContent, tabSize);
            const lineHasSpace = fontInfo.spaceWidth * indent > 22;
            const isFolded = (lineNumber) => {
                return lineNumber > 2 && this._editor.getTopForLineNumber(lineNumber) === this._editor.getTopForLineNumber(lineNumber - 1);
            };
            // Check for glyph margin decorations of any kind
            const currLineDecorations = this._editor.getLineDecorations(lineNumber);
            let hasDecoration = false;
            if (currLineDecorations) {
                for (const decoration of currLineDecorations) {
                    const glyphClass = decoration.options.glyphMarginClassName;
                    if (glyphClass && !this.lightbulbClasses.some(className => glyphClass.includes(className))) {
                        hasDecoration = true;
                        break;
                    }
                }
            }
            let effectiveLineNumber = lineNumber;
            let effectiveColumnNumber = 1;
            if (!lineHasSpace) {
                // Checks if line is empty or starts with any amount of whitespace
                const isLineEmptyOrIndented = (lineNumber) => {
                    const lineContent = model.getLineContent(lineNumber);
                    return /^\s*$|^\s+/.test(lineContent) || lineContent.length <= effectiveColumnNumber;
                };
                if (lineNumber > 1 && !isFolded(lineNumber - 1)) {
                    const lineCount = model.getLineCount();
                    const endLine = lineNumber === lineCount;
                    const prevLineEmptyOrIndented = lineNumber > 1 && isLineEmptyOrIndented(lineNumber - 1);
                    const nextLineEmptyOrIndented = !endLine && isLineEmptyOrIndented(lineNumber + 1);
                    const currLineEmptyOrIndented = isLineEmptyOrIndented(lineNumber);
                    const notEmpty = !nextLineEmptyOrIndented && !prevLineEmptyOrIndented;
                    // check above and below. if both are blocked, display lightbulb in the gutter.
                    if (!nextLineEmptyOrIndented && !prevLineEmptyOrIndented && !hasDecoration) {
                        this.gutterState = new LightBulbState.Showing(actions, trigger, atPosition, {
                            position: { lineNumber: effectiveLineNumber, column: effectiveColumnNumber },
                            preference: LightBulbWidget_1._posPref
                        });
                        this.renderGutterLightbub();
                        return this.hide();
                    }
                    else if (prevLineEmptyOrIndented || endLine || (prevLineEmptyOrIndented && !currLineEmptyOrIndented)) {
                        effectiveLineNumber -= 1;
                    }
                    else if (nextLineEmptyOrIndented || (notEmpty && currLineEmptyOrIndented)) {
                        effectiveLineNumber += 1;
                    }
                }
                else if (lineNumber === 1 && (lineNumber === model.getLineCount() || !isLineEmptyOrIndented(lineNumber + 1) && !isLineEmptyOrIndented(lineNumber))) {
                    // special checks for first line blocked vs. not blocked.
                    this.gutterState = new LightBulbState.Showing(actions, trigger, atPosition, {
                        position: { lineNumber: effectiveLineNumber, column: effectiveColumnNumber },
                        preference: LightBulbWidget_1._posPref
                    });
                    if (hasDecoration) {
                        this.gutterHide();
                    }
                    else {
                        this.renderGutterLightbub();
                        return this.hide();
                    }
                }
                else if ((lineNumber < model.getLineCount()) && !isFolded(lineNumber + 1)) {
                    effectiveLineNumber += 1;
                }
                else if (column * fontInfo.spaceWidth < 22) {
                    // cannot show lightbulb above/below and showing
                    // it inline would overlay the cursor...
                    return this.hide();
                }
                effectiveColumnNumber = /^\S\s*$/.test(model.getLineContent(effectiveLineNumber)) ? 2 : 1;
            }
            this.state = new LightBulbState.Showing(actions, trigger, atPosition, {
                position: { lineNumber: effectiveLineNumber, column: effectiveColumnNumber },
                preference: LightBulbWidget_1._posPref
            });
            if (this._gutterDecorationID) {
                this._removeGutterDecoration(this._gutterDecorationID);
                this.gutterHide();
            }
            const validActions = actions.validActions;
            const actionKind = actions.validActions[0].action.kind;
            if (validActions.length !== 1 || !actionKind) {
                this._editor.layoutContentWidget(this);
                return;
            }
            this._editor.layoutContentWidget(this);
        }
        hide() {
            if (this.state === LightBulbState.Hidden) {
                return;
            }
            this.state = LightBulbState.Hidden;
            this._editor.layoutContentWidget(this);
        }
        gutterHide() {
            if (this.gutterState === LightBulbState.Hidden) {
                return;
            }
            if (this._gutterDecorationID) {
                this._removeGutterDecoration(this._gutterDecorationID);
            }
            this.gutterState = LightBulbState.Hidden;
        }
        get state() { return this._state; }
        set state(value) {
            this._state = value;
            this._updateLightBulbTitleAndIcon();
        }
        get gutterState() { return this._gutterState; }
        set gutterState(value) {
            this._gutterState = value;
            this._updateGutterLightBulbTitleAndIcon();
        }
        _updateLightBulbTitleAndIcon() {
            this._domNode.classList.remove(...this._iconClasses);
            this._iconClasses = [];
            if (this.state.type !== 1 /* LightBulbState.Type.Showing */) {
                return;
            }
            let icon;
            let autoRun = false;
            if (this.state.actions.allAIFixes) {
                icon = codicons_1.Codicon.sparkleFilled;
                if (this.state.actions.validActions.length === 1) {
                    autoRun = true;
                }
            }
            else if (this.state.actions.hasAutoFix) {
                if (this.state.actions.hasAIFix) {
                    icon = codicons_1.Codicon.lightbulbSparkleAutofix;
                }
                else {
                    icon = codicons_1.Codicon.lightbulbAutofix;
                }
            }
            else if (this.state.actions.hasAIFix) {
                icon = codicons_1.Codicon.lightbulbSparkle;
            }
            else {
                icon = codicons_1.Codicon.lightBulb;
            }
            this._updateLightbulbTitle(this.state.actions.hasAutoFix, autoRun);
            this._iconClasses = themables_1.ThemeIcon.asClassNameArray(icon);
            this._domNode.classList.add(...this._iconClasses);
        }
        _updateGutterLightBulbTitleAndIcon() {
            if (this.gutterState.type !== 1 /* LightBulbState.Type.Showing */) {
                return;
            }
            let icon;
            let autoRun = false;
            if (this.gutterState.actions.allAIFixes) {
                icon = GUTTER_SPARKLE_FILLED_ICON;
                if (this.gutterState.actions.validActions.length === 1) {
                    autoRun = true;
                }
            }
            else if (this.gutterState.actions.hasAutoFix) {
                if (this.gutterState.actions.hasAIFix) {
                    icon = GUTTER_LIGHTBULB_AIFIX_AUTO_FIX_ICON;
                }
                else {
                    icon = GUTTER_LIGHTBULB_AUTO_FIX_ICON;
                }
            }
            else if (this.gutterState.actions.hasAIFix) {
                icon = GUTTER_LIGHTBULB_AIFIX_ICON;
            }
            else {
                icon = GUTTER_LIGHTBULB_ICON;
            }
            this._updateLightbulbTitle(this.gutterState.actions.hasAutoFix, autoRun);
            const GUTTER_DECORATION = textModel_1.ModelDecorationOptions.register({
                description: 'codicon-gutter-lightbulb-decoration',
                glyphMarginClassName: themables_1.ThemeIcon.asClassName(icon),
                glyphMargin: { position: model_1.GlyphMarginLane.Left },
                stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */,
            });
            this.gutterDecoration = GUTTER_DECORATION;
        }
        /* Gutter Helper Functions */
        renderGutterLightbub() {
            const selection = this._editor.getSelection();
            if (!selection) {
                return;
            }
            if (this._gutterDecorationID === undefined) {
                this._addGutterDecoration(selection.startLineNumber);
            }
            else {
                this._updateGutterDecoration(this._gutterDecorationID, selection.startLineNumber);
            }
        }
        _addGutterDecoration(lineNumber) {
            this._editor.changeDecorations((accessor) => {
                this._gutterDecorationID = accessor.addDecoration(new range_1.Range(lineNumber, 0, lineNumber, 0), this.gutterDecoration);
            });
        }
        _removeGutterDecoration(decorationId) {
            this._editor.changeDecorations((accessor) => {
                accessor.removeDecoration(decorationId);
                this._gutterDecorationID = undefined;
            });
        }
        _updateGutterDecoration(decorationId, lineNumber) {
            this._editor.changeDecorations((accessor) => {
                accessor.changeDecoration(decorationId, new range_1.Range(lineNumber, 0, lineNumber, 0));
                accessor.changeDecorationOptions(decorationId, this.gutterDecoration);
            });
        }
        _updateLightbulbTitle(autoFix, autoRun) {
            if (this.state.type !== 1 /* LightBulbState.Type.Showing */) {
                return;
            }
            if (autoRun) {
                this.title = nls.localize(790, "Run: {0}", this.state.actions.validActions[0].action.title);
            }
            else if (autoFix && this._preferredKbLabel) {
                this.title = nls.localize(791, "Show Code Actions. Preferred Quick Fix Available ({0})", this._preferredKbLabel);
            }
            else if (!autoFix && this._quickFixKbLabel) {
                this.title = nls.localize(792, "Show Code Actions ({0})", this._quickFixKbLabel);
            }
            else if (!autoFix) {
                this.title = nls.localize(793, "Show Code Actions");
            }
        }
        set title(value) {
            this._domNode.title = value;
        }
    };
    exports.LightBulbWidget = LightBulbWidget;
    exports.LightBulbWidget = LightBulbWidget = LightBulbWidget_1 = __decorate([
        __param(1, keybinding_1.IKeybindingService)
    ], LightBulbWidget);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[287/*vs/editor/contrib/codeAction/browser/codeActionController*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,46/*vs/base/browser/ui/aria/aria*/,8/*vs/base/common/errors*/,98/*vs/base/common/lazy*/,2/*vs/base/common/lifecycle*/,9/*vs/editor/common/core/position*/,35/*vs/editor/common/model/textModel*/,17/*vs/editor/common/services/languageFeatures*/,157/*vs/editor/contrib/codeAction/browser/codeAction*/,733/*vs/editor/contrib/codeAction/browser/codeActionKeybindingResolver*/,757/*vs/editor/contrib/codeAction/browser/codeActionMenu*/,421/*vs/editor/contrib/codeAction/browser/lightBulbWidget*/,184/*vs/editor/contrib/message/browser/messageController*/,3/*vs/nls*/,760/*vs/platform/actionWidget/browser/actionWidget*/,24/*vs/platform/commands/common/commands*/,28/*vs/platform/configuration/common/configuration*/,12/*vs/platform/contextkey/common/contextkey*/,7/*vs/platform/instantiation/common/instantiation*/,108/*vs/platform/markers/common/markers*/,96/*vs/platform/progress/common/progress*/,32/*vs/platform/theme/common/colorRegistry*/,97/*vs/platform/theme/common/theme*/,25/*vs/platform/theme/common/themeService*/,134/*vs/editor/contrib/codeAction/common/types*/,408/*vs/editor/contrib/codeAction/browser/codeActionModel*/,91/*vs/base/common/hierarchicalKind*/,63/*vs/platform/telemetry/common/telemetry*/]), function (require, exports, dom_1, aria, errors_1, lazy_1, lifecycle_1, position_1, textModel_1, languageFeatures_1, codeAction_1, codeActionKeybindingResolver_1, codeActionMenu_1, lightBulbWidget_1, messageController_1, nls_1, actionWidget_1, commands_1, configuration_1, contextkey_1, instantiation_1, markers_1, progress_1, colorRegistry_1, theme_1, themeService_1, types_1, codeActionModel_1, hierarchicalKind_1, telemetry_1) {
    "use strict";
    var CodeActionController_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CodeActionController = void 0;
    const DECORATION_CLASS_NAME = 'quickfix-edit-highlight';
    let CodeActionController = class CodeActionController extends lifecycle_1.Disposable {
        static { CodeActionController_1 = this; }
        static { this.ID = 'editor.contrib.codeActionController'; }
        static get(editor) {
            return editor.getContribution(CodeActionController_1.ID);
        }
        constructor(editor, markerService, contextKeyService, instantiationService, languageFeaturesService, progressService, _commandService, _configurationService, _actionWidgetService, _instantiationService, _telemetryService) {
            super();
            this._commandService = _commandService;
            this._configurationService = _configurationService;
            this._actionWidgetService = _actionWidgetService;
            this._instantiationService = _instantiationService;
            this._telemetryService = _telemetryService;
            this._activeCodeActions = this._register(new lifecycle_1.MutableDisposable());
            this._showDisabled = false;
            this._disposed = false;
            this._editor = editor;
            this._model = this._register(new codeActionModel_1.CodeActionModel(this._editor, languageFeaturesService.codeActionProvider, markerService, contextKeyService, progressService, _configurationService, this._telemetryService));
            this._register(this._model.onDidChangeState(newState => this.update(newState)));
            this._lightBulbWidget = new lazy_1.Lazy(() => {
                const widget = this._editor.getContribution(lightBulbWidget_1.LightBulbWidget.ID);
                if (widget) {
                    this._register(widget.onClick(e => this.showCodeActionsFromLightbulb(e.actions, e)));
                }
                return widget;
            });
            this._resolver = instantiationService.createInstance(codeActionKeybindingResolver_1.CodeActionKeybindingResolver);
            this._register(this._editor.onDidLayoutChange(() => this._actionWidgetService.hide()));
        }
        dispose() {
            this._disposed = true;
            super.dispose();
        }
        async showCodeActionsFromLightbulb(actions, at) {
            if (actions.allAIFixes && actions.validActions.length === 1) {
                const actionItem = actions.validActions[0];
                const command = actionItem.action.command;
                if (command && command.id === 'inlineChat.start') {
                    if (command.arguments && command.arguments.length >= 1) {
                        command.arguments[0] = { ...command.arguments[0], autoSend: false };
                    }
                }
                await this._applyCodeAction(actionItem, false, false, codeAction_1.ApplyCodeActionReason.FromAILightbulb);
                return;
            }
            await this.showCodeActionList(actions, at, { includeDisabledActions: false, fromLightbulb: true });
        }
        showCodeActions(_trigger, actions, at) {
            return this.showCodeActionList(actions, at, { includeDisabledActions: false, fromLightbulb: false });
        }
        manualTriggerAtCurrentPosition(notAvailableMessage, triggerAction, filter, autoApply) {
            if (!this._editor.hasModel()) {
                return;
            }
            messageController_1.MessageController.get(this._editor)?.closeMessage();
            const triggerPosition = this._editor.getPosition();
            this._trigger({ type: 1 /* CodeActionTriggerType.Invoke */, triggerAction, filter, autoApply, context: { notAvailableMessage, position: triggerPosition } });
        }
        _trigger(trigger) {
            return this._model.trigger(trigger);
        }
        async _applyCodeAction(action, retrigger, preview, actionReason) {
            try {
                await this._instantiationService.invokeFunction(codeAction_1.applyCodeAction, action, actionReason, { preview, editor: this._editor });
            }
            finally {
                if (retrigger) {
                    this._trigger({ type: 2 /* CodeActionTriggerType.Auto */, triggerAction: types_1.CodeActionTriggerSource.QuickFix, filter: {} });
                }
            }
        }
        hideLightBulbWidget() {
            this._lightBulbWidget.rawValue?.hide();
            this._lightBulbWidget.rawValue?.gutterHide();
        }
        async update(newState) {
            if (newState.type !== 1 /* CodeActionsState.Type.Triggered */) {
                this.hideLightBulbWidget();
                return;
            }
            let actions;
            try {
                actions = await newState.actions;
            }
            catch (e) {
                (0, errors_1.onUnexpectedError)(e);
                return;
            }
            if (this._disposed) {
                return;
            }
            const selection = this._editor.getSelection();
            if (selection?.startLineNumber !== newState.position.lineNumber) {
                return;
            }
            this._lightBulbWidget.value?.update(actions, newState.trigger, newState.position);
            if (newState.trigger.type === 1 /* CodeActionTriggerType.Invoke */) {
                if (newState.trigger.filter?.include) { // Triggered for specific scope
                    // Check to see if we want to auto apply.
                    const validActionToApply = this.tryGetValidActionToApply(newState.trigger, actions);
                    if (validActionToApply) {
                        try {
                            this.hideLightBulbWidget();
                            await this._applyCodeAction(validActionToApply, false, false, codeAction_1.ApplyCodeActionReason.FromCodeActions);
                        }
                        finally {
                            actions.dispose();
                        }
                        return;
                    }
                    // Check to see if there is an action that we would have applied were it not invalid
                    if (newState.trigger.context) {
                        const invalidAction = this.getInvalidActionThatWouldHaveBeenApplied(newState.trigger, actions);
                        if (invalidAction && invalidAction.action.disabled) {
                            messageController_1.MessageController.get(this._editor)?.showMessage(invalidAction.action.disabled, newState.trigger.context.position);
                            actions.dispose();
                            return;
                        }
                    }
                }
                const includeDisabledActions = !!newState.trigger.filter?.include;
                if (newState.trigger.context) {
                    if (!actions.allActions.length || !includeDisabledActions && !actions.validActions.length) {
                        messageController_1.MessageController.get(this._editor)?.showMessage(newState.trigger.context.notAvailableMessage, newState.trigger.context.position);
                        this._activeCodeActions.value = actions;
                        actions.dispose();
                        return;
                    }
                }
                this._activeCodeActions.value = actions;
                this.showCodeActionList(actions, this.toCoords(newState.position), { includeDisabledActions, fromLightbulb: false });
            }
            else {
                // auto magically triggered
                if (this._actionWidgetService.isVisible) {
                    // TODO: Figure out if we should update the showing menu?
                    actions.dispose();
                }
                else {
                    this._activeCodeActions.value = actions;
                }
            }
        }
        getInvalidActionThatWouldHaveBeenApplied(trigger, actions) {
            if (!actions.allActions.length) {
                return undefined;
            }
            if ((trigger.autoApply === "first" /* CodeActionAutoApply.First */ && actions.validActions.length === 0)
                || (trigger.autoApply === "ifSingle" /* CodeActionAutoApply.IfSingle */ && actions.allActions.length === 1)) {
                return actions.allActions.find(({ action }) => action.disabled);
            }
            return undefined;
        }
        tryGetValidActionToApply(trigger, actions) {
            if (!actions.validActions.length) {
                return undefined;
            }
            if ((trigger.autoApply === "first" /* CodeActionAutoApply.First */ && actions.validActions.length > 0)
                || (trigger.autoApply === "ifSingle" /* CodeActionAutoApply.IfSingle */ && actions.validActions.length === 1)) {
                return actions.validActions[0];
            }
            return undefined;
        }
        static { this.DECORATION = textModel_1.ModelDecorationOptions.register({
            description: 'quickfix-highlight',
            className: DECORATION_CLASS_NAME
        }); }
        async showCodeActionList(actions, at, options) {
            const currentDecorations = this._editor.createDecorationsCollection();
            const editorDom = this._editor.getDomNode();
            if (!editorDom) {
                return;
            }
            const actionsToShow = options.includeDisabledActions && (this._showDisabled || actions.validActions.length === 0) ? actions.allActions : actions.validActions;
            if (!actionsToShow.length) {
                return;
            }
            const anchor = position_1.Position.isIPosition(at) ? this.toCoords(at) : at;
            const delegate = {
                onSelect: async (action, preview) => {
                    this._applyCodeAction(action, /* retrigger */ true, !!preview, options.fromLightbulb ? codeAction_1.ApplyCodeActionReason.FromAILightbulb : codeAction_1.ApplyCodeActionReason.FromCodeActions);
                    this._actionWidgetService.hide(false);
                    currentDecorations.clear();
                },
                onHide: (didCancel) => {
                    this._editor?.focus();
                    currentDecorations.clear();
                },
                onHover: async (action, token) => {
                    if (token.isCancellationRequested) {
                        return;
                    }
                    let canPreview = false;
                    const actionKind = action.action.kind;
                    if (actionKind) {
                        const hierarchicalKind = new hierarchicalKind_1.HierarchicalKind(actionKind);
                        const refactorKinds = [
                            types_1.CodeActionKind.RefactorExtract,
                            types_1.CodeActionKind.RefactorInline,
                            types_1.CodeActionKind.RefactorRewrite,
                            types_1.CodeActionKind.RefactorMove,
                            types_1.CodeActionKind.Source
                        ];
                        canPreview = refactorKinds.some(refactorKind => refactorKind.contains(hierarchicalKind));
                    }
                    return { canPreview: canPreview || !!action.action.edit?.edits.length };
                },
                onFocus: (action) => {
                    if (action && action.action) {
                        const ranges = action.action.ranges;
                        const diagnostics = action.action.diagnostics;
                        currentDecorations.clear();
                        if (ranges && ranges.length > 0) {
                            // Handles case for `fix all` where there are multiple diagnostics.
                            const decorations = (diagnostics && diagnostics?.length > 1)
                                ? diagnostics.map(diagnostic => ({ range: diagnostic, options: CodeActionController_1.DECORATION }))
                                : ranges.map(range => ({ range, options: CodeActionController_1.DECORATION }));
                            currentDecorations.set(decorations);
                        }
                        else if (diagnostics && diagnostics.length > 0) {
                            const decorations = diagnostics.map(diagnostic => ({ range: diagnostic, options: CodeActionController_1.DECORATION }));
                            currentDecorations.set(decorations);
                            const diagnostic = diagnostics[0];
                            if (diagnostic.startLineNumber && diagnostic.startColumn) {
                                const selectionText = this._editor.getModel()?.getWordAtPosition({ lineNumber: diagnostic.startLineNumber, column: diagnostic.startColumn })?.word;
                                aria.status((0, nls_1.localize)(774, "Context: {0} at line {1} and column {2}.", selectionText, diagnostic.startLineNumber, diagnostic.startColumn));
                            }
                        }
                    }
                    else {
                        currentDecorations.clear();
                    }
                }
            };
            this._actionWidgetService.show('codeActionWidget', true, (0, codeActionMenu_1.toMenuItems)(actionsToShow, this._shouldShowHeaders(), this._resolver.getResolver()), delegate, anchor, editorDom, this._getActionBarActions(actions, at, options));
        }
        toCoords(position) {
            if (!this._editor.hasModel()) {
                return { x: 0, y: 0 };
            }
            this._editor.revealPosition(position, 1 /* ScrollType.Immediate */);
            this._editor.render();
            // Translate to absolute editor position
            const cursorCoords = this._editor.getScrolledVisiblePosition(position);
            const editorCoords = (0, dom_1.getDomNodePagePosition)(this._editor.getDomNode());
            const x = editorCoords.left + cursorCoords.left;
            const y = editorCoords.top + cursorCoords.top + cursorCoords.height;
            return { x, y };
        }
        _shouldShowHeaders() {
            const model = this._editor?.getModel();
            return this._configurationService.getValue('editor.codeActionWidget.showHeaders', { resource: model?.uri });
        }
        _getActionBarActions(actions, at, options) {
            if (options.fromLightbulb) {
                return [];
            }
            const resultActions = actions.documentation.map((command) => ({
                id: command.id,
                label: command.title,
                tooltip: command.tooltip ?? '',
                class: undefined,
                enabled: true,
                run: () => this._commandService.executeCommand(command.id, ...(command.arguments ?? [])),
            }));
            if (options.includeDisabledActions && actions.validActions.length > 0 && actions.allActions.length !== actions.validActions.length) {
                resultActions.push(this._showDisabled ? {
                    id: 'hideMoreActions',
                    label: (0, nls_1.localize)(775, 'Hide Disabled'),
                    enabled: true,
                    tooltip: '',
                    class: undefined,
                    run: () => {
                        this._showDisabled = false;
                        return this.showCodeActionList(actions, at, options);
                    }
                } : {
                    id: 'showMoreActions',
                    label: (0, nls_1.localize)(776, 'Show Disabled'),
                    enabled: true,
                    tooltip: '',
                    class: undefined,
                    run: () => {
                        this._showDisabled = true;
                        return this.showCodeActionList(actions, at, options);
                    }
                });
            }
            return resultActions;
        }
    };
    exports.CodeActionController = CodeActionController;
    exports.CodeActionController = CodeActionController = CodeActionController_1 = __decorate([
        __param(1, markers_1.IMarkerService),
        __param(2, contextkey_1.IContextKeyService),
        __param(3, instantiation_1.IInstantiationService),
        __param(4, languageFeatures_1.ILanguageFeaturesService),
        __param(5, progress_1.IEditorProgressService),
        __param(6, commands_1.ICommandService),
        __param(7, configuration_1.IConfigurationService),
        __param(8, actionWidget_1.IActionWidgetService),
        __param(9, instantiation_1.IInstantiationService),
        __param(10, telemetry_1.ITelemetryService)
    ], CodeActionController);
    (0, themeService_1.registerThemingParticipant)((theme, collector) => {
        const addBackgroundColorRule = (selector, color) => {
            if (color) {
                collector.addRule(`.monaco-editor ${selector} { background-color: ${color}; }`);
            }
        };
        addBackgroundColorRule('.quickfix-edit-highlight', theme.getColor(colorRegistry_1.editorFindMatchHighlight));
        const findMatchHighlightBorder = theme.getColor(colorRegistry_1.editorFindMatchHighlightBorder);
        if (findMatchHighlightBorder) {
            collector.addRule(`.monaco-editor .quickfix-edit-highlight { border: 1px ${(0, theme_1.isHighContrast)(theme.type) ? 'dotted' : 'solid'} ${findMatchHighlightBorder}; box-sizing: border-box; }`);
        }
    });
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[816/*vs/editor/contrib/codeAction/browser/codeActionCommands*/], __M([1/*require*/,0/*exports*/,91/*vs/base/common/hierarchicalKind*/,11/*vs/base/common/strings*/,15/*vs/editor/browser/editorExtensions*/,20/*vs/editor/common/editorContextKeys*/,157/*vs/editor/contrib/codeAction/browser/codeAction*/,3/*vs/nls*/,12/*vs/platform/contextkey/common/contextkey*/,134/*vs/editor/contrib/codeAction/common/types*/,287/*vs/editor/contrib/codeAction/browser/codeActionController*/,408/*vs/editor/contrib/codeAction/browser/codeActionModel*/]), function (require, exports, hierarchicalKind_1, strings_1, editorExtensions_1, editorContextKeys_1, codeAction_1, nls, contextkey_1, types_1, codeActionController_1, codeActionModel_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AutoFixAction = exports.FixAllAction = exports.OrganizeImportsAction = exports.SourceAction = exports.RefactorAction = exports.CodeActionCommand = exports.QuickFixAction = void 0;
    function contextKeyForSupportedActions(kind) {
        return contextkey_1.ContextKeyExpr.regex(codeActionModel_1.SUPPORTED_CODE_ACTIONS.keys()[0], new RegExp('(\\s|^)' + (0, strings_1.escapeRegExpCharacters)(kind.value) + '\\b'));
    }
    const argsSchema = {
        type: 'object',
        defaultSnippets: [{ body: { kind: '' } }],
        properties: {
            'kind': {
                type: 'string',
                description: nls.localize(743, "Kind of the code action to run."),
            },
            'apply': {
                type: 'string',
                description: nls.localize(744, "Controls when the returned actions are applied."),
                default: "ifSingle" /* CodeActionAutoApply.IfSingle */,
                enum: ["first" /* CodeActionAutoApply.First */, "ifSingle" /* CodeActionAutoApply.IfSingle */, "never" /* CodeActionAutoApply.Never */],
                enumDescriptions: [
                    nls.localize(745, "Always apply the first returned code action."),
                    nls.localize(746, "Apply the first returned code action if it is the only one."),
                    nls.localize(747, "Do not apply the returned code actions."),
                ]
            },
            'preferred': {
                type: 'boolean',
                default: false,
                description: nls.localize(748, "Controls if only preferred code actions should be returned."),
            }
        }
    };
    function triggerCodeActionsForEditorSelection(editor, notAvailableMessage, filter, autoApply, triggerAction = types_1.CodeActionTriggerSource.Default) {
        if (editor.hasModel()) {
            const controller = codeActionController_1.CodeActionController.get(editor);
            controller?.manualTriggerAtCurrentPosition(notAvailableMessage, triggerAction, filter, autoApply);
        }
    }
    class QuickFixAction extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: codeAction_1.quickFixCommandId,
                label: nls.localize(749, "Quick Fix..."),
                alias: 'Quick Fix...',
                precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, editorContextKeys_1.EditorContextKeys.hasCodeActionsProvider),
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                    primary: 2048 /* KeyMod.CtrlCmd */ | 89 /* KeyCode.Period */,
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
        run(_accessor, editor) {
            return triggerCodeActionsForEditorSelection(editor, nls.localize(750, "No code actions available"), undefined, undefined, types_1.CodeActionTriggerSource.QuickFix);
        }
    }
    exports.QuickFixAction = QuickFixAction;
    class CodeActionCommand extends editorExtensions_1.EditorCommand {
        constructor() {
            super({
                id: codeAction_1.codeActionCommandId,
                precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, editorContextKeys_1.EditorContextKeys.hasCodeActionsProvider),
                metadata: {
                    description: 'Trigger a code action',
                    args: [{ name: 'args', schema: argsSchema, }]
                }
            });
        }
        runEditorCommand(_accessor, editor, userArgs) {
            const args = types_1.CodeActionCommandArgs.fromUser(userArgs, {
                kind: hierarchicalKind_1.HierarchicalKind.Empty,
                apply: "ifSingle" /* CodeActionAutoApply.IfSingle */,
            });
            return triggerCodeActionsForEditorSelection(editor, typeof userArgs?.kind === 'string'
                ? args.preferred
                    ? nls.localize(751, "No preferred code actions for '{0}' available", userArgs.kind)
                    : nls.localize(752, "No code actions for '{0}' available", userArgs.kind)
                : args.preferred
                    ? nls.localize(753, "No preferred code actions available")
                    : nls.localize(754, "No code actions available"), {
                include: args.kind,
                includeSourceActions: true,
                onlyIncludePreferredActions: args.preferred,
            }, args.apply);
        }
    }
    exports.CodeActionCommand = CodeActionCommand;
    class RefactorAction extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: codeAction_1.refactorCommandId,
                label: nls.localize(755, "Refactor..."),
                alias: 'Refactor...',
                precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, editorContextKeys_1.EditorContextKeys.hasCodeActionsProvider),
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                    primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 48 /* KeyCode.KeyR */,
                    mac: {
                        primary: 256 /* KeyMod.WinCtrl */ | 1024 /* KeyMod.Shift */ | 48 /* KeyCode.KeyR */
                    },
                    weight: 100 /* KeybindingWeight.EditorContrib */
                },
                contextMenuOpts: {
                    group: '1_modification',
                    order: 2,
                    when: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, contextKeyForSupportedActions(types_1.CodeActionKind.Refactor)),
                },
                metadata: {
                    description: 'Refactor...',
                    args: [{ name: 'args', schema: argsSchema }]
                }
            });
        }
        run(_accessor, editor, userArgs) {
            const args = types_1.CodeActionCommandArgs.fromUser(userArgs, {
                kind: types_1.CodeActionKind.Refactor,
                apply: "never" /* CodeActionAutoApply.Never */
            });
            return triggerCodeActionsForEditorSelection(editor, typeof userArgs?.kind === 'string'
                ? args.preferred
                    ? nls.localize(756, "No preferred refactorings for '{0}' available", userArgs.kind)
                    : nls.localize(757, "No refactorings for '{0}' available", userArgs.kind)
                : args.preferred
                    ? nls.localize(758, "No preferred refactorings available")
                    : nls.localize(759, "No refactorings available"), {
                include: types_1.CodeActionKind.Refactor.contains(args.kind) ? args.kind : hierarchicalKind_1.HierarchicalKind.None,
                onlyIncludePreferredActions: args.preferred
            }, args.apply, types_1.CodeActionTriggerSource.Refactor);
        }
    }
    exports.RefactorAction = RefactorAction;
    class SourceAction extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: codeAction_1.sourceActionCommandId,
                label: nls.localize(760, "Source Action..."),
                alias: 'Source Action...',
                precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, editorContextKeys_1.EditorContextKeys.hasCodeActionsProvider),
                contextMenuOpts: {
                    group: '1_modification',
                    order: 2.1,
                    when: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, contextKeyForSupportedActions(types_1.CodeActionKind.Source)),
                },
                metadata: {
                    description: 'Source Action...',
                    args: [{ name: 'args', schema: argsSchema }]
                }
            });
        }
        run(_accessor, editor, userArgs) {
            const args = types_1.CodeActionCommandArgs.fromUser(userArgs, {
                kind: types_1.CodeActionKind.Source,
                apply: "never" /* CodeActionAutoApply.Never */
            });
            return triggerCodeActionsForEditorSelection(editor, typeof userArgs?.kind === 'string'
                ? args.preferred
                    ? nls.localize(761, "No preferred source actions for '{0}' available", userArgs.kind)
                    : nls.localize(762, "No source actions for '{0}' available", userArgs.kind)
                : args.preferred
                    ? nls.localize(763, "No preferred source actions available")
                    : nls.localize(764, "No source actions available"), {
                include: types_1.CodeActionKind.Source.contains(args.kind) ? args.kind : hierarchicalKind_1.HierarchicalKind.None,
                includeSourceActions: true,
                onlyIncludePreferredActions: args.preferred,
            }, args.apply, types_1.CodeActionTriggerSource.SourceAction);
        }
    }
    exports.SourceAction = SourceAction;
    class OrganizeImportsAction extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: codeAction_1.organizeImportsCommandId,
                label: nls.localize(765, "Organize Imports"),
                alias: 'Organize Imports',
                precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, contextKeyForSupportedActions(types_1.CodeActionKind.SourceOrganizeImports)),
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                    primary: 1024 /* KeyMod.Shift */ | 512 /* KeyMod.Alt */ | 45 /* KeyCode.KeyO */,
                    weight: 100 /* KeybindingWeight.EditorContrib */
                },
            });
        }
        run(_accessor, editor) {
            return triggerCodeActionsForEditorSelection(editor, nls.localize(766, "No organize imports action available"), { include: types_1.CodeActionKind.SourceOrganizeImports, includeSourceActions: true }, "ifSingle" /* CodeActionAutoApply.IfSingle */, types_1.CodeActionTriggerSource.OrganizeImports);
        }
    }
    exports.OrganizeImportsAction = OrganizeImportsAction;
    class FixAllAction extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: codeAction_1.fixAllCommandId,
                label: nls.localize(767, "Fix All"),
                alias: 'Fix All',
                precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, contextKeyForSupportedActions(types_1.CodeActionKind.SourceFixAll))
            });
        }
        run(_accessor, editor) {
            return triggerCodeActionsForEditorSelection(editor, nls.localize(768, "No fix all action available"), { include: types_1.CodeActionKind.SourceFixAll, includeSourceActions: true }, "ifSingle" /* CodeActionAutoApply.IfSingle */, types_1.CodeActionTriggerSource.FixAll);
        }
    }
    exports.FixAllAction = FixAllAction;
    class AutoFixAction extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: codeAction_1.autoFixCommandId,
                label: nls.localize(769, "Auto Fix..."),
                alias: 'Auto Fix...',
                precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, contextKeyForSupportedActions(types_1.CodeActionKind.QuickFix)),
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                    primary: 512 /* KeyMod.Alt */ | 1024 /* KeyMod.Shift */ | 89 /* KeyCode.Period */,
                    mac: {
                        primary: 2048 /* KeyMod.CtrlCmd */ | 512 /* KeyMod.Alt */ | 89 /* KeyCode.Period */
                    },
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
        run(_accessor, editor) {
            return triggerCodeActionsForEditorSelection(editor, nls.localize(770, "No auto fixes available"), {
                include: types_1.CodeActionKind.QuickFix,
                onlyIncludePreferredActions: true
            }, "ifSingle" /* CodeActionAutoApply.IfSingle */, types_1.CodeActionTriggerSource.AutoFix);
        }
    }
    exports.AutoFixAction = AutoFixAction;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[817/*vs/editor/contrib/codeAction/browser/codeActionContributions*/], __M([1/*require*/,0/*exports*/,15/*vs/editor/browser/editorExtensions*/,274/*vs/editor/common/config/editorConfigurationSchema*/,816/*vs/editor/contrib/codeAction/browser/codeActionCommands*/,287/*vs/editor/contrib/codeAction/browser/codeActionController*/,421/*vs/editor/contrib/codeAction/browser/lightBulbWidget*/,3/*vs/nls*/,109/*vs/platform/configuration/common/configurationRegistry*/,38/*vs/platform/registry/common/platform*/]), function (require, exports, editorExtensions_1, editorConfigurationSchema_1, codeActionCommands_1, codeActionController_1, lightBulbWidget_1, nls, configurationRegistry_1, platform_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    (0, editorExtensions_1.registerEditorContribution)(codeActionController_1.CodeActionController.ID, codeActionController_1.CodeActionController, 3 /* EditorContributionInstantiation.Eventually */);
    (0, editorExtensions_1.registerEditorContribution)(lightBulbWidget_1.LightBulbWidget.ID, lightBulbWidget_1.LightBulbWidget, 4 /* EditorContributionInstantiation.Lazy */);
    (0, editorExtensions_1.registerEditorAction)(codeActionCommands_1.QuickFixAction);
    (0, editorExtensions_1.registerEditorAction)(codeActionCommands_1.RefactorAction);
    (0, editorExtensions_1.registerEditorAction)(codeActionCommands_1.SourceAction);
    (0, editorExtensions_1.registerEditorAction)(codeActionCommands_1.OrganizeImportsAction);
    (0, editorExtensions_1.registerEditorAction)(codeActionCommands_1.AutoFixAction);
    (0, editorExtensions_1.registerEditorAction)(codeActionCommands_1.FixAllAction);
    (0, editorExtensions_1.registerEditorCommand)(new codeActionCommands_1.CodeActionCommand());
    platform_1.Registry.as(configurationRegistry_1.Extensions.Configuration).registerConfiguration({
        ...editorConfigurationSchema_1.editorConfigurationBaseNode,
        properties: {
            'editor.codeActionWidget.showHeaders': {
                type: 'boolean',
                scope: 5 /* ConfigurationScope.LANGUAGE_OVERRIDABLE */,
                description: nls.localize(771, "Enable/disable showing group headers in the Code Action menu."),
                default: true,
            },
        }
    });
    platform_1.Registry.as(configurationRegistry_1.Extensions.Configuration).registerConfiguration({
        ...editorConfigurationSchema_1.editorConfigurationBaseNode,
        properties: {
            'editor.codeActionWidget.includeNearbyQuickFixes': {
                type: 'boolean',
                scope: 5 /* ConfigurationScope.LANGUAGE_OVERRIDABLE */,
                description: nls.localize(772, "Enable/disable showing nearest Quick Fix within a line when not currently on a diagnostic."),
                default: true,
            },
        }
    });
    platform_1.Registry.as(configurationRegistry_1.Extensions.Configuration).registerConfiguration({
        ...editorConfigurationSchema_1.editorConfigurationBaseNode,
        properties: {
            'editor.codeActions.triggerOnFocusChange': {
                type: 'boolean',
                scope: 5 /* ConfigurationScope.LANGUAGE_OVERRIDABLE */,
                markdownDescription: nls.localize(773, 'Enable triggering {0} when {1} is set to {2}. Code Actions must be set to {3} to be triggered for window and focus changes.', '`#editor.codeActionsOnSave#`', '`#files.autoSave#`', '`afterDelay`', '`always`'),
                default: false,
            },
        }
    });
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[818/*vs/editor/contrib/codelens/browser/codelensWidget*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,114/*vs/base/browser/ui/iconLabel/iconLabels*/,4/*vs/editor/common/core/range*/,35/*vs/editor/common/model/textModel*/,506/*vs/css!vs/editor/contrib/codelens/browser/codelensWidget*/]), function (require, exports, dom, iconLabels_1, range_1, textModel_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CodeLensWidget = exports.CodeLensHelper = void 0;
    class CodeLensViewZone {
        constructor(afterLineNumber, heightInPx, onHeight) {
            /**
             * We want that this view zone, which reserves space for a code lens appears
             * as close as possible to the next line, so we use a very large value here.
             */
            this.afterColumn = 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */;
            this.afterLineNumber = afterLineNumber;
            this.heightInPx = heightInPx;
            this._onHeight = onHeight;
            this.suppressMouseDown = true;
            this.domNode = document.createElement('div');
        }
        onComputedHeight(height) {
            if (this._lastHeight === undefined) {
                this._lastHeight = height;
            }
            else if (this._lastHeight !== height) {
                this._lastHeight = height;
                this._onHeight();
            }
        }
        isVisible() {
            return this._lastHeight !== 0
                && this.domNode.hasAttribute('monaco-visible-view-zone');
        }
    }
    class CodeLensContentWidget {
        static { this._idPool = 0; }
        constructor(editor, line) {
            // Editor.IContentWidget.allowEditorOverflow
            this.allowEditorOverflow = false;
            this.suppressMouseDown = true;
            this._commands = new Map();
            this._isEmpty = true;
            this._editor = editor;
            this._id = `codelens.widget-${(CodeLensContentWidget._idPool++)}`;
            this.updatePosition(line);
            this._domNode = document.createElement('span');
            this._domNode.className = `codelens-decoration`;
        }
        withCommands(lenses, animate) {
            this._commands.clear();
            const children = [];
            let hasSymbol = false;
            for (let i = 0; i < lenses.length; i++) {
                const lens = lenses[i];
                if (!lens) {
                    continue;
                }
                hasSymbol = true;
                if (lens.command) {
                    const title = (0, iconLabels_1.renderLabelWithIcons)(lens.command.title.trim());
                    if (lens.command.id) {
                        const id = `c${(CodeLensContentWidget._idPool++)}`;
                        children.push(dom.$('a', { id, title: lens.command.tooltip, role: 'button' }, ...title));
                        this._commands.set(id, lens.command);
                    }
                    else {
                        children.push(dom.$('span', { title: lens.command.tooltip }, ...title));
                    }
                    if (i + 1 < lenses.length) {
                        children.push(dom.$('span', undefined, '\u00a0|\u00a0'));
                    }
                }
            }
            if (!hasSymbol) {
                // symbols but no commands
                dom.reset(this._domNode, dom.$('span', undefined, 'no commands'));
            }
            else {
                // symbols and commands
                dom.reset(this._domNode, ...children);
                if (this._isEmpty && animate) {
                    this._domNode.classList.add('fadein');
                }
                this._isEmpty = false;
            }
        }
        getCommand(link) {
            return link.parentElement === this._domNode
                ? this._commands.get(link.id)
                : undefined;
        }
        getId() {
            return this._id;
        }
        getDomNode() {
            return this._domNode;
        }
        updatePosition(line) {
            const column = this._editor.getModel().getLineFirstNonWhitespaceColumn(line);
            this._widgetPosition = {
                position: { lineNumber: line, column: column },
                preference: [1 /* ContentWidgetPositionPreference.ABOVE */]
            };
        }
        getPosition() {
            return this._widgetPosition || null;
        }
    }
    class CodeLensHelper {
        constructor() {
            this._removeDecorations = [];
            this._addDecorations = [];
            this._addDecorationsCallbacks = [];
        }
        addDecoration(decoration, callback) {
            this._addDecorations.push(decoration);
            this._addDecorationsCallbacks.push(callback);
        }
        removeDecoration(decorationId) {
            this._removeDecorations.push(decorationId);
        }
        commit(changeAccessor) {
            const resultingDecorations = changeAccessor.deltaDecorations(this._removeDecorations, this._addDecorations);
            for (let i = 0, len = resultingDecorations.length; i < len; i++) {
                this._addDecorationsCallbacks[i](resultingDecorations[i]);
            }
        }
    }
    exports.CodeLensHelper = CodeLensHelper;
    const codeLensDecorationOptions = textModel_1.ModelDecorationOptions.register({
        collapseOnReplaceEdit: true,
        description: 'codelens'
    });
    class CodeLensWidget {
        constructor(data, editor, helper, viewZoneChangeAccessor, heightInPx, updateCallback) {
            this._isDisposed = false;
            this._editor = editor;
            this._data = data;
            // create combined range, track all ranges with decorations,
            // check if there is already something to render
            this._decorationIds = [];
            let range;
            const lenses = [];
            this._data.forEach((codeLensData, i) => {
                if (codeLensData.symbol.command) {
                    lenses.push(codeLensData.symbol);
                }
                helper.addDecoration({
                    range: codeLensData.symbol.range,
                    options: codeLensDecorationOptions
                }, id => this._decorationIds[i] = id);
                // the range contains all lenses on this line
                if (!range) {
                    range = range_1.Range.lift(codeLensData.symbol.range);
                }
                else {
                    range = range_1.Range.plusRange(range, codeLensData.symbol.range);
                }
            });
            this._viewZone = new CodeLensViewZone(range.startLineNumber - 1, heightInPx, updateCallback);
            this._viewZoneId = viewZoneChangeAccessor.addZone(this._viewZone);
            if (lenses.length > 0) {
                this._createContentWidgetIfNecessary();
                this._contentWidget.withCommands(lenses, false);
            }
        }
        _createContentWidgetIfNecessary() {
            if (!this._contentWidget) {
                this._contentWidget = new CodeLensContentWidget(this._editor, this._viewZone.afterLineNumber + 1);
                this._editor.addContentWidget(this._contentWidget);
            }
            else {
                this._editor.layoutContentWidget(this._contentWidget);
            }
        }
        dispose(helper, viewZoneChangeAccessor) {
            this._decorationIds.forEach(helper.removeDecoration, helper);
            this._decorationIds = [];
            viewZoneChangeAccessor?.removeZone(this._viewZoneId);
            if (this._contentWidget) {
                this._editor.removeContentWidget(this._contentWidget);
                this._contentWidget = undefined;
            }
            this._isDisposed = true;
        }
        isDisposed() {
            return this._isDisposed;
        }
        isValid() {
            return this._decorationIds.some((id, i) => {
                const range = this._editor.getModel().getDecorationRange(id);
                const symbol = this._data[i].symbol;
                return !!(range && range_1.Range.isEmpty(symbol.range) === range.isEmpty());
            });
        }
        updateCodeLensSymbols(data, helper) {
            this._decorationIds.forEach(helper.removeDecoration, helper);
            this._decorationIds = [];
            this._data = data;
            this._data.forEach((codeLensData, i) => {
                helper.addDecoration({
                    range: codeLensData.symbol.range,
                    options: codeLensDecorationOptions
                }, id => this._decorationIds[i] = id);
            });
        }
        updateHeight(height, viewZoneChangeAccessor) {
            this._viewZone.heightInPx = height;
            viewZoneChangeAccessor.layoutZone(this._viewZoneId);
            if (this._contentWidget) {
                this._editor.layoutContentWidget(this._contentWidget);
            }
        }
        computeIfNecessary(model) {
            if (!this._viewZone.isVisible()) {
                return null;
            }
            // Read editor current state
            for (let i = 0; i < this._decorationIds.length; i++) {
                const range = model.getDecorationRange(this._decorationIds[i]);
                if (range) {
                    this._data[i].symbol.range = range;
                }
            }
            return this._data;
        }
        updateCommands(symbols) {
            this._createContentWidgetIfNecessary();
            this._contentWidget.withCommands(symbols, true);
            for (let i = 0; i < this._data.length; i++) {
                const resolved = symbols[i];
                if (resolved) {
                    const { symbol } = this._data[i];
                    symbol.command = resolved.command || symbol.command;
                }
            }
        }
        getCommand(link) {
            return this._contentWidget?.getCommand(link);
        }
        getLineNumber() {
            const range = this._editor.getModel().getDecorationRange(this._decorationIds[0]);
            if (range) {
                return range.startLineNumber;
            }
            return -1;
        }
        update(viewZoneChangeAccessor) {
            if (this.isValid()) {
                const range = this._editor.getModel().getDecorationRange(this._decorationIds[0]);
                if (range) {
                    this._viewZone.afterLineNumber = range.startLineNumber - 1;
                    viewZoneChangeAccessor.layoutZone(this._viewZoneId);
                    if (this._contentWidget) {
                        this._contentWidget.updatePosition(range.startLineNumber);
                        this._editor.layoutContentWidget(this._contentWidget);
                    }
                }
            }
        }
    }
    exports.CodeLensWidget = CodeLensWidget;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[819/*vs/editor/contrib/codelens/browser/codelensController*/], __M([1/*require*/,0/*exports*/,14/*vs/base/common/async*/,8/*vs/base/common/errors*/,2/*vs/base/common/lifecycle*/,143/*vs/editor/browser/stableEditorScroll*/,15/*vs/editor/browser/editorExtensions*/,37/*vs/editor/common/config/editorOptions*/,20/*vs/editor/common/editorContextKeys*/,386/*vs/editor/contrib/codelens/browser/codelens*/,724/*vs/editor/contrib/codelens/browser/codeLensCache*/,818/*vs/editor/contrib/codelens/browser/codelensWidget*/,3/*vs/nls*/,24/*vs/platform/commands/common/commands*/,50/*vs/platform/notification/common/notification*/,66/*vs/platform/quickinput/common/quickInput*/,79/*vs/editor/common/services/languageFeatureDebounce*/,17/*vs/editor/common/services/languageFeatures*/]), function (require, exports, async_1, errors_1, lifecycle_1, stableEditorScroll_1, editorExtensions_1, editorOptions_1, editorContextKeys_1, codelens_1, codeLensCache_1, codelensWidget_1, nls_1, commands_1, notification_1, quickInput_1, languageFeatureDebounce_1, languageFeatures_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CodeLensContribution = void 0;
    let CodeLensContribution = class CodeLensContribution {
        static { this.ID = 'css.editor.codeLens'; }
        constructor(_editor, _languageFeaturesService, debounceService, _commandService, _notificationService, _codeLensCache) {
            this._editor = _editor;
            this._languageFeaturesService = _languageFeaturesService;
            this._commandService = _commandService;
            this._notificationService = _notificationService;
            this._codeLensCache = _codeLensCache;
            this._disposables = new lifecycle_1.DisposableStore();
            this._localToDispose = new lifecycle_1.DisposableStore();
            this._lenses = [];
            this._oldCodeLensModels = new lifecycle_1.DisposableStore();
            this._provideCodeLensDebounce = debounceService.for(_languageFeaturesService.codeLensProvider, 'CodeLensProvide', { min: 250 });
            this._resolveCodeLensesDebounce = debounceService.for(_languageFeaturesService.codeLensProvider, 'CodeLensResolve', { min: 250, salt: 'resolve' });
            this._resolveCodeLensesScheduler = new async_1.RunOnceScheduler(() => this._resolveCodeLensesInViewport(), this._resolveCodeLensesDebounce.default());
            this._disposables.add(this._editor.onDidChangeModel(() => this._onModelChange()));
            this._disposables.add(this._editor.onDidChangeModelLanguage(() => this._onModelChange()));
            this._disposables.add(this._editor.onDidChangeConfiguration((e) => {
                if (e.hasChanged(50 /* EditorOption.fontInfo */) || e.hasChanged(19 /* EditorOption.codeLensFontSize */) || e.hasChanged(18 /* EditorOption.codeLensFontFamily */)) {
                    this._updateLensStyle();
                }
                if (e.hasChanged(17 /* EditorOption.codeLens */)) {
                    this._onModelChange();
                }
            }));
            this._disposables.add(_languageFeaturesService.codeLensProvider.onDidChange(this._onModelChange, this));
            this._onModelChange();
            this._updateLensStyle();
        }
        dispose() {
            this._localDispose();
            this._disposables.dispose();
            this._oldCodeLensModels.dispose();
            this._currentCodeLensModel?.dispose();
        }
        _getLayoutInfo() {
            const lineHeightFactor = Math.max(1.3, this._editor.getOption(67 /* EditorOption.lineHeight */) / this._editor.getOption(52 /* EditorOption.fontSize */));
            let fontSize = this._editor.getOption(19 /* EditorOption.codeLensFontSize */);
            if (!fontSize || fontSize < 5) {
                fontSize = (this._editor.getOption(52 /* EditorOption.fontSize */) * .9) | 0;
            }
            return {
                fontSize,
                codeLensHeight: (fontSize * lineHeightFactor) | 0,
            };
        }
        _updateLensStyle() {
            const { codeLensHeight, fontSize } = this._getLayoutInfo();
            const fontFamily = this._editor.getOption(18 /* EditorOption.codeLensFontFamily */);
            const editorFontInfo = this._editor.getOption(50 /* EditorOption.fontInfo */);
            const { style } = this._editor.getContainerDomNode();
            style.setProperty('--vscode-editorCodeLens-lineHeight', `${codeLensHeight}px`);
            style.setProperty('--vscode-editorCodeLens-fontSize', `${fontSize}px`);
            style.setProperty('--vscode-editorCodeLens-fontFeatureSettings', editorFontInfo.fontFeatureSettings);
            if (fontFamily) {
                style.setProperty('--vscode-editorCodeLens-fontFamily', fontFamily);
                style.setProperty('--vscode-editorCodeLens-fontFamilyDefault', editorOptions_1.EDITOR_FONT_DEFAULTS.fontFamily);
            }
            //
            this._editor.changeViewZones(accessor => {
                for (const lens of this._lenses) {
                    lens.updateHeight(codeLensHeight, accessor);
                }
            });
        }
        _localDispose() {
            this._getCodeLensModelPromise?.cancel();
            this._getCodeLensModelPromise = undefined;
            this._resolveCodeLensesPromise?.cancel();
            this._resolveCodeLensesPromise = undefined;
            this._localToDispose.clear();
            this._oldCodeLensModels.clear();
            this._currentCodeLensModel?.dispose();
        }
        _onModelChange() {
            this._localDispose();
            const model = this._editor.getModel();
            if (!model) {
                return;
            }
            if (!this._editor.getOption(17 /* EditorOption.codeLens */) || model.isTooLargeForTokenization()) {
                return;
            }
            const cachedLenses = this._codeLensCache.get(model);
            if (cachedLenses) {
                this._renderCodeLensSymbols(cachedLenses);
            }
            if (!this._languageFeaturesService.codeLensProvider.has(model)) {
                // no provider -> return but check with
                // cached lenses. they expire after 30 seconds
                if (cachedLenses) {
                    (0, async_1.disposableTimeout)(() => {
                        const cachedLensesNow = this._codeLensCache.get(model);
                        if (cachedLenses === cachedLensesNow) {
                            this._codeLensCache.delete(model);
                            this._onModelChange();
                        }
                    }, 30 * 1000, this._localToDispose);
                }
                return;
            }
            for (const provider of this._languageFeaturesService.codeLensProvider.all(model)) {
                if (typeof provider.onDidChange === 'function') {
                    const registration = provider.onDidChange(() => scheduler.schedule());
                    this._localToDispose.add(registration);
                }
            }
            const scheduler = new async_1.RunOnceScheduler(() => {
                const t1 = Date.now();
                this._getCodeLensModelPromise?.cancel();
                this._getCodeLensModelPromise = (0, async_1.createCancelablePromise)(token => (0, codelens_1.getCodeLensModel)(this._languageFeaturesService.codeLensProvider, model, token));
                this._getCodeLensModelPromise.then(result => {
                    if (this._currentCodeLensModel) {
                        this._oldCodeLensModels.add(this._currentCodeLensModel);
                    }
                    this._currentCodeLensModel = result;
                    // cache model to reduce flicker
                    this._codeLensCache.put(model, result);
                    // update moving average
                    const newDelay = this._provideCodeLensDebounce.update(model, Date.now() - t1);
                    scheduler.delay = newDelay;
                    // render lenses
                    this._renderCodeLensSymbols(result);
                    // dom.scheduleAtNextAnimationFrame(() => this._resolveCodeLensesInViewport());
                    this._resolveCodeLensesInViewportSoon();
                }, errors_1.onUnexpectedError);
            }, this._provideCodeLensDebounce.get(model));
            this._localToDispose.add(scheduler);
            this._localToDispose.add((0, lifecycle_1.toDisposable)(() => this._resolveCodeLensesScheduler.cancel()));
            this._localToDispose.add(this._editor.onDidChangeModelContent(() => {
                this._editor.changeDecorations(decorationsAccessor => {
                    this._editor.changeViewZones(viewZonesAccessor => {
                        const toDispose = [];
                        let lastLensLineNumber = -1;
                        this._lenses.forEach((lens) => {
                            if (!lens.isValid() || lastLensLineNumber === lens.getLineNumber()) {
                                // invalid -> lens collapsed, attach range doesn't exist anymore
                                // line_number -> lenses should never be on the same line
                                toDispose.push(lens);
                            }
                            else {
                                lens.update(viewZonesAccessor);
                                lastLensLineNumber = lens.getLineNumber();
                            }
                        });
                        const helper = new codelensWidget_1.CodeLensHelper();
                        toDispose.forEach((l) => {
                            l.dispose(helper, viewZonesAccessor);
                            this._lenses.splice(this._lenses.indexOf(l), 1);
                        });
                        helper.commit(decorationsAccessor);
                    });
                });
                // Ask for all references again
                scheduler.schedule();
                // Cancel pending and active resolve requests
                this._resolveCodeLensesScheduler.cancel();
                this._resolveCodeLensesPromise?.cancel();
                this._resolveCodeLensesPromise = undefined;
            }));
            this._localToDispose.add(this._editor.onDidFocusEditorText(() => {
                scheduler.schedule();
            }));
            this._localToDispose.add(this._editor.onDidBlurEditorText(() => {
                scheduler.cancel();
            }));
            this._localToDispose.add(this._editor.onDidScrollChange(e => {
                if (e.scrollTopChanged && this._lenses.length > 0) {
                    this._resolveCodeLensesInViewportSoon();
                }
            }));
            this._localToDispose.add(this._editor.onDidLayoutChange(() => {
                this._resolveCodeLensesInViewportSoon();
            }));
            this._localToDispose.add((0, lifecycle_1.toDisposable)(() => {
                if (this._editor.getModel()) {
                    const scrollState = stableEditorScroll_1.StableEditorScrollState.capture(this._editor);
                    this._editor.changeDecorations(decorationsAccessor => {
                        this._editor.changeViewZones(viewZonesAccessor => {
                            this._disposeAllLenses(decorationsAccessor, viewZonesAccessor);
                        });
                    });
                    scrollState.restore(this._editor);
                }
                else {
                    // No accessors available
                    this._disposeAllLenses(undefined, undefined);
                }
            }));
            this._localToDispose.add(this._editor.onMouseDown(e => {
                if (e.target.type !== 9 /* MouseTargetType.CONTENT_WIDGET */) {
                    return;
                }
                let target = e.target.element;
                if (target?.tagName === 'SPAN') {
                    target = target.parentElement;
                }
                if (target?.tagName === 'A') {
                    for (const lens of this._lenses) {
                        const command = lens.getCommand(target);
                        if (command) {
                            this._commandService.executeCommand(command.id, ...(command.arguments || [])).catch(err => this._notificationService.error(err));
                            break;
                        }
                    }
                }
            }));
            scheduler.schedule();
        }
        _disposeAllLenses(decChangeAccessor, viewZoneChangeAccessor) {
            const helper = new codelensWidget_1.CodeLensHelper();
            for (const lens of this._lenses) {
                lens.dispose(helper, viewZoneChangeAccessor);
            }
            if (decChangeAccessor) {
                helper.commit(decChangeAccessor);
            }
            this._lenses.length = 0;
        }
        _renderCodeLensSymbols(symbols) {
            if (!this._editor.hasModel()) {
                return;
            }
            const maxLineNumber = this._editor.getModel().getLineCount();
            const groups = [];
            let lastGroup;
            for (const symbol of symbols.lenses) {
                const line = symbol.symbol.range.startLineNumber;
                if (line < 1 || line > maxLineNumber) {
                    // invalid code lens
                    continue;
                }
                else if (lastGroup && lastGroup[lastGroup.length - 1].symbol.range.startLineNumber === line) {
                    // on same line as previous
                    lastGroup.push(symbol);
                }
                else {
                    // on later line as previous
                    lastGroup = [symbol];
                    groups.push(lastGroup);
                }
            }
            if (!groups.length && !this._lenses.length) {
                // Nothing to change
                return;
            }
            const scrollState = stableEditorScroll_1.StableEditorScrollState.capture(this._editor);
            const layoutInfo = this._getLayoutInfo();
            this._editor.changeDecorations(decorationsAccessor => {
                this._editor.changeViewZones(viewZoneAccessor => {
                    const helper = new codelensWidget_1.CodeLensHelper();
                    let codeLensIndex = 0;
                    let groupsIndex = 0;
                    while (groupsIndex < groups.length && codeLensIndex < this._lenses.length) {
                        const symbolsLineNumber = groups[groupsIndex][0].symbol.range.startLineNumber;
                        const codeLensLineNumber = this._lenses[codeLensIndex].getLineNumber();
                        if (codeLensLineNumber < symbolsLineNumber) {
                            this._lenses[codeLensIndex].dispose(helper, viewZoneAccessor);
                            this._lenses.splice(codeLensIndex, 1);
                        }
                        else if (codeLensLineNumber === symbolsLineNumber) {
                            this._lenses[codeLensIndex].updateCodeLensSymbols(groups[groupsIndex], helper);
                            groupsIndex++;
                            codeLensIndex++;
                        }
                        else {
                            this._lenses.splice(codeLensIndex, 0, new codelensWidget_1.CodeLensWidget(groups[groupsIndex], this._editor, helper, viewZoneAccessor, layoutInfo.codeLensHeight, () => this._resolveCodeLensesInViewportSoon()));
                            codeLensIndex++;
                            groupsIndex++;
                        }
                    }
                    // Delete extra code lenses
                    while (codeLensIndex < this._lenses.length) {
                        this._lenses[codeLensIndex].dispose(helper, viewZoneAccessor);
                        this._lenses.splice(codeLensIndex, 1);
                    }
                    // Create extra symbols
                    while (groupsIndex < groups.length) {
                        this._lenses.push(new codelensWidget_1.CodeLensWidget(groups[groupsIndex], this._editor, helper, viewZoneAccessor, layoutInfo.codeLensHeight, () => this._resolveCodeLensesInViewportSoon()));
                        groupsIndex++;
                    }
                    helper.commit(decorationsAccessor);
                });
            });
            scrollState.restore(this._editor);
        }
        _resolveCodeLensesInViewportSoon() {
            const model = this._editor.getModel();
            if (model) {
                this._resolveCodeLensesScheduler.schedule();
            }
        }
        _resolveCodeLensesInViewport() {
            this._resolveCodeLensesPromise?.cancel();
            this._resolveCodeLensesPromise = undefined;
            const model = this._editor.getModel();
            if (!model) {
                return;
            }
            const toResolve = [];
            const lenses = [];
            this._lenses.forEach((lens) => {
                const request = lens.computeIfNecessary(model);
                if (request) {
                    toResolve.push(request);
                    lenses.push(lens);
                }
            });
            if (toResolve.length === 0) {
                return;
            }
            const t1 = Date.now();
            const resolvePromise = (0, async_1.createCancelablePromise)(token => {
                const promises = toResolve.map((request, i) => {
                    const resolvedSymbols = new Array(request.length);
                    const promises = request.map((request, i) => {
                        if (!request.symbol.command && typeof request.provider.resolveCodeLens === 'function') {
                            return Promise.resolve(request.provider.resolveCodeLens(model, request.symbol, token)).then(symbol => {
                                resolvedSymbols[i] = symbol;
                            }, errors_1.onUnexpectedExternalError);
                        }
                        else {
                            resolvedSymbols[i] = request.symbol;
                            return Promise.resolve(undefined);
                        }
                    });
                    return Promise.all(promises).then(() => {
                        if (!token.isCancellationRequested && !lenses[i].isDisposed()) {
                            lenses[i].updateCommands(resolvedSymbols);
                        }
                    });
                });
                return Promise.all(promises);
            });
            this._resolveCodeLensesPromise = resolvePromise;
            this._resolveCodeLensesPromise.then(() => {
                // update moving average
                const newDelay = this._resolveCodeLensesDebounce.update(model, Date.now() - t1);
                this._resolveCodeLensesScheduler.delay = newDelay;
                if (this._currentCodeLensModel) { // update the cached state with new resolved items
                    this._codeLensCache.put(model, this._currentCodeLensModel);
                }
                this._oldCodeLensModels.clear(); // dispose old models once we have updated the UI with the current model
                if (resolvePromise === this._resolveCodeLensesPromise) {
                    this._resolveCodeLensesPromise = undefined;
                }
            }, err => {
                (0, errors_1.onUnexpectedError)(err); // can also be cancellation!
                if (resolvePromise === this._resolveCodeLensesPromise) {
                    this._resolveCodeLensesPromise = undefined;
                }
            });
        }
        async getModel() {
            await this._getCodeLensModelPromise;
            await this._resolveCodeLensesPromise;
            return !this._currentCodeLensModel?.isDisposed
                ? this._currentCodeLensModel
                : undefined;
        }
    };
    exports.CodeLensContribution = CodeLensContribution;
    exports.CodeLensContribution = CodeLensContribution = __decorate([
        __param(1, languageFeatures_1.ILanguageFeaturesService),
        __param(2, languageFeatureDebounce_1.ILanguageFeatureDebounceService),
        __param(3, commands_1.ICommandService),
        __param(4, notification_1.INotificationService),
        __param(5, codeLensCache_1.ICodeLensCache)
    ], CodeLensContribution);
    (0, editorExtensions_1.registerEditorContribution)(CodeLensContribution.ID, CodeLensContribution, 1 /* EditorContributionInstantiation.AfterFirstRender */);
    (0, editorExtensions_1.registerEditorAction)(class ShowLensesInCurrentLine extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: 'codelens.showLensesInCurrentLine',
                precondition: editorContextKeys_1.EditorContextKeys.hasCodeLensProvider,
                label: (0, nls_1.localize)(794, "Show CodeLens Commands For Current Line"),
                alias: 'Show CodeLens Commands For Current Line',
            });
        }
        async run(accessor, editor) {
            if (!editor.hasModel()) {
                return;
            }
            const quickInputService = accessor.get(quickInput_1.IQuickInputService);
            const commandService = accessor.get(commands_1.ICommandService);
            const notificationService = accessor.get(notification_1.INotificationService);
            const lineNumber = editor.getSelection().positionLineNumber;
            const codelensController = editor.getContribution(CodeLensContribution.ID);
            if (!codelensController) {
                return;
            }
            const model = await codelensController.getModel();
            if (!model) {
                // nothing
                return;
            }
            const items = [];
            for (const lens of model.lenses) {
                if (lens.symbol.command && lens.symbol.range.startLineNumber === lineNumber) {
                    items.push({
                        label: lens.symbol.command.title,
                        command: lens.symbol.command
                    });
                }
            }
            if (items.length === 0) {
                // We dont want an empty picker
                return;
            }
            const item = await quickInputService.pick(items, {
                canPickMany: false,
                placeHolder: (0, nls_1.localize)(795, "Select a command")
            });
            if (!item) {
                // Nothing picked
                return;
            }
            let command = item.command;
            if (model.isDisposed) {
                // try to find the same command again in-case the model has been re-created in the meantime
                // this is a best attempt approach which shouldn't be needed because eager model re-creates
                // shouldn't happen due to focus in/out anymore
                const newModel = await codelensController.getModel();
                const newLens = newModel?.lenses.find(lens => lens.symbol.range.startLineNumber === lineNumber && lens.symbol.command?.title === command.title);
                if (!newLens || !newLens.symbol.command) {
                    return;
                }
                command = newLens.symbol.command;
            }
            try {
                await commandService.executeCommand(command.id, ...(command.arguments || []));
            }
            catch (err) {
                notificationService.error(err);
            }
        }
    });
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[422/*vs/editor/contrib/colorPicker/browser/colorDetector*/], __M([1/*require*/,0/*exports*/,14/*vs/base/common/async*/,33/*vs/base/common/color*/,8/*vs/base/common/errors*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,54/*vs/base/common/stopwatch*/,11/*vs/base/common/strings*/,185/*vs/editor/browser/editorDom*/,15/*vs/editor/browser/editorExtensions*/,4/*vs/editor/common/core/range*/,35/*vs/editor/common/model/textModel*/,79/*vs/editor/common/services/languageFeatureDebounce*/,17/*vs/editor/common/services/languageFeatures*/,388/*vs/editor/contrib/colorPicker/browser/color*/,28/*vs/platform/configuration/common/configuration*/]), function (require, exports, async_1, color_1, errors_1, event_1, lifecycle_1, stopwatch_1, strings_1, editorDom_1, editorExtensions_1, range_1, textModel_1, languageFeatureDebounce_1, languageFeatures_1, color_2, configuration_1) {
    "use strict";
    var ColorDetector_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DecoratorLimitReporter = exports.ColorDetector = exports.ColorDecorationInjectedTextMarker = void 0;
    exports.ColorDecorationInjectedTextMarker = Object.create({});
    let ColorDetector = class ColorDetector extends lifecycle_1.Disposable {
        static { ColorDetector_1 = this; }
        static { this.ID = 'editor.contrib.colorDetector'; }
        static { this.RECOMPUTE_TIME = 1000; } // ms
        constructor(_editor, _configurationService, _languageFeaturesService, languageFeatureDebounceService) {
            super();
            this._editor = _editor;
            this._configurationService = _configurationService;
            this._languageFeaturesService = _languageFeaturesService;
            this._localToDispose = this._register(new lifecycle_1.DisposableStore());
            this._decorationsIds = [];
            this._colorDatas = new Map();
            this._colorDecoratorIds = this._editor.createDecorationsCollection();
            this._ruleFactory = new editorDom_1.DynamicCssRules(this._editor);
            this._decoratorLimitReporter = new DecoratorLimitReporter();
            this._colorDecorationClassRefs = this._register(new lifecycle_1.DisposableStore());
            this._debounceInformation = languageFeatureDebounceService.for(_languageFeaturesService.colorProvider, 'Document Colors', { min: ColorDetector_1.RECOMPUTE_TIME });
            this._register(_editor.onDidChangeModel(() => {
                this._isColorDecoratorsEnabled = this.isEnabled();
                this.updateColors();
            }));
            this._register(_editor.onDidChangeModelLanguage(() => this.updateColors()));
            this._register(_languageFeaturesService.colorProvider.onDidChange(() => this.updateColors()));
            this._register(_editor.onDidChangeConfiguration((e) => {
                const prevIsEnabled = this._isColorDecoratorsEnabled;
                this._isColorDecoratorsEnabled = this.isEnabled();
                this._isDefaultColorDecoratorsEnabled = this._editor.getOption(148 /* EditorOption.defaultColorDecorators */);
                const updatedColorDecoratorsSetting = prevIsEnabled !== this._isColorDecoratorsEnabled || e.hasChanged(21 /* EditorOption.colorDecoratorsLimit */);
                const updatedDefaultColorDecoratorsSetting = e.hasChanged(148 /* EditorOption.defaultColorDecorators */);
                if (updatedColorDecoratorsSetting || updatedDefaultColorDecoratorsSetting) {
                    if (this._isColorDecoratorsEnabled) {
                        this.updateColors();
                    }
                    else {
                        this.removeAllDecorations();
                    }
                }
            }));
            this._timeoutTimer = null;
            this._computePromise = null;
            this._isColorDecoratorsEnabled = this.isEnabled();
            this._isDefaultColorDecoratorsEnabled = this._editor.getOption(148 /* EditorOption.defaultColorDecorators */);
            this.updateColors();
        }
        isEnabled() {
            const model = this._editor.getModel();
            if (!model) {
                return false;
            }
            const languageId = model.getLanguageId();
            // handle deprecated settings. [languageId].colorDecorators.enable
            const deprecatedConfig = this._configurationService.getValue(languageId);
            if (deprecatedConfig && typeof deprecatedConfig === 'object') {
                const colorDecorators = deprecatedConfig['colorDecorators']; // deprecatedConfig.valueOf('.colorDecorators.enable');
                if (colorDecorators && colorDecorators['enable'] !== undefined && !colorDecorators['enable']) {
                    return colorDecorators['enable'];
                }
            }
            return this._editor.getOption(20 /* EditorOption.colorDecorators */);
        }
        static get(editor) {
            return editor.getContribution(this.ID);
        }
        dispose() {
            this.stop();
            this.removeAllDecorations();
            super.dispose();
        }
        updateColors() {
            this.stop();
            if (!this._isColorDecoratorsEnabled) {
                return;
            }
            const model = this._editor.getModel();
            if (!model || !this._languageFeaturesService.colorProvider.has(model)) {
                return;
            }
            this._localToDispose.add(this._editor.onDidChangeModelContent(() => {
                if (!this._timeoutTimer) {
                    this._timeoutTimer = new async_1.TimeoutTimer();
                    this._timeoutTimer.cancelAndSet(() => {
                        this._timeoutTimer = null;
                        this.beginCompute();
                    }, this._debounceInformation.get(model));
                }
            }));
            this.beginCompute();
        }
        async beginCompute() {
            this._computePromise = (0, async_1.createCancelablePromise)(async (token) => {
                const model = this._editor.getModel();
                if (!model) {
                    return [];
                }
                const sw = new stopwatch_1.StopWatch(false);
                const colors = await (0, color_2.getColors)(this._languageFeaturesService.colorProvider, model, token, this._isDefaultColorDecoratorsEnabled);
                this._debounceInformation.update(model, sw.elapsed());
                return colors;
            });
            try {
                const colors = await this._computePromise;
                this.updateDecorations(colors);
                this.updateColorDecorators(colors);
                this._computePromise = null;
            }
            catch (e) {
                (0, errors_1.onUnexpectedError)(e);
            }
        }
        stop() {
            if (this._timeoutTimer) {
                this._timeoutTimer.cancel();
                this._timeoutTimer = null;
            }
            if (this._computePromise) {
                this._computePromise.cancel();
                this._computePromise = null;
            }
            this._localToDispose.clear();
        }
        updateDecorations(colorDatas) {
            const decorations = colorDatas.map(c => ({
                range: {
                    startLineNumber: c.colorInfo.range.startLineNumber,
                    startColumn: c.colorInfo.range.startColumn,
                    endLineNumber: c.colorInfo.range.endLineNumber,
                    endColumn: c.colorInfo.range.endColumn
                },
                options: textModel_1.ModelDecorationOptions.EMPTY
            }));
            this._editor.changeDecorations((changeAccessor) => {
                this._decorationsIds = changeAccessor.deltaDecorations(this._decorationsIds, decorations);
                this._colorDatas = new Map();
                this._decorationsIds.forEach((id, i) => this._colorDatas.set(id, colorDatas[i]));
            });
        }
        updateColorDecorators(colorData) {
            this._colorDecorationClassRefs.clear();
            const decorations = [];
            const limit = this._editor.getOption(21 /* EditorOption.colorDecoratorsLimit */);
            for (let i = 0; i < colorData.length && decorations.length < limit; i++) {
                const { red, green, blue, alpha } = colorData[i].colorInfo.color;
                const rgba = new color_1.RGBA(Math.round(red * 255), Math.round(green * 255), Math.round(blue * 255), alpha);
                const color = `rgba(${rgba.r}, ${rgba.g}, ${rgba.b}, ${rgba.a})`;
                const ref = this._colorDecorationClassRefs.add(this._ruleFactory.createClassNameRef({
                    backgroundColor: color
                }));
                decorations.push({
                    range: {
                        startLineNumber: colorData[i].colorInfo.range.startLineNumber,
                        startColumn: colorData[i].colorInfo.range.startColumn,
                        endLineNumber: colorData[i].colorInfo.range.endLineNumber,
                        endColumn: colorData[i].colorInfo.range.endColumn
                    },
                    options: {
                        description: 'colorDetector',
                        before: {
                            content: strings_1.noBreakWhitespace,
                            inlineClassName: `${ref.className} colorpicker-color-decoration`,
                            inlineClassNameAffectsLetterSpacing: true,
                            attachedData: exports.ColorDecorationInjectedTextMarker
                        }
                    }
                });
            }
            const limited = limit < colorData.length ? limit : false;
            this._decoratorLimitReporter.update(colorData.length, limited);
            this._colorDecoratorIds.set(decorations);
        }
        removeAllDecorations() {
            this._editor.removeDecorations(this._decorationsIds);
            this._decorationsIds = [];
            this._colorDecoratorIds.clear();
            this._colorDecorationClassRefs.clear();
        }
        getColorData(position) {
            const model = this._editor.getModel();
            if (!model) {
                return null;
            }
            const decorations = model
                .getDecorationsInRange(range_1.Range.fromPositions(position, position))
                .filter(d => this._colorDatas.has(d.id));
            if (decorations.length === 0) {
                return null;
            }
            return this._colorDatas.get(decorations[0].id);
        }
        isColorDecoration(decoration) {
            return this._colorDecoratorIds.has(decoration);
        }
    };
    exports.ColorDetector = ColorDetector;
    exports.ColorDetector = ColorDetector = ColorDetector_1 = __decorate([
        __param(1, configuration_1.IConfigurationService),
        __param(2, languageFeatures_1.ILanguageFeaturesService),
        __param(3, languageFeatureDebounce_1.ILanguageFeatureDebounceService)
    ], ColorDetector);
    class DecoratorLimitReporter {
        constructor() {
            this._onDidChange = new event_1.Emitter();
            this._computed = 0;
            this._limited = false;
        }
        update(computed, limited) {
            if (computed !== this._computed || limited !== this._limited) {
                this._computed = computed;
                this._limited = limited;
                this._onDidChange.fire();
            }
        }
    }
    exports.DecoratorLimitReporter = DecoratorLimitReporter;
    (0, editorExtensions_1.registerEditorContribution)(ColorDetector.ID, ColorDetector, 1 /* EditorContributionInstantiation.AfterFirstRender */);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[288/*vs/editor/contrib/colorPicker/browser/colorHoverParticipant*/], __M([1/*require*/,0/*exports*/,14/*vs/base/common/async*/,18/*vs/base/common/cancellation*/,33/*vs/base/common/color*/,2/*vs/base/common/lifecycle*/,4/*vs/editor/common/core/range*/,388/*vs/editor/contrib/colorPicker/browser/color*/,422/*vs/editor/contrib/colorPicker/browser/colorDetector*/,608/*vs/editor/contrib/colorPicker/browser/colorPickerModel*/,763/*vs/editor/contrib/colorPicker/browser/colorPickerWidget*/,84/*vs/editor/contrib/hover/browser/hoverTypes*/,25/*vs/platform/theme/common/themeService*/,5/*vs/base/browser/dom*/]), function (require, exports, async_1, cancellation_1, color_1, lifecycle_1, range_1, color_2, colorDetector_1, colorPickerModel_1, colorPickerWidget_1, hoverTypes_1, themeService_1, dom_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.StandaloneColorPickerParticipant = exports.StandaloneColorPickerHover = exports.ColorHoverParticipant = exports.ColorHover = void 0;
    class ColorHover {
        constructor(owner, range, model, provider) {
            this.owner = owner;
            this.range = range;
            this.model = model;
            this.provider = provider;
            /**
             * Force the hover to always be rendered at this specific range,
             * even in the case of multiple hover parts.
             */
            this.forceShowAtRange = true;
        }
        isValidForHoverAnchor(anchor) {
            return (anchor.type === 1 /* HoverAnchorType.Range */
                && this.range.startColumn <= anchor.range.startColumn
                && this.range.endColumn >= anchor.range.endColumn);
        }
    }
    exports.ColorHover = ColorHover;
    let ColorHoverParticipant = class ColorHoverParticipant {
        constructor(_editor, _themeService) {
            this._editor = _editor;
            this._themeService = _themeService;
            this.hoverOrdinal = 2;
        }
        computeSync(_anchor, _lineDecorations) {
            return [];
        }
        computeAsync(anchor, lineDecorations, token) {
            return async_1.AsyncIterableObject.fromPromise(this._computeAsync(anchor, lineDecorations, token));
        }
        async _computeAsync(_anchor, lineDecorations, _token) {
            if (!this._editor.hasModel()) {
                return [];
            }
            const colorDetector = colorDetector_1.ColorDetector.get(this._editor);
            if (!colorDetector) {
                return [];
            }
            for (const d of lineDecorations) {
                if (!colorDetector.isColorDecoration(d)) {
                    continue;
                }
                const colorData = colorDetector.getColorData(d.range.getStartPosition());
                if (colorData) {
                    const colorHover = await _createColorHover(this, this._editor.getModel(), colorData.colorInfo, colorData.provider);
                    return [colorHover];
                }
            }
            return [];
        }
        renderHoverParts(context, hoverParts) {
            const renderedPart = renderHoverParts(this, this._editor, this._themeService, hoverParts, context);
            if (!renderedPart) {
                return new hoverTypes_1.RenderedHoverParts([]);
            }
            this._colorPicker = renderedPart.colorPicker;
            const renderedHoverPart = {
                hoverPart: renderedPart.hoverPart,
                hoverElement: this._colorPicker.domNode,
                dispose() { renderedPart.disposables.dispose(); }
            };
            return new hoverTypes_1.RenderedHoverParts([renderedHoverPart]);
        }
        handleResize() {
            this._colorPicker?.layout();
        }
        isColorPickerVisible() {
            return !!this._colorPicker;
        }
    };
    exports.ColorHoverParticipant = ColorHoverParticipant;
    exports.ColorHoverParticipant = ColorHoverParticipant = __decorate([
        __param(1, themeService_1.IThemeService)
    ], ColorHoverParticipant);
    class StandaloneColorPickerHover {
        constructor(owner, range, model, provider) {
            this.owner = owner;
            this.range = range;
            this.model = model;
            this.provider = provider;
        }
    }
    exports.StandaloneColorPickerHover = StandaloneColorPickerHover;
    let StandaloneColorPickerParticipant = class StandaloneColorPickerParticipant {
        constructor(_editor, _themeService) {
            this._editor = _editor;
            this._themeService = _themeService;
            this._color = null;
        }
        async createColorHover(defaultColorInfo, defaultColorProvider, colorProviderRegistry) {
            if (!this._editor.hasModel()) {
                return null;
            }
            const colorDetector = colorDetector_1.ColorDetector.get(this._editor);
            if (!colorDetector) {
                return null;
            }
            const colors = await (0, color_2.getColors)(colorProviderRegistry, this._editor.getModel(), cancellation_1.CancellationToken.None);
            let foundColorInfo = null;
            let foundColorProvider = null;
            for (const colorData of colors) {
                const colorInfo = colorData.colorInfo;
                if (range_1.Range.containsRange(colorInfo.range, defaultColorInfo.range)) {
                    foundColorInfo = colorInfo;
                    foundColorProvider = colorData.provider;
                }
            }
            const colorInfo = foundColorInfo ?? defaultColorInfo;
            const colorProvider = foundColorProvider ?? defaultColorProvider;
            const foundInEditor = !!foundColorInfo;
            return { colorHover: await _createColorHover(this, this._editor.getModel(), colorInfo, colorProvider), foundInEditor: foundInEditor };
        }
        async updateEditorModel(colorHoverData) {
            if (!this._editor.hasModel()) {
                return;
            }
            const colorPickerModel = colorHoverData.model;
            let range = new range_1.Range(colorHoverData.range.startLineNumber, colorHoverData.range.startColumn, colorHoverData.range.endLineNumber, colorHoverData.range.endColumn);
            if (this._color) {
                await _updateColorPresentations(this._editor.getModel(), colorPickerModel, this._color, range, colorHoverData);
                range = _updateEditorModel(this._editor, range, colorPickerModel);
            }
        }
        renderHoverParts(context, hoverParts) {
            return renderHoverParts(this, this._editor, this._themeService, hoverParts, context);
        }
        set color(color) {
            this._color = color;
        }
        get color() {
            return this._color;
        }
    };
    exports.StandaloneColorPickerParticipant = StandaloneColorPickerParticipant;
    exports.StandaloneColorPickerParticipant = StandaloneColorPickerParticipant = __decorate([
        __param(1, themeService_1.IThemeService)
    ], StandaloneColorPickerParticipant);
    async function _createColorHover(participant, editorModel, colorInfo, provider) {
        const originalText = editorModel.getValueInRange(colorInfo.range);
        const { red, green, blue, alpha } = colorInfo.color;
        const rgba = new color_1.RGBA(Math.round(red * 255), Math.round(green * 255), Math.round(blue * 255), alpha);
        const color = new color_1.Color(rgba);
        const colorPresentations = await (0, color_2.getColorPresentations)(editorModel, colorInfo, provider, cancellation_1.CancellationToken.None);
        const model = new colorPickerModel_1.ColorPickerModel(color, [], 0);
        model.colorPresentations = colorPresentations || [];
        model.guessColorPresentation(color, originalText);
        if (participant instanceof ColorHoverParticipant) {
            return new ColorHover(participant, range_1.Range.lift(colorInfo.range), model, provider);
        }
        else {
            return new StandaloneColorPickerHover(participant, range_1.Range.lift(colorInfo.range), model, provider);
        }
    }
    function renderHoverParts(participant, editor, themeService, hoverParts, context) {
        if (hoverParts.length === 0 || !editor.hasModel()) {
            return undefined;
        }
        if (context.setMinimumDimensions) {
            const minimumHeight = editor.getOption(67 /* EditorOption.lineHeight */) + 8;
            context.setMinimumDimensions(new dom_1.Dimension(302, minimumHeight));
        }
        const disposables = new lifecycle_1.DisposableStore();
        const colorHover = hoverParts[0];
        const editorModel = editor.getModel();
        const model = colorHover.model;
        const colorPicker = disposables.add(new colorPickerWidget_1.ColorPickerWidget(context.fragment, model, editor.getOption(144 /* EditorOption.pixelRatio */), themeService, participant instanceof StandaloneColorPickerParticipant));
        let editorUpdatedByColorPicker = false;
        let range = new range_1.Range(colorHover.range.startLineNumber, colorHover.range.startColumn, colorHover.range.endLineNumber, colorHover.range.endColumn);
        if (participant instanceof StandaloneColorPickerParticipant) {
            const color = colorHover.model.color;
            participant.color = color;
            _updateColorPresentations(editorModel, model, color, range, colorHover);
            disposables.add(model.onColorFlushed((color) => {
                participant.color = color;
            }));
        }
        else {
            disposables.add(model.onColorFlushed(async (color) => {
                await _updateColorPresentations(editorModel, model, color, range, colorHover);
                editorUpdatedByColorPicker = true;
                range = _updateEditorModel(editor, range, model);
            }));
        }
        disposables.add(model.onDidChangeColor((color) => {
            _updateColorPresentations(editorModel, model, color, range, colorHover);
        }));
        disposables.add(editor.onDidChangeModelContent((e) => {
            if (editorUpdatedByColorPicker) {
                editorUpdatedByColorPicker = false;
            }
            else {
                context.hide();
                editor.focus();
            }
        }));
        return { hoverPart: colorHover, colorPicker, disposables };
    }
    function _updateEditorModel(editor, range, model) {
        const textEdits = [];
        const edit = model.presentation.textEdit ?? { range, text: model.presentation.label, forceMoveMarkers: false };
        textEdits.push(edit);
        if (model.presentation.additionalTextEdits) {
            textEdits.push(...model.presentation.additionalTextEdits);
        }
        const replaceRange = range_1.Range.lift(edit.range);
        const trackedRange = editor.getModel()._setTrackedRange(null, replaceRange, 3 /* TrackedRangeStickiness.GrowsOnlyWhenTypingAfter */);
        editor.executeEdits('colorpicker', textEdits);
        editor.pushUndoStop();
        return editor.getModel()._getTrackedRange(trackedRange) ?? replaceRange;
    }
    async function _updateColorPresentations(editorModel, colorPickerModel, color, range, colorHover) {
        const colorPresentations = await (0, color_2.getColorPresentations)(editorModel, {
            range: range,
            color: {
                red: color.rgba.r / 255,
                green: color.rgba.g / 255,
                blue: color.rgba.b / 255,
                alpha: color.rgba.a
            }
        }, colorHover.provider, cancellation_1.CancellationToken.None);
        colorPickerModel.colorPresentations = colorPresentations || [];
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[820/*vs/editor/contrib/colorPicker/browser/standaloneColorPickerWidget*/], __M([1/*require*/,0/*exports*/,2/*vs/base/common/lifecycle*/,288/*vs/editor/contrib/colorPicker/browser/colorHoverParticipant*/,7/*vs/platform/instantiation/common/instantiation*/,391/*vs/editor/contrib/hover/browser/contentHoverStatusBar*/,31/*vs/platform/keybinding/common/keybinding*/,6/*vs/base/common/event*/,17/*vs/editor/common/services/languageFeatures*/,15/*vs/editor/browser/editorExtensions*/,20/*vs/editor/common/editorContextKeys*/,12/*vs/platform/contextkey/common/contextkey*/,385/*vs/editor/contrib/colorPicker/browser/defaultDocumentColorProvider*/,5/*vs/base/browser/dom*/,100/*vs/editor/common/services/editorWorker*/,227/*vs/css!vs/editor/contrib/colorPicker/browser/colorPicker*/]), function (require, exports, lifecycle_1, colorHoverParticipant_1, instantiation_1, contentHoverStatusBar_1, keybinding_1, event_1, languageFeatures_1, editorExtensions_1, editorContextKeys_1, contextkey_1, defaultDocumentColorProvider_1, dom, editorWorker_1) {
    "use strict";
    var StandaloneColorPickerController_1, StandaloneColorPickerWidget_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.StandaloneColorPickerWidget = exports.StandaloneColorPickerController = void 0;
    let StandaloneColorPickerController = class StandaloneColorPickerController extends lifecycle_1.Disposable {
        static { StandaloneColorPickerController_1 = this; }
        static { this.ID = 'editor.contrib.standaloneColorPickerController'; }
        constructor(_editor, _contextKeyService, _instantiationService) {
            super();
            this._editor = _editor;
            this._instantiationService = _instantiationService;
            this._standaloneColorPickerWidget = null;
            this._standaloneColorPickerVisible = editorContextKeys_1.EditorContextKeys.standaloneColorPickerVisible.bindTo(_contextKeyService);
            this._standaloneColorPickerFocused = editorContextKeys_1.EditorContextKeys.standaloneColorPickerFocused.bindTo(_contextKeyService);
        }
        showOrFocus() {
            if (!this._editor.hasModel()) {
                return;
            }
            if (!this._standaloneColorPickerVisible.get()) {
                this._standaloneColorPickerWidget = this._instantiationService.createInstance(StandaloneColorPickerWidget, this._editor, this._standaloneColorPickerVisible, this._standaloneColorPickerFocused);
            }
            else if (!this._standaloneColorPickerFocused.get()) {
                this._standaloneColorPickerWidget?.focus();
            }
        }
        hide() {
            this._standaloneColorPickerFocused.set(false);
            this._standaloneColorPickerVisible.set(false);
            this._standaloneColorPickerWidget?.hide();
            this._editor.focus();
        }
        insertColor() {
            this._standaloneColorPickerWidget?.updateEditor();
            this.hide();
        }
        static get(editor) {
            return editor.getContribution(StandaloneColorPickerController_1.ID);
        }
    };
    exports.StandaloneColorPickerController = StandaloneColorPickerController;
    exports.StandaloneColorPickerController = StandaloneColorPickerController = StandaloneColorPickerController_1 = __decorate([
        __param(1, contextkey_1.IContextKeyService),
        __param(2, instantiation_1.IInstantiationService)
    ], StandaloneColorPickerController);
    (0, editorExtensions_1.registerEditorContribution)(StandaloneColorPickerController.ID, StandaloneColorPickerController, 1 /* EditorContributionInstantiation.AfterFirstRender */);
    const PADDING = 8;
    const CLOSE_BUTTON_WIDTH = 22;
    let StandaloneColorPickerWidget = class StandaloneColorPickerWidget extends lifecycle_1.Disposable {
        static { StandaloneColorPickerWidget_1 = this; }
        static { this.ID = 'editor.contrib.standaloneColorPickerWidget'; }
        constructor(_editor, _standaloneColorPickerVisible, _standaloneColorPickerFocused, _instantiationService, _keybindingService, _languageFeaturesService, _editorWorkerService) {
            super();
            this._editor = _editor;
            this._standaloneColorPickerVisible = _standaloneColorPickerVisible;
            this._standaloneColorPickerFocused = _standaloneColorPickerFocused;
            this._keybindingService = _keybindingService;
            this._languageFeaturesService = _languageFeaturesService;
            this._editorWorkerService = _editorWorkerService;
            this.allowEditorOverflow = true;
            this._position = undefined;
            this._body = document.createElement('div');
            this._colorHover = null;
            this._selectionSetInEditor = false;
            this._onResult = this._register(new event_1.Emitter());
            this.onResult = this._onResult.event;
            this._standaloneColorPickerVisible.set(true);
            this._standaloneColorPickerParticipant = _instantiationService.createInstance(colorHoverParticipant_1.StandaloneColorPickerParticipant, this._editor);
            this._position = this._editor._getViewModel()?.getPrimaryCursorState().modelState.position;
            const editorSelection = this._editor.getSelection();
            const selection = editorSelection ?
                {
                    startLineNumber: editorSelection.startLineNumber,
                    startColumn: editorSelection.startColumn,
                    endLineNumber: editorSelection.endLineNumber,
                    endColumn: editorSelection.endColumn
                } : { startLineNumber: 0, endLineNumber: 0, endColumn: 0, startColumn: 0 };
            const focusTracker = this._register(dom.trackFocus(this._body));
            this._register(focusTracker.onDidBlur(_ => {
                this.hide();
            }));
            this._register(focusTracker.onDidFocus(_ => {
                this.focus();
            }));
            // When the cursor position changes, hide the color picker
            this._register(this._editor.onDidChangeCursorPosition(() => {
                // Do not hide the color picker when the cursor changes position due to the keybindings
                if (!this._selectionSetInEditor) {
                    this.hide();
                }
                else {
                    this._selectionSetInEditor = false;
                }
            }));
            this._register(this._editor.onMouseMove((e) => {
                const classList = e.target.element?.classList;
                if (classList && classList.contains('colorpicker-color-decoration')) {
                    this.hide();
                }
            }));
            this._register(this.onResult((result) => {
                this._render(result.value, result.foundInEditor);
            }));
            this._start(selection);
            this._body.style.zIndex = '50';
            this._editor.addContentWidget(this);
        }
        updateEditor() {
            if (this._colorHover) {
                this._standaloneColorPickerParticipant.updateEditorModel(this._colorHover);
            }
        }
        getId() {
            return StandaloneColorPickerWidget_1.ID;
        }
        getDomNode() {
            return this._body;
        }
        getPosition() {
            if (!this._position) {
                return null;
            }
            const positionPreference = this._editor.getOption(60 /* EditorOption.hover */).above;
            return {
                position: this._position,
                secondaryPosition: this._position,
                preference: positionPreference ? [1 /* ContentWidgetPositionPreference.ABOVE */, 2 /* ContentWidgetPositionPreference.BELOW */] : [2 /* ContentWidgetPositionPreference.BELOW */, 1 /* ContentWidgetPositionPreference.ABOVE */],
                positionAffinity: 2 /* PositionAffinity.None */
            };
        }
        hide() {
            this.dispose();
            this._standaloneColorPickerVisible.set(false);
            this._standaloneColorPickerFocused.set(false);
            this._editor.removeContentWidget(this);
            this._editor.focus();
        }
        focus() {
            this._standaloneColorPickerFocused.set(true);
            this._body.focus();
        }
        async _start(selection) {
            const computeAsyncResult = await this._computeAsync(selection);
            if (!computeAsyncResult) {
                return;
            }
            this._onResult.fire(new StandaloneColorPickerResult(computeAsyncResult.result, computeAsyncResult.foundInEditor));
        }
        async _computeAsync(range) {
            if (!this._editor.hasModel()) {
                return null;
            }
            const colorInfo = {
                range: range,
                color: { red: 0, green: 0, blue: 0, alpha: 1 }
            };
            const colorHoverResult = await this._standaloneColorPickerParticipant.createColorHover(colorInfo, new defaultDocumentColorProvider_1.DefaultDocumentColorProvider(this._editorWorkerService), this._languageFeaturesService.colorProvider);
            if (!colorHoverResult) {
                return null;
            }
            return { result: colorHoverResult.colorHover, foundInEditor: colorHoverResult.foundInEditor };
        }
        _render(colorHover, foundInEditor) {
            const fragment = document.createDocumentFragment();
            const statusBar = this._register(new contentHoverStatusBar_1.EditorHoverStatusBar(this._keybindingService));
            const context = {
                fragment,
                statusBar,
                onContentsChanged: () => { },
                hide: () => this.hide()
            };
            this._colorHover = colorHover;
            const renderedHoverPart = this._standaloneColorPickerParticipant.renderHoverParts(context, [colorHover]);
            if (!renderedHoverPart) {
                return;
            }
            this._register(renderedHoverPart.disposables);
            const colorPicker = renderedHoverPart.colorPicker;
            this._body.classList.add('standalone-colorpicker-body');
            this._body.style.maxHeight = Math.max(this._editor.getLayoutInfo().height / 4, 250) + 'px';
            this._body.style.maxWidth = Math.max(this._editor.getLayoutInfo().width * 0.66, 500) + 'px';
            this._body.tabIndex = 0;
            this._body.appendChild(fragment);
            colorPicker.layout();
            const colorPickerBody = colorPicker.body;
            const saturationBoxWidth = colorPickerBody.saturationBox.domNode.clientWidth;
            const widthOfOriginalColorBox = colorPickerBody.domNode.clientWidth - saturationBoxWidth - CLOSE_BUTTON_WIDTH - PADDING;
            const enterButton = colorPicker.body.enterButton;
            enterButton?.onClicked(() => {
                this.updateEditor();
                this.hide();
            });
            const colorPickerHeader = colorPicker.header;
            const pickedColorNode = colorPickerHeader.pickedColorNode;
            pickedColorNode.style.width = saturationBoxWidth + PADDING + 'px';
            const originalColorNode = colorPickerHeader.originalColorNode;
            originalColorNode.style.width = widthOfOriginalColorBox + 'px';
            const closeButton = colorPicker.header.closeButton;
            closeButton?.onClicked(() => {
                this.hide();
            });
            // When found in the editor, highlight the selection in the editor
            if (foundInEditor) {
                if (enterButton) {
                    enterButton.button.textContent = 'Replace';
                }
                this._selectionSetInEditor = true;
                this._editor.setSelection(colorHover.range);
            }
            this._editor.layoutContentWidget(this);
        }
    };
    exports.StandaloneColorPickerWidget = StandaloneColorPickerWidget;
    exports.StandaloneColorPickerWidget = StandaloneColorPickerWidget = StandaloneColorPickerWidget_1 = __decorate([
        __param(3, instantiation_1.IInstantiationService),
        __param(4, keybinding_1.IKeybindingService),
        __param(5, languageFeatures_1.ILanguageFeaturesService),
        __param(6, editorWorker_1.IEditorWorkerService)
    ], StandaloneColorPickerWidget);
    class StandaloneColorPickerResult {
        // The color picker result consists of: an array of color results and a boolean indicating if the color was found in the editor
        constructor(value, foundInEditor) {
            this.value = value;
            this.foundInEditor = foundInEditor;
        }
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[821/*vs/editor/contrib/colorPicker/browser/standaloneColorPickerActions*/], __M([1/*require*/,0/*exports*/,15/*vs/editor/browser/editorExtensions*/,3/*vs/nls*/,820/*vs/editor/contrib/colorPicker/browser/standaloneColorPickerWidget*/,20/*vs/editor/common/editorContextKeys*/,29/*vs/platform/actions/common/actions*/,227/*vs/css!vs/editor/contrib/colorPicker/browser/colorPicker*/]), function (require, exports, editorExtensions_1, nls_1, standaloneColorPickerWidget_1, editorContextKeys_1, actions_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ShowOrFocusStandaloneColorPicker = void 0;
    class ShowOrFocusStandaloneColorPicker extends editorExtensions_1.EditorAction2 {
        constructor() {
            super({
                id: 'editor.action.showOrFocusStandaloneColorPicker',
                title: {
                    ...(0, nls_1.localize2)(801, "Show or Focus Standalone Color Picker"),
                    mnemonicTitle: (0, nls_1.localize)(798, "&&Show or Focus Standalone Color Picker"),
                },
                precondition: undefined,
                menu: [
                    { id: actions_1.MenuId.CommandPalette },
                ],
                metadata: {
                    description: (0, nls_1.localize2)(802, "Show or focus a standalone color picker which uses the default color provider. It displays hex/rgb/hsl colors."),
                }
            });
        }
        runEditorCommand(_accessor, editor) {
            standaloneColorPickerWidget_1.StandaloneColorPickerController.get(editor)?.showOrFocus();
        }
    }
    exports.ShowOrFocusStandaloneColorPicker = ShowOrFocusStandaloneColorPicker;
    class HideStandaloneColorPicker extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: 'editor.action.hideColorPicker',
                label: (0, nls_1.localize)(799, "Hide the Color Picker"),





                alias: 'Hide the Color Picker',
                precondition: editorContextKeys_1.EditorContextKeys.standaloneColorPickerVisible.isEqualTo(true),
                kbOpts: {
                    primary: 9 /* KeyCode.Escape */,
                    weight: 100 /* KeybindingWeight.EditorContrib */
                },
                metadata: {
                    description: (0, nls_1.localize2)(803, "Hide the standalone color picker."),
                }
            });
        }
        run(_accessor, editor) {
            standaloneColorPickerWidget_1.StandaloneColorPickerController.get(editor)?.hide();
        }
    }
    class InsertColorWithStandaloneColorPicker extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: 'editor.action.insertColorWithStandaloneColorPicker',
                label: (0, nls_1.localize)(800, "Insert Color with Standalone Color Picker"),





                alias: 'Insert Color with Standalone Color Picker',
                precondition: editorContextKeys_1.EditorContextKeys.standaloneColorPickerFocused.isEqualTo(true),
                kbOpts: {
                    primary: 3 /* KeyCode.Enter */,
                    weight: 100 /* KeybindingWeight.EditorContrib */
                },
                metadata: {
                    description: (0, nls_1.localize2)(804, "Insert hex/rgb/hsl colors with the focused standalone color picker."),
                }
            });
        }
        run(_accessor, editor) {
            standaloneColorPickerWidget_1.StandaloneColorPickerController.get(editor)?.insertColor();
        }
    }
    (0, editorExtensions_1.registerEditorAction)(HideStandaloneColorPicker);
    (0, editorExtensions_1.registerEditorAction)(InsertColorWithStandaloneColorPicker);
    (0, actions_1.registerAction2)(ShowOrFocusStandaloneColorPicker);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[822/*vs/editor/contrib/dnd/browser/dnd*/], __M([1/*require*/,0/*exports*/,2/*vs/base/common/lifecycle*/,16/*vs/base/common/platform*/,15/*vs/editor/browser/editorExtensions*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/,23/*vs/editor/common/core/selection*/,35/*vs/editor/common/model/textModel*/,610/*vs/editor/contrib/dnd/browser/dragAndDropCommand*/,507/*vs/css!vs/editor/contrib/dnd/browser/dnd*/]), function (require, exports, lifecycle_1, platform_1, editorExtensions_1, position_1, range_1, selection_1, textModel_1, dragAndDropCommand_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DragAndDropController = void 0;
    function hasTriggerModifier(e) {
        if (platform_1.isMacintosh) {
            return e.altKey;
        }
        else {
            return e.ctrlKey;
        }
    }
    class DragAndDropController extends lifecycle_1.Disposable {
        static { this.ID = 'editor.contrib.dragAndDrop'; }
        static { this.TRIGGER_KEY_VALUE = platform_1.isMacintosh ? 6 /* KeyCode.Alt */ : 5 /* KeyCode.Ctrl */; }
        constructor(editor) {
            super();
            this._editor = editor;
            this._dndDecorationIds = this._editor.createDecorationsCollection();
            this._register(this._editor.onMouseDown((e) => this._onEditorMouseDown(e)));
            this._register(this._editor.onMouseUp((e) => this._onEditorMouseUp(e)));
            this._register(this._editor.onMouseDrag((e) => this._onEditorMouseDrag(e)));
            this._register(this._editor.onMouseDrop((e) => this._onEditorMouseDrop(e)));
            this._register(this._editor.onMouseDropCanceled(() => this._onEditorMouseDropCanceled()));
            this._register(this._editor.onKeyDown((e) => this.onEditorKeyDown(e)));
            this._register(this._editor.onKeyUp((e) => this.onEditorKeyUp(e)));
            this._register(this._editor.onDidBlurEditorWidget(() => this.onEditorBlur()));
            this._register(this._editor.onDidBlurEditorText(() => this.onEditorBlur()));
            this._mouseDown = false;
            this._modifierPressed = false;
            this._dragSelection = null;
        }
        onEditorBlur() {
            this._removeDecoration();
            this._dragSelection = null;
            this._mouseDown = false;
            this._modifierPressed = false;
        }
        onEditorKeyDown(e) {
            if (!this._editor.getOption(35 /* EditorOption.dragAndDrop */) || this._editor.getOption(22 /* EditorOption.columnSelection */)) {
                return;
            }
            if (hasTriggerModifier(e)) {
                this._modifierPressed = true;
            }
            if (this._mouseDown && hasTriggerModifier(e)) {
                this._editor.updateOptions({
                    mouseStyle: 'copy'
                });
            }
        }
        onEditorKeyUp(e) {
            if (!this._editor.getOption(35 /* EditorOption.dragAndDrop */) || this._editor.getOption(22 /* EditorOption.columnSelection */)) {
                return;
            }
            if (hasTriggerModifier(e)) {
                this._modifierPressed = false;
            }
            if (this._mouseDown && e.keyCode === DragAndDropController.TRIGGER_KEY_VALUE) {
                this._editor.updateOptions({
                    mouseStyle: 'default'
                });
            }
        }
        _onEditorMouseDown(mouseEvent) {
            this._mouseDown = true;
        }
        _onEditorMouseUp(mouseEvent) {
            this._mouseDown = false;
            // Whenever users release the mouse, the drag and drop operation should finish and the cursor should revert to text.
            this._editor.updateOptions({
                mouseStyle: 'text'
            });
        }
        _onEditorMouseDrag(mouseEvent) {
            const target = mouseEvent.target;
            if (this._dragSelection === null) {
                const selections = this._editor.getSelections() || [];
                const possibleSelections = selections.filter(selection => target.position && selection.containsPosition(target.position));
                if (possibleSelections.length === 1) {
                    this._dragSelection = possibleSelections[0];
                }
                else {
                    return;
                }
            }
            if (hasTriggerModifier(mouseEvent.event)) {
                this._editor.updateOptions({
                    mouseStyle: 'copy'
                });
            }
            else {
                this._editor.updateOptions({
                    mouseStyle: 'default'
                });
            }
            if (target.position) {
                if (this._dragSelection.containsPosition(target.position)) {
                    this._removeDecoration();
                }
                else {
                    this.showAt(target.position);
                }
            }
        }
        _onEditorMouseDropCanceled() {
            this._editor.updateOptions({
                mouseStyle: 'text'
            });
            this._removeDecoration();
            this._dragSelection = null;
            this._mouseDown = false;
        }
        _onEditorMouseDrop(mouseEvent) {
            if (mouseEvent.target && (this._hitContent(mouseEvent.target) || this._hitMargin(mouseEvent.target)) && mouseEvent.target.position) {
                const newCursorPosition = new position_1.Position(mouseEvent.target.position.lineNumber, mouseEvent.target.position.column);
                if (this._dragSelection === null) {
                    let newSelections = null;
                    if (mouseEvent.event.shiftKey) {
                        const primarySelection = this._editor.getSelection();
                        if (primarySelection) {
                            const { selectionStartLineNumber, selectionStartColumn } = primarySelection;
                            newSelections = [new selection_1.Selection(selectionStartLineNumber, selectionStartColumn, newCursorPosition.lineNumber, newCursorPosition.column)];
                        }
                    }
                    else {
                        newSelections = (this._editor.getSelections() || []).map(selection => {
                            if (selection.containsPosition(newCursorPosition)) {
                                return new selection_1.Selection(newCursorPosition.lineNumber, newCursorPosition.column, newCursorPosition.lineNumber, newCursorPosition.column);
                            }
                            else {
                                return selection;
                            }
                        });
                    }
                    // Use `mouse` as the source instead of `api` and setting the reason to explicit (to behave like any other mouse operation).
                    this._editor.setSelections(newSelections || [], 'mouse', 3 /* CursorChangeReason.Explicit */);
                }
                else if (!this._dragSelection.containsPosition(newCursorPosition) ||
                    ((hasTriggerModifier(mouseEvent.event) ||
                        this._modifierPressed) && (this._dragSelection.getEndPosition().equals(newCursorPosition) || this._dragSelection.getStartPosition().equals(newCursorPosition)) // we allow users to paste content beside the selection
                    )) {
                    this._editor.pushUndoStop();
                    this._editor.executeCommand(DragAndDropController.ID, new dragAndDropCommand_1.DragAndDropCommand(this._dragSelection, newCursorPosition, hasTriggerModifier(mouseEvent.event) || this._modifierPressed));
                    this._editor.pushUndoStop();
                }
            }
            this._editor.updateOptions({
                mouseStyle: 'text'
            });
            this._removeDecoration();
            this._dragSelection = null;
            this._mouseDown = false;
        }
        static { this._DECORATION_OPTIONS = textModel_1.ModelDecorationOptions.register({
            description: 'dnd-target',
            className: 'dnd-target'
        }); }
        showAt(position) {
            this._dndDecorationIds.set([{
                    range: new range_1.Range(position.lineNumber, position.column, position.lineNumber, position.column),
                    options: DragAndDropController._DECORATION_OPTIONS
                }]);
            this._editor.revealPosition(position, 1 /* ScrollType.Immediate */);
        }
        _removeDecoration() {
            this._dndDecorationIds.clear();
        }
        _hitContent(target) {
            return target.type === 6 /* MouseTargetType.CONTENT_TEXT */ ||
                target.type === 7 /* MouseTargetType.CONTENT_EMPTY */;
        }
        _hitMargin(target) {
            return target.type === 2 /* MouseTargetType.GUTTER_GLYPH_MARGIN */ ||
                target.type === 3 /* MouseTargetType.GUTTER_LINE_NUMBERS */ ||
                target.type === 4 /* MouseTargetType.GUTTER_LINE_DECORATIONS */;
        }
        dispose() {
            this._removeDecoration();
            this._dragSelection = null;
            this._mouseDown = false;
            this._modifierPressed = false;
            super.dispose();
        }
    }
    exports.DragAndDropController = DragAndDropController;
    (0, editorExtensions_1.registerEditorContribution)(DragAndDropController.ID, DragAndDropController, 2 /* EditorContributionInstantiation.BeforeFirstInteraction */);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[823/*vs/editor/contrib/find/browser/findDecorations*/], __M([1/*require*/,0/*exports*/,4/*vs/editor/common/core/range*/,40/*vs/editor/common/model*/,35/*vs/editor/common/model/textModel*/,32/*vs/platform/theme/common/colorRegistry*/,25/*vs/platform/theme/common/themeService*/]), function (require, exports, range_1, model_1, textModel_1, colorRegistry_1, themeService_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.FindDecorations = void 0;
    class FindDecorations {
        constructor(editor) {
            this._editor = editor;
            this._decorations = [];
            this._overviewRulerApproximateDecorations = [];
            this._findScopeDecorationIds = [];
            this._rangeHighlightDecorationId = null;
            this._highlightedDecorationId = null;
            this._startPosition = this._editor.getPosition();
        }
        dispose() {
            this._editor.removeDecorations(this._allDecorations());
            this._decorations = [];
            this._overviewRulerApproximateDecorations = [];
            this._findScopeDecorationIds = [];
            this._rangeHighlightDecorationId = null;
            this._highlightedDecorationId = null;
        }
        reset() {
            this._decorations = [];
            this._overviewRulerApproximateDecorations = [];
            this._findScopeDecorationIds = [];
            this._rangeHighlightDecorationId = null;
            this._highlightedDecorationId = null;
        }
        getCount() {
            return this._decorations.length;
        }
        /** @deprecated use getFindScopes to support multiple selections */
        getFindScope() {
            if (this._findScopeDecorationIds[0]) {
                return this._editor.getModel().getDecorationRange(this._findScopeDecorationIds[0]);
            }
            return null;
        }
        getFindScopes() {
            if (this._findScopeDecorationIds.length) {
                const scopes = this._findScopeDecorationIds.map(findScopeDecorationId => this._editor.getModel().getDecorationRange(findScopeDecorationId)).filter(element => !!element);
                if (scopes.length) {
                    return scopes;
                }
            }
            return null;
        }
        getStartPosition() {
            return this._startPosition;
        }
        setStartPosition(newStartPosition) {
            this._startPosition = newStartPosition;
            this.setCurrentFindMatch(null);
        }
        _getDecorationIndex(decorationId) {
            const index = this._decorations.indexOf(decorationId);
            if (index >= 0) {
                return index + 1;
            }
            return 1;
        }
        getDecorationRangeAt(index) {
            const decorationId = index < this._decorations.length ? this._decorations[index] : null;
            if (decorationId) {
                return this._editor.getModel().getDecorationRange(decorationId);
            }
            return null;
        }
        getCurrentMatchesPosition(desiredRange) {
            const candidates = this._editor.getModel().getDecorationsInRange(desiredRange);
            for (const candidate of candidates) {
                const candidateOpts = candidate.options;
                if (candidateOpts === FindDecorations._FIND_MATCH_DECORATION || candidateOpts === FindDecorations._CURRENT_FIND_MATCH_DECORATION) {
                    return this._getDecorationIndex(candidate.id);
                }
            }
            // We don't know the current match position, so returns zero to show '?' in find widget
            return 0;
        }
        setCurrentFindMatch(nextMatch) {
            let newCurrentDecorationId = null;
            let matchPosition = 0;
            if (nextMatch) {
                for (let i = 0, len = this._decorations.length; i < len; i++) {
                    const range = this._editor.getModel().getDecorationRange(this._decorations[i]);
                    if (nextMatch.equalsRange(range)) {
                        newCurrentDecorationId = this._decorations[i];
                        matchPosition = (i + 1);
                        break;
                    }
                }
            }
            if (this._highlightedDecorationId !== null || newCurrentDecorationId !== null) {
                this._editor.changeDecorations((changeAccessor) => {
                    if (this._highlightedDecorationId !== null) {
                        changeAccessor.changeDecorationOptions(this._highlightedDecorationId, FindDecorations._FIND_MATCH_DECORATION);
                        this._highlightedDecorationId = null;
                    }
                    if (newCurrentDecorationId !== null) {
                        this._highlightedDecorationId = newCurrentDecorationId;
                        changeAccessor.changeDecorationOptions(this._highlightedDecorationId, FindDecorations._CURRENT_FIND_MATCH_DECORATION);
                    }
                    if (this._rangeHighlightDecorationId !== null) {
                        changeAccessor.removeDecoration(this._rangeHighlightDecorationId);
                        this._rangeHighlightDecorationId = null;
                    }
                    if (newCurrentDecorationId !== null) {
                        let rng = this._editor.getModel().getDecorationRange(newCurrentDecorationId);
                        if (rng.startLineNumber !== rng.endLineNumber && rng.endColumn === 1) {
                            const lineBeforeEnd = rng.endLineNumber - 1;
                            const lineBeforeEndMaxColumn = this._editor.getModel().getLineMaxColumn(lineBeforeEnd);
                            rng = new range_1.Range(rng.startLineNumber, rng.startColumn, lineBeforeEnd, lineBeforeEndMaxColumn);
                        }
                        this._rangeHighlightDecorationId = changeAccessor.addDecoration(rng, FindDecorations._RANGE_HIGHLIGHT_DECORATION);
                    }
                });
            }
            return matchPosition;
        }
        set(findMatches, findScopes) {
            this._editor.changeDecorations((accessor) => {
                let findMatchesOptions = FindDecorations._FIND_MATCH_DECORATION;
                const newOverviewRulerApproximateDecorations = [];
                if (findMatches.length > 1000) {
                    // we go into a mode where the overview ruler gets "approximate" decorations
                    // the reason is that the overview ruler paints all the decorations in the file and we don't want to cause freezes
                    findMatchesOptions = FindDecorations._FIND_MATCH_NO_OVERVIEW_DECORATION;
                    // approximate a distance in lines where matches should be merged
                    const lineCount = this._editor.getModel().getLineCount();
                    const height = this._editor.getLayoutInfo().height;
                    const approxPixelsPerLine = height / lineCount;
                    const mergeLinesDelta = Math.max(2, Math.ceil(3 / approxPixelsPerLine));
                    // merge decorations as much as possible
                    let prevStartLineNumber = findMatches[0].range.startLineNumber;
                    let prevEndLineNumber = findMatches[0].range.endLineNumber;
                    for (let i = 1, len = findMatches.length; i < len; i++) {
                        const range = findMatches[i].range;
                        if (prevEndLineNumber + mergeLinesDelta >= range.startLineNumber) {
                            if (range.endLineNumber > prevEndLineNumber) {
                                prevEndLineNumber = range.endLineNumber;
                            }
                        }
                        else {
                            newOverviewRulerApproximateDecorations.push({
                                range: new range_1.Range(prevStartLineNumber, 1, prevEndLineNumber, 1),
                                options: FindDecorations._FIND_MATCH_ONLY_OVERVIEW_DECORATION
                            });
                            prevStartLineNumber = range.startLineNumber;
                            prevEndLineNumber = range.endLineNumber;
                        }
                    }
                    newOverviewRulerApproximateDecorations.push({
                        range: new range_1.Range(prevStartLineNumber, 1, prevEndLineNumber, 1),
                        options: FindDecorations._FIND_MATCH_ONLY_OVERVIEW_DECORATION
                    });
                }
                // Find matches
                const newFindMatchesDecorations = new Array(findMatches.length);
                for (let i = 0, len = findMatches.length; i < len; i++) {
                    newFindMatchesDecorations[i] = {
                        range: findMatches[i].range,
                        options: findMatchesOptions
                    };
                }
                this._decorations = accessor.deltaDecorations(this._decorations, newFindMatchesDecorations);
                // Overview ruler approximate decorations
                this._overviewRulerApproximateDecorations = accessor.deltaDecorations(this._overviewRulerApproximateDecorations, newOverviewRulerApproximateDecorations);
                // Range highlight
                if (this._rangeHighlightDecorationId) {
                    accessor.removeDecoration(this._rangeHighlightDecorationId);
                    this._rangeHighlightDecorationId = null;
                }
                // Find scope
                if (this._findScopeDecorationIds.length) {
                    this._findScopeDecorationIds.forEach(findScopeDecorationId => accessor.removeDecoration(findScopeDecorationId));
                    this._findScopeDecorationIds = [];
                }
                if (findScopes?.length) {
                    this._findScopeDecorationIds = findScopes.map(findScope => accessor.addDecoration(findScope, FindDecorations._FIND_SCOPE_DECORATION));
                }
            });
        }
        matchBeforePosition(position) {
            if (this._decorations.length === 0) {
                return null;
            }
            for (let i = this._decorations.length - 1; i >= 0; i--) {
                const decorationId = this._decorations[i];
                const r = this._editor.getModel().getDecorationRange(decorationId);
                if (!r || r.endLineNumber > position.lineNumber) {
                    continue;
                }
                if (r.endLineNumber < position.lineNumber) {
                    return r;
                }
                if (r.endColumn > position.column) {
                    continue;
                }
                return r;
            }
            return this._editor.getModel().getDecorationRange(this._decorations[this._decorations.length - 1]);
        }
        matchAfterPosition(position) {
            if (this._decorations.length === 0) {
                return null;
            }
            for (let i = 0, len = this._decorations.length; i < len; i++) {
                const decorationId = this._decorations[i];
                const r = this._editor.getModel().getDecorationRange(decorationId);
                if (!r || r.startLineNumber < position.lineNumber) {
                    continue;
                }
                if (r.startLineNumber > position.lineNumber) {
                    return r;
                }
                if (r.startColumn < position.column) {
                    continue;
                }
                return r;
            }
            return this._editor.getModel().getDecorationRange(this._decorations[0]);
        }
        _allDecorations() {
            let result = [];
            result = result.concat(this._decorations);
            result = result.concat(this._overviewRulerApproximateDecorations);
            if (this._findScopeDecorationIds.length) {
                result.push(...this._findScopeDecorationIds);
            }
            if (this._rangeHighlightDecorationId) {
                result.push(this._rangeHighlightDecorationId);
            }
            return result;
        }
        static { this._CURRENT_FIND_MATCH_DECORATION = textModel_1.ModelDecorationOptions.register({
            description: 'current-find-match',
            stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */,
            zIndex: 13,
            className: 'currentFindMatch',
            inlineClassName: 'currentFindMatchInline',
            showIfCollapsed: true,
            overviewRuler: {
                color: (0, themeService_1.themeColorFromId)(colorRegistry_1.overviewRulerFindMatchForeground),
                position: model_1.OverviewRulerLane.Center
            },
            minimap: {
                color: (0, themeService_1.themeColorFromId)(colorRegistry_1.minimapFindMatch),
                position: 1 /* MinimapPosition.Inline */
            }
        }); }
        static { this._FIND_MATCH_DECORATION = textModel_1.ModelDecorationOptions.register({
            description: 'find-match',
            stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */,
            zIndex: 10,
            className: 'findMatch',
            inlineClassName: 'findMatchInline',
            showIfCollapsed: true,
            overviewRuler: {
                color: (0, themeService_1.themeColorFromId)(colorRegistry_1.overviewRulerFindMatchForeground),
                position: model_1.OverviewRulerLane.Center
            },
            minimap: {
                color: (0, themeService_1.themeColorFromId)(colorRegistry_1.minimapFindMatch),
                position: 1 /* MinimapPosition.Inline */
            }
        }); }
        static { this._FIND_MATCH_NO_OVERVIEW_DECORATION = textModel_1.ModelDecorationOptions.register({
            description: 'find-match-no-overview',
            stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */,
            className: 'findMatch',
            showIfCollapsed: true
        }); }
        static { this._FIND_MATCH_ONLY_OVERVIEW_DECORATION = textModel_1.ModelDecorationOptions.register({
            description: 'find-match-only-overview',
            stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */,
            overviewRuler: {
                color: (0, themeService_1.themeColorFromId)(colorRegistry_1.overviewRulerFindMatchForeground),
                position: model_1.OverviewRulerLane.Center
            }
        }); }
        static { this._RANGE_HIGHLIGHT_DECORATION = textModel_1.ModelDecorationOptions.register({
            description: 'find-range-highlight',
            stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */,
            className: 'rangeHighlight',
            isWholeLine: true
        }); }
        static { this._FIND_SCOPE_DECORATION = textModel_1.ModelDecorationOptions.register({
            description: 'find-scope',
            className: 'findScope',
            isWholeLine: true
        }); }
    }
    exports.FindDecorations = FindDecorations;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[220/*vs/editor/contrib/find/browser/findModel*/], __M([1/*require*/,0/*exports*/,67/*vs/base/common/arraysFind*/,14/*vs/base/common/async*/,2/*vs/base/common/lifecycle*/,146/*vs/editor/common/commands/replaceCommand*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/,23/*vs/editor/common/core/selection*/,202/*vs/editor/common/model/textModelSearch*/,823/*vs/editor/contrib/find/browser/findDecorations*/,611/*vs/editor/contrib/find/browser/replaceAllCommand*/,612/*vs/editor/contrib/find/browser/replacePattern*/,12/*vs/platform/contextkey/common/contextkey*/]), function (require, exports, arraysFind_1, async_1, lifecycle_1, replaceCommand_1, position_1, range_1, selection_1, textModelSearch_1, findDecorations_1, replaceAllCommand_1, replacePattern_1, contextkey_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.FindModelBoundToEditorModel = exports.MATCHES_LIMIT = exports.FIND_IDS = exports.TogglePreserveCaseKeybinding = exports.ToggleSearchScopeKeybinding = exports.ToggleRegexKeybinding = exports.ToggleWholeWordKeybinding = exports.ToggleCaseSensitiveKeybinding = exports.CONTEXT_REPLACE_INPUT_FOCUSED = exports.CONTEXT_FIND_INPUT_FOCUSED = exports.CONTEXT_FIND_WIDGET_NOT_VISIBLE = exports.CONTEXT_FIND_WIDGET_VISIBLE = void 0;
    exports.CONTEXT_FIND_WIDGET_VISIBLE = new contextkey_1.RawContextKey('findWidgetVisible', false);
    exports.CONTEXT_FIND_WIDGET_NOT_VISIBLE = exports.CONTEXT_FIND_WIDGET_VISIBLE.toNegated();
    // Keep ContextKey use of 'Focussed' to not break when clauses
    exports.CONTEXT_FIND_INPUT_FOCUSED = new contextkey_1.RawContextKey('findInputFocussed', false);
    exports.CONTEXT_REPLACE_INPUT_FOCUSED = new contextkey_1.RawContextKey('replaceInputFocussed', false);
    exports.ToggleCaseSensitiveKeybinding = {
        primary: 512 /* KeyMod.Alt */ | 33 /* KeyCode.KeyC */,
        mac: { primary: 2048 /* KeyMod.CtrlCmd */ | 512 /* KeyMod.Alt */ | 33 /* KeyCode.KeyC */ }
    };
    exports.ToggleWholeWordKeybinding = {
        primary: 512 /* KeyMod.Alt */ | 53 /* KeyCode.KeyW */,
        mac: { primary: 2048 /* KeyMod.CtrlCmd */ | 512 /* KeyMod.Alt */ | 53 /* KeyCode.KeyW */ }
    };
    exports.ToggleRegexKeybinding = {
        primary: 512 /* KeyMod.Alt */ | 48 /* KeyCode.KeyR */,
        mac: { primary: 2048 /* KeyMod.CtrlCmd */ | 512 /* KeyMod.Alt */ | 48 /* KeyCode.KeyR */ }
    };
    exports.ToggleSearchScopeKeybinding = {
        primary: 512 /* KeyMod.Alt */ | 42 /* KeyCode.KeyL */,
        mac: { primary: 2048 /* KeyMod.CtrlCmd */ | 512 /* KeyMod.Alt */ | 42 /* KeyCode.KeyL */ }
    };
    exports.TogglePreserveCaseKeybinding = {
        primary: 512 /* KeyMod.Alt */ | 46 /* KeyCode.KeyP */,
        mac: { primary: 2048 /* KeyMod.CtrlCmd */ | 512 /* KeyMod.Alt */ | 46 /* KeyCode.KeyP */ }
    };
    exports.FIND_IDS = {
        StartFindAction: 'actions.find',
        StartFindWithSelection: 'actions.findWithSelection',
        StartFindWithArgs: 'editor.actions.findWithArgs',
        NextMatchFindAction: 'editor.action.nextMatchFindAction',
        PreviousMatchFindAction: 'editor.action.previousMatchFindAction',
        GoToMatchFindAction: 'editor.action.goToMatchFindAction',
        NextSelectionMatchFindAction: 'editor.action.nextSelectionMatchFindAction',
        PreviousSelectionMatchFindAction: 'editor.action.previousSelectionMatchFindAction',
        StartFindReplaceAction: 'editor.action.startFindReplaceAction',
        CloseFindWidgetCommand: 'closeFindWidget',
        ToggleCaseSensitiveCommand: 'toggleFindCaseSensitive',
        ToggleWholeWordCommand: 'toggleFindWholeWord',
        ToggleRegexCommand: 'toggleFindRegex',
        ToggleSearchScopeCommand: 'toggleFindInSelection',
        TogglePreserveCaseCommand: 'togglePreserveCase',
        ReplaceOneAction: 'editor.action.replaceOne',
        ReplaceAllAction: 'editor.action.replaceAll',
        SelectAllMatchesAction: 'editor.action.selectAllMatches'
    };
    exports.MATCHES_LIMIT = 19999;
    const RESEARCH_DELAY = 240;
    class FindModelBoundToEditorModel {
        constructor(editor, state) {
            this._toDispose = new lifecycle_1.DisposableStore();
            this._editor = editor;
            this._state = state;
            this._isDisposed = false;
            this._startSearchingTimer = new async_1.TimeoutTimer();
            this._decorations = new findDecorations_1.FindDecorations(editor);
            this._toDispose.add(this._decorations);
            this._updateDecorationsScheduler = new async_1.RunOnceScheduler(() => {
                if (!this._editor.hasModel()) {
                    return;
                }
                return this.research(false);
            }, 100);
            this._toDispose.add(this._updateDecorationsScheduler);
            this._toDispose.add(this._editor.onDidChangeCursorPosition((e) => {
                if (e.reason === 3 /* CursorChangeReason.Explicit */
                    || e.reason === 5 /* CursorChangeReason.Undo */
                    || e.reason === 6 /* CursorChangeReason.Redo */) {
                    this._decorations.setStartPosition(this._editor.getPosition());
                }
            }));
            this._ignoreModelContentChanged = false;
            this._toDispose.add(this._editor.onDidChangeModelContent((e) => {
                if (this._ignoreModelContentChanged) {
                    return;
                }
                if (e.isFlush) {
                    // a model.setValue() was called
                    this._decorations.reset();
                }
                this._decorations.setStartPosition(this._editor.getPosition());
                this._updateDecorationsScheduler.schedule();
            }));
            this._toDispose.add(this._state.onFindReplaceStateChange((e) => this._onStateChanged(e)));
            this.research(false, this._state.searchScope);
        }
        dispose() {
            this._isDisposed = true;
            (0, lifecycle_1.dispose)(this._startSearchingTimer);
            this._toDispose.dispose();
        }
        _onStateChanged(e) {
            if (this._isDisposed) {
                // The find model is disposed during a find state changed event
                return;
            }
            if (!this._editor.hasModel()) {
                // The find model will be disposed momentarily
                return;
            }
            if (e.searchString || e.isReplaceRevealed || e.isRegex || e.wholeWord || e.matchCase || e.searchScope) {
                const model = this._editor.getModel();
                if (model.isTooLargeForSyncing()) {
                    this._startSearchingTimer.cancel();
                    this._startSearchingTimer.setIfNotSet(() => {
                        if (e.searchScope) {
                            this.research(e.moveCursor, this._state.searchScope);
                        }
                        else {
                            this.research(e.moveCursor);
                        }
                    }, RESEARCH_DELAY);
                }
                else {
                    if (e.searchScope) {
                        this.research(e.moveCursor, this._state.searchScope);
                    }
                    else {
                        this.research(e.moveCursor);
                    }
                }
            }
        }
        static _getSearchRange(model, findScope) {
            // If we have set now or before a find scope, use it for computing the search range
            if (findScope) {
                return findScope;
            }
            return model.getFullModelRange();
        }
        research(moveCursor, newFindScope) {
            let findScopes = null;
            if (typeof newFindScope !== 'undefined') {
                if (newFindScope !== null) {
                    if (!Array.isArray(newFindScope)) {
                        findScopes = [newFindScope];
                    }
                    else {
                        findScopes = newFindScope;
                    }
                }
            }
            else {
                findScopes = this._decorations.getFindScopes();
            }
            if (findScopes !== null) {
                findScopes = findScopes.map(findScope => {
                    if (findScope.startLineNumber !== findScope.endLineNumber) {
                        let endLineNumber = findScope.endLineNumber;
                        if (findScope.endColumn === 1) {
                            endLineNumber = endLineNumber - 1;
                        }
                        return new range_1.Range(findScope.startLineNumber, 1, endLineNumber, this._editor.getModel().getLineMaxColumn(endLineNumber));
                    }
                    return findScope;
                });
            }
            const findMatches = this._findMatches(findScopes, false, exports.MATCHES_LIMIT);
            this._decorations.set(findMatches, findScopes);
            const editorSelection = this._editor.getSelection();
            let currentMatchesPosition = this._decorations.getCurrentMatchesPosition(editorSelection);
            if (currentMatchesPosition === 0 && findMatches.length > 0) {
                // current selection is not on top of a match
                // try to find its nearest result from the top of the document
                const matchAfterSelection = (0, arraysFind_1.findFirstIdxMonotonousOrArrLen)(findMatches.map(match => match.range), range => range_1.Range.compareRangesUsingStarts(range, editorSelection) >= 0);
                currentMatchesPosition = matchAfterSelection > 0 ? matchAfterSelection - 1 + 1 /** match position is one based */ : currentMatchesPosition;
            }
            this._state.changeMatchInfo(currentMatchesPosition, this._decorations.getCount(), undefined);
            if (moveCursor && this._editor.getOption(41 /* EditorOption.find */).cursorMoveOnType) {
                this._moveToNextMatch(this._decorations.getStartPosition());
            }
        }
        _hasMatches() {
            return (this._state.matchesCount > 0);
        }
        _cannotFind() {
            if (!this._hasMatches()) {
                const findScope = this._decorations.getFindScope();
                if (findScope) {
                    // Reveal the selection so user is reminded that 'selection find' is on.
                    this._editor.revealRangeInCenterIfOutsideViewport(findScope, 0 /* ScrollType.Smooth */);
                }
                return true;
            }
            return false;
        }
        _setCurrentFindMatch(match) {
            const matchesPosition = this._decorations.setCurrentFindMatch(match);
            this._state.changeMatchInfo(matchesPosition, this._decorations.getCount(), match);
            this._editor.setSelection(match);
            this._editor.revealRangeInCenterIfOutsideViewport(match, 0 /* ScrollType.Smooth */);
        }
        _prevSearchPosition(before) {
            const isUsingLineStops = this._state.isRegex && (this._state.searchString.indexOf('^') >= 0
                || this._state.searchString.indexOf('$') >= 0);
            let { lineNumber, column } = before;
            const model = this._editor.getModel();
            if (isUsingLineStops || column === 1) {
                if (lineNumber === 1) {
                    lineNumber = model.getLineCount();
                }
                else {
                    lineNumber--;
                }
                column = model.getLineMaxColumn(lineNumber);
            }
            else {
                column--;
            }
            return new position_1.Position(lineNumber, column);
        }
        _moveToPrevMatch(before, isRecursed = false) {
            if (!this._state.canNavigateBack()) {
                // we are beyond the first matched find result
                // instead of doing nothing, we should refocus the first item
                const nextMatchRange = this._decorations.matchAfterPosition(before);
                if (nextMatchRange) {
                    this._setCurrentFindMatch(nextMatchRange);
                }
                return;
            }
            if (this._decorations.getCount() < exports.MATCHES_LIMIT) {
                let prevMatchRange = this._decorations.matchBeforePosition(before);
                if (prevMatchRange && prevMatchRange.isEmpty() && prevMatchRange.getStartPosition().equals(before)) {
                    before = this._prevSearchPosition(before);
                    prevMatchRange = this._decorations.matchBeforePosition(before);
                }
                if (prevMatchRange) {
                    this._setCurrentFindMatch(prevMatchRange);
                }
                return;
            }
            if (this._cannotFind()) {
                return;
            }
            const findScope = this._decorations.getFindScope();
            const searchRange = FindModelBoundToEditorModel._getSearchRange(this._editor.getModel(), findScope);
            // ...(----)...|...
            if (searchRange.getEndPosition().isBefore(before)) {
                before = searchRange.getEndPosition();
            }
            // ...|...(----)...
            if (before.isBefore(searchRange.getStartPosition())) {
                before = searchRange.getEndPosition();
            }
            const { lineNumber, column } = before;
            const model = this._editor.getModel();
            let position = new position_1.Position(lineNumber, column);
            let prevMatch = model.findPreviousMatch(this._state.searchString, position, this._state.isRegex, this._state.matchCase, this._state.wholeWord ? this._editor.getOption(132 /* EditorOption.wordSeparators */) : null, false);
            if (prevMatch && prevMatch.range.isEmpty() && prevMatch.range.getStartPosition().equals(position)) {
                // Looks like we're stuck at this position, unacceptable!
                position = this._prevSearchPosition(position);
                prevMatch = model.findPreviousMatch(this._state.searchString, position, this._state.isRegex, this._state.matchCase, this._state.wholeWord ? this._editor.getOption(132 /* EditorOption.wordSeparators */) : null, false);
            }
            if (!prevMatch) {
                // there is precisely one match and selection is on top of it
                return;
            }
            if (!isRecursed && !searchRange.containsRange(prevMatch.range)) {
                return this._moveToPrevMatch(prevMatch.range.getStartPosition(), true);
            }
            this._setCurrentFindMatch(prevMatch.range);
        }
        moveToPrevMatch() {
            this._moveToPrevMatch(this._editor.getSelection().getStartPosition());
        }
        _nextSearchPosition(after) {
            const isUsingLineStops = this._state.isRegex && (this._state.searchString.indexOf('^') >= 0
                || this._state.searchString.indexOf('$') >= 0);
            let { lineNumber, column } = after;
            const model = this._editor.getModel();
            if (isUsingLineStops || column === model.getLineMaxColumn(lineNumber)) {
                if (lineNumber === model.getLineCount()) {
                    lineNumber = 1;
                }
                else {
                    lineNumber++;
                }
                column = 1;
            }
            else {
                column++;
            }
            return new position_1.Position(lineNumber, column);
        }
        _moveToNextMatch(after) {
            if (!this._state.canNavigateForward()) {
                // we are beyond the last matched find result
                // instead of doing nothing, we should refocus the last item
                const prevMatchRange = this._decorations.matchBeforePosition(after);
                if (prevMatchRange) {
                    this._setCurrentFindMatch(prevMatchRange);
                }
                return;
            }
            if (this._decorations.getCount() < exports.MATCHES_LIMIT) {
                let nextMatchRange = this._decorations.matchAfterPosition(after);
                if (nextMatchRange && nextMatchRange.isEmpty() && nextMatchRange.getStartPosition().equals(after)) {
                    // Looks like we're stuck at this position, unacceptable!
                    after = this._nextSearchPosition(after);
                    nextMatchRange = this._decorations.matchAfterPosition(after);
                }
                if (nextMatchRange) {
                    this._setCurrentFindMatch(nextMatchRange);
                }
                return;
            }
            const nextMatch = this._getNextMatch(after, false, true);
            if (nextMatch) {
                this._setCurrentFindMatch(nextMatch.range);
            }
        }
        _getNextMatch(after, captureMatches, forceMove, isRecursed = false) {
            if (this._cannotFind()) {
                return null;
            }
            const findScope = this._decorations.getFindScope();
            const searchRange = FindModelBoundToEditorModel._getSearchRange(this._editor.getModel(), findScope);
            // ...(----)...|...
            if (searchRange.getEndPosition().isBefore(after)) {
                after = searchRange.getStartPosition();
            }
            // ...|...(----)...
            if (after.isBefore(searchRange.getStartPosition())) {
                after = searchRange.getStartPosition();
            }
            const { lineNumber, column } = after;
            const model = this._editor.getModel();
            let position = new position_1.Position(lineNumber, column);
            let nextMatch = model.findNextMatch(this._state.searchString, position, this._state.isRegex, this._state.matchCase, this._state.wholeWord ? this._editor.getOption(132 /* EditorOption.wordSeparators */) : null, captureMatches);
            if (forceMove && nextMatch && nextMatch.range.isEmpty() && nextMatch.range.getStartPosition().equals(position)) {
                // Looks like we're stuck at this position, unacceptable!
                position = this._nextSearchPosition(position);
                nextMatch = model.findNextMatch(this._state.searchString, position, this._state.isRegex, this._state.matchCase, this._state.wholeWord ? this._editor.getOption(132 /* EditorOption.wordSeparators */) : null, captureMatches);
            }
            if (!nextMatch) {
                // there is precisely one match and selection is on top of it
                return null;
            }
            if (!isRecursed && !searchRange.containsRange(nextMatch.range)) {
                return this._getNextMatch(nextMatch.range.getEndPosition(), captureMatches, forceMove, true);
            }
            return nextMatch;
        }
        moveToNextMatch() {
            this._moveToNextMatch(this._editor.getSelection().getEndPosition());
        }
        _moveToMatch(index) {
            const decorationRange = this._decorations.getDecorationRangeAt(index);
            if (decorationRange) {
                this._setCurrentFindMatch(decorationRange);
            }
        }
        moveToMatch(index) {
            this._moveToMatch(index);
        }
        _getReplacePattern() {
            if (this._state.isRegex) {
                return (0, replacePattern_1.parseReplaceString)(this._state.replaceString);
            }
            return replacePattern_1.ReplacePattern.fromStaticValue(this._state.replaceString);
        }
        replace() {
            if (!this._hasMatches()) {
                return;
            }
            const replacePattern = this._getReplacePattern();
            const selection = this._editor.getSelection();
            const nextMatch = this._getNextMatch(selection.getStartPosition(), true, false);
            if (nextMatch) {
                if (selection.equalsRange(nextMatch.range)) {
                    // selection sits on a find match => replace it!
                    const replaceString = replacePattern.buildReplaceString(nextMatch.matches, this._state.preserveCase);
                    const command = new replaceCommand_1.ReplaceCommand(selection, replaceString);
                    this._executeEditorCommand('replace', command);
                    this._decorations.setStartPosition(new position_1.Position(selection.startLineNumber, selection.startColumn + replaceString.length));
                    this.research(true);
                }
                else {
                    this._decorations.setStartPosition(this._editor.getPosition());
                    this._setCurrentFindMatch(nextMatch.range);
                }
            }
        }
        _findMatches(findScopes, captureMatches, limitResultCount) {
            const searchRanges = (findScopes || [null]).map((scope) => FindModelBoundToEditorModel._getSearchRange(this._editor.getModel(), scope));
            return this._editor.getModel().findMatches(this._state.searchString, searchRanges, this._state.isRegex, this._state.matchCase, this._state.wholeWord ? this._editor.getOption(132 /* EditorOption.wordSeparators */) : null, captureMatches, limitResultCount);
        }
        replaceAll() {
            if (!this._hasMatches()) {
                return;
            }
            const findScopes = this._decorations.getFindScopes();
            if (findScopes === null && this._state.matchesCount >= exports.MATCHES_LIMIT) {
                // Doing a replace on the entire file that is over ${MATCHES_LIMIT} matches
                this._largeReplaceAll();
            }
            else {
                this._regularReplaceAll(findScopes);
            }
            this.research(false);
        }
        _largeReplaceAll() {
            const searchParams = new textModelSearch_1.SearchParams(this._state.searchString, this._state.isRegex, this._state.matchCase, this._state.wholeWord ? this._editor.getOption(132 /* EditorOption.wordSeparators */) : null);
            const searchData = searchParams.parseSearchRequest();
            if (!searchData) {
                return;
            }
            let searchRegex = searchData.regex;
            if (!searchRegex.multiline) {
                let mod = 'mu';
                if (searchRegex.ignoreCase) {
                    mod += 'i';
                }
                if (searchRegex.global) {
                    mod += 'g';
                }
                searchRegex = new RegExp(searchRegex.source, mod);
            }
            const model = this._editor.getModel();
            const modelText = model.getValue(1 /* EndOfLinePreference.LF */);
            const fullModelRange = model.getFullModelRange();
            const replacePattern = this._getReplacePattern();
            let resultText;
            const preserveCase = this._state.preserveCase;
            if (replacePattern.hasReplacementPatterns || preserveCase) {
                resultText = modelText.replace(searchRegex, function () {
                    return replacePattern.buildReplaceString(arguments, preserveCase);
                });
            }
            else {
                resultText = modelText.replace(searchRegex, replacePattern.buildReplaceString(null, preserveCase));
            }
            const command = new replaceCommand_1.ReplaceCommandThatPreservesSelection(fullModelRange, resultText, this._editor.getSelection());
            this._executeEditorCommand('replaceAll', command);
        }
        _regularReplaceAll(findScopes) {
            const replacePattern = this._getReplacePattern();
            // Get all the ranges (even more than the highlighted ones)
            const matches = this._findMatches(findScopes, replacePattern.hasReplacementPatterns || this._state.preserveCase, 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */);
            const replaceStrings = [];
            for (let i = 0, len = matches.length; i < len; i++) {
                replaceStrings[i] = replacePattern.buildReplaceString(matches[i].matches, this._state.preserveCase);
            }
            const command = new replaceAllCommand_1.ReplaceAllCommand(this._editor.getSelection(), matches.map(m => m.range), replaceStrings);
            this._executeEditorCommand('replaceAll', command);
        }
        selectAllMatches() {
            if (!this._hasMatches()) {
                return;
            }
            const findScopes = this._decorations.getFindScopes();
            // Get all the ranges (even more than the highlighted ones)
            const matches = this._findMatches(findScopes, false, 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */);
            let selections = matches.map(m => new selection_1.Selection(m.range.startLineNumber, m.range.startColumn, m.range.endLineNumber, m.range.endColumn));
            // If one of the ranges is the editor selection, then maintain it as primary
            const editorSelection = this._editor.getSelection();
            for (let i = 0, len = selections.length; i < len; i++) {
                const sel = selections[i];
                if (sel.equalsRange(editorSelection)) {
                    selections = [editorSelection].concat(selections.slice(0, i)).concat(selections.slice(i + 1));
                    break;
                }
            }
            this._editor.setSelections(selections);
        }
        _executeEditorCommand(source, command) {
            try {
                this._ignoreModelContentChanged = true;
                this._editor.pushUndoStop();
                this._editor.executeCommand(source, command);
                this._editor.pushUndoStop();
            }
            finally {
                this._ignoreModelContentChanged = false;
            }
        }
    }
    exports.FindModelBoundToEditorModel = FindModelBoundToEditorModel;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[824/*vs/editor/contrib/find/browser/findOptionsWidget*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,358/*vs/base/browser/ui/findinput/findInputToggles*/,85/*vs/base/browser/ui/widget*/,14/*vs/base/common/async*/,220/*vs/editor/contrib/find/browser/findModel*/,32/*vs/platform/theme/common/colorRegistry*/,44/*vs/base/browser/ui/hover/hoverDelegateFactory*/,509/*vs/css!vs/editor/contrib/find/browser/findOptionsWidget*/]), function (require, exports, dom, findInputToggles_1, widget_1, async_1, findModel_1, colorRegistry_1, hoverDelegateFactory_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.FindOptionsWidget = void 0;
    class FindOptionsWidget extends widget_1.Widget {
        static { this.ID = 'editor.contrib.findOptionsWidget'; }
        constructor(editor, state, keybindingService) {
            super();
            this._hideSoon = this._register(new async_1.RunOnceScheduler(() => this._hide(), 2000));
            this._isVisible = false;
            this._editor = editor;
            this._state = state;
            this._keybindingService = keybindingService;
            this._domNode = document.createElement('div');
            this._domNode.className = 'findOptionsWidget';
            this._domNode.style.display = 'none';
            this._domNode.style.top = '10px';
            this._domNode.style.zIndex = '12';
            this._domNode.setAttribute('role', 'presentation');
            this._domNode.setAttribute('aria-hidden', 'true');
            const toggleStyles = {
                inputActiveOptionBorder: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.inputActiveOptionBorder),
                inputActiveOptionForeground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.inputActiveOptionForeground),
                inputActiveOptionBackground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.inputActiveOptionBackground),
            };
            const hoverDelegate = this._register((0, hoverDelegateFactory_1.createInstantHoverDelegate)());
            this.caseSensitive = this._register(new findInputToggles_1.CaseSensitiveToggle({
                appendTitle: this._keybindingLabelFor(findModel_1.FIND_IDS.ToggleCaseSensitiveCommand),
                isChecked: this._state.matchCase,
                hoverDelegate,
                ...toggleStyles
            }));
            this._domNode.appendChild(this.caseSensitive.domNode);
            this._register(this.caseSensitive.onChange(() => {
                this._state.change({
                    matchCase: this.caseSensitive.checked
                }, false);
            }));
            this.wholeWords = this._register(new findInputToggles_1.WholeWordsToggle({
                appendTitle: this._keybindingLabelFor(findModel_1.FIND_IDS.ToggleWholeWordCommand),
                isChecked: this._state.wholeWord,
                hoverDelegate,
                ...toggleStyles
            }));
            this._domNode.appendChild(this.wholeWords.domNode);
            this._register(this.wholeWords.onChange(() => {
                this._state.change({
                    wholeWord: this.wholeWords.checked
                }, false);
            }));
            this.regex = this._register(new findInputToggles_1.RegexToggle({
                appendTitle: this._keybindingLabelFor(findModel_1.FIND_IDS.ToggleRegexCommand),
                isChecked: this._state.isRegex,
                hoverDelegate,
                ...toggleStyles
            }));
            this._domNode.appendChild(this.regex.domNode);
            this._register(this.regex.onChange(() => {
                this._state.change({
                    isRegex: this.regex.checked
                }, false);
            }));
            this._editor.addOverlayWidget(this);
            this._register(this._state.onFindReplaceStateChange((e) => {
                let somethingChanged = false;
                if (e.isRegex) {
                    this.regex.checked = this._state.isRegex;
                    somethingChanged = true;
                }
                if (e.wholeWord) {
                    this.wholeWords.checked = this._state.wholeWord;
                    somethingChanged = true;
                }
                if (e.matchCase) {
                    this.caseSensitive.checked = this._state.matchCase;
                    somethingChanged = true;
                }
                if (!this._state.isRevealed && somethingChanged) {
                    this._revealTemporarily();
                }
            }));
            this._register(dom.addDisposableListener(this._domNode, dom.EventType.MOUSE_LEAVE, (e) => this._onMouseLeave()));
            this._register(dom.addDisposableListener(this._domNode, 'mouseover', (e) => this._onMouseOver()));
        }
        _keybindingLabelFor(actionId) {
            const kb = this._keybindingService.lookupKeybinding(actionId);
            if (!kb) {
                return '';
            }
            return ` (${kb.getLabel()})`;
        }
        dispose() {
            this._editor.removeOverlayWidget(this);
            super.dispose();
        }
        // ----- IOverlayWidget API
        getId() {
            return FindOptionsWidget.ID;
        }
        getDomNode() {
            return this._domNode;
        }
        getPosition() {
            return {
                preference: 0 /* OverlayWidgetPositionPreference.TOP_RIGHT_CORNER */
            };
        }
        highlightFindOptions() {
            this._revealTemporarily();
        }
        _revealTemporarily() {
            this._show();
            this._hideSoon.schedule();
        }
        _onMouseLeave() {
            this._hideSoon.schedule();
        }
        _onMouseOver() {
            this._hideSoon.cancel();
        }
        _show() {
            if (this._isVisible) {
                return;
            }
            this._isVisible = true;
            this._domNode.style.display = 'block';
        }
        _hide() {
            if (!this._isVisible) {
                return;
            }
            this._isVisible = false;
            this._domNode.style.display = 'none';
        }
    }
    exports.FindOptionsWidget = FindOptionsWidget;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[825/*vs/editor/contrib/find/browser/findState*/], __M([1/*require*/,0/*exports*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,4/*vs/editor/common/core/range*/,220/*vs/editor/contrib/find/browser/findModel*/]), function (require, exports, event_1, lifecycle_1, range_1, findModel_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.FindReplaceState = void 0;
    function effectiveOptionValue(override, value) {
        if (override === 1 /* FindOptionOverride.True */) {
            return true;
        }
        if (override === 2 /* FindOptionOverride.False */) {
            return false;
        }
        return value;
    }
    class FindReplaceState extends lifecycle_1.Disposable {
        get searchString() { return this._searchString; }
        get replaceString() { return this._replaceString; }
        get isRevealed() { return this._isRevealed; }
        get isReplaceRevealed() { return this._isReplaceRevealed; }
        get isRegex() { return effectiveOptionValue(this._isRegexOverride, this._isRegex); }
        get wholeWord() { return effectiveOptionValue(this._wholeWordOverride, this._wholeWord); }
        get matchCase() { return effectiveOptionValue(this._matchCaseOverride, this._matchCase); }
        get preserveCase() { return effectiveOptionValue(this._preserveCaseOverride, this._preserveCase); }
        get actualIsRegex() { return this._isRegex; }
        get actualWholeWord() { return this._wholeWord; }
        get actualMatchCase() { return this._matchCase; }
        get actualPreserveCase() { return this._preserveCase; }
        get searchScope() { return this._searchScope; }
        get matchesPosition() { return this._matchesPosition; }
        get matchesCount() { return this._matchesCount; }
        get currentMatch() { return this._currentMatch; }
        constructor() {
            super();
            this._onFindReplaceStateChange = this._register(new event_1.Emitter());
            this.onFindReplaceStateChange = this._onFindReplaceStateChange.event;
            this._searchString = '';
            this._replaceString = '';
            this._isRevealed = false;
            this._isReplaceRevealed = false;
            this._isRegex = false;
            this._isRegexOverride = 0 /* FindOptionOverride.NotSet */;
            this._wholeWord = false;
            this._wholeWordOverride = 0 /* FindOptionOverride.NotSet */;
            this._matchCase = false;
            this._matchCaseOverride = 0 /* FindOptionOverride.NotSet */;
            this._preserveCase = false;
            this._preserveCaseOverride = 0 /* FindOptionOverride.NotSet */;
            this._searchScope = null;
            this._matchesPosition = 0;
            this._matchesCount = 0;
            this._currentMatch = null;
            this._loop = true;
            this._isSearching = false;
            this._filters = null;
        }
        changeMatchInfo(matchesPosition, matchesCount, currentMatch) {
            const changeEvent = {
                moveCursor: false,
                updateHistory: false,
                searchString: false,
                replaceString: false,
                isRevealed: false,
                isReplaceRevealed: false,
                isRegex: false,
                wholeWord: false,
                matchCase: false,
                preserveCase: false,
                searchScope: false,
                matchesPosition: false,
                matchesCount: false,
                currentMatch: false,
                loop: false,
                isSearching: false,
                filters: false
            };
            let somethingChanged = false;
            if (matchesCount === 0) {
                matchesPosition = 0;
            }
            if (matchesPosition > matchesCount) {
                matchesPosition = matchesCount;
            }
            if (this._matchesPosition !== matchesPosition) {
                this._matchesPosition = matchesPosition;
                changeEvent.matchesPosition = true;
                somethingChanged = true;
            }
            if (this._matchesCount !== matchesCount) {
                this._matchesCount = matchesCount;
                changeEvent.matchesCount = true;
                somethingChanged = true;
            }
            if (typeof currentMatch !== 'undefined') {
                if (!range_1.Range.equalsRange(this._currentMatch, currentMatch)) {
                    this._currentMatch = currentMatch;
                    changeEvent.currentMatch = true;
                    somethingChanged = true;
                }
            }
            if (somethingChanged) {
                this._onFindReplaceStateChange.fire(changeEvent);
            }
        }
        change(newState, moveCursor, updateHistory = true) {
            const changeEvent = {
                moveCursor: moveCursor,
                updateHistory: updateHistory,
                searchString: false,
                replaceString: false,
                isRevealed: false,
                isReplaceRevealed: false,
                isRegex: false,
                wholeWord: false,
                matchCase: false,
                preserveCase: false,
                searchScope: false,
                matchesPosition: false,
                matchesCount: false,
                currentMatch: false,
                loop: false,
                isSearching: false,
                filters: false
            };
            let somethingChanged = false;
            const oldEffectiveIsRegex = this.isRegex;
            const oldEffectiveWholeWords = this.wholeWord;
            const oldEffectiveMatchCase = this.matchCase;
            const oldEffectivePreserveCase = this.preserveCase;
            if (typeof newState.searchString !== 'undefined') {
                if (this._searchString !== newState.searchString) {
                    this._searchString = newState.searchString;
                    changeEvent.searchString = true;
                    somethingChanged = true;
                }
            }
            if (typeof newState.replaceString !== 'undefined') {
                if (this._replaceString !== newState.replaceString) {
                    this._replaceString = newState.replaceString;
                    changeEvent.replaceString = true;
                    somethingChanged = true;
                }
            }
            if (typeof newState.isRevealed !== 'undefined') {
                if (this._isRevealed !== newState.isRevealed) {
                    this._isRevealed = newState.isRevealed;
                    changeEvent.isRevealed = true;
                    somethingChanged = true;
                }
            }
            if (typeof newState.isReplaceRevealed !== 'undefined') {
                if (this._isReplaceRevealed !== newState.isReplaceRevealed) {
                    this._isReplaceRevealed = newState.isReplaceRevealed;
                    changeEvent.isReplaceRevealed = true;
                    somethingChanged = true;
                }
            }
            if (typeof newState.isRegex !== 'undefined') {
                this._isRegex = newState.isRegex;
            }
            if (typeof newState.wholeWord !== 'undefined') {
                this._wholeWord = newState.wholeWord;
            }
            if (typeof newState.matchCase !== 'undefined') {
                this._matchCase = newState.matchCase;
            }
            if (typeof newState.preserveCase !== 'undefined') {
                this._preserveCase = newState.preserveCase;
            }
            if (typeof newState.searchScope !== 'undefined') {
                if (!newState.searchScope?.every((newSearchScope) => {
                    return this._searchScope?.some(existingSearchScope => {
                        return !range_1.Range.equalsRange(existingSearchScope, newSearchScope);
                    });
                })) {
                    this._searchScope = newState.searchScope;
                    changeEvent.searchScope = true;
                    somethingChanged = true;
                }
            }
            if (typeof newState.loop !== 'undefined') {
                if (this._loop !== newState.loop) {
                    this._loop = newState.loop;
                    changeEvent.loop = true;
                    somethingChanged = true;
                }
            }
            if (typeof newState.isSearching !== 'undefined') {
                if (this._isSearching !== newState.isSearching) {
                    this._isSearching = newState.isSearching;
                    changeEvent.isSearching = true;
                    somethingChanged = true;
                }
            }
            if (typeof newState.filters !== 'undefined') {
                if (this._filters) {
                    this._filters.update(newState.filters);
                }
                else {
                    this._filters = newState.filters;
                }
                changeEvent.filters = true;
                somethingChanged = true;
            }
            // Overrides get set when they explicitly come in and get reset anytime something else changes
            this._isRegexOverride = (typeof newState.isRegexOverride !== 'undefined' ? newState.isRegexOverride : 0 /* FindOptionOverride.NotSet */);
            this._wholeWordOverride = (typeof newState.wholeWordOverride !== 'undefined' ? newState.wholeWordOverride : 0 /* FindOptionOverride.NotSet */);
            this._matchCaseOverride = (typeof newState.matchCaseOverride !== 'undefined' ? newState.matchCaseOverride : 0 /* FindOptionOverride.NotSet */);
            this._preserveCaseOverride = (typeof newState.preserveCaseOverride !== 'undefined' ? newState.preserveCaseOverride : 0 /* FindOptionOverride.NotSet */);
            if (oldEffectiveIsRegex !== this.isRegex) {
                somethingChanged = true;
                changeEvent.isRegex = true;
            }
            if (oldEffectiveWholeWords !== this.wholeWord) {
                somethingChanged = true;
                changeEvent.wholeWord = true;
            }
            if (oldEffectiveMatchCase !== this.matchCase) {
                somethingChanged = true;
                changeEvent.matchCase = true;
            }
            if (oldEffectivePreserveCase !== this.preserveCase) {
                somethingChanged = true;
                changeEvent.preserveCase = true;
            }
            if (somethingChanged) {
                this._onFindReplaceStateChange.fire(changeEvent);
            }
        }
        canNavigateBack() {
            return this.canNavigateInLoop() || (this.matchesPosition !== 1);
        }
        canNavigateForward() {
            return this.canNavigateInLoop() || (this.matchesPosition < this.matchesCount);
        }
        canNavigateInLoop() {
            return this._loop || (this.matchesCount >= findModel_1.MATCHES_LIMIT);
        }
    }
    exports.FindReplaceState = FindReplaceState;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[826/*vs/editor/contrib/find/browser/findWidget*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,46/*vs/base/browser/ui/aria/aria*/,175/*vs/base/browser/ui/toggle/toggle*/,173/*vs/base/browser/ui/sash/sash*/,85/*vs/base/browser/ui/widget*/,14/*vs/base/common/async*/,26/*vs/base/common/codicons*/,8/*vs/base/common/errors*/,2/*vs/base/common/lifecycle*/,16/*vs/base/common/platform*/,11/*vs/base/common/strings*/,4/*vs/editor/common/core/range*/,220/*vs/editor/contrib/find/browser/findModel*/,3/*vs/nls*/,404/*vs/platform/history/browser/contextScopedHistoryWidget*/,675/*vs/platform/history/browser/historyWidgetKeybindingHint*/,32/*vs/platform/theme/common/colorRegistry*/,71/*vs/platform/theme/common/iconRegistry*/,25/*vs/platform/theme/common/themeService*/,30/*vs/base/common/themables*/,97/*vs/platform/theme/common/theme*/,19/*vs/base/common/types*/,110/*vs/platform/theme/browser/defaultStyles*/,44/*vs/base/browser/ui/hover/hoverDelegateFactory*/,510/*vs/css!vs/editor/contrib/find/browser/findWidget*/]), function (require, exports, dom, aria_1, toggle_1, sash_1, widget_1, async_1, codicons_1, errors_1, lifecycle_1, platform, strings, range_1, findModel_1, nls, contextScopedHistoryWidget_1, historyWidgetKeybindingHint_1, colorRegistry_1, iconRegistry_1, themeService_1, themables_1, theme_1, types_1, defaultStyles_1, hoverDelegateFactory_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SimpleButton = exports.FindWidget = exports.FindWidgetViewZone = exports.NLS_NO_RESULTS = exports.NLS_MATCHES_LOCATION = exports.findNextMatchIcon = exports.findPreviousMatchIcon = exports.findReplaceAllIcon = exports.findReplaceIcon = exports.findSelectionIcon = void 0;
    const findCollapsedIcon = (0, iconRegistry_1.registerIcon)('find-collapsed', codicons_1.Codicon.chevronRight, nls.localize(864, 'Icon to indicate that the editor find widget is collapsed.'));
    const findExpandedIcon = (0, iconRegistry_1.registerIcon)('find-expanded', codicons_1.Codicon.chevronDown, nls.localize(865, 'Icon to indicate that the editor find widget is expanded.'));
    exports.findSelectionIcon = (0, iconRegistry_1.registerIcon)('find-selection', codicons_1.Codicon.selection, nls.localize(866, 'Icon for \'Find in Selection\' in the editor find widget.'));
    exports.findReplaceIcon = (0, iconRegistry_1.registerIcon)('find-replace', codicons_1.Codicon.replace, nls.localize(867, 'Icon for \'Replace\' in the editor find widget.'));
    exports.findReplaceAllIcon = (0, iconRegistry_1.registerIcon)('find-replace-all', codicons_1.Codicon.replaceAll, nls.localize(868, 'Icon for \'Replace All\' in the editor find widget.'));
    exports.findPreviousMatchIcon = (0, iconRegistry_1.registerIcon)('find-previous-match', codicons_1.Codicon.arrowUp, nls.localize(869, 'Icon for \'Find Previous\' in the editor find widget.'));
    exports.findNextMatchIcon = (0, iconRegistry_1.registerIcon)('find-next-match', codicons_1.Codicon.arrowDown, nls.localize(870, 'Icon for \'Find Next\' in the editor find widget.'));
    const NLS_FIND_DIALOG_LABEL = nls.localize(871, "Find / Replace");
    const NLS_FIND_INPUT_LABEL = nls.localize(872, "Find");
    const NLS_FIND_INPUT_PLACEHOLDER = nls.localize(873, "Find");
    const NLS_PREVIOUS_MATCH_BTN_LABEL = nls.localize(874, "Previous Match");
    const NLS_NEXT_MATCH_BTN_LABEL = nls.localize(875, "Next Match");
    const NLS_TOGGLE_SELECTION_FIND_TITLE = nls.localize(876, "Find in Selection");
    const NLS_CLOSE_BTN_LABEL = nls.localize(877, "Close");
    const NLS_REPLACE_INPUT_LABEL = nls.localize(878, "Replace");
    const NLS_REPLACE_INPUT_PLACEHOLDER = nls.localize(879, "Replace");
    const NLS_REPLACE_BTN_LABEL = nls.localize(880, "Replace");
    const NLS_REPLACE_ALL_BTN_LABEL = nls.localize(881, "Replace All");
    const NLS_TOGGLE_REPLACE_MODE_BTN_LABEL = nls.localize(882, "Toggle Replace");
    const NLS_MATCHES_COUNT_LIMIT_TITLE = nls.localize(883, "Only the first {0} results are highlighted, but all find operations work on the entire text.", findModel_1.MATCHES_LIMIT);
    exports.NLS_MATCHES_LOCATION = nls.localize(884, "{0} of {1}");
    exports.NLS_NO_RESULTS = nls.localize(885, "No results");
    const FIND_WIDGET_INITIAL_WIDTH = 419;
    const PART_WIDTH = 275;
    const FIND_INPUT_AREA_WIDTH = PART_WIDTH - 54;
    let MAX_MATCHES_COUNT_WIDTH = 69;
    // let FIND_ALL_CONTROLS_WIDTH = 17/** Find Input margin-left */ + (MAX_MATCHES_COUNT_WIDTH + 3 + 1) /** Match Results */ + 23 /** Button */ * 4 + 2/** sash */;
    const FIND_INPUT_AREA_HEIGHT = 33; // The height of Find Widget when Replace Input is not visible.
    const ctrlEnterReplaceAllWarningPromptedKey = 'ctrlEnterReplaceAll.windows.donotask';
    const ctrlKeyMod = (platform.isMacintosh ? 256 /* KeyMod.WinCtrl */ : 2048 /* KeyMod.CtrlCmd */);
    class FindWidgetViewZone {
        constructor(afterLineNumber) {
            this.afterLineNumber = afterLineNumber;
            this.heightInPx = FIND_INPUT_AREA_HEIGHT;
            this.suppressMouseDown = false;
            this.domNode = document.createElement('div');
            this.domNode.className = 'dock-find-viewzone';
        }
    }
    exports.FindWidgetViewZone = FindWidgetViewZone;
    function stopPropagationForMultiLineUpwards(event, value, textarea) {
        const isMultiline = !!value.match(/\n/);
        if (textarea && isMultiline && textarea.selectionStart > 0) {
            event.stopPropagation();
            return;
        }
    }
    function stopPropagationForMultiLineDownwards(event, value, textarea) {
        const isMultiline = !!value.match(/\n/);
        if (textarea && isMultiline && textarea.selectionEnd < textarea.value.length) {
            event.stopPropagation();
            return;
        }
    }
    class FindWidget extends widget_1.Widget {
        static { this.ID = 'editor.contrib.findWidget'; }
        constructor(codeEditor, controller, state, contextViewProvider, keybindingService, contextKeyService, themeService, storageService, notificationService, _hoverService) {
            super();
            this._hoverService = _hoverService;
            this._cachedHeight = null;
            this._revealTimeouts = [];
            this._codeEditor = codeEditor;
            this._controller = controller;
            this._state = state;
            this._contextViewProvider = contextViewProvider;
            this._keybindingService = keybindingService;
            this._contextKeyService = contextKeyService;
            this._storageService = storageService;
            this._notificationService = notificationService;
            this._ctrlEnterReplaceAllWarningPrompted = !!storageService.getBoolean(ctrlEnterReplaceAllWarningPromptedKey, 0 /* StorageScope.PROFILE */);
            this._isVisible = false;
            this._isReplaceVisible = false;
            this._ignoreChangeEvent = false;
            this._updateHistoryDelayer = new async_1.Delayer(500);
            this._register((0, lifecycle_1.toDisposable)(() => this._updateHistoryDelayer.cancel()));
            this._register(this._state.onFindReplaceStateChange((e) => this._onStateChanged(e)));
            this._buildDomNode();
            this._updateButtons();
            this._tryUpdateWidgetWidth();
            this._findInput.inputBox.layout();
            this._register(this._codeEditor.onDidChangeConfiguration((e) => {
                if (e.hasChanged(92 /* EditorOption.readOnly */)) {
                    if (this._codeEditor.getOption(92 /* EditorOption.readOnly */)) {
                        // Hide replace part if editor becomes read only
                        this._state.change({ isReplaceRevealed: false }, false);
                    }
                    this._updateButtons();
                }
                if (e.hasChanged(146 /* EditorOption.layoutInfo */)) {
                    this._tryUpdateWidgetWidth();
                }
                if (e.hasChanged(2 /* EditorOption.accessibilitySupport */)) {
                    this.updateAccessibilitySupport();
                }
                if (e.hasChanged(41 /* EditorOption.find */)) {
                    const supportLoop = this._codeEditor.getOption(41 /* EditorOption.find */).loop;
                    this._state.change({ loop: supportLoop }, false);
                    const addExtraSpaceOnTop = this._codeEditor.getOption(41 /* EditorOption.find */).addExtraSpaceOnTop;
                    if (addExtraSpaceOnTop && !this._viewZone) {
                        this._viewZone = new FindWidgetViewZone(0);
                        this._showViewZone();
                    }
                    if (!addExtraSpaceOnTop && this._viewZone) {
                        this._removeViewZone();
                    }
                }
            }));
            this.updateAccessibilitySupport();
            this._register(this._codeEditor.onDidChangeCursorSelection(() => {
                if (this._isVisible) {
                    this._updateToggleSelectionFindButton();
                }
            }));
            this._register(this._codeEditor.onDidFocusEditorWidget(async () => {
                if (this._isVisible) {
                    const globalBufferTerm = await this._controller.getGlobalBufferTerm();
                    if (globalBufferTerm && globalBufferTerm !== this._state.searchString) {
                        this._state.change({ searchString: globalBufferTerm }, false);
                        this._findInput.select();
                    }
                }
            }));
            this._findInputFocused = findModel_1.CONTEXT_FIND_INPUT_FOCUSED.bindTo(contextKeyService);
            this._findFocusTracker = this._register(dom.trackFocus(this._findInput.inputBox.inputElement));
            this._register(this._findFocusTracker.onDidFocus(() => {
                this._findInputFocused.set(true);
                this._updateSearchScope();
            }));
            this._register(this._findFocusTracker.onDidBlur(() => {
                this._findInputFocused.set(false);
            }));
            this._replaceInputFocused = findModel_1.CONTEXT_REPLACE_INPUT_FOCUSED.bindTo(contextKeyService);
            this._replaceFocusTracker = this._register(dom.trackFocus(this._replaceInput.inputBox.inputElement));
            this._register(this._replaceFocusTracker.onDidFocus(() => {
                this._replaceInputFocused.set(true);
                this._updateSearchScope();
            }));
            this._register(this._replaceFocusTracker.onDidBlur(() => {
                this._replaceInputFocused.set(false);
            }));
            this._codeEditor.addOverlayWidget(this);
            if (this._codeEditor.getOption(41 /* EditorOption.find */).addExtraSpaceOnTop) {
                this._viewZone = new FindWidgetViewZone(0); // Put it before the first line then users can scroll beyond the first line.
            }
            this._register(this._codeEditor.onDidChangeModel(() => {
                if (!this._isVisible) {
                    return;
                }
                this._viewZoneId = undefined;
            }));
            this._register(this._codeEditor.onDidScrollChange((e) => {
                if (e.scrollTopChanged) {
                    this._layoutViewZone();
                    return;
                }
                // for other scroll changes, layout the viewzone in next tick to avoid ruining current rendering.
                setTimeout(() => {
                    this._layoutViewZone();
                }, 0);
            }));
        }
        // ----- IOverlayWidget API
        getId() {
            return FindWidget.ID;
        }
        getDomNode() {
            return this._domNode;
        }
        getPosition() {
            if (this._isVisible) {
                return {
                    preference: 0 /* OverlayWidgetPositionPreference.TOP_RIGHT_CORNER */
                };
            }
            return null;
        }
        // ----- React to state changes
        _onStateChanged(e) {
            if (e.searchString) {
                try {
                    this._ignoreChangeEvent = true;
                    this._findInput.setValue(this._state.searchString);
                }
                finally {
                    this._ignoreChangeEvent = false;
                }
                this._updateButtons();
            }
            if (e.replaceString) {
                this._replaceInput.inputBox.value = this._state.replaceString;
            }
            if (e.isRevealed) {
                if (this._state.isRevealed) {
                    this._reveal();
                }
                else {
                    this._hide(true);
                }
            }
            if (e.isReplaceRevealed) {
                if (this._state.isReplaceRevealed) {
                    if (!this._codeEditor.getOption(92 /* EditorOption.readOnly */) && !this._isReplaceVisible) {
                        this._isReplaceVisible = true;
                        this._replaceInput.width = dom.getTotalWidth(this._findInput.domNode);
                        this._updateButtons();
                        this._replaceInput.inputBox.layout();
                    }
                }
                else {
                    if (this._isReplaceVisible) {
                        this._isReplaceVisible = false;
                        this._updateButtons();
                    }
                }
            }
            if ((e.isRevealed || e.isReplaceRevealed) && (this._state.isRevealed || this._state.isReplaceRevealed)) {
                if (this._tryUpdateHeight()) {
                    this._showViewZone();
                }
            }
            if (e.isRegex) {
                this._findInput.setRegex(this._state.isRegex);
            }
            if (e.wholeWord) {
                this._findInput.setWholeWords(this._state.wholeWord);
            }
            if (e.matchCase) {
                this._findInput.setCaseSensitive(this._state.matchCase);
            }
            if (e.preserveCase) {
                this._replaceInput.setPreserveCase(this._state.preserveCase);
            }
            if (e.searchScope) {
                if (this._state.searchScope) {
                    this._toggleSelectionFind.checked = true;
                }
                else {
                    this._toggleSelectionFind.checked = false;
                }
                this._updateToggleSelectionFindButton();
            }
            if (e.searchString || e.matchesCount || e.matchesPosition) {
                const showRedOutline = (this._state.searchString.length > 0 && this._state.matchesCount === 0);
                this._domNode.classList.toggle('no-results', showRedOutline);
                this._updateMatchesCount();
                this._updateButtons();
            }
            if (e.searchString || e.currentMatch) {
                this._layoutViewZone();
            }
            if (e.updateHistory) {
                this._delayedUpdateHistory();
            }
            if (e.loop) {
                this._updateButtons();
            }
        }
        _delayedUpdateHistory() {
            this._updateHistoryDelayer.trigger(this._updateHistory.bind(this)).then(undefined, errors_1.onUnexpectedError);
        }
        _updateHistory() {
            if (this._state.searchString) {
                this._findInput.inputBox.addToHistory();
            }
            if (this._state.replaceString) {
                this._replaceInput.inputBox.addToHistory();
            }
        }
        _updateMatchesCount() {
            this._matchesCount.style.minWidth = MAX_MATCHES_COUNT_WIDTH + 'px';
            if (this._state.matchesCount >= findModel_1.MATCHES_LIMIT) {
                this._matchesCount.title = NLS_MATCHES_COUNT_LIMIT_TITLE;
            }
            else {
                this._matchesCount.title = '';
            }
            // remove previous content
            this._matchesCount.firstChild?.remove();
            let label;
            if (this._state.matchesCount > 0) {
                let matchesCount = String(this._state.matchesCount);
                if (this._state.matchesCount >= findModel_1.MATCHES_LIMIT) {
                    matchesCount += '+';
                }
                let matchesPosition = String(this._state.matchesPosition);
                if (matchesPosition === '0') {
                    matchesPosition = '?';
                }
                label = strings.format(exports.NLS_MATCHES_LOCATION, matchesPosition, matchesCount);
            }
            else {
                label = exports.NLS_NO_RESULTS;
            }
            this._matchesCount.appendChild(document.createTextNode(label));
            (0, aria_1.alert)(this._getAriaLabel(label, this._state.currentMatch, this._state.searchString));
            MAX_MATCHES_COUNT_WIDTH = Math.max(MAX_MATCHES_COUNT_WIDTH, this._matchesCount.clientWidth);
        }
        // ----- actions
        _getAriaLabel(label, currentMatch, searchString) {
            if (label === exports.NLS_NO_RESULTS) {
                return searchString === ''
                    ? nls.localize(886, "{0} found", label)
                    : nls.localize(887, "{0} found for '{1}'", label, searchString);
            }
            if (currentMatch) {
                const ariaLabel = nls.localize(888, "{0} found for '{1}', at {2}", label, searchString, currentMatch.startLineNumber + ':' + currentMatch.startColumn);
                const model = this._codeEditor.getModel();
                if (model && (currentMatch.startLineNumber <= model.getLineCount()) && (currentMatch.startLineNumber >= 1)) {
                    const lineContent = model.getLineContent(currentMatch.startLineNumber);
                    return `${lineContent}, ${ariaLabel}`;
                }
                return ariaLabel;
            }
            return nls.localize(889, "{0} found for '{1}'", label, searchString);
        }
        /**
         * If 'selection find' is ON we should not disable the button (its function is to cancel 'selection find').
         * If 'selection find' is OFF we enable the button only if there is a selection.
         */
        _updateToggleSelectionFindButton() {
            const selection = this._codeEditor.getSelection();
            const isSelection = selection ? (selection.startLineNumber !== selection.endLineNumber || selection.startColumn !== selection.endColumn) : false;
            const isChecked = this._toggleSelectionFind.checked;
            if (this._isVisible && (isChecked || isSelection)) {
                this._toggleSelectionFind.enable();
            }
            else {
                this._toggleSelectionFind.disable();
            }
        }
        _updateButtons() {
            this._findInput.setEnabled(this._isVisible);
            this._replaceInput.setEnabled(this._isVisible && this._isReplaceVisible);
            this._updateToggleSelectionFindButton();
            this._closeBtn.setEnabled(this._isVisible);
            const findInputIsNonEmpty = (this._state.searchString.length > 0);
            const matchesCount = this._state.matchesCount ? true : false;
            this._prevBtn.setEnabled(this._isVisible && findInputIsNonEmpty && matchesCount && this._state.canNavigateBack());
            this._nextBtn.setEnabled(this._isVisible && findInputIsNonEmpty && matchesCount && this._state.canNavigateForward());
            this._replaceBtn.setEnabled(this._isVisible && this._isReplaceVisible && findInputIsNonEmpty);
            this._replaceAllBtn.setEnabled(this._isVisible && this._isReplaceVisible && findInputIsNonEmpty);
            this._domNode.classList.toggle('replaceToggled', this._isReplaceVisible);
            this._toggleReplaceBtn.setExpanded(this._isReplaceVisible);
            const canReplace = !this._codeEditor.getOption(92 /* EditorOption.readOnly */);
            this._toggleReplaceBtn.setEnabled(this._isVisible && canReplace);
        }
        _reveal() {
            this._revealTimeouts.forEach(e => {
                clearTimeout(e);
            });
            this._revealTimeouts = [];
            if (!this._isVisible) {
                this._isVisible = true;
                const selection = this._codeEditor.getSelection();
                switch (this._codeEditor.getOption(41 /* EditorOption.find */).autoFindInSelection) {
                    case 'always':
                        this._toggleSelectionFind.checked = true;
                        break;
                    case 'never':
                        this._toggleSelectionFind.checked = false;
                        break;
                    case 'multiline': {
                        const isSelectionMultipleLine = !!selection && selection.startLineNumber !== selection.endLineNumber;
                        this._toggleSelectionFind.checked = isSelectionMultipleLine;
                        break;
                    }
                    default:
                        break;
                }
                this._tryUpdateWidgetWidth();
                this._updateButtons();
                this._revealTimeouts.push(setTimeout(() => {
                    this._domNode.classList.add('visible');
                    this._domNode.setAttribute('aria-hidden', 'false');
                }, 0));
                // validate query again as it's being dismissed when we hide the find widget.
                this._revealTimeouts.push(setTimeout(() => {
                    this._findInput.validate();
                }, 200));
                this._codeEditor.layoutOverlayWidget(this);
                let adjustEditorScrollTop = true;
                if (this._codeEditor.getOption(41 /* EditorOption.find */).seedSearchStringFromSelection && selection) {
                    const domNode = this._codeEditor.getDomNode();
                    if (domNode) {
                        const editorCoords = dom.getDomNodePagePosition(domNode);
                        const startCoords = this._codeEditor.getScrolledVisiblePosition(selection.getStartPosition());
                        const startLeft = editorCoords.left + (startCoords ? startCoords.left : 0);
                        const startTop = startCoords ? startCoords.top : 0;
                        if (this._viewZone && startTop < this._viewZone.heightInPx) {
                            if (selection.endLineNumber > selection.startLineNumber) {
                                adjustEditorScrollTop = false;
                            }
                            const leftOfFindWidget = dom.getTopLeftOffset(this._domNode).left;
                            if (startLeft > leftOfFindWidget) {
                                adjustEditorScrollTop = false;
                            }
                            const endCoords = this._codeEditor.getScrolledVisiblePosition(selection.getEndPosition());
                            const endLeft = editorCoords.left + (endCoords ? endCoords.left : 0);
                            if (endLeft > leftOfFindWidget) {
                                adjustEditorScrollTop = false;
                            }
                        }
                    }
                }
                this._showViewZone(adjustEditorScrollTop);
            }
        }
        _hide(focusTheEditor) {
            this._revealTimeouts.forEach(e => {
                clearTimeout(e);
            });
            this._revealTimeouts = [];
            if (this._isVisible) {
                this._isVisible = false;
                this._updateButtons();
                this._domNode.classList.remove('visible');
                this._domNode.setAttribute('aria-hidden', 'true');
                this._findInput.clearMessage();
                if (focusTheEditor) {
                    this._codeEditor.focus();
                }
                this._codeEditor.layoutOverlayWidget(this);
                this._removeViewZone();
            }
        }
        _layoutViewZone(targetScrollTop) {
            const addExtraSpaceOnTop = this._codeEditor.getOption(41 /* EditorOption.find */).addExtraSpaceOnTop;
            if (!addExtraSpaceOnTop) {
                this._removeViewZone();
                return;
            }
            if (!this._isVisible) {
                return;
            }
            const viewZone = this._viewZone;
            if (this._viewZoneId !== undefined || !viewZone) {
                return;
            }
            this._codeEditor.changeViewZones((accessor) => {
                viewZone.heightInPx = this._getHeight();
                this._viewZoneId = accessor.addZone(viewZone);
                // scroll top adjust to make sure the editor doesn't scroll when adding viewzone at the beginning.
                this._codeEditor.setScrollTop(targetScrollTop || this._codeEditor.getScrollTop() + viewZone.heightInPx);
            });
        }
        _showViewZone(adjustScroll = true) {
            if (!this._isVisible) {
                return;
            }
            const addExtraSpaceOnTop = this._codeEditor.getOption(41 /* EditorOption.find */).addExtraSpaceOnTop;
            if (!addExtraSpaceOnTop) {
                return;
            }
            if (this._viewZone === undefined) {
                this._viewZone = new FindWidgetViewZone(0);
            }
            const viewZone = this._viewZone;
            this._codeEditor.changeViewZones((accessor) => {
                if (this._viewZoneId !== undefined) {
                    // the view zone already exists, we need to update the height
                    const newHeight = this._getHeight();
                    if (newHeight === viewZone.heightInPx) {
                        return;
                    }
                    const scrollAdjustment = newHeight - viewZone.heightInPx;
                    viewZone.heightInPx = newHeight;
                    accessor.layoutZone(this._viewZoneId);
                    if (adjustScroll) {
                        this._codeEditor.setScrollTop(this._codeEditor.getScrollTop() + scrollAdjustment);
                    }
                    return;
                }
                else {
                    let scrollAdjustment = this._getHeight();
                    // if the editor has top padding, factor that into the zone height
                    scrollAdjustment -= this._codeEditor.getOption(84 /* EditorOption.padding */).top;
                    if (scrollAdjustment <= 0) {
                        return;
                    }
                    viewZone.heightInPx = scrollAdjustment;
                    this._viewZoneId = accessor.addZone(viewZone);
                    if (adjustScroll) {
                        this._codeEditor.setScrollTop(this._codeEditor.getScrollTop() + scrollAdjustment);
                    }
                }
            });
        }
        _removeViewZone() {
            this._codeEditor.changeViewZones((accessor) => {
                if (this._viewZoneId !== undefined) {
                    accessor.removeZone(this._viewZoneId);
                    this._viewZoneId = undefined;
                    if (this._viewZone) {
                        this._codeEditor.setScrollTop(this._codeEditor.getScrollTop() - this._viewZone.heightInPx);
                        this._viewZone = undefined;
                    }
                }
            });
        }
        _tryUpdateWidgetWidth() {
            if (!this._isVisible) {
                return;
            }
            if (!this._domNode.isConnected) {
                // the widget is not in the DOM
                return;
            }
            const layoutInfo = this._codeEditor.getLayoutInfo();
            const editorContentWidth = layoutInfo.contentWidth;
            if (editorContentWidth <= 0) {
                // for example, diff view original editor
                this._domNode.classList.add('hiddenEditor');
                return;
            }
            else if (this._domNode.classList.contains('hiddenEditor')) {
                this._domNode.classList.remove('hiddenEditor');
            }
            const editorWidth = layoutInfo.width;
            const minimapWidth = layoutInfo.minimap.minimapWidth;
            let collapsedFindWidget = false;
            let reducedFindWidget = false;
            let narrowFindWidget = false;
            if (this._resized) {
                const widgetWidth = dom.getTotalWidth(this._domNode);
                if (widgetWidth > FIND_WIDGET_INITIAL_WIDTH) {
                    // as the widget is resized by users, we may need to change the max width of the widget as the editor width changes.
                    this._domNode.style.maxWidth = `${editorWidth - 28 - minimapWidth - 15}px`;
                    this._replaceInput.width = dom.getTotalWidth(this._findInput.domNode);
                    return;
                }
            }
            if (FIND_WIDGET_INITIAL_WIDTH + 28 + minimapWidth >= editorWidth) {
                reducedFindWidget = true;
            }
            if (FIND_WIDGET_INITIAL_WIDTH + 28 + minimapWidth - MAX_MATCHES_COUNT_WIDTH >= editorWidth) {
                narrowFindWidget = true;
            }
            if (FIND_WIDGET_INITIAL_WIDTH + 28 + minimapWidth - MAX_MATCHES_COUNT_WIDTH >= editorWidth + 50) {
                collapsedFindWidget = true;
            }
            this._domNode.classList.toggle('collapsed-find-widget', collapsedFindWidget);
            this._domNode.classList.toggle('narrow-find-widget', narrowFindWidget);
            this._domNode.classList.toggle('reduced-find-widget', reducedFindWidget);
            if (!narrowFindWidget && !collapsedFindWidget) {
                // the minimal left offset of findwidget is 15px.
                this._domNode.style.maxWidth = `${editorWidth - 28 - minimapWidth - 15}px`;
            }
            this._findInput.layout({ collapsedFindWidget, narrowFindWidget, reducedFindWidget });
            if (this._resized) {
                const findInputWidth = this._findInput.inputBox.element.clientWidth;
                if (findInputWidth > 0) {
                    this._replaceInput.width = findInputWidth;
                }
            }
            else if (this._isReplaceVisible) {
                this._replaceInput.width = dom.getTotalWidth(this._findInput.domNode);
            }
        }
        _getHeight() {
            let totalheight = 0;
            // find input margin top
            totalheight += 4;
            // find input height
            totalheight += this._findInput.inputBox.height + 2 /** input box border */;
            if (this._isReplaceVisible) {
                // replace input margin
                totalheight += 4;
                totalheight += this._replaceInput.inputBox.height + 2 /** input box border */;
            }
            // margin bottom
            totalheight += 4;
            return totalheight;
        }
        _tryUpdateHeight() {
            const totalHeight = this._getHeight();
            if (this._cachedHeight !== null && this._cachedHeight === totalHeight) {
                return false;
            }
            this._cachedHeight = totalHeight;
            this._domNode.style.height = `${totalHeight}px`;
            return true;
        }
        // ----- Public
        focusFindInput() {
            this._findInput.select();
            // Edge browser requires focus() in addition to select()
            this._findInput.focus();
        }
        focusReplaceInput() {
            this._replaceInput.select();
            // Edge browser requires focus() in addition to select()
            this._replaceInput.focus();
        }
        highlightFindOptions() {
            this._findInput.highlightFindOptions();
        }
        _updateSearchScope() {
            if (!this._codeEditor.hasModel()) {
                return;
            }
            if (this._toggleSelectionFind.checked) {
                const selections = this._codeEditor.getSelections();
                selections.map(selection => {
                    if (selection.endColumn === 1 && selection.endLineNumber > selection.startLineNumber) {
                        selection = selection.setEndPosition(selection.endLineNumber - 1, this._codeEditor.getModel().getLineMaxColumn(selection.endLineNumber - 1));
                    }
                    const currentMatch = this._state.currentMatch;
                    if (selection.startLineNumber !== selection.endLineNumber) {
                        if (!range_1.Range.equalsRange(selection, currentMatch)) {
                            return selection;
                        }
                    }
                    return null;
                }).filter(element => !!element);
                if (selections.length) {
                    this._state.change({ searchScope: selections }, true);
                }
            }
        }
        _onFindInputMouseDown(e) {
            // on linux, middle key does pasting.
            if (e.middleButton) {
                e.stopPropagation();
            }
        }
        _onFindInputKeyDown(e) {
            if (e.equals(ctrlKeyMod | 3 /* KeyCode.Enter */)) {
                if (this._keybindingService.dispatchEvent(e, e.target)) {
                    e.preventDefault();
                    return;
                }
                else {
                    this._findInput.inputBox.insertAtCursor('\n');
                    e.preventDefault();
                    return;
                }
            }
            if (e.equals(2 /* KeyCode.Tab */)) {
                if (this._isReplaceVisible) {
                    this._replaceInput.focus();
                }
                else {
                    this._findInput.focusOnCaseSensitive();
                }
                e.preventDefault();
                return;
            }
            if (e.equals(2048 /* KeyMod.CtrlCmd */ | 18 /* KeyCode.DownArrow */)) {
                this._codeEditor.focus();
                e.preventDefault();
                return;
            }
            if (e.equals(16 /* KeyCode.UpArrow */)) {
                return stopPropagationForMultiLineUpwards(e, this._findInput.getValue(), this._findInput.domNode.querySelector('textarea'));
            }
            if (e.equals(18 /* KeyCode.DownArrow */)) {
                return stopPropagationForMultiLineDownwards(e, this._findInput.getValue(), this._findInput.domNode.querySelector('textarea'));
            }
        }
        _onReplaceInputKeyDown(e) {
            if (e.equals(ctrlKeyMod | 3 /* KeyCode.Enter */)) {
                if (this._keybindingService.dispatchEvent(e, e.target)) {
                    e.preventDefault();
                    return;
                }
                else {
                    if (platform.isWindows && platform.isNative && !this._ctrlEnterReplaceAllWarningPrompted) {
                        // this is the first time when users press Ctrl + Enter to replace all
                        this._notificationService.info(nls.localize(890, 'Ctrl+Enter now inserts line break instead of replacing all. You can modify the keybinding for editor.action.replaceAll to override this behavior.'));
                        this._ctrlEnterReplaceAllWarningPrompted = true;
                        this._storageService.store(ctrlEnterReplaceAllWarningPromptedKey, true, 0 /* StorageScope.PROFILE */, 0 /* StorageTarget.USER */);
                    }
                    this._replaceInput.inputBox.insertAtCursor('\n');
                    e.preventDefault();
                    return;
                }
            }
            if (e.equals(2 /* KeyCode.Tab */)) {
                this._findInput.focusOnCaseSensitive();
                e.preventDefault();
                return;
            }
            if (e.equals(1024 /* KeyMod.Shift */ | 2 /* KeyCode.Tab */)) {
                this._findInput.focus();
                e.preventDefault();
                return;
            }
            if (e.equals(2048 /* KeyMod.CtrlCmd */ | 18 /* KeyCode.DownArrow */)) {
                this._codeEditor.focus();
                e.preventDefault();
                return;
            }
            if (e.equals(16 /* KeyCode.UpArrow */)) {
                return stopPropagationForMultiLineUpwards(e, this._replaceInput.inputBox.value, this._replaceInput.inputBox.element.querySelector('textarea'));
            }
            if (e.equals(18 /* KeyCode.DownArrow */)) {
                return stopPropagationForMultiLineDownwards(e, this._replaceInput.inputBox.value, this._replaceInput.inputBox.element.querySelector('textarea'));
            }
        }
        // ----- sash
        getVerticalSashLeft(_sash) {
            return 0;
        }
        // ----- initialization
        _keybindingLabelFor(actionId) {
            const kb = this._keybindingService.lookupKeybinding(actionId);
            if (!kb) {
                return '';
            }
            return ` (${kb.getLabel()})`;
        }
        _buildDomNode() {
            const flexibleHeight = true;
            const flexibleWidth = true;
            // Find input
            this._findInput = this._register(new contextScopedHistoryWidget_1.ContextScopedFindInput(null, this._contextViewProvider, {
                width: FIND_INPUT_AREA_WIDTH,
                label: NLS_FIND_INPUT_LABEL,
                placeholder: NLS_FIND_INPUT_PLACEHOLDER,
                appendCaseSensitiveLabel: this._keybindingLabelFor(findModel_1.FIND_IDS.ToggleCaseSensitiveCommand),
                appendWholeWordsLabel: this._keybindingLabelFor(findModel_1.FIND_IDS.ToggleWholeWordCommand),
                appendRegexLabel: this._keybindingLabelFor(findModel_1.FIND_IDS.ToggleRegexCommand),
                validation: (value) => {
                    if (value.length === 0 || !this._findInput.getRegex()) {
                        return null;
                    }
                    try {
                        // use `g` and `u` which are also used by the TextModel search
                        new RegExp(value, 'gu');
                        return null;
                    }
                    catch (e) {
                        return { content: e.message };
                    }
                },
                flexibleHeight,
                flexibleWidth,
                flexibleMaxHeight: 118,
                showCommonFindToggles: true,
                showHistoryHint: () => (0, historyWidgetKeybindingHint_1.showHistoryKeybindingHint)(this._keybindingService),
                inputBoxStyles: defaultStyles_1.defaultInputBoxStyles,
                toggleStyles: defaultStyles_1.defaultToggleStyles
            }, this._contextKeyService));
            this._findInput.setRegex(!!this._state.isRegex);
            this._findInput.setCaseSensitive(!!this._state.matchCase);
            this._findInput.setWholeWords(!!this._state.wholeWord);
            this._register(this._findInput.onKeyDown((e) => this._onFindInputKeyDown(e)));
            this._register(this._findInput.inputBox.onDidChange(() => {
                if (this._ignoreChangeEvent) {
                    return;
                }
                this._state.change({ searchString: this._findInput.getValue() }, true);
            }));
            this._register(this._findInput.onDidOptionChange(() => {
                this._state.change({
                    isRegex: this._findInput.getRegex(),
                    wholeWord: this._findInput.getWholeWords(),
                    matchCase: this._findInput.getCaseSensitive()
                }, true);
            }));
            this._register(this._findInput.onCaseSensitiveKeyDown((e) => {
                if (e.equals(1024 /* KeyMod.Shift */ | 2 /* KeyCode.Tab */)) {
                    if (this._isReplaceVisible) {
                        this._replaceInput.focus();
                        e.preventDefault();
                    }
                }
            }));
            this._register(this._findInput.onRegexKeyDown((e) => {
                if (e.equals(2 /* KeyCode.Tab */)) {
                    if (this._isReplaceVisible) {
                        this._replaceInput.focusOnPreserve();
                        e.preventDefault();
                    }
                }
            }));
            this._register(this._findInput.inputBox.onDidHeightChange((e) => {
                if (this._tryUpdateHeight()) {
                    this._showViewZone();
                }
            }));
            if (platform.isLinux) {
                this._register(this._findInput.onMouseDown((e) => this._onFindInputMouseDown(e)));
            }
            this._matchesCount = document.createElement('div');
            this._matchesCount.className = 'matchesCount';
            this._updateMatchesCount();
            // Create a scoped hover delegate for all find related buttons
            const hoverDelegate = this._register((0, hoverDelegateFactory_1.createInstantHoverDelegate)());
            // Previous button
            this._prevBtn = this._register(new SimpleButton({
                label: NLS_PREVIOUS_MATCH_BTN_LABEL + this._keybindingLabelFor(findModel_1.FIND_IDS.PreviousMatchFindAction),
                icon: exports.findPreviousMatchIcon,
                hoverDelegate,
                onTrigger: () => {
                    (0, types_1.assertIsDefined)(this._codeEditor.getAction(findModel_1.FIND_IDS.PreviousMatchFindAction)).run().then(undefined, errors_1.onUnexpectedError);
                }
            }, this._hoverService));
            // Next button
            this._nextBtn = this._register(new SimpleButton({
                label: NLS_NEXT_MATCH_BTN_LABEL + this._keybindingLabelFor(findModel_1.FIND_IDS.NextMatchFindAction),
                icon: exports.findNextMatchIcon,
                hoverDelegate,
                onTrigger: () => {
                    (0, types_1.assertIsDefined)(this._codeEditor.getAction(findModel_1.FIND_IDS.NextMatchFindAction)).run().then(undefined, errors_1.onUnexpectedError);
                }
            }, this._hoverService));
            const findPart = document.createElement('div');
            findPart.className = 'find-part';
            findPart.appendChild(this._findInput.domNode);
            const actionsContainer = document.createElement('div');
            actionsContainer.className = 'find-actions';
            findPart.appendChild(actionsContainer);
            actionsContainer.appendChild(this._matchesCount);
            actionsContainer.appendChild(this._prevBtn.domNode);
            actionsContainer.appendChild(this._nextBtn.domNode);
            // Toggle selection button
            this._toggleSelectionFind = this._register(new toggle_1.Toggle({
                icon: exports.findSelectionIcon,
                title: NLS_TOGGLE_SELECTION_FIND_TITLE + this._keybindingLabelFor(findModel_1.FIND_IDS.ToggleSearchScopeCommand),
                isChecked: false,
                hoverDelegate: hoverDelegate,
                inputActiveOptionBackground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.inputActiveOptionBackground),
                inputActiveOptionBorder: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.inputActiveOptionBorder),
                inputActiveOptionForeground: (0, colorRegistry_1.asCssVariable)(colorRegistry_1.inputActiveOptionForeground),
            }));
            this._register(this._toggleSelectionFind.onChange(() => {
                if (this._toggleSelectionFind.checked) {
                    if (this._codeEditor.hasModel()) {
                        let selections = this._codeEditor.getSelections();
                        selections = selections.map(selection => {
                            if (selection.endColumn === 1 && selection.endLineNumber > selection.startLineNumber) {
                                selection = selection.setEndPosition(selection.endLineNumber - 1, this._codeEditor.getModel().getLineMaxColumn(selection.endLineNumber - 1));
                            }
                            if (!selection.isEmpty()) {
                                return selection;
                            }
                            return null;
                        }).filter((element) => !!element);
                        if (selections.length) {
                            this._state.change({ searchScope: selections }, true);
                        }
                    }
                }
                else {
                    this._state.change({ searchScope: null }, true);
                }
            }));
            actionsContainer.appendChild(this._toggleSelectionFind.domNode);
            // Close button
            this._closeBtn = this._register(new SimpleButton({
                label: NLS_CLOSE_BTN_LABEL + this._keybindingLabelFor(findModel_1.FIND_IDS.CloseFindWidgetCommand),
                icon: iconRegistry_1.widgetClose,
                hoverDelegate,
                onTrigger: () => {
                    this._state.change({ isRevealed: false, searchScope: null }, false);
                },
                onKeyDown: (e) => {
                    if (e.equals(2 /* KeyCode.Tab */)) {
                        if (this._isReplaceVisible) {
                            if (this._replaceBtn.isEnabled()) {
                                this._replaceBtn.focus();
                            }
                            else {
                                this._codeEditor.focus();
                            }
                            e.preventDefault();
                        }
                    }
                }
            }, this._hoverService));
            // Replace input
            this._replaceInput = this._register(new contextScopedHistoryWidget_1.ContextScopedReplaceInput(null, undefined, {
                label: NLS_REPLACE_INPUT_LABEL,
                placeholder: NLS_REPLACE_INPUT_PLACEHOLDER,
                appendPreserveCaseLabel: this._keybindingLabelFor(findModel_1.FIND_IDS.TogglePreserveCaseCommand),
                history: [],
                flexibleHeight,
                flexibleWidth,
                flexibleMaxHeight: 118,
                showHistoryHint: () => (0, historyWidgetKeybindingHint_1.showHistoryKeybindingHint)(this._keybindingService),
                inputBoxStyles: defaultStyles_1.defaultInputBoxStyles,
                toggleStyles: defaultStyles_1.defaultToggleStyles
            }, this._contextKeyService, true));
            this._replaceInput.setPreserveCase(!!this._state.preserveCase);
            this._register(this._replaceInput.onKeyDown((e) => this._onReplaceInputKeyDown(e)));
            this._register(this._replaceInput.inputBox.onDidChange(() => {
                this._state.change({ replaceString: this._replaceInput.inputBox.value }, false);
            }));
            this._register(this._replaceInput.inputBox.onDidHeightChange((e) => {
                if (this._isReplaceVisible && this._tryUpdateHeight()) {
                    this._showViewZone();
                }
            }));
            this._register(this._replaceInput.onDidOptionChange(() => {
                this._state.change({
                    preserveCase: this._replaceInput.getPreserveCase()
                }, true);
            }));
            this._register(this._replaceInput.onPreserveCaseKeyDown((e) => {
                if (e.equals(2 /* KeyCode.Tab */)) {
                    if (this._prevBtn.isEnabled()) {
                        this._prevBtn.focus();
                    }
                    else if (this._nextBtn.isEnabled()) {
                        this._nextBtn.focus();
                    }
                    else if (this._toggleSelectionFind.enabled) {
                        this._toggleSelectionFind.focus();
                    }
                    else if (this._closeBtn.isEnabled()) {
                        this._closeBtn.focus();
                    }
                    e.preventDefault();
                }
            }));
            // Create scoped hover delegate for replace actions
            const replaceHoverDelegate = this._register((0, hoverDelegateFactory_1.createInstantHoverDelegate)());
            // Replace one button
            this._replaceBtn = this._register(new SimpleButton({
                label: NLS_REPLACE_BTN_LABEL + this._keybindingLabelFor(findModel_1.FIND_IDS.ReplaceOneAction),
                icon: exports.findReplaceIcon,
                hoverDelegate: replaceHoverDelegate,
                onTrigger: () => {
                    this._controller.replace();
                },
                onKeyDown: (e) => {
                    if (e.equals(1024 /* KeyMod.Shift */ | 2 /* KeyCode.Tab */)) {
                        this._closeBtn.focus();
                        e.preventDefault();
                    }
                }
            }, this._hoverService));
            // Replace all button
            this._replaceAllBtn = this._register(new SimpleButton({
                label: NLS_REPLACE_ALL_BTN_LABEL + this._keybindingLabelFor(findModel_1.FIND_IDS.ReplaceAllAction),
                icon: exports.findReplaceAllIcon,
                hoverDelegate: replaceHoverDelegate,
                onTrigger: () => {
                    this._controller.replaceAll();
                }
            }, this._hoverService));
            const replacePart = document.createElement('div');
            replacePart.className = 'replace-part';
            replacePart.appendChild(this._replaceInput.domNode);
            const replaceActionsContainer = document.createElement('div');
            replaceActionsContainer.className = 'replace-actions';
            replacePart.appendChild(replaceActionsContainer);
            replaceActionsContainer.appendChild(this._replaceBtn.domNode);
            replaceActionsContainer.appendChild(this._replaceAllBtn.domNode);
            // Toggle replace button
            this._toggleReplaceBtn = this._register(new SimpleButton({
                label: NLS_TOGGLE_REPLACE_MODE_BTN_LABEL,
                className: 'codicon toggle left',
                onTrigger: () => {
                    this._state.change({ isReplaceRevealed: !this._isReplaceVisible }, false);
                    if (this._isReplaceVisible) {
                        this._replaceInput.width = dom.getTotalWidth(this._findInput.domNode);
                        this._replaceInput.inputBox.layout();
                    }
                    this._showViewZone();
                }
            }, this._hoverService));
            this._toggleReplaceBtn.setExpanded(this._isReplaceVisible);
            // Widget
            this._domNode = document.createElement('div');
            this._domNode.className = 'editor-widget find-widget';
            this._domNode.setAttribute('aria-hidden', 'true');
            this._domNode.ariaLabel = NLS_FIND_DIALOG_LABEL;
            this._domNode.role = 'dialog';
            // We need to set this explicitly, otherwise on IE11, the width inheritence of flex doesn't work.
            this._domNode.style.width = `${FIND_WIDGET_INITIAL_WIDTH}px`;
            this._domNode.appendChild(this._toggleReplaceBtn.domNode);
            this._domNode.appendChild(findPart);
            this._domNode.appendChild(this._closeBtn.domNode);
            this._domNode.appendChild(replacePart);
            this._resizeSash = this._register(new sash_1.Sash(this._domNode, this, { orientation: 0 /* Orientation.VERTICAL */, size: 2 }));
            this._resized = false;
            let originalWidth = FIND_WIDGET_INITIAL_WIDTH;
            this._register(this._resizeSash.onDidStart(() => {
                originalWidth = dom.getTotalWidth(this._domNode);
            }));
            this._register(this._resizeSash.onDidChange((evt) => {
                this._resized = true;
                const width = originalWidth + evt.startX - evt.currentX;
                if (width < FIND_WIDGET_INITIAL_WIDTH) {
                    // narrow down the find widget should be handled by CSS.
                    return;
                }
                const maxWidth = parseFloat(dom.getComputedStyle(this._domNode).maxWidth) || 0;
                if (width > maxWidth) {
                    return;
                }
                this._domNode.style.width = `${width}px`;
                if (this._isReplaceVisible) {
                    this._replaceInput.width = dom.getTotalWidth(this._findInput.domNode);
                }
                this._findInput.inputBox.layout();
                this._tryUpdateHeight();
            }));
            this._register(this._resizeSash.onDidReset(() => {
                // users double click on the sash
                const currentWidth = dom.getTotalWidth(this._domNode);
                if (currentWidth < FIND_WIDGET_INITIAL_WIDTH) {
                    // The editor is narrow and the width of the find widget is controlled fully by CSS.
                    return;
                }
                let width = FIND_WIDGET_INITIAL_WIDTH;
                if (!this._resized || currentWidth === FIND_WIDGET_INITIAL_WIDTH) {
                    // 1. never resized before, double click should maximizes it
                    // 2. users resized it already but its width is the same as default
                    const layoutInfo = this._codeEditor.getLayoutInfo();
                    width = layoutInfo.width - 28 - layoutInfo.minimap.minimapWidth - 15;
                    this._resized = true;
                }
                else {
                    /**
                     * no op, the find widget should be shrinked to its default size.
                     */
                }
                this._domNode.style.width = `${width}px`;
                if (this._isReplaceVisible) {
                    this._replaceInput.width = dom.getTotalWidth(this._findInput.domNode);
                }
                this._findInput.inputBox.layout();
            }));
        }
        updateAccessibilitySupport() {
            const value = this._codeEditor.getOption(2 /* EditorOption.accessibilitySupport */);
            this._findInput.setFocusInputOnOptionClick(value !== 2 /* AccessibilitySupport.Enabled */);
        }
    }
    exports.FindWidget = FindWidget;
    class SimpleButton extends widget_1.Widget {
        constructor(opts, hoverService) {
            super();
            this._opts = opts;
            let className = 'button';
            if (this._opts.className) {
                className = className + ' ' + this._opts.className;
            }
            if (this._opts.icon) {
                className = className + ' ' + themables_1.ThemeIcon.asClassName(this._opts.icon);
            }
            this._domNode = document.createElement('div');
            this._domNode.tabIndex = 0;
            this._domNode.className = className;
            this._domNode.setAttribute('role', 'button');
            this._domNode.setAttribute('aria-label', this._opts.label);
            this._register(hoverService.setupManagedHover(opts.hoverDelegate ?? (0, hoverDelegateFactory_1.getDefaultHoverDelegate)('element'), this._domNode, this._opts.label));
            this.onclick(this._domNode, (e) => {
                this._opts.onTrigger();
                e.preventDefault();
            });
            this.onkeydown(this._domNode, (e) => {
                if (e.equals(10 /* KeyCode.Space */) || e.equals(3 /* KeyCode.Enter */)) {
                    this._opts.onTrigger();
                    e.preventDefault();
                    return;
                }
                this._opts.onKeyDown?.(e);
            });
        }
        get domNode() {
            return this._domNode;
        }
        isEnabled() {
            return (this._domNode.tabIndex >= 0);
        }
        focus() {
            this._domNode.focus();
        }
        setEnabled(enabled) {
            this._domNode.classList.toggle('disabled', !enabled);
            this._domNode.setAttribute('aria-disabled', String(!enabled));
            this._domNode.tabIndex = enabled ? 0 : -1;
        }
        setExpanded(expanded) {
            this._domNode.setAttribute('aria-expanded', String(!!expanded));
            if (expanded) {
                this._domNode.classList.remove(...themables_1.ThemeIcon.asClassNameArray(findCollapsedIcon));
                this._domNode.classList.add(...themables_1.ThemeIcon.asClassNameArray(findExpandedIcon));
            }
            else {
                this._domNode.classList.remove(...themables_1.ThemeIcon.asClassNameArray(findExpandedIcon));
                this._domNode.classList.add(...themables_1.ThemeIcon.asClassNameArray(findCollapsedIcon));
            }
        }
    }
    exports.SimpleButton = SimpleButton;
    // theming
    (0, themeService_1.registerThemingParticipant)((theme, collector) => {
        const findMatchHighlightBorder = theme.getColor(colorRegistry_1.editorFindMatchHighlightBorder);
        if (findMatchHighlightBorder) {
            collector.addRule(`.monaco-editor .findMatch { border: 1px ${(0, theme_1.isHighContrast)(theme.type) ? 'dotted' : 'solid'} ${findMatchHighlightBorder}; box-sizing: border-box; }`);
        }
        const findRangeHighlightBorder = theme.getColor(colorRegistry_1.editorFindRangeHighlightBorder);
        if (findRangeHighlightBorder) {
            collector.addRule(`.monaco-editor .findScope { border: 1px ${(0, theme_1.isHighContrast)(theme.type) ? 'dashed' : 'solid'} ${findRangeHighlightBorder}; }`);
        }
        const hcBorder = theme.getColor(colorRegistry_1.contrastBorder);
        if (hcBorder) {
            collector.addRule(`.monaco-editor .find-widget { border: 1px solid ${hcBorder}; }`);
        }
        const findMatchForeground = theme.getColor(colorRegistry_1.editorFindMatchForeground);
        if (findMatchForeground) {
            collector.addRule(`.monaco-editor .findMatchInline { color: ${findMatchForeground}; }`);
        }
        const findMatchHighlightForeground = theme.getColor(colorRegistry_1.editorFindMatchHighlightForeground);
        if (findMatchHighlightForeground) {
            collector.addRule(`.monaco-editor .currentFindMatchInline { color: ${findMatchHighlightForeground}; }`);
        }
    });
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[423/*vs/editor/contrib/find/browser/findController*/], __M([1/*require*/,0/*exports*/,14/*vs/base/common/async*/,2/*vs/base/common/lifecycle*/,11/*vs/base/common/strings*/,15/*vs/editor/browser/editorExtensions*/,80/*vs/editor/common/core/editorColorRegistry*/,20/*vs/editor/common/editorContextKeys*/,40/*vs/editor/common/model*/,220/*vs/editor/contrib/find/browser/findModel*/,824/*vs/editor/contrib/find/browser/findOptionsWidget*/,825/*vs/editor/contrib/find/browser/findState*/,826/*vs/editor/contrib/find/browser/findWidget*/,3/*vs/nls*/,29/*vs/platform/actions/common/actions*/,117/*vs/platform/clipboard/common/clipboardService*/,12/*vs/platform/contextkey/common/contextkey*/,58/*vs/platform/contextview/browser/contextView*/,31/*vs/platform/keybinding/common/keybinding*/,50/*vs/platform/notification/common/notification*/,66/*vs/platform/quickinput/common/quickInput*/,101/*vs/platform/storage/common/storage*/,25/*vs/platform/theme/common/themeService*/,118/*vs/platform/hover/browser/hover*/]), function (require, exports, async_1, lifecycle_1, strings, editorExtensions_1, editorColorRegistry_1, editorContextKeys_1, model_1, findModel_1, findOptionsWidget_1, findState_1, findWidget_1, nls, actions_1, clipboardService_1, contextkey_1, contextView_1, keybinding_1, notification_1, quickInput_1, storage_1, themeService_1, hover_1) {
    "use strict";
    var CommonFindController_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.StartFindReplaceAction = exports.PreviousSelectionMatchFindAction = exports.NextSelectionMatchFindAction = exports.SelectionMatchFindAction = exports.MoveToMatchFindAction = exports.PreviousMatchFindAction = exports.NextMatchFindAction = exports.MatchFindAction = exports.StartFindWithSelectionAction = exports.StartFindWithArgsAction = exports.StartFindAction = exports.FindController = exports.CommonFindController = void 0;
    exports.getSelectionSearchString = getSelectionSearchString;
    const SEARCH_STRING_MAX_LENGTH = 524288;
    function getSelectionSearchString(editor, seedSearchStringFromSelection = 'single', seedSearchStringFromNonEmptySelection = false) {
        if (!editor.hasModel()) {
            return null;
        }
        const selection = editor.getSelection();
        // if selection spans multiple lines, default search string to empty
        if ((seedSearchStringFromSelection === 'single' && selection.startLineNumber === selection.endLineNumber)
            || seedSearchStringFromSelection === 'multiple') {
            if (selection.isEmpty()) {
                const wordAtPosition = editor.getConfiguredWordAtPosition(selection.getStartPosition());
                if (wordAtPosition && (false === seedSearchStringFromNonEmptySelection)) {
                    return wordAtPosition.word;
                }
            }
            else {
                if (editor.getModel().getValueLengthInRange(selection) < SEARCH_STRING_MAX_LENGTH) {
                    return editor.getModel().getValueInRange(selection);
                }
            }
        }
        return null;
    }
    let CommonFindController = class CommonFindController extends lifecycle_1.Disposable {
        static { CommonFindController_1 = this; }
        static { this.ID = 'editor.contrib.findController'; }
        get editor() {
            return this._editor;
        }
        static get(editor) {
            return editor.getContribution(CommonFindController_1.ID);
        }
        constructor(editor, contextKeyService, storageService, clipboardService, notificationService, hoverService) {
            super();
            this._editor = editor;
            this._findWidgetVisible = findModel_1.CONTEXT_FIND_WIDGET_VISIBLE.bindTo(contextKeyService);
            this._contextKeyService = contextKeyService;
            this._storageService = storageService;
            this._clipboardService = clipboardService;
            this._notificationService = notificationService;
            this._hoverService = hoverService;
            this._updateHistoryDelayer = new async_1.Delayer(500);
            this._state = this._register(new findState_1.FindReplaceState());
            this.loadQueryState();
            this._register(this._state.onFindReplaceStateChange((e) => this._onStateChanged(e)));
            this._model = null;
            this._register(this._editor.onDidChangeModel(() => {
                const shouldRestartFind = (this._editor.getModel() && this._state.isRevealed);
                this.disposeModel();
                this._state.change({
                    searchScope: null,
                    matchCase: this._storageService.getBoolean('editor.matchCase', 1 /* StorageScope.WORKSPACE */, false),
                    wholeWord: this._storageService.getBoolean('editor.wholeWord', 1 /* StorageScope.WORKSPACE */, false),
                    isRegex: this._storageService.getBoolean('editor.isRegex', 1 /* StorageScope.WORKSPACE */, false),
                    preserveCase: this._storageService.getBoolean('editor.preserveCase', 1 /* StorageScope.WORKSPACE */, false)
                }, false);
                if (shouldRestartFind) {
                    this._start({
                        forceRevealReplace: false,
                        seedSearchStringFromSelection: 'none',
                        seedSearchStringFromNonEmptySelection: false,
                        seedSearchStringFromGlobalClipboard: false,
                        shouldFocus: 0 /* FindStartFocusAction.NoFocusChange */,
                        shouldAnimate: false,
                        updateSearchScope: false,
                        loop: this._editor.getOption(41 /* EditorOption.find */).loop
                    });
                }
            }));
        }
        dispose() {
            this.disposeModel();
            super.dispose();
        }
        disposeModel() {
            if (this._model) {
                this._model.dispose();
                this._model = null;
            }
        }
        _onStateChanged(e) {
            this.saveQueryState(e);
            if (e.isRevealed) {
                if (this._state.isRevealed) {
                    this._findWidgetVisible.set(true);
                }
                else {
                    this._findWidgetVisible.reset();
                    this.disposeModel();
                }
            }
            if (e.searchString) {
                this.setGlobalBufferTerm(this._state.searchString);
            }
        }
        saveQueryState(e) {
            if (e.isRegex) {
                this._storageService.store('editor.isRegex', this._state.actualIsRegex, 1 /* StorageScope.WORKSPACE */, 1 /* StorageTarget.MACHINE */);
            }
            if (e.wholeWord) {
                this._storageService.store('editor.wholeWord', this._state.actualWholeWord, 1 /* StorageScope.WORKSPACE */, 1 /* StorageTarget.MACHINE */);
            }
            if (e.matchCase) {
                this._storageService.store('editor.matchCase', this._state.actualMatchCase, 1 /* StorageScope.WORKSPACE */, 1 /* StorageTarget.MACHINE */);
            }
            if (e.preserveCase) {
                this._storageService.store('editor.preserveCase', this._state.actualPreserveCase, 1 /* StorageScope.WORKSPACE */, 1 /* StorageTarget.MACHINE */);
            }
        }
        loadQueryState() {
            this._state.change({
                matchCase: this._storageService.getBoolean('editor.matchCase', 1 /* StorageScope.WORKSPACE */, this._state.matchCase),
                wholeWord: this._storageService.getBoolean('editor.wholeWord', 1 /* StorageScope.WORKSPACE */, this._state.wholeWord),
                isRegex: this._storageService.getBoolean('editor.isRegex', 1 /* StorageScope.WORKSPACE */, this._state.isRegex),
                preserveCase: this._storageService.getBoolean('editor.preserveCase', 1 /* StorageScope.WORKSPACE */, this._state.preserveCase)
            }, false);
        }
        isFindInputFocused() {
            return !!findModel_1.CONTEXT_FIND_INPUT_FOCUSED.getValue(this._contextKeyService);
        }
        getState() {
            return this._state;
        }
        closeFindWidget() {
            this._state.change({
                isRevealed: false,
                searchScope: null
            }, false);
            this._editor.focus();
        }
        toggleCaseSensitive() {
            this._state.change({ matchCase: !this._state.matchCase }, false);
            if (!this._state.isRevealed) {
                this.highlightFindOptions();
            }
        }
        toggleWholeWords() {
            this._state.change({ wholeWord: !this._state.wholeWord }, false);
            if (!this._state.isRevealed) {
                this.highlightFindOptions();
            }
        }
        toggleRegex() {
            this._state.change({ isRegex: !this._state.isRegex }, false);
            if (!this._state.isRevealed) {
                this.highlightFindOptions();
            }
        }
        togglePreserveCase() {
            this._state.change({ preserveCase: !this._state.preserveCase }, false);
            if (!this._state.isRevealed) {
                this.highlightFindOptions();
            }
        }
        toggleSearchScope() {
            if (this._state.searchScope) {
                this._state.change({ searchScope: null }, true);
            }
            else {
                if (this._editor.hasModel()) {
                    let selections = this._editor.getSelections();
                    selections = selections.map(selection => {
                        if (selection.endColumn === 1 && selection.endLineNumber > selection.startLineNumber) {
                            selection = selection.setEndPosition(selection.endLineNumber - 1, this._editor.getModel().getLineMaxColumn(selection.endLineNumber - 1));
                        }
                        if (!selection.isEmpty()) {
                            return selection;
                        }
                        return null;
                    }).filter((element) => !!element);
                    if (selections.length) {
                        this._state.change({ searchScope: selections }, true);
                    }
                }
            }
        }
        setSearchString(searchString) {
            if (this._state.isRegex) {
                searchString = strings.escapeRegExpCharacters(searchString);
            }
            this._state.change({ searchString: searchString }, false);
        }
        highlightFindOptions(ignoreWhenVisible = false) {
            // overwritten in subclass
        }
        async _start(opts, newState) {
            this.disposeModel();
            if (!this._editor.hasModel()) {
                // cannot do anything with an editor that doesn't have a model...
                return;
            }
            const stateChanges = {
                ...newState,
                isRevealed: true
            };
            if (opts.seedSearchStringFromSelection === 'single') {
                const selectionSearchString = getSelectionSearchString(this._editor, opts.seedSearchStringFromSelection, opts.seedSearchStringFromNonEmptySelection);
                if (selectionSearchString) {
                    if (this._state.isRegex) {
                        stateChanges.searchString = strings.escapeRegExpCharacters(selectionSearchString);
                    }
                    else {
                        stateChanges.searchString = selectionSearchString;
                    }
                }
            }
            else if (opts.seedSearchStringFromSelection === 'multiple' && !opts.updateSearchScope) {
                const selectionSearchString = getSelectionSearchString(this._editor, opts.seedSearchStringFromSelection);
                if (selectionSearchString) {
                    stateChanges.searchString = selectionSearchString;
                }
            }
            if (!stateChanges.searchString && opts.seedSearchStringFromGlobalClipboard) {
                const selectionSearchString = await this.getGlobalBufferTerm();
                if (!this._editor.hasModel()) {
                    // the editor has lost its model in the meantime
                    return;
                }
                if (selectionSearchString) {
                    stateChanges.searchString = selectionSearchString;
                }
            }
            // Overwrite isReplaceRevealed
            if (opts.forceRevealReplace || stateChanges.isReplaceRevealed) {
                stateChanges.isReplaceRevealed = true;
            }
            else if (!this._findWidgetVisible.get()) {
                stateChanges.isReplaceRevealed = false;
            }
            if (opts.updateSearchScope) {
                const currentSelections = this._editor.getSelections();
                if (currentSelections.some(selection => !selection.isEmpty())) {
                    stateChanges.searchScope = currentSelections;
                }
            }
            stateChanges.loop = opts.loop;
            this._state.change(stateChanges, false);
            if (!this._model) {
                this._model = new findModel_1.FindModelBoundToEditorModel(this._editor, this._state);
            }
        }
        start(opts, newState) {
            return this._start(opts, newState);
        }
        moveToNextMatch() {
            if (this._model) {
                this._model.moveToNextMatch();
                return true;
            }
            return false;
        }
        moveToPrevMatch() {
            if (this._model) {
                this._model.moveToPrevMatch();
                return true;
            }
            return false;
        }
        goToMatch(index) {
            if (this._model) {
                this._model.moveToMatch(index);
                return true;
            }
            return false;
        }
        replace() {
            if (this._model) {
                this._model.replace();
                return true;
            }
            return false;
        }
        replaceAll() {
            if (this._model) {
                if (this._editor.getModel()?.isTooLargeForHeapOperation()) {
                    this._notificationService.warn(nls.localize(848, "The file is too large to perform a replace all operation."));
                    return false;
                }
                this._model.replaceAll();
                return true;
            }
            return false;
        }
        selectAllMatches() {
            if (this._model) {
                this._model.selectAllMatches();
                this._editor.focus();
                return true;
            }
            return false;
        }
        async getGlobalBufferTerm() {
            if (this._editor.getOption(41 /* EditorOption.find */).globalFindClipboard
                && this._editor.hasModel()
                && !this._editor.getModel().isTooLargeForSyncing()) {
                return this._clipboardService.readFindText();
            }
            return '';
        }
        setGlobalBufferTerm(text) {
            if (this._editor.getOption(41 /* EditorOption.find */).globalFindClipboard
                && this._editor.hasModel()
                && !this._editor.getModel().isTooLargeForSyncing()) {
                // intentionally not awaited
                this._clipboardService.writeFindText(text);
            }
        }
    };
    exports.CommonFindController = CommonFindController;
    exports.CommonFindController = CommonFindController = CommonFindController_1 = __decorate([
        __param(1, contextkey_1.IContextKeyService),
        __param(2, storage_1.IStorageService),
        __param(3, clipboardService_1.IClipboardService),
        __param(4, notification_1.INotificationService),
        __param(5, hover_1.IHoverService)
    ], CommonFindController);
    let FindController = class FindController extends CommonFindController {
        constructor(editor, _contextViewService, _contextKeyService, _keybindingService, _themeService, notificationService, _storageService, clipboardService, hoverService) {
            super(editor, _contextKeyService, _storageService, clipboardService, notificationService, hoverService);
            this._contextViewService = _contextViewService;
            this._keybindingService = _keybindingService;
            this._themeService = _themeService;
            this._widget = null;
            this._findOptionsWidget = null;
        }
        async _start(opts, newState) {
            if (!this._widget) {
                this._createFindWidget();
            }
            const selection = this._editor.getSelection();
            let updateSearchScope = false;
            switch (this._editor.getOption(41 /* EditorOption.find */).autoFindInSelection) {
                case 'always':
                    updateSearchScope = true;
                    break;
                case 'never':
                    updateSearchScope = false;
                    break;
                case 'multiline': {
                    const isSelectionMultipleLine = !!selection && selection.startLineNumber !== selection.endLineNumber;
                    updateSearchScope = isSelectionMultipleLine;
                    break;
                }
                default:
                    break;
            }
            opts.updateSearchScope = opts.updateSearchScope || updateSearchScope;
            await super._start(opts, newState);
            if (this._widget) {
                if (opts.shouldFocus === 2 /* FindStartFocusAction.FocusReplaceInput */) {
                    this._widget.focusReplaceInput();
                }
                else if (opts.shouldFocus === 1 /* FindStartFocusAction.FocusFindInput */) {
                    this._widget.focusFindInput();
                }
            }
        }
        highlightFindOptions(ignoreWhenVisible = false) {
            if (!this._widget) {
                this._createFindWidget();
            }
            if (this._state.isRevealed && !ignoreWhenVisible) {
                this._widget.highlightFindOptions();
            }
            else {
                this._findOptionsWidget.highlightFindOptions();
            }
        }
        _createFindWidget() {
            this._widget = this._register(new findWidget_1.FindWidget(this._editor, this, this._state, this._contextViewService, this._keybindingService, this._contextKeyService, this._themeService, this._storageService, this._notificationService, this._hoverService));
            this._findOptionsWidget = this._register(new findOptionsWidget_1.FindOptionsWidget(this._editor, this._state, this._keybindingService));
        }
    };
    exports.FindController = FindController;
    exports.FindController = FindController = __decorate([
        __param(1, contextView_1.IContextViewService),
        __param(2, contextkey_1.IContextKeyService),
        __param(3, keybinding_1.IKeybindingService),
        __param(4, themeService_1.IThemeService),
        __param(5, notification_1.INotificationService),
        __param(6, storage_1.IStorageService),
        __param(7, clipboardService_1.IClipboardService),
        __param(8, hover_1.IHoverService)
    ], FindController);
    exports.StartFindAction = (0, editorExtensions_1.registerMultiEditorAction)(new editorExtensions_1.MultiEditorAction({
        id: findModel_1.FIND_IDS.StartFindAction,
        label: nls.localize(849, "Find"),
        alias: 'Find',
        precondition: contextkey_1.ContextKeyExpr.or(editorContextKeys_1.EditorContextKeys.focus, contextkey_1.ContextKeyExpr.has('editorIsOpen')),
        kbOpts: {
            kbExpr: null,
            primary: 2048 /* KeyMod.CtrlCmd */ | 36 /* KeyCode.KeyF */,
            weight: 100 /* KeybindingWeight.EditorContrib */
        },
        menuOpts: {
            menuId: actions_1.MenuId.MenubarEditMenu,
            group: '3_find',
            title: nls.localize(850, "&&Find"),
            order: 1
        }
    }));
    exports.StartFindAction.addImplementation(0, (accessor, editor, args) => {
        const controller = CommonFindController.get(editor);
        if (!controller) {
            return false;
        }
        return controller.start({
            forceRevealReplace: false,
            seedSearchStringFromSelection: editor.getOption(41 /* EditorOption.find */).seedSearchStringFromSelection !== 'never' ? 'single' : 'none',
            seedSearchStringFromNonEmptySelection: editor.getOption(41 /* EditorOption.find */).seedSearchStringFromSelection === 'selection',
            seedSearchStringFromGlobalClipboard: editor.getOption(41 /* EditorOption.find */).globalFindClipboard,
            shouldFocus: 1 /* FindStartFocusAction.FocusFindInput */,
            shouldAnimate: true,
            updateSearchScope: false,
            loop: editor.getOption(41 /* EditorOption.find */).loop
        });
    });
    const findArgDescription = {
        description: 'Open a new In-Editor Find Widget.',
        args: [{
                name: 'Open a new In-Editor Find Widget args',
                schema: {
                    properties: {
                        searchString: { type: 'string' },
                        replaceString: { type: 'string' },
                        isRegex: { type: 'boolean' },
                        matchWholeWord: { type: 'boolean' },
                        isCaseSensitive: { type: 'boolean' },
                        preserveCase: { type: 'boolean' },
                        findInSelection: { type: 'boolean' },
                    }
                }
            }]
    };
    class StartFindWithArgsAction extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: findModel_1.FIND_IDS.StartFindWithArgs,
                label: nls.localize(851, "Find With Arguments"),
                alias: 'Find With Arguments',
                precondition: undefined,
                kbOpts: {
                    kbExpr: null,
                    primary: 0,
                    weight: 100 /* KeybindingWeight.EditorContrib */
                },
                metadata: findArgDescription
            });
        }
        async run(accessor, editor, args) {
            const controller = CommonFindController.get(editor);
            if (controller) {
                const newState = args ? {
                    searchString: args.searchString,
                    replaceString: args.replaceString,
                    isReplaceRevealed: args.replaceString !== undefined,
                    isRegex: args.isRegex,
                    // isRegexOverride: args.regexOverride,
                    wholeWord: args.matchWholeWord,
                    // wholeWordOverride: args.wholeWordOverride,
                    matchCase: args.isCaseSensitive,
                    // matchCaseOverride: args.matchCaseOverride,
                    preserveCase: args.preserveCase,
                    // preserveCaseOverride: args.preserveCaseOverride,
                } : {};
                await controller.start({
                    forceRevealReplace: false,
                    seedSearchStringFromSelection: (controller.getState().searchString.length === 0) && editor.getOption(41 /* EditorOption.find */).seedSearchStringFromSelection !== 'never' ? 'single' : 'none',
                    seedSearchStringFromNonEmptySelection: editor.getOption(41 /* EditorOption.find */).seedSearchStringFromSelection === 'selection',
                    seedSearchStringFromGlobalClipboard: true,
                    shouldFocus: 1 /* FindStartFocusAction.FocusFindInput */,
                    shouldAnimate: true,
                    updateSearchScope: args?.findInSelection || false,
                    loop: editor.getOption(41 /* EditorOption.find */).loop
                }, newState);
                controller.setGlobalBufferTerm(controller.getState().searchString);
            }
        }
    }
    exports.StartFindWithArgsAction = StartFindWithArgsAction;
    class StartFindWithSelectionAction extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: findModel_1.FIND_IDS.StartFindWithSelection,
                label: nls.localize(852, "Find With Selection"),
                alias: 'Find With Selection',
                precondition: undefined,
                kbOpts: {
                    kbExpr: null,
                    primary: 0,
                    mac: {
                        primary: 2048 /* KeyMod.CtrlCmd */ | 35 /* KeyCode.KeyE */,
                    },
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
        async run(accessor, editor) {
            const controller = CommonFindController.get(editor);
            if (controller) {
                await controller.start({
                    forceRevealReplace: false,
                    seedSearchStringFromSelection: 'multiple',
                    seedSearchStringFromNonEmptySelection: false,
                    seedSearchStringFromGlobalClipboard: false,
                    shouldFocus: 0 /* FindStartFocusAction.NoFocusChange */,
                    shouldAnimate: true,
                    updateSearchScope: false,
                    loop: editor.getOption(41 /* EditorOption.find */).loop
                });
                controller.setGlobalBufferTerm(controller.getState().searchString);
            }
        }
    }
    exports.StartFindWithSelectionAction = StartFindWithSelectionAction;
    class MatchFindAction extends editorExtensions_1.EditorAction {
        async run(accessor, editor) {
            const controller = CommonFindController.get(editor);
            if (controller && !this._run(controller)) {
                await controller.start({
                    forceRevealReplace: false,
                    seedSearchStringFromSelection: (controller.getState().searchString.length === 0) && editor.getOption(41 /* EditorOption.find */).seedSearchStringFromSelection !== 'never' ? 'single' : 'none',
                    seedSearchStringFromNonEmptySelection: editor.getOption(41 /* EditorOption.find */).seedSearchStringFromSelection === 'selection',
                    seedSearchStringFromGlobalClipboard: true,
                    shouldFocus: 0 /* FindStartFocusAction.NoFocusChange */,
                    shouldAnimate: true,
                    updateSearchScope: false,
                    loop: editor.getOption(41 /* EditorOption.find */).loop
                });
                this._run(controller);
            }
        }
    }
    exports.MatchFindAction = MatchFindAction;
    class NextMatchFindAction extends MatchFindAction {
        constructor() {
            super({
                id: findModel_1.FIND_IDS.NextMatchFindAction,
                label: nls.localize(853, "Find Next"),
                alias: 'Find Next',
                precondition: undefined,
                kbOpts: [{
                        kbExpr: editorContextKeys_1.EditorContextKeys.focus,
                        primary: 61 /* KeyCode.F3 */,
                        mac: { primary: 2048 /* KeyMod.CtrlCmd */ | 37 /* KeyCode.KeyG */, secondary: [61 /* KeyCode.F3 */] },
                        weight: 100 /* KeybindingWeight.EditorContrib */
                    }, {
                        kbExpr: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.focus, findModel_1.CONTEXT_FIND_INPUT_FOCUSED),
                        primary: 3 /* KeyCode.Enter */,
                        weight: 100 /* KeybindingWeight.EditorContrib */
                    }]
            });
        }
        _run(controller) {
            const result = controller.moveToNextMatch();
            if (result) {
                controller.editor.pushUndoStop();
                return true;
            }
            return false;
        }
    }
    exports.NextMatchFindAction = NextMatchFindAction;
    class PreviousMatchFindAction extends MatchFindAction {
        constructor() {
            super({
                id: findModel_1.FIND_IDS.PreviousMatchFindAction,
                label: nls.localize(854, "Find Previous"),
                alias: 'Find Previous',
                precondition: undefined,
                kbOpts: [{
                        kbExpr: editorContextKeys_1.EditorContextKeys.focus,
                        primary: 1024 /* KeyMod.Shift */ | 61 /* KeyCode.F3 */,
                        mac: { primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 37 /* KeyCode.KeyG */, secondary: [1024 /* KeyMod.Shift */ | 61 /* KeyCode.F3 */] },
                        weight: 100 /* KeybindingWeight.EditorContrib */
                    }, {
                        kbExpr: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.focus, findModel_1.CONTEXT_FIND_INPUT_FOCUSED),
                        primary: 1024 /* KeyMod.Shift */ | 3 /* KeyCode.Enter */,
                        weight: 100 /* KeybindingWeight.EditorContrib */
                    }
                ]
            });
        }
        _run(controller) {
            return controller.moveToPrevMatch();
        }
    }
    exports.PreviousMatchFindAction = PreviousMatchFindAction;
    class MoveToMatchFindAction extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: findModel_1.FIND_IDS.GoToMatchFindAction,
                label: nls.localize(855, "Go to Match..."),
                alias: 'Go to Match...',
                precondition: findModel_1.CONTEXT_FIND_WIDGET_VISIBLE
            });
            this._highlightDecorations = [];
        }
        run(accessor, editor, args) {
            const controller = CommonFindController.get(editor);
            if (!controller) {
                return;
            }
            const matchesCount = controller.getState().matchesCount;
            if (matchesCount < 1) {
                const notificationService = accessor.get(notification_1.INotificationService);
                notificationService.notify({
                    severity: notification_1.Severity.Warning,
                    message: nls.localize(856, "No matches. Try searching for something else.")
                });
                return;
            }
            const quickInputService = accessor.get(quickInput_1.IQuickInputService);
            const disposables = new lifecycle_1.DisposableStore();
            const inputBox = disposables.add(quickInputService.createInputBox());
            inputBox.placeholder = nls.localize(857, "Type a number to go to a specific match (between 1 and {0})", matchesCount);
            const toFindMatchIndex = (value) => {
                const index = parseInt(value);
                if (isNaN(index)) {
                    return undefined;
                }
                const matchCount = controller.getState().matchesCount;
                if (index > 0 && index <= matchCount) {
                    return index - 1; // zero based
                }
                else if (index < 0 && index >= -matchCount) {
                    return matchCount + index;
                }
                return undefined;
            };
            const updatePickerAndEditor = (value) => {
                const index = toFindMatchIndex(value);
                if (typeof index === 'number') {
                    // valid
                    inputBox.validationMessage = undefined;
                    controller.goToMatch(index);
                    const currentMatch = controller.getState().currentMatch;
                    if (currentMatch) {
                        this.addDecorations(editor, currentMatch);
                    }
                }
                else {
                    inputBox.validationMessage = nls.localize(858, "Please type a number between 1 and {0}", controller.getState().matchesCount);
                    this.clearDecorations(editor);
                }
            };
            disposables.add(inputBox.onDidChangeValue(value => {
                updatePickerAndEditor(value);
            }));
            disposables.add(inputBox.onDidAccept(() => {
                const index = toFindMatchIndex(inputBox.value);
                if (typeof index === 'number') {
                    controller.goToMatch(index);
                    inputBox.hide();
                }
                else {
                    inputBox.validationMessage = nls.localize(859, "Please type a number between 1 and {0}", controller.getState().matchesCount);
                }
            }));
            disposables.add(inputBox.onDidHide(() => {
                this.clearDecorations(editor);
                disposables.dispose();
            }));
            inputBox.show();
        }
        clearDecorations(editor) {
            editor.changeDecorations(changeAccessor => {
                this._highlightDecorations = changeAccessor.deltaDecorations(this._highlightDecorations, []);
            });
        }
        addDecorations(editor, range) {
            editor.changeDecorations(changeAccessor => {
                this._highlightDecorations = changeAccessor.deltaDecorations(this._highlightDecorations, [
                    {
                        range,
                        options: {
                            description: 'find-match-quick-access-range-highlight',
                            className: 'rangeHighlight',
                            isWholeLine: true
                        }
                    },
                    {
                        range,
                        options: {
                            description: 'find-match-quick-access-range-highlight-overview',
                            overviewRuler: {
                                color: (0, themeService_1.themeColorFromId)(editorColorRegistry_1.overviewRulerRangeHighlight),
                                position: model_1.OverviewRulerLane.Full
                            }
                        }
                    }
                ]);
            });
        }
    }
    exports.MoveToMatchFindAction = MoveToMatchFindAction;
    class SelectionMatchFindAction extends editorExtensions_1.EditorAction {
        async run(accessor, editor) {
            const controller = CommonFindController.get(editor);
            if (!controller) {
                return;
            }
            const selectionSearchString = getSelectionSearchString(editor, 'single', false);
            if (selectionSearchString) {
                controller.setSearchString(selectionSearchString);
            }
            if (!this._run(controller)) {
                await controller.start({
                    forceRevealReplace: false,
                    seedSearchStringFromSelection: 'none',
                    seedSearchStringFromNonEmptySelection: false,
                    seedSearchStringFromGlobalClipboard: false,
                    shouldFocus: 0 /* FindStartFocusAction.NoFocusChange */,
                    shouldAnimate: true,
                    updateSearchScope: false,
                    loop: editor.getOption(41 /* EditorOption.find */).loop
                });
                this._run(controller);
            }
        }
    }
    exports.SelectionMatchFindAction = SelectionMatchFindAction;
    class NextSelectionMatchFindAction extends SelectionMatchFindAction {
        constructor() {
            super({
                id: findModel_1.FIND_IDS.NextSelectionMatchFindAction,
                label: nls.localize(860, "Find Next Selection"),
                alias: 'Find Next Selection',
                precondition: undefined,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.focus,
                    primary: 2048 /* KeyMod.CtrlCmd */ | 61 /* KeyCode.F3 */,
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
        _run(controller) {
            return controller.moveToNextMatch();
        }
    }
    exports.NextSelectionMatchFindAction = NextSelectionMatchFindAction;
    class PreviousSelectionMatchFindAction extends SelectionMatchFindAction {
        constructor() {
            super({
                id: findModel_1.FIND_IDS.PreviousSelectionMatchFindAction,
                label: nls.localize(861, "Find Previous Selection"),
                alias: 'Find Previous Selection',
                precondition: undefined,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.focus,
                    primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 61 /* KeyCode.F3 */,
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
        _run(controller) {
            return controller.moveToPrevMatch();
        }
    }
    exports.PreviousSelectionMatchFindAction = PreviousSelectionMatchFindAction;
    exports.StartFindReplaceAction = (0, editorExtensions_1.registerMultiEditorAction)(new editorExtensions_1.MultiEditorAction({
        id: findModel_1.FIND_IDS.StartFindReplaceAction,
        label: nls.localize(862, "Replace"),
        alias: 'Replace',
        precondition: contextkey_1.ContextKeyExpr.or(editorContextKeys_1.EditorContextKeys.focus, contextkey_1.ContextKeyExpr.has('editorIsOpen')),
        kbOpts: {
            kbExpr: null,
            primary: 2048 /* KeyMod.CtrlCmd */ | 38 /* KeyCode.KeyH */,
            mac: { primary: 2048 /* KeyMod.CtrlCmd */ | 512 /* KeyMod.Alt */ | 36 /* KeyCode.KeyF */ },
            weight: 100 /* KeybindingWeight.EditorContrib */
        },
        menuOpts: {
            menuId: actions_1.MenuId.MenubarEditMenu,
            group: '3_find',
            title: nls.localize(863, "&&Replace"),
            order: 2
        }
    }));
    exports.StartFindReplaceAction.addImplementation(0, (accessor, editor, args) => {
        if (!editor.hasModel() || editor.getOption(92 /* EditorOption.readOnly */)) {
            return false;
        }
        const controller = CommonFindController.get(editor);
        if (!controller) {
            return false;
        }
        const currentSelection = editor.getSelection();
        const findInputFocused = controller.isFindInputFocused();
        // we only seed search string from selection when the current selection is single line and not empty,
        // + the find input is not focused
        const seedSearchStringFromSelection = !currentSelection.isEmpty()
            && currentSelection.startLineNumber === currentSelection.endLineNumber
            && (editor.getOption(41 /* EditorOption.find */).seedSearchStringFromSelection !== 'never')
            && !findInputFocused;
        /*
        * if the existing search string in find widget is empty and we don't seed search string from selection, it means the Find Input is still empty, so we should focus the Find Input instead of Replace Input.
    
        * findInputFocused true -> seedSearchStringFromSelection false, FocusReplaceInput
        * findInputFocused false, seedSearchStringFromSelection true FocusReplaceInput
        * findInputFocused false seedSearchStringFromSelection false FocusFindInput
        */
        const shouldFocus = (findInputFocused || seedSearchStringFromSelection) ?
            2 /* FindStartFocusAction.FocusReplaceInput */ : 1 /* FindStartFocusAction.FocusFindInput */;
        return controller.start({
            forceRevealReplace: true,
            seedSearchStringFromSelection: seedSearchStringFromSelection ? 'single' : 'none',
            seedSearchStringFromNonEmptySelection: editor.getOption(41 /* EditorOption.find */).seedSearchStringFromSelection === 'selection',
            seedSearchStringFromGlobalClipboard: editor.getOption(41 /* EditorOption.find */).seedSearchStringFromSelection !== 'never',
            shouldFocus: shouldFocus,
            shouldAnimate: true,
            updateSearchScope: false,
            loop: editor.getOption(41 /* EditorOption.find */).loop
        });
    });
    (0, editorExtensions_1.registerEditorContribution)(CommonFindController.ID, FindController, 0 /* EditorContributionInstantiation.Eager */); // eager because it uses `saveViewState`/`restoreViewState`
    (0, editorExtensions_1.registerEditorAction)(StartFindWithArgsAction);
    (0, editorExtensions_1.registerEditorAction)(StartFindWithSelectionAction);
    (0, editorExtensions_1.registerEditorAction)(NextMatchFindAction);
    (0, editorExtensions_1.registerEditorAction)(PreviousMatchFindAction);
    (0, editorExtensions_1.registerEditorAction)(MoveToMatchFindAction);
    (0, editorExtensions_1.registerEditorAction)(NextSelectionMatchFindAction);
    (0, editorExtensions_1.registerEditorAction)(PreviousSelectionMatchFindAction);
    const FindCommand = editorExtensions_1.EditorCommand.bindToContribution(CommonFindController.get);
    (0, editorExtensions_1.registerEditorCommand)(new FindCommand({
        id: findModel_1.FIND_IDS.CloseFindWidgetCommand,
        precondition: findModel_1.CONTEXT_FIND_WIDGET_VISIBLE,
        handler: x => x.closeFindWidget(),
        kbOpts: {
            weight: 100 /* KeybindingWeight.EditorContrib */ + 5,
            kbExpr: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.focus, contextkey_1.ContextKeyExpr.not('isComposing')),
            primary: 9 /* KeyCode.Escape */,
            secondary: [1024 /* KeyMod.Shift */ | 9 /* KeyCode.Escape */]
        }
    }));
    (0, editorExtensions_1.registerEditorCommand)(new FindCommand({
        id: findModel_1.FIND_IDS.ToggleCaseSensitiveCommand,
        precondition: undefined,
        handler: x => x.toggleCaseSensitive(),
        kbOpts: {
            weight: 100 /* KeybindingWeight.EditorContrib */ + 5,
            kbExpr: editorContextKeys_1.EditorContextKeys.focus,
            primary: findModel_1.ToggleCaseSensitiveKeybinding.primary,
            mac: findModel_1.ToggleCaseSensitiveKeybinding.mac,
            win: findModel_1.ToggleCaseSensitiveKeybinding.win,
            linux: findModel_1.ToggleCaseSensitiveKeybinding.linux
        }
    }));
    (0, editorExtensions_1.registerEditorCommand)(new FindCommand({
        id: findModel_1.FIND_IDS.ToggleWholeWordCommand,
        precondition: undefined,
        handler: x => x.toggleWholeWords(),
        kbOpts: {
            weight: 100 /* KeybindingWeight.EditorContrib */ + 5,
            kbExpr: editorContextKeys_1.EditorContextKeys.focus,
            primary: findModel_1.ToggleWholeWordKeybinding.primary,
            mac: findModel_1.ToggleWholeWordKeybinding.mac,
            win: findModel_1.ToggleWholeWordKeybinding.win,
            linux: findModel_1.ToggleWholeWordKeybinding.linux
        }
    }));
    (0, editorExtensions_1.registerEditorCommand)(new FindCommand({
        id: findModel_1.FIND_IDS.ToggleRegexCommand,
        precondition: undefined,
        handler: x => x.toggleRegex(),
        kbOpts: {
            weight: 100 /* KeybindingWeight.EditorContrib */ + 5,
            kbExpr: editorContextKeys_1.EditorContextKeys.focus,
            primary: findModel_1.ToggleRegexKeybinding.primary,
            mac: findModel_1.ToggleRegexKeybinding.mac,
            win: findModel_1.ToggleRegexKeybinding.win,
            linux: findModel_1.ToggleRegexKeybinding.linux
        }
    }));
    (0, editorExtensions_1.registerEditorCommand)(new FindCommand({
        id: findModel_1.FIND_IDS.ToggleSearchScopeCommand,
        precondition: undefined,
        handler: x => x.toggleSearchScope(),
        kbOpts: {
            weight: 100 /* KeybindingWeight.EditorContrib */ + 5,
            kbExpr: editorContextKeys_1.EditorContextKeys.focus,
            primary: findModel_1.ToggleSearchScopeKeybinding.primary,
            mac: findModel_1.ToggleSearchScopeKeybinding.mac,
            win: findModel_1.ToggleSearchScopeKeybinding.win,
            linux: findModel_1.ToggleSearchScopeKeybinding.linux
        }
    }));
    (0, editorExtensions_1.registerEditorCommand)(new FindCommand({
        id: findModel_1.FIND_IDS.TogglePreserveCaseCommand,
        precondition: undefined,
        handler: x => x.togglePreserveCase(),
        kbOpts: {
            weight: 100 /* KeybindingWeight.EditorContrib */ + 5,
            kbExpr: editorContextKeys_1.EditorContextKeys.focus,
            primary: findModel_1.TogglePreserveCaseKeybinding.primary,
            mac: findModel_1.TogglePreserveCaseKeybinding.mac,
            win: findModel_1.TogglePreserveCaseKeybinding.win,
            linux: findModel_1.TogglePreserveCaseKeybinding.linux
        }
    }));
    (0, editorExtensions_1.registerEditorCommand)(new FindCommand({
        id: findModel_1.FIND_IDS.ReplaceOneAction,
        precondition: findModel_1.CONTEXT_FIND_WIDGET_VISIBLE,
        handler: x => x.replace(),
        kbOpts: {
            weight: 100 /* KeybindingWeight.EditorContrib */ + 5,
            kbExpr: editorContextKeys_1.EditorContextKeys.focus,
            primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 22 /* KeyCode.Digit1 */
        }
    }));
    (0, editorExtensions_1.registerEditorCommand)(new FindCommand({
        id: findModel_1.FIND_IDS.ReplaceOneAction,
        precondition: findModel_1.CONTEXT_FIND_WIDGET_VISIBLE,
        handler: x => x.replace(),
        kbOpts: {
            weight: 100 /* KeybindingWeight.EditorContrib */ + 5,
            kbExpr: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.focus, findModel_1.CONTEXT_REPLACE_INPUT_FOCUSED),
            primary: 3 /* KeyCode.Enter */
        }
    }));
    (0, editorExtensions_1.registerEditorCommand)(new FindCommand({
        id: findModel_1.FIND_IDS.ReplaceAllAction,
        precondition: findModel_1.CONTEXT_FIND_WIDGET_VISIBLE,
        handler: x => x.replaceAll(),
        kbOpts: {
            weight: 100 /* KeybindingWeight.EditorContrib */ + 5,
            kbExpr: editorContextKeys_1.EditorContextKeys.focus,
            primary: 2048 /* KeyMod.CtrlCmd */ | 512 /* KeyMod.Alt */ | 3 /* KeyCode.Enter */
        }
    }));
    (0, editorExtensions_1.registerEditorCommand)(new FindCommand({
        id: findModel_1.FIND_IDS.ReplaceAllAction,
        precondition: findModel_1.CONTEXT_FIND_WIDGET_VISIBLE,
        handler: x => x.replaceAll(),
        kbOpts: {
            weight: 100 /* KeybindingWeight.EditorContrib */ + 5,
            kbExpr: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.focus, findModel_1.CONTEXT_REPLACE_INPUT_FOCUSED),
            primary: undefined,
            mac: {
                primary: 2048 /* KeyMod.CtrlCmd */ | 3 /* KeyCode.Enter */,
            }
        }
    }));
    (0, editorExtensions_1.registerEditorCommand)(new FindCommand({
        id: findModel_1.FIND_IDS.SelectAllMatchesAction,
        precondition: findModel_1.CONTEXT_FIND_WIDGET_VISIBLE,
        handler: x => x.selectAllMatches(),
        kbOpts: {
            weight: 100 /* KeybindingWeight.EditorContrib */ + 5,
            kbExpr: editorContextKeys_1.EditorContextKeys.focus,
            primary: 512 /* KeyMod.Alt */ | 3 /* KeyCode.Enter */
        }
    }));
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[424/*vs/editor/contrib/folding/browser/foldingDecorations*/], __M([1/*require*/,0/*exports*/,26/*vs/base/common/codicons*/,35/*vs/editor/common/model/textModel*/,3/*vs/nls*/,32/*vs/platform/theme/common/colorRegistry*/,71/*vs/platform/theme/common/iconRegistry*/,25/*vs/platform/theme/common/themeService*/,30/*vs/base/common/themables*/]), function (require, exports, codicons_1, textModel_1, nls_1, colorRegistry_1, iconRegistry_1, themeService_1, themables_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.FoldingDecorationProvider = exports.foldingManualExpandedIcon = exports.foldingManualCollapsedIcon = exports.foldingCollapsedIcon = exports.foldingExpandedIcon = void 0;
    const foldBackground = (0, colorRegistry_1.registerColor)('editor.foldBackground', { light: (0, colorRegistry_1.transparent)(colorRegistry_1.editorSelectionBackground, 0.3), dark: (0, colorRegistry_1.transparent)(colorRegistry_1.editorSelectionBackground, 0.3), hcDark: null, hcLight: null }, (0, nls_1.localize)(910, "Background color behind folded ranges. The color must not be opaque so as not to hide underlying decorations."), true);
    (0, colorRegistry_1.registerColor)('editor.foldPlaceholderForeground', { light: '#808080', dark: '#808080', hcDark: null, hcLight: null }, (0, nls_1.localize)(911, "Color of the collapsed text after the first line of a folded range."));
    (0, colorRegistry_1.registerColor)('editorGutter.foldingControlForeground', colorRegistry_1.iconForeground, (0, nls_1.localize)(912, 'Color of the folding control in the editor gutter.'));
    exports.foldingExpandedIcon = (0, iconRegistry_1.registerIcon)('folding-expanded', codicons_1.Codicon.chevronDown, (0, nls_1.localize)(913, 'Icon for expanded ranges in the editor glyph margin.'));
    exports.foldingCollapsedIcon = (0, iconRegistry_1.registerIcon)('folding-collapsed', codicons_1.Codicon.chevronRight, (0, nls_1.localize)(914, 'Icon for collapsed ranges in the editor glyph margin.'));
    exports.foldingManualCollapsedIcon = (0, iconRegistry_1.registerIcon)('folding-manual-collapsed', exports.foldingCollapsedIcon, (0, nls_1.localize)(915, 'Icon for manually collapsed ranges in the editor glyph margin.'));
    exports.foldingManualExpandedIcon = (0, iconRegistry_1.registerIcon)('folding-manual-expanded', exports.foldingExpandedIcon, (0, nls_1.localize)(916, 'Icon for manually expanded ranges in the editor glyph margin.'));
    const foldedBackgroundMinimap = { color: (0, themeService_1.themeColorFromId)(foldBackground), position: 1 /* MinimapPosition.Inline */ };
    const collapsed = (0, nls_1.localize)(917, "Click to expand the range.");
    const expanded = (0, nls_1.localize)(918, "Click to collapse the range.");
    class FoldingDecorationProvider {
        static { this.COLLAPSED_VISUAL_DECORATION = textModel_1.ModelDecorationOptions.register({
            description: 'folding-collapsed-visual-decoration',
            stickiness: 0 /* TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges */,
            afterContentClassName: 'inline-folded',
            isWholeLine: true,
            linesDecorationsTooltip: collapsed,
            firstLineDecorationClassName: themables_1.ThemeIcon.asClassName(exports.foldingCollapsedIcon),
        }); }
        static { this.COLLAPSED_HIGHLIGHTED_VISUAL_DECORATION = textModel_1.ModelDecorationOptions.register({
            description: 'folding-collapsed-highlighted-visual-decoration',
            stickiness: 0 /* TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges */,
            afterContentClassName: 'inline-folded',
            className: 'folded-background',
            minimap: foldedBackgroundMinimap,
            isWholeLine: true,
            linesDecorationsTooltip: collapsed,
            firstLineDecorationClassName: themables_1.ThemeIcon.asClassName(exports.foldingCollapsedIcon)
        }); }
        static { this.MANUALLY_COLLAPSED_VISUAL_DECORATION = textModel_1.ModelDecorationOptions.register({
            description: 'folding-manually-collapsed-visual-decoration',
            stickiness: 0 /* TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges */,
            afterContentClassName: 'inline-folded',
            isWholeLine: true,
            linesDecorationsTooltip: collapsed,
            firstLineDecorationClassName: themables_1.ThemeIcon.asClassName(exports.foldingManualCollapsedIcon)
        }); }
        static { this.MANUALLY_COLLAPSED_HIGHLIGHTED_VISUAL_DECORATION = textModel_1.ModelDecorationOptions.register({
            description: 'folding-manually-collapsed-highlighted-visual-decoration',
            stickiness: 0 /* TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges */,
            afterContentClassName: 'inline-folded',
            className: 'folded-background',
            minimap: foldedBackgroundMinimap,
            isWholeLine: true,
            linesDecorationsTooltip: collapsed,
            firstLineDecorationClassName: themables_1.ThemeIcon.asClassName(exports.foldingManualCollapsedIcon)
        }); }
        static { this.NO_CONTROLS_COLLAPSED_RANGE_DECORATION = textModel_1.ModelDecorationOptions.register({
            description: 'folding-no-controls-range-decoration',
            stickiness: 0 /* TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges */,
            afterContentClassName: 'inline-folded',
            isWholeLine: true,
            linesDecorationsTooltip: collapsed,
        }); }
        static { this.NO_CONTROLS_COLLAPSED_HIGHLIGHTED_RANGE_DECORATION = textModel_1.ModelDecorationOptions.register({
            description: 'folding-no-controls-range-decoration',
            stickiness: 0 /* TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges */,
            afterContentClassName: 'inline-folded',
            className: 'folded-background',
            minimap: foldedBackgroundMinimap,
            isWholeLine: true,
            linesDecorationsTooltip: collapsed,
        }); }
        static { this.EXPANDED_VISUAL_DECORATION = textModel_1.ModelDecorationOptions.register({
            description: 'folding-expanded-visual-decoration',
            stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */,
            isWholeLine: true,
            firstLineDecorationClassName: 'alwaysShowFoldIcons ' + themables_1.ThemeIcon.asClassName(exports.foldingExpandedIcon),
            linesDecorationsTooltip: expanded,
        }); }
        static { this.EXPANDED_AUTO_HIDE_VISUAL_DECORATION = textModel_1.ModelDecorationOptions.register({
            description: 'folding-expanded-auto-hide-visual-decoration',
            stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */,
            isWholeLine: true,
            firstLineDecorationClassName: themables_1.ThemeIcon.asClassName(exports.foldingExpandedIcon),
            linesDecorationsTooltip: expanded,
        }); }
        static { this.MANUALLY_EXPANDED_VISUAL_DECORATION = textModel_1.ModelDecorationOptions.register({
            description: 'folding-manually-expanded-visual-decoration',
            stickiness: 0 /* TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges */,
            isWholeLine: true,
            firstLineDecorationClassName: 'alwaysShowFoldIcons ' + themables_1.ThemeIcon.asClassName(exports.foldingManualExpandedIcon),
            linesDecorationsTooltip: expanded,
        }); }
        static { this.MANUALLY_EXPANDED_AUTO_HIDE_VISUAL_DECORATION = textModel_1.ModelDecorationOptions.register({
            description: 'folding-manually-expanded-auto-hide-visual-decoration',
            stickiness: 0 /* TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges */,
            isWholeLine: true,
            firstLineDecorationClassName: themables_1.ThemeIcon.asClassName(exports.foldingManualExpandedIcon),
            linesDecorationsTooltip: expanded,
        }); }
        static { this.NO_CONTROLS_EXPANDED_RANGE_DECORATION = textModel_1.ModelDecorationOptions.register({
            description: 'folding-no-controls-range-decoration',
            stickiness: 0 /* TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges */,
            isWholeLine: true
        }); }
        static { this.HIDDEN_RANGE_DECORATION = textModel_1.ModelDecorationOptions.register({
            description: 'folding-hidden-range-decoration',
            stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */
        }); }
        constructor(editor) {
            this.editor = editor;
            this.showFoldingControls = 'mouseover';
            this.showFoldingHighlights = true;
        }
        getDecorationOption(isCollapsed, isHidden, isManual) {
            if (isHidden) { // is inside another collapsed region
                return FoldingDecorationProvider.HIDDEN_RANGE_DECORATION;
            }
            if (this.showFoldingControls === 'never') {
                if (isCollapsed) {
                    return this.showFoldingHighlights ? FoldingDecorationProvider.NO_CONTROLS_COLLAPSED_HIGHLIGHTED_RANGE_DECORATION : FoldingDecorationProvider.NO_CONTROLS_COLLAPSED_RANGE_DECORATION;
                }
                return FoldingDecorationProvider.NO_CONTROLS_EXPANDED_RANGE_DECORATION;
            }
            if (isCollapsed) {
                return isManual ?
                    (this.showFoldingHighlights ? FoldingDecorationProvider.MANUALLY_COLLAPSED_HIGHLIGHTED_VISUAL_DECORATION : FoldingDecorationProvider.MANUALLY_COLLAPSED_VISUAL_DECORATION)
                    : (this.showFoldingHighlights ? FoldingDecorationProvider.COLLAPSED_HIGHLIGHTED_VISUAL_DECORATION : FoldingDecorationProvider.COLLAPSED_VISUAL_DECORATION);
            }
            else if (this.showFoldingControls === 'mouseover') {
                return isManual ? FoldingDecorationProvider.MANUALLY_EXPANDED_AUTO_HIDE_VISUAL_DECORATION : FoldingDecorationProvider.EXPANDED_AUTO_HIDE_VISUAL_DECORATION;
            }
            else {
                return isManual ? FoldingDecorationProvider.MANUALLY_EXPANDED_VISUAL_DECORATION : FoldingDecorationProvider.EXPANDED_VISUAL_DECORATION;
            }
        }
        changeDecorations(callback) {
            return this.editor.changeDecorations(callback);
        }
        removeDecorations(decorationIds) {
            this.editor.removeDecorations(decorationIds);
        }
    }
    exports.FoldingDecorationProvider = FoldingDecorationProvider;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[289/*vs/editor/contrib/folding/browser/folding*/], __M([1/*require*/,0/*exports*/,14/*vs/base/common/async*/,18/*vs/base/common/cancellation*/,8/*vs/base/common/errors*/,72/*vs/base/common/keyCodes*/,2/*vs/base/common/lifecycle*/,11/*vs/base/common/strings*/,19/*vs/base/common/types*/,143/*vs/editor/browser/stableEditorScroll*/,15/*vs/editor/browser/editorExtensions*/,20/*vs/editor/common/editorContextKeys*/,27/*vs/editor/common/languages*/,36/*vs/editor/common/languages/languageConfigurationRegistry*/,334/*vs/editor/contrib/folding/browser/foldingModel*/,613/*vs/editor/contrib/folding/browser/hiddenRangeModel*/,335/*vs/editor/contrib/folding/browser/indentRangeProvider*/,3/*vs/nls*/,12/*vs/platform/contextkey/common/contextkey*/,424/*vs/editor/contrib/folding/browser/foldingDecorations*/,203/*vs/editor/contrib/folding/browser/foldingRanges*/,336/*vs/editor/contrib/folding/browser/syntaxRangeProvider*/,50/*vs/platform/notification/common/notification*/,79/*vs/editor/common/services/languageFeatureDebounce*/,54/*vs/base/common/stopwatch*/,17/*vs/editor/common/services/languageFeatures*/,6/*vs/base/common/event*/,24/*vs/platform/commands/common/commands*/,22/*vs/base/common/uri*/,51/*vs/editor/common/services/model*/,28/*vs/platform/configuration/common/configuration*/,511/*vs/css!vs/editor/contrib/folding/browser/folding*/]), function (require, exports, async_1, cancellation_1, errors_1, keyCodes_1, lifecycle_1, strings_1, types, stableEditorScroll_1, editorExtensions_1, editorContextKeys_1, languages_1, languageConfigurationRegistry_1, foldingModel_1, hiddenRangeModel_1, indentRangeProvider_1, nls, contextkey_1, foldingDecorations_1, foldingRanges_1, syntaxRangeProvider_1, notification_1, languageFeatureDebounce_1, stopwatch_1, languageFeatures_1, event_1, commands_1, uri_1, model_1, configuration_1) {
    "use strict";
    var FoldingController_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.RangesLimitReporter = exports.FoldingController = void 0;
    exports.toSelectedLines = toSelectedLines;
    const CONTEXT_FOLDING_ENABLED = new contextkey_1.RawContextKey('foldingEnabled', false);
    let FoldingController = class FoldingController extends lifecycle_1.Disposable {
        static { FoldingController_1 = this; }
        static { this.ID = 'editor.contrib.folding'; }
        static get(editor) {
            return editor.getContribution(FoldingController_1.ID);
        }
        static getFoldingRangeProviders(languageFeaturesService, model) {
            const foldingRangeProviders = languageFeaturesService.foldingRangeProvider.ordered(model);
            return (FoldingController_1._foldingRangeSelector?.(foldingRangeProviders, model)) ?? foldingRangeProviders;
        }
        constructor(editor, contextKeyService, languageConfigurationService, notificationService, languageFeatureDebounceService, languageFeaturesService) {
            super();
            this.contextKeyService = contextKeyService;
            this.languageConfigurationService = languageConfigurationService;
            this.languageFeaturesService = languageFeaturesService;
            this.localToDispose = this._register(new lifecycle_1.DisposableStore());
            this.editor = editor;
            this._foldingLimitReporter = new RangesLimitReporter(editor);
            const options = this.editor.getOptions();
            this._isEnabled = options.get(43 /* EditorOption.folding */);
            this._useFoldingProviders = options.get(44 /* EditorOption.foldingStrategy */) !== 'indentation';
            this._unfoldOnClickAfterEndOfLine = options.get(48 /* EditorOption.unfoldOnClickAfterEndOfLine */);
            this._restoringViewState = false;
            this._currentModelHasFoldedImports = false;
            this._foldingImportsByDefault = options.get(46 /* EditorOption.foldingImportsByDefault */);
            this.updateDebounceInfo = languageFeatureDebounceService.for(languageFeaturesService.foldingRangeProvider, 'Folding', { min: 200 });
            this.foldingModel = null;
            this.hiddenRangeModel = null;
            this.rangeProvider = null;
            this.foldingRegionPromise = null;
            this.foldingModelPromise = null;
            this.updateScheduler = null;
            this.cursorChangedScheduler = null;
            this.mouseDownInfo = null;
            this.foldingDecorationProvider = new foldingDecorations_1.FoldingDecorationProvider(editor);
            this.foldingDecorationProvider.showFoldingControls = options.get(111 /* EditorOption.showFoldingControls */);
            this.foldingDecorationProvider.showFoldingHighlights = options.get(45 /* EditorOption.foldingHighlight */);
            this.foldingEnabled = CONTEXT_FOLDING_ENABLED.bindTo(this.contextKeyService);
            this.foldingEnabled.set(this._isEnabled);
            this._register(this.editor.onDidChangeModel(() => this.onModelChanged()));
            this._register(this.editor.onDidChangeConfiguration((e) => {
                if (e.hasChanged(43 /* EditorOption.folding */)) {
                    this._isEnabled = this.editor.getOptions().get(43 /* EditorOption.folding */);
                    this.foldingEnabled.set(this._isEnabled);
                    this.onModelChanged();
                }
                if (e.hasChanged(47 /* EditorOption.foldingMaximumRegions */)) {
                    this.onModelChanged();
                }
                if (e.hasChanged(111 /* EditorOption.showFoldingControls */) || e.hasChanged(45 /* EditorOption.foldingHighlight */)) {
                    const options = this.editor.getOptions();
                    this.foldingDecorationProvider.showFoldingControls = options.get(111 /* EditorOption.showFoldingControls */);
                    this.foldingDecorationProvider.showFoldingHighlights = options.get(45 /* EditorOption.foldingHighlight */);
                    this.triggerFoldingModelChanged();
                }
                if (e.hasChanged(44 /* EditorOption.foldingStrategy */)) {
                    this._useFoldingProviders = this.editor.getOptions().get(44 /* EditorOption.foldingStrategy */) !== 'indentation';
                    this.onFoldingStrategyChanged();
                }
                if (e.hasChanged(48 /* EditorOption.unfoldOnClickAfterEndOfLine */)) {
                    this._unfoldOnClickAfterEndOfLine = this.editor.getOptions().get(48 /* EditorOption.unfoldOnClickAfterEndOfLine */);
                }
                if (e.hasChanged(46 /* EditorOption.foldingImportsByDefault */)) {
                    this._foldingImportsByDefault = this.editor.getOptions().get(46 /* EditorOption.foldingImportsByDefault */);
                }
            }));
            this.onModelChanged();
        }
        /**
         * Store view state.
         */
        saveViewState() {
            const model = this.editor.getModel();
            if (!model || !this._isEnabled || model.isTooLargeForTokenization()) {
                return {};
            }
            if (this.foldingModel) { // disposed ?
                const collapsedRegions = this.foldingModel.getMemento();
                const provider = this.rangeProvider ? this.rangeProvider.id : undefined;
                return { collapsedRegions, lineCount: model.getLineCount(), provider, foldedImports: this._currentModelHasFoldedImports };
            }
            return undefined;
        }
        /**
         * Restore view state.
         */
        restoreViewState(state) {
            const model = this.editor.getModel();
            if (!model || !this._isEnabled || model.isTooLargeForTokenization() || !this.hiddenRangeModel) {
                return;
            }
            if (!state) {
                return;
            }
            this._currentModelHasFoldedImports = !!state.foldedImports;
            if (state.collapsedRegions && state.collapsedRegions.length > 0 && this.foldingModel) {
                this._restoringViewState = true;
                try {
                    this.foldingModel.applyMemento(state.collapsedRegions);
                }
                finally {
                    this._restoringViewState = false;
                }
            }
        }
        onModelChanged() {
            this.localToDispose.clear();
            const model = this.editor.getModel();
            if (!this._isEnabled || !model || model.isTooLargeForTokenization()) {
                // huge files get no view model, so they cannot support hidden areas
                return;
            }
            this._currentModelHasFoldedImports = false;
            this.foldingModel = new foldingModel_1.FoldingModel(model, this.foldingDecorationProvider);
            this.localToDispose.add(this.foldingModel);
            this.hiddenRangeModel = new hiddenRangeModel_1.HiddenRangeModel(this.foldingModel);
            this.localToDispose.add(this.hiddenRangeModel);
            this.localToDispose.add(this.hiddenRangeModel.onDidChange(hr => this.onHiddenRangesChanges(hr)));
            this.updateScheduler = new async_1.Delayer(this.updateDebounceInfo.get(model));
            this.cursorChangedScheduler = new async_1.RunOnceScheduler(() => this.revealCursor(), 200);
            this.localToDispose.add(this.cursorChangedScheduler);
            this.localToDispose.add(this.languageFeaturesService.foldingRangeProvider.onDidChange(() => this.onFoldingStrategyChanged()));
            this.localToDispose.add(this.editor.onDidChangeModelLanguageConfiguration(() => this.onFoldingStrategyChanged())); // covers model language changes as well
            this.localToDispose.add(this.editor.onDidChangeModelContent(e => this.onDidChangeModelContent(e)));
            this.localToDispose.add(this.editor.onDidChangeCursorPosition(() => this.onCursorPositionChanged()));
            this.localToDispose.add(this.editor.onMouseDown(e => this.onEditorMouseDown(e)));
            this.localToDispose.add(this.editor.onMouseUp(e => this.onEditorMouseUp(e)));
            this.localToDispose.add({
                dispose: () => {
                    if (this.foldingRegionPromise) {
                        this.foldingRegionPromise.cancel();
                        this.foldingRegionPromise = null;
                    }
                    this.updateScheduler?.cancel();
                    this.updateScheduler = null;
                    this.foldingModel = null;
                    this.foldingModelPromise = null;
                    this.hiddenRangeModel = null;
                    this.cursorChangedScheduler = null;
                    this.rangeProvider?.dispose();
                    this.rangeProvider = null;
                }
            });
            this.triggerFoldingModelChanged();
        }
        onFoldingStrategyChanged() {
            this.rangeProvider?.dispose();
            this.rangeProvider = null;
            this.triggerFoldingModelChanged();
        }
        getRangeProvider(editorModel) {
            if (this.rangeProvider) {
                return this.rangeProvider;
            }
            const indentRangeProvider = new indentRangeProvider_1.IndentRangeProvider(editorModel, this.languageConfigurationService, this._foldingLimitReporter);
            this.rangeProvider = indentRangeProvider; // fallback
            if (this._useFoldingProviders && this.foldingModel) {
                const selectedProviders = FoldingController_1.getFoldingRangeProviders(this.languageFeaturesService, editorModel);
                if (selectedProviders.length > 0) {
                    this.rangeProvider = new syntaxRangeProvider_1.SyntaxRangeProvider(editorModel, selectedProviders, () => this.triggerFoldingModelChanged(), this._foldingLimitReporter, indentRangeProvider);
                }
            }
            return this.rangeProvider;
        }
        getFoldingModel() {
            return this.foldingModelPromise;
        }
        onDidChangeModelContent(e) {
            this.hiddenRangeModel?.notifyChangeModelContent(e);
            this.triggerFoldingModelChanged();
        }
        triggerFoldingModelChanged() {
            if (this.updateScheduler) {
                if (this.foldingRegionPromise) {
                    this.foldingRegionPromise.cancel();
                    this.foldingRegionPromise = null;
                }
                this.foldingModelPromise = this.updateScheduler.trigger(() => {
                    const foldingModel = this.foldingModel;
                    if (!foldingModel) { // null if editor has been disposed, or folding turned off
                        return null;
                    }
                    const sw = new stopwatch_1.StopWatch();
                    const provider = this.getRangeProvider(foldingModel.textModel);
                    const foldingRegionPromise = this.foldingRegionPromise = (0, async_1.createCancelablePromise)(token => provider.compute(token));
                    return foldingRegionPromise.then(foldingRanges => {
                        if (foldingRanges && foldingRegionPromise === this.foldingRegionPromise) { // new request or cancelled in the meantime?
                            let scrollState;
                            if (this._foldingImportsByDefault && !this._currentModelHasFoldedImports) {
                                const hasChanges = foldingRanges.setCollapsedAllOfType(languages_1.FoldingRangeKind.Imports.value, true);
                                if (hasChanges) {
                                    scrollState = stableEditorScroll_1.StableEditorScrollState.capture(this.editor);
                                    this._currentModelHasFoldedImports = hasChanges;
                                }
                            }
                            // some cursors might have moved into hidden regions, make sure they are in expanded regions
                            const selections = this.editor.getSelections();
                            foldingModel.update(foldingRanges, toSelectedLines(selections));
                            scrollState?.restore(this.editor);
                            // update debounce info
                            const newValue = this.updateDebounceInfo.update(foldingModel.textModel, sw.elapsed());
                            if (this.updateScheduler) {
                                this.updateScheduler.defaultDelay = newValue;
                            }
                        }
                        return foldingModel;
                    });
                }).then(undefined, (err) => {
                    (0, errors_1.onUnexpectedError)(err);
                    return null;
                });
            }
        }
        onHiddenRangesChanges(hiddenRanges) {
            if (this.hiddenRangeModel && hiddenRanges.length && !this._restoringViewState) {
                const selections = this.editor.getSelections();
                if (selections) {
                    if (this.hiddenRangeModel.adjustSelections(selections)) {
                        this.editor.setSelections(selections);
                    }
                }
            }
            this.editor.setHiddenAreas(hiddenRanges, this);
        }
        onCursorPositionChanged() {
            if (this.hiddenRangeModel && this.hiddenRangeModel.hasRanges()) {
                this.cursorChangedScheduler.schedule();
            }
        }
        revealCursor() {
            const foldingModel = this.getFoldingModel();
            if (!foldingModel) {
                return;
            }
            foldingModel.then(foldingModel => {
                if (foldingModel) {
                    const selections = this.editor.getSelections();
                    if (selections && selections.length > 0) {
                        const toToggle = [];
                        for (const selection of selections) {
                            const lineNumber = selection.selectionStartLineNumber;
                            if (this.hiddenRangeModel && this.hiddenRangeModel.isHidden(lineNumber)) {
                                toToggle.push(...foldingModel.getAllRegionsAtLine(lineNumber, r => r.isCollapsed && lineNumber > r.startLineNumber));
                            }
                        }
                        if (toToggle.length) {
                            foldingModel.toggleCollapseState(toToggle);
                            this.reveal(selections[0].getPosition());
                        }
                    }
                }
            }).then(undefined, errors_1.onUnexpectedError);
        }
        onEditorMouseDown(e) {
            this.mouseDownInfo = null;
            if (!this.hiddenRangeModel || !e.target || !e.target.range) {
                return;
            }
            if (!e.event.leftButton && !e.event.middleButton) {
                return;
            }
            const range = e.target.range;
            let iconClicked = false;
            switch (e.target.type) {
                case 4 /* MouseTargetType.GUTTER_LINE_DECORATIONS */: {
                    const data = e.target.detail;
                    const offsetLeftInGutter = e.target.element.offsetLeft;
                    const gutterOffsetX = data.offsetX - offsetLeftInGutter;
                    // const gutterOffsetX = data.offsetX - data.glyphMarginWidth - data.lineNumbersWidth - data.glyphMarginLeft;
                    // TODO@joao TODO@alex TODO@martin this is such that we don't collide with dirty diff
                    if (gutterOffsetX < 4) { // the whitespace between the border and the real folding icon border is 4px
                        return;
                    }
                    iconClicked = true;
                    break;
                }
                case 7 /* MouseTargetType.CONTENT_EMPTY */: {
                    if (this._unfoldOnClickAfterEndOfLine && this.hiddenRangeModel.hasRanges()) {
                        const data = e.target.detail;
                        if (!data.isAfterLines) {
                            break;
                        }
                    }
                    return;
                }
                case 6 /* MouseTargetType.CONTENT_TEXT */: {
                    if (this.hiddenRangeModel.hasRanges()) {
                        const model = this.editor.getModel();
                        if (model && range.startColumn === model.getLineMaxColumn(range.startLineNumber)) {
                            break;
                        }
                    }
                    return;
                }
                default:
                    return;
            }
            this.mouseDownInfo = { lineNumber: range.startLineNumber, iconClicked };
        }
        onEditorMouseUp(e) {
            const foldingModel = this.foldingModel;
            if (!foldingModel || !this.mouseDownInfo || !e.target) {
                return;
            }
            const lineNumber = this.mouseDownInfo.lineNumber;
            const iconClicked = this.mouseDownInfo.iconClicked;
            const range = e.target.range;
            if (!range || range.startLineNumber !== lineNumber) {
                return;
            }
            if (iconClicked) {
                if (e.target.type !== 4 /* MouseTargetType.GUTTER_LINE_DECORATIONS */) {
                    return;
                }
            }
            else {
                const model = this.editor.getModel();
                if (!model || range.startColumn !== model.getLineMaxColumn(lineNumber)) {
                    return;
                }
            }
            const region = foldingModel.getRegionAtLine(lineNumber);
            if (region && region.startLineNumber === lineNumber) {
                const isCollapsed = region.isCollapsed;
                if (iconClicked || isCollapsed) {
                    const surrounding = e.event.altKey;
                    let toToggle = [];
                    if (surrounding) {
                        const filter = (otherRegion) => !otherRegion.containedBy(region) && !region.containedBy(otherRegion);
                        const toMaybeToggle = foldingModel.getRegionsInside(null, filter);
                        for (const r of toMaybeToggle) {
                            if (r.isCollapsed) {
                                toToggle.push(r);
                            }
                        }
                        // if any surrounding regions are folded, unfold those. Otherwise, fold all surrounding
                        if (toToggle.length === 0) {
                            toToggle = toMaybeToggle;
                        }
                    }
                    else {
                        const recursive = e.event.middleButton || e.event.shiftKey;
                        if (recursive) {
                            for (const r of foldingModel.getRegionsInside(region)) {
                                if (r.isCollapsed === isCollapsed) {
                                    toToggle.push(r);
                                }
                            }
                        }
                        // when recursive, first only collapse all children. If all are already folded or there are no children, also fold parent.
                        if (isCollapsed || !recursive || toToggle.length === 0) {
                            toToggle.push(region);
                        }
                    }
                    foldingModel.toggleCollapseState(toToggle);
                    this.reveal({ lineNumber, column: 1 });
                }
            }
        }
        reveal(position) {
            this.editor.revealPositionInCenterIfOutsideViewport(position, 0 /* ScrollType.Smooth */);
        }
    };
    exports.FoldingController = FoldingController;
    exports.FoldingController = FoldingController = FoldingController_1 = __decorate([
        __param(1, contextkey_1.IContextKeyService),
        __param(2, languageConfigurationRegistry_1.ILanguageConfigurationService),
        __param(3, notification_1.INotificationService),
        __param(4, languageFeatureDebounce_1.ILanguageFeatureDebounceService),
        __param(5, languageFeatures_1.ILanguageFeaturesService)
    ], FoldingController);
    class RangesLimitReporter {
        constructor(editor) {
            this.editor = editor;
            this._onDidChange = new event_1.Emitter();
            this._computed = 0;
            this._limited = false;
        }
        get limit() {
            return this.editor.getOptions().get(47 /* EditorOption.foldingMaximumRegions */);
        }
        update(computed, limited) {
            if (computed !== this._computed || limited !== this._limited) {
                this._computed = computed;
                this._limited = limited;
                this._onDidChange.fire();
            }
        }
    }
    exports.RangesLimitReporter = RangesLimitReporter;
    class FoldingAction extends editorExtensions_1.EditorAction {
        runEditorCommand(accessor, editor, args) {
            const languageConfigurationService = accessor.get(languageConfigurationRegistry_1.ILanguageConfigurationService);
            const foldingController = FoldingController.get(editor);
            if (!foldingController) {
                return;
            }
            const foldingModelPromise = foldingController.getFoldingModel();
            if (foldingModelPromise) {
                this.reportTelemetry(accessor, editor);
                return foldingModelPromise.then(foldingModel => {
                    if (foldingModel) {
                        this.invoke(foldingController, foldingModel, editor, args, languageConfigurationService);
                        const selection = editor.getSelection();
                        if (selection) {
                            foldingController.reveal(selection.getStartPosition());
                        }
                    }
                });
            }
        }
        getSelectedLines(editor) {
            const selections = editor.getSelections();
            return selections ? selections.map(s => s.startLineNumber) : [];
        }
        getLineNumbers(args, editor) {
            if (args && args.selectionLines) {
                return args.selectionLines.map(l => l + 1); // to 0-bases line numbers
            }
            return this.getSelectedLines(editor);
        }
        run(_accessor, _editor) {
        }
    }
    function toSelectedLines(selections) {
        if (!selections || selections.length === 0) {
            return {
                startsInside: () => false
            };
        }
        return {
            startsInside(startLine, endLine) {
                for (const s of selections) {
                    const line = s.startLineNumber;
                    if (line >= startLine && line <= endLine) {
                        return true;
                    }
                }
                return false;
            }
        };
    }
    function foldingArgumentsConstraint(args) {
        if (!types.isUndefined(args)) {
            if (!types.isObject(args)) {
                return false;
            }
            const foldingArgs = args;
            if (!types.isUndefined(foldingArgs.levels) && !types.isNumber(foldingArgs.levels)) {
                return false;
            }
            if (!types.isUndefined(foldingArgs.direction) && !types.isString(foldingArgs.direction)) {
                return false;
            }
            if (!types.isUndefined(foldingArgs.selectionLines) && (!Array.isArray(foldingArgs.selectionLines) || !foldingArgs.selectionLines.every(types.isNumber))) {
                return false;
            }
        }
        return true;
    }
    class UnfoldAction extends FoldingAction {
        constructor() {
            super({
                id: 'editor.unfold',
                label: nls.localize(891, "Unfold"),
                alias: 'Unfold',
                precondition: CONTEXT_FOLDING_ENABLED,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 94 /* KeyCode.BracketRight */,
                    mac: {
                        primary: 2048 /* KeyMod.CtrlCmd */ | 512 /* KeyMod.Alt */ | 94 /* KeyCode.BracketRight */
                    },
                    weight: 100 /* KeybindingWeight.EditorContrib */
                },
                metadata: {
                    description: 'Unfold the content in the editor',
                    args: [
                        {
                            name: 'Unfold editor argument',
                            description: `Property-value pairs that can be passed through this argument:
						* 'levels': Number of levels to unfold. If not set, defaults to 1.
						* 'direction': If 'up', unfold given number of levels up otherwise unfolds down.
						* 'selectionLines': Array of the start lines (0-based) of the editor selections to apply the unfold action to. If not set, the active selection(s) will be used.
						`,
                            constraint: foldingArgumentsConstraint,
                            schema: {
                                'type': 'object',
                                'properties': {
                                    'levels': {
                                        'type': 'number',
                                        'default': 1
                                    },
                                    'direction': {
                                        'type': 'string',
                                        'enum': ['up', 'down'],
                                        'default': 'down'
                                    },
                                    'selectionLines': {
                                        'type': 'array',
                                        'items': {
                                            'type': 'number'
                                        }
                                    }
                                }
                            }
                        }
                    ]
                }
            });
        }
        invoke(_foldingController, foldingModel, editor, args) {
            const levels = args && args.levels || 1;
            const lineNumbers = this.getLineNumbers(args, editor);
            if (args && args.direction === 'up') {
                (0, foldingModel_1.setCollapseStateLevelsUp)(foldingModel, false, levels, lineNumbers);
            }
            else {
                (0, foldingModel_1.setCollapseStateLevelsDown)(foldingModel, false, levels, lineNumbers);
            }
        }
    }
    class UnFoldRecursivelyAction extends FoldingAction {
        constructor() {
            super({
                id: 'editor.unfoldRecursively',
                label: nls.localize(892, "Unfold Recursively"),
                alias: 'Unfold Recursively',
                precondition: CONTEXT_FOLDING_ENABLED,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    primary: (0, keyCodes_1.KeyChord)(2048 /* KeyMod.CtrlCmd */ | 41 /* KeyCode.KeyK */, 2048 /* KeyMod.CtrlCmd */ | 94 /* KeyCode.BracketRight */),
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
        invoke(_foldingController, foldingModel, editor, _args) {
            (0, foldingModel_1.setCollapseStateLevelsDown)(foldingModel, false, Number.MAX_VALUE, this.getSelectedLines(editor));
        }
    }
    class FoldAction extends FoldingAction {
        constructor() {
            super({
                id: 'editor.fold',
                label: nls.localize(893, "Fold"),
                alias: 'Fold',
                precondition: CONTEXT_FOLDING_ENABLED,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 92 /* KeyCode.BracketLeft */,
                    mac: {
                        primary: 2048 /* KeyMod.CtrlCmd */ | 512 /* KeyMod.Alt */ | 92 /* KeyCode.BracketLeft */
                    },
                    weight: 100 /* KeybindingWeight.EditorContrib */
                },
                metadata: {
                    description: 'Fold the content in the editor',
                    args: [
                        {
                            name: 'Fold editor argument',
                            description: `Property-value pairs that can be passed through this argument:
							* 'levels': Number of levels to fold.
							* 'direction': If 'up', folds given number of levels up otherwise folds down.
							* 'selectionLines': Array of the start lines (0-based) of the editor selections to apply the fold action to. If not set, the active selection(s) will be used.
							If no levels or direction is set, folds the region at the locations or if already collapsed, the first uncollapsed parent instead.
						`,
                            constraint: foldingArgumentsConstraint,
                            schema: {
                                'type': 'object',
                                'properties': {
                                    'levels': {
                                        'type': 'number',
                                    },
                                    'direction': {
                                        'type': 'string',
                                        'enum': ['up', 'down'],
                                    },
                                    'selectionLines': {
                                        'type': 'array',
                                        'items': {
                                            'type': 'number'
                                        }
                                    }
                                }
                            }
                        }
                    ]
                }
            });
        }
        invoke(_foldingController, foldingModel, editor, args) {
            const lineNumbers = this.getLineNumbers(args, editor);
            const levels = args && args.levels;
            const direction = args && args.direction;
            if (typeof levels !== 'number' && typeof direction !== 'string') {
                // fold the region at the location or if already collapsed, the first uncollapsed parent instead.
                (0, foldingModel_1.setCollapseStateUp)(foldingModel, true, lineNumbers);
            }
            else {
                if (direction === 'up') {
                    (0, foldingModel_1.setCollapseStateLevelsUp)(foldingModel, true, levels || 1, lineNumbers);
                }
                else {
                    (0, foldingModel_1.setCollapseStateLevelsDown)(foldingModel, true, levels || 1, lineNumbers);
                }
            }
        }
    }
    class ToggleFoldAction extends FoldingAction {
        constructor() {
            super({
                id: 'editor.toggleFold',
                label: nls.localize(894, "Toggle Fold"),
                alias: 'Toggle Fold',
                precondition: CONTEXT_FOLDING_ENABLED,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    primary: (0, keyCodes_1.KeyChord)(2048 /* KeyMod.CtrlCmd */ | 41 /* KeyCode.KeyK */, 2048 /* KeyMod.CtrlCmd */ | 42 /* KeyCode.KeyL */),
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
        invoke(_foldingController, foldingModel, editor) {
            const selectedLines = this.getSelectedLines(editor);
            (0, foldingModel_1.toggleCollapseState)(foldingModel, 1, selectedLines);
        }
    }
    class FoldRecursivelyAction extends FoldingAction {
        constructor() {
            super({
                id: 'editor.foldRecursively',
                label: nls.localize(895, "Fold Recursively"),
                alias: 'Fold Recursively',
                precondition: CONTEXT_FOLDING_ENABLED,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    primary: (0, keyCodes_1.KeyChord)(2048 /* KeyMod.CtrlCmd */ | 41 /* KeyCode.KeyK */, 2048 /* KeyMod.CtrlCmd */ | 92 /* KeyCode.BracketLeft */),
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
        invoke(_foldingController, foldingModel, editor) {
            const selectedLines = this.getSelectedLines(editor);
            (0, foldingModel_1.setCollapseStateLevelsDown)(foldingModel, true, Number.MAX_VALUE, selectedLines);
        }
    }
    class ToggleFoldRecursivelyAction extends FoldingAction {
        constructor() {
            super({
                id: 'editor.toggleFoldRecursively',
                label: nls.localize(896, "Toggle Fold Recursively"),
                alias: 'Toggle Fold Recursively',
                precondition: CONTEXT_FOLDING_ENABLED,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    primary: (0, keyCodes_1.KeyChord)(2048 /* KeyMod.CtrlCmd */ | 41 /* KeyCode.KeyK */, 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 42 /* KeyCode.KeyL */),
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
        invoke(_foldingController, foldingModel, editor) {
            const selectedLines = this.getSelectedLines(editor);
            (0, foldingModel_1.toggleCollapseState)(foldingModel, Number.MAX_VALUE, selectedLines);
        }
    }
    class FoldAllBlockCommentsAction extends FoldingAction {
        constructor() {
            super({
                id: 'editor.foldAllBlockComments',
                label: nls.localize(897, "Fold All Block Comments"),
                alias: 'Fold All Block Comments',
                precondition: CONTEXT_FOLDING_ENABLED,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    primary: (0, keyCodes_1.KeyChord)(2048 /* KeyMod.CtrlCmd */ | 41 /* KeyCode.KeyK */, 2048 /* KeyMod.CtrlCmd */ | 90 /* KeyCode.Slash */),
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
        invoke(_foldingController, foldingModel, editor, args, languageConfigurationService) {
            if (foldingModel.regions.hasTypes()) {
                (0, foldingModel_1.setCollapseStateForType)(foldingModel, languages_1.FoldingRangeKind.Comment.value, true);
            }
            else {
                const editorModel = editor.getModel();
                if (!editorModel) {
                    return;
                }
                const comments = languageConfigurationService.getLanguageConfiguration(editorModel.getLanguageId()).comments;
                if (comments && comments.blockCommentStartToken) {
                    const regExp = new RegExp('^\\s*' + (0, strings_1.escapeRegExpCharacters)(comments.blockCommentStartToken));
                    (0, foldingModel_1.setCollapseStateForMatchingLines)(foldingModel, regExp, true);
                }
            }
        }
    }
    class FoldAllRegionsAction extends FoldingAction {
        constructor() {
            super({
                id: 'editor.foldAllMarkerRegions',
                label: nls.localize(898, "Fold All Regions"),
                alias: 'Fold All Regions',
                precondition: CONTEXT_FOLDING_ENABLED,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    primary: (0, keyCodes_1.KeyChord)(2048 /* KeyMod.CtrlCmd */ | 41 /* KeyCode.KeyK */, 2048 /* KeyMod.CtrlCmd */ | 29 /* KeyCode.Digit8 */),
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
        invoke(_foldingController, foldingModel, editor, args, languageConfigurationService) {
            if (foldingModel.regions.hasTypes()) {
                (0, foldingModel_1.setCollapseStateForType)(foldingModel, languages_1.FoldingRangeKind.Region.value, true);
            }
            else {
                const editorModel = editor.getModel();
                if (!editorModel) {
                    return;
                }
                const foldingRules = languageConfigurationService.getLanguageConfiguration(editorModel.getLanguageId()).foldingRules;
                if (foldingRules && foldingRules.markers && foldingRules.markers.start) {
                    const regExp = new RegExp(foldingRules.markers.start);
                    (0, foldingModel_1.setCollapseStateForMatchingLines)(foldingModel, regExp, true);
                }
            }
        }
    }
    class UnfoldAllRegionsAction extends FoldingAction {
        constructor() {
            super({
                id: 'editor.unfoldAllMarkerRegions',
                label: nls.localize(899, "Unfold All Regions"),
                alias: 'Unfold All Regions',
                precondition: CONTEXT_FOLDING_ENABLED,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    primary: (0, keyCodes_1.KeyChord)(2048 /* KeyMod.CtrlCmd */ | 41 /* KeyCode.KeyK */, 2048 /* KeyMod.CtrlCmd */ | 30 /* KeyCode.Digit9 */),
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
        invoke(_foldingController, foldingModel, editor, args, languageConfigurationService) {
            if (foldingModel.regions.hasTypes()) {
                (0, foldingModel_1.setCollapseStateForType)(foldingModel, languages_1.FoldingRangeKind.Region.value, false);
            }
            else {
                const editorModel = editor.getModel();
                if (!editorModel) {
                    return;
                }
                const foldingRules = languageConfigurationService.getLanguageConfiguration(editorModel.getLanguageId()).foldingRules;
                if (foldingRules && foldingRules.markers && foldingRules.markers.start) {
                    const regExp = new RegExp(foldingRules.markers.start);
                    (0, foldingModel_1.setCollapseStateForMatchingLines)(foldingModel, regExp, false);
                }
            }
        }
    }
    class FoldAllExceptAction extends FoldingAction {
        constructor() {
            super({
                id: 'editor.foldAllExcept',
                label: nls.localize(900, "Fold All Except Selected"),
                alias: 'Fold All Except Selected',
                precondition: CONTEXT_FOLDING_ENABLED,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    primary: (0, keyCodes_1.KeyChord)(2048 /* KeyMod.CtrlCmd */ | 41 /* KeyCode.KeyK */, 2048 /* KeyMod.CtrlCmd */ | 88 /* KeyCode.Minus */),
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
        invoke(_foldingController, foldingModel, editor) {
            const selectedLines = this.getSelectedLines(editor);
            (0, foldingModel_1.setCollapseStateForRest)(foldingModel, true, selectedLines);
        }
    }
    class UnfoldAllExceptAction extends FoldingAction {
        constructor() {
            super({
                id: 'editor.unfoldAllExcept',
                label: nls.localize(901, "Unfold All Except Selected"),
                alias: 'Unfold All Except Selected',
                precondition: CONTEXT_FOLDING_ENABLED,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    primary: (0, keyCodes_1.KeyChord)(2048 /* KeyMod.CtrlCmd */ | 41 /* KeyCode.KeyK */, 2048 /* KeyMod.CtrlCmd */ | 86 /* KeyCode.Equal */),
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
        invoke(_foldingController, foldingModel, editor) {
            const selectedLines = this.getSelectedLines(editor);
            (0, foldingModel_1.setCollapseStateForRest)(foldingModel, false, selectedLines);
        }
    }
    class FoldAllAction extends FoldingAction {
        constructor() {
            super({
                id: 'editor.foldAll',
                label: nls.localize(902, "Fold All"),
                alias: 'Fold All',
                precondition: CONTEXT_FOLDING_ENABLED,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    primary: (0, keyCodes_1.KeyChord)(2048 /* KeyMod.CtrlCmd */ | 41 /* KeyCode.KeyK */, 2048 /* KeyMod.CtrlCmd */ | 21 /* KeyCode.Digit0 */),
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
        invoke(_foldingController, foldingModel, _editor) {
            (0, foldingModel_1.setCollapseStateLevelsDown)(foldingModel, true);
        }
    }
    class UnfoldAllAction extends FoldingAction {
        constructor() {
            super({
                id: 'editor.unfoldAll',
                label: nls.localize(903, "Unfold All"),
                alias: 'Unfold All',
                precondition: CONTEXT_FOLDING_ENABLED,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    primary: (0, keyCodes_1.KeyChord)(2048 /* KeyMod.CtrlCmd */ | 41 /* KeyCode.KeyK */, 2048 /* KeyMod.CtrlCmd */ | 40 /* KeyCode.KeyJ */),
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
        invoke(_foldingController, foldingModel, _editor) {
            (0, foldingModel_1.setCollapseStateLevelsDown)(foldingModel, false);
        }
    }
    class FoldLevelAction extends FoldingAction {
        static { this.ID_PREFIX = 'editor.foldLevel'; }
        static { this.ID = (level) => FoldLevelAction.ID_PREFIX + level; }
        getFoldingLevel() {
            return parseInt(this.id.substr(FoldLevelAction.ID_PREFIX.length));
        }
        invoke(_foldingController, foldingModel, editor) {
            (0, foldingModel_1.setCollapseStateAtLevel)(foldingModel, this.getFoldingLevel(), true, this.getSelectedLines(editor));
        }
    }
    /** Action to go to the parent fold of current line */
    class GotoParentFoldAction extends FoldingAction {
        constructor() {
            super({
                id: 'editor.gotoParentFold',
                label: nls.localize(904, "Go to Parent Fold"),
                alias: 'Go to Parent Fold',
                precondition: CONTEXT_FOLDING_ENABLED,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
        invoke(_foldingController, foldingModel, editor) {
            const selectedLines = this.getSelectedLines(editor);
            if (selectedLines.length > 0) {
                const startLineNumber = (0, foldingModel_1.getParentFoldLine)(selectedLines[0], foldingModel);
                if (startLineNumber !== null) {
                    editor.setSelection({
                        startLineNumber: startLineNumber,
                        startColumn: 1,
                        endLineNumber: startLineNumber,
                        endColumn: 1
                    });
                }
            }
        }
    }
    /** Action to go to the previous fold of current line */
    class GotoPreviousFoldAction extends FoldingAction {
        constructor() {
            super({
                id: 'editor.gotoPreviousFold',
                label: nls.localize(905, "Go to Previous Folding Range"),
                alias: 'Go to Previous Folding Range',
                precondition: CONTEXT_FOLDING_ENABLED,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
        invoke(_foldingController, foldingModel, editor) {
            const selectedLines = this.getSelectedLines(editor);
            if (selectedLines.length > 0) {
                const startLineNumber = (0, foldingModel_1.getPreviousFoldLine)(selectedLines[0], foldingModel);
                if (startLineNumber !== null) {
                    editor.setSelection({
                        startLineNumber: startLineNumber,
                        startColumn: 1,
                        endLineNumber: startLineNumber,
                        endColumn: 1
                    });
                }
            }
        }
    }
    /** Action to go to the next fold of current line */
    class GotoNextFoldAction extends FoldingAction {
        constructor() {
            super({
                id: 'editor.gotoNextFold',
                label: nls.localize(906, "Go to Next Folding Range"),
                alias: 'Go to Next Folding Range',
                precondition: CONTEXT_FOLDING_ENABLED,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
        invoke(_foldingController, foldingModel, editor) {
            const selectedLines = this.getSelectedLines(editor);
            if (selectedLines.length > 0) {
                const startLineNumber = (0, foldingModel_1.getNextFoldLine)(selectedLines[0], foldingModel);
                if (startLineNumber !== null) {
                    editor.setSelection({
                        startLineNumber: startLineNumber,
                        startColumn: 1,
                        endLineNumber: startLineNumber,
                        endColumn: 1
                    });
                }
            }
        }
    }
    class FoldRangeFromSelectionAction extends FoldingAction {
        constructor() {
            super({
                id: 'editor.createFoldingRangeFromSelection',
                label: nls.localize(907, "Create Folding Range from Selection"),
                alias: 'Create Folding Range from Selection',
                precondition: CONTEXT_FOLDING_ENABLED,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    primary: (0, keyCodes_1.KeyChord)(2048 /* KeyMod.CtrlCmd */ | 41 /* KeyCode.KeyK */, 2048 /* KeyMod.CtrlCmd */ | 87 /* KeyCode.Comma */),
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
        invoke(_foldingController, foldingModel, editor) {
            const collapseRanges = [];
            const selections = editor.getSelections();
            if (selections) {
                for (const selection of selections) {
                    let endLineNumber = selection.endLineNumber;
                    if (selection.endColumn === 1) {
                        --endLineNumber;
                    }
                    if (endLineNumber > selection.startLineNumber) {
                        collapseRanges.push({
                            startLineNumber: selection.startLineNumber,
                            endLineNumber: endLineNumber,
                            type: undefined,
                            isCollapsed: true,
                            source: 1 /* FoldSource.userDefined */
                        });
                        editor.setSelection({
                            startLineNumber: selection.startLineNumber,
                            startColumn: 1,
                            endLineNumber: selection.startLineNumber,
                            endColumn: 1
                        });
                    }
                }
                if (collapseRanges.length > 0) {
                    collapseRanges.sort((a, b) => {
                        return a.startLineNumber - b.startLineNumber;
                    });
                    const newRanges = foldingRanges_1.FoldingRegions.sanitizeAndMerge(foldingModel.regions, collapseRanges, editor.getModel()?.getLineCount());
                    foldingModel.updatePost(foldingRanges_1.FoldingRegions.fromFoldRanges(newRanges));
                }
            }
        }
    }
    class RemoveFoldRangeFromSelectionAction extends FoldingAction {
        constructor() {
            super({
                id: 'editor.removeManualFoldingRanges',
                label: nls.localize(908, "Remove Manual Folding Ranges"),
                alias: 'Remove Manual Folding Ranges',
                precondition: CONTEXT_FOLDING_ENABLED,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    primary: (0, keyCodes_1.KeyChord)(2048 /* KeyMod.CtrlCmd */ | 41 /* KeyCode.KeyK */, 2048 /* KeyMod.CtrlCmd */ | 89 /* KeyCode.Period */),
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
        invoke(foldingController, foldingModel, editor) {
            const selections = editor.getSelections();
            if (selections) {
                const ranges = [];
                for (const selection of selections) {
                    const { startLineNumber, endLineNumber } = selection;
                    ranges.push(endLineNumber >= startLineNumber ? { startLineNumber, endLineNumber } : { endLineNumber, startLineNumber });
                }
                foldingModel.removeManualRanges(ranges);
                foldingController.triggerFoldingModelChanged();
            }
        }
    }
    (0, editorExtensions_1.registerEditorContribution)(FoldingController.ID, FoldingController, 0 /* EditorContributionInstantiation.Eager */); // eager because it uses `saveViewState`/`restoreViewState`
    (0, editorExtensions_1.registerEditorAction)(UnfoldAction);
    (0, editorExtensions_1.registerEditorAction)(UnFoldRecursivelyAction);
    (0, editorExtensions_1.registerEditorAction)(FoldAction);
    (0, editorExtensions_1.registerEditorAction)(FoldRecursivelyAction);
    (0, editorExtensions_1.registerEditorAction)(ToggleFoldRecursivelyAction);
    (0, editorExtensions_1.registerEditorAction)(FoldAllAction);
    (0, editorExtensions_1.registerEditorAction)(UnfoldAllAction);
    (0, editorExtensions_1.registerEditorAction)(FoldAllBlockCommentsAction);
    (0, editorExtensions_1.registerEditorAction)(FoldAllRegionsAction);
    (0, editorExtensions_1.registerEditorAction)(UnfoldAllRegionsAction);
    (0, editorExtensions_1.registerEditorAction)(FoldAllExceptAction);
    (0, editorExtensions_1.registerEditorAction)(UnfoldAllExceptAction);
    (0, editorExtensions_1.registerEditorAction)(ToggleFoldAction);
    (0, editorExtensions_1.registerEditorAction)(GotoParentFoldAction);
    (0, editorExtensions_1.registerEditorAction)(GotoPreviousFoldAction);
    (0, editorExtensions_1.registerEditorAction)(GotoNextFoldAction);
    (0, editorExtensions_1.registerEditorAction)(FoldRangeFromSelectionAction);
    (0, editorExtensions_1.registerEditorAction)(RemoveFoldRangeFromSelectionAction);
    for (let i = 1; i <= 7; i++) {
        (0, editorExtensions_1.registerInstantiatedEditorAction)(new FoldLevelAction({
            id: FoldLevelAction.ID(i),
            label: nls.localize(909, "Fold Level {0}", i),
            alias: `Fold Level ${i}`,
            precondition: CONTEXT_FOLDING_ENABLED,
            kbOpts: {
                kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                primary: (0, keyCodes_1.KeyChord)(2048 /* KeyMod.CtrlCmd */ | 41 /* KeyCode.KeyK */, 2048 /* KeyMod.CtrlCmd */ | (21 /* KeyCode.Digit0 */ + i)),
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        }));
    }
    commands_1.CommandsRegistry.registerCommand('_executeFoldingRangeProvider', async function (accessor, ...args) {
        const [resource] = args;
        if (!(resource instanceof uri_1.URI)) {
            throw (0, errors_1.illegalArgument)();
        }
        const languageFeaturesService = accessor.get(languageFeatures_1.ILanguageFeaturesService);
        const model = accessor.get(model_1.IModelService).getModel(resource);
        if (!model) {
            throw (0, errors_1.illegalArgument)();
        }
        const configurationService = accessor.get(configuration_1.IConfigurationService);
        if (!configurationService.getValue('editor.folding', { resource })) {
            return [];
        }
        const languageConfigurationService = accessor.get(languageConfigurationRegistry_1.ILanguageConfigurationService);
        const strategy = configurationService.getValue('editor.foldingStrategy', { resource });
        const foldingLimitReporter = {
            get limit() {
                return configurationService.getValue('editor.foldingMaximumRegions', { resource });
            },
            update: (computed, limited) => { }
        };
        const indentRangeProvider = new indentRangeProvider_1.IndentRangeProvider(model, languageConfigurationService, foldingLimitReporter);
        let rangeProvider = indentRangeProvider;
        if (strategy !== 'indentation') {
            const providers = FoldingController.getFoldingRangeProviders(languageFeaturesService, model);
            if (providers.length) {
                rangeProvider = new syntaxRangeProvider_1.SyntaxRangeProvider(model, providers, () => { }, foldingLimitReporter, indentRangeProvider);
            }
        }
        const ranges = await rangeProvider.compute(cancellation_1.CancellationToken.None);
        const result = [];
        try {
            if (ranges) {
                for (let i = 0; i < ranges.length; i++) {
                    const type = ranges.getType(i);
                    result.push({ start: ranges.getStartLineNumber(i), end: ranges.getEndLineNumber(i), kind: type ? languages_1.FoldingRangeKind.fromValue(type) : undefined });
                }
            }
            return result;
        }
        finally {
            rangeProvider.dispose();
        }
    });
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[827/*vs/editor/contrib/inPlaceReplace/browser/inPlaceReplace*/], __M([1/*require*/,0/*exports*/,14/*vs/base/common/async*/,8/*vs/base/common/errors*/,122/*vs/editor/contrib/editorState/browser/editorState*/,15/*vs/editor/browser/editorExtensions*/,4/*vs/editor/common/core/range*/,23/*vs/editor/common/core/selection*/,20/*vs/editor/common/editorContextKeys*/,35/*vs/editor/common/model/textModel*/,100/*vs/editor/common/services/editorWorker*/,3/*vs/nls*/,616/*vs/editor/contrib/inPlaceReplace/browser/inPlaceReplaceCommand*/,515/*vs/css!vs/editor/contrib/inPlaceReplace/browser/inPlaceReplace*/]), function (require, exports, async_1, errors_1, editorState_1, editorExtensions_1, range_1, selection_1, editorContextKeys_1, textModel_1, editorWorker_1, nls, inPlaceReplaceCommand_1) {
    "use strict";
    var InPlaceReplaceController_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    let InPlaceReplaceController = class InPlaceReplaceController {
        static { InPlaceReplaceController_1 = this; }
        static { this.ID = 'editor.contrib.inPlaceReplaceController'; }
        static get(editor) {
            return editor.getContribution(InPlaceReplaceController_1.ID);
        }
        static { this.DECORATION = textModel_1.ModelDecorationOptions.register({
            description: 'in-place-replace',
            className: 'valueSetReplacement'
        }); }
        constructor(editor, editorWorkerService) {
            this.editor = editor;
            this.editorWorkerService = editorWorkerService;
            this.decorations = this.editor.createDecorationsCollection();
        }
        dispose() {
        }
        run(source, up) {
            // cancel any pending request
            this.currentRequest?.cancel();
            const editorSelection = this.editor.getSelection();
            const model = this.editor.getModel();
            if (!model || !editorSelection) {
                return undefined;
            }
            let selection = editorSelection;
            if (selection.startLineNumber !== selection.endLineNumber) {
                // Can't accept multiline selection
                return undefined;
            }
            const state = new editorState_1.EditorState(this.editor, 1 /* CodeEditorStateFlag.Value */ | 4 /* CodeEditorStateFlag.Position */);
            const modelURI = model.uri;
            if (!this.editorWorkerService.canNavigateValueSet(modelURI)) {
                return Promise.resolve(undefined);
            }
            this.currentRequest = (0, async_1.createCancelablePromise)(token => this.editorWorkerService.navigateValueSet(modelURI, selection, up));
            return this.currentRequest.then(result => {
                if (!result || !result.range || !result.value) {
                    // No proper result
                    return;
                }
                if (!state.validate(this.editor)) {
                    // state has changed
                    return;
                }
                // Selection
                const editRange = range_1.Range.lift(result.range);
                let highlightRange = result.range;
                const diff = result.value.length - (selection.endColumn - selection.startColumn);
                // highlight
                highlightRange = {
                    startLineNumber: highlightRange.startLineNumber,
                    startColumn: highlightRange.startColumn,
                    endLineNumber: highlightRange.endLineNumber,
                    endColumn: highlightRange.startColumn + result.value.length
                };
                if (diff > 1) {
                    selection = new selection_1.Selection(selection.startLineNumber, selection.startColumn, selection.endLineNumber, selection.endColumn + diff - 1);
                }
                // Insert new text
                const command = new inPlaceReplaceCommand_1.InPlaceReplaceCommand(editRange, selection, result.value);
                this.editor.pushUndoStop();
                this.editor.executeCommand(source, command);
                this.editor.pushUndoStop();
                // add decoration
                this.decorations.set([{
                        range: highlightRange,
                        options: InPlaceReplaceController_1.DECORATION
                    }]);
                // remove decoration after delay
                this.decorationRemover?.cancel();
                this.decorationRemover = (0, async_1.timeout)(350);
                this.decorationRemover.then(() => this.decorations.clear()).catch(errors_1.onUnexpectedError);
            }).catch(errors_1.onUnexpectedError);
        }
    };
    InPlaceReplaceController = InPlaceReplaceController_1 = __decorate([
        __param(1, editorWorker_1.IEditorWorkerService)
    ], InPlaceReplaceController);
    class InPlaceReplaceUp extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: 'editor.action.inPlaceReplace.up',
                label: nls.localize(1103, "Replace with Previous Value"),
                alias: 'Replace with Previous Value',
                precondition: editorContextKeys_1.EditorContextKeys.writable,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 87 /* KeyCode.Comma */,
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
        run(accessor, editor) {
            const controller = InPlaceReplaceController.get(editor);
            if (!controller) {
                return Promise.resolve(undefined);
            }
            return controller.run(this.id, false);
        }
    }
    class InPlaceReplaceDown extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: 'editor.action.inPlaceReplace.down',
                label: nls.localize(1104, "Replace with Next Value"),
                alias: 'Replace with Next Value',
                precondition: editorContextKeys_1.EditorContextKeys.writable,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 89 /* KeyCode.Period */,
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
        run(accessor, editor) {
            const controller = InPlaceReplaceController.get(editor);
            if (!controller) {
                return Promise.resolve(undefined);
            }
            return controller.run(this.id, true);
        }
    }
    (0, editorExtensions_1.registerEditorContribution)(InPlaceReplaceController.ID, InPlaceReplaceController, 4 /* EditorContributionInstantiation.Lazy */);
    (0, editorExtensions_1.registerEditorAction)(InPlaceReplaceUp);
    (0, editorExtensions_1.registerEditorAction)(InPlaceReplaceDown);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[828/*vs/editor/contrib/inlineEdit/browser/ghostTextWidget*/], __M([1/*require*/,0/*exports*/,2/*vs/base/common/lifecycle*/,21/*vs/base/common/observable*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/,43/*vs/editor/common/languages/language*/,40/*vs/editor/common/model*/,150/*vs/editor/common/viewLayout/lineDecorations*/,205/*vs/editor/contrib/inlineCompletions/browser/utils*/,139/*vs/editor/browser/widget/diffEditor/registrations.contribution*/,518/*vs/css!vs/editor/contrib/inlineEdit/browser/inlineEdit*/]), function (require, exports, lifecycle_1, observable_1, position_1, range_1, language_1, model_1, lineDecorations_1, utils_1, registrations_contribution_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.GhostTextWidget = exports.INLINE_EDIT_DESCRIPTION = void 0;
    exports.INLINE_EDIT_DESCRIPTION = 'inline-edit';
    let GhostTextWidget = class GhostTextWidget extends lifecycle_1.Disposable {
        constructor(editor, model, languageService) {
            super();
            this.editor = editor;
            this.model = model;
            this.languageService = languageService;
            this.isDisposed = (0, observable_1.observableValue)(this, false);
            this.currentTextModel = (0, observable_1.observableFromEvent)(this, this.editor.onDidChangeModel, () => /** @description editor.model */ this.editor.getModel());
            this.uiState = (0, observable_1.derived)(this, reader => {
                if (this.isDisposed.read(reader)) {
                    return undefined;
                }
                const textModel = this.currentTextModel.read(reader);
                if (textModel !== this.model.targetTextModel.read(reader)) {
                    return undefined;
                }
                const ghostText = this.model.ghostText.read(reader);
                if (!ghostText) {
                    return undefined;
                }
                let range = this.model.range?.read(reader);
                //if range is empty, we want to remove it
                if (range && range.startLineNumber === range.endLineNumber && range.startColumn === range.endColumn) {
                    range = undefined;
                }
                //check if both range and text are single line - in this case we want to do inline replacement
                //rather than replacing whole lines
                const isSingleLine = (range ? range.startLineNumber === range.endLineNumber : true) && ghostText.parts.length === 1 && ghostText.parts[0].lines.length === 1;
                //check if we're just removing code
                const isPureRemove = ghostText.parts.length === 1 && ghostText.parts[0].lines.every(l => l.length === 0);
                const inlineTexts = [];
                const additionalLines = [];
                function addToAdditionalLines(lines, className) {
                    if (additionalLines.length > 0) {
                        const lastLine = additionalLines[additionalLines.length - 1];
                        if (className) {
                            lastLine.decorations.push(new lineDecorations_1.LineDecoration(lastLine.content.length + 1, lastLine.content.length + 1 + lines[0].length, className, 0 /* InlineDecorationType.Regular */));
                        }
                        lastLine.content += lines[0];
                        lines = lines.slice(1);
                    }
                    for (const line of lines) {
                        additionalLines.push({
                            content: line,
                            decorations: className ? [new lineDecorations_1.LineDecoration(1, line.length + 1, className, 0 /* InlineDecorationType.Regular */)] : []
                        });
                    }
                }
                const textBufferLine = textModel.getLineContent(ghostText.lineNumber);
                let hiddenTextStartColumn = undefined;
                let lastIdx = 0;
                if (!isPureRemove && (isSingleLine || !range)) {
                    for (const part of ghostText.parts) {
                        let lines = part.lines;
                        //If remove range is set, we want to push all new liens to virtual area
                        if (range && !isSingleLine) {
                            addToAdditionalLines(lines, exports.INLINE_EDIT_DESCRIPTION);
                            lines = [];
                        }
                        if (hiddenTextStartColumn === undefined) {
                            inlineTexts.push({
                                column: part.column,
                                text: lines[0],
                                preview: part.preview,
                            });
                            lines = lines.slice(1);
                        }
                        else {
                            addToAdditionalLines([textBufferLine.substring(lastIdx, part.column - 1)], undefined);
                        }
                        if (lines.length > 0) {
                            addToAdditionalLines(lines, exports.INLINE_EDIT_DESCRIPTION);
                            if (hiddenTextStartColumn === undefined && part.column <= textBufferLine.length) {
                                hiddenTextStartColumn = part.column;
                            }
                        }
                        lastIdx = part.column - 1;
                    }
                    if (hiddenTextStartColumn !== undefined) {
                        addToAdditionalLines([textBufferLine.substring(lastIdx)], undefined);
                    }
                }
                const hiddenRange = hiddenTextStartColumn !== undefined ? new utils_1.ColumnRange(hiddenTextStartColumn, textBufferLine.length + 1) : undefined;
                const lineNumber = (isSingleLine || !range) ? ghostText.lineNumber : range.endLineNumber - 1;
                return {
                    inlineTexts,
                    additionalLines,
                    hiddenRange,
                    lineNumber,
                    additionalReservedLineCount: this.model.minReservedLineCount.read(reader),
                    targetTextModel: textModel,
                    range,
                    isSingleLine,
                    isPureRemove,
                };
            });
            this.decorations = (0, observable_1.derived)(this, reader => {
                const uiState = this.uiState.read(reader);
                if (!uiState) {
                    return [];
                }
                const decorations = [];
                if (uiState.hiddenRange) {
                    decorations.push({
                        range: uiState.hiddenRange.toRange(uiState.lineNumber),
                        options: { inlineClassName: 'inline-edit-hidden', description: 'inline-edit-hidden', }
                    });
                }
                if (uiState.range) {
                    const ranges = [];
                    if (uiState.isSingleLine) {
                        ranges.push(uiState.range);
                    }
                    else if (!uiState.isPureRemove) {
                        const lines = uiState.range.endLineNumber - uiState.range.startLineNumber;
                        for (let i = 0; i < lines; i++) {
                            const line = uiState.range.startLineNumber + i;
                            const firstNonWhitespace = uiState.targetTextModel.getLineFirstNonWhitespaceColumn(line);
                            const lastNonWhitespace = uiState.targetTextModel.getLineLastNonWhitespaceColumn(line);
                            const range = new range_1.Range(line, firstNonWhitespace, line, lastNonWhitespace);
                            ranges.push(range);
                        }
                    }
                    for (const range of ranges) {
                        decorations.push({
                            range,
                            options: registrations_contribution_1.diffDeleteDecoration
                        });
                    }
                }
                if (uiState.range && !uiState.isSingleLine && uiState.isPureRemove) {
                    const r = new range_1.Range(uiState.range.startLineNumber, 1, uiState.range.endLineNumber - 1, 1);
                    decorations.push({
                        range: r,
                        options: registrations_contribution_1.diffLineDeleteDecorationBackgroundWithIndicator
                    });
                }
                for (const p of uiState.inlineTexts) {
                    decorations.push({
                        range: range_1.Range.fromPositions(new position_1.Position(uiState.lineNumber, p.column)),
                        options: {
                            description: exports.INLINE_EDIT_DESCRIPTION,
                            after: { content: p.text, inlineClassName: p.preview ? 'inline-edit-decoration-preview' : 'inline-edit-decoration', cursorStops: model_1.InjectedTextCursorStops.Left },
                            showIfCollapsed: true,
                        }
                    });
                }
                return decorations;
            });
            this._register((0, lifecycle_1.toDisposable)(() => { this.isDisposed.set(true, undefined); }));
            this._register((0, utils_1.applyObservableDecorations)(this.editor, this.decorations));
        }
    };
    exports.GhostTextWidget = GhostTextWidget;
    exports.GhostTextWidget = GhostTextWidget = __decorate([
        __param(2, language_1.ILanguageService)
    ], GhostTextWidget);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[829/*vs/editor/contrib/inlineEdit/browser/inlineEditSideBySideWidget*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,18/*vs/base/common/cancellation*/,2/*vs/base/common/lifecycle*/,21/*vs/base/common/observable*/,65/*vs/base/common/observableInternal/derived*/,22/*vs/base/common/uri*/,112/*vs/editor/browser/observableCodeEditor*/,125/*vs/editor/browser/widget/codeEditor/embeddedCodeEditorWidget*/,215/*vs/editor/browser/widget/diffEditor/diffProviderFactoryService*/,139/*vs/editor/browser/widget/diffEditor/registrations.contribution*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/,70/*vs/editor/common/languages/modesRegistry*/,35/*vs/editor/common/model/textModel*/,51/*vs/editor/common/services/model*/,7/*vs/platform/instantiation/common/instantiation*/,520/*vs/css!vs/editor/contrib/inlineEdit/browser/inlineEditSideBySideWidget*/]), function (require, exports, dom_1, cancellation_1, lifecycle_1, observable_1, derived_1, uri_1, observableCodeEditor_1, embeddedCodeEditorWidget_1, diffProviderFactoryService_1, registrations_contribution_1, position_1, range_1, modesRegistry_1, textModel_1, model_1, instantiation_1) {
    "use strict";
    var InlineEditSideBySideWidget_1, InlineEditSideBySideContentWidget_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.InlineEditSideBySideWidget = void 0;
    function* range(start, end, step = 1) {
        if (end === undefined) {
            [end, start] = [start, 0];
        }
        for (let n = start; n < end; n += step) {
            yield n;
        }
    }
    function removeIndentation(lines) {
        const indentation = lines[0].match(/^\s*/)?.[0] ?? '';
        const length = indentation.length;
        return {
            text: lines.map(l => l.replace(new RegExp('^' + indentation), '')),
            shift: length
        };
    }
    let InlineEditSideBySideWidget = class InlineEditSideBySideWidget extends lifecycle_1.Disposable {
        static { InlineEditSideBySideWidget_1 = this; }
        static { this._modelId = 0; }
        static _createUniqueUri() {
            return uri_1.URI.from({ scheme: 'inline-edit-widget', path: new Date().toString() + String(InlineEditSideBySideWidget_1._modelId++) });
        }
        constructor(_editor, _model, _instantiationService, _diffProviderFactoryService, _modelService) {
            super();
            this._editor = _editor;
            this._model = _model;
            this._instantiationService = _instantiationService;
            this._diffProviderFactoryService = _diffProviderFactoryService;
            this._modelService = _modelService;
            this._position = (0, observable_1.derived)(this, reader => {
                const ghostText = this._model.read(reader);
                if (!ghostText || ghostText.text.length === 0) {
                    return null;
                }
                if (ghostText.range.startLineNumber === ghostText.range.endLineNumber && !(ghostText.range.startColumn === ghostText.range.endColumn && ghostText.range.startColumn === 1)) {
                    //for inner-line suggestions we still want to use minimal ghost text
                    return null;
                }
                const editorModel = this._editor.getModel();
                if (!editorModel) {
                    return null;
                }
                const lines = Array.from(range(ghostText.range.startLineNumber, ghostText.range.endLineNumber + 1));
                const lengths = lines.map(lineNumber => editorModel.getLineLastNonWhitespaceColumn(lineNumber));
                const maxColumn = Math.max(...lengths);
                const lineOfMaxColumn = lines[lengths.indexOf(maxColumn)];
                const position = new position_1.Position(lineOfMaxColumn, maxColumn);
                const pos = {
                    top: ghostText.range.startLineNumber,
                    left: position
                };
                return pos;
            });
            this._text = (0, observable_1.derived)(this, reader => {
                const ghostText = this._model.read(reader);
                if (!ghostText) {
                    return { text: '', shift: 0 };
                }
                const t = removeIndentation(ghostText.text.split('\n'));
                return {
                    text: t.text.join('\n'),
                    shift: t.shift
                };
            });
            this._originalModel = (0, derived_1.derivedDisposable)(() => this._modelService.createModel('', null, InlineEditSideBySideWidget_1._createUniqueUri())).keepObserved(this._store);
            this._modifiedModel = (0, derived_1.derivedDisposable)(() => this._modelService.createModel('', null, InlineEditSideBySideWidget_1._createUniqueUri())).keepObserved(this._store);
            this._diff = (0, observable_1.derived)(this, reader => {
                return this._diffPromise.read(reader)?.promiseResult.read(reader)?.data;
            });
            this._diffPromise = (0, observable_1.derived)(this, reader => {
                const ghostText = this._model.read(reader);
                if (!ghostText) {
                    return;
                }
                const editorModel = this._editor.getModel();
                if (!editorModel) {
                    return;
                }
                const originalText = removeIndentation(editorModel.getValueInRange(ghostText.range).split('\n')).text.join('\n');
                const modifiedText = removeIndentation(ghostText.text.split('\n')).text.join('\n');
                this._originalModel.get().setValue(originalText);
                this._modifiedModel.get().setValue(modifiedText);
                const d = this._diffProviderFactoryService.createDiffProvider({ diffAlgorithm: 'advanced' });
                return observable_1.ObservablePromise.fromFn(async () => {
                    const result = await d.computeDiff(this._originalModel.get(), this._modifiedModel.get(), {
                        computeMoves: false,
                        ignoreTrimWhitespace: false,
                        maxComputationTimeMs: 1000,
                    }, cancellation_1.CancellationToken.None);
                    if (result.identical) {
                        return undefined;
                    }
                    return result.changes;
                });
            });
            this._register((0, observable_1.autorunWithStore)((reader, store) => {
                /** @description setup content widget */
                const model = this._model.read(reader);
                if (!model) {
                    return;
                }
                if (this._position.get() === null) {
                    return;
                }
                const contentWidget = store.add(this._instantiationService.createInstance(InlineEditSideBySideContentWidget, this._editor, this._position, this._text.map(t => t.text), this._text.map(t => t.shift), this._diff));
                _editor.addOverlayWidget(contentWidget);
                store.add((0, lifecycle_1.toDisposable)(() => _editor.removeOverlayWidget(contentWidget)));
            }));
        }
    };
    exports.InlineEditSideBySideWidget = InlineEditSideBySideWidget;
    exports.InlineEditSideBySideWidget = InlineEditSideBySideWidget = InlineEditSideBySideWidget_1 = __decorate([
        __param(2, instantiation_1.IInstantiationService),
        __param(3, diffProviderFactoryService_1.IDiffProviderFactoryService),
        __param(4, model_1.IModelService)
    ], InlineEditSideBySideWidget);
    let InlineEditSideBySideContentWidget = class InlineEditSideBySideContentWidget extends lifecycle_1.Disposable {
        static { InlineEditSideBySideContentWidget_1 = this; }
        static { this.id = 0; }
        constructor(_editor, _position, _text, _shift, _diff, _instantiationService) {
            super();
            this._editor = _editor;
            this._position = _position;
            this._text = _text;
            this._shift = _shift;
            this._diff = _diff;
            this._instantiationService = _instantiationService;
            this.id = `InlineEditSideBySideContentWidget${InlineEditSideBySideContentWidget_1.id++}`;
            this.allowEditorOverflow = false;
            this._nodes = (0, dom_1.$)('div.inlineEditSideBySide', undefined);
            this._scrollChanged = (0, observable_1.observableSignalFromEvent)('editor.onDidScrollChange', this._editor.onDidScrollChange);
            this._previewEditor = this._register(this._instantiationService.createInstance(embeddedCodeEditorWidget_1.EmbeddedCodeEditorWidget, this._nodes, {
                glyphMargin: false,
                lineNumbers: 'off',
                minimap: { enabled: false },
                guides: {
                    indentation: false,
                    bracketPairs: false,
                    bracketPairsHorizontal: false,
                    highlightActiveIndentation: false,
                },
                folding: false,
                selectOnLineNumbers: false,
                selectionHighlight: false,
                columnSelection: false,
                overviewRulerBorder: false,
                overviewRulerLanes: 0,
                lineDecorationsWidth: 0,
                lineNumbersMinChars: 0,
                scrollbar: { vertical: 'hidden', horizontal: 'hidden', alwaysConsumeMouseWheel: false, handleMouseWheel: false },
                readOnly: true,
                wordWrap: 'off',
                wordWrapOverride1: 'off',
                wordWrapOverride2: 'off',
                wrappingIndent: 'none',
                wrappingStrategy: undefined,
            }, { contributions: [], isSimpleWidget: true }, this._editor));
            this._previewEditorObs = (0, observableCodeEditor_1.observableCodeEditor)(this._previewEditor);
            this._editorObs = (0, observableCodeEditor_1.observableCodeEditor)(this._editor);
            this._previewTextModel = this._register(this._instantiationService.createInstance(textModel_1.TextModel, '', this._editor.getModel()?.getLanguageId() ?? modesRegistry_1.PLAINTEXT_LANGUAGE_ID, textModel_1.TextModel.DEFAULT_CREATION_OPTIONS, null));
            this._setText = (0, observable_1.derived)(reader => {
                const edit = this._text.read(reader);
                if (!edit) {
                    return;
                }
                this._previewTextModel.setValue(edit);
            }).recomputeInitiallyAndOnChange(this._store);
            this._decorations = (0, observable_1.derived)(this, (reader) => {
                this._setText.read(reader);
                const position = this._position.read(reader);
                if (!position) {
                    return { org: [], mod: [] };
                }
                const diff = this._diff.read(reader);
                if (!diff) {
                    return { org: [], mod: [] };
                }
                const originalDecorations = [];
                const modifiedDecorations = [];
                if (diff.length === 1 && diff[0].innerChanges[0].modifiedRange.equalsRange(this._previewTextModel.getFullModelRange())) {
                    return { org: [], mod: [] };
                }
                const shift = this._shift.get();
                const moveRange = (range) => {
                    return new range_1.Range(range.startLineNumber + position.top - 1, range.startColumn + shift, range.endLineNumber + position.top - 1, range.endColumn + shift);
                };
                for (const m of diff) {
                    if (!m.original.isEmpty) {
                        originalDecorations.push({ range: moveRange(m.original.toInclusiveRange()), options: registrations_contribution_1.diffLineDeleteDecorationBackgroundWithIndicator });
                    }
                    if (!m.modified.isEmpty) {
                        modifiedDecorations.push({ range: m.modified.toInclusiveRange(), options: registrations_contribution_1.diffLineAddDecorationBackgroundWithIndicator });
                    }
                    if (m.modified.isEmpty || m.original.isEmpty) {
                        if (!m.original.isEmpty) {
                            originalDecorations.push({ range: moveRange(m.original.toInclusiveRange()), options: registrations_contribution_1.diffWholeLineDeleteDecoration });
                        }
                        if (!m.modified.isEmpty) {
                            modifiedDecorations.push({ range: m.modified.toInclusiveRange(), options: registrations_contribution_1.diffWholeLineAddDecoration });
                        }
                    }
                    else {
                        for (const i of m.innerChanges || []) {
                            // Don't show empty markers outside the line range
                            if (m.original.contains(i.originalRange.startLineNumber)) {
                                originalDecorations.push({ range: moveRange(i.originalRange), options: i.originalRange.isEmpty() ? registrations_contribution_1.diffDeleteDecorationEmpty : registrations_contribution_1.diffDeleteDecoration });
                            }
                            if (m.modified.contains(i.modifiedRange.startLineNumber)) {
                                modifiedDecorations.push({ range: i.modifiedRange, options: i.modifiedRange.isEmpty() ? registrations_contribution_1.diffAddDecorationEmpty : registrations_contribution_1.diffAddDecoration });
                            }
                        }
                    }
                }
                return { org: originalDecorations, mod: modifiedDecorations };
            });
            this._originalDecorations = (0, observable_1.derived)(this, reader => {
                return this._decorations.read(reader).org;
            });
            this._modifiedDecorations = (0, observable_1.derived)(this, reader => {
                return this._decorations.read(reader).mod;
            });
            this._previewEditor.setModel(this._previewTextModel);
            this._register(this._editorObs.setDecorations(this._originalDecorations));
            this._register(this._previewEditorObs.setDecorations(this._modifiedDecorations));
            this._register((0, observable_1.autorun)(reader => {
                const width = this._previewEditorObs.contentWidth.read(reader);
                const lines = this._text.read(reader).split('\n').length - 1;
                const height = this._editor.getOption(67 /* EditorOption.lineHeight */) * lines;
                if (width <= 0) {
                    return;
                }
                this._previewEditor.layout({ height: height, width: width });
            }));
            this._register((0, observable_1.autorun)(reader => {
                /** @description update position */
                this._position.read(reader);
                this._editor.layoutOverlayWidget(this);
            }));
            this._register((0, observable_1.autorun)(reader => {
                /** @description scroll change */
                this._scrollChanged.read(reader);
                const position = this._position.read(reader);
                if (!position) {
                    return;
                }
                this._editor.layoutOverlayWidget(this);
            }));
        }
        getId() { return this.id; }
        getDomNode() {
            return this._nodes;
        }
        getPosition() {
            const position = this._position.get();
            if (!position) {
                return null;
            }
            const layoutInfo = this._editor.getLayoutInfo();
            const visibPos = this._editor.getScrolledVisiblePosition(new position_1.Position(position.top, 1));
            if (!visibPos) {
                return null;
            }
            const top = visibPos.top - 1; //-1 to offset the border width
            const offset = this._editor.getOffsetForColumn(position.left.lineNumber, position.left.column);
            const left = layoutInfo.contentLeft + offset + 10;
            return {
                preference: {
                    left,
                    top,
                }
            };
        }
    };
    InlineEditSideBySideContentWidget = InlineEditSideBySideContentWidget_1 = __decorate([
        __param(5, instantiation_1.IInstantiationService)
    ], InlineEditSideBySideContentWidget);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[425/*vs/editor/contrib/inlineEdit/browser/inlineEditController*/], __M([1/*require*/,0/*exports*/,2/*vs/base/common/lifecycle*/,21/*vs/base/common/observable*/,75/*vs/editor/common/core/editOperation*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/,828/*vs/editor/contrib/inlineEdit/browser/ghostTextWidget*/,12/*vs/platform/contextkey/common/contextkey*/,7/*vs/platform/instantiation/common/instantiation*/,27/*vs/editor/common/languages*/,17/*vs/editor/common/services/languageFeatures*/,18/*vs/base/common/cancellation*/,204/*vs/editor/contrib/inlineCompletions/browser/model/ghostText*/,24/*vs/platform/commands/common/commands*/,800/*vs/editor/contrib/inlineEdit/browser/inlineEditHintsWidget*/,5/*vs/base/browser/dom*/,28/*vs/platform/configuration/common/configuration*/,8/*vs/base/common/errors*/,65/*vs/base/common/observableInternal/derived*/,829/*vs/editor/contrib/inlineEdit/browser/inlineEditSideBySideWidget*/,215/*vs/editor/browser/widget/diffEditor/diffProviderFactoryService*/,51/*vs/editor/common/services/model*/]), function (require, exports, lifecycle_1, observable_1, editOperation_1, position_1, range_1, ghostTextWidget_1, contextkey_1, instantiation_1, languages_1, languageFeatures_1, cancellation_1, ghostText_1, commands_1, inlineEditHintsWidget_1, dom_1, configuration_1, errors_1, derived_1, inlineEditSideBySideWidget_1, diffProviderFactoryService_1, model_1) {
    "use strict";
    var InlineEditController_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.InlineEditController = void 0;
    let InlineEditController = class InlineEditController extends lifecycle_1.Disposable {
        static { InlineEditController_1 = this; }
        static { this.ID = 'editor.contrib.inlineEditController'; }
        static { this.inlineEditVisibleKey = 'inlineEditVisible'; }
        static { this.inlineEditVisibleContext = new contextkey_1.RawContextKey(this.inlineEditVisibleKey, false); }
        static { this.cursorAtInlineEditKey = 'cursorAtInlineEdit'; }
        static { this.cursorAtInlineEditContext = new contextkey_1.RawContextKey(this.cursorAtInlineEditKey, false); }
        static get(editor) {
            return editor.getContribution(InlineEditController_1.ID);
        }
        constructor(editor, instantiationService, contextKeyService, languageFeaturesService, _commandService, _configurationService, _diffProviderFactoryService, _modelService) {
            super();
            this.editor = editor;
            this.instantiationService = instantiationService;
            this.contextKeyService = contextKeyService;
            this.languageFeaturesService = languageFeaturesService;
            this._commandService = _commandService;
            this._configurationService = _configurationService;
            this._diffProviderFactoryService = _diffProviderFactoryService;
            this._modelService = _modelService;
            this._isVisibleContext = InlineEditController_1.inlineEditVisibleContext.bindTo(this.contextKeyService);
            this._isCursorAtInlineEditContext = InlineEditController_1.cursorAtInlineEditContext.bindTo(this.contextKeyService);
            this._currentEdit = (0, observable_1.observableValue)(this, undefined);
            this._currentWidget = (0, derived_1.derivedDisposable)(this._currentEdit, (reader) => {
                const edit = this._currentEdit.read(reader);
                if (!edit) {
                    return undefined;
                }
                const line = edit.range.endLineNumber;
                const column = edit.range.endColumn;
                const textToDisplay = edit.text.endsWith('\n') && !(edit.range.startLineNumber === edit.range.endLineNumber && edit.range.startColumn === edit.range.endColumn) ? edit.text.slice(0, -1) : edit.text;
                const ghostText = new ghostText_1.GhostText(line, [new ghostText_1.GhostTextPart(column, textToDisplay, false)]);
                //only show ghost text for single line edits
                //unless it is a pure removal
                //multi line edits are shown in the side by side widget
                const isSingleLine = edit.range.startLineNumber === edit.range.endLineNumber && ghostText.parts.length === 1 && ghostText.parts[0].lines.length === 1;
                const isPureRemoval = edit.text === '';
                if (!isSingleLine && !isPureRemoval) {
                    return undefined;
                }
                const instance = this.instantiationService.createInstance(ghostTextWidget_1.GhostTextWidget, this.editor, {
                    ghostText: (0, observable_1.constObservable)(ghostText),
                    minReservedLineCount: (0, observable_1.constObservable)(0),
                    targetTextModel: (0, observable_1.constObservable)(this.editor.getModel() ?? undefined),
                    range: (0, observable_1.constObservable)(edit.range)
                });
                return instance;
            });
            this._isAccepting = (0, observable_1.observableValue)(this, false);
            this._enabled = (0, observable_1.observableFromEvent)(this, this.editor.onDidChangeConfiguration, () => this.editor.getOption(63 /* EditorOption.inlineEdit */).enabled);
            this._fontFamily = (0, observable_1.observableFromEvent)(this, this.editor.onDidChangeConfiguration, () => this.editor.getOption(63 /* EditorOption.inlineEdit */).fontFamily);
            //Automatically request inline edit when the content was changed
            //Cancel the previous request if there is one
            //Remove the previous ghost text
            const modelChangedSignal = (0, observable_1.observableSignalFromEvent)('InlineEditController.modelContentChangedSignal', editor.onDidChangeModelContent);
            this._register((0, observable_1.autorun)(reader => {
                /** @description InlineEditController.modelContentChanged model */
                if (!this._enabled.read(reader)) {
                    return;
                }
                modelChangedSignal.read(reader);
                if (this._isAccepting.read(reader)) {
                    return;
                }
                this.getInlineEdit(editor, true);
            }));
            //Check if the cursor is at the ghost text
            const cursorPosition = (0, observable_1.observableFromEvent)(this, editor.onDidChangeCursorPosition, () => editor.getPosition());
            this._register((0, observable_1.autorun)(reader => {
                /** @description InlineEditController.cursorPositionChanged model */
                if (!this._enabled.read(reader)) {
                    return;
                }
                const pos = cursorPosition.read(reader);
                if (pos) {
                    this.checkCursorPosition(pos);
                }
            }));
            //Perform stuff when the current edit has changed
            this._register((0, observable_1.autorun)((reader) => {
                /** @description InlineEditController.update model */
                const currentEdit = this._currentEdit.read(reader);
                this._isCursorAtInlineEditContext.set(false);
                if (!currentEdit) {
                    this._isVisibleContext.set(false);
                    return;
                }
                this._isVisibleContext.set(true);
                const pos = editor.getPosition();
                if (pos) {
                    this.checkCursorPosition(pos);
                }
            }));
            //Clear suggestions on lost focus
            const editorBlurSingal = (0, observable_1.observableSignalFromEvent)('InlineEditController.editorBlurSignal', editor.onDidBlurEditorWidget);
            this._register((0, observable_1.autorun)(async (reader) => {
                /** @description InlineEditController.editorBlur */
                if (!this._enabled.read(reader)) {
                    return;
                }
                editorBlurSingal.read(reader);
                // This is a hidden setting very useful for debugging
                if (this._configurationService.getValue('editor.experimentalInlineEdit.keepOnBlur') || editor.getOption(63 /* EditorOption.inlineEdit */).keepOnBlur) {
                    return;
                }
                this._currentRequestCts?.dispose(true);
                this._currentRequestCts = undefined;
                await this.clear(false);
            }));
            //Invoke provider on focus
            const editorFocusSignal = (0, observable_1.observableSignalFromEvent)('InlineEditController.editorFocusSignal', editor.onDidFocusEditorText);
            this._register((0, observable_1.autorun)(reader => {
                /** @description InlineEditController.editorFocus */
                if (!this._enabled.read(reader)) {
                    return;
                }
                editorFocusSignal.read(reader);
                this.getInlineEdit(editor, true);
            }));
            //handle changes of font setting
            const styleElement = this._register((0, dom_1.createStyleSheet2)());
            this._register((0, observable_1.autorun)(reader => {
                const fontFamily = this._fontFamily.read(reader);
                styleElement.setStyle(fontFamily === '' || fontFamily === 'default' ? `` : `
.monaco-editor .inline-edit-decoration,
.monaco-editor .inline-edit-decoration-preview,
.monaco-editor .inline-edit {
	font-family: ${fontFamily};
}`);
            }));
            this._register(new inlineEditHintsWidget_1.InlineEditHintsWidget(this.editor, this._currentWidget, this.instantiationService));
            this._register(new inlineEditSideBySideWidget_1.InlineEditSideBySideWidget(this.editor, this._currentEdit, this.instantiationService, this._diffProviderFactoryService, this._modelService));
        }
        checkCursorPosition(position) {
            if (!this._currentEdit) {
                this._isCursorAtInlineEditContext.set(false);
                return;
            }
            const gt = this._currentEdit.get();
            if (!gt) {
                this._isCursorAtInlineEditContext.set(false);
                return;
            }
            this._isCursorAtInlineEditContext.set(range_1.Range.containsPosition(gt.range, position));
        }
        validateInlineEdit(editor, edit) {
            //Multiline inline replacing edit must replace whole lines
            if (edit.text.includes('\n') && edit.range.startLineNumber !== edit.range.endLineNumber && edit.range.startColumn !== edit.range.endColumn) {
                const firstColumn = edit.range.startColumn;
                if (firstColumn !== 1) {
                    return false;
                }
                const lastLine = edit.range.endLineNumber;
                const lastColumn = edit.range.endColumn;
                const lineLength = editor.getModel()?.getLineLength(lastLine) ?? 0;
                if (lastColumn !== lineLength + 1) {
                    return false;
                }
            }
            return true;
        }
        async fetchInlineEdit(editor, auto) {
            if (this._currentRequestCts) {
                this._currentRequestCts.dispose(true);
            }
            const model = editor.getModel();
            if (!model) {
                return;
            }
            const modelVersion = model.getVersionId();
            const providers = this.languageFeaturesService.inlineEditProvider.all(model);
            if (providers.length === 0) {
                return;
            }
            const provider = providers[0];
            this._currentRequestCts = new cancellation_1.CancellationTokenSource();
            const token = this._currentRequestCts.token;
            const triggerKind = auto ? languages_1.InlineEditTriggerKind.Automatic : languages_1.InlineEditTriggerKind.Invoke;
            const shouldDebounce = auto;
            if (shouldDebounce) {
                await wait(50, token);
            }
            if (token.isCancellationRequested || model.isDisposed() || model.getVersionId() !== modelVersion) {
                return;
            }
            const edit = await provider.provideInlineEdit(model, { triggerKind }, token);
            if (!edit) {
                return;
            }
            if (token.isCancellationRequested || model.isDisposed() || model.getVersionId() !== modelVersion) {
                return;
            }
            if (!this.validateInlineEdit(editor, edit)) {
                return;
            }
            return edit;
        }
        async getInlineEdit(editor, auto) {
            this._isCursorAtInlineEditContext.set(false);
            await this.clear();
            const edit = await this.fetchInlineEdit(editor, auto);
            if (!edit) {
                return;
            }
            this._currentEdit.set(edit, undefined);
        }
        async trigger() {
            await this.getInlineEdit(this.editor, false);
        }
        async jumpBack() {
            if (!this._jumpBackPosition) {
                return;
            }
            this.editor.setPosition(this._jumpBackPosition);
            //if position is outside viewports, scroll to it
            this.editor.revealPositionInCenterIfOutsideViewport(this._jumpBackPosition);
        }
        async accept() {
            this._isAccepting.set(true, undefined);
            const data = this._currentEdit.get();
            if (!data) {
                return;
            }
            //It should only happen in case of last line suggestion
            let text = data.text;
            if (data.text.startsWith('\n')) {
                text = data.text.substring(1);
            }
            this.editor.pushUndoStop();
            this.editor.executeEdits('acceptCurrent', [editOperation_1.EditOperation.replace(range_1.Range.lift(data.range), text)]);
            if (data.accepted) {
                await this._commandService
                    .executeCommand(data.accepted.id, ...(data.accepted.arguments || []))
                    .then(undefined, errors_1.onUnexpectedExternalError);
            }
            this.freeEdit(data);
            (0, observable_1.transaction)((tx) => {
                this._currentEdit.set(undefined, tx);
                this._isAccepting.set(false, tx);
            });
        }
        jumpToCurrent() {
            this._jumpBackPosition = this.editor.getSelection()?.getStartPosition();
            const data = this._currentEdit.get();
            if (!data) {
                return;
            }
            const position = position_1.Position.lift({ lineNumber: data.range.startLineNumber, column: data.range.startColumn });
            this.editor.setPosition(position);
            //if position is outside viewports, scroll to it
            this.editor.revealPositionInCenterIfOutsideViewport(position);
        }
        async clear(sendRejection = true) {
            const edit = this._currentEdit.get();
            if (edit && edit?.rejected && sendRejection) {
                await this._commandService
                    .executeCommand(edit.rejected.id, ...(edit.rejected.arguments || []))
                    .then(undefined, errors_1.onUnexpectedExternalError);
            }
            if (edit) {
                this.freeEdit(edit);
            }
            this._currentEdit.set(undefined, undefined);
        }
        freeEdit(edit) {
            const model = this.editor.getModel();
            if (!model) {
                return;
            }
            const providers = this.languageFeaturesService.inlineEditProvider.all(model);
            if (providers.length === 0) {
                return;
            }
            providers[0].freeInlineEdit(edit);
        }
    };
    exports.InlineEditController = InlineEditController;
    exports.InlineEditController = InlineEditController = InlineEditController_1 = __decorate([
        __param(1, instantiation_1.IInstantiationService),
        __param(2, contextkey_1.IContextKeyService),
        __param(3, languageFeatures_1.ILanguageFeaturesService),
        __param(4, commands_1.ICommandService),
        __param(5, configuration_1.IConfigurationService),
        __param(6, diffProviderFactoryService_1.IDiffProviderFactoryService),
        __param(7, model_1.IModelService)
    ], InlineEditController);
    function wait(ms, cancellationToken) {
        return new Promise(resolve => {
            let d = undefined;
            const handle = setTimeout(() => {
                if (d) {
                    d.dispose();
                }
                resolve();
            }, ms);
            if (cancellationToken) {
                d = cancellationToken.onCancellationRequested(() => {
                    clearTimeout(handle);
                    if (d) {
                        d.dispose();
                    }
                    resolve();
                });
            }
        });
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[830/*vs/editor/contrib/inlineEdit/browser/commands*/], __M([1/*require*/,0/*exports*/,15/*vs/editor/browser/editorExtensions*/,20/*vs/editor/common/editorContextKeys*/,618/*vs/editor/contrib/inlineEdit/browser/commandIds*/,425/*vs/editor/contrib/inlineEdit/browser/inlineEditController*/,29/*vs/platform/actions/common/actions*/,12/*vs/platform/contextkey/common/contextkey*/]), function (require, exports, editorExtensions_1, editorContextKeys_1, commandIds_1, inlineEditController_1, actions_1, contextkey_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.RejectInlineEdit = exports.JumpBackInlineEdit = exports.JumpToInlineEdit = exports.TriggerInlineEdit = exports.AcceptInlineEdit = void 0;
    class AcceptInlineEdit extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: commandIds_1.inlineEditAcceptId,
                label: 'Accept Inline Edit',
                alias: 'Accept Inline Edit',
                precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, inlineEditController_1.InlineEditController.inlineEditVisibleContext),
                kbOpts: [
                    {
                        weight: 100 /* KeybindingWeight.EditorContrib */ + 1,
                        primary: 2 /* KeyCode.Tab */,
                        kbExpr: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, inlineEditController_1.InlineEditController.inlineEditVisibleContext, inlineEditController_1.InlineEditController.cursorAtInlineEditContext)
                    }
                ],
                menuOpts: [{
                        menuId: actions_1.MenuId.InlineEditToolbar,
                        title: 'Accept',
                        group: 'primary',
                        order: 1,
                    }],
            });
        }
        async run(accessor, editor) {
            const controller = inlineEditController_1.InlineEditController.get(editor);
            await controller?.accept();
        }
    }
    exports.AcceptInlineEdit = AcceptInlineEdit;
    class TriggerInlineEdit extends editorExtensions_1.EditorAction {
        constructor() {
            const activeExpr = contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, contextkey_1.ContextKeyExpr.not(inlineEditController_1.InlineEditController.inlineEditVisibleKey));
            super({
                id: 'editor.action.inlineEdit.trigger',
                label: 'Trigger Inline Edit',
                alias: 'Trigger Inline Edit',
                precondition: activeExpr,
                kbOpts: {
                    weight: 100 /* KeybindingWeight.EditorContrib */ + 1,
                    primary: 2048 /* KeyMod.CtrlCmd */ | 512 /* KeyMod.Alt */ | 86 /* KeyCode.Equal */,
                    kbExpr: activeExpr
                },
            });
        }
        async run(accessor, editor) {
            const controller = inlineEditController_1.InlineEditController.get(editor);
            controller?.trigger();
        }
    }
    exports.TriggerInlineEdit = TriggerInlineEdit;
    class JumpToInlineEdit extends editorExtensions_1.EditorAction {
        constructor() {
            const activeExpr = contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, inlineEditController_1.InlineEditController.inlineEditVisibleContext, contextkey_1.ContextKeyExpr.not(inlineEditController_1.InlineEditController.cursorAtInlineEditKey));
            super({
                id: commandIds_1.inlineEditJumpToId,
                label: 'Jump to Inline Edit',
                alias: 'Jump to Inline Edit',
                precondition: activeExpr,
                kbOpts: {
                    weight: 100 /* KeybindingWeight.EditorContrib */ + 1,
                    primary: 2048 /* KeyMod.CtrlCmd */ | 512 /* KeyMod.Alt */ | 86 /* KeyCode.Equal */,
                    kbExpr: activeExpr
                },
                menuOpts: [{
                        menuId: actions_1.MenuId.InlineEditToolbar,
                        title: 'Jump To Edit',
                        group: 'primary',
                        order: 3,
                        when: activeExpr
                    }],
            });
        }
        async run(accessor, editor) {
            const controller = inlineEditController_1.InlineEditController.get(editor);
            controller?.jumpToCurrent();
        }
    }
    exports.JumpToInlineEdit = JumpToInlineEdit;
    class JumpBackInlineEdit extends editorExtensions_1.EditorAction {
        constructor() {
            const activeExpr = contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, inlineEditController_1.InlineEditController.cursorAtInlineEditContext);
            super({
                id: commandIds_1.inlineEditJumpBackId,
                label: 'Jump Back from Inline Edit',
                alias: 'Jump Back from Inline Edit',
                precondition: activeExpr,
                kbOpts: {
                    weight: 100 /* KeybindingWeight.EditorContrib */ + 10,
                    primary: 2048 /* KeyMod.CtrlCmd */ | 512 /* KeyMod.Alt */ | 86 /* KeyCode.Equal */,
                    kbExpr: activeExpr
                },
                menuOpts: [{
                        menuId: actions_1.MenuId.InlineEditToolbar,
                        title: 'Jump Back',
                        group: 'primary',
                        order: 3,
                        when: activeExpr
                    }],
            });
        }
        async run(accessor, editor) {
            const controller = inlineEditController_1.InlineEditController.get(editor);
            controller?.jumpBack();
        }
    }
    exports.JumpBackInlineEdit = JumpBackInlineEdit;
    class RejectInlineEdit extends editorExtensions_1.EditorAction {
        constructor() {
            const activeExpr = contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, inlineEditController_1.InlineEditController.inlineEditVisibleContext);
            super({
                id: commandIds_1.inlineEditRejectId,
                label: 'Reject Inline Edit',
                alias: 'Reject Inline Edit',
                precondition: activeExpr,
                kbOpts: {
                    weight: 100 /* KeybindingWeight.EditorContrib */,
                    primary: 9 /* KeyCode.Escape */,
                    kbExpr: activeExpr
                },
                menuOpts: [{
                        menuId: actions_1.MenuId.InlineEditToolbar,
                        title: 'Reject',
                        group: 'secondary',
                        order: 2,
                    }],
            });
        }
        async run(accessor, editor) {
            const controller = inlineEditController_1.InlineEditController.get(editor);
            await controller?.clear();
        }
    }
    exports.RejectInlineEdit = RejectInlineEdit;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[831/*vs/editor/contrib/inlineEdit/browser/inlineEdit.contribution*/], __M([1/*require*/,0/*exports*/,15/*vs/editor/browser/editorExtensions*/,830/*vs/editor/contrib/inlineEdit/browser/commands*/,425/*vs/editor/contrib/inlineEdit/browser/inlineEditController*/]), function (require, exports, editorExtensions_1, commands_1, inlineEditController_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    (0, editorExtensions_1.registerEditorAction)(commands_1.AcceptInlineEdit);
    (0, editorExtensions_1.registerEditorAction)(commands_1.RejectInlineEdit);
    (0, editorExtensions_1.registerEditorAction)(commands_1.JumpToInlineEdit);
    (0, editorExtensions_1.registerEditorAction)(commands_1.JumpBackInlineEdit);
    (0, editorExtensions_1.registerEditorAction)(commands_1.TriggerInlineEdit);
    (0, editorExtensions_1.registerEditorContribution)(inlineEditController_1.InlineEditController.ID, inlineEditController_1.InlineEditController, 3 /* EditorContributionInstantiation.Eventually */);
});
// HoverParticipantRegistry.register(InlineEditHoverParticipant);

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[290/*vs/editor/contrib/inlineProgress/browser/inlineProgress*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,14/*vs/base/common/async*/,26/*vs/base/common/codicons*/,2/*vs/base/common/lifecycle*/,11/*vs/base/common/strings*/,30/*vs/base/common/themables*/,4/*vs/editor/common/core/range*/,35/*vs/editor/common/model/textModel*/,7/*vs/platform/instantiation/common/instantiation*/,522/*vs/css!vs/editor/contrib/inlineProgress/browser/inlineProgressWidget*/]), function (require, exports, dom, async_1, codicons_1, lifecycle_1, strings_1, themables_1, range_1, textModel_1, instantiation_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.InlineProgressManager = void 0;
    const inlineProgressDecoration = textModel_1.ModelDecorationOptions.register({
        description: 'inline-progress-widget',
        stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */,
        showIfCollapsed: true,
        after: {
            content: strings_1.noBreakWhitespace,
            inlineClassName: 'inline-editor-progress-decoration',
            inlineClassNameAffectsLetterSpacing: true,
        }
    });
    class InlineProgressWidget extends lifecycle_1.Disposable {
        static { this.baseId = 'editor.widget.inlineProgressWidget'; }
        constructor(typeId, editor, range, title, delegate) {
            super();
            this.typeId = typeId;
            this.editor = editor;
            this.range = range;
            this.delegate = delegate;
            this.allowEditorOverflow = false;
            this.suppressMouseDown = true;
            this.create(title);
            this.editor.addContentWidget(this);
            this.editor.layoutContentWidget(this);
        }
        create(title) {
            this.domNode = dom.$('.inline-progress-widget');
            this.domNode.role = 'button';
            this.domNode.title = title;
            const iconElement = dom.$('span.icon');
            this.domNode.append(iconElement);
            iconElement.classList.add(...themables_1.ThemeIcon.asClassNameArray(codicons_1.Codicon.loading), 'codicon-modifier-spin');
            const updateSize = () => {
                const lineHeight = this.editor.getOption(67 /* EditorOption.lineHeight */);
                this.domNode.style.height = `${lineHeight}px`;
                this.domNode.style.width = `${Math.ceil(0.8 * lineHeight)}px`;
            };
            updateSize();
            this._register(this.editor.onDidChangeConfiguration(c => {
                if (c.hasChanged(52 /* EditorOption.fontSize */) || c.hasChanged(67 /* EditorOption.lineHeight */)) {
                    updateSize();
                }
            }));
            this._register(dom.addDisposableListener(this.domNode, dom.EventType.CLICK, e => {
                this.delegate.cancel();
            }));
        }
        getId() {
            return InlineProgressWidget.baseId + '.' + this.typeId;
        }
        getDomNode() {
            return this.domNode;
        }
        getPosition() {
            return {
                position: { lineNumber: this.range.startLineNumber, column: this.range.startColumn },
                preference: [0 /* ContentWidgetPositionPreference.EXACT */]
            };
        }
        dispose() {
            super.dispose();
            this.editor.removeContentWidget(this);
        }
    }
    let InlineProgressManager = class InlineProgressManager extends lifecycle_1.Disposable {
        constructor(id, _editor, _instantiationService) {
            super();
            this.id = id;
            this._editor = _editor;
            this._instantiationService = _instantiationService;
            /** Delay before showing the progress widget */
            this._showDelay = 500; // ms
            this._showPromise = this._register(new lifecycle_1.MutableDisposable());
            this._currentWidget = this._register(new lifecycle_1.MutableDisposable());
            this._operationIdPool = 0;
            this._currentDecorations = _editor.createDecorationsCollection();
        }
        dispose() {
            super.dispose();
            this._currentDecorations.clear();
        }
        async showWhile(position, title, promise, delegate, delayOverride) {
            const operationId = this._operationIdPool++;
            this._currentOperation = operationId;
            this.clear();
            this._showPromise.value = (0, async_1.disposableTimeout)(() => {
                const range = range_1.Range.fromPositions(position);
                const decorationIds = this._currentDecorations.set([{
                        range: range,
                        options: inlineProgressDecoration,
                    }]);
                if (decorationIds.length > 0) {
                    this._currentWidget.value = this._instantiationService.createInstance(InlineProgressWidget, this.id, this._editor, range, title, delegate);
                }
            }, delayOverride ?? this._showDelay);
            try {
                return await promise;
            }
            finally {
                if (this._currentOperation === operationId) {
                    this.clear();
                    this._currentOperation = undefined;
                }
            }
        }
        clear() {
            this._showPromise.clear();
            this._currentDecorations.clear();
            this._currentWidget.clear();
        }
    };
    exports.InlineProgressManager = InlineProgressManager;
    exports.InlineProgressManager = InlineProgressManager = __decorate([
        __param(2, instantiation_1.IInstantiationService)
    ], InlineProgressManager);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[832/*vs/editor/contrib/dropOrPasteInto/browser/dropIntoEditorController*/], __M([1/*require*/,0/*exports*/,13/*vs/base/common/arrays*/,14/*vs/base/common/async*/,194/*vs/base/common/dataTransfer*/,91/*vs/base/common/hierarchicalKind*/,2/*vs/base/common/lifecycle*/,400/*vs/editor/browser/dnd*/,4/*vs/editor/common/core/range*/,17/*vs/editor/common/services/languageFeatures*/,327/*vs/editor/common/services/treeViewsDnd*/,678/*vs/editor/common/services/treeViewsDndService*/,122/*vs/editor/contrib/editorState/browser/editorState*/,290/*vs/editor/contrib/inlineProgress/browser/inlineProgress*/,3/*vs/nls*/,28/*vs/platform/configuration/common/configuration*/,12/*vs/platform/contextkey/common/contextkey*/,399/*vs/platform/dnd/browser/dnd*/,7/*vs/platform/instantiation/common/instantiation*/,268/*vs/editor/contrib/dropOrPasteInto/browser/edit*/,396/*vs/editor/contrib/dropOrPasteInto/browser/postEditWidget*/]), function (require, exports, arrays_1, async_1, dataTransfer_1, hierarchicalKind_1, lifecycle_1, dnd_1, range_1, languageFeatures_1, treeViewsDnd_1, treeViewsDndService_1, editorState_1, inlineProgress_1, nls_1, configuration_1, contextkey_1, dnd_2, instantiation_1, edit_1, postEditWidget_1) {
    "use strict";
    var DropIntoEditorController_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DropIntoEditorController = exports.dropWidgetVisibleCtx = exports.changeDropTypeCommandId = exports.defaultProviderConfig = void 0;
    exports.defaultProviderConfig = 'editor.experimental.dropIntoEditor.defaultProvider';
    exports.changeDropTypeCommandId = 'editor.changeDropType';
    exports.dropWidgetVisibleCtx = new contextkey_1.RawContextKey('dropWidgetVisible', false, (0, nls_1.localize)(842, "Whether the drop widget is showing"));
    let DropIntoEditorController = class DropIntoEditorController extends lifecycle_1.Disposable {
        static { DropIntoEditorController_1 = this; }
        static { this.ID = 'editor.contrib.dropIntoEditorController'; }
        static get(editor) {
            return editor.getContribution(DropIntoEditorController_1.ID);
        }
        constructor(editor, instantiationService, _configService, _languageFeaturesService, _treeViewsDragAndDropService) {
            super();
            this._configService = _configService;
            this._languageFeaturesService = _languageFeaturesService;
            this._treeViewsDragAndDropService = _treeViewsDragAndDropService;
            this.treeItemsTransfer = dnd_2.LocalSelectionTransfer.getInstance();
            this._dropProgressManager = this._register(instantiationService.createInstance(inlineProgress_1.InlineProgressManager, 'dropIntoEditor', editor));
            this._postDropWidgetManager = this._register(instantiationService.createInstance(postEditWidget_1.PostEditWidgetManager, 'dropIntoEditor', editor, exports.dropWidgetVisibleCtx, { id: exports.changeDropTypeCommandId, label: (0, nls_1.localize)(843, "Show drop options...") }));
            this._register(editor.onDropIntoEditor(e => this.onDropIntoEditor(editor, e.position, e.event)));
        }
        clearWidgets() {
            this._postDropWidgetManager.clear();
        }
        changeDropType() {
            this._postDropWidgetManager.tryShowSelector();
        }
        async onDropIntoEditor(editor, position, dragEvent) {
            if (!dragEvent.dataTransfer || !editor.hasModel()) {
                return;
            }
            this._currentOperation?.cancel();
            editor.focus();
            editor.setPosition(position);
            const p = (0, async_1.createCancelablePromise)(async (token) => {
                const disposables = new lifecycle_1.DisposableStore();
                const tokenSource = disposables.add(new editorState_1.EditorStateCancellationTokenSource(editor, 1 /* CodeEditorStateFlag.Value */, undefined, token));
                try {
                    const ourDataTransfer = await this.extractDataTransferData(dragEvent);
                    if (ourDataTransfer.size === 0 || tokenSource.token.isCancellationRequested) {
                        return;
                    }
                    const model = editor.getModel();
                    if (!model) {
                        return;
                    }
                    const providers = this._languageFeaturesService.documentDropEditProvider
                        .ordered(model)
                        .filter(provider => {
                        if (!provider.dropMimeTypes) {
                            // Keep all providers that don't specify mime types
                            return true;
                        }
                        return provider.dropMimeTypes.some(mime => ourDataTransfer.matches(mime));
                    });
                    const editSession = disposables.add(await this.getDropEdits(providers, model, position, ourDataTransfer, tokenSource));
                    if (tokenSource.token.isCancellationRequested) {
                        return;
                    }
                    if (editSession.edits.length) {
                        const activeEditIndex = this.getInitialActiveEditIndex(model, editSession.edits);
                        const canShowWidget = editor.getOption(36 /* EditorOption.dropIntoEditor */).showDropSelector === 'afterDrop';
                        // Pass in the parent token here as it tracks cancelling the entire drop operation
                        await this._postDropWidgetManager.applyEditAndShowIfNeeded([range_1.Range.fromPositions(position)], { activeEditIndex, allEdits: editSession.edits }, canShowWidget, async (edit) => edit, token);
                    }
                }
                finally {
                    disposables.dispose();
                    if (this._currentOperation === p) {
                        this._currentOperation = undefined;
                    }
                }
            });
            this._dropProgressManager.showWhile(position, (0, nls_1.localize)(844, "Running drop handlers. Click to cancel"), p, { cancel: () => p.cancel() });
            this._currentOperation = p;
        }
        async getDropEdits(providers, model, position, dataTransfer, tokenSource) {
            const disposables = new lifecycle_1.DisposableStore();
            const results = await (0, async_1.raceCancellation)(Promise.all(providers.map(async (provider) => {
                try {
                    const edits = await provider.provideDocumentDropEdits(model, position, dataTransfer, tokenSource.token);
                    if (edits) {
                        disposables.add(edits);
                    }
                    return edits?.edits.map(edit => ({ ...edit, providerId: provider.id }));
                }
                catch (err) {
                    console.error(err);
                }
                return undefined;
            })), tokenSource.token);
            const edits = (0, arrays_1.coalesce)(results ?? []).flat();
            return {
                edits: (0, edit_1.sortEditsByYieldTo)(edits),
                dispose: () => disposables.dispose()
            };
        }
        getInitialActiveEditIndex(model, edits) {
            const preferredProviders = this._configService.getValue(exports.defaultProviderConfig, { resource: model.uri });
            for (const [configMime, desiredKindStr] of Object.entries(preferredProviders)) {
                const desiredKind = new hierarchicalKind_1.HierarchicalKind(desiredKindStr);
                const editIndex = edits.findIndex(edit => desiredKind.value === edit.providerId
                    && edit.handledMimeType && (0, dataTransfer_1.matchesMimeType)(configMime, [edit.handledMimeType]));
                if (editIndex >= 0) {
                    return editIndex;
                }
            }
            return 0;
        }
        async extractDataTransferData(dragEvent) {
            if (!dragEvent.dataTransfer) {
                return new dataTransfer_1.VSDataTransfer();
            }
            const dataTransfer = (0, dnd_1.toExternalVSDataTransfer)(dragEvent.dataTransfer);
            if (this.treeItemsTransfer.hasData(treeViewsDnd_1.DraggedTreeItemsIdentifier.prototype)) {
                const data = this.treeItemsTransfer.getData(treeViewsDnd_1.DraggedTreeItemsIdentifier.prototype);
                if (Array.isArray(data)) {
                    for (const id of data) {
                        const treeDataTransfer = await this._treeViewsDragAndDropService.removeDragOperationTransfer(id.identifier);
                        if (treeDataTransfer) {
                            for (const [type, value] of treeDataTransfer) {
                                dataTransfer.replace(type, value);
                            }
                        }
                    }
                }
            }
            return dataTransfer;
        }
    };
    exports.DropIntoEditorController = DropIntoEditorController;
    exports.DropIntoEditorController = DropIntoEditorController = DropIntoEditorController_1 = __decorate([
        __param(1, instantiation_1.IInstantiationService),
        __param(2, configuration_1.IConfigurationService),
        __param(3, languageFeatures_1.ILanguageFeaturesService),
        __param(4, treeViewsDndService_1.ITreeViewsDnDService)
    ], DropIntoEditorController);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[833/*vs/editor/contrib/linkedEditing/browser/linkedEditing*/], __M([1/*require*/,0/*exports*/,13/*vs/base/common/arrays*/,14/*vs/base/common/async*/,18/*vs/base/common/cancellation*/,33/*vs/base/common/color*/,8/*vs/base/common/errors*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,11/*vs/base/common/strings*/,22/*vs/base/common/uri*/,15/*vs/editor/browser/editorExtensions*/,34/*vs/editor/browser/services/codeEditorService*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/,20/*vs/editor/common/editorContextKeys*/,35/*vs/editor/common/model/textModel*/,36/*vs/editor/common/languages/languageConfigurationRegistry*/,3/*vs/nls*/,12/*vs/platform/contextkey/common/contextkey*/,17/*vs/editor/common/services/languageFeatures*/,32/*vs/platform/theme/common/colorRegistry*/,79/*vs/editor/common/services/languageFeatureDebounce*/,54/*vs/base/common/stopwatch*/,523/*vs/css!vs/editor/contrib/linkedEditing/browser/linkedEditing*/]), function (require, exports, arrays, async_1, cancellation_1, color_1, errors_1, event_1, lifecycle_1, strings, uri_1, editorExtensions_1, codeEditorService_1, position_1, range_1, editorContextKeys_1, textModel_1, languageConfigurationRegistry_1, nls, contextkey_1, languageFeatures_1, colorRegistry_1, languageFeatureDebounce_1, stopwatch_1) {
    "use strict";
    var LinkedEditingContribution_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.editorLinkedEditingBackground = exports.LinkedEditingAction = exports.LinkedEditingContribution = exports.CONTEXT_ONTYPE_RENAME_INPUT_VISIBLE = void 0;
    exports.CONTEXT_ONTYPE_RENAME_INPUT_VISIBLE = new contextkey_1.RawContextKey('LinkedEditingInputVisible', false);
    const DECORATION_CLASS_NAME = 'linked-editing-decoration';
    let LinkedEditingContribution = class LinkedEditingContribution extends lifecycle_1.Disposable {
        static { LinkedEditingContribution_1 = this; }
        static { this.ID = 'editor.contrib.linkedEditing'; }
        static { this.DECORATION = textModel_1.ModelDecorationOptions.register({
            description: 'linked-editing',
            stickiness: 0 /* TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges */,
            className: DECORATION_CLASS_NAME
        }); }
        static get(editor) {
            return editor.getContribution(LinkedEditingContribution_1.ID);
        }
        constructor(editor, contextKeyService, languageFeaturesService, languageConfigurationService, languageFeatureDebounceService) {
            super();
            this.languageConfigurationService = languageConfigurationService;
            this._syncRangesToken = 0;
            this._localToDispose = this._register(new lifecycle_1.DisposableStore());
            this._editor = editor;
            this._providers = languageFeaturesService.linkedEditingRangeProvider;
            this._enabled = false;
            this._visibleContextKey = exports.CONTEXT_ONTYPE_RENAME_INPUT_VISIBLE.bindTo(contextKeyService);
            this._debounceInformation = languageFeatureDebounceService.for(this._providers, 'Linked Editing', { max: 200 });
            this._currentDecorations = this._editor.createDecorationsCollection();
            this._languageWordPattern = null;
            this._currentWordPattern = null;
            this._ignoreChangeEvent = false;
            this._localToDispose = this._register(new lifecycle_1.DisposableStore());
            this._rangeUpdateTriggerPromise = null;
            this._rangeSyncTriggerPromise = null;
            this._currentRequestCts = null;
            this._currentRequestPosition = null;
            this._currentRequestModelVersion = null;
            this._register(this._editor.onDidChangeModel(() => this.reinitialize(true)));
            this._register(this._editor.onDidChangeConfiguration(e => {
                if (e.hasChanged(70 /* EditorOption.linkedEditing */) || e.hasChanged(94 /* EditorOption.renameOnType */)) {
                    this.reinitialize(false);
                }
            }));
            this._register(this._providers.onDidChange(() => this.reinitialize(false)));
            this._register(this._editor.onDidChangeModelLanguage(() => this.reinitialize(true)));
            this.reinitialize(true);
        }
        reinitialize(forceRefresh) {
            const model = this._editor.getModel();
            const isEnabled = model !== null && (this._editor.getOption(70 /* EditorOption.linkedEditing */) || this._editor.getOption(94 /* EditorOption.renameOnType */)) && this._providers.has(model);
            if (isEnabled === this._enabled && !forceRefresh) {
                return;
            }
            this._enabled = isEnabled;
            this.clearRanges();
            this._localToDispose.clear();
            if (!isEnabled || model === null) {
                return;
            }
            this._localToDispose.add(event_1.Event.runAndSubscribe(model.onDidChangeLanguageConfiguration, () => {
                this._languageWordPattern = this.languageConfigurationService.getLanguageConfiguration(model.getLanguageId()).getWordDefinition();
            }));
            const rangeUpdateScheduler = new async_1.Delayer(this._debounceInformation.get(model));
            const triggerRangeUpdate = () => {
                this._rangeUpdateTriggerPromise = rangeUpdateScheduler.trigger(() => this.updateRanges(), this._debounceDuration ?? this._debounceInformation.get(model));
            };
            const rangeSyncScheduler = new async_1.Delayer(0);
            const triggerRangeSync = (token) => {
                this._rangeSyncTriggerPromise = rangeSyncScheduler.trigger(() => this._syncRanges(token));
            };
            this._localToDispose.add(this._editor.onDidChangeCursorPosition(() => {
                triggerRangeUpdate();
            }));
            this._localToDispose.add(this._editor.onDidChangeModelContent((e) => {
                if (!this._ignoreChangeEvent) {
                    if (this._currentDecorations.length > 0) {
                        const referenceRange = this._currentDecorations.getRange(0);
                        if (referenceRange && e.changes.every(c => referenceRange.intersectRanges(c.range))) {
                            triggerRangeSync(this._syncRangesToken);
                            return;
                        }
                    }
                }
                triggerRangeUpdate();
            }));
            this._localToDispose.add({
                dispose: () => {
                    rangeUpdateScheduler.dispose();
                    rangeSyncScheduler.dispose();
                }
            });
            this.updateRanges();
        }
        _syncRanges(token) {
            // delayed invocation, make sure we're still on
            if (!this._editor.hasModel() || token !== this._syncRangesToken || this._currentDecorations.length === 0) {
                // nothing to do
                return;
            }
            const model = this._editor.getModel();
            const referenceRange = this._currentDecorations.getRange(0);
            if (!referenceRange || referenceRange.startLineNumber !== referenceRange.endLineNumber) {
                return this.clearRanges();
            }
            const referenceValue = model.getValueInRange(referenceRange);
            if (this._currentWordPattern) {
                const match = referenceValue.match(this._currentWordPattern);
                const matchLength = match ? match[0].length : 0;
                if (matchLength !== referenceValue.length) {
                    return this.clearRanges();
                }
            }
            const edits = [];
            for (let i = 1, len = this._currentDecorations.length; i < len; i++) {
                const mirrorRange = this._currentDecorations.getRange(i);
                if (!mirrorRange) {
                    continue;
                }
                if (mirrorRange.startLineNumber !== mirrorRange.endLineNumber) {
                    edits.push({
                        range: mirrorRange,
                        text: referenceValue
                    });
                }
                else {
                    let oldValue = model.getValueInRange(mirrorRange);
                    let newValue = referenceValue;
                    let rangeStartColumn = mirrorRange.startColumn;
                    let rangeEndColumn = mirrorRange.endColumn;
                    const commonPrefixLength = strings.commonPrefixLength(oldValue, newValue);
                    rangeStartColumn += commonPrefixLength;
                    oldValue = oldValue.substr(commonPrefixLength);
                    newValue = newValue.substr(commonPrefixLength);
                    const commonSuffixLength = strings.commonSuffixLength(oldValue, newValue);
                    rangeEndColumn -= commonSuffixLength;
                    oldValue = oldValue.substr(0, oldValue.length - commonSuffixLength);
                    newValue = newValue.substr(0, newValue.length - commonSuffixLength);
                    if (rangeStartColumn !== rangeEndColumn || newValue.length !== 0) {
                        edits.push({
                            range: new range_1.Range(mirrorRange.startLineNumber, rangeStartColumn, mirrorRange.endLineNumber, rangeEndColumn),
                            text: newValue
                        });
                    }
                }
            }
            if (edits.length === 0) {
                return;
            }
            try {
                this._editor.popUndoStop();
                this._ignoreChangeEvent = true;
                const prevEditOperationType = this._editor._getViewModel().getPrevEditOperationType();
                this._editor.executeEdits('linkedEditing', edits);
                this._editor._getViewModel().setPrevEditOperationType(prevEditOperationType);
            }
            finally {
                this._ignoreChangeEvent = false;
            }
        }
        dispose() {
            this.clearRanges();
            super.dispose();
        }
        clearRanges() {
            this._visibleContextKey.set(false);
            this._currentDecorations.clear();
            if (this._currentRequestCts) {
                this._currentRequestCts.cancel();
                this._currentRequestCts = null;
                this._currentRequestPosition = null;
            }
        }
        async updateRanges(force = false) {
            if (!this._editor.hasModel()) {
                this.clearRanges();
                return;
            }
            const position = this._editor.getPosition();
            if (!this._enabled && !force || this._editor.getSelections().length > 1) {
                // disabled or multicursor
                this.clearRanges();
                return;
            }
            const model = this._editor.getModel();
            const modelVersionId = model.getVersionId();
            if (this._currentRequestPosition && this._currentRequestModelVersion === modelVersionId) {
                if (position.equals(this._currentRequestPosition)) {
                    return; // same position
                }
                if (this._currentDecorations.length > 0) {
                    const range = this._currentDecorations.getRange(0);
                    if (range && range.containsPosition(position)) {
                        return; // just moving inside the existing primary range
                    }
                }
            }
            // Clear existing decorations while we compute new ones
            this.clearRanges();
            this._currentRequestPosition = position;
            this._currentRequestModelVersion = modelVersionId;
            const currentRequestCts = this._currentRequestCts = new cancellation_1.CancellationTokenSource();
            try {
                const sw = new stopwatch_1.StopWatch(false);
                const response = await getLinkedEditingRanges(this._providers, model, position, currentRequestCts.token);
                this._debounceInformation.update(model, sw.elapsed());
                if (currentRequestCts !== this._currentRequestCts) {
                    return;
                }
                this._currentRequestCts = null;
                if (modelVersionId !== model.getVersionId()) {
                    return;
                }
                let ranges = [];
                if (response?.ranges) {
                    ranges = response.ranges;
                }
                this._currentWordPattern = response?.wordPattern || this._languageWordPattern;
                let foundReferenceRange = false;
                for (let i = 0, len = ranges.length; i < len; i++) {
                    if (range_1.Range.containsPosition(ranges[i], position)) {
                        foundReferenceRange = true;
                        if (i !== 0) {
                            const referenceRange = ranges[i];
                            ranges.splice(i, 1);
                            ranges.unshift(referenceRange);
                        }
                        break;
                    }
                }
                if (!foundReferenceRange) {
                    // Cannot do linked editing if the ranges are not where the cursor is...
                    this.clearRanges();
                    return;
                }
                const decorations = ranges.map(range => ({ range: range, options: LinkedEditingContribution_1.DECORATION }));
                this._visibleContextKey.set(true);
                this._currentDecorations.set(decorations);
                this._syncRangesToken++; // cancel any pending syncRanges call
            }
            catch (err) {
                if (!(0, errors_1.isCancellationError)(err)) {
                    (0, errors_1.onUnexpectedError)(err);
                }
                if (this._currentRequestCts === currentRequestCts || !this._currentRequestCts) {
                    // stop if we are still the latest request
                    this.clearRanges();
                }
            }
        }
    };
    exports.LinkedEditingContribution = LinkedEditingContribution;
    exports.LinkedEditingContribution = LinkedEditingContribution = LinkedEditingContribution_1 = __decorate([
        __param(1, contextkey_1.IContextKeyService),
        __param(2, languageFeatures_1.ILanguageFeaturesService),
        __param(3, languageConfigurationRegistry_1.ILanguageConfigurationService),
        __param(4, languageFeatureDebounce_1.ILanguageFeatureDebounceService)
    ], LinkedEditingContribution);
    class LinkedEditingAction extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: 'editor.action.linkedEditing',
                label: nls.localize(1136, "Start Linked Editing"),
                alias: 'Start Linked Editing',
                precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, editorContextKeys_1.EditorContextKeys.hasRenameProvider),
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 60 /* KeyCode.F2 */,
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
        runCommand(accessor, args) {
            const editorService = accessor.get(codeEditorService_1.ICodeEditorService);
            const [uri, pos] = Array.isArray(args) && args || [undefined, undefined];
            if (uri_1.URI.isUri(uri) && position_1.Position.isIPosition(pos)) {
                return editorService.openCodeEditor({ resource: uri }, editorService.getActiveCodeEditor()).then(editor => {
                    if (!editor) {
                        return;
                    }
                    editor.setPosition(pos);
                    editor.invokeWithinContext(accessor => {
                        this.reportTelemetry(accessor, editor);
                        return this.run(accessor, editor);
                    });
                }, errors_1.onUnexpectedError);
            }
            return super.runCommand(accessor, args);
        }
        run(_accessor, editor) {
            const controller = LinkedEditingContribution.get(editor);
            if (controller) {
                return Promise.resolve(controller.updateRanges(true));
            }
            return Promise.resolve();
        }
    }
    exports.LinkedEditingAction = LinkedEditingAction;
    const LinkedEditingCommand = editorExtensions_1.EditorCommand.bindToContribution(LinkedEditingContribution.get);
    (0, editorExtensions_1.registerEditorCommand)(new LinkedEditingCommand({
        id: 'cancelLinkedEditingInput',
        precondition: exports.CONTEXT_ONTYPE_RENAME_INPUT_VISIBLE,
        handler: x => x.clearRanges(),
        kbOpts: {
            kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
            weight: 100 /* KeybindingWeight.EditorContrib */ + 99,
            primary: 9 /* KeyCode.Escape */,
            secondary: [1024 /* KeyMod.Shift */ | 9 /* KeyCode.Escape */]
        }
    }));
    function getLinkedEditingRanges(providers, model, position, token) {
        const orderedByScore = providers.ordered(model);
        // in order of score ask the linked editing range provider
        // until someone response with a good result
        // (good = not null)
        return (0, async_1.first)(orderedByScore.map(provider => async () => {
            try {
                return await provider.provideLinkedEditingRanges(model, position, token);
            }
            catch (e) {
                (0, errors_1.onUnexpectedExternalError)(e);
                return undefined;
            }
        }), result => !!result && arrays.isNonEmptyArray(result?.ranges));
    }
    exports.editorLinkedEditingBackground = (0, colorRegistry_1.registerColor)('editor.linkedEditingBackground', { dark: color_1.Color.fromHex('#f00').transparent(0.3), light: color_1.Color.fromHex('#f00').transparent(0.3), hcDark: color_1.Color.fromHex('#f00').transparent(0.3), hcLight: color_1.Color.white }, nls.localize(1137, 'Background color when the editor auto renames on type.'));
    (0, editorExtensions_1.registerModelAndPositionCommand)('_executeLinkedEditingProvider', (_accessor, model, position) => {
        const { linkedEditingRangeProvider } = _accessor.get(languageFeatures_1.ILanguageFeaturesService);
        return getLinkedEditingRanges(linkedEditingRangeProvider, model, position, cancellation_1.CancellationToken.None);
    });
    (0, editorExtensions_1.registerEditorContribution)(LinkedEditingContribution.ID, LinkedEditingContribution, 1 /* EditorContributionInstantiation.AfterFirstRender */);
    (0, editorExtensions_1.registerEditorAction)(LinkedEditingAction);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[834/*vs/editor/contrib/links/browser/links*/], __M([1/*require*/,0/*exports*/,14/*vs/base/common/async*/,18/*vs/base/common/cancellation*/,8/*vs/base/common/errors*/,57/*vs/base/common/htmlContent*/,2/*vs/base/common/lifecycle*/,42/*vs/base/common/network*/,16/*vs/base/common/platform*/,48/*vs/base/common/resources*/,54/*vs/base/common/stopwatch*/,22/*vs/base/common/uri*/,15/*vs/editor/browser/editorExtensions*/,35/*vs/editor/common/model/textModel*/,79/*vs/editor/common/services/languageFeatureDebounce*/,17/*vs/editor/common/services/languageFeatures*/,209/*vs/editor/contrib/gotoSymbol/browser/link/clickLinkGesture*/,681/*vs/editor/contrib/links/browser/getLinks*/,3/*vs/nls*/,50/*vs/platform/notification/common/notification*/,59/*vs/platform/opener/common/opener*/,524/*vs/css!vs/editor/contrib/links/browser/links*/]), function (require, exports, async_1, cancellation_1, errors_1, htmlContent_1, lifecycle_1, network_1, platform, resources, stopwatch_1, uri_1, editorExtensions_1, textModel_1, languageFeatureDebounce_1, languageFeatures_1, clickLinkGesture_1, getLinks_1, nls, notification_1, opener_1) {
    "use strict";
    var LinkDetector_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.LinkDetector = void 0;
    let LinkDetector = class LinkDetector extends lifecycle_1.Disposable {
        static { LinkDetector_1 = this; }
        static { this.ID = 'editor.linkDetector'; }
        static get(editor) {
            return editor.getContribution(LinkDetector_1.ID);
        }
        constructor(editor, openerService, notificationService, languageFeaturesService, languageFeatureDebounceService) {
            super();
            this.editor = editor;
            this.openerService = openerService;
            this.notificationService = notificationService;
            this.languageFeaturesService = languageFeaturesService;
            this.providers = this.languageFeaturesService.linkProvider;
            this.debounceInformation = languageFeatureDebounceService.for(this.providers, 'Links', { min: 1000, max: 4000 });
            this.computeLinks = this._register(new async_1.RunOnceScheduler(() => this.computeLinksNow(), 1000));
            this.computePromise = null;
            this.activeLinksList = null;
            this.currentOccurrences = {};
            this.activeLinkDecorationId = null;
            const clickLinkGesture = this._register(new clickLinkGesture_1.ClickLinkGesture(editor));
            this._register(clickLinkGesture.onMouseMoveOrRelevantKeyDown(([mouseEvent, keyboardEvent]) => {
                this._onEditorMouseMove(mouseEvent, keyboardEvent);
            }));
            this._register(clickLinkGesture.onExecute((e) => {
                this.onEditorMouseUp(e);
            }));
            this._register(clickLinkGesture.onCancel((e) => {
                this.cleanUpActiveLinkDecoration();
            }));
            this._register(editor.onDidChangeConfiguration((e) => {
                if (!e.hasChanged(71 /* EditorOption.links */)) {
                    return;
                }
                // Remove any links (for the getting disabled case)
                this.updateDecorations([]);
                // Stop any computation (for the getting disabled case)
                this.stop();
                // Start computing (for the getting enabled case)
                this.computeLinks.schedule(0);
            }));
            this._register(editor.onDidChangeModelContent((e) => {
                if (!this.editor.hasModel()) {
                    return;
                }
                this.computeLinks.schedule(this.debounceInformation.get(this.editor.getModel()));
            }));
            this._register(editor.onDidChangeModel((e) => {
                this.currentOccurrences = {};
                this.activeLinkDecorationId = null;
                this.stop();
                this.computeLinks.schedule(0);
            }));
            this._register(editor.onDidChangeModelLanguage((e) => {
                this.stop();
                this.computeLinks.schedule(0);
            }));
            this._register(this.providers.onDidChange((e) => {
                this.stop();
                this.computeLinks.schedule(0);
            }));
            this.computeLinks.schedule(0);
        }
        async computeLinksNow() {
            if (!this.editor.hasModel() || !this.editor.getOption(71 /* EditorOption.links */)) {
                return;
            }
            const model = this.editor.getModel();
            if (model.isTooLargeForSyncing()) {
                return;
            }
            if (!this.providers.has(model)) {
                return;
            }
            if (this.activeLinksList) {
                this.activeLinksList.dispose();
                this.activeLinksList = null;
            }
            this.computePromise = (0, async_1.createCancelablePromise)(token => (0, getLinks_1.getLinks)(this.providers, model, token));
            try {
                const sw = new stopwatch_1.StopWatch(false);
                this.activeLinksList = await this.computePromise;
                this.debounceInformation.update(model, sw.elapsed());
                if (model.isDisposed()) {
                    return;
                }
                this.updateDecorations(this.activeLinksList.links);
            }
            catch (err) {
                (0, errors_1.onUnexpectedError)(err);
            }
            finally {
                this.computePromise = null;
            }
        }
        updateDecorations(links) {
            const useMetaKey = (this.editor.getOption(78 /* EditorOption.multiCursorModifier */) === 'altKey');
            const oldDecorations = [];
            const keys = Object.keys(this.currentOccurrences);
            for (const decorationId of keys) {
                const occurence = this.currentOccurrences[decorationId];
                oldDecorations.push(occurence.decorationId);
            }
            const newDecorations = [];
            if (links) {
                // Not sure why this is sometimes null
                for (const link of links) {
                    newDecorations.push(LinkOccurrence.decoration(link, useMetaKey));
                }
            }
            this.editor.changeDecorations((changeAccessor) => {
                const decorations = changeAccessor.deltaDecorations(oldDecorations, newDecorations);
                this.currentOccurrences = {};
                this.activeLinkDecorationId = null;
                for (let i = 0, len = decorations.length; i < len; i++) {
                    const occurence = new LinkOccurrence(links[i], decorations[i]);
                    this.currentOccurrences[occurence.decorationId] = occurence;
                }
            });
        }
        _onEditorMouseMove(mouseEvent, withKey) {
            const useMetaKey = (this.editor.getOption(78 /* EditorOption.multiCursorModifier */) === 'altKey');
            if (this.isEnabled(mouseEvent, withKey)) {
                this.cleanUpActiveLinkDecoration(); // always remove previous link decoration as their can only be one
                const occurrence = this.getLinkOccurrence(mouseEvent.target.position);
                if (occurrence) {
                    this.editor.changeDecorations((changeAccessor) => {
                        occurrence.activate(changeAccessor, useMetaKey);
                        this.activeLinkDecorationId = occurrence.decorationId;
                    });
                }
            }
            else {
                this.cleanUpActiveLinkDecoration();
            }
        }
        cleanUpActiveLinkDecoration() {
            const useMetaKey = (this.editor.getOption(78 /* EditorOption.multiCursorModifier */) === 'altKey');
            if (this.activeLinkDecorationId) {
                const occurrence = this.currentOccurrences[this.activeLinkDecorationId];
                if (occurrence) {
                    this.editor.changeDecorations((changeAccessor) => {
                        occurrence.deactivate(changeAccessor, useMetaKey);
                    });
                }
                this.activeLinkDecorationId = null;
            }
        }
        onEditorMouseUp(mouseEvent) {
            if (!this.isEnabled(mouseEvent)) {
                return;
            }
            const occurrence = this.getLinkOccurrence(mouseEvent.target.position);
            if (!occurrence) {
                return;
            }
            this.openLinkOccurrence(occurrence, mouseEvent.hasSideBySideModifier, true /* from user gesture */);
        }
        openLinkOccurrence(occurrence, openToSide, fromUserGesture = false) {
            if (!this.openerService) {
                return;
            }
            const { link } = occurrence;
            link.resolve(cancellation_1.CancellationToken.None).then(uri => {
                // Support for relative file URIs of the shape file://./relativeFile.txt or file:///./relativeFile.txt
                if (typeof uri === 'string' && this.editor.hasModel()) {
                    const modelUri = this.editor.getModel().uri;
                    if (modelUri.scheme === network_1.Schemas.file && uri.startsWith(`${network_1.Schemas.file}:`)) {
                        const parsedUri = uri_1.URI.parse(uri);
                        if (parsedUri.scheme === network_1.Schemas.file) {
                            const fsPath = resources.originalFSPath(parsedUri);
                            let relativePath = null;
                            if (fsPath.startsWith('/./') || fsPath.startsWith('\\.\\')) {
                                relativePath = `.${fsPath.substr(1)}`;
                            }
                            else if (fsPath.startsWith('//./') || fsPath.startsWith('\\\\.\\')) {
                                relativePath = `.${fsPath.substr(2)}`;
                            }
                            if (relativePath) {
                                uri = resources.joinPath(modelUri, relativePath);
                            }
                        }
                    }
                }
                return this.openerService.open(uri, { openToSide, fromUserGesture, allowContributedOpeners: true, allowCommands: true, fromWorkspace: true });
            }, err => {
                const messageOrError = err instanceof Error ? err.message : err;
                // different error cases
                if (messageOrError === 'invalid') {
                    this.notificationService.warn(nls.localize(1138, 'Failed to open this link because it is not well-formed: {0}', link.url.toString()));
                }
                else if (messageOrError === 'missing') {
                    this.notificationService.warn(nls.localize(1139, 'Failed to open this link because its target is missing.'));
                }
                else {
                    (0, errors_1.onUnexpectedError)(err);
                }
            });
        }
        getLinkOccurrence(position) {
            if (!this.editor.hasModel() || !position) {
                return null;
            }
            const decorations = this.editor.getModel().getDecorationsInRange({
                startLineNumber: position.lineNumber,
                startColumn: position.column,
                endLineNumber: position.lineNumber,
                endColumn: position.column
            }, 0, true);
            for (const decoration of decorations) {
                const currentOccurrence = this.currentOccurrences[decoration.id];
                if (currentOccurrence) {
                    return currentOccurrence;
                }
            }
            return null;
        }
        isEnabled(mouseEvent, withKey) {
            return Boolean((mouseEvent.target.type === 6 /* MouseTargetType.CONTENT_TEXT */)
                && (mouseEvent.hasTriggerModifier || (withKey && withKey.keyCodeIsTriggerKey)));
        }
        stop() {
            this.computeLinks.cancel();
            if (this.activeLinksList) {
                this.activeLinksList?.dispose();
                this.activeLinksList = null;
            }
            if (this.computePromise) {
                this.computePromise.cancel();
                this.computePromise = null;
            }
        }
        dispose() {
            super.dispose();
            this.stop();
        }
    };
    exports.LinkDetector = LinkDetector;
    exports.LinkDetector = LinkDetector = LinkDetector_1 = __decorate([
        __param(1, opener_1.IOpenerService),
        __param(2, notification_1.INotificationService),
        __param(3, languageFeatures_1.ILanguageFeaturesService),
        __param(4, languageFeatureDebounce_1.ILanguageFeatureDebounceService)
    ], LinkDetector);
    const decoration = {
        general: textModel_1.ModelDecorationOptions.register({
            description: 'detected-link',
            stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */,
            collapseOnReplaceEdit: true,
            inlineClassName: 'detected-link'
        }),
        active: textModel_1.ModelDecorationOptions.register({
            description: 'detected-link-active',
            stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */,
            collapseOnReplaceEdit: true,
            inlineClassName: 'detected-link-active'
        })
    };
    class LinkOccurrence {
        static decoration(link, useMetaKey) {
            return {
                range: link.range,
                options: LinkOccurrence._getOptions(link, useMetaKey, false)
            };
        }
        static _getOptions(link, useMetaKey, isActive) {
            const options = { ...(isActive ? decoration.active : decoration.general) };
            options.hoverMessage = getHoverMessage(link, useMetaKey);
            return options;
        }
        constructor(link, decorationId) {
            this.link = link;
            this.decorationId = decorationId;
        }
        activate(changeAccessor, useMetaKey) {
            changeAccessor.changeDecorationOptions(this.decorationId, LinkOccurrence._getOptions(this.link, useMetaKey, true));
        }
        deactivate(changeAccessor, useMetaKey) {
            changeAccessor.changeDecorationOptions(this.decorationId, LinkOccurrence._getOptions(this.link, useMetaKey, false));
        }
    }
    function getHoverMessage(link, useMetaKey) {
        const executeCmd = link.url && /^command:/i.test(link.url.toString());
        const label = link.tooltip
            ? link.tooltip
            : executeCmd
                ? nls.localize(1140, 'Execute command')
                : nls.localize(1141, 'Follow link');
        const kb = useMetaKey
            ? platform.isMacintosh
                ? nls.localize(1142, "cmd + click")
                : nls.localize(1143, "ctrl + click")
            : platform.isMacintosh
                ? nls.localize(1144, "option + click")
                : nls.localize(1145, "alt + click");
        if (link.url) {
            let nativeLabel = '';
            if (/^command:/i.test(link.url.toString())) {
                // Don't show complete command arguments in the native tooltip
                const match = link.url.toString().match(/^command:([^?#]+)/);
                if (match) {
                    const commandId = match[1];
                    nativeLabel = nls.localize(1146, "Execute command {0}", commandId);
                }
            }
            const hoverMessage = new htmlContent_1.MarkdownString('', true)
                .appendLink(link.url.toString(true).replace(/ /g, '%20'), label, nativeLabel)
                .appendMarkdown(` (${kb})`);
            return hoverMessage;
        }
        else {
            return new htmlContent_1.MarkdownString().appendText(`${label} (${kb})`);
        }
    }
    class OpenLinkAction extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: 'editor.action.openLink',
                label: nls.localize(1147, "Open Link"),
                alias: 'Open Link',
                precondition: undefined
            });
        }
        run(accessor, editor) {
            const linkDetector = LinkDetector.get(editor);
            if (!linkDetector) {
                return;
            }
            if (!editor.hasModel()) {
                return;
            }
            const selections = editor.getSelections();
            for (const sel of selections) {
                const link = linkDetector.getLinkOccurrence(sel.getEndPosition());
                if (link) {
                    linkDetector.openLinkOccurrence(link, false);
                }
            }
        }
    }
    (0, editorExtensions_1.registerEditorContribution)(LinkDetector.ID, LinkDetector, 1 /* EditorContributionInstantiation.AfterFirstRender */);
    (0, editorExtensions_1.registerEditorAction)(OpenLinkAction);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[835/*vs/editor/contrib/sectionHeaders/browser/sectionHeaders*/], __M([1/*require*/,0/*exports*/,14/*vs/base/common/async*/,2/*vs/base/common/lifecycle*/,15/*vs/editor/browser/editorExtensions*/,36/*vs/editor/common/languages/languageConfigurationRegistry*/,35/*vs/editor/common/model/textModel*/,100/*vs/editor/common/services/editorWorker*/]), function (require, exports, async_1, lifecycle_1, editorExtensions_1, languageConfigurationRegistry_1, textModel_1, editorWorker_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SectionHeaderDetector = void 0;
    let SectionHeaderDetector = class SectionHeaderDetector extends lifecycle_1.Disposable {
        static { this.ID = 'editor.sectionHeaderDetector'; }
        constructor(editor, languageConfigurationService, editorWorkerService) {
            super();
            this.editor = editor;
            this.languageConfigurationService = languageConfigurationService;
            this.editorWorkerService = editorWorkerService;
            this.decorations = this.editor.createDecorationsCollection();
            this.options = this.createOptions(editor.getOption(73 /* EditorOption.minimap */));
            this.computePromise = null;
            this.currentOccurrences = {};
            this._register(editor.onDidChangeModel((e) => {
                this.currentOccurrences = {};
                this.options = this.createOptions(editor.getOption(73 /* EditorOption.minimap */));
                this.stop();
                this.computeSectionHeaders.schedule(0);
            }));
            this._register(editor.onDidChangeModelLanguage((e) => {
                this.currentOccurrences = {};
                this.options = this.createOptions(editor.getOption(73 /* EditorOption.minimap */));
                this.stop();
                this.computeSectionHeaders.schedule(0);
            }));
            this._register(languageConfigurationService.onDidChange((e) => {
                const editorLanguageId = this.editor.getModel()?.getLanguageId();
                if (editorLanguageId && e.affects(editorLanguageId)) {
                    this.currentOccurrences = {};
                    this.options = this.createOptions(editor.getOption(73 /* EditorOption.minimap */));
                    this.stop();
                    this.computeSectionHeaders.schedule(0);
                }
            }));
            this._register(editor.onDidChangeConfiguration(e => {
                if (this.options && !e.hasChanged(73 /* EditorOption.minimap */)) {
                    return;
                }
                this.options = this.createOptions(editor.getOption(73 /* EditorOption.minimap */));
                // Remove any links (for the getting disabled case)
                this.updateDecorations([]);
                // Stop any computation (for the getting disabled case)
                this.stop();
                // Start computing (for the getting enabled case)
                this.computeSectionHeaders.schedule(0);
            }));
            this._register(this.editor.onDidChangeModelContent(e => {
                this.computeSectionHeaders.schedule();
            }));
            this._register(editor.onDidChangeModelTokens((e) => {
                if (!this.computeSectionHeaders.isScheduled()) {
                    this.computeSectionHeaders.schedule(1000);
                }
            }));
            this.computeSectionHeaders = this._register(new async_1.RunOnceScheduler(() => {
                this.findSectionHeaders();
            }, 250));
            this.computeSectionHeaders.schedule(0);
        }
        createOptions(minimap) {
            if (!minimap || !this.editor.hasModel()) {
                return undefined;
            }
            const languageId = this.editor.getModel().getLanguageId();
            if (!languageId) {
                return undefined;
            }
            const commentsConfiguration = this.languageConfigurationService.getLanguageConfiguration(languageId).comments;
            const foldingRules = this.languageConfigurationService.getLanguageConfiguration(languageId).foldingRules;
            if (!commentsConfiguration && !foldingRules?.markers) {
                return undefined;
            }
            return {
                foldingRules,
                findMarkSectionHeaders: minimap.showMarkSectionHeaders,
                findRegionSectionHeaders: minimap.showRegionSectionHeaders,
            };
        }
        findSectionHeaders() {
            if (!this.editor.hasModel()
                || (!this.options?.findMarkSectionHeaders && !this.options?.findRegionSectionHeaders)) {
                return;
            }
            const model = this.editor.getModel();
            if (model.isDisposed() || model.isTooLargeForSyncing()) {
                return;
            }
            const modelVersionId = model.getVersionId();
            this.editorWorkerService.findSectionHeaders(model.uri, this.options)
                .then((sectionHeaders) => {
                if (model.isDisposed() || model.getVersionId() !== modelVersionId) {
                    // model changed in the meantime
                    return;
                }
                this.updateDecorations(sectionHeaders);
            });
        }
        updateDecorations(sectionHeaders) {
            const model = this.editor.getModel();
            if (model) {
                // Remove all section headers that should be in comments and are not in comments
                sectionHeaders = sectionHeaders.filter((sectionHeader) => {
                    if (!sectionHeader.shouldBeInComments) {
                        return true;
                    }
                    const validRange = model.validateRange(sectionHeader.range);
                    const tokens = model.tokenization.getLineTokens(validRange.startLineNumber);
                    const idx = tokens.findTokenIndexAtOffset(validRange.startColumn - 1);
                    const tokenType = tokens.getStandardTokenType(idx);
                    const languageId = tokens.getLanguageId(idx);
                    return (languageId === model.getLanguageId() && tokenType === 1 /* StandardTokenType.Comment */);
                });
            }
            const oldDecorations = Object.values(this.currentOccurrences).map(occurrence => occurrence.decorationId);
            const newDecorations = sectionHeaders.map(sectionHeader => decoration(sectionHeader));
            this.editor.changeDecorations((changeAccessor) => {
                const decorations = changeAccessor.deltaDecorations(oldDecorations, newDecorations);
                this.currentOccurrences = {};
                for (let i = 0, len = decorations.length; i < len; i++) {
                    const occurrence = { sectionHeader: sectionHeaders[i], decorationId: decorations[i] };
                    this.currentOccurrences[occurrence.decorationId] = occurrence;
                }
            });
        }
        stop() {
            this.computeSectionHeaders.cancel();
            if (this.computePromise) {
                this.computePromise.cancel();
                this.computePromise = null;
            }
        }
        dispose() {
            super.dispose();
            this.stop();
            this.decorations.clear();
        }
    };
    exports.SectionHeaderDetector = SectionHeaderDetector;
    exports.SectionHeaderDetector = SectionHeaderDetector = __decorate([
        __param(1, languageConfigurationRegistry_1.ILanguageConfigurationService),
        __param(2, editorWorker_1.IEditorWorkerService)
    ], SectionHeaderDetector);
    function decoration(sectionHeader) {
        return {
            range: sectionHeader.range,
            options: textModel_1.ModelDecorationOptions.createDynamic({
                description: 'section-header',
                stickiness: 3 /* TrackedRangeStickiness.GrowsOnlyWhenTypingAfter */,
                collapseOnReplaceEdit: true,
                minimap: {
                    color: undefined,
                    position: 1 /* MinimapPosition.Inline */,
                    sectionHeaderStyle: sectionHeader.hasSeparatorLine ? 2 /* MinimapSectionHeaderStyle.Underlined */ : 1 /* MinimapSectionHeaderStyle.Normal */,
                    sectionHeaderText: sectionHeader.text,
                },
            })
        };
    }
    (0, editorExtensions_1.registerEditorContribution)(SectionHeaderDetector.ID, SectionHeaderDetector, 1 /* EditorContributionInstantiation.AfterFirstRender */);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[836/*vs/editor/contrib/stickyScroll/browser/stickyScrollModelProvider*/], __M([1/*require*/,0/*exports*/,2/*vs/base/common/lifecycle*/,17/*vs/editor/common/services/languageFeatures*/,182/*vs/editor/contrib/documentSymbols/browser/outlineModel*/,14/*vs/base/common/async*/,289/*vs/editor/contrib/folding/browser/folding*/,336/*vs/editor/contrib/folding/browser/syntaxRangeProvider*/,335/*vs/editor/contrib/folding/browser/indentRangeProvider*/,36/*vs/editor/common/languages/languageConfigurationRegistry*/,8/*vs/base/common/errors*/,341/*vs/editor/contrib/stickyScroll/browser/stickyScrollElement*/,53/*vs/base/common/iterator*/,7/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, lifecycle_1, languageFeatures_1, outlineModel_1, async_1, folding_1, syntaxRangeProvider_1, indentRangeProvider_1, languageConfigurationRegistry_1, errors_1, stickyScrollElement_1, iterator_1, instantiation_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.StickyModelProvider = void 0;
    var ModelProvider;
    (function (ModelProvider) {
        ModelProvider["OUTLINE_MODEL"] = "outlineModel";
        ModelProvider["FOLDING_PROVIDER_MODEL"] = "foldingProviderModel";
        ModelProvider["INDENTATION_MODEL"] = "indentationModel";
    })(ModelProvider || (ModelProvider = {}));
    var Status;
    (function (Status) {
        Status[Status["VALID"] = 0] = "VALID";
        Status[Status["INVALID"] = 1] = "INVALID";
        Status[Status["CANCELED"] = 2] = "CANCELED";
    })(Status || (Status = {}));
    let StickyModelProvider = class StickyModelProvider extends lifecycle_1.Disposable {
        constructor(_editor, onProviderUpdate, _languageConfigurationService, _languageFeaturesService) {
            super();
            this._editor = _editor;
            this._modelProviders = [];
            this._modelPromise = null;
            this._updateScheduler = this._register(new async_1.Delayer(300));
            this._updateOperation = this._register(new lifecycle_1.DisposableStore());
            switch (this._editor.getOption(116 /* EditorOption.stickyScroll */).defaultModel) {
                case ModelProvider.OUTLINE_MODEL:
                    this._modelProviders.push(new StickyModelFromCandidateOutlineProvider(this._editor, _languageFeaturesService));
                // fall through
                case ModelProvider.FOLDING_PROVIDER_MODEL:
                    this._modelProviders.push(new StickyModelFromCandidateSyntaxFoldingProvider(this._editor, onProviderUpdate, _languageFeaturesService));
                // fall through
                case ModelProvider.INDENTATION_MODEL:
                    this._modelProviders.push(new StickyModelFromCandidateIndentationFoldingProvider(this._editor, _languageConfigurationService));
                    break;
            }
        }
        dispose() {
            this._modelProviders.forEach(provider => provider.dispose());
            this._updateOperation.clear();
            this._cancelModelPromise();
            super.dispose();
        }
        _cancelModelPromise() {
            if (this._modelPromise) {
                this._modelPromise.cancel();
                this._modelPromise = null;
            }
        }
        async update(token) {
            this._updateOperation.clear();
            this._updateOperation.add({
                dispose: () => {
                    this._cancelModelPromise();
                    this._updateScheduler.cancel();
                }
            });
            this._cancelModelPromise();
            return await this._updateScheduler.trigger(async () => {
                for (const modelProvider of this._modelProviders) {
                    const { statusPromise, modelPromise } = modelProvider.computeStickyModel(token);
                    this._modelPromise = modelPromise;
                    const status = await statusPromise;
                    if (this._modelPromise !== modelPromise) {
                        return null;
                    }
                    switch (status) {
                        case Status.CANCELED:
                            this._updateOperation.clear();
                            return null;
                        case Status.VALID:
                            return modelProvider.stickyModel;
                    }
                }
                return null;
            }).catch((error) => {
                (0, errors_1.onUnexpectedError)(error);
                return null;
            });
        }
    };
    exports.StickyModelProvider = StickyModelProvider;
    exports.StickyModelProvider = StickyModelProvider = __decorate([
        __param(2, instantiation_1.IInstantiationService),
        __param(3, languageFeatures_1.ILanguageFeaturesService)
    ], StickyModelProvider);
    class StickyModelCandidateProvider extends lifecycle_1.Disposable {
        constructor(_editor) {
            super();
            this._editor = _editor;
            this._stickyModel = null;
        }
        get stickyModel() {
            return this._stickyModel;
        }
        _invalid() {
            this._stickyModel = null;
            return Status.INVALID;
        }
        computeStickyModel(token) {
            if (token.isCancellationRequested || !this.isProviderValid()) {
                return { statusPromise: this._invalid(), modelPromise: null };
            }
            const providerModelPromise = (0, async_1.createCancelablePromise)(token => this.createModelFromProvider(token));
            return {
                statusPromise: providerModelPromise.then(providerModel => {
                    if (!this.isModelValid(providerModel)) {
                        return this._invalid();
                    }
                    if (token.isCancellationRequested) {
                        return Status.CANCELED;
                    }
                    this._stickyModel = this.createStickyModel(token, providerModel);
                    return Status.VALID;
                }).then(undefined, (err) => {
                    (0, errors_1.onUnexpectedError)(err);
                    return Status.CANCELED;
                }),
                modelPromise: providerModelPromise
            };
        }
        /**
         * Method which checks whether the model returned by the provider is valid and can be used to compute a sticky model.
         * This method by default returns true.
         * @param model model returned by the provider
         * @returns boolean indicating whether the model is valid
         */
        isModelValid(model) {
            return true;
        }
        /**
         * Method which checks whether the provider is valid before applying it to find the provider model.
         * This method by default returns true.
         * @returns boolean indicating whether the provider is valid
         */
        isProviderValid() {
            return true;
        }
    }
    let StickyModelFromCandidateOutlineProvider = class StickyModelFromCandidateOutlineProvider extends StickyModelCandidateProvider {
        constructor(_editor, _languageFeaturesService) {
            super(_editor);
            this._languageFeaturesService = _languageFeaturesService;
        }
        createModelFromProvider(token) {
            return outlineModel_1.OutlineModel.create(this._languageFeaturesService.documentSymbolProvider, this._editor.getModel(), token);
        }
        createStickyModel(token, model) {
            const { stickyOutlineElement, providerID } = this._stickyModelFromOutlineModel(model, this._stickyModel?.outlineProviderId);
            const textModel = this._editor.getModel();
            return new stickyScrollElement_1.StickyModel(textModel.uri, textModel.getVersionId(), stickyOutlineElement, providerID);
        }
        isModelValid(model) {
            return model && model.children.size > 0;
        }
        _stickyModelFromOutlineModel(outlineModel, preferredProvider) {
            let outlineElements;
            // When several possible outline providers
            if (iterator_1.Iterable.first(outlineModel.children.values()) instanceof outlineModel_1.OutlineGroup) {
                const provider = iterator_1.Iterable.find(outlineModel.children.values(), outlineGroupOfModel => outlineGroupOfModel.id === preferredProvider);
                if (provider) {
                    outlineElements = provider.children;
                }
                else {
                    let tempID = '';
                    let maxTotalSumOfRanges = -1;
                    let optimalOutlineGroup = undefined;
                    for (const [_key, outlineGroup] of outlineModel.children.entries()) {
                        const totalSumRanges = this._findSumOfRangesOfGroup(outlineGroup);
                        if (totalSumRanges > maxTotalSumOfRanges) {
                            optimalOutlineGroup = outlineGroup;
                            maxTotalSumOfRanges = totalSumRanges;
                            tempID = outlineGroup.id;
                        }
                    }
                    preferredProvider = tempID;
                    outlineElements = optimalOutlineGroup.children;
                }
            }
            else {
                outlineElements = outlineModel.children;
            }
            const stickyChildren = [];
            const outlineElementsArray = Array.from(outlineElements.values()).sort((element1, element2) => {
                const range1 = new stickyScrollElement_1.StickyRange(element1.symbol.range.startLineNumber, element1.symbol.range.endLineNumber);
                const range2 = new stickyScrollElement_1.StickyRange(element2.symbol.range.startLineNumber, element2.symbol.range.endLineNumber);
                return this._comparator(range1, range2);
            });
            for (const outlineElement of outlineElementsArray) {
                stickyChildren.push(this._stickyModelFromOutlineElement(outlineElement, outlineElement.symbol.selectionRange.startLineNumber));
            }
            const stickyOutlineElement = new stickyScrollElement_1.StickyElement(undefined, stickyChildren, undefined);
            return {
                stickyOutlineElement: stickyOutlineElement,
                providerID: preferredProvider
            };
        }
        _stickyModelFromOutlineElement(outlineElement, previousStartLine) {
            const children = [];
            for (const child of outlineElement.children.values()) {
                if (child.symbol.selectionRange.startLineNumber !== child.symbol.range.endLineNumber) {
                    if (child.symbol.selectionRange.startLineNumber !== previousStartLine) {
                        children.push(this._stickyModelFromOutlineElement(child, child.symbol.selectionRange.startLineNumber));
                    }
                    else {
                        for (const subchild of child.children.values()) {
                            children.push(this._stickyModelFromOutlineElement(subchild, child.symbol.selectionRange.startLineNumber));
                        }
                    }
                }
            }
            children.sort((child1, child2) => this._comparator(child1.range, child2.range));
            const range = new stickyScrollElement_1.StickyRange(outlineElement.symbol.selectionRange.startLineNumber, outlineElement.symbol.range.endLineNumber);
            return new stickyScrollElement_1.StickyElement(range, children, undefined);
        }
        _comparator(range1, range2) {
            if (range1.startLineNumber !== range2.startLineNumber) {
                return range1.startLineNumber - range2.startLineNumber;
            }
            else {
                return range2.endLineNumber - range1.endLineNumber;
            }
        }
        _findSumOfRangesOfGroup(outline) {
            let res = 0;
            for (const child of outline.children.values()) {
                res += this._findSumOfRangesOfGroup(child);
            }
            if (outline instanceof outlineModel_1.OutlineElement) {
                return res + outline.symbol.range.endLineNumber - outline.symbol.selectionRange.startLineNumber;
            }
            else {
                return res;
            }
        }
    };
    StickyModelFromCandidateOutlineProvider = __decorate([
        __param(1, languageFeatures_1.ILanguageFeaturesService)
    ], StickyModelFromCandidateOutlineProvider);
    class StickyModelFromCandidateFoldingProvider extends StickyModelCandidateProvider {
        constructor(editor) {
            super(editor);
            this._foldingLimitReporter = new folding_1.RangesLimitReporter(editor);
        }
        createStickyModel(token, model) {
            const foldingElement = this._fromFoldingRegions(model);
            const textModel = this._editor.getModel();
            return new stickyScrollElement_1.StickyModel(textModel.uri, textModel.getVersionId(), foldingElement, undefined);
        }
        isModelValid(model) {
            return model !== null;
        }
        _fromFoldingRegions(foldingRegions) {
            const length = foldingRegions.length;
            const orderedStickyElements = [];
            // The root sticky outline element
            const stickyOutlineElement = new stickyScrollElement_1.StickyElement(undefined, [], undefined);
            for (let i = 0; i < length; i++) {
                // Finding the parent index of the current range
                const parentIndex = foldingRegions.getParentIndex(i);
                let parentNode;
                if (parentIndex !== -1) {
                    // Access the reference of the parent node
                    parentNode = orderedStickyElements[parentIndex];
                }
                else {
                    // In that case the parent node is the root node
                    parentNode = stickyOutlineElement;
                }
                const child = new stickyScrollElement_1.StickyElement(new stickyScrollElement_1.StickyRange(foldingRegions.getStartLineNumber(i), foldingRegions.getEndLineNumber(i) + 1), [], parentNode);
                parentNode.children.push(child);
                orderedStickyElements.push(child);
            }
            return stickyOutlineElement;
        }
    }
    let StickyModelFromCandidateIndentationFoldingProvider = class StickyModelFromCandidateIndentationFoldingProvider extends StickyModelFromCandidateFoldingProvider {
        constructor(editor, _languageConfigurationService) {
            super(editor);
            this._languageConfigurationService = _languageConfigurationService;
            this.provider = this._register(new indentRangeProvider_1.IndentRangeProvider(editor.getModel(), this._languageConfigurationService, this._foldingLimitReporter));
        }
        async createModelFromProvider(token) {
            return this.provider.compute(token);
        }
    };
    StickyModelFromCandidateIndentationFoldingProvider = __decorate([
        __param(1, languageConfigurationRegistry_1.ILanguageConfigurationService)
    ], StickyModelFromCandidateIndentationFoldingProvider);
    let StickyModelFromCandidateSyntaxFoldingProvider = class StickyModelFromCandidateSyntaxFoldingProvider extends StickyModelFromCandidateFoldingProvider {
        constructor(editor, onProviderUpdate, _languageFeaturesService) {
            super(editor);
            this._languageFeaturesService = _languageFeaturesService;
            const selectedProviders = folding_1.FoldingController.getFoldingRangeProviders(this._languageFeaturesService, editor.getModel());
            if (selectedProviders.length > 0) {
                this.provider = this._register(new syntaxRangeProvider_1.SyntaxRangeProvider(editor.getModel(), selectedProviders, onProviderUpdate, this._foldingLimitReporter, undefined));
            }
        }
        isProviderValid() {
            return this.provider !== undefined;
        }
        async createModelFromProvider(token) {
            return this.provider?.compute(token) ?? null;
        }
    };
    StickyModelFromCandidateSyntaxFoldingProvider = __decorate([
        __param(2, languageFeatures_1.ILanguageFeaturesService)
    ], StickyModelFromCandidateSyntaxFoldingProvider);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[837/*vs/editor/contrib/stickyScroll/browser/stickyScrollProvider*/], __M([1/*require*/,0/*exports*/,2/*vs/base/common/lifecycle*/,17/*vs/editor/common/services/languageFeatures*/,18/*vs/base/common/cancellation*/,14/*vs/base/common/async*/,13/*vs/base/common/arrays*/,6/*vs/base/common/event*/,36/*vs/editor/common/languages/languageConfigurationRegistry*/,836/*vs/editor/contrib/stickyScroll/browser/stickyScrollModelProvider*/]), function (require, exports, lifecycle_1, languageFeatures_1, cancellation_1, async_1, arrays_1, event_1, languageConfigurationRegistry_1, stickyScrollModelProvider_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.StickyLineCandidateProvider = exports.StickyLineCandidate = void 0;
    class StickyLineCandidate {
        constructor(startLineNumber, endLineNumber, nestingDepth) {
            this.startLineNumber = startLineNumber;
            this.endLineNumber = endLineNumber;
            this.nestingDepth = nestingDepth;
        }
    }
    exports.StickyLineCandidate = StickyLineCandidate;
    let StickyLineCandidateProvider = class StickyLineCandidateProvider extends lifecycle_1.Disposable {
        constructor(editor, _languageFeaturesService, _languageConfigurationService) {
            super();
            this._languageFeaturesService = _languageFeaturesService;
            this._languageConfigurationService = _languageConfigurationService;
            this._onDidChangeStickyScroll = this._register(new event_1.Emitter());
            this.onDidChangeStickyScroll = this._onDidChangeStickyScroll.event;
            this._model = null;
            this._cts = null;
            this._stickyModelProvider = null;
            this._editor = editor;
            this._sessionStore = this._register(new lifecycle_1.DisposableStore());
            this._updateSoon = this._register(new async_1.RunOnceScheduler(() => this.update(), 50));
            this._register(this._editor.onDidChangeConfiguration(e => {
                if (e.hasChanged(116 /* EditorOption.stickyScroll */)) {
                    this.readConfiguration();
                }
            }));
            this.readConfiguration();
        }
        readConfiguration() {
            this._sessionStore.clear();
            const options = this._editor.getOption(116 /* EditorOption.stickyScroll */);
            if (!options.enabled) {
                return;
            }
            this._sessionStore.add(this._editor.onDidChangeModel(() => {
                // We should not show an old model for a different file, it will always be wrong.
                // So we clear the model here immediately and then trigger an update.
                this._model = null;
                this.updateStickyModelProvider();
                this._onDidChangeStickyScroll.fire();
                this.update();
            }));
            this._sessionStore.add(this._editor.onDidChangeHiddenAreas(() => this.update()));
            this._sessionStore.add(this._editor.onDidChangeModelContent(() => this._updateSoon.schedule()));
            this._sessionStore.add(this._languageFeaturesService.documentSymbolProvider.onDidChange(() => this.update()));
            this._sessionStore.add((0, lifecycle_1.toDisposable)(() => {
                this._stickyModelProvider?.dispose();
                this._stickyModelProvider = null;
            }));
            this.updateStickyModelProvider();
            this.update();
        }
        getVersionId() {
            return this._model?.version;
        }
        updateStickyModelProvider() {
            this._stickyModelProvider?.dispose();
            this._stickyModelProvider = null;
            const editor = this._editor;
            if (editor.hasModel()) {
                this._stickyModelProvider = new stickyScrollModelProvider_1.StickyModelProvider(editor, () => this._updateSoon.schedule(), this._languageConfigurationService, this._languageFeaturesService);
            }
        }
        async update() {
            this._cts?.dispose(true);
            this._cts = new cancellation_1.CancellationTokenSource();
            await this.updateStickyModel(this._cts.token);
            this._onDidChangeStickyScroll.fire();
        }
        async updateStickyModel(token) {
            if (!this._editor.hasModel() || !this._stickyModelProvider || this._editor.getModel().isTooLargeForTokenization()) {
                this._model = null;
                return;
            }
            const model = await this._stickyModelProvider.update(token);
            if (token.isCancellationRequested) {
                // the computation was canceled, so do not overwrite the model
                return;
            }
            this._model = model;
        }
        updateIndex(index) {
            if (index === -1) {
                index = 0;
            }
            else if (index < 0) {
                index = -index - 2;
            }
            return index;
        }
        getCandidateStickyLinesIntersectingFromStickyModel(range, outlineModel, result, depth, lastStartLineNumber) {
            if (outlineModel.children.length === 0) {
                return;
            }
            let lastLine = lastStartLineNumber;
            const childrenStartLines = [];
            for (let i = 0; i < outlineModel.children.length; i++) {
                const child = outlineModel.children[i];
                if (child.range) {
                    childrenStartLines.push(child.range.startLineNumber);
                }
            }
            const lowerBound = this.updateIndex((0, arrays_1.binarySearch)(childrenStartLines, range.startLineNumber, (a, b) => { return a - b; }));
            const upperBound = this.updateIndex((0, arrays_1.binarySearch)(childrenStartLines, range.startLineNumber + depth, (a, b) => { return a - b; }));
            for (let i = lowerBound; i <= upperBound; i++) {
                const child = outlineModel.children[i];
                if (!child) {
                    return;
                }
                if (child.range) {
                    const childStartLine = child.range.startLineNumber;
                    const childEndLine = child.range.endLineNumber;
                    if (range.startLineNumber <= childEndLine + 1 && childStartLine - 1 <= range.endLineNumber && childStartLine !== lastLine) {
                        lastLine = childStartLine;
                        result.push(new StickyLineCandidate(childStartLine, childEndLine - 1, depth + 1));
                        this.getCandidateStickyLinesIntersectingFromStickyModel(range, child, result, depth + 1, childStartLine);
                    }
                }
                else {
                    this.getCandidateStickyLinesIntersectingFromStickyModel(range, child, result, depth, lastStartLineNumber);
                }
            }
        }
        getCandidateStickyLinesIntersecting(range) {
            if (!this._model?.element) {
                return [];
            }
            let stickyLineCandidates = [];
            this.getCandidateStickyLinesIntersectingFromStickyModel(range, this._model.element, stickyLineCandidates, 0, -1);
            const hiddenRanges = this._editor._getViewModel()?.getHiddenAreas();
            if (hiddenRanges) {
                for (const hiddenRange of hiddenRanges) {
                    stickyLineCandidates = stickyLineCandidates.filter(stickyLine => !(stickyLine.startLineNumber >= hiddenRange.startLineNumber && stickyLine.endLineNumber <= hiddenRange.endLineNumber + 1));
                }
            }
            return stickyLineCandidates;
        }
    };
    exports.StickyLineCandidateProvider = StickyLineCandidateProvider;
    exports.StickyLineCandidateProvider = StickyLineCandidateProvider = __decorate([
        __param(1, languageFeatures_1.ILanguageFeaturesService),
        __param(2, languageConfigurationRegistry_1.ILanguageConfigurationService)
    ], StickyLineCandidateProvider);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[838/*vs/editor/contrib/stickyScroll/browser/stickyScrollWidget*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,103/*vs/base/browser/trustedTypes*/,13/*vs/base/common/arrays*/,2/*vs/base/common/lifecycle*/,30/*vs/base/common/themables*/,281/*vs/editor/browser/viewParts/lines/viewLine*/,125/*vs/editor/browser/widget/codeEditor/embeddedCodeEditorWidget*/,9/*vs/editor/common/core/position*/,116/*vs/editor/common/core/stringBuilder*/,150/*vs/editor/common/viewLayout/lineDecorations*/,136/*vs/editor/common/viewLayout/viewLineRenderer*/,424/*vs/editor/contrib/folding/browser/foldingDecorations*/,531/*vs/css!vs/editor/contrib/stickyScroll/browser/stickyScroll*/]), function (require, exports, dom, trustedTypes_1, arrays_1, lifecycle_1, themables_1, viewLine_1, embeddedCodeEditorWidget_1, position_1, stringBuilder_1, lineDecorations_1, viewLineRenderer_1, foldingDecorations_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.StickyScrollWidget = exports.StickyScrollWidgetState = void 0;
    class StickyScrollWidgetState {
        constructor(startLineNumbers, endLineNumbers, lastLineRelativePosition, showEndForLine = null) {
            this.startLineNumbers = startLineNumbers;
            this.endLineNumbers = endLineNumbers;
            this.lastLineRelativePosition = lastLineRelativePosition;
            this.showEndForLine = showEndForLine;
        }
        equals(other) {
            return !!other
                && this.lastLineRelativePosition === other.lastLineRelativePosition
                && this.showEndForLine === other.showEndForLine
                && (0, arrays_1.equals)(this.startLineNumbers, other.startLineNumbers)
                && (0, arrays_1.equals)(this.endLineNumbers, other.endLineNumbers);
        }
        static get Empty() {
            return new StickyScrollWidgetState([], [], 0);
        }
    }
    exports.StickyScrollWidgetState = StickyScrollWidgetState;
    const _ttPolicy = (0, trustedTypes_1.createTrustedTypesPolicy)('stickyScrollViewLayer', { createHTML: value => value });
    const STICKY_INDEX_ATTR = 'data-sticky-line-index';
    const STICKY_IS_LINE_ATTR = 'data-sticky-is-line';
    const STICKY_IS_LINE_NUMBER_ATTR = 'data-sticky-is-line-number';
    const STICKY_IS_FOLDING_ICON_ATTR = 'data-sticky-is-folding-icon';
    class StickyScrollWidget extends lifecycle_1.Disposable {
        constructor(_editor) {
            super();
            this._editor = _editor;
            this._foldingIconStore = new lifecycle_1.DisposableStore();
            this._rootDomNode = document.createElement('div');
            this._lineNumbersDomNode = document.createElement('div');
            this._linesDomNodeScrollable = document.createElement('div');
            this._linesDomNode = document.createElement('div');
            this._lineHeight = this._editor.getOption(67 /* EditorOption.lineHeight */);
            this._renderedStickyLines = [];
            this._lineNumbers = [];
            this._lastLineRelativePosition = 0;
            this._minContentWidthInPx = 0;
            this._isOnGlyphMargin = false;
            this._lineNumbersDomNode.className = 'sticky-widget-line-numbers';
            this._lineNumbersDomNode.setAttribute('role', 'none');
            this._linesDomNode.className = 'sticky-widget-lines';
            this._linesDomNode.setAttribute('role', 'list');
            this._linesDomNodeScrollable.className = 'sticky-widget-lines-scrollable';
            this._linesDomNodeScrollable.appendChild(this._linesDomNode);
            this._rootDomNode.className = 'sticky-widget';
            this._rootDomNode.classList.toggle('peek', _editor instanceof embeddedCodeEditorWidget_1.EmbeddedCodeEditorWidget);
            this._rootDomNode.appendChild(this._lineNumbersDomNode);
            this._rootDomNode.appendChild(this._linesDomNodeScrollable);
            const updateScrollLeftPosition = () => {
                this._linesDomNode.style.left = this._editor.getOption(116 /* EditorOption.stickyScroll */).scrollWithEditor ? `-${this._editor.getScrollLeft()}px` : '0px';
            };
            this._register(this._editor.onDidChangeConfiguration((e) => {
                if (e.hasChanged(116 /* EditorOption.stickyScroll */)) {
                    updateScrollLeftPosition();
                }
                if (e.hasChanged(67 /* EditorOption.lineHeight */)) {
                    this._lineHeight = this._editor.getOption(67 /* EditorOption.lineHeight */);
                }
            }));
            this._register(this._editor.onDidScrollChange((e) => {
                if (e.scrollLeftChanged) {
                    updateScrollLeftPosition();
                }
                if (e.scrollWidthChanged) {
                    this._updateWidgetWidth();
                }
            }));
            this._register(this._editor.onDidChangeModel(() => {
                updateScrollLeftPosition();
                this._updateWidgetWidth();
            }));
            this._register(this._foldingIconStore);
            updateScrollLeftPosition();
            this._register(this._editor.onDidLayoutChange((e) => {
                this._updateWidgetWidth();
            }));
            this._updateWidgetWidth();
        }
        get lineNumbers() {
            return this._lineNumbers;
        }
        get lineNumberCount() {
            return this._lineNumbers.length;
        }
        getRenderedStickyLine(lineNumber) {
            return this._renderedStickyLines.find(stickyLine => stickyLine.lineNumber === lineNumber);
        }
        getCurrentLines() {
            return this._lineNumbers;
        }
        setState(_state, foldingModel, _rebuildFromLine) {
            if (_rebuildFromLine === undefined &&
                ((!this._previousState && !_state) || (this._previousState && this._previousState.equals(_state)))) {
                return;
            }
            const isWidgetHeightZero = this._isWidgetHeightZero(_state);
            const state = isWidgetHeightZero ? undefined : _state;
            const rebuildFromLine = isWidgetHeightZero ? 0 : this._findLineToRebuildWidgetFrom(_state, _rebuildFromLine);
            this._renderRootNode(state, foldingModel, rebuildFromLine);
            this._previousState = _state;
        }
        _isWidgetHeightZero(state) {
            if (!state) {
                return true;
            }
            const futureWidgetHeight = state.startLineNumbers.length * this._lineHeight + state.lastLineRelativePosition;
            if (futureWidgetHeight > 0) {
                this._lastLineRelativePosition = state.lastLineRelativePosition;
                const lineNumbers = [...state.startLineNumbers];
                if (state.showEndForLine !== null) {
                    lineNumbers[state.showEndForLine] = state.endLineNumbers[state.showEndForLine];
                }
                this._lineNumbers = lineNumbers;
            }
            else {
                this._lastLineRelativePosition = 0;
                this._lineNumbers = [];
            }
            return futureWidgetHeight === 0;
        }
        _findLineToRebuildWidgetFrom(state, _rebuildFromLine) {
            if (!state || !this._previousState) {
                return 0;
            }
            if (_rebuildFromLine !== undefined) {
                return _rebuildFromLine;
            }
            const previousState = this._previousState;
            const indexOfLinesAlreadyRendered = state.startLineNumbers.findIndex(startLineNumber => !previousState.startLineNumbers.includes(startLineNumber));
            return (indexOfLinesAlreadyRendered === -1) ? 0 : indexOfLinesAlreadyRendered;
        }
        _updateWidgetWidth() {
            const layoutInfo = this._editor.getLayoutInfo();
            const lineNumbersWidth = layoutInfo.contentLeft;
            this._lineNumbersDomNode.style.width = `${lineNumbersWidth}px`;
            this._linesDomNodeScrollable.style.setProperty('--vscode-editorStickyScroll-scrollableWidth', `${this._editor.getScrollWidth() - layoutInfo.verticalScrollbarWidth}px`);
            this._rootDomNode.style.width = `${layoutInfo.width - layoutInfo.verticalScrollbarWidth}px`;
        }
        _clearStickyLinesFromLine(clearFromLine) {
            this._foldingIconStore.clear();
            // Removing only the lines that need to be rerendered
            for (let i = clearFromLine; i < this._renderedStickyLines.length; i++) {
                const stickyLine = this._renderedStickyLines[i];
                stickyLine.lineNumberDomNode.remove();
                stickyLine.lineDomNode.remove();
            }
            // Keep the lines that need to be updated
            this._renderedStickyLines = this._renderedStickyLines.slice(0, clearFromLine);
            this._rootDomNode.style.display = 'none';
        }
        _useFoldingOpacityTransition(requireTransitions) {
            this._lineNumbersDomNode.style.setProperty('--vscode-editorStickyScroll-foldingOpacityTransition', `opacity ${requireTransitions ? 0.5 : 0}s`);
        }
        _setFoldingIconsVisibility(allVisible) {
            for (const line of this._renderedStickyLines) {
                const foldingIcon = line.foldingIcon;
                if (!foldingIcon) {
                    continue;
                }
                foldingIcon.setVisible(allVisible ? true : foldingIcon.isCollapsed);
            }
        }
        async _renderRootNode(state, foldingModel, rebuildFromLine) {
            this._clearStickyLinesFromLine(rebuildFromLine);
            if (!state) {
                return;
            }
            // For existing sticky lines update the top and z-index
            for (const stickyLine of this._renderedStickyLines) {
                this._updateTopAndZIndexOfStickyLine(stickyLine);
            }
            // For new sticky lines
            const layoutInfo = this._editor.getLayoutInfo();
            const linesToRender = this._lineNumbers.slice(rebuildFromLine);
            for (const [index, line] of linesToRender.entries()) {
                const stickyLine = this._renderChildNode(index + rebuildFromLine, line, foldingModel, layoutInfo);
                if (!stickyLine) {
                    continue;
                }
                this._linesDomNode.appendChild(stickyLine.lineDomNode);
                this._lineNumbersDomNode.appendChild(stickyLine.lineNumberDomNode);
                this._renderedStickyLines.push(stickyLine);
            }
            if (foldingModel) {
                this._setFoldingHoverListeners();
                this._useFoldingOpacityTransition(!this._isOnGlyphMargin);
            }
            const widgetHeight = this._lineNumbers.length * this._lineHeight + this._lastLineRelativePosition;
            this._rootDomNode.style.display = 'block';
            this._lineNumbersDomNode.style.height = `${widgetHeight}px`;
            this._linesDomNodeScrollable.style.height = `${widgetHeight}px`;
            this._rootDomNode.style.height = `${widgetHeight}px`;
            this._rootDomNode.style.marginLeft = '0px';
            this._minContentWidthInPx = Math.max(...this._renderedStickyLines.map(l => l.scrollWidth)) + layoutInfo.verticalScrollbarWidth;
            this._editor.layoutOverlayWidget(this);
        }
        _setFoldingHoverListeners() {
            const showFoldingControls = this._editor.getOption(111 /* EditorOption.showFoldingControls */);
            if (showFoldingControls !== 'mouseover') {
                return;
            }
            this._foldingIconStore.add(dom.addDisposableListener(this._lineNumbersDomNode, dom.EventType.MOUSE_ENTER, () => {
                this._isOnGlyphMargin = true;
                this._setFoldingIconsVisibility(true);
            }));
            this._foldingIconStore.add(dom.addDisposableListener(this._lineNumbersDomNode, dom.EventType.MOUSE_LEAVE, () => {
                this._isOnGlyphMargin = false;
                this._useFoldingOpacityTransition(true);
                this._setFoldingIconsVisibility(false);
            }));
        }
        _renderChildNode(index, line, foldingModel, layoutInfo) {
            const viewModel = this._editor._getViewModel();
            if (!viewModel) {
                return;
            }
            const viewLineNumber = viewModel.coordinatesConverter.convertModelPositionToViewPosition(new position_1.Position(line, 1)).lineNumber;
            const lineRenderingData = viewModel.getViewLineRenderingData(viewLineNumber);
            const lineNumberOption = this._editor.getOption(68 /* EditorOption.lineNumbers */);
            let actualInlineDecorations;
            try {
                actualInlineDecorations = lineDecorations_1.LineDecoration.filter(lineRenderingData.inlineDecorations, viewLineNumber, lineRenderingData.minColumn, lineRenderingData.maxColumn);
            }
            catch (err) {
                actualInlineDecorations = [];
            }
            const renderLineInput = new viewLineRenderer_1.RenderLineInput(true, true, lineRenderingData.content, lineRenderingData.continuesWithWrappedLine, lineRenderingData.isBasicASCII, lineRenderingData.containsRTL, 0, lineRenderingData.tokens, actualInlineDecorations, lineRenderingData.tabSize, lineRenderingData.startVisibleColumn, 1, 1, 1, 500, 'none', true, true, null);
            const sb = new stringBuilder_1.StringBuilder(2000);
            const renderOutput = (0, viewLineRenderer_1.renderViewLine)(renderLineInput, sb);
            let newLine;
            if (_ttPolicy) {
                newLine = _ttPolicy.createHTML(sb.build());
            }
            else {
                newLine = sb.build();
            }
            const lineHTMLNode = document.createElement('span');
            lineHTMLNode.setAttribute(STICKY_INDEX_ATTR, String(index));
            lineHTMLNode.setAttribute(STICKY_IS_LINE_ATTR, '');
            lineHTMLNode.setAttribute('role', 'listitem');
            lineHTMLNode.tabIndex = 0;
            lineHTMLNode.className = 'sticky-line-content';
            lineHTMLNode.classList.add(`stickyLine${line}`);
            lineHTMLNode.style.lineHeight = `${this._lineHeight}px`;
            lineHTMLNode.innerHTML = newLine;
            const lineNumberHTMLNode = document.createElement('span');
            lineNumberHTMLNode.setAttribute(STICKY_INDEX_ATTR, String(index));
            lineNumberHTMLNode.setAttribute(STICKY_IS_LINE_NUMBER_ATTR, '');
            lineNumberHTMLNode.className = 'sticky-line-number';
            lineNumberHTMLNode.style.lineHeight = `${this._lineHeight}px`;
            const lineNumbersWidth = layoutInfo.contentLeft;
            lineNumberHTMLNode.style.width = `${lineNumbersWidth}px`;
            const innerLineNumberHTML = document.createElement('span');
            if (lineNumberOption.renderType === 1 /* RenderLineNumbersType.On */ || lineNumberOption.renderType === 3 /* RenderLineNumbersType.Interval */ && line % 10 === 0) {
                innerLineNumberHTML.innerText = line.toString();
            }
            else if (lineNumberOption.renderType === 2 /* RenderLineNumbersType.Relative */) {
                innerLineNumberHTML.innerText = Math.abs(line - this._editor.getPosition().lineNumber).toString();
            }
            innerLineNumberHTML.className = 'sticky-line-number-inner';
            innerLineNumberHTML.style.lineHeight = `${this._lineHeight}px`;
            innerLineNumberHTML.style.width = `${layoutInfo.lineNumbersWidth}px`;
            innerLineNumberHTML.style.paddingLeft = `${layoutInfo.lineNumbersLeft}px`;
            lineNumberHTMLNode.appendChild(innerLineNumberHTML);
            const foldingIcon = this._renderFoldingIconForLine(foldingModel, line);
            if (foldingIcon) {
                lineNumberHTMLNode.appendChild(foldingIcon.domNode);
            }
            this._editor.applyFontInfo(lineHTMLNode);
            this._editor.applyFontInfo(innerLineNumberHTML);
            lineNumberHTMLNode.style.lineHeight = `${this._lineHeight}px`;
            lineHTMLNode.style.lineHeight = `${this._lineHeight}px`;
            lineNumberHTMLNode.style.height = `${this._lineHeight}px`;
            lineHTMLNode.style.height = `${this._lineHeight}px`;
            const renderedLine = new RenderedStickyLine(index, line, lineHTMLNode, lineNumberHTMLNode, foldingIcon, renderOutput.characterMapping, lineHTMLNode.scrollWidth);
            return this._updateTopAndZIndexOfStickyLine(renderedLine);
        }
        _updateTopAndZIndexOfStickyLine(stickyLine) {
            const index = stickyLine.index;
            const lineHTMLNode = stickyLine.lineDomNode;
            const lineNumberHTMLNode = stickyLine.lineNumberDomNode;
            const isLastLine = index === this._lineNumbers.length - 1;
            const lastLineZIndex = '0';
            const intermediateLineZIndex = '1';
            lineHTMLNode.style.zIndex = isLastLine ? lastLineZIndex : intermediateLineZIndex;
            lineNumberHTMLNode.style.zIndex = isLastLine ? lastLineZIndex : intermediateLineZIndex;
            const lastLineTop = `${index * this._lineHeight + this._lastLineRelativePosition + (stickyLine.foldingIcon?.isCollapsed ? 1 : 0)}px`;
            const intermediateLineTop = `${index * this._lineHeight}px`;
            lineHTMLNode.style.top = isLastLine ? lastLineTop : intermediateLineTop;
            lineNumberHTMLNode.style.top = isLastLine ? lastLineTop : intermediateLineTop;
            return stickyLine;
        }
        _renderFoldingIconForLine(foldingModel, line) {
            const showFoldingControls = this._editor.getOption(111 /* EditorOption.showFoldingControls */);
            if (!foldingModel || showFoldingControls === 'never') {
                return;
            }
            const foldingRegions = foldingModel.regions;
            const indexOfFoldingRegion = foldingRegions.findRange(line);
            const startLineNumber = foldingRegions.getStartLineNumber(indexOfFoldingRegion);
            const isFoldingScope = line === startLineNumber;
            if (!isFoldingScope) {
                return;
            }
            const isCollapsed = foldingRegions.isCollapsed(indexOfFoldingRegion);
            const foldingIcon = new StickyFoldingIcon(isCollapsed, startLineNumber, foldingRegions.getEndLineNumber(indexOfFoldingRegion), this._lineHeight);
            foldingIcon.setVisible(this._isOnGlyphMargin ? true : (isCollapsed || showFoldingControls === 'always'));
            foldingIcon.domNode.setAttribute(STICKY_IS_FOLDING_ICON_ATTR, '');
            return foldingIcon;
        }
        getId() {
            return 'editor.contrib.stickyScrollWidget';
        }
        getDomNode() {
            return this._rootDomNode;
        }
        getPosition() {
            return {
                preference: 2 /* OverlayWidgetPositionPreference.TOP_CENTER */,
                stackOridinal: 10,
            };
        }
        getMinContentWidthInPx() {
            return this._minContentWidthInPx;
        }
        focusLineWithIndex(index) {
            if (0 <= index && index < this._renderedStickyLines.length) {
                this._renderedStickyLines[index].lineDomNode.focus();
            }
        }
        /**
         * Given a leaf dom node, tries to find the editor position.
         */
        getEditorPositionFromNode(spanDomNode) {
            if (!spanDomNode || spanDomNode.children.length > 0) {
                // This is not a leaf node
                return null;
            }
            const renderedStickyLine = this._getRenderedStickyLineFromChildDomNode(spanDomNode);
            if (!renderedStickyLine) {
                return null;
            }
            const column = (0, viewLine_1.getColumnOfNodeOffset)(renderedStickyLine.characterMapping, spanDomNode, 0);
            return new position_1.Position(renderedStickyLine.lineNumber, column);
        }
        getLineNumberFromChildDomNode(domNode) {
            return this._getRenderedStickyLineFromChildDomNode(domNode)?.lineNumber ?? null;
        }
        _getRenderedStickyLineFromChildDomNode(domNode) {
            const index = this.getLineIndexFromChildDomNode(domNode);
            if (index === null || index < 0 || index >= this._renderedStickyLines.length) {
                return null;
            }
            return this._renderedStickyLines[index];
        }
        /**
         * Given a child dom node, tries to find the line number attribute that was stored in the node.
         * @returns the attribute value or null if none is found.
         */
        getLineIndexFromChildDomNode(domNode) {
            const lineIndex = this._getAttributeValue(domNode, STICKY_INDEX_ATTR);
            return lineIndex ? parseInt(lineIndex, 10) : null;
        }
        /**
         * Given a child dom node, tries to find if it is (contained in) a sticky line.
         * @returns a boolean.
         */
        isInStickyLine(domNode) {
            const isInLine = this._getAttributeValue(domNode, STICKY_IS_LINE_ATTR);
            return isInLine !== undefined;
        }
        /**
         * Given a child dom node, tries to find if this dom node is (contained in) a sticky folding icon.
         * @returns a boolean.
         */
        isInFoldingIconDomNode(domNode) {
            const isInFoldingIcon = this._getAttributeValue(domNode, STICKY_IS_FOLDING_ICON_ATTR);
            return isInFoldingIcon !== undefined;
        }
        /**
         * Given the dom node, finds if it or its parent sequence contains the given attribute.
         * @returns the attribute value or undefined.
         */
        _getAttributeValue(domNode, attribute) {
            while (domNode && domNode !== this._rootDomNode) {
                const line = domNode.getAttribute(attribute);
                if (line !== null) {
                    return line;
                }
                domNode = domNode.parentElement;
            }
            return;
        }
    }
    exports.StickyScrollWidget = StickyScrollWidget;
    class RenderedStickyLine {
        constructor(index, lineNumber, lineDomNode, lineNumberDomNode, foldingIcon, characterMapping, scrollWidth) {
            this.index = index;
            this.lineNumber = lineNumber;
            this.lineDomNode = lineDomNode;
            this.lineNumberDomNode = lineNumberDomNode;
            this.foldingIcon = foldingIcon;
            this.characterMapping = characterMapping;
            this.scrollWidth = scrollWidth;
        }
    }
    class StickyFoldingIcon {
        constructor(isCollapsed, foldingStartLine, foldingEndLine, dimension) {
            this.isCollapsed = isCollapsed;
            this.foldingStartLine = foldingStartLine;
            this.foldingEndLine = foldingEndLine;
            this.dimension = dimension;
            this.domNode = document.createElement('div');
            this.domNode.style.width = `${dimension}px`;
            this.domNode.style.height = `${dimension}px`;
            this.domNode.className = themables_1.ThemeIcon.asClassName(isCollapsed ? foldingDecorations_1.foldingCollapsedIcon : foldingDecorations_1.foldingExpandedIcon);
        }
        setVisible(visible) {
            this.domNode.style.cursor = visible ? 'pointer' : 'default';
            this.domNode.style.opacity = visible ? '1' : '0';
        }
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[839/*vs/editor/contrib/suggest/browser/suggestWidget*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,115/*vs/base/browser/ui/list/listWidget*/,14/*vs/base/common/async*/,8/*vs/base/common/errors*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,141/*vs/base/common/numbers*/,11/*vs/base/common/strings*/,125/*vs/editor/browser/widget/codeEditor/embeddedCodeEditorWidget*/,798/*vs/editor/contrib/suggest/browser/suggestWidgetStatus*/,3/*vs/nls*/,12/*vs/platform/contextkey/common/contextkey*/,7/*vs/platform/instantiation/common/instantiation*/,101/*vs/platform/storage/common/storage*/,32/*vs/platform/theme/common/colorRegistry*/,97/*vs/platform/theme/common/theme*/,25/*vs/platform/theme/common/themeService*/,255/*vs/base/browser/ui/resizable/resizable*/,155/*vs/editor/contrib/suggest/browser/suggest*/,402/*vs/editor/contrib/suggest/browser/suggestWidgetDetails*/,793/*vs/editor/contrib/suggest/browser/suggestWidgetRenderer*/,110/*vs/platform/theme/browser/defaultStyles*/,46/*vs/base/browser/ui/aria/aria*/,195/*vs/base/browser/ui/codicons/codiconStyles*/,532/*vs/css!vs/editor/contrib/suggest/browser/media/suggest*/,280/*vs/editor/contrib/symbolIcons/browser/symbolIcons*/]), function (require, exports, dom, listWidget_1, async_1, errors_1, event_1, lifecycle_1, numbers_1, strings, embeddedCodeEditorWidget_1, suggestWidgetStatus_1, nls, contextkey_1, instantiation_1, storage_1, colorRegistry_1, theme_1, themeService_1, resizable_1, suggest_1, suggestWidgetDetails_1, suggestWidgetRenderer_1, defaultStyles_1, aria_1) {
    "use strict";
    var SuggestWidget_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SuggestContentWidget = exports.SuggestWidget = exports.editorSuggestWidgetSelectedBackground = void 0;
    /**
     * Suggest widget colors
     */
    (0, colorRegistry_1.registerColor)('editorSuggestWidget.background', colorRegistry_1.editorWidgetBackground, nls.localize(1328, 'Background color of the suggest widget.'));
    (0, colorRegistry_1.registerColor)('editorSuggestWidget.border', colorRegistry_1.editorWidgetBorder, nls.localize(1329, 'Border color of the suggest widget.'));
    const editorSuggestWidgetForeground = (0, colorRegistry_1.registerColor)('editorSuggestWidget.foreground', colorRegistry_1.editorForeground, nls.localize(1330, 'Foreground color of the suggest widget.'));
    (0, colorRegistry_1.registerColor)('editorSuggestWidget.selectedForeground', colorRegistry_1.quickInputListFocusForeground, nls.localize(1331, 'Foreground color of the selected entry in the suggest widget.'));
    (0, colorRegistry_1.registerColor)('editorSuggestWidget.selectedIconForeground', colorRegistry_1.quickInputListFocusIconForeground, nls.localize(1332, 'Icon foreground color of the selected entry in the suggest widget.'));
    exports.editorSuggestWidgetSelectedBackground = (0, colorRegistry_1.registerColor)('editorSuggestWidget.selectedBackground', colorRegistry_1.quickInputListFocusBackground, nls.localize(1333, 'Background color of the selected entry in the suggest widget.'));
    (0, colorRegistry_1.registerColor)('editorSuggestWidget.highlightForeground', colorRegistry_1.listHighlightForeground, nls.localize(1334, 'Color of the match highlights in the suggest widget.'));
    (0, colorRegistry_1.registerColor)('editorSuggestWidget.focusHighlightForeground', colorRegistry_1.listFocusHighlightForeground, nls.localize(1335, 'Color of the match highlights in the suggest widget when an item is focused.'));
    (0, colorRegistry_1.registerColor)('editorSuggestWidgetStatus.foreground', (0, colorRegistry_1.transparent)(editorSuggestWidgetForeground, .5), nls.localize(1336, 'Foreground color of the suggest widget status.'));
    class PersistedWidgetSize {
        constructor(_service, editor) {
            this._service = _service;
            this._key = `suggestWidget.size/${editor.getEditorType()}/${editor instanceof embeddedCodeEditorWidget_1.EmbeddedCodeEditorWidget}`;
        }
        restore() {
            const raw = this._service.get(this._key, 0 /* StorageScope.PROFILE */) ?? '';
            try {
                const obj = JSON.parse(raw);
                if (dom.Dimension.is(obj)) {
                    return dom.Dimension.lift(obj);
                }
            }
            catch {
                // ignore
            }
            return undefined;
        }
        store(size) {
            this._service.store(this._key, JSON.stringify(size), 0 /* StorageScope.PROFILE */, 1 /* StorageTarget.MACHINE */);
        }
        reset() {
            this._service.remove(this._key, 0 /* StorageScope.PROFILE */);
        }
    }
    let SuggestWidget = class SuggestWidget {
        static { SuggestWidget_1 = this; }
        static { this.LOADING_MESSAGE = nls.localize(1337, "Loading..."); }
        static { this.NO_SUGGESTIONS_MESSAGE = nls.localize(1338, "No suggestions."); }
        constructor(editor, _storageService, _contextKeyService, _themeService, instantiationService) {
            this.editor = editor;
            this._storageService = _storageService;
            this._state = 0 /* State.Hidden */;
            this._isAuto = false;
            this._pendingLayout = new lifecycle_1.MutableDisposable();
            this._pendingShowDetails = new lifecycle_1.MutableDisposable();
            this._ignoreFocusEvents = false;
            this._forceRenderingAbove = false;
            this._explainMode = false;
            this._showTimeout = new async_1.TimeoutTimer();
            this._disposables = new lifecycle_1.DisposableStore();
            this._onDidSelect = new event_1.PauseableEmitter();
            this._onDidFocus = new event_1.PauseableEmitter();
            this._onDidHide = new event_1.Emitter();
            this._onDidShow = new event_1.Emitter();
            this.onDidSelect = this._onDidSelect.event;
            this.onDidFocus = this._onDidFocus.event;
            this.onDidHide = this._onDidHide.event;
            this.onDidShow = this._onDidShow.event;
            this._onDetailsKeydown = new event_1.Emitter();
            this.onDetailsKeyDown = this._onDetailsKeydown.event;
            this.element = new resizable_1.ResizableHTMLElement();
            this.element.domNode.classList.add('editor-widget', 'suggest-widget');
            this._contentWidget = new SuggestContentWidget(this, editor);
            this._persistedSize = new PersistedWidgetSize(_storageService, editor);
            class ResizeState {
                constructor(persistedSize, currentSize, persistHeight = false, persistWidth = false) {
                    this.persistedSize = persistedSize;
                    this.currentSize = currentSize;
                    this.persistHeight = persistHeight;
                    this.persistWidth = persistWidth;
                }
            }
            let state;
            this._disposables.add(this.element.onDidWillResize(() => {
                this._contentWidget.lockPreference();
                state = new ResizeState(this._persistedSize.restore(), this.element.size);
            }));
            this._disposables.add(this.element.onDidResize(e => {
                this._resize(e.dimension.width, e.dimension.height);
                if (state) {
                    state.persistHeight = state.persistHeight || !!e.north || !!e.south;
                    state.persistWidth = state.persistWidth || !!e.east || !!e.west;
                }
                if (!e.done) {
                    return;
                }
                if (state) {
                    // only store width or height value that have changed and also
                    // only store changes that are above a certain threshold
                    const { itemHeight, defaultSize } = this.getLayoutInfo();
                    const threshold = Math.round(itemHeight / 2);
                    let { width, height } = this.element.size;
                    if (!state.persistHeight || Math.abs(state.currentSize.height - height) <= threshold) {
                        height = state.persistedSize?.height ?? defaultSize.height;
                    }
                    if (!state.persistWidth || Math.abs(state.currentSize.width - width) <= threshold) {
                        width = state.persistedSize?.width ?? defaultSize.width;
                    }
                    this._persistedSize.store(new dom.Dimension(width, height));
                }
                // reset working state
                this._contentWidget.unlockPreference();
                state = undefined;
            }));
            this._messageElement = dom.append(this.element.domNode, dom.$('.message'));
            this._listElement = dom.append(this.element.domNode, dom.$('.tree'));
            const details = this._disposables.add(instantiationService.createInstance(suggestWidgetDetails_1.SuggestDetailsWidget, this.editor));
            details.onDidClose(this.toggleDetails, this, this._disposables);
            this._details = new suggestWidgetDetails_1.SuggestDetailsOverlay(details, this.editor);
            const applyIconStyle = () => this.element.domNode.classList.toggle('no-icons', !this.editor.getOption(119 /* EditorOption.suggest */).showIcons);
            applyIconStyle();
            const renderer = instantiationService.createInstance(suggestWidgetRenderer_1.ItemRenderer, this.editor);
            this._disposables.add(renderer);
            this._disposables.add(renderer.onDidToggleDetails(() => this.toggleDetails()));
            this._list = new listWidget_1.List('SuggestWidget', this._listElement, {
                getHeight: (_element) => this.getLayoutInfo().itemHeight,
                getTemplateId: (_element) => 'suggestion'
            }, [renderer], {
                alwaysConsumeMouseWheel: true,
                useShadows: false,
                mouseSupport: false,
                multipleSelectionSupport: false,
                accessibilityProvider: {
                    getRole: () => 'option',
                    getWidgetAriaLabel: () => nls.localize(1339, "Suggest"),
                    getWidgetRole: () => 'listbox',
                    getAriaLabel: (item) => {
                        let label = item.textLabel;
                        if (typeof item.completion.label !== 'string') {
                            const { detail, description } = item.completion.label;
                            if (detail && description) {
                                label = nls.localize(1340, '{0} {1}, {2}', label, detail, description);
                            }
                            else if (detail) {
                                label = nls.localize(1341, '{0} {1}', label, detail);
                            }
                            else if (description) {
                                label = nls.localize(1342, '{0}, {1}', label, description);
                            }
                        }
                        if (!item.isResolved || !this._isDetailsVisible()) {
                            return label;
                        }
                        const { documentation, detail } = item.completion;
                        const docs = strings.format('{0}{1}', detail || '', documentation ? (typeof documentation === 'string' ? documentation : documentation.value) : '');
                        return nls.localize(1343, "{0}, docs: {1}", label, docs);
                    },
                }
            });
            this._list.style((0, defaultStyles_1.getListStyles)({
                listInactiveFocusBackground: exports.editorSuggestWidgetSelectedBackground,
                listInactiveFocusOutline: colorRegistry_1.activeContrastBorder
            }));
            this._status = instantiationService.createInstance(suggestWidgetStatus_1.SuggestWidgetStatus, this.element.domNode, suggest_1.suggestWidgetStatusbarMenu);
            const applyStatusBarStyle = () => this.element.domNode.classList.toggle('with-status-bar', this.editor.getOption(119 /* EditorOption.suggest */).showStatusBar);
            applyStatusBarStyle();
            this._disposables.add(_themeService.onDidColorThemeChange(t => this._onThemeChange(t)));
            this._onThemeChange(_themeService.getColorTheme());
            this._disposables.add(this._list.onMouseDown(e => this._onListMouseDownOrTap(e)));
            this._disposables.add(this._list.onTap(e => this._onListMouseDownOrTap(e)));
            this._disposables.add(this._list.onDidChangeSelection(e => this._onListSelection(e)));
            this._disposables.add(this._list.onDidChangeFocus(e => this._onListFocus(e)));
            this._disposables.add(this.editor.onDidChangeCursorSelection(() => this._onCursorSelectionChanged()));
            this._disposables.add(this.editor.onDidChangeConfiguration(e => {
                if (e.hasChanged(119 /* EditorOption.suggest */)) {
                    applyStatusBarStyle();
                    applyIconStyle();
                }
                if (this._completionModel && (e.hasChanged(50 /* EditorOption.fontInfo */) || e.hasChanged(120 /* EditorOption.suggestFontSize */) || e.hasChanged(121 /* EditorOption.suggestLineHeight */))) {
                    this._list.splice(0, this._list.length, this._completionModel.items);
                }
            }));
            this._ctxSuggestWidgetVisible = suggest_1.Context.Visible.bindTo(_contextKeyService);
            this._ctxSuggestWidgetDetailsVisible = suggest_1.Context.DetailsVisible.bindTo(_contextKeyService);
            this._ctxSuggestWidgetMultipleSuggestions = suggest_1.Context.MultipleSuggestions.bindTo(_contextKeyService);
            this._ctxSuggestWidgetHasFocusedSuggestion = suggest_1.Context.HasFocusedSuggestion.bindTo(_contextKeyService);
            this._disposables.add(dom.addStandardDisposableListener(this._details.widget.domNode, 'keydown', e => {
                this._onDetailsKeydown.fire(e);
            }));
            this._disposables.add(this.editor.onMouseDown((e) => this._onEditorMouseDown(e)));
        }
        dispose() {
            this._details.widget.dispose();
            this._details.dispose();
            this._list.dispose();
            this._status.dispose();
            this._disposables.dispose();
            this._loadingTimeout?.dispose();
            this._pendingLayout.dispose();
            this._pendingShowDetails.dispose();
            this._showTimeout.dispose();
            this._contentWidget.dispose();
            this.element.dispose();
        }
        _onEditorMouseDown(mouseEvent) {
            if (this._details.widget.domNode.contains(mouseEvent.target.element)) {
                // Clicking inside details
                this._details.widget.domNode.focus();
            }
            else {
                // Clicking outside details and inside suggest
                if (this.element.domNode.contains(mouseEvent.target.element)) {
                    this.editor.focus();
                }
            }
        }
        _onCursorSelectionChanged() {
            if (this._state !== 0 /* State.Hidden */) {
                this._contentWidget.layout();
            }
        }
        _onListMouseDownOrTap(e) {
            if (typeof e.element === 'undefined' || typeof e.index === 'undefined') {
                return;
            }
            // prevent stealing browser focus from the editor
            e.browserEvent.preventDefault();
            e.browserEvent.stopPropagation();
            this._select(e.element, e.index);
        }
        _onListSelection(e) {
            if (e.elements.length) {
                this._select(e.elements[0], e.indexes[0]);
            }
        }
        _select(item, index) {
            const completionModel = this._completionModel;
            if (completionModel) {
                this._onDidSelect.fire({ item, index, model: completionModel });
                this.editor.focus();
            }
        }
        _onThemeChange(theme) {
            this._details.widget.borderWidth = (0, theme_1.isHighContrast)(theme.type) ? 2 : 1;
        }
        _onListFocus(e) {
            if (this._ignoreFocusEvents) {
                return;
            }
            if (!e.elements.length) {
                if (this._currentSuggestionDetails) {
                    this._currentSuggestionDetails.cancel();
                    this._currentSuggestionDetails = undefined;
                    this._focusedItem = undefined;
                }
                this.editor.setAriaOptions({ activeDescendant: undefined });
                this._ctxSuggestWidgetHasFocusedSuggestion.set(false);
                return;
            }
            if (!this._completionModel) {
                return;
            }
            this._ctxSuggestWidgetHasFocusedSuggestion.set(true);
            const item = e.elements[0];
            const index = e.indexes[0];
            if (item !== this._focusedItem) {
                this._currentSuggestionDetails?.cancel();
                this._currentSuggestionDetails = undefined;
                this._focusedItem = item;
                this._list.reveal(index);
                this._currentSuggestionDetails = (0, async_1.createCancelablePromise)(async (token) => {
                    const loading = (0, async_1.disposableTimeout)(() => {
                        if (this._isDetailsVisible()) {
                            this.showDetails(true);
                        }
                    }, 250);
                    const sub = token.onCancellationRequested(() => loading.dispose());
                    try {
                        return await item.resolve(token);
                    }
                    finally {
                        loading.dispose();
                        sub.dispose();
                    }
                });
                this._currentSuggestionDetails.then(() => {
                    if (index >= this._list.length || item !== this._list.element(index)) {
                        return;
                    }
                    // item can have extra information, so re-render
                    this._ignoreFocusEvents = true;
                    this._list.splice(index, 1, [item]);
                    this._list.setFocus([index]);
                    this._ignoreFocusEvents = false;
                    if (this._isDetailsVisible()) {
                        this.showDetails(false);
                    }
                    else {
                        this.element.domNode.classList.remove('docs-side');
                    }
                    this.editor.setAriaOptions({ activeDescendant: (0, suggestWidgetRenderer_1.getAriaId)(index) });
                }).catch(errors_1.onUnexpectedError);
            }
            // emit an event
            this._onDidFocus.fire({ item, index, model: this._completionModel });
        }
        _setState(state) {
            if (this._state === state) {
                return;
            }
            this._state = state;
            this.element.domNode.classList.toggle('frozen', state === 4 /* State.Frozen */);
            this.element.domNode.classList.remove('message');
            switch (state) {
                case 0 /* State.Hidden */:
                    dom.hide(this._messageElement, this._listElement, this._status.element);
                    this._details.hide(true);
                    this._status.hide();
                    this._contentWidget.hide();
                    this._ctxSuggestWidgetVisible.reset();
                    this._ctxSuggestWidgetMultipleSuggestions.reset();
                    this._ctxSuggestWidgetHasFocusedSuggestion.reset();
                    this._showTimeout.cancel();
                    this.element.domNode.classList.remove('visible');
                    this._list.splice(0, this._list.length);
                    this._focusedItem = undefined;
                    this._cappedHeight = undefined;
                    this._explainMode = false;
                    break;
                case 1 /* State.Loading */:
                    this.element.domNode.classList.add('message');
                    this._messageElement.textContent = SuggestWidget_1.LOADING_MESSAGE;
                    dom.hide(this._listElement, this._status.element);
                    dom.show(this._messageElement);
                    this._details.hide();
                    this._show();
                    this._focusedItem = undefined;
                    (0, aria_1.status)(SuggestWidget_1.LOADING_MESSAGE);
                    break;
                case 2 /* State.Empty */:
                    this.element.domNode.classList.add('message');
                    this._messageElement.textContent = SuggestWidget_1.NO_SUGGESTIONS_MESSAGE;
                    dom.hide(this._listElement, this._status.element);
                    dom.show(this._messageElement);
                    this._details.hide();
                    this._show();
                    this._focusedItem = undefined;
                    (0, aria_1.status)(SuggestWidget_1.NO_SUGGESTIONS_MESSAGE);
                    break;
                case 3 /* State.Open */:
                    dom.hide(this._messageElement);
                    dom.show(this._listElement, this._status.element);
                    this._show();
                    break;
                case 4 /* State.Frozen */:
                    dom.hide(this._messageElement);
                    dom.show(this._listElement, this._status.element);
                    this._show();
                    break;
                case 5 /* State.Details */:
                    dom.hide(this._messageElement);
                    dom.show(this._listElement, this._status.element);
                    this._details.show();
                    this._show();
                    break;
            }
        }
        _show() {
            this._status.show();
            this._contentWidget.show();
            this._layout(this._persistedSize.restore());
            this._ctxSuggestWidgetVisible.set(true);
            this._showTimeout.cancelAndSet(() => {
                this.element.domNode.classList.add('visible');
                this._onDidShow.fire(this);
            }, 100);
        }
        showTriggered(auto, delay) {
            if (this._state !== 0 /* State.Hidden */) {
                return;
            }
            this._contentWidget.setPosition(this.editor.getPosition());
            this._isAuto = !!auto;
            if (!this._isAuto) {
                this._loadingTimeout = (0, async_1.disposableTimeout)(() => this._setState(1 /* State.Loading */), delay);
            }
        }
        showSuggestions(completionModel, selectionIndex, isFrozen, isAuto, noFocus) {
            this._contentWidget.setPosition(this.editor.getPosition());
            this._loadingTimeout?.dispose();
            this._currentSuggestionDetails?.cancel();
            this._currentSuggestionDetails = undefined;
            if (this._completionModel !== completionModel) {
                this._completionModel = completionModel;
            }
            if (isFrozen && this._state !== 2 /* State.Empty */ && this._state !== 0 /* State.Hidden */) {
                this._setState(4 /* State.Frozen */);
                return;
            }
            const visibleCount = this._completionModel.items.length;
            const isEmpty = visibleCount === 0;
            this._ctxSuggestWidgetMultipleSuggestions.set(visibleCount > 1);
            if (isEmpty) {
                this._setState(isAuto ? 0 /* State.Hidden */ : 2 /* State.Empty */);
                this._completionModel = undefined;
                return;
            }
            this._focusedItem = undefined;
            // calling list.splice triggers focus event which this widget forwards. That can lead to
            // suggestions being cancelled and the widget being cleared (and hidden). All this happens
            // before revealing and focusing is done which means revealing and focusing will fail when
            // they get run.
            this._onDidFocus.pause();
            this._onDidSelect.pause();
            try {
                this._list.splice(0, this._list.length, this._completionModel.items);
                this._setState(isFrozen ? 4 /* State.Frozen */ : 3 /* State.Open */);
                this._list.reveal(selectionIndex, 0);
                this._list.setFocus(noFocus ? [] : [selectionIndex]);
            }
            finally {
                this._onDidFocus.resume();
                this._onDidSelect.resume();
            }
            this._pendingLayout.value = dom.runAtThisOrScheduleAtNextAnimationFrame(dom.getWindow(this.element.domNode), () => {
                this._pendingLayout.clear();
                this._layout(this.element.size);
                // Reset focus border
                this._details.widget.domNode.classList.remove('focused');
            });
        }
        focusSelected() {
            if (this._list.length > 0) {
                this._list.setFocus([0]);
            }
        }
        selectNextPage() {
            switch (this._state) {
                case 0 /* State.Hidden */:
                    return false;
                case 5 /* State.Details */:
                    this._details.widget.pageDown();
                    return true;
                case 1 /* State.Loading */:
                    return !this._isAuto;
                default:
                    this._list.focusNextPage();
                    return true;
            }
        }
        selectNext() {
            switch (this._state) {
                case 0 /* State.Hidden */:
                    return false;
                case 1 /* State.Loading */:
                    return !this._isAuto;
                default:
                    this._list.focusNext(1, true);
                    return true;
            }
        }
        selectLast() {
            switch (this._state) {
                case 0 /* State.Hidden */:
                    return false;
                case 5 /* State.Details */:
                    this._details.widget.scrollBottom();
                    return true;
                case 1 /* State.Loading */:
                    return !this._isAuto;
                default:
                    this._list.focusLast();
                    return true;
            }
        }
        selectPreviousPage() {
            switch (this._state) {
                case 0 /* State.Hidden */:
                    return false;
                case 5 /* State.Details */:
                    this._details.widget.pageUp();
                    return true;
                case 1 /* State.Loading */:
                    return !this._isAuto;
                default:
                    this._list.focusPreviousPage();
                    return true;
            }
        }
        selectPrevious() {
            switch (this._state) {
                case 0 /* State.Hidden */:
                    return false;
                case 1 /* State.Loading */:
                    return !this._isAuto;
                default:
                    this._list.focusPrevious(1, true);
                    return false;
            }
        }
        selectFirst() {
            switch (this._state) {
                case 0 /* State.Hidden */:
                    return false;
                case 5 /* State.Details */:
                    this._details.widget.scrollTop();
                    return true;
                case 1 /* State.Loading */:
                    return !this._isAuto;
                default:
                    this._list.focusFirst();
                    return true;
            }
        }
        getFocusedItem() {
            if (this._state !== 0 /* State.Hidden */
                && this._state !== 2 /* State.Empty */
                && this._state !== 1 /* State.Loading */
                && this._completionModel
                && this._list.getFocus().length > 0) {
                return {
                    item: this._list.getFocusedElements()[0],
                    index: this._list.getFocus()[0],
                    model: this._completionModel
                };
            }
            return undefined;
        }
        toggleDetailsFocus() {
            if (this._state === 5 /* State.Details */) {
                this._setState(3 /* State.Open */);
                this._details.widget.domNode.classList.remove('focused');
            }
            else if (this._state === 3 /* State.Open */ && this._isDetailsVisible()) {
                this._setState(5 /* State.Details */);
                this._details.widget.domNode.classList.add('focused');
            }
        }
        toggleDetails() {
            if (this._isDetailsVisible()) {
                // hide details widget
                this._pendingShowDetails.clear();
                this._ctxSuggestWidgetDetailsVisible.set(false);
                this._setDetailsVisible(false);
                this._details.hide();
                this.element.domNode.classList.remove('shows-details');
            }
            else if (((0, suggestWidgetDetails_1.canExpandCompletionItem)(this._list.getFocusedElements()[0]) || this._explainMode) && (this._state === 3 /* State.Open */ || this._state === 5 /* State.Details */ || this._state === 4 /* State.Frozen */)) {
                // show details widget (iff possible)
                this._ctxSuggestWidgetDetailsVisible.set(true);
                this._setDetailsVisible(true);
                this.showDetails(false);
            }
        }
        showDetails(loading) {
            this._pendingShowDetails.value = dom.runAtThisOrScheduleAtNextAnimationFrame(dom.getWindow(this.element.domNode), () => {
                this._pendingShowDetails.clear();
                this._details.show();
                if (loading) {
                    this._details.widget.renderLoading();
                }
                else {
                    this._details.widget.renderItem(this._list.getFocusedElements()[0], this._explainMode);
                }
                if (!this._details.widget.isEmpty) {
                    this._positionDetails();
                    this.element.domNode.classList.add('shows-details');
                }
                else {
                    this._details.hide();
                }
                this.editor.focus();
            });
        }
        toggleExplainMode() {
            if (this._list.getFocusedElements()[0]) {
                this._explainMode = !this._explainMode;
                if (!this._isDetailsVisible()) {
                    this.toggleDetails();
                }
                else {
                    this.showDetails(false);
                }
            }
        }
        resetPersistedSize() {
            this._persistedSize.reset();
        }
        hideWidget() {
            this._pendingLayout.clear();
            this._pendingShowDetails.clear();
            this._loadingTimeout?.dispose();
            this._setState(0 /* State.Hidden */);
            this._onDidHide.fire(this);
            this.element.clearSashHoverState();
            // ensure that a reasonable widget height is persisted so that
            // accidential "resize-to-single-items" cases aren't happening
            const dim = this._persistedSize.restore();
            const minPersistedHeight = Math.ceil(this.getLayoutInfo().itemHeight * 4.3);
            if (dim && dim.height < minPersistedHeight) {
                this._persistedSize.store(dim.with(undefined, minPersistedHeight));
            }
        }
        isFrozen() {
            return this._state === 4 /* State.Frozen */;
        }
        _afterRender(position) {
            if (position === null) {
                if (this._isDetailsVisible()) {
                    this._details.hide(); //todo@jrieken soft-hide
                }
                return;
            }
            if (this._state === 2 /* State.Empty */ || this._state === 1 /* State.Loading */) {
                // no special positioning when widget isn't showing list
                return;
            }
            if (this._isDetailsVisible() && !this._details.widget.isEmpty) {
                this._details.show();
            }
            this._positionDetails();
        }
        _layout(size) {
            if (!this.editor.hasModel()) {
                return;
            }
            if (!this.editor.getDomNode()) {
                // happens when running tests
                return;
            }
            const bodyBox = dom.getClientArea(this.element.domNode.ownerDocument.body);
            const info = this.getLayoutInfo();
            if (!size) {
                size = info.defaultSize;
            }
            let height = size.height;
            let width = size.width;
            // status bar
            this._status.element.style.height = `${info.itemHeight}px`;
            if (this._state === 2 /* State.Empty */ || this._state === 1 /* State.Loading */) {
                // showing a message only
                height = info.itemHeight + info.borderHeight;
                width = info.defaultSize.width / 2;
                this.element.enableSashes(false, false, false, false);
                this.element.minSize = this.element.maxSize = new dom.Dimension(width, height);
                this._contentWidget.setPreference(2 /* ContentWidgetPositionPreference.BELOW */);
            }
            else {
                // showing items
                // width math
                const maxWidth = bodyBox.width - info.borderHeight - 2 * info.horizontalPadding;
                if (width > maxWidth) {
                    width = maxWidth;
                }
                const preferredWidth = this._completionModel ? this._completionModel.stats.pLabelLen * info.typicalHalfwidthCharacterWidth : width;
                // height math
                const fullHeight = info.statusBarHeight + this._list.contentHeight + info.borderHeight;
                const minHeight = info.itemHeight + info.statusBarHeight;
                const editorBox = dom.getDomNodePagePosition(this.editor.getDomNode());
                const cursorBox = this.editor.getScrolledVisiblePosition(this.editor.getPosition());
                const cursorBottom = editorBox.top + cursorBox.top + cursorBox.height;
                const maxHeightBelow = Math.min(bodyBox.height - cursorBottom - info.verticalPadding, fullHeight);
                const availableSpaceAbove = editorBox.top + cursorBox.top - info.verticalPadding;
                const maxHeightAbove = Math.min(availableSpaceAbove, fullHeight);
                let maxHeight = Math.min(Math.max(maxHeightAbove, maxHeightBelow) + info.borderHeight, fullHeight);
                if (height === this._cappedHeight?.capped) {
                    // Restore the old (wanted) height when the current
                    // height is capped to fit
                    height = this._cappedHeight.wanted;
                }
                if (height < minHeight) {
                    height = minHeight;
                }
                if (height > maxHeight) {
                    height = maxHeight;
                }
                const forceRenderingAboveRequiredSpace = 150;
                if (height > maxHeightBelow || (this._forceRenderingAbove && availableSpaceAbove > forceRenderingAboveRequiredSpace)) {
                    this._contentWidget.setPreference(1 /* ContentWidgetPositionPreference.ABOVE */);
                    this.element.enableSashes(true, true, false, false);
                    maxHeight = maxHeightAbove;
                }
                else {
                    this._contentWidget.setPreference(2 /* ContentWidgetPositionPreference.BELOW */);
                    this.element.enableSashes(false, true, true, false);
                    maxHeight = maxHeightBelow;
                }
                this.element.preferredSize = new dom.Dimension(preferredWidth, info.defaultSize.height);
                this.element.maxSize = new dom.Dimension(maxWidth, maxHeight);
                this.element.minSize = new dom.Dimension(220, minHeight);
                // Know when the height was capped to fit and remember
                // the wanted height for later. This is required when going
                // left to widen suggestions.
                this._cappedHeight = height === fullHeight
                    ? { wanted: this._cappedHeight?.wanted ?? size.height, capped: height }
                    : undefined;
            }
            this._resize(width, height);
        }
        _resize(width, height) {
            const { width: maxWidth, height: maxHeight } = this.element.maxSize;
            width = Math.min(maxWidth, width);
            height = Math.min(maxHeight, height);
            const { statusBarHeight } = this.getLayoutInfo();
            this._list.layout(height - statusBarHeight, width);
            this._listElement.style.height = `${height - statusBarHeight}px`;
            this.element.layout(height, width);
            this._contentWidget.layout();
            this._positionDetails();
        }
        _positionDetails() {
            if (this._isDetailsVisible()) {
                this._details.placeAtAnchor(this.element.domNode, this._contentWidget.getPosition()?.preference[0] === 2 /* ContentWidgetPositionPreference.BELOW */);
            }
        }
        getLayoutInfo() {
            const fontInfo = this.editor.getOption(50 /* EditorOption.fontInfo */);
            const itemHeight = (0, numbers_1.clamp)(this.editor.getOption(121 /* EditorOption.suggestLineHeight */) || fontInfo.lineHeight, 8, 1000);
            const statusBarHeight = !this.editor.getOption(119 /* EditorOption.suggest */).showStatusBar || this._state === 2 /* State.Empty */ || this._state === 1 /* State.Loading */ ? 0 : itemHeight;
            const borderWidth = this._details.widget.borderWidth;
            const borderHeight = 2 * borderWidth;
            return {
                itemHeight,
                statusBarHeight,
                borderWidth,
                borderHeight,
                typicalHalfwidthCharacterWidth: fontInfo.typicalHalfwidthCharacterWidth,
                verticalPadding: 22,
                horizontalPadding: 14,
                defaultSize: new dom.Dimension(430, statusBarHeight + 12 * itemHeight + borderHeight)
            };
        }
        _isDetailsVisible() {
            return this._storageService.getBoolean('expandSuggestionDocs', 0 /* StorageScope.PROFILE */, false);
        }
        _setDetailsVisible(value) {
            this._storageService.store('expandSuggestionDocs', value, 0 /* StorageScope.PROFILE */, 0 /* StorageTarget.USER */);
        }
        forceRenderingAbove() {
            if (!this._forceRenderingAbove) {
                this._forceRenderingAbove = true;
                this._layout(this._persistedSize.restore());
            }
        }
        stopForceRenderingAbove() {
            this._forceRenderingAbove = false;
        }
    };
    exports.SuggestWidget = SuggestWidget;
    exports.SuggestWidget = SuggestWidget = SuggestWidget_1 = __decorate([
        __param(1, storage_1.IStorageService),
        __param(2, contextkey_1.IContextKeyService),
        __param(3, themeService_1.IThemeService),
        __param(4, instantiation_1.IInstantiationService)
    ], SuggestWidget);
    class SuggestContentWidget {
        constructor(_widget, _editor) {
            this._widget = _widget;
            this._editor = _editor;
            this.allowEditorOverflow = true;
            this.suppressMouseDown = false;
            this._preferenceLocked = false;
            this._added = false;
            this._hidden = false;
        }
        dispose() {
            if (this._added) {
                this._added = false;
                this._editor.removeContentWidget(this);
            }
        }
        getId() {
            return 'editor.widget.suggestWidget';
        }
        getDomNode() {
            return this._widget.element.domNode;
        }
        show() {
            this._hidden = false;
            if (!this._added) {
                this._added = true;
                this._editor.addContentWidget(this);
            }
        }
        hide() {
            if (!this._hidden) {
                this._hidden = true;
                this.layout();
            }
        }
        layout() {
            this._editor.layoutContentWidget(this);
        }
        getPosition() {
            if (this._hidden || !this._position || !this._preference) {
                return null;
            }
            return {
                position: this._position,
                preference: [this._preference]
            };
        }
        beforeRender() {
            const { height, width } = this._widget.element.size;
            const { borderWidth, horizontalPadding } = this._widget.getLayoutInfo();
            return new dom.Dimension(width + 2 * borderWidth + horizontalPadding, height + 2 * borderWidth);
        }
        afterRender(position) {
            this._widget._afterRender(position);
        }
        setPreference(preference) {
            if (!this._preferenceLocked) {
                this._preference = preference;
            }
        }
        lockPreference() {
            this._preferenceLocked = true;
        }
        unlockPreference() {
            this._preferenceLocked = false;
        }
        setPosition(position) {
            this._position = position;
        }
    }
    exports.SuggestContentWidget = SuggestContentWidget;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[426/*vs/editor/contrib/wordHighlighter/browser/highlightDecorations*/], __M([1/*require*/,0/*exports*/,40/*vs/editor/common/model*/,35/*vs/editor/common/model/textModel*/,27/*vs/editor/common/languages*/,3/*vs/nls*/,32/*vs/platform/theme/common/colorRegistry*/,25/*vs/platform/theme/common/themeService*/,536/*vs/css!vs/editor/contrib/wordHighlighter/browser/highlightDecorations*/]), function (require, exports, model_1, textModel_1, languages_1, nls, colorRegistry_1, themeService_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.getHighlightDecorationOptions = getHighlightDecorationOptions;
    exports.getSelectionHighlightDecorationOptions = getSelectionHighlightDecorationOptions;
    const wordHighlightBackground = (0, colorRegistry_1.registerColor)('editor.wordHighlightBackground', { dark: '#575757B8', light: '#57575740', hcDark: null, hcLight: null }, nls.localize(1415, 'Background color of a symbol during read-access, like reading a variable. The color must not be opaque so as not to hide underlying decorations.'), true);
    (0, colorRegistry_1.registerColor)('editor.wordHighlightStrongBackground', { dark: '#004972B8', light: '#0e639c40', hcDark: null, hcLight: null }, nls.localize(1416, 'Background color of a symbol during write-access, like writing to a variable. The color must not be opaque so as not to hide underlying decorations.'), true);
    (0, colorRegistry_1.registerColor)('editor.wordHighlightTextBackground', wordHighlightBackground, nls.localize(1417, 'Background color of a textual occurrence for a symbol. The color must not be opaque so as not to hide underlying decorations.'), true);
    const wordHighlightBorder = (0, colorRegistry_1.registerColor)('editor.wordHighlightBorder', { light: null, dark: null, hcDark: colorRegistry_1.activeContrastBorder, hcLight: colorRegistry_1.activeContrastBorder }, nls.localize(1418, 'Border color of a symbol during read-access, like reading a variable.'));
    (0, colorRegistry_1.registerColor)('editor.wordHighlightStrongBorder', { light: null, dark: null, hcDark: colorRegistry_1.activeContrastBorder, hcLight: colorRegistry_1.activeContrastBorder }, nls.localize(1419, 'Border color of a symbol during write-access, like writing to a variable.'));
    (0, colorRegistry_1.registerColor)('editor.wordHighlightTextBorder', wordHighlightBorder, nls.localize(1420, "Border color of a textual occurrence for a symbol."));
    const overviewRulerWordHighlightForeground = (0, colorRegistry_1.registerColor)('editorOverviewRuler.wordHighlightForeground', '#A0A0A0CC', nls.localize(1421, 'Overview ruler marker color for symbol highlights. The color must not be opaque so as not to hide underlying decorations.'), true);
    const overviewRulerWordHighlightStrongForeground = (0, colorRegistry_1.registerColor)('editorOverviewRuler.wordHighlightStrongForeground', '#C0A0C0CC', nls.localize(1422, 'Overview ruler marker color for write-access symbol highlights. The color must not be opaque so as not to hide underlying decorations.'), true);
    const overviewRulerWordHighlightTextForeground = (0, colorRegistry_1.registerColor)('editorOverviewRuler.wordHighlightTextForeground', colorRegistry_1.overviewRulerSelectionHighlightForeground, nls.localize(1423, 'Overview ruler marker color of a textual occurrence for a symbol. The color must not be opaque so as not to hide underlying decorations.'), true);
    const _WRITE_OPTIONS = textModel_1.ModelDecorationOptions.register({
        description: 'word-highlight-strong',
        stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */,
        className: 'wordHighlightStrong',
        overviewRuler: {
            color: (0, themeService_1.themeColorFromId)(overviewRulerWordHighlightStrongForeground),
            position: model_1.OverviewRulerLane.Center
        },
        minimap: {
            color: (0, themeService_1.themeColorFromId)(colorRegistry_1.minimapSelectionOccurrenceHighlight),
            position: 1 /* MinimapPosition.Inline */
        },
    });
    const _TEXT_OPTIONS = textModel_1.ModelDecorationOptions.register({
        description: 'word-highlight-text',
        stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */,
        className: 'wordHighlightText',
        overviewRuler: {
            color: (0, themeService_1.themeColorFromId)(overviewRulerWordHighlightTextForeground),
            position: model_1.OverviewRulerLane.Center
        },
        minimap: {
            color: (0, themeService_1.themeColorFromId)(colorRegistry_1.minimapSelectionOccurrenceHighlight),
            position: 1 /* MinimapPosition.Inline */
        },
    });
    const _SELECTION_HIGHLIGHT_OPTIONS = textModel_1.ModelDecorationOptions.register({
        description: 'selection-highlight-overview',
        stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */,
        className: 'selectionHighlight',
        overviewRuler: {
            color: (0, themeService_1.themeColorFromId)(colorRegistry_1.overviewRulerSelectionHighlightForeground),
            position: model_1.OverviewRulerLane.Center
        },
        minimap: {
            color: (0, themeService_1.themeColorFromId)(colorRegistry_1.minimapSelectionOccurrenceHighlight),
            position: 1 /* MinimapPosition.Inline */
        },
    });
    const _SELECTION_HIGHLIGHT_OPTIONS_NO_OVERVIEW = textModel_1.ModelDecorationOptions.register({
        description: 'selection-highlight',
        stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */,
        className: 'selectionHighlight',
    });
    const _REGULAR_OPTIONS = textModel_1.ModelDecorationOptions.register({
        description: 'word-highlight',
        stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */,
        className: 'wordHighlight',
        overviewRuler: {
            color: (0, themeService_1.themeColorFromId)(overviewRulerWordHighlightForeground),
            position: model_1.OverviewRulerLane.Center
        },
        minimap: {
            color: (0, themeService_1.themeColorFromId)(colorRegistry_1.minimapSelectionOccurrenceHighlight),
            position: 1 /* MinimapPosition.Inline */
        },
    });
    function getHighlightDecorationOptions(kind) {
        if (kind === languages_1.DocumentHighlightKind.Write) {
            return _WRITE_OPTIONS;
        }
        else if (kind === languages_1.DocumentHighlightKind.Text) {
            return _TEXT_OPTIONS;
        }
        else {
            return _REGULAR_OPTIONS;
        }
    }
    function getSelectionHighlightDecorationOptions(hasSemanticHighlights) {
        // Show in overviewRuler only if model has no semantic highlighting
        return (hasSemanticHighlights ? _SELECTION_HIGHLIGHT_OPTIONS_NO_OVERVIEW : _SELECTION_HIGHLIGHT_OPTIONS);
    }
    (0, themeService_1.registerThemingParticipant)((theme, collector) => {
        const selectionHighlight = theme.getColor(colorRegistry_1.editorSelectionHighlight);
        if (selectionHighlight) {
            collector.addRule(`.monaco-editor .selectionHighlight { background-color: ${selectionHighlight.transparent(0.5)}; }`);
        }
    });
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[840/*vs/editor/contrib/multicursor/browser/multicursor*/], __M([1/*require*/,0/*exports*/,46/*vs/base/browser/ui/aria/aria*/,14/*vs/base/common/async*/,72/*vs/base/common/keyCodes*/,2/*vs/base/common/lifecycle*/,15/*vs/editor/browser/editorExtensions*/,235/*vs/editor/common/cursor/cursorMoveCommands*/,4/*vs/editor/common/core/range*/,23/*vs/editor/common/core/selection*/,20/*vs/editor/common/editorContextKeys*/,423/*vs/editor/contrib/find/browser/findController*/,3/*vs/nls*/,29/*vs/platform/actions/common/actions*/,12/*vs/platform/contextkey/common/contextkey*/,17/*vs/editor/common/services/languageFeatures*/,426/*vs/editor/contrib/wordHighlighter/browser/highlightDecorations*/,7/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, aria_1, async_1, keyCodes_1, lifecycle_1, editorExtensions_1, cursorMoveCommands_1, range_1, selection_1, editorContextKeys_1, findController_1, nls, actions_1, contextkey_1, languageFeatures_1, highlightDecorations_1, instantiation_1) {
    "use strict";
    var SelectionHighlighter_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.FocusPreviousCursor = exports.FocusNextCursor = exports.SelectionHighlighter = exports.CompatChangeAll = exports.SelectHighlightsAction = exports.MoveSelectionToPreviousFindMatchAction = exports.MoveSelectionToNextFindMatchAction = exports.AddSelectionToPreviousFindMatchAction = exports.AddSelectionToNextFindMatchAction = exports.MultiCursorSelectionControllerAction = exports.MultiCursorSelectionController = exports.MultiCursorSession = exports.MultiCursorSessionResult = exports.InsertCursorBelow = exports.InsertCursorAbove = void 0;
    function announceCursorChange(previousCursorState, cursorState) {
        const cursorDiff = cursorState.filter(cs => !previousCursorState.find(pcs => pcs.equals(cs)));
        if (cursorDiff.length >= 1) {
            const cursorPositions = cursorDiff.map(cs => `line ${cs.viewState.position.lineNumber} column ${cs.viewState.position.column}`).join(', ');
            const msg = cursorDiff.length === 1 ? nls.localize(1149, "Cursor added: {0}", cursorPositions) : nls.localize(1150, "Cursors added: {0}", cursorPositions);
            (0, aria_1.status)(msg);
        }
    }
    class InsertCursorAbove extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: 'editor.action.insertCursorAbove',
                label: nls.localize(1151, "Add Cursor Above"),
                alias: 'Add Cursor Above',
                precondition: undefined,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    primary: 2048 /* KeyMod.CtrlCmd */ | 512 /* KeyMod.Alt */ | 16 /* KeyCode.UpArrow */,
                    linux: {
                        primary: 1024 /* KeyMod.Shift */ | 512 /* KeyMod.Alt */ | 16 /* KeyCode.UpArrow */,
                        secondary: [2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 16 /* KeyCode.UpArrow */]
                    },
                    weight: 100 /* KeybindingWeight.EditorContrib */
                },
                menuOpts: {
                    menuId: actions_1.MenuId.MenubarSelectionMenu,
                    group: '3_multi',
                    title: nls.localize(1152, "&&Add Cursor Above"),
                    order: 2
                }
            });
        }
        run(accessor, editor, args) {
            if (!editor.hasModel()) {
                return;
            }
            let useLogicalLine = true;
            if (args && args.logicalLine === false) {
                useLogicalLine = false;
            }
            const viewModel = editor._getViewModel();
            if (viewModel.cursorConfig.readOnly) {
                return;
            }
            viewModel.model.pushStackElement();
            const previousCursorState = viewModel.getCursorStates();
            viewModel.setCursorStates(args.source, 3 /* CursorChangeReason.Explicit */, cursorMoveCommands_1.CursorMoveCommands.addCursorUp(viewModel, previousCursorState, useLogicalLine));
            viewModel.revealTopMostCursor(args.source);
            announceCursorChange(previousCursorState, viewModel.getCursorStates());
        }
    }
    exports.InsertCursorAbove = InsertCursorAbove;
    class InsertCursorBelow extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: 'editor.action.insertCursorBelow',
                label: nls.localize(1153, "Add Cursor Below"),
                alias: 'Add Cursor Below',
                precondition: undefined,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    primary: 2048 /* KeyMod.CtrlCmd */ | 512 /* KeyMod.Alt */ | 18 /* KeyCode.DownArrow */,
                    linux: {
                        primary: 1024 /* KeyMod.Shift */ | 512 /* KeyMod.Alt */ | 18 /* KeyCode.DownArrow */,
                        secondary: [2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 18 /* KeyCode.DownArrow */]
                    },
                    weight: 100 /* KeybindingWeight.EditorContrib */
                },
                menuOpts: {
                    menuId: actions_1.MenuId.MenubarSelectionMenu,
                    group: '3_multi',
                    title: nls.localize(1154, "A&&dd Cursor Below"),
                    order: 3
                }
            });
        }
        run(accessor, editor, args) {
            if (!editor.hasModel()) {
                return;
            }
            let useLogicalLine = true;
            if (args && args.logicalLine === false) {
                useLogicalLine = false;
            }
            const viewModel = editor._getViewModel();
            if (viewModel.cursorConfig.readOnly) {
                return;
            }
            viewModel.model.pushStackElement();
            const previousCursorState = viewModel.getCursorStates();
            viewModel.setCursorStates(args.source, 3 /* CursorChangeReason.Explicit */, cursorMoveCommands_1.CursorMoveCommands.addCursorDown(viewModel, previousCursorState, useLogicalLine));
            viewModel.revealBottomMostCursor(args.source);
            announceCursorChange(previousCursorState, viewModel.getCursorStates());
        }
    }
    exports.InsertCursorBelow = InsertCursorBelow;
    class InsertCursorAtEndOfEachLineSelected extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: 'editor.action.insertCursorAtEndOfEachLineSelected',
                label: nls.localize(1155, "Add Cursors to Line Ends"),
                alias: 'Add Cursors to Line Ends',
                precondition: undefined,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    primary: 1024 /* KeyMod.Shift */ | 512 /* KeyMod.Alt */ | 39 /* KeyCode.KeyI */,
                    weight: 100 /* KeybindingWeight.EditorContrib */
                },
                menuOpts: {
                    menuId: actions_1.MenuId.MenubarSelectionMenu,
                    group: '3_multi',
                    title: nls.localize(1156, "Add C&&ursors to Line Ends"),
                    order: 4
                }
            });
        }
        getCursorsForSelection(selection, model, result) {
            if (selection.isEmpty()) {
                return;
            }
            for (let i = selection.startLineNumber; i < selection.endLineNumber; i++) {
                const currentLineMaxColumn = model.getLineMaxColumn(i);
                result.push(new selection_1.Selection(i, currentLineMaxColumn, i, currentLineMaxColumn));
            }
            if (selection.endColumn > 1) {
                result.push(new selection_1.Selection(selection.endLineNumber, selection.endColumn, selection.endLineNumber, selection.endColumn));
            }
        }
        run(accessor, editor) {
            if (!editor.hasModel()) {
                return;
            }
            const model = editor.getModel();
            const selections = editor.getSelections();
            const viewModel = editor._getViewModel();
            const previousCursorState = viewModel.getCursorStates();
            const newSelections = [];
            selections.forEach((sel) => this.getCursorsForSelection(sel, model, newSelections));
            if (newSelections.length > 0) {
                editor.setSelections(newSelections);
            }
            announceCursorChange(previousCursorState, viewModel.getCursorStates());
        }
    }
    class InsertCursorAtEndOfLineSelected extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: 'editor.action.addCursorsToBottom',
                label: nls.localize(1157, "Add Cursors To Bottom"),
                alias: 'Add Cursors To Bottom',
                precondition: undefined
            });
        }
        run(accessor, editor) {
            if (!editor.hasModel()) {
                return;
            }
            const selections = editor.getSelections();
            const lineCount = editor.getModel().getLineCount();
            const newSelections = [];
            for (let i = selections[0].startLineNumber; i <= lineCount; i++) {
                newSelections.push(new selection_1.Selection(i, selections[0].startColumn, i, selections[0].endColumn));
            }
            const viewModel = editor._getViewModel();
            const previousCursorState = viewModel.getCursorStates();
            if (newSelections.length > 0) {
                editor.setSelections(newSelections);
            }
            announceCursorChange(previousCursorState, viewModel.getCursorStates());
        }
    }
    class InsertCursorAtTopOfLineSelected extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: 'editor.action.addCursorsToTop',
                label: nls.localize(1158, "Add Cursors To Top"),
                alias: 'Add Cursors To Top',
                precondition: undefined
            });
        }
        run(accessor, editor) {
            if (!editor.hasModel()) {
                return;
            }
            const selections = editor.getSelections();
            const newSelections = [];
            for (let i = selections[0].startLineNumber; i >= 1; i--) {
                newSelections.push(new selection_1.Selection(i, selections[0].startColumn, i, selections[0].endColumn));
            }
            const viewModel = editor._getViewModel();
            const previousCursorState = viewModel.getCursorStates();
            if (newSelections.length > 0) {
                editor.setSelections(newSelections);
            }
            announceCursorChange(previousCursorState, viewModel.getCursorStates());
        }
    }
    class MultiCursorSessionResult {
        constructor(selections, revealRange, revealScrollType) {
            this.selections = selections;
            this.revealRange = revealRange;
            this.revealScrollType = revealScrollType;
        }
    }
    exports.MultiCursorSessionResult = MultiCursorSessionResult;
    class MultiCursorSession {
        static create(editor, findController) {
            if (!editor.hasModel()) {
                return null;
            }
            const findState = findController.getState();
            // Find widget owns entirely what we search for if:
            //  - focus is not in the editor (i.e. it is in the find widget)
            //  - and the search widget is visible
            //  - and the search string is non-empty
            if (!editor.hasTextFocus() && findState.isRevealed && findState.searchString.length > 0) {
                // Find widget owns what is searched for
                return new MultiCursorSession(editor, findController, false, findState.searchString, findState.wholeWord, findState.matchCase, null);
            }
            // Otherwise, the selection gives the search text, and the find widget gives the search settings
            // The exception is the find state disassociation case: when beginning with a single, collapsed selection
            let isDisconnectedFromFindController = false;
            let wholeWord;
            let matchCase;
            const selections = editor.getSelections();
            if (selections.length === 1 && selections[0].isEmpty()) {
                isDisconnectedFromFindController = true;
                wholeWord = true;
                matchCase = true;
            }
            else {
                wholeWord = findState.wholeWord;
                matchCase = findState.matchCase;
            }
            // Selection owns what is searched for
            const s = editor.getSelection();
            let searchText;
            let currentMatch = null;
            if (s.isEmpty()) {
                // selection is empty => expand to current word
                const word = editor.getConfiguredWordAtPosition(s.getStartPosition());
                if (!word) {
                    return null;
                }
                searchText = word.word;
                currentMatch = new selection_1.Selection(s.startLineNumber, word.startColumn, s.startLineNumber, word.endColumn);
            }
            else {
                searchText = editor.getModel().getValueInRange(s).replace(/\r\n/g, '\n');
            }
            return new MultiCursorSession(editor, findController, isDisconnectedFromFindController, searchText, wholeWord, matchCase, currentMatch);
        }
        constructor(_editor, findController, isDisconnectedFromFindController, searchText, wholeWord, matchCase, currentMatch) {
            this._editor = _editor;
            this.findController = findController;
            this.isDisconnectedFromFindController = isDisconnectedFromFindController;
            this.searchText = searchText;
            this.wholeWord = wholeWord;
            this.matchCase = matchCase;
            this.currentMatch = currentMatch;
        }
        addSelectionToNextFindMatch() {
            if (!this._editor.hasModel()) {
                return null;
            }
            const nextMatch = this._getNextMatch();
            if (!nextMatch) {
                return null;
            }
            const allSelections = this._editor.getSelections();
            return new MultiCursorSessionResult(allSelections.concat(nextMatch), nextMatch, 0 /* ScrollType.Smooth */);
        }
        moveSelectionToNextFindMatch() {
            if (!this._editor.hasModel()) {
                return null;
            }
            const nextMatch = this._getNextMatch();
            if (!nextMatch) {
                return null;
            }
            const allSelections = this._editor.getSelections();
            return new MultiCursorSessionResult(allSelections.slice(0, allSelections.length - 1).concat(nextMatch), nextMatch, 0 /* ScrollType.Smooth */);
        }
        _getNextMatch() {
            if (!this._editor.hasModel()) {
                return null;
            }
            if (this.currentMatch) {
                const result = this.currentMatch;
                this.currentMatch = null;
                return result;
            }
            this.findController.highlightFindOptions();
            const allSelections = this._editor.getSelections();
            const lastAddedSelection = allSelections[allSelections.length - 1];
            const nextMatch = this._editor.getModel().findNextMatch(this.searchText, lastAddedSelection.getEndPosition(), false, this.matchCase, this.wholeWord ? this._editor.getOption(132 /* EditorOption.wordSeparators */) : null, false);
            if (!nextMatch) {
                return null;
            }
            return new selection_1.Selection(nextMatch.range.startLineNumber, nextMatch.range.startColumn, nextMatch.range.endLineNumber, nextMatch.range.endColumn);
        }
        addSelectionToPreviousFindMatch() {
            if (!this._editor.hasModel()) {
                return null;
            }
            const previousMatch = this._getPreviousMatch();
            if (!previousMatch) {
                return null;
            }
            const allSelections = this._editor.getSelections();
            return new MultiCursorSessionResult(allSelections.concat(previousMatch), previousMatch, 0 /* ScrollType.Smooth */);
        }
        moveSelectionToPreviousFindMatch() {
            if (!this._editor.hasModel()) {
                return null;
            }
            const previousMatch = this._getPreviousMatch();
            if (!previousMatch) {
                return null;
            }
            const allSelections = this._editor.getSelections();
            return new MultiCursorSessionResult(allSelections.slice(0, allSelections.length - 1).concat(previousMatch), previousMatch, 0 /* ScrollType.Smooth */);
        }
        _getPreviousMatch() {
            if (!this._editor.hasModel()) {
                return null;
            }
            if (this.currentMatch) {
                const result = this.currentMatch;
                this.currentMatch = null;
                return result;
            }
            this.findController.highlightFindOptions();
            const allSelections = this._editor.getSelections();
            const lastAddedSelection = allSelections[allSelections.length - 1];
            const previousMatch = this._editor.getModel().findPreviousMatch(this.searchText, lastAddedSelection.getStartPosition(), false, this.matchCase, this.wholeWord ? this._editor.getOption(132 /* EditorOption.wordSeparators */) : null, false);
            if (!previousMatch) {
                return null;
            }
            return new selection_1.Selection(previousMatch.range.startLineNumber, previousMatch.range.startColumn, previousMatch.range.endLineNumber, previousMatch.range.endColumn);
        }
        selectAll(searchScope) {
            if (!this._editor.hasModel()) {
                return [];
            }
            this.findController.highlightFindOptions();
            const editorModel = this._editor.getModel();
            if (searchScope) {
                return editorModel.findMatches(this.searchText, searchScope, false, this.matchCase, this.wholeWord ? this._editor.getOption(132 /* EditorOption.wordSeparators */) : null, false, 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */);
            }
            return editorModel.findMatches(this.searchText, true, false, this.matchCase, this.wholeWord ? this._editor.getOption(132 /* EditorOption.wordSeparators */) : null, false, 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */);
        }
    }
    exports.MultiCursorSession = MultiCursorSession;
    class MultiCursorSelectionController extends lifecycle_1.Disposable {
        static { this.ID = 'editor.contrib.multiCursorController'; }
        static get(editor) {
            return editor.getContribution(MultiCursorSelectionController.ID);
        }
        constructor(editor) {
            super();
            this._sessionDispose = this._register(new lifecycle_1.DisposableStore());
            this._editor = editor;
            this._ignoreSelectionChange = false;
            this._session = null;
        }
        dispose() {
            this._endSession();
            super.dispose();
        }
        _beginSessionIfNeeded(findController) {
            if (!this._session) {
                // Create a new session
                const session = MultiCursorSession.create(this._editor, findController);
                if (!session) {
                    return;
                }
                this._session = session;
                const newState = { searchString: this._session.searchText };
                if (this._session.isDisconnectedFromFindController) {
                    newState.wholeWordOverride = 1 /* FindOptionOverride.True */;
                    newState.matchCaseOverride = 1 /* FindOptionOverride.True */;
                    newState.isRegexOverride = 2 /* FindOptionOverride.False */;
                }
                findController.getState().change(newState, false);
                this._sessionDispose.add(this._editor.onDidChangeCursorSelection((e) => {
                    if (this._ignoreSelectionChange) {
                        return;
                    }
                    this._endSession();
                }));
                this._sessionDispose.add(this._editor.onDidBlurEditorText(() => {
                    this._endSession();
                }));
                this._sessionDispose.add(findController.getState().onFindReplaceStateChange((e) => {
                    if (e.matchCase || e.wholeWord) {
                        this._endSession();
                    }
                }));
            }
        }
        _endSession() {
            this._sessionDispose.clear();
            if (this._session && this._session.isDisconnectedFromFindController) {
                const newState = {
                    wholeWordOverride: 0 /* FindOptionOverride.NotSet */,
                    matchCaseOverride: 0 /* FindOptionOverride.NotSet */,
                    isRegexOverride: 0 /* FindOptionOverride.NotSet */,
                };
                this._session.findController.getState().change(newState, false);
            }
            this._session = null;
        }
        _setSelections(selections) {
            this._ignoreSelectionChange = true;
            this._editor.setSelections(selections);
            this._ignoreSelectionChange = false;
        }
        _expandEmptyToWord(model, selection) {
            if (!selection.isEmpty()) {
                return selection;
            }
            const word = this._editor.getConfiguredWordAtPosition(selection.getStartPosition());
            if (!word) {
                return selection;
            }
            return new selection_1.Selection(selection.startLineNumber, word.startColumn, selection.startLineNumber, word.endColumn);
        }
        _applySessionResult(result) {
            if (!result) {
                return;
            }
            this._setSelections(result.selections);
            if (result.revealRange) {
                this._editor.revealRangeInCenterIfOutsideViewport(result.revealRange, result.revealScrollType);
            }
        }
        getSession(findController) {
            return this._session;
        }
        addSelectionToNextFindMatch(findController) {
            if (!this._editor.hasModel()) {
                return;
            }
            if (!this._session) {
                // If there are multiple cursors, handle the case where they do not all select the same text.
                const allSelections = this._editor.getSelections();
                if (allSelections.length > 1) {
                    const findState = findController.getState();
                    const matchCase = findState.matchCase;
                    const selectionsContainSameText = modelRangesContainSameText(this._editor.getModel(), allSelections, matchCase);
                    if (!selectionsContainSameText) {
                        const model = this._editor.getModel();
                        const resultingSelections = [];
                        for (let i = 0, len = allSelections.length; i < len; i++) {
                            resultingSelections[i] = this._expandEmptyToWord(model, allSelections[i]);
                        }
                        this._editor.setSelections(resultingSelections);
                        return;
                    }
                }
            }
            this._beginSessionIfNeeded(findController);
            if (this._session) {
                this._applySessionResult(this._session.addSelectionToNextFindMatch());
            }
        }
        addSelectionToPreviousFindMatch(findController) {
            this._beginSessionIfNeeded(findController);
            if (this._session) {
                this._applySessionResult(this._session.addSelectionToPreviousFindMatch());
            }
        }
        moveSelectionToNextFindMatch(findController) {
            this._beginSessionIfNeeded(findController);
            if (this._session) {
                this._applySessionResult(this._session.moveSelectionToNextFindMatch());
            }
        }
        moveSelectionToPreviousFindMatch(findController) {
            this._beginSessionIfNeeded(findController);
            if (this._session) {
                this._applySessionResult(this._session.moveSelectionToPreviousFindMatch());
            }
        }
        selectAll(findController) {
            if (!this._editor.hasModel()) {
                return;
            }
            let matches = null;
            const findState = findController.getState();
            // Special case: find widget owns entirely what we search for if:
            // - focus is not in the editor (i.e. it is in the find widget)
            // - and the search widget is visible
            // - and the search string is non-empty
            // - and we're searching for a regex
            if (findState.isRevealed && findState.searchString.length > 0 && findState.isRegex) {
                const editorModel = this._editor.getModel();
                if (findState.searchScope) {
                    matches = editorModel.findMatches(findState.searchString, findState.searchScope, findState.isRegex, findState.matchCase, findState.wholeWord ? this._editor.getOption(132 /* EditorOption.wordSeparators */) : null, false, 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */);
                }
                else {
                    matches = editorModel.findMatches(findState.searchString, true, findState.isRegex, findState.matchCase, findState.wholeWord ? this._editor.getOption(132 /* EditorOption.wordSeparators */) : null, false, 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */);
                }
            }
            else {
                this._beginSessionIfNeeded(findController);
                if (!this._session) {
                    return;
                }
                matches = this._session.selectAll(findState.searchScope);
            }
            if (matches.length > 0) {
                const editorSelection = this._editor.getSelection();
                // Have the primary cursor remain the one where the action was invoked
                for (let i = 0, len = matches.length; i < len; i++) {
                    const match = matches[i];
                    const intersection = match.range.intersectRanges(editorSelection);
                    if (intersection) {
                        // bingo!
                        matches[i] = matches[0];
                        matches[0] = match;
                        break;
                    }
                }
                this._setSelections(matches.map(m => new selection_1.Selection(m.range.startLineNumber, m.range.startColumn, m.range.endLineNumber, m.range.endColumn)));
            }
        }
    }
    exports.MultiCursorSelectionController = MultiCursorSelectionController;
    class MultiCursorSelectionControllerAction extends editorExtensions_1.EditorAction {
        run(accessor, editor) {
            const multiCursorController = MultiCursorSelectionController.get(editor);
            if (!multiCursorController) {
                return;
            }
            const viewModel = editor._getViewModel();
            if (viewModel) {
                const previousCursorState = viewModel.getCursorStates();
                const findController = findController_1.CommonFindController.get(editor);
                if (findController) {
                    this._run(multiCursorController, findController);
                }
                else {
                    const newFindController = accessor.get(instantiation_1.IInstantiationService).createInstance(findController_1.CommonFindController, editor);
                    this._run(multiCursorController, newFindController);
                    newFindController.dispose();
                }
                announceCursorChange(previousCursorState, viewModel.getCursorStates());
            }
        }
    }
    exports.MultiCursorSelectionControllerAction = MultiCursorSelectionControllerAction;
    class AddSelectionToNextFindMatchAction extends MultiCursorSelectionControllerAction {
        constructor() {
            super({
                id: 'editor.action.addSelectionToNextFindMatch',
                label: nls.localize(1159, "Add Selection To Next Find Match"),
                alias: 'Add Selection To Next Find Match',
                precondition: undefined,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.focus,
                    primary: 2048 /* KeyMod.CtrlCmd */ | 34 /* KeyCode.KeyD */,
                    weight: 100 /* KeybindingWeight.EditorContrib */
                },
                menuOpts: {
                    menuId: actions_1.MenuId.MenubarSelectionMenu,
                    group: '3_multi',
                    title: nls.localize(1160, "Add &&Next Occurrence"),
                    order: 5
                }
            });
        }
        _run(multiCursorController, findController) {
            multiCursorController.addSelectionToNextFindMatch(findController);
        }
    }
    exports.AddSelectionToNextFindMatchAction = AddSelectionToNextFindMatchAction;
    class AddSelectionToPreviousFindMatchAction extends MultiCursorSelectionControllerAction {
        constructor() {
            super({
                id: 'editor.action.addSelectionToPreviousFindMatch',
                label: nls.localize(1161, "Add Selection To Previous Find Match"),
                alias: 'Add Selection To Previous Find Match',
                precondition: undefined,
                menuOpts: {
                    menuId: actions_1.MenuId.MenubarSelectionMenu,
                    group: '3_multi',
                    title: nls.localize(1162, "Add P&&revious Occurrence"),
                    order: 6
                }
            });
        }
        _run(multiCursorController, findController) {
            multiCursorController.addSelectionToPreviousFindMatch(findController);
        }
    }
    exports.AddSelectionToPreviousFindMatchAction = AddSelectionToPreviousFindMatchAction;
    class MoveSelectionToNextFindMatchAction extends MultiCursorSelectionControllerAction {
        constructor() {
            super({
                id: 'editor.action.moveSelectionToNextFindMatch',
                label: nls.localize(1163, "Move Last Selection To Next Find Match"),
                alias: 'Move Last Selection To Next Find Match',
                precondition: undefined,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.focus,
                    primary: (0, keyCodes_1.KeyChord)(2048 /* KeyMod.CtrlCmd */ | 41 /* KeyCode.KeyK */, 2048 /* KeyMod.CtrlCmd */ | 34 /* KeyCode.KeyD */),
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
        _run(multiCursorController, findController) {
            multiCursorController.moveSelectionToNextFindMatch(findController);
        }
    }
    exports.MoveSelectionToNextFindMatchAction = MoveSelectionToNextFindMatchAction;
    class MoveSelectionToPreviousFindMatchAction extends MultiCursorSelectionControllerAction {
        constructor() {
            super({
                id: 'editor.action.moveSelectionToPreviousFindMatch',
                label: nls.localize(1164, "Move Last Selection To Previous Find Match"),
                alias: 'Move Last Selection To Previous Find Match',
                precondition: undefined
            });
        }
        _run(multiCursorController, findController) {
            multiCursorController.moveSelectionToPreviousFindMatch(findController);
        }
    }
    exports.MoveSelectionToPreviousFindMatchAction = MoveSelectionToPreviousFindMatchAction;
    class SelectHighlightsAction extends MultiCursorSelectionControllerAction {
        constructor() {
            super({
                id: 'editor.action.selectHighlights',
                label: nls.localize(1165, "Select All Occurrences of Find Match"),
                alias: 'Select All Occurrences of Find Match',
                precondition: undefined,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.focus,
                    primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 42 /* KeyCode.KeyL */,
                    weight: 100 /* KeybindingWeight.EditorContrib */
                },
                menuOpts: {
                    menuId: actions_1.MenuId.MenubarSelectionMenu,
                    group: '3_multi',
                    title: nls.localize(1166, "Select All &&Occurrences"),
                    order: 7
                }
            });
        }
        _run(multiCursorController, findController) {
            multiCursorController.selectAll(findController);
        }
    }
    exports.SelectHighlightsAction = SelectHighlightsAction;
    class CompatChangeAll extends MultiCursorSelectionControllerAction {
        constructor() {
            super({
                id: 'editor.action.changeAll',
                label: nls.localize(1167, "Change All Occurrences"),
                alias: 'Change All Occurrences',
                precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, editorContextKeys_1.EditorContextKeys.editorTextFocus),
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    primary: 2048 /* KeyMod.CtrlCmd */ | 60 /* KeyCode.F2 */,
                    weight: 100 /* KeybindingWeight.EditorContrib */
                },
                contextMenuOpts: {
                    group: '1_modification',
                    order: 1.2
                }
            });
        }
        _run(multiCursorController, findController) {
            multiCursorController.selectAll(findController);
        }
    }
    exports.CompatChangeAll = CompatChangeAll;
    class SelectionHighlighterState {
        constructor(_model, _searchText, _matchCase, _wordSeparators, prevState) {
            this._model = _model;
            this._searchText = _searchText;
            this._matchCase = _matchCase;
            this._wordSeparators = _wordSeparators;
            this._modelVersionId = this._model.getVersionId();
            this._cachedFindMatches = null;
            if (prevState
                && this._model === prevState._model
                && this._searchText === prevState._searchText
                && this._matchCase === prevState._matchCase
                && this._wordSeparators === prevState._wordSeparators
                && this._modelVersionId === prevState._modelVersionId) {
                this._cachedFindMatches = prevState._cachedFindMatches;
            }
        }
        findMatches() {
            if (this._cachedFindMatches === null) {
                this._cachedFindMatches = this._model.findMatches(this._searchText, true, false, this._matchCase, this._wordSeparators, false).map(m => m.range);
                this._cachedFindMatches.sort(range_1.Range.compareRangesUsingStarts);
            }
            return this._cachedFindMatches;
        }
    }
    let SelectionHighlighter = class SelectionHighlighter extends lifecycle_1.Disposable {
        static { SelectionHighlighter_1 = this; }
        static { this.ID = 'editor.contrib.selectionHighlighter'; }
        constructor(editor, _languageFeaturesService) {
            super();
            this._languageFeaturesService = _languageFeaturesService;
            this.editor = editor;
            this._isEnabled = editor.getOption(109 /* EditorOption.selectionHighlight */);
            this._decorations = editor.createDecorationsCollection();
            this.updateSoon = this._register(new async_1.RunOnceScheduler(() => this._update(), 300));
            this.state = null;
            this._register(editor.onDidChangeConfiguration((e) => {
                this._isEnabled = editor.getOption(109 /* EditorOption.selectionHighlight */);
            }));
            this._register(editor.onDidChangeCursorSelection((e) => {
                if (!this._isEnabled) {
                    // Early exit if nothing needs to be done!
                    // Leave some form of early exit check here if you wish to continue being a cursor position change listener ;)
                    return;
                }
                if (e.selection.isEmpty()) {
                    if (e.reason === 3 /* CursorChangeReason.Explicit */) {
                        if (this.state) {
                            // no longer valid
                            this._setState(null);
                        }
                        this.updateSoon.schedule();
                    }
                    else {
                        this._setState(null);
                    }
                }
                else {
                    this._update();
                }
            }));
            this._register(editor.onDidChangeModel((e) => {
                this._setState(null);
            }));
            this._register(editor.onDidChangeModelContent((e) => {
                if (this._isEnabled) {
                    this.updateSoon.schedule();
                }
            }));
            const findController = findController_1.CommonFindController.get(editor);
            if (findController) {
                this._register(findController.getState().onFindReplaceStateChange((e) => {
                    this._update();
                }));
            }
            this.updateSoon.schedule();
        }
        _update() {
            this._setState(SelectionHighlighter_1._createState(this.state, this._isEnabled, this.editor));
        }
        static _createState(oldState, isEnabled, editor) {
            if (!isEnabled) {
                return null;
            }
            if (!editor.hasModel()) {
                return null;
            }
            const s = editor.getSelection();
            if (s.startLineNumber !== s.endLineNumber) {
                // multiline forbidden for perf reasons
                return null;
            }
            const multiCursorController = MultiCursorSelectionController.get(editor);
            if (!multiCursorController) {
                return null;
            }
            const findController = findController_1.CommonFindController.get(editor);
            if (!findController) {
                return null;
            }
            let r = multiCursorController.getSession(findController);
            if (!r) {
                const allSelections = editor.getSelections();
                if (allSelections.length > 1) {
                    const findState = findController.getState();
                    const matchCase = findState.matchCase;
                    const selectionsContainSameText = modelRangesContainSameText(editor.getModel(), allSelections, matchCase);
                    if (!selectionsContainSameText) {
                        return null;
                    }
                }
                r = MultiCursorSession.create(editor, findController);
            }
            if (!r) {
                return null;
            }
            if (r.currentMatch) {
                // This is an empty selection
                // Do not interfere with semantic word highlighting in the no selection case
                return null;
            }
            if (/^[ \t]+$/.test(r.searchText)) {
                // whitespace only selection
                return null;
            }
            if (r.searchText.length > 200) {
                // very long selection
                return null;
            }
            // TODO: better handling of this case
            const findState = findController.getState();
            const caseSensitive = findState.matchCase;
            // Return early if the find widget shows the exact same matches
            if (findState.isRevealed) {
                let findStateSearchString = findState.searchString;
                if (!caseSensitive) {
                    findStateSearchString = findStateSearchString.toLowerCase();
                }
                let mySearchString = r.searchText;
                if (!caseSensitive) {
                    mySearchString = mySearchString.toLowerCase();
                }
                if (findStateSearchString === mySearchString && r.matchCase === findState.matchCase && r.wholeWord === findState.wholeWord && !findState.isRegex) {
                    return null;
                }
            }
            return new SelectionHighlighterState(editor.getModel(), r.searchText, r.matchCase, r.wholeWord ? editor.getOption(132 /* EditorOption.wordSeparators */) : null, oldState);
        }
        _setState(newState) {
            this.state = newState;
            if (!this.state) {
                this._decorations.clear();
                return;
            }
            if (!this.editor.hasModel()) {
                return;
            }
            const model = this.editor.getModel();
            if (model.isTooLargeForTokenization()) {
                // the file is too large, so searching word under cursor in the whole document would be blocking the UI.
                return;
            }
            const allMatches = this.state.findMatches();
            const selections = this.editor.getSelections();
            selections.sort(range_1.Range.compareRangesUsingStarts);
            // do not overlap with selection (issue #64 and #512)
            const matches = [];
            for (let i = 0, j = 0, len = allMatches.length, lenJ = selections.length; i < len;) {
                const match = allMatches[i];
                if (j >= lenJ) {
                    // finished all editor selections
                    matches.push(match);
                    i++;
                }
                else {
                    const cmp = range_1.Range.compareRangesUsingStarts(match, selections[j]);
                    if (cmp < 0) {
                        // match is before sel
                        if (selections[j].isEmpty() || !range_1.Range.areIntersecting(match, selections[j])) {
                            matches.push(match);
                        }
                        i++;
                    }
                    else if (cmp > 0) {
                        // sel is before match
                        j++;
                    }
                    else {
                        // sel is equal to match
                        i++;
                        j++;
                    }
                }
            }
            const occurrenceHighlighting = this.editor.getOption(81 /* EditorOption.occurrencesHighlight */) !== 'off';
            const hasSemanticHighlights = this._languageFeaturesService.documentHighlightProvider.has(model) && occurrenceHighlighting;
            const decorations = matches.map(r => {
                return {
                    range: r,
                    options: (0, highlightDecorations_1.getSelectionHighlightDecorationOptions)(hasSemanticHighlights)
                };
            });
            this._decorations.set(decorations);
        }
        dispose() {
            this._setState(null);
            super.dispose();
        }
    };
    exports.SelectionHighlighter = SelectionHighlighter;
    exports.SelectionHighlighter = SelectionHighlighter = SelectionHighlighter_1 = __decorate([
        __param(1, languageFeatures_1.ILanguageFeaturesService)
    ], SelectionHighlighter);
    function modelRangesContainSameText(model, ranges, matchCase) {
        const selectedText = getValueInRange(model, ranges[0], !matchCase);
        for (let i = 1, len = ranges.length; i < len; i++) {
            const range = ranges[i];
            if (range.isEmpty()) {
                return false;
            }
            const thisSelectedText = getValueInRange(model, range, !matchCase);
            if (selectedText !== thisSelectedText) {
                return false;
            }
        }
        return true;
    }
    function getValueInRange(model, range, toLowerCase) {
        const text = model.getValueInRange(range);
        return (toLowerCase ? text.toLowerCase() : text);
    }
    class FocusNextCursor extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: 'editor.action.focusNextCursor',
                label: nls.localize(1168, "Focus Next Cursor"),
                metadata: {
                    description: nls.localize(1169, "Focuses the next cursor"),
                    args: [],
                },
                alias: 'Focus Next Cursor',
                precondition: undefined
            });
        }
        run(accessor, editor, args) {
            if (!editor.hasModel()) {
                return;
            }
            const viewModel = editor._getViewModel();
            if (viewModel.cursorConfig.readOnly) {
                return;
            }
            viewModel.model.pushStackElement();
            const previousCursorState = Array.from(viewModel.getCursorStates());
            const firstCursor = previousCursorState.shift();
            if (!firstCursor) {
                return;
            }
            previousCursorState.push(firstCursor);
            viewModel.setCursorStates(args.source, 3 /* CursorChangeReason.Explicit */, previousCursorState);
            viewModel.revealPrimaryCursor(args.source, true);
            announceCursorChange(previousCursorState, viewModel.getCursorStates());
        }
    }
    exports.FocusNextCursor = FocusNextCursor;
    class FocusPreviousCursor extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: 'editor.action.focusPreviousCursor',
                label: nls.localize(1170, "Focus Previous Cursor"),
                metadata: {
                    description: nls.localize(1171, "Focuses the previous cursor"),
                    args: [],
                },
                alias: 'Focus Previous Cursor',
                precondition: undefined
            });
        }
        run(accessor, editor, args) {
            if (!editor.hasModel()) {
                return;
            }
            const viewModel = editor._getViewModel();
            if (viewModel.cursorConfig.readOnly) {
                return;
            }
            viewModel.model.pushStackElement();
            const previousCursorState = Array.from(viewModel.getCursorStates());
            const firstCursor = previousCursorState.pop();
            if (!firstCursor) {
                return;
            }
            previousCursorState.unshift(firstCursor);
            viewModel.setCursorStates(args.source, 3 /* CursorChangeReason.Explicit */, previousCursorState);
            viewModel.revealPrimaryCursor(args.source, true);
            announceCursorChange(previousCursorState, viewModel.getCursorStates());
        }
    }
    exports.FocusPreviousCursor = FocusPreviousCursor;
    (0, editorExtensions_1.registerEditorContribution)(MultiCursorSelectionController.ID, MultiCursorSelectionController, 4 /* EditorContributionInstantiation.Lazy */);
    (0, editorExtensions_1.registerEditorContribution)(SelectionHighlighter.ID, SelectionHighlighter, 1 /* EditorContributionInstantiation.AfterFirstRender */);
    (0, editorExtensions_1.registerEditorAction)(InsertCursorAbove);
    (0, editorExtensions_1.registerEditorAction)(InsertCursorBelow);
    (0, editorExtensions_1.registerEditorAction)(InsertCursorAtEndOfEachLineSelected);
    (0, editorExtensions_1.registerEditorAction)(AddSelectionToNextFindMatchAction);
    (0, editorExtensions_1.registerEditorAction)(AddSelectionToPreviousFindMatchAction);
    (0, editorExtensions_1.registerEditorAction)(MoveSelectionToNextFindMatchAction);
    (0, editorExtensions_1.registerEditorAction)(MoveSelectionToPreviousFindMatchAction);
    (0, editorExtensions_1.registerEditorAction)(SelectHighlightsAction);
    (0, editorExtensions_1.registerEditorAction)(CompatChangeAll);
    (0, editorExtensions_1.registerEditorAction)(InsertCursorAtEndOfLineSelected);
    (0, editorExtensions_1.registerEditorAction)(InsertCursorAtTopOfLineSelected);
    (0, editorExtensions_1.registerEditorAction)(FocusNextCursor);
    (0, editorExtensions_1.registerEditorAction)(FocusPreviousCursor);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[841/*vs/editor/contrib/wordHighlighter/browser/wordHighlighter*/], __M([1/*require*/,0/*exports*/,3/*vs/nls*/,46/*vs/base/browser/ui/aria/aria*/,14/*vs/base/common/async*/,18/*vs/base/common/cancellation*/,8/*vs/base/common/errors*/,2/*vs/base/common/lifecycle*/,168/*vs/editor/browser/editorBrowser*/,15/*vs/editor/browser/editorExtensions*/,34/*vs/editor/browser/services/codeEditorService*/,4/*vs/editor/common/core/range*/,20/*vs/editor/common/editorContextKeys*/,40/*vs/editor/common/model*/,17/*vs/editor/common/services/languageFeatures*/,426/*vs/editor/contrib/wordHighlighter/browser/highlightDecorations*/,12/*vs/platform/contextkey/common/contextkey*/,42/*vs/base/common/network*/,45/*vs/base/common/map*/,368/*vs/editor/common/languageSelector*/,48/*vs/base/common/resources*/,680/*vs/editor/contrib/wordHighlighter/browser/textualHighlightProvider*/,130/*vs/editor/common/editorFeatures*/]), function (require, exports, nls, aria_1, async_1, cancellation_1, errors_1, lifecycle_1, editorBrowser_1, editorExtensions_1, codeEditorService_1, range_1, editorContextKeys_1, model_1, languageFeatures_1, highlightDecorations_1, contextkey_1, network_1, map_1, languageSelector_1, resources_1, textualHighlightProvider_1, editorFeatures_1) {
    "use strict";
    var WordHighlighter_1, WordHighlighterContribution_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.WordHighlighterContribution = void 0;
    exports.getOccurrencesAtPosition = getOccurrencesAtPosition;
    exports.getOccurrencesAcrossMultipleModels = getOccurrencesAcrossMultipleModels;
    const ctxHasWordHighlights = new contextkey_1.RawContextKey('hasWordHighlights', false);
    function getOccurrencesAtPosition(registry, model, position, token) {
        const orderedByScore = registry.ordered(model);
        // in order of score ask the occurrences provider
        // until someone response with a good result
        // (good = non undefined and non null value)
        // (result of size == 0 is valid, no highlights is a valid/expected result -- not a signal to fall back to other providers)
        return (0, async_1.first)(orderedByScore.map(provider => () => {
            return Promise.resolve(provider.provideDocumentHighlights(model, position, token))
                .then(undefined, errors_1.onUnexpectedExternalError);
        }), (result) => result !== undefined && result !== null).then(result => {
            if (result) {
                const map = new map_1.ResourceMap();
                map.set(model.uri, result);
                return map;
            }
            return new map_1.ResourceMap();
        });
    }
    function getOccurrencesAcrossMultipleModels(registry, model, position, wordSeparators, token, otherModels) {
        const orderedByScore = registry.ordered(model);
        // in order of score ask the occurrences provider
        // until someone response with a good result
        // (good = non undefined and non null ResourceMap)
        // (result of size == 0 is valid, no highlights is a valid/expected result -- not a signal to fall back to other providers)
        return (0, async_1.first)(orderedByScore.map(provider => () => {
            const filteredModels = otherModels.filter(otherModel => {
                return (0, model_1.shouldSynchronizeModel)(otherModel);
            }).filter(otherModel => {
                return (0, languageSelector_1.score)(provider.selector, otherModel.uri, otherModel.getLanguageId(), true, undefined, undefined) > 0;
            });
            return Promise.resolve(provider.provideMultiDocumentHighlights(model, position, filteredModels, token))
                .then(undefined, errors_1.onUnexpectedExternalError);
        }), (result) => result !== undefined && result !== null);
    }
    class OccurenceAtPositionRequest {
        constructor(_model, _selection, _wordSeparators) {
            this._model = _model;
            this._selection = _selection;
            this._wordSeparators = _wordSeparators;
            this._wordRange = this._getCurrentWordRange(_model, _selection);
            this._result = null;
        }
        get result() {
            if (!this._result) {
                this._result = (0, async_1.createCancelablePromise)(token => this._compute(this._model, this._selection, this._wordSeparators, token));
            }
            return this._result;
        }
        _getCurrentWordRange(model, selection) {
            const word = model.getWordAtPosition(selection.getPosition());
            if (word) {
                return new range_1.Range(selection.startLineNumber, word.startColumn, selection.startLineNumber, word.endColumn);
            }
            return null;
        }
        isValid(model, selection, decorations) {
            const lineNumber = selection.startLineNumber;
            const startColumn = selection.startColumn;
            const endColumn = selection.endColumn;
            const currentWordRange = this._getCurrentWordRange(model, selection);
            let requestIsValid = Boolean(this._wordRange && this._wordRange.equalsRange(currentWordRange));
            // Even if we are on a different word, if that word is in the decorations ranges, the request is still valid
            // (Same symbol)
            for (let i = 0, len = decorations.length; !requestIsValid && i < len; i++) {
                const range = decorations.getRange(i);
                if (range && range.startLineNumber === lineNumber) {
                    if (range.startColumn <= startColumn && range.endColumn >= endColumn) {
                        requestIsValid = true;
                    }
                }
            }
            return requestIsValid;
        }
        cancel() {
            this.result.cancel();
        }
    }
    class SemanticOccurenceAtPositionRequest extends OccurenceAtPositionRequest {
        constructor(model, selection, wordSeparators, providers) {
            super(model, selection, wordSeparators);
            this._providers = providers;
        }
        _compute(model, selection, wordSeparators, token) {
            return getOccurrencesAtPosition(this._providers, model, selection.getPosition(), token).then(value => {
                if (!value) {
                    return new map_1.ResourceMap();
                }
                return value;
            });
        }
    }
    class MultiModelOccurenceRequest extends OccurenceAtPositionRequest {
        constructor(model, selection, wordSeparators, providers, otherModels) {
            super(model, selection, wordSeparators);
            this._providers = providers;
            this._otherModels = otherModels;
        }
        _compute(model, selection, wordSeparators, token) {
            return getOccurrencesAcrossMultipleModels(this._providers, model, selection.getPosition(), wordSeparators, token, this._otherModels).then(value => {
                if (!value) {
                    return new map_1.ResourceMap();
                }
                return value;
            });
        }
    }
    function computeOccurencesAtPosition(registry, model, selection, word, wordSeparators) {
        return new SemanticOccurenceAtPositionRequest(model, selection, wordSeparators, registry);
    }
    function computeOccurencesMultiModel(registry, model, selection, word, wordSeparators, otherModels) {
        return new MultiModelOccurenceRequest(model, selection, wordSeparators, registry, otherModels);
    }
    (0, editorExtensions_1.registerModelAndPositionCommand)('_executeDocumentHighlights', async (accessor, model, position) => {
        const languageFeaturesService = accessor.get(languageFeatures_1.ILanguageFeaturesService);
        const map = await getOccurrencesAtPosition(languageFeaturesService.documentHighlightProvider, model, position, cancellation_1.CancellationToken.None);
        return map?.get(model.uri);
    });
    let WordHighlighter = class WordHighlighter {
        static { WordHighlighter_1 = this; }
        static { this.storedDecorationIDs = new map_1.ResourceMap(); }
        static { this.query = null; }
        constructor(editor, providers, multiProviders, contextKeyService, codeEditorService) {
            this.toUnhook = new lifecycle_1.DisposableStore();
            this.workerRequestTokenId = 0;
            this.workerRequestCompleted = false;
            this.workerRequestValue = new map_1.ResourceMap();
            this.lastCursorPositionChangeTime = 0;
            this.renderDecorationsTimer = -1;
            this.runDelayer = this.toUnhook.add(new async_1.Delayer(50));
            this.editor = editor;
            this.providers = providers;
            this.multiDocumentProviders = multiProviders;
            this.codeEditorService = codeEditorService;
            this._hasWordHighlights = ctxHasWordHighlights.bindTo(contextKeyService);
            this._ignorePositionChangeEvent = false;
            this.occurrencesHighlight = this.editor.getOption(81 /* EditorOption.occurrencesHighlight */);
            this.model = this.editor.getModel();
            this.toUnhook.add(editor.onDidChangeCursorPosition((e) => {
                if (this._ignorePositionChangeEvent) {
                    // We are changing the position => ignore this event
                    return;
                }
                if (this.occurrencesHighlight === 'off') {
                    // Early exit if nothing needs to be done!
                    // Leave some form of early exit check here if you wish to continue being a cursor position change listener ;)
                    return;
                }
                this.runDelayer.trigger(() => { this._onPositionChanged(e); });
            }));
            this.toUnhook.add(editor.onDidFocusEditorText((e) => {
                if (this.occurrencesHighlight === 'off') {
                    // Early exit if nothing needs to be done
                    return;
                }
                if (!this.workerRequest) {
                    this.runDelayer.trigger(() => { this._run(); });
                }
            }));
            this.toUnhook.add(editor.onDidChangeModelContent((e) => {
                if (!(0, network_1.matchesScheme)(this.model.uri, 'output')) {
                    this._stopAll();
                }
            }));
            this.toUnhook.add(editor.onDidChangeModel((e) => {
                if (!e.newModelUrl && e.oldModelUrl) {
                    this._stopSingular();
                }
                else {
                    if (WordHighlighter_1.query) {
                        this._run();
                    }
                }
            }));
            this.toUnhook.add(editor.onDidChangeConfiguration((e) => {
                const newValue = this.editor.getOption(81 /* EditorOption.occurrencesHighlight */);
                if (this.occurrencesHighlight !== newValue) {
                    this.occurrencesHighlight = newValue;
                    switch (newValue) {
                        case 'off':
                            this._stopAll();
                            break;
                        case 'singleFile':
                            this._stopAll(WordHighlighter_1.query?.modelInfo?.model);
                            break;
                        case 'multiFile':
                            if (WordHighlighter_1.query) {
                                this._run(true);
                            }
                            break;
                        default:
                            console.warn('Unknown occurrencesHighlight setting value:', newValue);
                            break;
                    }
                }
            }));
            this.decorations = this.editor.createDecorationsCollection();
            this.workerRequestTokenId = 0;
            this.workerRequest = null;
            this.workerRequestCompleted = false;
            this.lastCursorPositionChangeTime = 0;
            this.renderDecorationsTimer = -1;
            // if there is a query already, highlight off that query
            if (WordHighlighter_1.query) {
                this._run();
            }
        }
        hasDecorations() {
            return (this.decorations.length > 0);
        }
        restore() {
            if (this.occurrencesHighlight === 'off') {
                return;
            }
            this.runDelayer.cancel();
            this._run();
        }
        _getSortedHighlights() {
            return (this.decorations.getRanges()
                .sort(range_1.Range.compareRangesUsingStarts));
        }
        moveNext() {
            const highlights = this._getSortedHighlights();
            const index = highlights.findIndex((range) => range.containsPosition(this.editor.getPosition()));
            const newIndex = ((index + 1) % highlights.length);
            const dest = highlights[newIndex];
            try {
                this._ignorePositionChangeEvent = true;
                this.editor.setPosition(dest.getStartPosition());
                this.editor.revealRangeInCenterIfOutsideViewport(dest);
                const word = this._getWord();
                if (word) {
                    const lineContent = this.editor.getModel().getLineContent(dest.startLineNumber);
                    (0, aria_1.alert)(`${lineContent}, ${newIndex + 1} of ${highlights.length} for '${word.word}'`);
                }
            }
            finally {
                this._ignorePositionChangeEvent = false;
            }
        }
        moveBack() {
            const highlights = this._getSortedHighlights();
            const index = highlights.findIndex((range) => range.containsPosition(this.editor.getPosition()));
            const newIndex = ((index - 1 + highlights.length) % highlights.length);
            const dest = highlights[newIndex];
            try {
                this._ignorePositionChangeEvent = true;
                this.editor.setPosition(dest.getStartPosition());
                this.editor.revealRangeInCenterIfOutsideViewport(dest);
                const word = this._getWord();
                if (word) {
                    const lineContent = this.editor.getModel().getLineContent(dest.startLineNumber);
                    (0, aria_1.alert)(`${lineContent}, ${newIndex + 1} of ${highlights.length} for '${word.word}'`);
                }
            }
            finally {
                this._ignorePositionChangeEvent = false;
            }
        }
        _removeSingleDecorations() {
            // return if no model
            if (!this.editor.hasModel()) {
                return;
            }
            const currentDecorationIDs = WordHighlighter_1.storedDecorationIDs.get(this.editor.getModel().uri);
            if (!currentDecorationIDs) {
                return;
            }
            this.editor.removeDecorations(currentDecorationIDs);
            WordHighlighter_1.storedDecorationIDs.delete(this.editor.getModel().uri);
            if (this.decorations.length > 0) {
                this.decorations.clear();
                this._hasWordHighlights.set(false);
            }
        }
        _removeAllDecorations(preservedModel) {
            const currentEditors = this.codeEditorService.listCodeEditors();
            const deleteURI = [];
            // iterate over editors and store models in currentModels
            for (const editor of currentEditors) {
                if (!editor.hasModel() || (0, resources_1.isEqual)(editor.getModel().uri, preservedModel?.uri)) {
                    continue;
                }
                const currentDecorationIDs = WordHighlighter_1.storedDecorationIDs.get(editor.getModel().uri);
                if (!currentDecorationIDs) {
                    continue;
                }
                editor.removeDecorations(currentDecorationIDs);
                deleteURI.push(editor.getModel().uri);
                const editorHighlighterContrib = WordHighlighterContribution.get(editor);
                if (!editorHighlighterContrib?.wordHighlighter) {
                    continue;
                }
                if (editorHighlighterContrib.wordHighlighter.decorations.length > 0) {
                    editorHighlighterContrib.wordHighlighter.decorations.clear();
                    editorHighlighterContrib.wordHighlighter.workerRequest = null;
                    editorHighlighterContrib.wordHighlighter._hasWordHighlights.set(false);
                }
            }
            for (const uri of deleteURI) {
                WordHighlighter_1.storedDecorationIDs.delete(uri);
            }
        }
        _stopSingular() {
            // Remove any existing decorations + a possible query, and re - run to update decorations
            this._removeSingleDecorations();
            if (this.editor.hasTextFocus()) {
                if (this.editor.getModel()?.uri.scheme !== network_1.Schemas.vscodeNotebookCell && WordHighlighter_1.query?.modelInfo?.model.uri.scheme !== network_1.Schemas.vscodeNotebookCell) { // clear query if focused non-nb editor
                    WordHighlighter_1.query = null;
                    this._run(); // TODO: @Yoyokrazy -- investigate why we need a full rerun here. likely addressed a case/patch in the first iteration of this feature
                }
                else { // remove modelInfo to account for nb cell being disposed
                    if (WordHighlighter_1.query?.modelInfo) {
                        WordHighlighter_1.query.modelInfo = null;
                    }
                }
            }
            // Cancel any renderDecorationsTimer
            if (this.renderDecorationsTimer !== -1) {
                clearTimeout(this.renderDecorationsTimer);
                this.renderDecorationsTimer = -1;
            }
            // Cancel any worker request
            if (this.workerRequest !== null) {
                this.workerRequest.cancel();
                this.workerRequest = null;
            }
            // Invalidate any worker request callback
            if (!this.workerRequestCompleted) {
                this.workerRequestTokenId++;
                this.workerRequestCompleted = true;
            }
        }
        _stopAll(preservedModel) {
            // Remove any existing decorations
            // TODO: @Yoyokrazy -- this triggers as notebooks scroll, causing highlights to disappear momentarily.
            // maybe a nb type check?
            this._removeAllDecorations(preservedModel);
            // Cancel any renderDecorationsTimer
            if (this.renderDecorationsTimer !== -1) {
                clearTimeout(this.renderDecorationsTimer);
                this.renderDecorationsTimer = -1;
            }
            // Cancel any worker request
            if (this.workerRequest !== null) {
                this.workerRequest.cancel();
                this.workerRequest = null;
            }
            // Invalidate any worker request callback
            if (!this.workerRequestCompleted) {
                this.workerRequestTokenId++;
                this.workerRequestCompleted = true;
            }
        }
        _onPositionChanged(e) {
            // disabled
            if (this.occurrencesHighlight === 'off') {
                this._stopAll();
                return;
            }
            // ignore typing & other
            // need to check if the model is a notebook cell, should not stop if nb
            if (e.reason !== 3 /* CursorChangeReason.Explicit */ && this.editor.getModel()?.uri.scheme !== network_1.Schemas.vscodeNotebookCell) {
                this._stopAll();
                return;
            }
            this._run();
        }
        _getWord() {
            const editorSelection = this.editor.getSelection();
            const lineNumber = editorSelection.startLineNumber;
            const startColumn = editorSelection.startColumn;
            if (this.model.isDisposed()) {
                return null;
            }
            return this.model.getWordAtPosition({
                lineNumber: lineNumber,
                column: startColumn
            });
        }
        getOtherModelsToHighlight(model) {
            if (!model) {
                return [];
            }
            // notebook case
            const isNotebookEditor = model.uri.scheme === network_1.Schemas.vscodeNotebookCell;
            if (isNotebookEditor) {
                const currentModels = [];
                const currentEditors = this.codeEditorService.listCodeEditors();
                for (const editor of currentEditors) {
                    const tempModel = editor.getModel();
                    if (tempModel && tempModel !== model && tempModel.uri.scheme === network_1.Schemas.vscodeNotebookCell) {
                        currentModels.push(tempModel);
                    }
                }
                return currentModels;
            }
            // inline case
            // ? current works when highlighting outside of an inline diff, highlighting in.
            // ? broken when highlighting within a diff editor. highlighting the main editor does not work
            // ? editor group service could be useful here
            const currentModels = [];
            const currentEditors = this.codeEditorService.listCodeEditors();
            for (const editor of currentEditors) {
                if (!(0, editorBrowser_1.isDiffEditor)(editor)) {
                    continue;
                }
                const diffModel = editor.getModel();
                if (!diffModel) {
                    continue;
                }
                if (model === diffModel.modified) { // embedded inline chat diff would pass this, allowing highlights
                    //? currentModels.push(diffModel.original);
                    currentModels.push(diffModel.modified);
                }
            }
            if (currentModels.length) { // no matching editors have been found
                return currentModels;
            }
            // multi-doc OFF
            if (this.occurrencesHighlight === 'singleFile') {
                return [];
            }
            // multi-doc ON
            for (const editor of currentEditors) {
                const tempModel = editor.getModel();
                const isValidModel = tempModel && tempModel !== model;
                if (isValidModel) {
                    currentModels.push(tempModel);
                }
            }
            return currentModels;
        }
        _run(multiFileConfigChange) {
            let workerRequestIsValid;
            const hasTextFocus = this.editor.hasTextFocus();
            if (!hasTextFocus) { // new nb cell scrolled in, didChangeModel fires
                if (!WordHighlighter_1.query) { // no previous query, nothing to highlight off of
                    this._stopAll();
                    return;
                }
            }
            else { // has text focus
                const editorSelection = this.editor.getSelection();
                // ignore multiline selection
                if (!editorSelection || editorSelection.startLineNumber !== editorSelection.endLineNumber) {
                    WordHighlighter_1.query = null;
                    this._stopAll();
                    return;
                }
                const startColumn = editorSelection.startColumn;
                const endColumn = editorSelection.endColumn;
                const word = this._getWord();
                // The selection must be inside a word or surround one word at most
                if (!word || word.startColumn > startColumn || word.endColumn < endColumn) {
                    // no previous query, nothing to highlight
                    WordHighlighter_1.query = null;
                    this._stopAll();
                    return;
                }
                // All the effort below is trying to achieve this:
                // - when cursor is moved to a word, trigger immediately a findOccurrences request
                // - 250ms later after the last cursor move event, render the occurrences
                // - no flickering!
                workerRequestIsValid = (this.workerRequest && this.workerRequest.isValid(this.model, editorSelection, this.decorations));
                WordHighlighter_1.query = {
                    modelInfo: {
                        model: this.model,
                        selection: editorSelection,
                    },
                    word: word
                };
            }
            // There are 4 cases:
            // a) old workerRequest is valid & completed, renderDecorationsTimer fired
            // b) old workerRequest is valid & completed, renderDecorationsTimer not fired
            // c) old workerRequest is valid, but not completed
            // d) old workerRequest is not valid
            // For a) no action is needed
            // For c), member 'lastCursorPositionChangeTime' will be used when installing the timer so no action is needed
            this.lastCursorPositionChangeTime = (new Date()).getTime();
            if (workerRequestIsValid) {
                if (this.workerRequestCompleted && this.renderDecorationsTimer !== -1) {
                    // case b)
                    // Delay the firing of renderDecorationsTimer by an extra 250 ms
                    clearTimeout(this.renderDecorationsTimer);
                    this.renderDecorationsTimer = -1;
                    this._beginRenderDecorations();
                }
            }
            else if ((0, resources_1.isEqual)(this.editor.getModel().uri, WordHighlighter_1.query.modelInfo?.model.uri)) { // only trigger new worker requests from the primary model that initiated the query
                // case d)
                // check if the new queried word is contained in the range of a stored decoration for this model
                if (!multiFileConfigChange) {
                    const currentModelDecorationRanges = this.decorations.getRanges();
                    for (const storedRange of currentModelDecorationRanges) {
                        if (storedRange.containsPosition(this.editor.getPosition())) {
                            return;
                        }
                    }
                }
                // stop all previous actions if new word is highlighted
                // if we trigger the run off a setting change -> multifile highlighting, we do not want to remove decorations from this model
                this._stopAll(multiFileConfigChange ? this.model : undefined);
                const myRequestId = ++this.workerRequestTokenId;
                this.workerRequestCompleted = false;
                const otherModelsToHighlight = this.getOtherModelsToHighlight(this.editor.getModel());
                // when reaching here, there are two possible states.
                // 		1) we have text focus, and a valid query was updated.
                // 		2) we do not have text focus, and a valid query is cached.
                // the query will ALWAYS have the correct data for the current highlight request, so it can always be passed to the workerRequest safely
                if (!WordHighlighter_1.query || !WordHighlighter_1.query.modelInfo || WordHighlighter_1.query.modelInfo.model.isDisposed()) {
                    return;
                }
                this.workerRequest = this.computeWithModel(WordHighlighter_1.query.modelInfo.model, WordHighlighter_1.query.modelInfo.selection, WordHighlighter_1.query.word, otherModelsToHighlight);
                this.workerRequest?.result.then(data => {
                    if (myRequestId === this.workerRequestTokenId) {
                        this.workerRequestCompleted = true;
                        this.workerRequestValue = data || [];
                        this._beginRenderDecorations();
                    }
                }, errors_1.onUnexpectedError);
            }
        }
        computeWithModel(model, selection, word, otherModels) {
            if (!otherModels.length) {
                return computeOccurencesAtPosition(this.providers, model, selection, word, this.editor.getOption(132 /* EditorOption.wordSeparators */));
            }
            else {
                return computeOccurencesMultiModel(this.multiDocumentProviders, model, selection, word, this.editor.getOption(132 /* EditorOption.wordSeparators */), otherModels);
            }
        }
        _beginRenderDecorations() {
            const currentTime = (new Date()).getTime();
            const minimumRenderTime = this.lastCursorPositionChangeTime + 250;
            if (currentTime >= minimumRenderTime) {
                // Synchronous
                this.renderDecorationsTimer = -1;
                this.renderDecorations();
            }
            else {
                // Asynchronous
                this.renderDecorationsTimer = setTimeout(() => {
                    this.renderDecorations();
                }, (minimumRenderTime - currentTime));
            }
        }
        renderDecorations() {
            this.renderDecorationsTimer = -1;
            // create new loop, iterate over current editors using this.codeEditorService.listCodeEditors(),
            // if the URI of that codeEditor is in the map, then add the decorations to the decorations array
            // then set the decorations for the editor
            const currentEditors = this.codeEditorService.listCodeEditors();
            for (const editor of currentEditors) {
                const editorHighlighterContrib = WordHighlighterContribution.get(editor);
                if (!editorHighlighterContrib) {
                    continue;
                }
                const newDecorations = [];
                const uri = editor.getModel()?.uri;
                if (uri && this.workerRequestValue.has(uri)) {
                    const oldDecorationIDs = WordHighlighter_1.storedDecorationIDs.get(uri);
                    const newDocumentHighlights = this.workerRequestValue.get(uri);
                    if (newDocumentHighlights) {
                        for (const highlight of newDocumentHighlights) {
                            if (!highlight.range) {
                                continue;
                            }
                            newDecorations.push({
                                range: highlight.range,
                                options: (0, highlightDecorations_1.getHighlightDecorationOptions)(highlight.kind)
                            });
                        }
                    }
                    let newDecorationIDs = [];
                    editor.changeDecorations((changeAccessor) => {
                        newDecorationIDs = changeAccessor.deltaDecorations(oldDecorationIDs ?? [], newDecorations);
                    });
                    WordHighlighter_1.storedDecorationIDs = WordHighlighter_1.storedDecorationIDs.set(uri, newDecorationIDs);
                    if (newDecorations.length > 0) {
                        editorHighlighterContrib.wordHighlighter?.decorations.set(newDecorations);
                        editorHighlighterContrib.wordHighlighter?._hasWordHighlights.set(true);
                    }
                }
            }
        }
        dispose() {
            this._stopSingular();
            this.toUnhook.dispose();
        }
    };
    WordHighlighter = WordHighlighter_1 = __decorate([
        __param(4, codeEditorService_1.ICodeEditorService)
    ], WordHighlighter);
    let WordHighlighterContribution = class WordHighlighterContribution extends lifecycle_1.Disposable {
        static { WordHighlighterContribution_1 = this; }
        static { this.ID = 'editor.contrib.wordHighlighter'; }
        static get(editor) {
            return editor.getContribution(WordHighlighterContribution_1.ID);
        }
        constructor(editor, contextKeyService, languageFeaturesService, codeEditorService) {
            super();
            this._wordHighlighter = null;
            const createWordHighlighterIfPossible = () => {
                if (editor.hasModel() && !editor.getModel().isTooLargeForTokenization()) {
                    this._wordHighlighter = new WordHighlighter(editor, languageFeaturesService.documentHighlightProvider, languageFeaturesService.multiDocumentHighlightProvider, contextKeyService, codeEditorService);
                }
            };
            this._register(editor.onDidChangeModel((e) => {
                if (this._wordHighlighter) {
                    this._wordHighlighter.dispose();
                    this._wordHighlighter = null;
                }
                createWordHighlighterIfPossible();
            }));
            createWordHighlighterIfPossible();
        }
        get wordHighlighter() {
            return this._wordHighlighter;
        }
        saveViewState() {
            if (this._wordHighlighter && this._wordHighlighter.hasDecorations()) {
                return true;
            }
            return false;
        }
        moveNext() {
            this._wordHighlighter?.moveNext();
        }
        moveBack() {
            this._wordHighlighter?.moveBack();
        }
        restoreViewState(state) {
            if (this._wordHighlighter && state) {
                this._wordHighlighter.restore();
            }
        }
        dispose() {
            if (this._wordHighlighter) {
                this._wordHighlighter.dispose();
                this._wordHighlighter = null;
            }
            super.dispose();
        }
    };
    exports.WordHighlighterContribution = WordHighlighterContribution;
    exports.WordHighlighterContribution = WordHighlighterContribution = WordHighlighterContribution_1 = __decorate([
        __param(1, contextkey_1.IContextKeyService),
        __param(2, languageFeatures_1.ILanguageFeaturesService),
        __param(3, codeEditorService_1.ICodeEditorService)
    ], WordHighlighterContribution);
    class WordHighlightNavigationAction extends editorExtensions_1.EditorAction {
        constructor(next, opts) {
            super(opts);
            this._isNext = next;
        }
        run(accessor, editor) {
            const controller = WordHighlighterContribution.get(editor);
            if (!controller) {
                return;
            }
            if (this._isNext) {
                controller.moveNext();
            }
            else {
                controller.moveBack();
            }
        }
    }
    class NextWordHighlightAction extends WordHighlightNavigationAction {
        constructor() {
            super(true, {
                id: 'editor.action.wordHighlight.next',
                label: nls.localize(1424, "Go to Next Symbol Highlight"),
                alias: 'Go to Next Symbol Highlight',
                precondition: ctxHasWordHighlights,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    primary: 65 /* KeyCode.F7 */,
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
    }
    class PrevWordHighlightAction extends WordHighlightNavigationAction {
        constructor() {
            super(false, {
                id: 'editor.action.wordHighlight.prev',
                label: nls.localize(1425, "Go to Previous Symbol Highlight"),
                alias: 'Go to Previous Symbol Highlight',
                precondition: ctxHasWordHighlights,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    primary: 1024 /* KeyMod.Shift */ | 65 /* KeyCode.F7 */,
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
    }
    class TriggerWordHighlightAction extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: 'editor.action.wordHighlight.trigger',
                label: nls.localize(1426, "Trigger Symbol Highlight"),
                alias: 'Trigger Symbol Highlight',
                precondition: undefined,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    primary: 0,
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
        run(accessor, editor, args) {
            const controller = WordHighlighterContribution.get(editor);
            if (!controller) {
                return;
            }
            controller.restoreViewState(true);
        }
    }
    (0, editorExtensions_1.registerEditorContribution)(WordHighlighterContribution.ID, WordHighlighterContribution, 0 /* EditorContributionInstantiation.Eager */); // eager because it uses `saveViewState`/`restoreViewState`
    (0, editorExtensions_1.registerEditorAction)(NextWordHighlightAction);
    (0, editorExtensions_1.registerEditorAction)(PrevWordHighlightAction);
    (0, editorExtensions_1.registerEditorAction)(TriggerWordHighlightAction);
    (0, editorFeatures_1.registerEditorFeature)(textualHighlightProvider_1.TextualMultiDocumentHighlightFeature);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[842/*vs/editor/contrib/zoneWidget/browser/zoneWidget*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,173/*vs/base/browser/ui/sash/sash*/,33/*vs/base/common/color*/,187/*vs/base/common/idGenerator*/,2/*vs/base/common/lifecycle*/,60/*vs/base/common/objects*/,4/*vs/editor/common/core/range*/,35/*vs/editor/common/model/textModel*/,537/*vs/css!vs/editor/contrib/zoneWidget/browser/zoneWidget*/]), function (require, exports, dom, sash_1, color_1, idGenerator_1, lifecycle_1, objects, range_1, textModel_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ZoneWidget = exports.OverlayWidgetDelegate = void 0;
    const defaultColor = new color_1.Color(new color_1.RGBA(0, 122, 204));
    const defaultOptions = {
        showArrow: true,
        showFrame: true,
        className: '',
        frameColor: defaultColor,
        arrowColor: defaultColor,
        keepEditorSelection: false
    };
    const WIDGET_ID = 'vs.editor.contrib.zoneWidget';
    class ViewZoneDelegate {
        constructor(domNode, afterLineNumber, afterColumn, heightInLines, onDomNodeTop, onComputedHeight, showInHiddenAreas, ordinal) {
            this.id = ''; // A valid zone id should be greater than 0
            this.domNode = domNode;
            this.afterLineNumber = afterLineNumber;
            this.afterColumn = afterColumn;
            this.heightInLines = heightInLines;
            this.showInHiddenAreas = showInHiddenAreas;
            this.ordinal = ordinal;
            this._onDomNodeTop = onDomNodeTop;
            this._onComputedHeight = onComputedHeight;
        }
        onDomNodeTop(top) {
            this._onDomNodeTop(top);
        }
        onComputedHeight(height) {
            this._onComputedHeight(height);
        }
    }
    class OverlayWidgetDelegate {
        constructor(id, domNode) {
            this._id = id;
            this._domNode = domNode;
        }
        getId() {
            return this._id;
        }
        getDomNode() {
            return this._domNode;
        }
        getPosition() {
            return null;
        }
    }
    exports.OverlayWidgetDelegate = OverlayWidgetDelegate;
    class Arrow {
        static { this._IdGenerator = new idGenerator_1.IdGenerator('.arrow-decoration-'); }
        constructor(_editor) {
            this._editor = _editor;
            this._ruleName = Arrow._IdGenerator.nextId();
            this._decorations = this._editor.createDecorationsCollection();
            this._color = null;
            this._height = -1;
        }
        dispose() {
            this.hide();
            dom.removeCSSRulesContainingSelector(this._ruleName);
        }
        set color(value) {
            if (this._color !== value) {
                this._color = value;
                this._updateStyle();
            }
        }
        set height(value) {
            if (this._height !== value) {
                this._height = value;
                this._updateStyle();
            }
        }
        _updateStyle() {
            dom.removeCSSRulesContainingSelector(this._ruleName);
            dom.createCSSRule(`.monaco-editor ${this._ruleName}`, `border-style: solid; border-color: transparent; border-bottom-color: ${this._color}; border-width: ${this._height}px; bottom: -${this._height}px !important; margin-left: -${this._height}px; `);
        }
        show(where) {
            if (where.column === 1) {
                // the arrow isn't pretty at column 1 and we need to push it out a little
                where = { lineNumber: where.lineNumber, column: 2 };
            }
            this._decorations.set([{
                    range: range_1.Range.fromPositions(where),
                    options: {
                        description: 'zone-widget-arrow',
                        className: this._ruleName,
                        stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */
                    }
                }]);
        }
        hide() {
            this._decorations.clear();
        }
    }
    class ZoneWidget {
        constructor(editor, options = {}) {
            this._arrow = null;
            this._overlayWidget = null;
            this._resizeSash = null;
            this._viewZone = null;
            this._disposables = new lifecycle_1.DisposableStore();
            this.container = null;
            this._isShowing = false;
            this.editor = editor;
            this._positionMarkerId = this.editor.createDecorationsCollection();
            this.options = objects.deepClone(options);
            objects.mixin(this.options, defaultOptions, false);
            this.domNode = document.createElement('div');
            if (!this.options.isAccessible) {
                this.domNode.setAttribute('aria-hidden', 'true');
                this.domNode.setAttribute('role', 'presentation');
            }
            this._disposables.add(this.editor.onDidLayoutChange((info) => {
                const width = this._getWidth(info);
                this.domNode.style.width = width + 'px';
                this.domNode.style.left = this._getLeft(info) + 'px';
                this._onWidth(width);
            }));
        }
        dispose() {
            if (this._overlayWidget) {
                this.editor.removeOverlayWidget(this._overlayWidget);
                this._overlayWidget = null;
            }
            if (this._viewZone) {
                this.editor.changeViewZones(accessor => {
                    if (this._viewZone) {
                        accessor.removeZone(this._viewZone.id);
                    }
                    this._viewZone = null;
                });
            }
            this._positionMarkerId.clear();
            this._disposables.dispose();
        }
        create() {
            this.domNode.classList.add('zone-widget');
            if (this.options.className) {
                this.domNode.classList.add(this.options.className);
            }
            this.container = document.createElement('div');
            this.container.classList.add('zone-widget-container');
            this.domNode.appendChild(this.container);
            if (this.options.showArrow) {
                this._arrow = new Arrow(this.editor);
                this._disposables.add(this._arrow);
            }
            this._fillContainer(this.container);
            this._initSash();
            this._applyStyles();
        }
        style(styles) {
            if (styles.frameColor) {
                this.options.frameColor = styles.frameColor;
            }
            if (styles.arrowColor) {
                this.options.arrowColor = styles.arrowColor;
            }
            this._applyStyles();
        }
        _applyStyles() {
            if (this.container && this.options.frameColor) {
                const frameColor = this.options.frameColor.toString();
                this.container.style.borderTopColor = frameColor;
                this.container.style.borderBottomColor = frameColor;
            }
            if (this._arrow && this.options.arrowColor) {
                const arrowColor = this.options.arrowColor.toString();
                this._arrow.color = arrowColor;
            }
        }
        _getWidth(info) {
            return info.width - info.minimap.minimapWidth - info.verticalScrollbarWidth;
        }
        _getLeft(info) {
            // If minimap is to the left, we move beyond it
            if (info.minimap.minimapWidth > 0 && info.minimap.minimapLeft === 0) {
                return info.minimap.minimapWidth;
            }
            return 0;
        }
        _onViewZoneTop(top) {
            this.domNode.style.top = top + 'px';
        }
        _onViewZoneHeight(height) {
            this.domNode.style.height = `${height}px`;
            if (this.container) {
                const containerHeight = height - this._decoratingElementsHeight();
                this.container.style.height = `${containerHeight}px`;
                const layoutInfo = this.editor.getLayoutInfo();
                this._doLayout(containerHeight, this._getWidth(layoutInfo));
            }
            this._resizeSash?.layout();
        }
        get position() {
            const range = this._positionMarkerId.getRange(0);
            if (!range) {
                return undefined;
            }
            return range.getStartPosition();
        }
        show(rangeOrPos, heightInLines) {
            const range = range_1.Range.isIRange(rangeOrPos) ? range_1.Range.lift(rangeOrPos) : range_1.Range.fromPositions(rangeOrPos);
            this._isShowing = true;
            this._showImpl(range, heightInLines);
            this._isShowing = false;
            this._positionMarkerId.set([{ range, options: textModel_1.ModelDecorationOptions.EMPTY }]);
        }
        hide() {
            if (this._viewZone) {
                this.editor.changeViewZones(accessor => {
                    if (this._viewZone) {
                        accessor.removeZone(this._viewZone.id);
                    }
                });
                this._viewZone = null;
            }
            if (this._overlayWidget) {
                this.editor.removeOverlayWidget(this._overlayWidget);
                this._overlayWidget = null;
            }
            this._arrow?.hide();
            this._positionMarkerId.clear();
        }
        _decoratingElementsHeight() {
            const lineHeight = this.editor.getOption(67 /* EditorOption.lineHeight */);
            let result = 0;
            if (this.options.showArrow) {
                const arrowHeight = Math.round(lineHeight / 3);
                result += 2 * arrowHeight;
            }
            if (this.options.showFrame) {
                const frameThickness = Math.round(lineHeight / 9);
                result += 2 * frameThickness;
            }
            return result;
        }
        _showImpl(where, heightInLines) {
            const position = where.getStartPosition();
            const layoutInfo = this.editor.getLayoutInfo();
            const width = this._getWidth(layoutInfo);
            this.domNode.style.width = `${width}px`;
            this.domNode.style.left = this._getLeft(layoutInfo) + 'px';
            // Render the widget as zone (rendering) and widget (lifecycle)
            const viewZoneDomNode = document.createElement('div');
            viewZoneDomNode.style.overflow = 'hidden';
            const lineHeight = this.editor.getOption(67 /* EditorOption.lineHeight */);
            // adjust heightInLines to viewport
            if (!this.options.allowUnlimitedHeight) {
                const maxHeightInLines = Math.max(12, (this.editor.getLayoutInfo().height / lineHeight) * 0.8);
                heightInLines = Math.min(heightInLines, maxHeightInLines);
            }
            let arrowHeight = 0;
            let frameThickness = 0;
            // Render the arrow one 1/3 of an editor line height
            if (this._arrow && this.options.showArrow) {
                arrowHeight = Math.round(lineHeight / 3);
                this._arrow.height = arrowHeight;
                this._arrow.show(position);
            }
            // Render the frame as 1/9 of an editor line height
            if (this.options.showFrame) {
                frameThickness = Math.round(lineHeight / 9);
            }
            // insert zone widget
            this.editor.changeViewZones((accessor) => {
                if (this._viewZone) {
                    accessor.removeZone(this._viewZone.id);
                }
                if (this._overlayWidget) {
                    this.editor.removeOverlayWidget(this._overlayWidget);
                    this._overlayWidget = null;
                }
                this.domNode.style.top = '-1000px';
                this._viewZone = new ViewZoneDelegate(viewZoneDomNode, position.lineNumber, position.column, heightInLines, (top) => this._onViewZoneTop(top), (height) => this._onViewZoneHeight(height), this.options.showInHiddenAreas, this.options.ordinal);
                this._viewZone.id = accessor.addZone(this._viewZone);
                this._overlayWidget = new OverlayWidgetDelegate(WIDGET_ID + this._viewZone.id, this.domNode);
                this.editor.addOverlayWidget(this._overlayWidget);
            });
            if (this.container && this.options.showFrame) {
                const width = this.options.frameWidth ? this.options.frameWidth : frameThickness;
                this.container.style.borderTopWidth = width + 'px';
                this.container.style.borderBottomWidth = width + 'px';
            }
            const containerHeight = heightInLines * lineHeight - this._decoratingElementsHeight();
            if (this.container) {
                this.container.style.top = arrowHeight + 'px';
                this.container.style.height = containerHeight + 'px';
                this.container.style.overflow = 'hidden';
            }
            this._doLayout(containerHeight, width);
            if (!this.options.keepEditorSelection) {
                this.editor.setSelection(where);
            }
            const model = this.editor.getModel();
            if (model) {
                const range = model.validateRange(new range_1.Range(where.startLineNumber, 1, where.endLineNumber + 1, 1));
                this.revealRange(range, range.startLineNumber === model.getLineCount());
            }
        }
        revealRange(range, isLastLine) {
            if (isLastLine) {
                this.editor.revealLineNearTop(range.endLineNumber, 0 /* ScrollType.Smooth */);
            }
            else {
                this.editor.revealRange(range, 0 /* ScrollType.Smooth */);
            }
        }
        setCssClass(className, classToReplace) {
            if (!this.container) {
                return;
            }
            if (classToReplace) {
                this.container.classList.remove(classToReplace);
            }
            this.container.classList.add(className);
        }
        _onWidth(widthInPixel) {
            // implement in subclass
        }
        _doLayout(heightInPixel, widthInPixel) {
            // implement in subclass
        }
        _relayout(newHeightInLines) {
            if (this._viewZone && this._viewZone.heightInLines !== newHeightInLines) {
                this.editor.changeViewZones(accessor => {
                    if (this._viewZone) {
                        this._viewZone.heightInLines = newHeightInLines;
                        accessor.layoutZone(this._viewZone.id);
                    }
                });
            }
        }
        // --- sash
        _initSash() {
            if (this._resizeSash) {
                return;
            }
            this._resizeSash = this._disposables.add(new sash_1.Sash(this.domNode, this, { orientation: 1 /* Orientation.HORIZONTAL */ }));
            if (!this.options.isResizeable) {
                this._resizeSash.state = 0 /* SashState.Disabled */;
            }
            let data;
            this._disposables.add(this._resizeSash.onDidStart((e) => {
                if (this._viewZone) {
                    data = {
                        startY: e.startY,
                        heightInLines: this._viewZone.heightInLines,
                    };
                }
            }));
            this._disposables.add(this._resizeSash.onDidEnd(() => {
                data = undefined;
            }));
            this._disposables.add(this._resizeSash.onDidChange((evt) => {
                if (data) {
                    const lineDelta = (evt.currentY - data.startY) / this.editor.getOption(67 /* EditorOption.lineHeight */);
                    const roundedLineDelta = lineDelta < 0 ? Math.ceil(lineDelta) : Math.floor(lineDelta);
                    const newHeightInLines = data.heightInLines + roundedLineDelta;
                    if (newHeightInLines > 5 && newHeightInLines < 35) {
                        this._relayout(newHeightInLines);
                    }
                }
            }));
        }
        getHorizontalSashLeft() {
            return 0;
        }
        getHorizontalSashTop() {
            return (this.domNode.style.height === null ? 0 : parseInt(this.domNode.style.height)) - (this._decoratingElementsHeight() / 2);
        }
        getHorizontalSashWidth() {
            const layoutInfo = this.editor.getLayoutInfo();
            return layoutInfo.width - layoutInfo.minimap.minimapWidth;
        }
    }
    exports.ZoneWidget = ZoneWidget;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[158/*vs/editor/contrib/peekView/browser/peekView*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,87/*vs/base/browser/ui/actionbar/actionbar*/,41/*vs/base/common/actions*/,26/*vs/base/common/codicons*/,30/*vs/base/common/themables*/,33/*vs/base/common/color*/,6/*vs/base/common/event*/,60/*vs/base/common/objects*/,15/*vs/editor/browser/editorExtensions*/,34/*vs/editor/browser/services/codeEditorService*/,125/*vs/editor/browser/widget/codeEditor/embeddedCodeEditorWidget*/,842/*vs/editor/contrib/zoneWidget/browser/zoneWidget*/,3/*vs/nls*/,124/*vs/platform/actions/browser/menuEntryActionViewItem*/,12/*vs/platform/contextkey/common/contextkey*/,49/*vs/platform/instantiation/common/extensions*/,7/*vs/platform/instantiation/common/instantiation*/,32/*vs/platform/theme/common/colorRegistry*/,527/*vs/css!vs/editor/contrib/peekView/browser/media/peekViewWidget*/]), function (require, exports, dom, actionbar_1, actions_1, codicons_1, themables_1, color_1, event_1, objects, editorExtensions_1, codeEditorService_1, embeddedCodeEditorWidget_1, zoneWidget_1, nls, menuEntryActionViewItem_1, contextkey_1, extensions_1, instantiation_1, colorRegistry_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.peekViewEditorMatchHighlightBorder = exports.peekViewEditorMatchHighlight = exports.peekViewResultsMatchHighlight = exports.peekViewEditorStickyScrollBackground = exports.peekViewEditorGutterBackground = exports.peekViewEditorBackground = exports.peekViewResultsSelectionForeground = exports.peekViewResultsSelectionBackground = exports.peekViewResultsFileForeground = exports.peekViewResultsMatchForeground = exports.peekViewResultsBackground = exports.peekViewBorder = exports.peekViewTitleInfoForeground = exports.peekViewTitleForeground = exports.peekViewTitleBackground = exports.PeekViewWidget = exports.PeekContext = exports.IPeekViewService = void 0;
    exports.getOuterEditor = getOuterEditor;
    exports.IPeekViewService = (0, instantiation_1.createDecorator)('IPeekViewService');
    (0, extensions_1.registerSingleton)(exports.IPeekViewService, class {
        constructor() {
            this._widgets = new Map();
        }
        addExclusiveWidget(editor, widget) {
            const existing = this._widgets.get(editor);
            if (existing) {
                existing.listener.dispose();
                existing.widget.dispose();
            }
            const remove = () => {
                const data = this._widgets.get(editor);
                if (data && data.widget === widget) {
                    data.listener.dispose();
                    this._widgets.delete(editor);
                }
            };
            this._widgets.set(editor, { widget, listener: widget.onDidClose(remove) });
        }
    }, 1 /* InstantiationType.Delayed */);
    var PeekContext;
    (function (PeekContext) {
        PeekContext.inPeekEditor = new contextkey_1.RawContextKey('inReferenceSearchEditor', true, nls.localize(1177, "Whether the current code editor is embedded inside peek"));
        PeekContext.notInPeekEditor = PeekContext.inPeekEditor.toNegated();
    })(PeekContext || (exports.PeekContext = PeekContext = {}));
    let PeekContextController = class PeekContextController {
        static { this.ID = 'editor.contrib.referenceController'; }
        constructor(editor, contextKeyService) {
            if (editor instanceof embeddedCodeEditorWidget_1.EmbeddedCodeEditorWidget) {
                PeekContext.inPeekEditor.bindTo(contextKeyService);
            }
        }
        dispose() { }
    };
    PeekContextController = __decorate([
        __param(1, contextkey_1.IContextKeyService)
    ], PeekContextController);
    (0, editorExtensions_1.registerEditorContribution)(PeekContextController.ID, PeekContextController, 0 /* EditorContributionInstantiation.Eager */); // eager because it needs to define a context key
    function getOuterEditor(accessor) {
        const editor = accessor.get(codeEditorService_1.ICodeEditorService).getFocusedCodeEditor();
        if (editor instanceof embeddedCodeEditorWidget_1.EmbeddedCodeEditorWidget) {
            return editor.getParentEditor();
        }
        return editor;
    }
    const defaultOptions = {
        headerBackgroundColor: color_1.Color.white,
        primaryHeadingColor: color_1.Color.fromHex('#333333'),
        secondaryHeadingColor: color_1.Color.fromHex('#6c6c6cb3')
    };
    let PeekViewWidget = class PeekViewWidget extends zoneWidget_1.ZoneWidget {
        constructor(editor, options, instantiationService) {
            super(editor, options);
            this.instantiationService = instantiationService;
            this._onDidClose = new event_1.Emitter();
            this.onDidClose = this._onDidClose.event;
            objects.mixin(this.options, defaultOptions, false);
        }
        dispose() {
            if (!this.disposed) {
                this.disposed = true; // prevent consumers who dispose on onDidClose from looping
                super.dispose();
                this._onDidClose.fire(this);
            }
        }
        style(styles) {
            const options = this.options;
            if (styles.headerBackgroundColor) {
                options.headerBackgroundColor = styles.headerBackgroundColor;
            }
            if (styles.primaryHeadingColor) {
                options.primaryHeadingColor = styles.primaryHeadingColor;
            }
            if (styles.secondaryHeadingColor) {
                options.secondaryHeadingColor = styles.secondaryHeadingColor;
            }
            super.style(styles);
        }
        _applyStyles() {
            super._applyStyles();
            const options = this.options;
            if (this._headElement && options.headerBackgroundColor) {
                this._headElement.style.backgroundColor = options.headerBackgroundColor.toString();
            }
            if (this._primaryHeading && options.primaryHeadingColor) {
                this._primaryHeading.style.color = options.primaryHeadingColor.toString();
            }
            if (this._secondaryHeading && options.secondaryHeadingColor) {
                this._secondaryHeading.style.color = options.secondaryHeadingColor.toString();
            }
            if (this._bodyElement && options.frameColor) {
                this._bodyElement.style.borderColor = options.frameColor.toString();
            }
        }
        _fillContainer(container) {
            this.setCssClass('peekview-widget');
            this._headElement = dom.$('.head');
            this._bodyElement = dom.$('.body');
            this._fillHead(this._headElement);
            this._fillBody(this._bodyElement);
            container.appendChild(this._headElement);
            container.appendChild(this._bodyElement);
        }
        _fillHead(container, noCloseAction) {
            this._titleElement = dom.$('.peekview-title');
            if (this.options.supportOnTitleClick) {
                this._titleElement.classList.add('clickable');
                dom.addStandardDisposableListener(this._titleElement, 'click', event => this._onTitleClick(event));
            }
            dom.append(this._headElement, this._titleElement);
            this._fillTitleIcon(this._titleElement);
            this._primaryHeading = dom.$('span.filename');
            this._secondaryHeading = dom.$('span.dirname');
            this._metaHeading = dom.$('span.meta');
            dom.append(this._titleElement, this._primaryHeading, this._secondaryHeading, this._metaHeading);
            const actionsContainer = dom.$('.peekview-actions');
            dom.append(this._headElement, actionsContainer);
            const actionBarOptions = this._getActionBarOptions();
            this._actionbarWidget = new actionbar_1.ActionBar(actionsContainer, actionBarOptions);
            this._disposables.add(this._actionbarWidget);
            if (!noCloseAction) {
                this._actionbarWidget.push(new actions_1.Action('peekview.close', nls.localize(1178, "Close"), themables_1.ThemeIcon.asClassName(codicons_1.Codicon.close), true, () => {
                    this.dispose();
                    return Promise.resolve();
                }), { label: false, icon: true });
            }
        }
        _fillTitleIcon(container) {
        }
        _getActionBarOptions() {
            return {
                actionViewItemProvider: menuEntryActionViewItem_1.createActionViewItem.bind(undefined, this.instantiationService),
                orientation: 0 /* ActionsOrientation.HORIZONTAL */
            };
        }
        _onTitleClick(event) {
            // implement me if supportOnTitleClick option is set
        }
        setTitle(primaryHeading, secondaryHeading) {
            if (this._primaryHeading && this._secondaryHeading) {
                this._primaryHeading.innerText = primaryHeading;
                this._primaryHeading.setAttribute('title', primaryHeading);
                if (secondaryHeading) {
                    this._secondaryHeading.innerText = secondaryHeading;
                }
                else {
                    dom.clearNode(this._secondaryHeading);
                }
            }
        }
        setMetaTitle(value) {
            if (this._metaHeading) {
                if (value) {
                    this._metaHeading.innerText = value;
                    dom.show(this._metaHeading);
                }
                else {
                    dom.hide(this._metaHeading);
                }
            }
        }
        _doLayout(heightInPixel, widthInPixel) {
            if (!this._isShowing && heightInPixel < 0) {
                // Looks like the view zone got folded away!
                this.dispose();
                return;
            }
            const headHeight = Math.ceil(this.editor.getOption(67 /* EditorOption.lineHeight */) * 1.2);
            const bodyHeight = Math.round(heightInPixel - (headHeight + 2 /* the border-top/bottom width*/));
            this._doLayoutHead(headHeight, widthInPixel);
            this._doLayoutBody(bodyHeight, widthInPixel);
        }
        _doLayoutHead(heightInPixel, widthInPixel) {
            if (this._headElement) {
                this._headElement.style.height = `${heightInPixel}px`;
                this._headElement.style.lineHeight = this._headElement.style.height;
            }
        }
        _doLayoutBody(heightInPixel, widthInPixel) {
            if (this._bodyElement) {
                this._bodyElement.style.height = `${heightInPixel}px`;
            }
        }
    };
    exports.PeekViewWidget = PeekViewWidget;
    exports.PeekViewWidget = PeekViewWidget = __decorate([
        __param(2, instantiation_1.IInstantiationService)
    ], PeekViewWidget);
    exports.peekViewTitleBackground = (0, colorRegistry_1.registerColor)('peekViewTitle.background', { dark: '#252526', light: '#F3F3F3', hcDark: color_1.Color.black, hcLight: color_1.Color.white }, nls.localize(1179, 'Background color of the peek view title area.'));
    exports.peekViewTitleForeground = (0, colorRegistry_1.registerColor)('peekViewTitleLabel.foreground', { dark: color_1.Color.white, light: color_1.Color.black, hcDark: color_1.Color.white, hcLight: colorRegistry_1.editorForeground }, nls.localize(1180, 'Color of the peek view title.'));
    exports.peekViewTitleInfoForeground = (0, colorRegistry_1.registerColor)('peekViewTitleDescription.foreground', { dark: '#ccccccb3', light: '#616161', hcDark: '#FFFFFF99', hcLight: '#292929' }, nls.localize(1181, 'Color of the peek view title info.'));
    exports.peekViewBorder = (0, colorRegistry_1.registerColor)('peekView.border', { dark: colorRegistry_1.editorInfoForeground, light: colorRegistry_1.editorInfoForeground, hcDark: colorRegistry_1.contrastBorder, hcLight: colorRegistry_1.contrastBorder }, nls.localize(1182, 'Color of the peek view borders and arrow.'));
    exports.peekViewResultsBackground = (0, colorRegistry_1.registerColor)('peekViewResult.background', { dark: '#252526', light: '#F3F3F3', hcDark: color_1.Color.black, hcLight: color_1.Color.white }, nls.localize(1183, 'Background color of the peek view result list.'));
    exports.peekViewResultsMatchForeground = (0, colorRegistry_1.registerColor)('peekViewResult.lineForeground', { dark: '#bbbbbb', light: '#646465', hcDark: color_1.Color.white, hcLight: colorRegistry_1.editorForeground }, nls.localize(1184, 'Foreground color for line nodes in the peek view result list.'));
    exports.peekViewResultsFileForeground = (0, colorRegistry_1.registerColor)('peekViewResult.fileForeground', { dark: color_1.Color.white, light: '#1E1E1E', hcDark: color_1.Color.white, hcLight: colorRegistry_1.editorForeground }, nls.localize(1185, 'Foreground color for file nodes in the peek view result list.'));
    exports.peekViewResultsSelectionBackground = (0, colorRegistry_1.registerColor)('peekViewResult.selectionBackground', { dark: '#3399ff33', light: '#3399ff33', hcDark: null, hcLight: null }, nls.localize(1186, 'Background color of the selected entry in the peek view result list.'));
    exports.peekViewResultsSelectionForeground = (0, colorRegistry_1.registerColor)('peekViewResult.selectionForeground', { dark: color_1.Color.white, light: '#6C6C6C', hcDark: color_1.Color.white, hcLight: colorRegistry_1.editorForeground }, nls.localize(1187, 'Foreground color of the selected entry in the peek view result list.'));
    exports.peekViewEditorBackground = (0, colorRegistry_1.registerColor)('peekViewEditor.background', { dark: '#001F33', light: '#F2F8FC', hcDark: color_1.Color.black, hcLight: color_1.Color.white }, nls.localize(1188, 'Background color of the peek view editor.'));
    exports.peekViewEditorGutterBackground = (0, colorRegistry_1.registerColor)('peekViewEditorGutter.background', exports.peekViewEditorBackground, nls.localize(1189, 'Background color of the gutter in the peek view editor.'));
    exports.peekViewEditorStickyScrollBackground = (0, colorRegistry_1.registerColor)('peekViewEditorStickyScroll.background', exports.peekViewEditorBackground, nls.localize(1190, 'Background color of sticky scroll in the peek view editor.'));
    exports.peekViewResultsMatchHighlight = (0, colorRegistry_1.registerColor)('peekViewResult.matchHighlightBackground', { dark: '#ea5c004d', light: '#ea5c004d', hcDark: null, hcLight: null }, nls.localize(1191, 'Match highlight color in the peek view result list.'));
    exports.peekViewEditorMatchHighlight = (0, colorRegistry_1.registerColor)('peekViewEditor.matchHighlightBackground', { dark: '#ff8f0099', light: '#f5d802de', hcDark: null, hcLight: null }, nls.localize(1192, 'Match highlight color in the peek view editor.'));
    exports.peekViewEditorMatchHighlightBorder = (0, colorRegistry_1.registerColor)('peekViewEditor.matchHighlightBorder', { dark: null, light: null, hcDark: colorRegistry_1.activeContrastBorder, hcLight: colorRegistry_1.activeContrastBorder }, nls.localize(1193, 'Match highlight border in the peek view editor.'));
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[843/*vs/editor/contrib/gotoError/browser/gotoErrorWidget*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,86/*vs/base/browser/ui/scrollbar/scrollableElement*/,13/*vs/base/common/arrays*/,33/*vs/base/common/color*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,48/*vs/base/common/resources*/,11/*vs/base/common/strings*/,4/*vs/editor/common/core/range*/,158/*vs/editor/contrib/peekView/browser/peekView*/,3/*vs/nls*/,124/*vs/platform/actions/browser/menuEntryActionViewItem*/,29/*vs/platform/actions/common/actions*/,12/*vs/platform/contextkey/common/contextkey*/,7/*vs/platform/instantiation/common/instantiation*/,181/*vs/platform/label/common/label*/,108/*vs/platform/markers/common/markers*/,59/*vs/platform/opener/common/opener*/,723/*vs/platform/severityIcon/browser/severityIcon*/,32/*vs/platform/theme/common/colorRegistry*/,25/*vs/platform/theme/common/themeService*/,512/*vs/css!vs/editor/contrib/gotoError/browser/media/gotoErrorWidget*/]), function (require, exports, dom, scrollableElement_1, arrays_1, color_1, event_1, lifecycle_1, resources_1, strings_1, range_1, peekView_1, nls, menuEntryActionViewItem_1, actions_1, contextkey_1, instantiation_1, label_1, markers_1, opener_1, severityIcon_1, colorRegistry_1, themeService_1) {
    "use strict";
    var MarkerNavigationWidget_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MarkerNavigationWidget = void 0;
    class MessageWidget {
        constructor(parent, editor, onRelatedInformation, _openerService, _labelService) {
            this._openerService = _openerService;
            this._labelService = _labelService;
            this._lines = 0;
            this._longestLineLength = 0;
            this._relatedDiagnostics = new WeakMap();
            this._disposables = new lifecycle_1.DisposableStore();
            this._editor = editor;
            const domNode = document.createElement('div');
            domNode.className = 'descriptioncontainer';
            this._messageBlock = document.createElement('div');
            this._messageBlock.classList.add('message');
            this._messageBlock.setAttribute('aria-live', 'assertive');
            this._messageBlock.setAttribute('role', 'alert');
            domNode.appendChild(this._messageBlock);
            this._relatedBlock = document.createElement('div');
            domNode.appendChild(this._relatedBlock);
            this._disposables.add(dom.addStandardDisposableListener(this._relatedBlock, 'click', event => {
                event.preventDefault();
                const related = this._relatedDiagnostics.get(event.target);
                if (related) {
                    onRelatedInformation(related);
                }
            }));
            this._scrollable = new scrollableElement_1.ScrollableElement(domNode, {
                horizontal: 1 /* ScrollbarVisibility.Auto */,
                vertical: 1 /* ScrollbarVisibility.Auto */,
                useShadows: false,
                horizontalScrollbarSize: 6,
                verticalScrollbarSize: 6
            });
            parent.appendChild(this._scrollable.getDomNode());
            this._disposables.add(this._scrollable.onScroll(e => {
                domNode.style.left = `-${e.scrollLeft}px`;
                domNode.style.top = `-${e.scrollTop}px`;
            }));
            this._disposables.add(this._scrollable);
        }
        dispose() {
            (0, lifecycle_1.dispose)(this._disposables);
        }
        update(marker) {
            const { source, message, relatedInformation, code } = marker;
            let sourceAndCodeLength = (source?.length || 0) + '()'.length;
            if (code) {
                if (typeof code === 'string') {
                    sourceAndCodeLength += code.length;
                }
                else {
                    sourceAndCodeLength += code.value.length;
                }
            }
            const lines = (0, strings_1.splitLines)(message);
            this._lines = lines.length;
            this._longestLineLength = 0;
            for (const line of lines) {
                this._longestLineLength = Math.max(line.length + sourceAndCodeLength, this._longestLineLength);
            }
            dom.clearNode(this._messageBlock);
            this._messageBlock.setAttribute('aria-label', this.getAriaLabel(marker));
            this._editor.applyFontInfo(this._messageBlock);
            let lastLineElement = this._messageBlock;
            for (const line of lines) {
                lastLineElement = document.createElement('div');
                lastLineElement.innerText = line;
                if (line === '') {
                    lastLineElement.style.height = this._messageBlock.style.lineHeight;
                }
                this._messageBlock.appendChild(lastLineElement);
            }
            if (source || code) {
                const detailsElement = document.createElement('span');
                detailsElement.classList.add('details');
                lastLineElement.appendChild(detailsElement);
                if (source) {
                    const sourceElement = document.createElement('span');
                    sourceElement.innerText = source;
                    sourceElement.classList.add('source');
                    detailsElement.appendChild(sourceElement);
                }
                if (code) {
                    if (typeof code === 'string') {
                        const codeElement = document.createElement('span');
                        codeElement.innerText = `(${code})`;
                        codeElement.classList.add('code');
                        detailsElement.appendChild(codeElement);
                    }
                    else {
                        this._codeLink = dom.$('a.code-link');
                        this._codeLink.setAttribute('href', `${code.target.toString()}`);
                        this._codeLink.onclick = (e) => {
                            this._openerService.open(code.target, { allowCommands: true });
                            e.preventDefault();
                            e.stopPropagation();
                        };
                        const codeElement = dom.append(this._codeLink, dom.$('span'));
                        codeElement.innerText = code.value;
                        detailsElement.appendChild(this._codeLink);
                    }
                }
            }
            dom.clearNode(this._relatedBlock);
            this._editor.applyFontInfo(this._relatedBlock);
            if ((0, arrays_1.isNonEmptyArray)(relatedInformation)) {
                const relatedInformationNode = this._relatedBlock.appendChild(document.createElement('div'));
                relatedInformationNode.style.paddingTop = `${Math.floor(this._editor.getOption(67 /* EditorOption.lineHeight */) * 0.66)}px`;
                this._lines += 1;
                for (const related of relatedInformation) {
                    const container = document.createElement('div');
                    const relatedResource = document.createElement('a');
                    relatedResource.classList.add('filename');
                    relatedResource.innerText = `${this._labelService.getUriBasenameLabel(related.resource)}(${related.startLineNumber}, ${related.startColumn}): `;
                    relatedResource.title = this._labelService.getUriLabel(related.resource);
                    this._relatedDiagnostics.set(relatedResource, related);
                    const relatedMessage = document.createElement('span');
                    relatedMessage.innerText = related.message;
                    container.appendChild(relatedResource);
                    container.appendChild(relatedMessage);
                    this._lines += 1;
                    relatedInformationNode.appendChild(container);
                }
            }
            const fontInfo = this._editor.getOption(50 /* EditorOption.fontInfo */);
            const scrollWidth = Math.ceil(fontInfo.typicalFullwidthCharacterWidth * this._longestLineLength * 0.75);
            const scrollHeight = fontInfo.lineHeight * this._lines;
            this._scrollable.setScrollDimensions({ scrollWidth, scrollHeight });
        }
        layout(height, width) {
            this._scrollable.getDomNode().style.height = `${height}px`;
            this._scrollable.getDomNode().style.width = `${width}px`;
            this._scrollable.setScrollDimensions({ width, height });
        }
        getHeightInLines() {
            return Math.min(17, this._lines);
        }
        getAriaLabel(marker) {
            let severityLabel = '';
            switch (marker.severity) {
                case markers_1.MarkerSeverity.Error:
                    severityLabel = nls.localize(932, "Error");
                    break;
                case markers_1.MarkerSeverity.Warning:
                    severityLabel = nls.localize(933, "Warning");
                    break;
                case markers_1.MarkerSeverity.Info:
                    severityLabel = nls.localize(934, "Info");
                    break;
                case markers_1.MarkerSeverity.Hint:
                    severityLabel = nls.localize(935, "Hint");
                    break;
            }
            let ariaLabel = nls.localize(936, "{0} at {1}. ", severityLabel, marker.startLineNumber + ':' + marker.startColumn);
            const model = this._editor.getModel();
            if (model && (marker.startLineNumber <= model.getLineCount()) && (marker.startLineNumber >= 1)) {
                const lineContent = model.getLineContent(marker.startLineNumber);
                ariaLabel = `${lineContent}, ${ariaLabel}`;
            }
            return ariaLabel;
        }
    }
    let MarkerNavigationWidget = class MarkerNavigationWidget extends peekView_1.PeekViewWidget {
        static { MarkerNavigationWidget_1 = this; }
        static { this.TitleMenu = new actions_1.MenuId('gotoErrorTitleMenu'); }
        constructor(editor, _themeService, _openerService, _menuService, instantiationService, _contextKeyService, _labelService) {
            super(editor, { showArrow: true, showFrame: true, isAccessible: true, frameWidth: 1 }, instantiationService);
            this._themeService = _themeService;
            this._openerService = _openerService;
            this._menuService = _menuService;
            this._contextKeyService = _contextKeyService;
            this._labelService = _labelService;
            this._callOnDispose = new lifecycle_1.DisposableStore();
            this._onDidSelectRelatedInformation = new event_1.Emitter();
            this.onDidSelectRelatedInformation = this._onDidSelectRelatedInformation.event;
            this._severity = markers_1.MarkerSeverity.Warning;
            this._backgroundColor = color_1.Color.white;
            this._applyTheme(_themeService.getColorTheme());
            this._callOnDispose.add(_themeService.onDidColorThemeChange(this._applyTheme.bind(this)));
            this.create();
        }
        _applyTheme(theme) {
            this._backgroundColor = theme.getColor(editorMarkerNavigationBackground);
            let colorId = editorMarkerNavigationError;
            let headerBackground = editorMarkerNavigationErrorHeader;
            if (this._severity === markers_1.MarkerSeverity.Warning) {
                colorId = editorMarkerNavigationWarning;
                headerBackground = editorMarkerNavigationWarningHeader;
            }
            else if (this._severity === markers_1.MarkerSeverity.Info) {
                colorId = editorMarkerNavigationInfo;
                headerBackground = editorMarkerNavigationInfoHeader;
            }
            const frameColor = theme.getColor(colorId);
            const headerBg = theme.getColor(headerBackground);
            this.style({
                arrowColor: frameColor,
                frameColor: frameColor,
                headerBackgroundColor: headerBg,
                primaryHeadingColor: theme.getColor(peekView_1.peekViewTitleForeground),
                secondaryHeadingColor: theme.getColor(peekView_1.peekViewTitleInfoForeground)
            }); // style() will trigger _applyStyles
        }
        _applyStyles() {
            if (this._parentContainer) {
                this._parentContainer.style.backgroundColor = this._backgroundColor ? this._backgroundColor.toString() : '';
            }
            super._applyStyles();
        }
        dispose() {
            this._callOnDispose.dispose();
            super.dispose();
        }
        _fillHead(container) {
            super._fillHead(container);
            this._disposables.add(this._actionbarWidget.actionRunner.onWillRun(e => this.editor.focus()));
            const actions = [];
            const menu = this._menuService.getMenuActions(MarkerNavigationWidget_1.TitleMenu, this._contextKeyService);
            (0, menuEntryActionViewItem_1.createAndFillInActionBarActions)(menu, actions);
            this._actionbarWidget.push(actions, { label: false, icon: true, index: 0 });
        }
        _fillTitleIcon(container) {
            this._icon = dom.append(container, dom.$(''));
        }
        _fillBody(container) {
            this._parentContainer = container;
            container.classList.add('marker-widget');
            this._parentContainer.tabIndex = 0;
            this._parentContainer.setAttribute('role', 'tooltip');
            this._container = document.createElement('div');
            container.appendChild(this._container);
            this._message = new MessageWidget(this._container, this.editor, related => this._onDidSelectRelatedInformation.fire(related), this._openerService, this._labelService);
            this._disposables.add(this._message);
        }
        show() {
            throw new Error('call showAtMarker');
        }
        showAtMarker(marker, markerIdx, markerCount) {
            // update:
            // * title
            // * message
            this._container.classList.remove('stale');
            this._message.update(marker);
            // update frame color (only applied on 'show')
            this._severity = marker.severity;
            this._applyTheme(this._themeService.getColorTheme());
            // show
            const range = range_1.Range.lift(marker);
            const editorPosition = this.editor.getPosition();
            const position = editorPosition && range.containsPosition(editorPosition) ? editorPosition : range.getStartPosition();
            super.show(position, this.computeRequiredHeight());
            const model = this.editor.getModel();
            if (model) {
                const detail = markerCount > 1
                    ? nls.localize(937, "{0} of {1} problems", markerIdx, markerCount)
                    : nls.localize(938, "{0} of {1} problem", markerIdx, markerCount);
                this.setTitle((0, resources_1.basename)(model.uri), detail);
            }
            this._icon.className = `codicon ${severityIcon_1.SeverityIcon.className(markers_1.MarkerSeverity.toSeverity(this._severity))}`;
            this.editor.revealPositionNearTop(position, 0 /* ScrollType.Smooth */);
            this.editor.focus();
        }
        updateMarker(marker) {
            this._container.classList.remove('stale');
            this._message.update(marker);
        }
        showStale() {
            this._container.classList.add('stale');
            this._relayout();
        }
        _doLayoutBody(heightInPixel, widthInPixel) {
            super._doLayoutBody(heightInPixel, widthInPixel);
            this._heightInPixel = heightInPixel;
            this._message.layout(heightInPixel, widthInPixel);
            this._container.style.height = `${heightInPixel}px`;
        }
        _onWidth(widthInPixel) {
            this._message.layout(this._heightInPixel, widthInPixel);
        }
        _relayout() {
            super._relayout(this.computeRequiredHeight());
        }
        computeRequiredHeight() {
            return 3 + this._message.getHeightInLines();
        }
    };
    exports.MarkerNavigationWidget = MarkerNavigationWidget;
    exports.MarkerNavigationWidget = MarkerNavigationWidget = MarkerNavigationWidget_1 = __decorate([
        __param(1, themeService_1.IThemeService),
        __param(2, opener_1.IOpenerService),
        __param(3, actions_1.IMenuService),
        __param(4, instantiation_1.IInstantiationService),
        __param(5, contextkey_1.IContextKeyService),
        __param(6, label_1.ILabelService)
    ], MarkerNavigationWidget);
    // theming
    const errorDefault = (0, colorRegistry_1.oneOf)(colorRegistry_1.editorErrorForeground, colorRegistry_1.editorErrorBorder);
    const warningDefault = (0, colorRegistry_1.oneOf)(colorRegistry_1.editorWarningForeground, colorRegistry_1.editorWarningBorder);
    const infoDefault = (0, colorRegistry_1.oneOf)(colorRegistry_1.editorInfoForeground, colorRegistry_1.editorInfoBorder);
    const editorMarkerNavigationError = (0, colorRegistry_1.registerColor)('editorMarkerNavigationError.background', { dark: errorDefault, light: errorDefault, hcDark: colorRegistry_1.contrastBorder, hcLight: colorRegistry_1.contrastBorder }, nls.localize(939, 'Editor marker navigation widget error color.'));
    const editorMarkerNavigationErrorHeader = (0, colorRegistry_1.registerColor)('editorMarkerNavigationError.headerBackground', { dark: (0, colorRegistry_1.transparent)(editorMarkerNavigationError, .1), light: (0, colorRegistry_1.transparent)(editorMarkerNavigationError, .1), hcDark: null, hcLight: null }, nls.localize(940, 'Editor marker navigation widget error heading background.'));
    const editorMarkerNavigationWarning = (0, colorRegistry_1.registerColor)('editorMarkerNavigationWarning.background', { dark: warningDefault, light: warningDefault, hcDark: colorRegistry_1.contrastBorder, hcLight: colorRegistry_1.contrastBorder }, nls.localize(941, 'Editor marker navigation widget warning color.'));
    const editorMarkerNavigationWarningHeader = (0, colorRegistry_1.registerColor)('editorMarkerNavigationWarning.headerBackground', { dark: (0, colorRegistry_1.transparent)(editorMarkerNavigationWarning, .1), light: (0, colorRegistry_1.transparent)(editorMarkerNavigationWarning, .1), hcDark: '#0C141F', hcLight: (0, colorRegistry_1.transparent)(editorMarkerNavigationWarning, .2) }, nls.localize(942, 'Editor marker navigation widget warning heading background.'));
    const editorMarkerNavigationInfo = (0, colorRegistry_1.registerColor)('editorMarkerNavigationInfo.background', { dark: infoDefault, light: infoDefault, hcDark: colorRegistry_1.contrastBorder, hcLight: colorRegistry_1.contrastBorder }, nls.localize(943, 'Editor marker navigation widget info color.'));
    const editorMarkerNavigationInfoHeader = (0, colorRegistry_1.registerColor)('editorMarkerNavigationInfo.headerBackground', { dark: (0, colorRegistry_1.transparent)(editorMarkerNavigationInfo, .1), light: (0, colorRegistry_1.transparent)(editorMarkerNavigationInfo, .1), hcDark: null, hcLight: null }, nls.localize(944, 'Editor marker navigation widget info heading background.'));
    const editorMarkerNavigationBackground = (0, colorRegistry_1.registerColor)('editorMarkerNavigation.background', colorRegistry_1.editorBackground, nls.localize(945, 'Editor marker navigation widget background.'));
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[427/*vs/editor/contrib/gotoError/browser/gotoError*/], __M([1/*require*/,0/*exports*/,26/*vs/base/common/codicons*/,2/*vs/base/common/lifecycle*/,15/*vs/editor/browser/editorExtensions*/,34/*vs/editor/browser/services/codeEditorService*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/,20/*vs/editor/common/editorContextKeys*/,698/*vs/editor/contrib/gotoError/browser/markerNavigationService*/,3/*vs/nls*/,29/*vs/platform/actions/common/actions*/,12/*vs/platform/contextkey/common/contextkey*/,7/*vs/platform/instantiation/common/instantiation*/,71/*vs/platform/theme/common/iconRegistry*/,843/*vs/editor/contrib/gotoError/browser/gotoErrorWidget*/]), function (require, exports, codicons_1, lifecycle_1, editorExtensions_1, codeEditorService_1, position_1, range_1, editorContextKeys_1, markerNavigationService_1, nls, actions_1, contextkey_1, instantiation_1, iconRegistry_1, gotoErrorWidget_1) {
    "use strict";
    var MarkerController_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.NextMarkerAction = exports.MarkerController = void 0;
    let MarkerController = class MarkerController {
        static { MarkerController_1 = this; }
        static { this.ID = 'editor.contrib.markerController'; }
        static get(editor) {
            return editor.getContribution(MarkerController_1.ID);
        }
        constructor(editor, _markerNavigationService, _contextKeyService, _editorService, _instantiationService) {
            this._markerNavigationService = _markerNavigationService;
            this._contextKeyService = _contextKeyService;
            this._editorService = _editorService;
            this._instantiationService = _instantiationService;
            this._sessionDispoables = new lifecycle_1.DisposableStore();
            this._editor = editor;
            this._widgetVisible = CONTEXT_MARKERS_NAVIGATION_VISIBLE.bindTo(this._contextKeyService);
        }
        dispose() {
            this._cleanUp();
            this._sessionDispoables.dispose();
        }
        _cleanUp() {
            this._widgetVisible.reset();
            this._sessionDispoables.clear();
            this._widget = undefined;
            this._model = undefined;
        }
        _getOrCreateModel(uri) {
            if (this._model && this._model.matches(uri)) {
                return this._model;
            }
            let reusePosition = false;
            if (this._model) {
                reusePosition = true;
                this._cleanUp();
            }
            this._model = this._markerNavigationService.getMarkerList(uri);
            if (reusePosition) {
                this._model.move(true, this._editor.getModel(), this._editor.getPosition());
            }
            this._widget = this._instantiationService.createInstance(gotoErrorWidget_1.MarkerNavigationWidget, this._editor);
            this._widget.onDidClose(() => this.close(), this, this._sessionDispoables);
            this._widgetVisible.set(true);
            this._sessionDispoables.add(this._model);
            this._sessionDispoables.add(this._widget);
            // follow cursor
            this._sessionDispoables.add(this._editor.onDidChangeCursorPosition(e => {
                if (!this._model?.selected || !range_1.Range.containsPosition(this._model?.selected.marker, e.position)) {
                    this._model?.resetIndex();
                }
            }));
            // update markers
            this._sessionDispoables.add(this._model.onDidChange(() => {
                if (!this._widget || !this._widget.position || !this._model) {
                    return;
                }
                const info = this._model.find(this._editor.getModel().uri, this._widget.position);
                if (info) {
                    this._widget.updateMarker(info.marker);
                }
                else {
                    this._widget.showStale();
                }
            }));
            // open related
            this._sessionDispoables.add(this._widget.onDidSelectRelatedInformation(related => {
                this._editorService.openCodeEditor({
                    resource: related.resource,
                    options: { pinned: true, revealIfOpened: true, selection: range_1.Range.lift(related).collapseToStart() }
                }, this._editor);
                this.close(false);
            }));
            this._sessionDispoables.add(this._editor.onDidChangeModel(() => this._cleanUp()));
            return this._model;
        }
        close(focusEditor = true) {
            this._cleanUp();
            if (focusEditor) {
                this._editor.focus();
            }
        }
        showAtMarker(marker) {
            if (this._editor.hasModel()) {
                const model = this._getOrCreateModel(this._editor.getModel().uri);
                model.resetIndex();
                model.move(true, this._editor.getModel(), new position_1.Position(marker.startLineNumber, marker.startColumn));
                if (model.selected) {
                    this._widget.showAtMarker(model.selected.marker, model.selected.index, model.selected.total);
                }
            }
        }
        async nagivate(next, multiFile) {
            if (this._editor.hasModel()) {
                const model = this._getOrCreateModel(multiFile ? undefined : this._editor.getModel().uri);
                model.move(next, this._editor.getModel(), this._editor.getPosition());
                if (!model.selected) {
                    return;
                }
                if (model.selected.marker.resource.toString() !== this._editor.getModel().uri.toString()) {
                    // show in different editor
                    this._cleanUp();
                    const otherEditor = await this._editorService.openCodeEditor({
                        resource: model.selected.marker.resource,
                        options: { pinned: false, revealIfOpened: true, selectionRevealType: 2 /* TextEditorSelectionRevealType.NearTop */, selection: model.selected.marker }
                    }, this._editor);
                    if (otherEditor) {
                        MarkerController_1.get(otherEditor)?.close();
                        MarkerController_1.get(otherEditor)?.nagivate(next, multiFile);
                    }
                }
                else {
                    // show in this editor
                    this._widget.showAtMarker(model.selected.marker, model.selected.index, model.selected.total);
                }
            }
        }
    };
    exports.MarkerController = MarkerController;
    exports.MarkerController = MarkerController = MarkerController_1 = __decorate([
        __param(1, markerNavigationService_1.IMarkerNavigationService),
        __param(2, contextkey_1.IContextKeyService),
        __param(3, codeEditorService_1.ICodeEditorService),
        __param(4, instantiation_1.IInstantiationService)
    ], MarkerController);
    class MarkerNavigationAction extends editorExtensions_1.EditorAction {
        constructor(_next, _multiFile, opts) {
            super(opts);
            this._next = _next;
            this._multiFile = _multiFile;
        }
        async run(_accessor, editor) {
            if (editor.hasModel()) {
                MarkerController.get(editor)?.nagivate(this._next, this._multiFile);
            }
        }
    }
    class NextMarkerAction extends MarkerNavigationAction {
        static { this.ID = 'editor.action.marker.next'; }
        static { this.LABEL = nls.localize(924, "Go to Next Problem (Error, Warning, Info)"); }
        constructor() {
            super(true, false, {
                id: NextMarkerAction.ID,
                label: NextMarkerAction.LABEL,
                alias: 'Go to Next Problem (Error, Warning, Info)',
                precondition: undefined,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.focus,
                    primary: 512 /* KeyMod.Alt */ | 66 /* KeyCode.F8 */,
                    weight: 100 /* KeybindingWeight.EditorContrib */
                },
                menuOpts: {
                    menuId: gotoErrorWidget_1.MarkerNavigationWidget.TitleMenu,
                    title: NextMarkerAction.LABEL,
                    icon: (0, iconRegistry_1.registerIcon)('marker-navigation-next', codicons_1.Codicon.arrowDown, nls.localize(925, 'Icon for goto next marker.')),
                    group: 'navigation',
                    order: 1
                }
            });
        }
    }
    exports.NextMarkerAction = NextMarkerAction;
    class PrevMarkerAction extends MarkerNavigationAction {
        static { this.ID = 'editor.action.marker.prev'; }
        static { this.LABEL = nls.localize(926, "Go to Previous Problem (Error, Warning, Info)"); }
        constructor() {
            super(false, false, {
                id: PrevMarkerAction.ID,
                label: PrevMarkerAction.LABEL,
                alias: 'Go to Previous Problem (Error, Warning, Info)',
                precondition: undefined,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.focus,
                    primary: 1024 /* KeyMod.Shift */ | 512 /* KeyMod.Alt */ | 66 /* KeyCode.F8 */,
                    weight: 100 /* KeybindingWeight.EditorContrib */
                },
                menuOpts: {
                    menuId: gotoErrorWidget_1.MarkerNavigationWidget.TitleMenu,
                    title: PrevMarkerAction.LABEL,
                    icon: (0, iconRegistry_1.registerIcon)('marker-navigation-previous', codicons_1.Codicon.arrowUp, nls.localize(927, 'Icon for goto previous marker.')),
                    group: 'navigation',
                    order: 2
                }
            });
        }
    }
    class NextMarkerInFilesAction extends MarkerNavigationAction {
        constructor() {
            super(true, true, {
                id: 'editor.action.marker.nextInFiles',
                label: nls.localize(928, "Go to Next Problem in Files (Error, Warning, Info)"),
                alias: 'Go to Next Problem in Files (Error, Warning, Info)',
                precondition: undefined,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.focus,
                    primary: 66 /* KeyCode.F8 */,
                    weight: 100 /* KeybindingWeight.EditorContrib */
                },
                menuOpts: {
                    menuId: actions_1.MenuId.MenubarGoMenu,
                    title: nls.localize(929, "Next &&Problem"),
                    group: '6_problem_nav',
                    order: 1
                }
            });
        }
    }
    class PrevMarkerInFilesAction extends MarkerNavigationAction {
        constructor() {
            super(false, true, {
                id: 'editor.action.marker.prevInFiles',
                label: nls.localize(930, "Go to Previous Problem in Files (Error, Warning, Info)"),
                alias: 'Go to Previous Problem in Files (Error, Warning, Info)',
                precondition: undefined,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.focus,
                    primary: 1024 /* KeyMod.Shift */ | 66 /* KeyCode.F8 */,
                    weight: 100 /* KeybindingWeight.EditorContrib */
                },
                menuOpts: {
                    menuId: actions_1.MenuId.MenubarGoMenu,
                    title: nls.localize(931, "Previous &&Problem"),
                    group: '6_problem_nav',
                    order: 2
                }
            });
        }
    }
    (0, editorExtensions_1.registerEditorContribution)(MarkerController.ID, MarkerController, 4 /* EditorContributionInstantiation.Lazy */);
    (0, editorExtensions_1.registerEditorAction)(NextMarkerAction);
    (0, editorExtensions_1.registerEditorAction)(PrevMarkerAction);
    (0, editorExtensions_1.registerEditorAction)(NextMarkerInFilesAction);
    (0, editorExtensions_1.registerEditorAction)(PrevMarkerInFilesAction);
    const CONTEXT_MARKERS_NAVIGATION_VISIBLE = new contextkey_1.RawContextKey('markersNavigationVisible', false);
    const MarkerCommand = editorExtensions_1.EditorCommand.bindToContribution(MarkerController.get);
    (0, editorExtensions_1.registerEditorCommand)(new MarkerCommand({
        id: 'closeMarkersNavigation',
        precondition: CONTEXT_MARKERS_NAVIGATION_VISIBLE,
        handler: x => x.close(),
        kbOpts: {
            weight: 100 /* KeybindingWeight.EditorContrib */ + 50,
            kbExpr: editorContextKeys_1.EditorContextKeys.focus,
            primary: 9 /* KeyCode.Escape */,
            secondary: [1024 /* KeyMod.Shift */ | 9 /* KeyCode.Escape */]
        }
    }));
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[844/*vs/editor/contrib/gotoSymbol/browser/peek/referencesWidget*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,357/*vs/base/browser/ui/splitview/splitview*/,33/*vs/base/common/color*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,42/*vs/base/common/network*/,48/*vs/base/common/resources*/,125/*vs/editor/browser/widget/codeEditor/embeddedCodeEditorWidget*/,4/*vs/editor/common/core/range*/,35/*vs/editor/common/model/textModel*/,70/*vs/editor/common/languages/modesRegistry*/,78/*vs/editor/common/services/resolverService*/,758/*vs/editor/contrib/gotoSymbol/browser/peek/referencesTree*/,158/*vs/editor/contrib/peekView/browser/peekView*/,3/*vs/nls*/,7/*vs/platform/instantiation/common/instantiation*/,31/*vs/platform/keybinding/common/keybinding*/,181/*vs/platform/label/common/label*/,216/*vs/platform/list/browser/listService*/,25/*vs/platform/theme/common/themeService*/,178/*vs/editor/contrib/gotoSymbol/browser/referencesModel*/,514/*vs/css!vs/editor/contrib/gotoSymbol/browser/peek/referencesWidget*/]), function (require, exports, dom, splitview_1, color_1, event_1, lifecycle_1, network_1, resources_1, embeddedCodeEditorWidget_1, range_1, textModel_1, modesRegistry_1, resolverService_1, referencesTree_1, peekView, nls, instantiation_1, keybinding_1, label_1, listService_1, themeService_1, referencesModel_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ReferenceWidget = exports.LayoutData = void 0;
    class DecorationsManager {
        static { this.DecorationOptions = textModel_1.ModelDecorationOptions.register({
            description: 'reference-decoration',
            stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */,
            className: 'reference-decoration'
        }); }
        constructor(_editor, _model) {
            this._editor = _editor;
            this._model = _model;
            this._decorations = new Map();
            this._decorationIgnoreSet = new Set();
            this._callOnDispose = new lifecycle_1.DisposableStore();
            this._callOnModelChange = new lifecycle_1.DisposableStore();
            this._callOnDispose.add(this._editor.onDidChangeModel(() => this._onModelChanged()));
            this._onModelChanged();
        }
        dispose() {
            this._callOnModelChange.dispose();
            this._callOnDispose.dispose();
            this.removeDecorations();
        }
        _onModelChanged() {
            this._callOnModelChange.clear();
            const model = this._editor.getModel();
            if (!model) {
                return;
            }
            for (const ref of this._model.references) {
                if (ref.uri.toString() === model.uri.toString()) {
                    this._addDecorations(ref.parent);
                    return;
                }
            }
        }
        _addDecorations(reference) {
            if (!this._editor.hasModel()) {
                return;
            }
            this._callOnModelChange.add(this._editor.getModel().onDidChangeDecorations(() => this._onDecorationChanged()));
            const newDecorations = [];
            const newDecorationsActualIndex = [];
            for (let i = 0, len = reference.children.length; i < len; i++) {
                const oneReference = reference.children[i];
                if (this._decorationIgnoreSet.has(oneReference.id)) {
                    continue;
                }
                if (oneReference.uri.toString() !== this._editor.getModel().uri.toString()) {
                    continue;
                }
                newDecorations.push({
                    range: oneReference.range,
                    options: DecorationsManager.DecorationOptions
                });
                newDecorationsActualIndex.push(i);
            }
            this._editor.changeDecorations((changeAccessor) => {
                const decorations = changeAccessor.deltaDecorations([], newDecorations);
                for (let i = 0; i < decorations.length; i++) {
                    this._decorations.set(decorations[i], reference.children[newDecorationsActualIndex[i]]);
                }
            });
        }
        _onDecorationChanged() {
            const toRemove = [];
            const model = this._editor.getModel();
            if (!model) {
                return;
            }
            for (const [decorationId, reference] of this._decorations) {
                const newRange = model.getDecorationRange(decorationId);
                if (!newRange) {
                    continue;
                }
                let ignore = false;
                if (range_1.Range.equalsRange(newRange, reference.range)) {
                    continue;
                }
                if (range_1.Range.spansMultipleLines(newRange)) {
                    ignore = true;
                }
                else {
                    const lineLength = reference.range.endColumn - reference.range.startColumn;
                    const newLineLength = newRange.endColumn - newRange.startColumn;
                    if (lineLength !== newLineLength) {
                        ignore = true;
                    }
                }
                if (ignore) {
                    this._decorationIgnoreSet.add(reference.id);
                    toRemove.push(decorationId);
                }
                else {
                    reference.range = newRange;
                }
            }
            for (let i = 0, len = toRemove.length; i < len; i++) {
                this._decorations.delete(toRemove[i]);
            }
            this._editor.removeDecorations(toRemove);
        }
        removeDecorations() {
            this._editor.removeDecorations([...this._decorations.keys()]);
            this._decorations.clear();
        }
    }
    class LayoutData {
        constructor() {
            this.ratio = 0.7;
            this.heightInLines = 18;
        }
        static fromJSON(raw) {
            let ratio;
            let heightInLines;
            try {
                const data = JSON.parse(raw);
                ratio = data.ratio;
                heightInLines = data.heightInLines;
            }
            catch {
                //
            }
            return {
                ratio: ratio || 0.7,
                heightInLines: heightInLines || 18
            };
        }
    }
    exports.LayoutData = LayoutData;
    class ReferencesTree extends listService_1.WorkbenchAsyncDataTree {
    }
    /**
     * ZoneWidget that is shown inside the editor
     */
    let ReferenceWidget = class ReferenceWidget extends peekView.PeekViewWidget {
        constructor(editor, _defaultTreeKeyboardSupport, layoutData, themeService, _textModelResolverService, _instantiationService, _peekViewService, _uriLabel, _keybindingService) {
            super(editor, { showFrame: false, showArrow: true, isResizeable: true, isAccessible: true, supportOnTitleClick: true }, _instantiationService);
            this._defaultTreeKeyboardSupport = _defaultTreeKeyboardSupport;
            this.layoutData = layoutData;
            this._textModelResolverService = _textModelResolverService;
            this._instantiationService = _instantiationService;
            this._peekViewService = _peekViewService;
            this._uriLabel = _uriLabel;
            this._keybindingService = _keybindingService;
            this._disposeOnNewModel = new lifecycle_1.DisposableStore();
            this._callOnDispose = new lifecycle_1.DisposableStore();
            this._onDidSelectReference = new event_1.Emitter();
            this.onDidSelectReference = this._onDidSelectReference.event;
            this._dim = new dom.Dimension(0, 0);
            this._isClosing = false; // whether or not a dispose is already in progress
            this._applyTheme(themeService.getColorTheme());
            this._callOnDispose.add(themeService.onDidColorThemeChange(this._applyTheme.bind(this)));
            this._peekViewService.addExclusiveWidget(editor, this);
            this.create();
        }
        get isClosing() {
            return this._isClosing;
        }
        dispose() {
            this._isClosing = true;
            this.setModel(undefined);
            this._callOnDispose.dispose();
            this._disposeOnNewModel.dispose();
            (0, lifecycle_1.dispose)(this._preview);
            (0, lifecycle_1.dispose)(this._previewNotAvailableMessage);
            (0, lifecycle_1.dispose)(this._tree);
            (0, lifecycle_1.dispose)(this._previewModelReference);
            this._splitView.dispose();
            super.dispose();
        }
        _applyTheme(theme) {
            const borderColor = theme.getColor(peekView.peekViewBorder) || color_1.Color.transparent;
            this.style({
                arrowColor: borderColor,
                frameColor: borderColor,
                headerBackgroundColor: theme.getColor(peekView.peekViewTitleBackground) || color_1.Color.transparent,
                primaryHeadingColor: theme.getColor(peekView.peekViewTitleForeground),
                secondaryHeadingColor: theme.getColor(peekView.peekViewTitleInfoForeground)
            });
        }
        show(where) {
            super.show(where, this.layoutData.heightInLines || 18);
        }
        focusOnReferenceTree() {
            this._tree.domFocus();
        }
        focusOnPreviewEditor() {
            this._preview.focus();
        }
        isPreviewEditorFocused() {
            return this._preview.hasTextFocus();
        }
        _onTitleClick(e) {
            if (this._preview && this._preview.getModel()) {
                this._onDidSelectReference.fire({
                    element: this._getFocusedReference(),
                    kind: e.ctrlKey || e.metaKey || e.altKey ? 'side' : 'open',
                    source: 'title'
                });
            }
        }
        _fillBody(containerElement) {
            this.setCssClass('reference-zone-widget');
            // message pane
            this._messageContainer = dom.append(containerElement, dom.$('div.messages'));
            dom.hide(this._messageContainer);
            this._splitView = new splitview_1.SplitView(containerElement, { orientation: 1 /* Orientation.HORIZONTAL */ });
            // editor
            this._previewContainer = dom.append(containerElement, dom.$('div.preview.inline'));
            const options = {
                scrollBeyondLastLine: false,
                scrollbar: {
                    verticalScrollbarSize: 14,
                    horizontal: 'auto',
                    useShadows: true,
                    verticalHasArrows: false,
                    horizontalHasArrows: false,
                    alwaysConsumeMouseWheel: true
                },
                overviewRulerLanes: 2,
                fixedOverflowWidgets: true,
                minimap: {
                    enabled: false
                }
            };
            this._preview = this._instantiationService.createInstance(embeddedCodeEditorWidget_1.EmbeddedCodeEditorWidget, this._previewContainer, options, {}, this.editor);
            dom.hide(this._previewContainer);
            this._previewNotAvailableMessage = this._instantiationService.createInstance(textModel_1.TextModel, nls.localize(992, "no preview available"), modesRegistry_1.PLAINTEXT_LANGUAGE_ID, textModel_1.TextModel.DEFAULT_CREATION_OPTIONS, null);
            // tree
            this._treeContainer = dom.append(containerElement, dom.$('div.ref-tree.inline'));
            const treeOptions = {
                keyboardSupport: this._defaultTreeKeyboardSupport,
                accessibilityProvider: new referencesTree_1.AccessibilityProvider(),
                keyboardNavigationLabelProvider: this._instantiationService.createInstance(referencesTree_1.StringRepresentationProvider),
                identityProvider: new referencesTree_1.IdentityProvider(),
                openOnSingleClick: true,
                selectionNavigation: true,
                overrideStyles: {
                    listBackground: peekView.peekViewResultsBackground
                }
            };
            if (this._defaultTreeKeyboardSupport) {
                // the tree will consume `Escape` and prevent the widget from closing
                this._callOnDispose.add(dom.addStandardDisposableListener(this._treeContainer, 'keydown', (e) => {
                    if (e.equals(9 /* KeyCode.Escape */)) {
                        this._keybindingService.dispatchEvent(e, e.target);
                        e.stopPropagation();
                    }
                }, true));
            }
            this._tree = this._instantiationService.createInstance(ReferencesTree, 'ReferencesWidget', this._treeContainer, new referencesTree_1.Delegate(), [
                this._instantiationService.createInstance(referencesTree_1.FileReferencesRenderer),
                this._instantiationService.createInstance(referencesTree_1.OneReferenceRenderer),
            ], this._instantiationService.createInstance(referencesTree_1.DataSource), treeOptions);
            // split stuff
            this._splitView.addView({
                onDidChange: event_1.Event.None,
                element: this._previewContainer,
                minimumSize: 200,
                maximumSize: Number.MAX_VALUE,
                layout: (width) => {
                    this._preview.layout({ height: this._dim.height, width });
                }
            }, splitview_1.Sizing.Distribute);
            this._splitView.addView({
                onDidChange: event_1.Event.None,
                element: this._treeContainer,
                minimumSize: 100,
                maximumSize: Number.MAX_VALUE,
                layout: (width) => {
                    this._treeContainer.style.height = `${this._dim.height}px`;
                    this._treeContainer.style.width = `${width}px`;
                    this._tree.layout(this._dim.height, width);
                }
            }, splitview_1.Sizing.Distribute);
            this._disposables.add(this._splitView.onDidSashChange(() => {
                if (this._dim.width) {
                    this.layoutData.ratio = this._splitView.getViewSize(0) / this._dim.width;
                }
            }, undefined));
            // listen on selection and focus
            const onEvent = (element, kind) => {
                if (element instanceof referencesModel_1.OneReference) {
                    if (kind === 'show') {
                        this._revealReference(element, false);
                    }
                    this._onDidSelectReference.fire({ element, kind, source: 'tree' });
                }
            };
            this._disposables.add(this._tree.onDidOpen(e => {
                if (e.sideBySide) {
                    onEvent(e.element, 'side');
                }
                else if (e.editorOptions.pinned) {
                    onEvent(e.element, 'goto');
                }
                else {
                    onEvent(e.element, 'show');
                }
            }));
            dom.hide(this._treeContainer);
        }
        _onWidth(width) {
            if (this._dim) {
                this._doLayoutBody(this._dim.height, width);
            }
        }
        _doLayoutBody(heightInPixel, widthInPixel) {
            super._doLayoutBody(heightInPixel, widthInPixel);
            this._dim = new dom.Dimension(widthInPixel, heightInPixel);
            this.layoutData.heightInLines = this._viewZone ? this._viewZone.heightInLines : this.layoutData.heightInLines;
            this._splitView.layout(widthInPixel);
            this._splitView.resizeView(0, widthInPixel * this.layoutData.ratio);
        }
        setSelection(selection) {
            return this._revealReference(selection, true).then(() => {
                if (!this._model) {
                    // disposed
                    return;
                }
                // show in tree
                this._tree.setSelection([selection]);
                this._tree.setFocus([selection]);
            });
        }
        setModel(newModel) {
            // clean up
            this._disposeOnNewModel.clear();
            this._model = newModel;
            if (this._model) {
                return this._onNewModel();
            }
            return Promise.resolve();
        }
        _onNewModel() {
            if (!this._model) {
                return Promise.resolve(undefined);
            }
            if (this._model.isEmpty) {
                this.setTitle('');
                this._messageContainer.innerText = nls.localize(993, "No results");
                dom.show(this._messageContainer);
                return Promise.resolve(undefined);
            }
            dom.hide(this._messageContainer);
            this._decorationsManager = new DecorationsManager(this._preview, this._model);
            this._disposeOnNewModel.add(this._decorationsManager);
            // listen on model changes
            this._disposeOnNewModel.add(this._model.onDidChangeReferenceRange(reference => this._tree.rerender(reference)));
            // listen on editor
            this._disposeOnNewModel.add(this._preview.onMouseDown(e => {
                const { event, target } = e;
                if (event.detail !== 2) {
                    return;
                }
                const element = this._getFocusedReference();
                if (!element) {
                    return;
                }
                this._onDidSelectReference.fire({
                    element: { uri: element.uri, range: target.range },
                    kind: (event.ctrlKey || event.metaKey || event.altKey) ? 'side' : 'open',
                    source: 'editor'
                });
            }));
            // make sure things are rendered
            this.container.classList.add('results-loaded');
            dom.show(this._treeContainer);
            dom.show(this._previewContainer);
            this._splitView.layout(this._dim.width);
            this.focusOnReferenceTree();
            // pick input and a reference to begin with
            return this._tree.setInput(this._model.groups.length === 1 ? this._model.groups[0] : this._model);
        }
        _getFocusedReference() {
            const [element] = this._tree.getFocus();
            if (element instanceof referencesModel_1.OneReference) {
                return element;
            }
            else if (element instanceof referencesModel_1.FileReferences) {
                if (element.children.length > 0) {
                    return element.children[0];
                }
            }
            return undefined;
        }
        async revealReference(reference) {
            await this._revealReference(reference, false);
            this._onDidSelectReference.fire({ element: reference, kind: 'goto', source: 'tree' });
        }
        async _revealReference(reference, revealParent) {
            // check if there is anything to do...
            if (this._revealedReference === reference) {
                return;
            }
            this._revealedReference = reference;
            // Update widget header
            if (reference.uri.scheme !== network_1.Schemas.inMemory) {
                this.setTitle((0, resources_1.basenameOrAuthority)(reference.uri), this._uriLabel.getUriLabel((0, resources_1.dirname)(reference.uri)));
            }
            else {
                this.setTitle(nls.localize(994, "References"));
            }
            const promise = this._textModelResolverService.createModelReference(reference.uri);
            if (this._tree.getInput() === reference.parent) {
                this._tree.reveal(reference);
            }
            else {
                if (revealParent) {
                    this._tree.reveal(reference.parent);
                }
                await this._tree.expand(reference.parent);
                this._tree.reveal(reference);
            }
            const ref = await promise;
            if (!this._model) {
                // disposed
                ref.dispose();
                return;
            }
            (0, lifecycle_1.dispose)(this._previewModelReference);
            // show in editor
            const model = ref.object;
            if (model) {
                const scrollType = this._preview.getModel() === model.textEditorModel ? 0 /* ScrollType.Smooth */ : 1 /* ScrollType.Immediate */;
                const sel = range_1.Range.lift(reference.range).collapseToStart();
                this._previewModelReference = ref;
                this._preview.setModel(model.textEditorModel);
                this._preview.setSelection(sel);
                this._preview.revealRangeInCenter(sel, scrollType);
            }
            else {
                this._preview.setModel(this._previewNotAvailableMessage);
                ref.dispose();
            }
        }
    };
    exports.ReferenceWidget = ReferenceWidget;
    exports.ReferenceWidget = ReferenceWidget = __decorate([
        __param(3, themeService_1.IThemeService),
        __param(4, resolverService_1.ITextModelService),
        __param(5, instantiation_1.IInstantiationService),
        __param(6, peekView.IPeekViewService),
        __param(7, label_1.ILabelService),
        __param(8, keybinding_1.IKeybindingService)
    ], ReferenceWidget);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[428/*vs/editor/contrib/gotoSymbol/browser/peek/referencesController*/], __M([1/*require*/,0/*exports*/,14/*vs/base/common/async*/,8/*vs/base/common/errors*/,72/*vs/base/common/keyCodes*/,2/*vs/base/common/lifecycle*/,34/*vs/editor/browser/services/codeEditorService*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/,158/*vs/editor/contrib/peekView/browser/peekView*/,3/*vs/nls*/,24/*vs/platform/commands/common/commands*/,28/*vs/platform/configuration/common/configuration*/,12/*vs/platform/contextkey/common/contextkey*/,7/*vs/platform/instantiation/common/instantiation*/,121/*vs/platform/keybinding/common/keybindingsRegistry*/,216/*vs/platform/list/browser/listService*/,50/*vs/platform/notification/common/notification*/,101/*vs/platform/storage/common/storage*/,178/*vs/editor/contrib/gotoSymbol/browser/referencesModel*/,844/*vs/editor/contrib/gotoSymbol/browser/peek/referencesWidget*/,20/*vs/editor/common/editorContextKeys*/,179/*vs/platform/contextkey/common/contextkeys*/]), function (require, exports, async_1, errors_1, keyCodes_1, lifecycle_1, codeEditorService_1, position_1, range_1, peekView_1, nls, commands_1, configuration_1, contextkey_1, instantiation_1, keybindingsRegistry_1, listService_1, notification_1, storage_1, referencesModel_1, referencesWidget_1, editorContextKeys_1, contextkeys_1) {
    "use strict";
    var ReferencesController_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ReferencesController = exports.ctxReferenceSearchVisible = void 0;
    exports.ctxReferenceSearchVisible = new contextkey_1.RawContextKey('referenceSearchVisible', false, nls.localize(986, "Whether reference peek is visible, like 'Peek References' or 'Peek Definition'"));
    let ReferencesController = class ReferencesController {
        static { ReferencesController_1 = this; }
        static { this.ID = 'editor.contrib.referencesController'; }
        static get(editor) {
            return editor.getContribution(ReferencesController_1.ID);
        }
        constructor(_defaultTreeKeyboardSupport, _editor, contextKeyService, _editorService, _notificationService, _instantiationService, _storageService, _configurationService) {
            this._defaultTreeKeyboardSupport = _defaultTreeKeyboardSupport;
            this._editor = _editor;
            this._editorService = _editorService;
            this._notificationService = _notificationService;
            this._instantiationService = _instantiationService;
            this._storageService = _storageService;
            this._configurationService = _configurationService;
            this._disposables = new lifecycle_1.DisposableStore();
            this._requestIdPool = 0;
            this._ignoreModelChangeEvent = false;
            this._referenceSearchVisible = exports.ctxReferenceSearchVisible.bindTo(contextKeyService);
        }
        dispose() {
            this._referenceSearchVisible.reset();
            this._disposables.dispose();
            this._widget?.dispose();
            this._model?.dispose();
            this._widget = undefined;
            this._model = undefined;
        }
        toggleWidget(range, modelPromise, peekMode) {
            // close current widget and return early is position didn't change
            let widgetPosition;
            if (this._widget) {
                widgetPosition = this._widget.position;
            }
            this.closeWidget();
            if (!!widgetPosition && range.containsPosition(widgetPosition)) {
                return;
            }
            this._peekMode = peekMode;
            this._referenceSearchVisible.set(true);
            // close the widget on model/mode changes
            this._disposables.add(this._editor.onDidChangeModelLanguage(() => { this.closeWidget(); }));
            this._disposables.add(this._editor.onDidChangeModel(() => {
                if (!this._ignoreModelChangeEvent) {
                    this.closeWidget();
                }
            }));
            const storageKey = 'peekViewLayout';
            const data = referencesWidget_1.LayoutData.fromJSON(this._storageService.get(storageKey, 0 /* StorageScope.PROFILE */, '{}'));
            this._widget = this._instantiationService.createInstance(referencesWidget_1.ReferenceWidget, this._editor, this._defaultTreeKeyboardSupport, data);
            this._widget.setTitle(nls.localize(987, "Loading..."));
            this._widget.show(range);
            this._disposables.add(this._widget.onDidClose(() => {
                modelPromise.cancel();
                if (this._widget) {
                    this._storageService.store(storageKey, JSON.stringify(this._widget.layoutData), 0 /* StorageScope.PROFILE */, 1 /* StorageTarget.MACHINE */);
                    if (!this._widget.isClosing) {
                        // to prevent calling this too many times, check whether it was already closing.
                        this.closeWidget();
                    }
                    this._widget = undefined;
                }
                else {
                    this.closeWidget();
                }
            }));
            this._disposables.add(this._widget.onDidSelectReference(event => {
                const { element, kind } = event;
                if (!element) {
                    return;
                }
                switch (kind) {
                    case 'open':
                        if (event.source !== 'editor' || !this._configurationService.getValue('editor.stablePeek')) {
                            // when stable peek is configured we don't close
                            // the peek window on selecting the editor
                            this.openReference(element, false, false);
                        }
                        break;
                    case 'side':
                        this.openReference(element, true, false);
                        break;
                    case 'goto':
                        if (peekMode) {
                            this._gotoReference(element, true);
                        }
                        else {
                            this.openReference(element, false, true);
                        }
                        break;
                }
            }));
            const requestId = ++this._requestIdPool;
            modelPromise.then(model => {
                // still current request? widget still open?
                if (requestId !== this._requestIdPool || !this._widget) {
                    model.dispose();
                    return undefined;
                }
                this._model?.dispose();
                this._model = model;
                // show widget
                return this._widget.setModel(this._model).then(() => {
                    if (this._widget && this._model && this._editor.hasModel()) { // might have been closed
                        // set title
                        if (!this._model.isEmpty) {
                            this._widget.setMetaTitle(nls.localize(988, "{0} ({1})", this._model.title, this._model.references.length));
                        }
                        else {
                            this._widget.setMetaTitle('');
                        }
                        // set 'best' selection
                        const uri = this._editor.getModel().uri;
                        const pos = new position_1.Position(range.startLineNumber, range.startColumn);
                        const selection = this._model.nearestReference(uri, pos);
                        if (selection) {
                            return this._widget.setSelection(selection).then(() => {
                                if (this._widget && this._editor.getOption(87 /* EditorOption.peekWidgetDefaultFocus */) === 'editor') {
                                    this._widget.focusOnPreviewEditor();
                                }
                            });
                        }
                    }
                    return undefined;
                });
            }, error => {
                this._notificationService.error(error);
            });
        }
        changeFocusBetweenPreviewAndReferences() {
            if (!this._widget) {
                // can be called while still resolving...
                return;
            }
            if (this._widget.isPreviewEditorFocused()) {
                this._widget.focusOnReferenceTree();
            }
            else {
                this._widget.focusOnPreviewEditor();
            }
        }
        async goToNextOrPreviousReference(fwd) {
            if (!this._editor.hasModel() || !this._model || !this._widget) {
                // can be called while still resolving...
                return;
            }
            const currentPosition = this._widget.position;
            if (!currentPosition) {
                return;
            }
            const source = this._model.nearestReference(this._editor.getModel().uri, currentPosition);
            if (!source) {
                return;
            }
            const target = this._model.nextOrPreviousReference(source, fwd);
            const editorFocus = this._editor.hasTextFocus();
            const previewEditorFocus = this._widget.isPreviewEditorFocused();
            await this._widget.setSelection(target);
            await this._gotoReference(target, false);
            if (editorFocus) {
                this._editor.focus();
            }
            else if (this._widget && previewEditorFocus) {
                this._widget.focusOnPreviewEditor();
            }
        }
        async revealReference(reference) {
            if (!this._editor.hasModel() || !this._model || !this._widget) {
                // can be called while still resolving...
                return;
            }
            await this._widget.revealReference(reference);
        }
        closeWidget(focusEditor = true) {
            this._widget?.dispose();
            this._model?.dispose();
            this._referenceSearchVisible.reset();
            this._disposables.clear();
            this._widget = undefined;
            this._model = undefined;
            if (focusEditor) {
                this._editor.focus();
            }
            this._requestIdPool += 1; // Cancel pending requests
        }
        _gotoReference(ref, pinned) {
            this._widget?.hide();
            this._ignoreModelChangeEvent = true;
            const range = range_1.Range.lift(ref.range).collapseToStart();
            return this._editorService.openCodeEditor({
                resource: ref.uri,
                options: { selection: range, selectionSource: "code.jump" /* TextEditorSelectionSource.JUMP */, pinned }
            }, this._editor).then(openedEditor => {
                this._ignoreModelChangeEvent = false;
                if (!openedEditor || !this._widget) {
                    // something went wrong...
                    this.closeWidget();
                    return;
                }
                if (this._editor === openedEditor) {
                    //
                    this._widget.show(range);
                    this._widget.focusOnReferenceTree();
                }
                else {
                    // we opened a different editor instance which means a different controller instance.
                    // therefore we stop with this controller and continue with the other
                    const other = ReferencesController_1.get(openedEditor);
                    const model = this._model.clone();
                    this.closeWidget();
                    openedEditor.focus();
                    other?.toggleWidget(range, (0, async_1.createCancelablePromise)(_ => Promise.resolve(model)), this._peekMode ?? false);
                }
            }, (err) => {
                this._ignoreModelChangeEvent = false;
                (0, errors_1.onUnexpectedError)(err);
            });
        }
        openReference(ref, sideBySide, pinned) {
            // clear stage
            if (!sideBySide) {
                this.closeWidget();
            }
            const { uri, range } = ref;
            this._editorService.openCodeEditor({
                resource: uri,
                options: { selection: range, selectionSource: "code.jump" /* TextEditorSelectionSource.JUMP */, pinned }
            }, this._editor, sideBySide);
        }
    };
    exports.ReferencesController = ReferencesController;
    exports.ReferencesController = ReferencesController = ReferencesController_1 = __decorate([
        __param(2, contextkey_1.IContextKeyService),
        __param(3, codeEditorService_1.ICodeEditorService),
        __param(4, notification_1.INotificationService),
        __param(5, instantiation_1.IInstantiationService),
        __param(6, storage_1.IStorageService),
        __param(7, configuration_1.IConfigurationService)
    ], ReferencesController);
    function withController(accessor, fn) {
        const outerEditor = (0, peekView_1.getOuterEditor)(accessor);
        if (!outerEditor) {
            return;
        }
        const controller = ReferencesController.get(outerEditor);
        if (controller) {
            fn(controller);
        }
    }
    keybindingsRegistry_1.KeybindingsRegistry.registerCommandAndKeybindingRule({
        id: 'togglePeekWidgetFocus',
        weight: 100 /* KeybindingWeight.EditorContrib */,
        primary: (0, keyCodes_1.KeyChord)(2048 /* KeyMod.CtrlCmd */ | 41 /* KeyCode.KeyK */, 60 /* KeyCode.F2 */),
        when: contextkey_1.ContextKeyExpr.or(exports.ctxReferenceSearchVisible, peekView_1.PeekContext.inPeekEditor),
        handler(accessor) {
            withController(accessor, controller => {
                controller.changeFocusBetweenPreviewAndReferences();
            });
        }
    });
    keybindingsRegistry_1.KeybindingsRegistry.registerCommandAndKeybindingRule({
        id: 'goToNextReference',
        weight: 100 /* KeybindingWeight.EditorContrib */ - 10,
        primary: 62 /* KeyCode.F4 */,
        secondary: [70 /* KeyCode.F12 */],
        when: contextkey_1.ContextKeyExpr.or(exports.ctxReferenceSearchVisible, peekView_1.PeekContext.inPeekEditor),
        handler(accessor) {
            withController(accessor, controller => {
                controller.goToNextOrPreviousReference(true);
            });
        }
    });
    keybindingsRegistry_1.KeybindingsRegistry.registerCommandAndKeybindingRule({
        id: 'goToPreviousReference',
        weight: 100 /* KeybindingWeight.EditorContrib */ - 10,
        primary: 1024 /* KeyMod.Shift */ | 62 /* KeyCode.F4 */,
        secondary: [1024 /* KeyMod.Shift */ | 70 /* KeyCode.F12 */],
        when: contextkey_1.ContextKeyExpr.or(exports.ctxReferenceSearchVisible, peekView_1.PeekContext.inPeekEditor),
        handler(accessor) {
            withController(accessor, controller => {
                controller.goToNextOrPreviousReference(false);
            });
        }
    });
    // commands that aren't needed anymore because there is now ContextKeyExpr.OR
    commands_1.CommandsRegistry.registerCommandAlias('goToNextReferenceFromEmbeddedEditor', 'goToNextReference');
    commands_1.CommandsRegistry.registerCommandAlias('goToPreviousReferenceFromEmbeddedEditor', 'goToPreviousReference');
    // close
    commands_1.CommandsRegistry.registerCommandAlias('closeReferenceSearchEditor', 'closeReferenceSearch');
    commands_1.CommandsRegistry.registerCommand('closeReferenceSearch', accessor => withController(accessor, controller => controller.closeWidget()));
    keybindingsRegistry_1.KeybindingsRegistry.registerKeybindingRule({
        id: 'closeReferenceSearch',
        weight: 100 /* KeybindingWeight.EditorContrib */ - 101,
        primary: 9 /* KeyCode.Escape */,
        secondary: [1024 /* KeyMod.Shift */ | 9 /* KeyCode.Escape */],
        when: contextkey_1.ContextKeyExpr.and(peekView_1.PeekContext.inPeekEditor, contextkey_1.ContextKeyExpr.not('config.editor.stablePeek'))
    });
    keybindingsRegistry_1.KeybindingsRegistry.registerKeybindingRule({
        id: 'closeReferenceSearch',
        weight: 200 /* KeybindingWeight.WorkbenchContrib */ + 50,
        primary: 9 /* KeyCode.Escape */,
        secondary: [1024 /* KeyMod.Shift */ | 9 /* KeyCode.Escape */],
        when: contextkey_1.ContextKeyExpr.and(exports.ctxReferenceSearchVisible, contextkey_1.ContextKeyExpr.not('config.editor.stablePeek'), contextkey_1.ContextKeyExpr.or(editorContextKeys_1.EditorContextKeys.editorTextFocus, contextkeys_1.InputFocusedContext.negate()))
    });
    keybindingsRegistry_1.KeybindingsRegistry.registerCommandAndKeybindingRule({
        id: 'revealReference',
        weight: 200 /* KeybindingWeight.WorkbenchContrib */,
        primary: 3 /* KeyCode.Enter */,
        mac: {
            primary: 3 /* KeyCode.Enter */,
            secondary: [2048 /* KeyMod.CtrlCmd */ | 18 /* KeyCode.DownArrow */]
        },
        when: contextkey_1.ContextKeyExpr.and(exports.ctxReferenceSearchVisible, listService_1.WorkbenchListFocusContextKey, listService_1.WorkbenchTreeElementCanCollapse.negate(), listService_1.WorkbenchTreeElementCanExpand.negate()),
        handler(accessor) {
            const listService = accessor.get(listService_1.IListService);
            const focus = listService.lastFocusedList?.getFocus();
            if (Array.isArray(focus) && focus[0] instanceof referencesModel_1.OneReference) {
                withController(accessor, controller => controller.revealReference(focus[0]));
            }
        }
    });
    keybindingsRegistry_1.KeybindingsRegistry.registerCommandAndKeybindingRule({
        id: 'openReferenceToSide',
        weight: 100 /* KeybindingWeight.EditorContrib */,
        primary: 2048 /* KeyMod.CtrlCmd */ | 3 /* KeyCode.Enter */,
        mac: {
            primary: 256 /* KeyMod.WinCtrl */ | 3 /* KeyCode.Enter */
        },
        when: contextkey_1.ContextKeyExpr.and(exports.ctxReferenceSearchVisible, listService_1.WorkbenchListFocusContextKey, listService_1.WorkbenchTreeElementCanCollapse.negate(), listService_1.WorkbenchTreeElementCanExpand.negate()),
        handler(accessor) {
            const listService = accessor.get(listService_1.IListService);
            const focus = listService.lastFocusedList?.getFocus();
            if (Array.isArray(focus) && focus[0] instanceof referencesModel_1.OneReference) {
                withController(accessor, controller => controller.openReference(focus[0], true, true));
            }
        }
    });
    commands_1.CommandsRegistry.registerCommand('openReference', (accessor) => {
        const listService = accessor.get(listService_1.IListService);
        const focus = listService.lastFocusedList?.getFocus();
        if (Array.isArray(focus) && focus[0] instanceof referencesModel_1.OneReference) {
            withController(accessor, controller => controller.openReference(focus[0], false, true));
        }
    });
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[291/*vs/editor/contrib/gotoSymbol/browser/goToCommands*/], __M([1/*require*/,0/*exports*/,46/*vs/base/browser/ui/aria/aria*/,14/*vs/base/common/async*/,72/*vs/base/common/keyCodes*/,19/*vs/base/common/types*/,22/*vs/base/common/uri*/,122/*vs/editor/contrib/editorState/browser/editorState*/,168/*vs/editor/browser/editorBrowser*/,15/*vs/editor/browser/editorExtensions*/,34/*vs/editor/browser/services/codeEditorService*/,125/*vs/editor/browser/widget/codeEditor/embeddedCodeEditorWidget*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/,20/*vs/editor/common/editorContextKeys*/,27/*vs/editor/common/languages*/,428/*vs/editor/contrib/gotoSymbol/browser/peek/referencesController*/,178/*vs/editor/contrib/gotoSymbol/browser/referencesModel*/,736/*vs/editor/contrib/gotoSymbol/browser/symbolNavigation*/,184/*vs/editor/contrib/message/browser/messageController*/,158/*vs/editor/contrib/peekView/browser/peekView*/,3/*vs/nls*/,29/*vs/platform/actions/common/actions*/,24/*vs/platform/commands/common/commands*/,12/*vs/platform/contextkey/common/contextkey*/,7/*vs/platform/instantiation/common/instantiation*/,50/*vs/platform/notification/common/notification*/,96/*vs/platform/progress/common/progress*/,277/*vs/editor/contrib/gotoSymbol/browser/goToSymbol*/,17/*vs/editor/common/services/languageFeatures*/,53/*vs/base/common/iterator*/,179/*vs/platform/contextkey/common/contextkeys*/]), function (require, exports, aria_1, async_1, keyCodes_1, types_1, uri_1, editorState_1, editorBrowser_1, editorExtensions_1, codeEditorService_1, embeddedCodeEditorWidget_1, corePosition, range_1, editorContextKeys_1, languages_1, referencesController_1, referencesModel_1, symbolNavigation_1, messageController_1, peekView_1, nls, actions_1, commands_1, contextkey_1, instantiation_1, notification_1, progress_1, goToSymbol_1, languageFeatures_1, iterator_1, contextkeys_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DefinitionAction = exports.SymbolNavigationAction = exports.SymbolNavigationAnchor = void 0;
    actions_1.MenuRegistry.appendMenuItem(actions_1.MenuId.EditorContext, {
        submenu: actions_1.MenuId.EditorContextPeek,
        title: nls.localize(946, "Peek"),
        group: 'navigation',
        order: 100
    });
    class SymbolNavigationAnchor {
        static is(thing) {
            if (!thing || typeof thing !== 'object') {
                return false;
            }
            if (thing instanceof SymbolNavigationAnchor) {
                return true;
            }
            if (corePosition.Position.isIPosition(thing.position) && thing.model) {
                return true;
            }
            return false;
        }
        constructor(model, position) {
            this.model = model;
            this.position = position;
        }
    }
    exports.SymbolNavigationAnchor = SymbolNavigationAnchor;
    class SymbolNavigationAction extends editorExtensions_1.EditorAction2 {
        static { this._allSymbolNavigationCommands = new Map(); }
        static { this._activeAlternativeCommands = new Set(); }
        static all() {
            return SymbolNavigationAction._allSymbolNavigationCommands.values();
        }
        static _patchConfig(opts) {
            const result = { ...opts, f1: true };
            // patch context menu when clause
            if (result.menu) {
                for (const item of iterator_1.Iterable.wrap(result.menu)) {
                    if (item.id === actions_1.MenuId.EditorContext || item.id === actions_1.MenuId.EditorContextPeek) {
                        item.when = contextkey_1.ContextKeyExpr.and(opts.precondition, item.when);
                    }
                }
            }
            return result;
        }
        constructor(configuration, opts) {
            super(SymbolNavigationAction._patchConfig(opts));
            this.configuration = configuration;
            SymbolNavigationAction._allSymbolNavigationCommands.set(opts.id, this);
        }
        runEditorCommand(accessor, editor, arg, range) {
            if (!editor.hasModel()) {
                return Promise.resolve(undefined);
            }
            const notificationService = accessor.get(notification_1.INotificationService);
            const editorService = accessor.get(codeEditorService_1.ICodeEditorService);
            const progressService = accessor.get(progress_1.IEditorProgressService);
            const symbolNavService = accessor.get(symbolNavigation_1.ISymbolNavigationService);
            const languageFeaturesService = accessor.get(languageFeatures_1.ILanguageFeaturesService);
            const instaService = accessor.get(instantiation_1.IInstantiationService);
            const model = editor.getModel();
            const position = editor.getPosition();
            const anchor = SymbolNavigationAnchor.is(arg) ? arg : new SymbolNavigationAnchor(model, position);
            const cts = new editorState_1.EditorStateCancellationTokenSource(editor, 1 /* CodeEditorStateFlag.Value */ | 4 /* CodeEditorStateFlag.Position */);
            const promise = (0, async_1.raceCancellation)(this._getLocationModel(languageFeaturesService, anchor.model, anchor.position, cts.token), cts.token).then(async (references) => {
                if (!references || cts.token.isCancellationRequested) {
                    return;
                }
                (0, aria_1.alert)(references.ariaMessage);
                let altAction;
                if (references.referenceAt(model.uri, position)) {
                    const altActionId = this._getAlternativeCommand(editor);
                    if (!SymbolNavigationAction._activeAlternativeCommands.has(altActionId) && SymbolNavigationAction._allSymbolNavigationCommands.has(altActionId)) {
                        altAction = SymbolNavigationAction._allSymbolNavigationCommands.get(altActionId);
                    }
                }
                const referenceCount = references.references.length;
                if (referenceCount === 0) {
                    // no result -> show message
                    if (!this.configuration.muteMessage) {
                        const info = model.getWordAtPosition(position);
                        messageController_1.MessageController.get(editor)?.showMessage(this._getNoResultFoundMessage(info), position);
                    }
                }
                else if (referenceCount === 1 && altAction) {
                    // already at the only result, run alternative
                    SymbolNavigationAction._activeAlternativeCommands.add(this.desc.id);
                    instaService.invokeFunction((accessor) => altAction.runEditorCommand(accessor, editor, arg, range).finally(() => {
                        SymbolNavigationAction._activeAlternativeCommands.delete(this.desc.id);
                    }));
                }
                else {
                    // normal results handling
                    return this._onResult(editorService, symbolNavService, editor, references, range);
                }
            }, (err) => {
                // report an error
                notificationService.error(err);
            }).finally(() => {
                cts.dispose();
            });
            progressService.showWhile(promise, 250);
            return promise;
        }
        async _onResult(editorService, symbolNavService, editor, model, range) {
            const gotoLocation = this._getGoToPreference(editor);
            if (!(editor instanceof embeddedCodeEditorWidget_1.EmbeddedCodeEditorWidget) && (this.configuration.openInPeek || (gotoLocation === 'peek' && model.references.length > 1))) {
                this._openInPeek(editor, model, range);
            }
            else {
                const next = model.firstReference();
                const peek = model.references.length > 1 && gotoLocation === 'gotoAndPeek';
                const targetEditor = await this._openReference(editor, editorService, next, this.configuration.openToSide, !peek);
                if (peek && targetEditor) {
                    this._openInPeek(targetEditor, model, range);
                }
                else {
                    model.dispose();
                }
                // keep remaining locations around when using
                // 'goto'-mode
                if (gotoLocation === 'goto') {
                    symbolNavService.put(next);
                }
            }
        }
        async _openReference(editor, editorService, reference, sideBySide, highlight) {
            // range is the target-selection-range when we have one
            // and the fallback is the 'full' range
            let range = undefined;
            if ((0, languages_1.isLocationLink)(reference)) {
                range = reference.targetSelectionRange;
            }
            if (!range) {
                range = reference.range;
            }
            if (!range) {
                return undefined;
            }
            const targetEditor = await editorService.openCodeEditor({
                resource: reference.uri,
                options: {
                    selection: range_1.Range.collapseToStart(range),
                    selectionRevealType: 3 /* TextEditorSelectionRevealType.NearTopIfOutsideViewport */,
                    selectionSource: "code.jump" /* TextEditorSelectionSource.JUMP */
                }
            }, editor, sideBySide);
            if (!targetEditor) {
                return undefined;
            }
            if (highlight) {
                const modelNow = targetEditor.getModel();
                const decorations = targetEditor.createDecorationsCollection([{ range, options: { description: 'symbol-navigate-action-highlight', className: 'symbolHighlight' } }]);
                setTimeout(() => {
                    if (targetEditor.getModel() === modelNow) {
                        decorations.clear();
                    }
                }, 350);
            }
            return targetEditor;
        }
        _openInPeek(target, model, range) {
            const controller = referencesController_1.ReferencesController.get(target);
            if (controller && target.hasModel()) {
                controller.toggleWidget(range ?? target.getSelection(), (0, async_1.createCancelablePromise)(_ => Promise.resolve(model)), this.configuration.openInPeek);
            }
            else {
                model.dispose();
            }
        }
    }
    exports.SymbolNavigationAction = SymbolNavigationAction;
    //#region --- DEFINITION
    class DefinitionAction extends SymbolNavigationAction {
        async _getLocationModel(languageFeaturesService, model, position, token) {
            return new referencesModel_1.ReferencesModel(await (0, goToSymbol_1.getDefinitionsAtPosition)(languageFeaturesService.definitionProvider, model, position, false, token), nls.localize(947, 'Definitions'));
        }
        _getNoResultFoundMessage(info) {
            return info && info.word
                ? nls.localize(948, "No definition found for '{0}'", info.word)
                : nls.localize(949, "No definition found");
        }
        _getAlternativeCommand(editor) {
            return editor.getOption(58 /* EditorOption.gotoLocation */).alternativeDefinitionCommand;
        }
        _getGoToPreference(editor) {
            return editor.getOption(58 /* EditorOption.gotoLocation */).multipleDefinitions;
        }
    }
    exports.DefinitionAction = DefinitionAction;
    (0, actions_1.registerAction2)(class GoToDefinitionAction extends DefinitionAction {
        static { this.id = 'editor.action.revealDefinition'; }
        constructor() {
            super({
                openToSide: false,
                openInPeek: false,
                muteMessage: false
            }, {
                id: GoToDefinitionAction.id,
                title: {
                    ...nls.localize2(973, "Go to Definition"),
                    mnemonicTitle: nls.localize(950, "Go to &&Definition"),
                },
                precondition: editorContextKeys_1.EditorContextKeys.hasDefinitionProvider,
                keybinding: [{
                        when: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                        primary: 70 /* KeyCode.F12 */,
                        weight: 100 /* KeybindingWeight.EditorContrib */
                    }, {
                        when: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.editorTextFocus, contextkeys_1.IsWebContext),
                        primary: 2048 /* KeyMod.CtrlCmd */ | 70 /* KeyCode.F12 */,
                        weight: 100 /* KeybindingWeight.EditorContrib */
                    }],
                menu: [{
                        id: actions_1.MenuId.EditorContext,
                        group: 'navigation',
                        order: 1.1
                    }, {
                        id: actions_1.MenuId.MenubarGoMenu,
                        precondition: null,
                        group: '4_symbol_nav',
                        order: 2,
                    }]
            });
            commands_1.CommandsRegistry.registerCommandAlias('editor.action.goToDeclaration', GoToDefinitionAction.id);
        }
    });
    (0, actions_1.registerAction2)(class OpenDefinitionToSideAction extends DefinitionAction {
        static { this.id = 'editor.action.revealDefinitionAside'; }
        constructor() {
            super({
                openToSide: true,
                openInPeek: false,
                muteMessage: false
            }, {
                id: OpenDefinitionToSideAction.id,
                title: nls.localize2(974, "Open Definition to the Side"),
                precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.hasDefinitionProvider, editorContextKeys_1.EditorContextKeys.isInEmbeddedEditor.toNegated()),
                keybinding: [{
                        when: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                        primary: (0, keyCodes_1.KeyChord)(2048 /* KeyMod.CtrlCmd */ | 41 /* KeyCode.KeyK */, 70 /* KeyCode.F12 */),
                        weight: 100 /* KeybindingWeight.EditorContrib */
                    }, {
                        when: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.editorTextFocus, contextkeys_1.IsWebContext),
                        primary: (0, keyCodes_1.KeyChord)(2048 /* KeyMod.CtrlCmd */ | 41 /* KeyCode.KeyK */, 2048 /* KeyMod.CtrlCmd */ | 70 /* KeyCode.F12 */),
                        weight: 100 /* KeybindingWeight.EditorContrib */
                    }]
            });
            commands_1.CommandsRegistry.registerCommandAlias('editor.action.openDeclarationToTheSide', OpenDefinitionToSideAction.id);
        }
    });
    (0, actions_1.registerAction2)(class PeekDefinitionAction extends DefinitionAction {
        static { this.id = 'editor.action.peekDefinition'; }
        constructor() {
            super({
                openToSide: false,
                openInPeek: true,
                muteMessage: false
            }, {
                id: PeekDefinitionAction.id,
                title: nls.localize2(975, "Peek Definition"),
                precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.hasDefinitionProvider, peekView_1.PeekContext.notInPeekEditor, editorContextKeys_1.EditorContextKeys.isInEmbeddedEditor.toNegated()),
                keybinding: {
                    when: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    primary: 512 /* KeyMod.Alt */ | 70 /* KeyCode.F12 */,
                    linux: { primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 68 /* KeyCode.F10 */ },
                    weight: 100 /* KeybindingWeight.EditorContrib */
                },
                menu: {
                    id: actions_1.MenuId.EditorContextPeek,
                    group: 'peek',
                    order: 2
                }
            });
            commands_1.CommandsRegistry.registerCommandAlias('editor.action.previewDeclaration', PeekDefinitionAction.id);
        }
    });
    //#endregion
    //#region --- DECLARATION
    class DeclarationAction extends SymbolNavigationAction {
        async _getLocationModel(languageFeaturesService, model, position, token) {
            return new referencesModel_1.ReferencesModel(await (0, goToSymbol_1.getDeclarationsAtPosition)(languageFeaturesService.declarationProvider, model, position, false, token), nls.localize(951, 'Declarations'));
        }
        _getNoResultFoundMessage(info) {
            return info && info.word
                ? nls.localize(952, "No declaration found for '{0}'", info.word)
                : nls.localize(953, "No declaration found");
        }
        _getAlternativeCommand(editor) {
            return editor.getOption(58 /* EditorOption.gotoLocation */).alternativeDeclarationCommand;
        }
        _getGoToPreference(editor) {
            return editor.getOption(58 /* EditorOption.gotoLocation */).multipleDeclarations;
        }
    }
    (0, actions_1.registerAction2)(class GoToDeclarationAction extends DeclarationAction {
        static { this.id = 'editor.action.revealDeclaration'; }
        constructor() {
            super({
                openToSide: false,
                openInPeek: false,
                muteMessage: false
            }, {
                id: GoToDeclarationAction.id,
                title: {
                    ...nls.localize2(976, "Go to Declaration"),
                    mnemonicTitle: nls.localize(954, "Go to &&Declaration"),
                },
                precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.hasDeclarationProvider, editorContextKeys_1.EditorContextKeys.isInEmbeddedEditor.toNegated()),
                menu: [{
                        id: actions_1.MenuId.EditorContext,
                        group: 'navigation',
                        order: 1.3
                    }, {
                        id: actions_1.MenuId.MenubarGoMenu,
                        precondition: null,
                        group: '4_symbol_nav',
                        order: 3,
                    }],
            });
        }
        _getNoResultFoundMessage(info) {
            return info && info.word
                ? nls.localize(955, "No declaration found for '{0}'", info.word)
                : nls.localize(956, "No declaration found");
        }
    });
    (0, actions_1.registerAction2)(class PeekDeclarationAction extends DeclarationAction {
        constructor() {
            super({
                openToSide: false,
                openInPeek: true,
                muteMessage: false
            }, {
                id: 'editor.action.peekDeclaration',
                title: nls.localize2(977, "Peek Declaration"),
                precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.hasDeclarationProvider, peekView_1.PeekContext.notInPeekEditor, editorContextKeys_1.EditorContextKeys.isInEmbeddedEditor.toNegated()),
                menu: {
                    id: actions_1.MenuId.EditorContextPeek,
                    group: 'peek',
                    order: 3
                }
            });
        }
    });
    //#endregion
    //#region --- TYPE DEFINITION
    class TypeDefinitionAction extends SymbolNavigationAction {
        async _getLocationModel(languageFeaturesService, model, position, token) {
            return new referencesModel_1.ReferencesModel(await (0, goToSymbol_1.getTypeDefinitionsAtPosition)(languageFeaturesService.typeDefinitionProvider, model, position, false, token), nls.localize(957, 'Type Definitions'));
        }
        _getNoResultFoundMessage(info) {
            return info && info.word
                ? nls.localize(958, "No type definition found for '{0}'", info.word)
                : nls.localize(959, "No type definition found");
        }
        _getAlternativeCommand(editor) {
            return editor.getOption(58 /* EditorOption.gotoLocation */).alternativeTypeDefinitionCommand;
        }
        _getGoToPreference(editor) {
            return editor.getOption(58 /* EditorOption.gotoLocation */).multipleTypeDefinitions;
        }
    }
    (0, actions_1.registerAction2)(class GoToTypeDefinitionAction extends TypeDefinitionAction {
        static { this.ID = 'editor.action.goToTypeDefinition'; }
        constructor() {
            super({
                openToSide: false,
                openInPeek: false,
                muteMessage: false
            }, {
                id: GoToTypeDefinitionAction.ID,
                title: {
                    ...nls.localize2(978, "Go to Type Definition"),
                    mnemonicTitle: nls.localize(960, "Go to &&Type Definition"),
                },
                precondition: editorContextKeys_1.EditorContextKeys.hasTypeDefinitionProvider,
                keybinding: {
                    when: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    primary: 0,
                    weight: 100 /* KeybindingWeight.EditorContrib */
                },
                menu: [{
                        id: actions_1.MenuId.EditorContext,
                        group: 'navigation',
                        order: 1.4
                    }, {
                        id: actions_1.MenuId.MenubarGoMenu,
                        precondition: null,
                        group: '4_symbol_nav',
                        order: 3,
                    }]
            });
        }
    });
    (0, actions_1.registerAction2)(class PeekTypeDefinitionAction extends TypeDefinitionAction {
        static { this.ID = 'editor.action.peekTypeDefinition'; }
        constructor() {
            super({
                openToSide: false,
                openInPeek: true,
                muteMessage: false
            }, {
                id: PeekTypeDefinitionAction.ID,
                title: nls.localize2(979, "Peek Type Definition"),
                precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.hasTypeDefinitionProvider, peekView_1.PeekContext.notInPeekEditor, editorContextKeys_1.EditorContextKeys.isInEmbeddedEditor.toNegated()),
                menu: {
                    id: actions_1.MenuId.EditorContextPeek,
                    group: 'peek',
                    order: 4
                }
            });
        }
    });
    //#endregion
    //#region --- IMPLEMENTATION
    class ImplementationAction extends SymbolNavigationAction {
        async _getLocationModel(languageFeaturesService, model, position, token) {
            return new referencesModel_1.ReferencesModel(await (0, goToSymbol_1.getImplementationsAtPosition)(languageFeaturesService.implementationProvider, model, position, false, token), nls.localize(961, 'Implementations'));
        }
        _getNoResultFoundMessage(info) {
            return info && info.word
                ? nls.localize(962, "No implementation found for '{0}'", info.word)
                : nls.localize(963, "No implementation found");
        }
        _getAlternativeCommand(editor) {
            return editor.getOption(58 /* EditorOption.gotoLocation */).alternativeImplementationCommand;
        }
        _getGoToPreference(editor) {
            return editor.getOption(58 /* EditorOption.gotoLocation */).multipleImplementations;
        }
    }
    (0, actions_1.registerAction2)(class GoToImplementationAction extends ImplementationAction {
        static { this.ID = 'editor.action.goToImplementation'; }
        constructor() {
            super({
                openToSide: false,
                openInPeek: false,
                muteMessage: false
            }, {
                id: GoToImplementationAction.ID,
                title: {
                    ...nls.localize2(980, "Go to Implementations"),
                    mnemonicTitle: nls.localize(964, "Go to &&Implementations"),
                },
                precondition: editorContextKeys_1.EditorContextKeys.hasImplementationProvider,
                keybinding: {
                    when: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    primary: 2048 /* KeyMod.CtrlCmd */ | 70 /* KeyCode.F12 */,
                    weight: 100 /* KeybindingWeight.EditorContrib */
                },
                menu: [{
                        id: actions_1.MenuId.EditorContext,
                        group: 'navigation',
                        order: 1.45
                    }, {
                        id: actions_1.MenuId.MenubarGoMenu,
                        precondition: null,
                        group: '4_symbol_nav',
                        order: 4,
                    }]
            });
        }
    });
    (0, actions_1.registerAction2)(class PeekImplementationAction extends ImplementationAction {
        static { this.ID = 'editor.action.peekImplementation'; }
        constructor() {
            super({
                openToSide: false,
                openInPeek: true,
                muteMessage: false
            }, {
                id: PeekImplementationAction.ID,
                title: nls.localize2(981, "Peek Implementations"),
                precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.hasImplementationProvider, peekView_1.PeekContext.notInPeekEditor, editorContextKeys_1.EditorContextKeys.isInEmbeddedEditor.toNegated()),
                keybinding: {
                    when: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 70 /* KeyCode.F12 */,
                    weight: 100 /* KeybindingWeight.EditorContrib */
                },
                menu: {
                    id: actions_1.MenuId.EditorContextPeek,
                    group: 'peek',
                    order: 5
                }
            });
        }
    });
    //#endregion
    //#region --- REFERENCES
    class ReferencesAction extends SymbolNavigationAction {
        _getNoResultFoundMessage(info) {
            return info
                ? nls.localize(965, "No references found for '{0}'", info.word)
                : nls.localize(966, "No references found");
        }
        _getAlternativeCommand(editor) {
            return editor.getOption(58 /* EditorOption.gotoLocation */).alternativeReferenceCommand;
        }
        _getGoToPreference(editor) {
            return editor.getOption(58 /* EditorOption.gotoLocation */).multipleReferences;
        }
    }
    (0, actions_1.registerAction2)(class GoToReferencesAction extends ReferencesAction {
        constructor() {
            super({
                openToSide: false,
                openInPeek: false,
                muteMessage: false
            }, {
                id: 'editor.action.goToReferences',
                title: {
                    ...nls.localize2(982, "Go to References"),
                    mnemonicTitle: nls.localize(967, "Go to &&References"),
                },
                precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.hasReferenceProvider, peekView_1.PeekContext.notInPeekEditor, editorContextKeys_1.EditorContextKeys.isInEmbeddedEditor.toNegated()),
                keybinding: {
                    when: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    primary: 1024 /* KeyMod.Shift */ | 70 /* KeyCode.F12 */,
                    weight: 100 /* KeybindingWeight.EditorContrib */
                },
                menu: [{
                        id: actions_1.MenuId.EditorContext,
                        group: 'navigation',
                        order: 1.45
                    }, {
                        id: actions_1.MenuId.MenubarGoMenu,
                        precondition: null,
                        group: '4_symbol_nav',
                        order: 5,
                    }]
            });
        }
        async _getLocationModel(languageFeaturesService, model, position, token) {
            return new referencesModel_1.ReferencesModel(await (0, goToSymbol_1.getReferencesAtPosition)(languageFeaturesService.referenceProvider, model, position, true, false, token), nls.localize(968, 'References'));
        }
    });
    (0, actions_1.registerAction2)(class PeekReferencesAction extends ReferencesAction {
        constructor() {
            super({
                openToSide: false,
                openInPeek: true,
                muteMessage: false
            }, {
                id: 'editor.action.referenceSearch.trigger',
                title: nls.localize2(983, "Peek References"),
                precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.hasReferenceProvider, peekView_1.PeekContext.notInPeekEditor, editorContextKeys_1.EditorContextKeys.isInEmbeddedEditor.toNegated()),
                menu: {
                    id: actions_1.MenuId.EditorContextPeek,
                    group: 'peek',
                    order: 6
                }
            });
        }
        async _getLocationModel(languageFeaturesService, model, position, token) {
            return new referencesModel_1.ReferencesModel(await (0, goToSymbol_1.getReferencesAtPosition)(languageFeaturesService.referenceProvider, model, position, false, false, token), nls.localize(969, 'References'));
        }
    });
    //#endregion
    //#region --- GENERIC goto symbols command
    class GenericGoToLocationAction extends SymbolNavigationAction {
        constructor(config, _references, _gotoMultipleBehaviour) {
            super(config, {
                id: 'editor.action.goToLocation',
                title: nls.localize2(984, "Go to Any Symbol"),
                precondition: contextkey_1.ContextKeyExpr.and(peekView_1.PeekContext.notInPeekEditor, editorContextKeys_1.EditorContextKeys.isInEmbeddedEditor.toNegated()),
            });
            this._references = _references;
            this._gotoMultipleBehaviour = _gotoMultipleBehaviour;
        }
        async _getLocationModel(languageFeaturesService, _model, _position, _token) {
            return new referencesModel_1.ReferencesModel(this._references, nls.localize(970, 'Locations'));
        }
        _getNoResultFoundMessage(info) {
            return info && nls.localize(971, "No results for '{0}'", info.word) || '';
        }
        _getGoToPreference(editor) {
            return this._gotoMultipleBehaviour ?? editor.getOption(58 /* EditorOption.gotoLocation */).multipleReferences;
        }
        _getAlternativeCommand() { return ''; }
    }
    commands_1.CommandsRegistry.registerCommand({
        id: 'editor.action.goToLocations',
        metadata: {
            description: 'Go to locations from a position in a file',
            args: [
                { name: 'uri', description: 'The text document in which to start', constraint: uri_1.URI },
                { name: 'position', description: 'The position at which to start', constraint: corePosition.Position.isIPosition },
                { name: 'locations', description: 'An array of locations.', constraint: Array },
                { name: 'multiple', description: 'Define what to do when having multiple results, either `peek`, `gotoAndPeek`, or `goto`' },
                { name: 'noResultsMessage', description: 'Human readable message that shows when locations is empty.' },
            ]
        },
        handler: async (accessor, resource, position, references, multiple, noResultsMessage, openInPeek) => {
            (0, types_1.assertType)(uri_1.URI.isUri(resource));
            (0, types_1.assertType)(corePosition.Position.isIPosition(position));
            (0, types_1.assertType)(Array.isArray(references));
            (0, types_1.assertType)(typeof multiple === 'undefined' || typeof multiple === 'string');
            (0, types_1.assertType)(typeof openInPeek === 'undefined' || typeof openInPeek === 'boolean');
            const editorService = accessor.get(codeEditorService_1.ICodeEditorService);
            const editor = await editorService.openCodeEditor({ resource }, editorService.getFocusedCodeEditor());
            if ((0, editorBrowser_1.isCodeEditor)(editor)) {
                editor.setPosition(position);
                editor.revealPositionInCenterIfOutsideViewport(position, 0 /* ScrollType.Smooth */);
                return editor.invokeWithinContext(accessor => {
                    const command = new class extends GenericGoToLocationAction {
                        _getNoResultFoundMessage(info) {
                            return noResultsMessage || super._getNoResultFoundMessage(info);
                        }
                    }({
                        muteMessage: !Boolean(noResultsMessage),
                        openInPeek: Boolean(openInPeek),
                        openToSide: false
                    }, references, multiple);
                    accessor.get(instantiation_1.IInstantiationService).invokeFunction(command.run.bind(command), editor);
                });
            }
        }
    });
    commands_1.CommandsRegistry.registerCommand({
        id: 'editor.action.peekLocations',
        metadata: {
            description: 'Peek locations from a position in a file',
            args: [
                { name: 'uri', description: 'The text document in which to start', constraint: uri_1.URI },
                { name: 'position', description: 'The position at which to start', constraint: corePosition.Position.isIPosition },
                { name: 'locations', description: 'An array of locations.', constraint: Array },
                { name: 'multiple', description: 'Define what to do when having multiple results, either `peek`, `gotoAndPeek`, or `goto`' },
            ]
        },
        handler: async (accessor, resource, position, references, multiple) => {
            accessor.get(commands_1.ICommandService).executeCommand('editor.action.goToLocations', resource, position, references, multiple, undefined, true);
        }
    });
    //#endregion
    //#region --- REFERENCE search special commands
    commands_1.CommandsRegistry.registerCommand({
        id: 'editor.action.findReferences',
        handler: (accessor, resource, position) => {
            (0, types_1.assertType)(uri_1.URI.isUri(resource));
            (0, types_1.assertType)(corePosition.Position.isIPosition(position));
            const languageFeaturesService = accessor.get(languageFeatures_1.ILanguageFeaturesService);
            const codeEditorService = accessor.get(codeEditorService_1.ICodeEditorService);
            return codeEditorService.openCodeEditor({ resource }, codeEditorService.getFocusedCodeEditor()).then(control => {
                if (!(0, editorBrowser_1.isCodeEditor)(control) || !control.hasModel()) {
                    return undefined;
                }
                const controller = referencesController_1.ReferencesController.get(control);
                if (!controller) {
                    return undefined;
                }
                const references = (0, async_1.createCancelablePromise)(token => (0, goToSymbol_1.getReferencesAtPosition)(languageFeaturesService.referenceProvider, control.getModel(), corePosition.Position.lift(position), false, false, token).then(references => new referencesModel_1.ReferencesModel(references, nls.localize(972, 'References'))));
                const range = new range_1.Range(position.lineNumber, position.column, position.lineNumber, position.column);
                return Promise.resolve(controller.toggleWidget(range, references, false));
            });
        }
    });
    // use NEW command
    commands_1.CommandsRegistry.registerCommandAlias('editor.action.showReferences', 'editor.action.peekLocations');
});
//#endregion

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[429/*vs/editor/contrib/gotoSymbol/browser/link/goToDefinitionAtPosition*/], __M([1/*require*/,0/*exports*/,14/*vs/base/common/async*/,8/*vs/base/common/errors*/,57/*vs/base/common/htmlContent*/,2/*vs/base/common/lifecycle*/,122/*vs/editor/contrib/editorState/browser/editorState*/,15/*vs/editor/browser/editorExtensions*/,4/*vs/editor/common/core/range*/,43/*vs/editor/common/languages/language*/,78/*vs/editor/common/services/resolverService*/,209/*vs/editor/contrib/gotoSymbol/browser/link/clickLinkGesture*/,158/*vs/editor/contrib/peekView/browser/peekView*/,3/*vs/nls*/,12/*vs/platform/contextkey/common/contextkey*/,291/*vs/editor/contrib/gotoSymbol/browser/goToCommands*/,277/*vs/editor/contrib/gotoSymbol/browser/goToSymbol*/,17/*vs/editor/common/services/languageFeatures*/,35/*vs/editor/common/model/textModel*/,513/*vs/css!vs/editor/contrib/gotoSymbol/browser/link/goToDefinitionAtPosition*/]), function (require, exports, async_1, errors_1, htmlContent_1, lifecycle_1, editorState_1, editorExtensions_1, range_1, language_1, resolverService_1, clickLinkGesture_1, peekView_1, nls, contextkey_1, goToCommands_1, goToSymbol_1, languageFeatures_1, textModel_1) {
    "use strict";
    var GotoDefinitionAtPositionEditorContribution_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.GotoDefinitionAtPositionEditorContribution = void 0;
    let GotoDefinitionAtPositionEditorContribution = class GotoDefinitionAtPositionEditorContribution {
        static { GotoDefinitionAtPositionEditorContribution_1 = this; }
        static { this.ID = 'editor.contrib.gotodefinitionatposition'; }
        static { this.MAX_SOURCE_PREVIEW_LINES = 8; }
        constructor(editor, textModelResolverService, languageService, languageFeaturesService) {
            this.textModelResolverService = textModelResolverService;
            this.languageService = languageService;
            this.languageFeaturesService = languageFeaturesService;
            this.toUnhook = new lifecycle_1.DisposableStore();
            this.toUnhookForKeyboard = new lifecycle_1.DisposableStore();
            this.currentWordAtPosition = null;
            this.previousPromise = null;
            this.editor = editor;
            this.linkDecorations = this.editor.createDecorationsCollection();
            const linkGesture = new clickLinkGesture_1.ClickLinkGesture(editor);
            this.toUnhook.add(linkGesture);
            this.toUnhook.add(linkGesture.onMouseMoveOrRelevantKeyDown(([mouseEvent, keyboardEvent]) => {
                this.startFindDefinitionFromMouse(mouseEvent, keyboardEvent ?? undefined);
            }));
            this.toUnhook.add(linkGesture.onExecute((mouseEvent) => {
                if (this.isEnabled(mouseEvent)) {
                    this.gotoDefinition(mouseEvent.target.position, mouseEvent.hasSideBySideModifier)
                        .catch((error) => {
                        (0, errors_1.onUnexpectedError)(error);
                    })
                        .finally(() => {
                        this.removeLinkDecorations();
                    });
                }
            }));
            this.toUnhook.add(linkGesture.onCancel(() => {
                this.removeLinkDecorations();
                this.currentWordAtPosition = null;
            }));
        }
        static get(editor) {
            return editor.getContribution(GotoDefinitionAtPositionEditorContribution_1.ID);
        }
        async startFindDefinitionFromCursor(position) {
            // For issue: https://github.com/microsoft/vscode/issues/46257
            // equivalent to mouse move with meta/ctrl key
            // First find the definition and add decorations
            // to the editor to be shown with the content hover widget
            await this.startFindDefinition(position);
            // Add listeners for editor cursor move and key down events
            // Dismiss the "extended" editor decorations when the user hides
            // the hover widget. There is no event for the widget itself so these
            // serve as a best effort. After removing the link decorations, the hover
            // widget is clean and will only show declarations per next request.
            this.toUnhookForKeyboard.add(this.editor.onDidChangeCursorPosition(() => {
                this.currentWordAtPosition = null;
                this.removeLinkDecorations();
                this.toUnhookForKeyboard.clear();
            }));
            this.toUnhookForKeyboard.add(this.editor.onKeyDown((e) => {
                if (e) {
                    this.currentWordAtPosition = null;
                    this.removeLinkDecorations();
                    this.toUnhookForKeyboard.clear();
                }
            }));
        }
        startFindDefinitionFromMouse(mouseEvent, withKey) {
            // check if we are active and on a content widget
            if (mouseEvent.target.type === 9 /* MouseTargetType.CONTENT_WIDGET */ && this.linkDecorations.length > 0) {
                return;
            }
            if (!this.editor.hasModel() || !this.isEnabled(mouseEvent, withKey)) {
                this.currentWordAtPosition = null;
                this.removeLinkDecorations();
                return;
            }
            const position = mouseEvent.target.position;
            this.startFindDefinition(position);
        }
        async startFindDefinition(position) {
            // Dispose listeners for updating decorations when using keyboard to show definition hover
            this.toUnhookForKeyboard.clear();
            // Find word at mouse position
            const word = position ? this.editor.getModel()?.getWordAtPosition(position) : null;
            if (!word) {
                this.currentWordAtPosition = null;
                this.removeLinkDecorations();
                return;
            }
            // Return early if word at position is still the same
            if (this.currentWordAtPosition && this.currentWordAtPosition.startColumn === word.startColumn && this.currentWordAtPosition.endColumn === word.endColumn && this.currentWordAtPosition.word === word.word) {
                return;
            }
            this.currentWordAtPosition = word;
            // Find definition and decorate word if found
            const state = new editorState_1.EditorState(this.editor, 4 /* CodeEditorStateFlag.Position */ | 1 /* CodeEditorStateFlag.Value */ | 2 /* CodeEditorStateFlag.Selection */ | 8 /* CodeEditorStateFlag.Scroll */);
            if (this.previousPromise) {
                this.previousPromise.cancel();
                this.previousPromise = null;
            }
            this.previousPromise = (0, async_1.createCancelablePromise)(token => this.findDefinition(position, token));
            let results;
            try {
                results = await this.previousPromise;
            }
            catch (error) {
                (0, errors_1.onUnexpectedError)(error);
                return;
            }
            if (!results || !results.length || !state.validate(this.editor)) {
                this.removeLinkDecorations();
                return;
            }
            const linkRange = results[0].originSelectionRange
                ? range_1.Range.lift(results[0].originSelectionRange)
                : new range_1.Range(position.lineNumber, word.startColumn, position.lineNumber, word.endColumn);
            // Multiple results
            if (results.length > 1) {
                let combinedRange = linkRange;
                for (const { originSelectionRange } of results) {
                    if (originSelectionRange) {
                        combinedRange = range_1.Range.plusRange(combinedRange, originSelectionRange);
                    }
                }
                this.addDecoration(combinedRange, new htmlContent_1.MarkdownString().appendText(nls.localize(985, "Click to show {0} definitions.", results.length)));
            }
            else {
                // Single result
                const result = results[0];
                if (!result.uri) {
                    return;
                }
                this.textModelResolverService.createModelReference(result.uri).then(ref => {
                    if (!ref.object || !ref.object.textEditorModel) {
                        ref.dispose();
                        return;
                    }
                    const { object: { textEditorModel } } = ref;
                    const { startLineNumber } = result.range;
                    if (startLineNumber < 1 || startLineNumber > textEditorModel.getLineCount()) {
                        // invalid range
                        ref.dispose();
                        return;
                    }
                    const previewValue = this.getPreviewValue(textEditorModel, startLineNumber, result);
                    const languageId = this.languageService.guessLanguageIdByFilepathOrFirstLine(textEditorModel.uri);
                    this.addDecoration(linkRange, previewValue ? new htmlContent_1.MarkdownString().appendCodeblock(languageId ? languageId : '', previewValue) : undefined);
                    ref.dispose();
                });
            }
        }
        getPreviewValue(textEditorModel, startLineNumber, result) {
            let rangeToUse = result.range;
            const numberOfLinesInRange = rangeToUse.endLineNumber - rangeToUse.startLineNumber;
            if (numberOfLinesInRange >= GotoDefinitionAtPositionEditorContribution_1.MAX_SOURCE_PREVIEW_LINES) {
                rangeToUse = this.getPreviewRangeBasedOnIndentation(textEditorModel, startLineNumber);
            }
            const previewValue = this.stripIndentationFromPreviewRange(textEditorModel, startLineNumber, rangeToUse);
            return previewValue;
        }
        stripIndentationFromPreviewRange(textEditorModel, startLineNumber, previewRange) {
            const startIndent = textEditorModel.getLineFirstNonWhitespaceColumn(startLineNumber);
            let minIndent = startIndent;
            for (let endLineNumber = startLineNumber + 1; endLineNumber < previewRange.endLineNumber; endLineNumber++) {
                const endIndent = textEditorModel.getLineFirstNonWhitespaceColumn(endLineNumber);
                minIndent = Math.min(minIndent, endIndent);
            }
            const previewValue = textEditorModel.getValueInRange(previewRange).replace(new RegExp(`^\\s{${minIndent - 1}}`, 'gm'), '').trim();
            return previewValue;
        }
        getPreviewRangeBasedOnIndentation(textEditorModel, startLineNumber) {
            const startIndent = textEditorModel.getLineFirstNonWhitespaceColumn(startLineNumber);
            const maxLineNumber = Math.min(textEditorModel.getLineCount(), startLineNumber + GotoDefinitionAtPositionEditorContribution_1.MAX_SOURCE_PREVIEW_LINES);
            let endLineNumber = startLineNumber + 1;
            for (; endLineNumber < maxLineNumber; endLineNumber++) {
                const endIndent = textEditorModel.getLineFirstNonWhitespaceColumn(endLineNumber);
                if (startIndent === endIndent) {
                    break;
                }
            }
            return new range_1.Range(startLineNumber, 1, endLineNumber + 1, 1);
        }
        addDecoration(range, hoverMessage) {
            const newDecorations = {
                range: range,
                options: {
                    description: 'goto-definition-link',
                    inlineClassName: 'goto-definition-link',
                    hoverMessage
                }
            };
            this.linkDecorations.set([newDecorations]);
        }
        removeLinkDecorations() {
            this.linkDecorations.clear();
        }
        isEnabled(mouseEvent, withKey) {
            return this.editor.hasModel()
                && mouseEvent.isLeftClick
                && mouseEvent.isNoneOrSingleMouseDown
                && mouseEvent.target.type === 6 /* MouseTargetType.CONTENT_TEXT */
                && !(mouseEvent.target.detail.injectedText?.options instanceof textModel_1.ModelDecorationInjectedTextOptions)
                && (mouseEvent.hasTriggerModifier || (withKey ? withKey.keyCodeIsTriggerKey : false))
                && this.languageFeaturesService.definitionProvider.has(this.editor.getModel());
        }
        findDefinition(position, token) {
            const model = this.editor.getModel();
            if (!model) {
                return Promise.resolve(null);
            }
            return (0, goToSymbol_1.getDefinitionsAtPosition)(this.languageFeaturesService.definitionProvider, model, position, false, token);
        }
        gotoDefinition(position, openToSide) {
            this.editor.setPosition(position);
            return this.editor.invokeWithinContext((accessor) => {
                const canPeek = !openToSide && this.editor.getOption(89 /* EditorOption.definitionLinkOpensInPeek */) && !this.isInPeekEditor(accessor);
                const action = new goToCommands_1.DefinitionAction({ openToSide, openInPeek: canPeek, muteMessage: true }, { title: { value: '', original: '' }, id: '', precondition: undefined });
                return action.run(accessor);
            });
        }
        isInPeekEditor(accessor) {
            const contextKeyService = accessor.get(contextkey_1.IContextKeyService);
            return peekView_1.PeekContext.inPeekEditor.getValue(contextKeyService);
        }
        dispose() {
            this.toUnhook.dispose();
            this.toUnhookForKeyboard.dispose();
        }
    };
    exports.GotoDefinitionAtPositionEditorContribution = GotoDefinitionAtPositionEditorContribution;
    exports.GotoDefinitionAtPositionEditorContribution = GotoDefinitionAtPositionEditorContribution = GotoDefinitionAtPositionEditorContribution_1 = __decorate([
        __param(1, resolverService_1.ITextModelService),
        __param(2, language_1.ILanguageService),
        __param(3, languageFeatures_1.ILanguageFeaturesService)
    ], GotoDefinitionAtPositionEditorContribution);
    (0, editorExtensions_1.registerEditorContribution)(GotoDefinitionAtPositionEditorContribution.ID, GotoDefinitionAtPositionEditorContribution, 2 /* EditorContributionInstantiation.BeforeFirstInteraction */);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[845/*vs/editor/contrib/hover/browser/markerHoverParticipant*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,13/*vs/base/common/arrays*/,14/*vs/base/common/async*/,8/*vs/base/common/errors*/,2/*vs/base/common/lifecycle*/,48/*vs/base/common/resources*/,4/*vs/editor/common/core/range*/,17/*vs/editor/common/services/languageFeatures*/,266/*vs/editor/common/services/markerDecorations*/,157/*vs/editor/contrib/codeAction/browser/codeAction*/,287/*vs/editor/contrib/codeAction/browser/codeActionController*/,134/*vs/editor/contrib/codeAction/common/types*/,427/*vs/editor/contrib/gotoError/browser/gotoError*/,84/*vs/editor/contrib/hover/browser/hoverTypes*/,3/*vs/nls*/,108/*vs/platform/markers/common/markers*/,59/*vs/platform/opener/common/opener*/,96/*vs/platform/progress/common/progress*/]), function (require, exports, dom, arrays_1, async_1, errors_1, lifecycle_1, resources_1, range_1, languageFeatures_1, markerDecorations_1, codeAction_1, codeActionController_1, types_1, gotoError_1, hoverTypes_1, nls, markers_1, opener_1, progress_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MarkerHoverParticipant = exports.MarkerHover = void 0;
    const $ = dom.$;
    class MarkerHover {
        constructor(owner, range, marker) {
            this.owner = owner;
            this.range = range;
            this.marker = marker;
        }
        isValidForHoverAnchor(anchor) {
            return (anchor.type === 1 /* HoverAnchorType.Range */
                && this.range.startColumn <= anchor.range.startColumn
                && this.range.endColumn >= anchor.range.endColumn);
        }
    }
    exports.MarkerHover = MarkerHover;
    const markerCodeActionTrigger = {
        type: 1 /* CodeActionTriggerType.Invoke */,
        filter: { include: types_1.CodeActionKind.QuickFix },
        triggerAction: types_1.CodeActionTriggerSource.QuickFixHover
    };
    let MarkerHoverParticipant = class MarkerHoverParticipant {
        constructor(_editor, _markerDecorationsService, _openerService, _languageFeaturesService) {
            this._editor = _editor;
            this._markerDecorationsService = _markerDecorationsService;
            this._openerService = _openerService;
            this._languageFeaturesService = _languageFeaturesService;
            this.hoverOrdinal = 1;
            this.recentMarkerCodeActionsInfo = undefined;
        }
        computeSync(anchor, lineDecorations) {
            if (!this._editor.hasModel() || anchor.type !== 1 /* HoverAnchorType.Range */ && !anchor.supportsMarkerHover) {
                return [];
            }
            const model = this._editor.getModel();
            const lineNumber = anchor.range.startLineNumber;
            const maxColumn = model.getLineMaxColumn(lineNumber);
            const result = [];
            for (const d of lineDecorations) {
                const startColumn = (d.range.startLineNumber === lineNumber) ? d.range.startColumn : 1;
                const endColumn = (d.range.endLineNumber === lineNumber) ? d.range.endColumn : maxColumn;
                const marker = this._markerDecorationsService.getMarker(model.uri, d);
                if (!marker) {
                    continue;
                }
                const range = new range_1.Range(anchor.range.startLineNumber, startColumn, anchor.range.startLineNumber, endColumn);
                result.push(new MarkerHover(this, range, marker));
            }
            return result;
        }
        renderHoverParts(context, hoverParts) {
            if (!hoverParts.length) {
                return new hoverTypes_1.RenderedHoverParts([]);
            }
            const disposables = new lifecycle_1.DisposableStore();
            const renderedHoverParts = [];
            hoverParts.forEach(hoverPart => {
                const renderedMarkerHover = this._renderMarkerHover(hoverPart);
                context.fragment.appendChild(renderedMarkerHover.hoverElement);
                renderedHoverParts.push(renderedMarkerHover);
            });
            const markerHoverForStatusbar = hoverParts.length === 1 ? hoverParts[0] : hoverParts.sort((a, b) => markers_1.MarkerSeverity.compare(a.marker.severity, b.marker.severity))[0];
            this.renderMarkerStatusbar(context, markerHoverForStatusbar, disposables);
            return new hoverTypes_1.RenderedHoverParts(renderedHoverParts);
        }
        _renderMarkerHover(markerHover) {
            const disposables = new lifecycle_1.DisposableStore();
            const hoverElement = $('div.hover-row');
            const markerElement = dom.append(hoverElement, $('div.marker.hover-contents'));
            const { source, message, code, relatedInformation } = markerHover.marker;
            this._editor.applyFontInfo(markerElement);
            const messageElement = dom.append(markerElement, $('span'));
            messageElement.style.whiteSpace = 'pre-wrap';
            messageElement.innerText = message;
            if (source || code) {
                // Code has link
                if (code && typeof code !== 'string') {
                    const sourceAndCodeElement = $('span');
                    if (source) {
                        const sourceElement = dom.append(sourceAndCodeElement, $('span'));
                        sourceElement.innerText = source;
                    }
                    const codeLink = dom.append(sourceAndCodeElement, $('a.code-link'));
                    codeLink.setAttribute('href', code.target.toString());
                    disposables.add(dom.addDisposableListener(codeLink, 'click', (e) => {
                        this._openerService.open(code.target, { allowCommands: true });
                        e.preventDefault();
                        e.stopPropagation();
                    }));
                    const codeElement = dom.append(codeLink, $('span'));
                    codeElement.innerText = code.value;
                    const detailsElement = dom.append(markerElement, sourceAndCodeElement);
                    detailsElement.style.opacity = '0.6';
                    detailsElement.style.paddingLeft = '6px';
                }
                else {
                    const detailsElement = dom.append(markerElement, $('span'));
                    detailsElement.style.opacity = '0.6';
                    detailsElement.style.paddingLeft = '6px';
                    detailsElement.innerText = source && code ? `${source}(${code})` : source ? source : `(${code})`;
                }
            }
            if ((0, arrays_1.isNonEmptyArray)(relatedInformation)) {
                for (const { message, resource, startLineNumber, startColumn } of relatedInformation) {
                    const relatedInfoContainer = dom.append(markerElement, $('div'));
                    relatedInfoContainer.style.marginTop = '8px';
                    const a = dom.append(relatedInfoContainer, $('a'));
                    a.innerText = `${(0, resources_1.basename)(resource)}(${startLineNumber}, ${startColumn}): `;
                    a.style.cursor = 'pointer';
                    disposables.add(dom.addDisposableListener(a, 'click', (e) => {
                        e.stopPropagation();
                        e.preventDefault();
                        if (this._openerService) {
                            const editorOptions = { selection: { startLineNumber, startColumn } };
                            this._openerService.open(resource, {
                                fromUserGesture: true,
                                editorOptions
                            }).catch(errors_1.onUnexpectedError);
                        }
                    }));
                    const messageElement = dom.append(relatedInfoContainer, $('span'));
                    messageElement.innerText = message;
                    this._editor.applyFontInfo(messageElement);
                }
            }
            const renderedHoverPart = {
                hoverPart: markerHover,
                hoverElement,
                dispose: () => disposables.dispose()
            };
            return renderedHoverPart;
        }
        renderMarkerStatusbar(context, markerHover, disposables) {
            if (markerHover.marker.severity === markers_1.MarkerSeverity.Error || markerHover.marker.severity === markers_1.MarkerSeverity.Warning || markerHover.marker.severity === markers_1.MarkerSeverity.Info) {
                const markerController = gotoError_1.MarkerController.get(this._editor);
                if (markerController) {
                    context.statusBar.addAction({
                        label: nls.localize(1040, "View Problem"),
                        commandId: gotoError_1.NextMarkerAction.ID,
                        run: () => {
                            context.hide();
                            markerController.showAtMarker(markerHover.marker);
                            this._editor.focus();
                        }
                    });
                }
            }
            if (!this._editor.getOption(92 /* EditorOption.readOnly */)) {
                const quickfixPlaceholderElement = context.statusBar.append($('div'));
                if (this.recentMarkerCodeActionsInfo) {
                    if (markers_1.IMarkerData.makeKey(this.recentMarkerCodeActionsInfo.marker) === markers_1.IMarkerData.makeKey(markerHover.marker)) {
                        if (!this.recentMarkerCodeActionsInfo.hasCodeActions) {
                            quickfixPlaceholderElement.textContent = nls.localize(1041, "No quick fixes available");
                        }
                    }
                    else {
                        this.recentMarkerCodeActionsInfo = undefined;
                    }
                }
                const updatePlaceholderDisposable = this.recentMarkerCodeActionsInfo && !this.recentMarkerCodeActionsInfo.hasCodeActions ? lifecycle_1.Disposable.None : (0, async_1.disposableTimeout)(() => quickfixPlaceholderElement.textContent = nls.localize(1042, "Checking for quick fixes..."), 200, disposables);
                if (!quickfixPlaceholderElement.textContent) {
                    // Have some content in here to avoid flickering
                    quickfixPlaceholderElement.textContent = String.fromCharCode(0xA0); // &nbsp;
                }
                const codeActionsPromise = this.getCodeActions(markerHover.marker);
                disposables.add((0, lifecycle_1.toDisposable)(() => codeActionsPromise.cancel()));
                codeActionsPromise.then(actions => {
                    updatePlaceholderDisposable.dispose();
                    this.recentMarkerCodeActionsInfo = { marker: markerHover.marker, hasCodeActions: actions.validActions.length > 0 };
                    if (!this.recentMarkerCodeActionsInfo.hasCodeActions) {
                        actions.dispose();
                        quickfixPlaceholderElement.textContent = nls.localize(1043, "No quick fixes available");
                        return;
                    }
                    quickfixPlaceholderElement.style.display = 'none';
                    let showing = false;
                    disposables.add((0, lifecycle_1.toDisposable)(() => {
                        if (!showing) {
                            actions.dispose();
                        }
                    }));
                    context.statusBar.addAction({
                        label: nls.localize(1044, "Quick Fix..."),
                        commandId: codeAction_1.quickFixCommandId,
                        run: (target) => {
                            showing = true;
                            const controller = codeActionController_1.CodeActionController.get(this._editor);
                            const elementPosition = dom.getDomNodePagePosition(target);
                            // Hide the hover pre-emptively, otherwise the editor can close the code actions
                            // context menu as well when using keyboard navigation
                            context.hide();
                            controller?.showCodeActions(markerCodeActionTrigger, actions, {
                                x: elementPosition.left,
                                y: elementPosition.top,
                                width: elementPosition.width,
                                height: elementPosition.height
                            });
                        }
                    });
                }, errors_1.onUnexpectedError);
            }
        }
        getCodeActions(marker) {
            return (0, async_1.createCancelablePromise)(cancellationToken => {
                return (0, codeAction_1.getCodeActions)(this._languageFeaturesService.codeActionProvider, this._editor.getModel(), new range_1.Range(marker.startLineNumber, marker.startColumn, marker.endLineNumber, marker.endColumn), markerCodeActionTrigger, progress_1.Progress.None, cancellationToken);
            });
        }
    };
    exports.MarkerHoverParticipant = MarkerHoverParticipant;
    exports.MarkerHoverParticipant = MarkerHoverParticipant = __decorate([
        __param(1, markerDecorations_1.IMarkerDecorationsService),
        __param(2, opener_1.IOpenerService),
        __param(3, languageFeatures_1.ILanguageFeaturesService)
    ], MarkerHoverParticipant);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[430/*vs/editor/contrib/inlayHints/browser/inlayHintsLocations*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,41/*vs/base/common/actions*/,18/*vs/base/common/cancellation*/,193/*vs/base/common/uuid*/,4/*vs/editor/common/core/range*/,78/*vs/editor/common/services/resolverService*/,291/*vs/editor/contrib/gotoSymbol/browser/goToCommands*/,158/*vs/editor/contrib/peekView/browser/peekView*/,29/*vs/platform/actions/common/actions*/,24/*vs/platform/commands/common/commands*/,12/*vs/platform/contextkey/common/contextkey*/,58/*vs/platform/contextview/browser/contextView*/,7/*vs/platform/instantiation/common/instantiation*/,50/*vs/platform/notification/common/notification*/]), function (require, exports, dom, actions_1, cancellation_1, uuid_1, range_1, resolverService_1, goToCommands_1, peekView_1, actions_2, commands_1, contextkey_1, contextView_1, instantiation_1, notification_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.showGoToContextMenu = showGoToContextMenu;
    exports.goToDefinitionWithLocation = goToDefinitionWithLocation;
    async function showGoToContextMenu(accessor, editor, anchor, part) {
        const resolverService = accessor.get(resolverService_1.ITextModelService);
        const contextMenuService = accessor.get(contextView_1.IContextMenuService);
        const commandService = accessor.get(commands_1.ICommandService);
        const instaService = accessor.get(instantiation_1.IInstantiationService);
        const notificationService = accessor.get(notification_1.INotificationService);
        await part.item.resolve(cancellation_1.CancellationToken.None);
        if (!part.part.location) {
            return;
        }
        const location = part.part.location;
        const menuActions = [];
        // from all registered (not active) context menu actions select those
        // that are a symbol navigation actions
        const filter = new Set(actions_2.MenuRegistry.getMenuItems(actions_2.MenuId.EditorContext)
            .map(item => (0, actions_2.isIMenuItem)(item) ? item.command.id : (0, uuid_1.generateUuid)()));
        for (const delegate of goToCommands_1.SymbolNavigationAction.all()) {
            if (filter.has(delegate.desc.id)) {
                menuActions.push(new actions_1.Action(delegate.desc.id, actions_2.MenuItemAction.label(delegate.desc, { renderShortTitle: true }), undefined, true, async () => {
                    const ref = await resolverService.createModelReference(location.uri);
                    try {
                        const symbolAnchor = new goToCommands_1.SymbolNavigationAnchor(ref.object.textEditorModel, range_1.Range.getStartPosition(location.range));
                        const range = part.item.anchor.range;
                        await instaService.invokeFunction(delegate.runEditorCommand.bind(delegate), editor, symbolAnchor, range);
                    }
                    finally {
                        ref.dispose();
                    }
                }));
            }
        }
        if (part.part.command) {
            const { command } = part.part;
            menuActions.push(new actions_1.Separator());
            menuActions.push(new actions_1.Action(command.id, command.title, undefined, true, async () => {
                try {
                    await commandService.executeCommand(command.id, ...(command.arguments ?? []));
                }
                catch (err) {
                    notificationService.notify({
                        severity: notification_1.Severity.Error,
                        source: part.item.provider.displayName,
                        message: err
                    });
                }
            }));
        }
        // show context menu
        const useShadowDOM = editor.getOption(128 /* EditorOption.useShadowDOM */);
        contextMenuService.showContextMenu({
            domForShadowRoot: useShadowDOM ? editor.getDomNode() ?? undefined : undefined,
            getAnchor: () => {
                const box = dom.getDomNodePagePosition(anchor);
                return { x: box.left, y: box.top + box.height + 8 };
            },
            getActions: () => menuActions,
            onHide: () => {
                editor.focus();
            },
            autoSelectFirstItem: true,
        });
    }
    async function goToDefinitionWithLocation(accessor, event, editor, location) {
        const resolverService = accessor.get(resolverService_1.ITextModelService);
        const ref = await resolverService.createModelReference(location.uri);
        await editor.invokeWithinContext(async (accessor) => {
            const openToSide = event.hasSideBySideModifier;
            const contextKeyService = accessor.get(contextkey_1.IContextKeyService);
            const isInPeek = peekView_1.PeekContext.inPeekEditor.getValue(contextKeyService);
            const canPeek = !openToSide && editor.getOption(89 /* EditorOption.definitionLinkOpensInPeek */) && !isInPeek;
            const action = new goToCommands_1.DefinitionAction({ openToSide, openInPeek: canPeek, muteMessage: true }, { title: { value: '', original: '' }, id: '', precondition: undefined });
            return action.run(accessor, new goToCommands_1.SymbolNavigationAnchor(ref.object.textEditorModel, range_1.Range.getStartPosition(location.range)), range_1.Range.lift(location.range));
        });
        ref.dispose();
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[431/*vs/editor/contrib/inlayHints/browser/inlayHintsController*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,13/*vs/base/common/arrays*/,14/*vs/base/common/async*/,18/*vs/base/common/cancellation*/,8/*vs/base/common/errors*/,2/*vs/base/common/lifecycle*/,45/*vs/base/common/map*/,19/*vs/base/common/types*/,22/*vs/base/common/uri*/,185/*vs/editor/browser/editorDom*/,143/*vs/editor/browser/stableEditorScroll*/,37/*vs/editor/common/config/editorOptions*/,75/*vs/editor/common/core/editOperation*/,4/*vs/editor/common/core/range*/,27/*vs/editor/common/languages*/,40/*vs/editor/common/model*/,35/*vs/editor/common/model/textModel*/,79/*vs/editor/common/services/languageFeatureDebounce*/,17/*vs/editor/common/services/languageFeatures*/,78/*vs/editor/common/services/resolverService*/,209/*vs/editor/contrib/gotoSymbol/browser/link/clickLinkGesture*/,377/*vs/editor/contrib/inlayHints/browser/inlayHints*/,430/*vs/editor/contrib/inlayHints/browser/inlayHintsLocations*/,24/*vs/platform/commands/common/commands*/,49/*vs/platform/instantiation/common/extensions*/,7/*vs/platform/instantiation/common/instantiation*/,50/*vs/platform/notification/common/notification*/,32/*vs/platform/theme/common/colorRegistry*/,25/*vs/platform/theme/common/themeService*/]), function (require, exports, dom_1, arrays_1, async_1, cancellation_1, errors_1, lifecycle_1, map_1, types_1, uri_1, editorDom_1, stableEditorScroll_1, editorOptions_1, editOperation_1, range_1, languages, model_1, textModel_1, languageFeatureDebounce_1, languageFeatures_1, resolverService_1, clickLinkGesture_1, inlayHints_1, inlayHintsLocations_1, commands_1, extensions_1, instantiation_1, notification_1, colors, themeService_1) {
    "use strict";
    var InlayHintsController_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.InlayHintsController = exports.RenderedInlayHintLabelPart = void 0;
    // --- hint caching service (per session)
    class InlayHintsCache {
        constructor() {
            this._entries = new map_1.LRUCache(50);
        }
        get(model) {
            const key = InlayHintsCache._key(model);
            return this._entries.get(key);
        }
        set(model, value) {
            const key = InlayHintsCache._key(model);
            this._entries.set(key, value);
        }
        static _key(model) {
            return `${model.uri.toString()}/${model.getVersionId()}`;
        }
    }
    const IInlayHintsCache = (0, instantiation_1.createDecorator)('IInlayHintsCache');
    (0, extensions_1.registerSingleton)(IInlayHintsCache, InlayHintsCache, 1 /* InstantiationType.Delayed */);
    // --- rendered label
    class RenderedInlayHintLabelPart {
        constructor(item, index) {
            this.item = item;
            this.index = index;
        }
        get part() {
            const label = this.item.hint.label;
            if (typeof label === 'string') {
                return { label };
            }
            else {
                return label[this.index];
            }
        }
    }
    exports.RenderedInlayHintLabelPart = RenderedInlayHintLabelPart;
    class ActiveInlayHintInfo {
        constructor(part, hasTriggerModifier) {
            this.part = part;
            this.hasTriggerModifier = hasTriggerModifier;
        }
    }
    // --- controller
    let InlayHintsController = class InlayHintsController {
        static { InlayHintsController_1 = this; }
        static { this.ID = 'editor.contrib.InlayHints'; }
        static { this._MAX_DECORATORS = 1500; }
        static { this._MAX_LABEL_LEN = 43; }
        static get(editor) {
            return editor.getContribution(InlayHintsController_1.ID) ?? undefined;
        }
        constructor(_editor, _languageFeaturesService, _featureDebounce, _inlayHintsCache, _commandService, _notificationService, _instaService) {
            this._editor = _editor;
            this._languageFeaturesService = _languageFeaturesService;
            this._inlayHintsCache = _inlayHintsCache;
            this._commandService = _commandService;
            this._notificationService = _notificationService;
            this._instaService = _instaService;
            this._disposables = new lifecycle_1.DisposableStore();
            this._sessionDisposables = new lifecycle_1.DisposableStore();
            this._decorationsMetadata = new Map();
            this._ruleFactory = new editorDom_1.DynamicCssRules(this._editor);
            this._activeRenderMode = 0 /* RenderMode.Normal */;
            this._debounceInfo = _featureDebounce.for(_languageFeaturesService.inlayHintsProvider, 'InlayHint', { min: 25 });
            this._disposables.add(_languageFeaturesService.inlayHintsProvider.onDidChange(() => this._update()));
            this._disposables.add(_editor.onDidChangeModel(() => this._update()));
            this._disposables.add(_editor.onDidChangeModelLanguage(() => this._update()));
            this._disposables.add(_editor.onDidChangeConfiguration(e => {
                if (e.hasChanged(142 /* EditorOption.inlayHints */)) {
                    this._update();
                }
            }));
            this._update();
        }
        dispose() {
            this._sessionDisposables.dispose();
            this._removeAllDecorations();
            this._disposables.dispose();
        }
        _update() {
            this._sessionDisposables.clear();
            this._removeAllDecorations();
            const options = this._editor.getOption(142 /* EditorOption.inlayHints */);
            if (options.enabled === 'off') {
                return;
            }
            const model = this._editor.getModel();
            if (!model || !this._languageFeaturesService.inlayHintsProvider.has(model)) {
                return;
            }
            if (options.enabled === 'on') {
                // different "on" modes: always
                this._activeRenderMode = 0 /* RenderMode.Normal */;
            }
            else {
                // different "on" modes: offUnlessPressed, or onUnlessPressed
                let defaultMode;
                let altMode;
                if (options.enabled === 'onUnlessPressed') {
                    defaultMode = 0 /* RenderMode.Normal */;
                    altMode = 1 /* RenderMode.Invisible */;
                }
                else {
                    defaultMode = 1 /* RenderMode.Invisible */;
                    altMode = 0 /* RenderMode.Normal */;
                }
                this._activeRenderMode = defaultMode;
                this._sessionDisposables.add(dom_1.ModifierKeyEmitter.getInstance().event(e => {
                    if (!this._editor.hasModel()) {
                        return;
                    }
                    const newRenderMode = e.altKey && e.ctrlKey && !(e.shiftKey || e.metaKey) ? altMode : defaultMode;
                    if (newRenderMode !== this._activeRenderMode) {
                        this._activeRenderMode = newRenderMode;
                        const model = this._editor.getModel();
                        const copies = this._copyInlayHintsWithCurrentAnchor(model);
                        this._updateHintsDecorators([model.getFullModelRange()], copies);
                        scheduler.schedule(0);
                    }
                }));
            }
            // iff possible, quickly update from cache
            const cached = this._inlayHintsCache.get(model);
            if (cached) {
                this._updateHintsDecorators([model.getFullModelRange()], cached);
            }
            this._sessionDisposables.add((0, lifecycle_1.toDisposable)(() => {
                // cache items when switching files etc
                if (!model.isDisposed()) {
                    this._cacheHintsForFastRestore(model);
                }
            }));
            let cts;
            const watchedProviders = new Set();
            const scheduler = new async_1.RunOnceScheduler(async () => {
                const t1 = Date.now();
                cts?.dispose(true);
                cts = new cancellation_1.CancellationTokenSource();
                const listener = model.onWillDispose(() => cts?.cancel());
                try {
                    const myToken = cts.token;
                    const inlayHints = await inlayHints_1.InlayHintsFragments.create(this._languageFeaturesService.inlayHintsProvider, model, this._getHintsRanges(), myToken);
                    scheduler.delay = this._debounceInfo.update(model, Date.now() - t1);
                    if (myToken.isCancellationRequested) {
                        inlayHints.dispose();
                        return;
                    }
                    // listen to provider changes
                    for (const provider of inlayHints.provider) {
                        if (typeof provider.onDidChangeInlayHints === 'function' && !watchedProviders.has(provider)) {
                            watchedProviders.add(provider);
                            this._sessionDisposables.add(provider.onDidChangeInlayHints(() => {
                                if (!scheduler.isScheduled()) { // ignore event when request is already scheduled
                                    scheduler.schedule();
                                }
                            }));
                        }
                    }
                    this._sessionDisposables.add(inlayHints);
                    this._updateHintsDecorators(inlayHints.ranges, inlayHints.items);
                    this._cacheHintsForFastRestore(model);
                }
                catch (err) {
                    (0, errors_1.onUnexpectedError)(err);
                }
                finally {
                    cts.dispose();
                    listener.dispose();
                }
            }, this._debounceInfo.get(model));
            this._sessionDisposables.add(scheduler);
            this._sessionDisposables.add((0, lifecycle_1.toDisposable)(() => cts?.dispose(true)));
            scheduler.schedule(0);
            this._sessionDisposables.add(this._editor.onDidScrollChange((e) => {
                // update when scroll position changes
                // uses scrollTopChanged has weak heuristic to differenatiate between scrolling due to
                // typing or due to "actual" scrolling
                if (e.scrollTopChanged || !scheduler.isScheduled()) {
                    scheduler.schedule();
                }
            }));
            this._sessionDisposables.add(this._editor.onDidChangeModelContent((e) => {
                cts?.cancel();
                // update less aggressive when typing
                const delay = Math.max(scheduler.delay, 1250);
                scheduler.schedule(delay);
            }));
            // mouse gestures
            this._sessionDisposables.add(this._installDblClickGesture(() => scheduler.schedule(0)));
            this._sessionDisposables.add(this._installLinkGesture());
            this._sessionDisposables.add(this._installContextMenu());
        }
        _installLinkGesture() {
            const store = new lifecycle_1.DisposableStore();
            const gesture = store.add(new clickLinkGesture_1.ClickLinkGesture(this._editor));
            // let removeHighlight = () => { };
            const sessionStore = new lifecycle_1.DisposableStore();
            store.add(sessionStore);
            store.add(gesture.onMouseMoveOrRelevantKeyDown(e => {
                const [mouseEvent] = e;
                const labelPart = this._getInlayHintLabelPart(mouseEvent);
                const model = this._editor.getModel();
                if (!labelPart || !model) {
                    sessionStore.clear();
                    return;
                }
                // resolve the item
                const cts = new cancellation_1.CancellationTokenSource();
                sessionStore.add((0, lifecycle_1.toDisposable)(() => cts.dispose(true)));
                labelPart.item.resolve(cts.token);
                // render link => when the modifier is pressed and when there is a command or location
                this._activeInlayHintPart = labelPart.part.command || labelPart.part.location
                    ? new ActiveInlayHintInfo(labelPart, mouseEvent.hasTriggerModifier)
                    : undefined;
                const lineNumber = model.validatePosition(labelPart.item.hint.position).lineNumber;
                const range = new range_1.Range(lineNumber, 1, lineNumber, model.getLineMaxColumn(lineNumber));
                const lineHints = this._getInlineHintsForRange(range);
                this._updateHintsDecorators([range], lineHints);
                sessionStore.add((0, lifecycle_1.toDisposable)(() => {
                    this._activeInlayHintPart = undefined;
                    this._updateHintsDecorators([range], lineHints);
                }));
            }));
            store.add(gesture.onCancel(() => sessionStore.clear()));
            store.add(gesture.onExecute(async (e) => {
                const label = this._getInlayHintLabelPart(e);
                if (label) {
                    const part = label.part;
                    if (part.location) {
                        // location -> execute go to def
                        this._instaService.invokeFunction(inlayHintsLocations_1.goToDefinitionWithLocation, e, this._editor, part.location);
                    }
                    else if (languages.Command.is(part.command)) {
                        // command -> execute it
                        await this._invokeCommand(part.command, label.item);
                    }
                }
            }));
            return store;
        }
        _getInlineHintsForRange(range) {
            const lineHints = new Set();
            for (const data of this._decorationsMetadata.values()) {
                if (range.containsRange(data.item.anchor.range)) {
                    lineHints.add(data.item);
                }
            }
            return Array.from(lineHints);
        }
        _installDblClickGesture(updateInlayHints) {
            return this._editor.onMouseUp(async (e) => {
                if (e.event.detail !== 2) {
                    return;
                }
                const part = this._getInlayHintLabelPart(e);
                if (!part) {
                    return;
                }
                e.event.preventDefault();
                await part.item.resolve(cancellation_1.CancellationToken.None);
                if ((0, arrays_1.isNonEmptyArray)(part.item.hint.textEdits)) {
                    const edits = part.item.hint.textEdits.map(edit => editOperation_1.EditOperation.replace(range_1.Range.lift(edit.range), edit.text));
                    this._editor.executeEdits('inlayHint.default', edits);
                    updateInlayHints();
                }
            });
        }
        _installContextMenu() {
            return this._editor.onContextMenu(async (e) => {
                if (!((0, dom_1.isHTMLElement)(e.event.target))) {
                    return;
                }
                const part = this._getInlayHintLabelPart(e);
                if (part) {
                    await this._instaService.invokeFunction(inlayHintsLocations_1.showGoToContextMenu, this._editor, e.event.target, part);
                }
            });
        }
        _getInlayHintLabelPart(e) {
            if (e.target.type !== 6 /* MouseTargetType.CONTENT_TEXT */) {
                return undefined;
            }
            const options = e.target.detail.injectedText?.options;
            if (options instanceof textModel_1.ModelDecorationInjectedTextOptions && options?.attachedData instanceof RenderedInlayHintLabelPart) {
                return options.attachedData;
            }
            return undefined;
        }
        async _invokeCommand(command, item) {
            try {
                await this._commandService.executeCommand(command.id, ...(command.arguments ?? []));
            }
            catch (err) {
                this._notificationService.notify({
                    severity: notification_1.Severity.Error,
                    source: item.provider.displayName,
                    message: err
                });
            }
        }
        _cacheHintsForFastRestore(model) {
            const hints = this._copyInlayHintsWithCurrentAnchor(model);
            this._inlayHintsCache.set(model, hints);
        }
        // return inlay hints but with an anchor that reflects "updates"
        // that happened after receiving them, e.g adding new lines before a hint
        _copyInlayHintsWithCurrentAnchor(model) {
            const items = new Map();
            for (const [id, obj] of this._decorationsMetadata) {
                if (items.has(obj.item)) {
                    // an inlay item can be rendered as multiple decorations
                    // but they will all uses the same range
                    continue;
                }
                const range = model.getDecorationRange(id);
                if (range) {
                    // update range with whatever the editor has tweaked it to
                    const anchor = new inlayHints_1.InlayHintAnchor(range, obj.item.anchor.direction);
                    const copy = obj.item.with({ anchor });
                    items.set(obj.item, copy);
                }
            }
            return Array.from(items.values());
        }
        _getHintsRanges() {
            const extra = 30;
            const model = this._editor.getModel();
            const visibleRanges = this._editor.getVisibleRangesPlusViewportAboveBelow();
            const result = [];
            for (const range of visibleRanges.sort(range_1.Range.compareRangesUsingStarts)) {
                const extendedRange = model.validateRange(new range_1.Range(range.startLineNumber - extra, range.startColumn, range.endLineNumber + extra, range.endColumn));
                if (result.length === 0 || !range_1.Range.areIntersectingOrTouching(result[result.length - 1], extendedRange)) {
                    result.push(extendedRange);
                }
                else {
                    result[result.length - 1] = range_1.Range.plusRange(result[result.length - 1], extendedRange);
                }
            }
            return result;
        }
        _updateHintsDecorators(ranges, items) {
            // utils to collect/create injected text decorations
            const newDecorationsData = [];
            const addInjectedText = (item, ref, content, cursorStops, attachedData) => {
                const opts = {
                    content,
                    inlineClassNameAffectsLetterSpacing: true,
                    inlineClassName: ref.className,
                    cursorStops,
                    attachedData
                };
                newDecorationsData.push({
                    item,
                    classNameRef: ref,
                    decoration: {
                        range: item.anchor.range,
                        options: {
                            // className: "rangeHighlight", // DEBUG highlight to see to what range a hint is attached
                            description: 'InlayHint',
                            showIfCollapsed: item.anchor.range.isEmpty(), // "original" range is empty
                            collapseOnReplaceEdit: !item.anchor.range.isEmpty(),
                            stickiness: 0 /* TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges */,
                            [item.anchor.direction]: this._activeRenderMode === 0 /* RenderMode.Normal */ ? opts : undefined
                        }
                    }
                });
            };
            const addInjectedWhitespace = (item, isLast) => {
                const marginRule = this._ruleFactory.createClassNameRef({
                    width: `${(fontSize / 3) | 0}px`,
                    display: 'inline-block'
                });
                addInjectedText(item, marginRule, '\u200a', isLast ? model_1.InjectedTextCursorStops.Right : model_1.InjectedTextCursorStops.None);
            };
            //
            const { fontSize, fontFamily, padding, isUniform } = this._getLayoutInfo();
            const fontFamilyVar = '--code-editorInlayHintsFontFamily';
            this._editor.getContainerDomNode().style.setProperty(fontFamilyVar, fontFamily);
            let currentLineInfo = { line: 0, totalLen: 0 };
            for (const item of items) {
                if (currentLineInfo.line !== item.anchor.range.startLineNumber) {
                    currentLineInfo = { line: item.anchor.range.startLineNumber, totalLen: 0 };
                }
                if (currentLineInfo.totalLen > InlayHintsController_1._MAX_LABEL_LEN) {
                    continue;
                }
                // whitespace leading the actual label
                if (item.hint.paddingLeft) {
                    addInjectedWhitespace(item, false);
                }
                // the label with its parts
                const parts = typeof item.hint.label === 'string'
                    ? [{ label: item.hint.label }]
                    : item.hint.label;
                for (let i = 0; i < parts.length; i++) {
                    const part = parts[i];
                    const isFirst = i === 0;
                    const isLast = i === parts.length - 1;
                    const cssProperties = {
                        fontSize: `${fontSize}px`,
                        fontFamily: `var(${fontFamilyVar}), ${editorOptions_1.EDITOR_FONT_DEFAULTS.fontFamily}`,
                        verticalAlign: isUniform ? 'baseline' : 'middle',
                        unicodeBidi: 'isolate'
                    };
                    if ((0, arrays_1.isNonEmptyArray)(item.hint.textEdits)) {
                        cssProperties.cursor = 'default';
                    }
                    this._fillInColors(cssProperties, item.hint);
                    if ((part.command || part.location) && this._activeInlayHintPart?.part.item === item && this._activeInlayHintPart.part.index === i) {
                        // active link!
                        cssProperties.textDecoration = 'underline';
                        if (this._activeInlayHintPart.hasTriggerModifier) {
                            cssProperties.color = (0, themeService_1.themeColorFromId)(colors.editorActiveLinkForeground);
                            cssProperties.cursor = 'pointer';
                        }
                    }
                    if (padding) {
                        if (isFirst && isLast) {
                            // only element
                            cssProperties.padding = `1px ${Math.max(1, fontSize / 4) | 0}px`;
                            cssProperties.borderRadius = `${(fontSize / 4) | 0}px`;
                        }
                        else if (isFirst) {
                            // first element
                            cssProperties.padding = `1px 0 1px ${Math.max(1, fontSize / 4) | 0}px`;
                            cssProperties.borderRadius = `${(fontSize / 4) | 0}px 0 0 ${(fontSize / 4) | 0}px`;
                        }
                        else if (isLast) {
                            // last element
                            cssProperties.padding = `1px ${Math.max(1, fontSize / 4) | 0}px 1px 0`;
                            cssProperties.borderRadius = `0 ${(fontSize / 4) | 0}px ${(fontSize / 4) | 0}px 0`;
                        }
                        else {
                            cssProperties.padding = `1px 0 1px 0`;
                        }
                    }
                    let textlabel = part.label;
                    currentLineInfo.totalLen += textlabel.length;
                    let tooLong = false;
                    const over = currentLineInfo.totalLen - InlayHintsController_1._MAX_LABEL_LEN;
                    if (over > 0) {
                        textlabel = textlabel.slice(0, -over) + '…';
                        tooLong = true;
                    }
                    addInjectedText(item, this._ruleFactory.createClassNameRef(cssProperties), fixSpace(textlabel), isLast && !item.hint.paddingRight ? model_1.InjectedTextCursorStops.Right : model_1.InjectedTextCursorStops.None, new RenderedInlayHintLabelPart(item, i));
                    if (tooLong) {
                        break;
                    }
                }
                // whitespace trailing the actual label
                if (item.hint.paddingRight) {
                    addInjectedWhitespace(item, true);
                }
                if (newDecorationsData.length > InlayHintsController_1._MAX_DECORATORS) {
                    break;
                }
            }
            // collect all decoration ids that are affected by the ranges
            // and only update those decorations
            const decorationIdsToReplace = [];
            for (const [id, metadata] of this._decorationsMetadata) {
                const range = this._editor.getModel()?.getDecorationRange(id);
                if (range && ranges.some(r => r.containsRange(range))) {
                    decorationIdsToReplace.push(id);
                    metadata.classNameRef.dispose();
                    this._decorationsMetadata.delete(id);
                }
            }
            const scrollState = stableEditorScroll_1.StableEditorScrollState.capture(this._editor);
            this._editor.changeDecorations(accessor => {
                const newDecorationIds = accessor.deltaDecorations(decorationIdsToReplace, newDecorationsData.map(d => d.decoration));
                for (let i = 0; i < newDecorationIds.length; i++) {
                    const data = newDecorationsData[i];
                    this._decorationsMetadata.set(newDecorationIds[i], data);
                }
            });
            scrollState.restore(this._editor);
        }
        _fillInColors(props, hint) {
            if (hint.kind === languages.InlayHintKind.Parameter) {
                props.backgroundColor = (0, themeService_1.themeColorFromId)(colors.editorInlayHintParameterBackground);
                props.color = (0, themeService_1.themeColorFromId)(colors.editorInlayHintParameterForeground);
            }
            else if (hint.kind === languages.InlayHintKind.Type) {
                props.backgroundColor = (0, themeService_1.themeColorFromId)(colors.editorInlayHintTypeBackground);
                props.color = (0, themeService_1.themeColorFromId)(colors.editorInlayHintTypeForeground);
            }
            else {
                props.backgroundColor = (0, themeService_1.themeColorFromId)(colors.editorInlayHintBackground);
                props.color = (0, themeService_1.themeColorFromId)(colors.editorInlayHintForeground);
            }
        }
        _getLayoutInfo() {
            const options = this._editor.getOption(142 /* EditorOption.inlayHints */);
            const padding = options.padding;
            const editorFontSize = this._editor.getOption(52 /* EditorOption.fontSize */);
            const editorFontFamily = this._editor.getOption(49 /* EditorOption.fontFamily */);
            let fontSize = options.fontSize;
            if (!fontSize || fontSize < 5 || fontSize > editorFontSize) {
                fontSize = editorFontSize;
            }
            const fontFamily = options.fontFamily || editorFontFamily;
            const isUniform = !padding
                && fontFamily === editorFontFamily
                && fontSize === editorFontSize;
            return { fontSize, fontFamily, padding, isUniform };
        }
        _removeAllDecorations() {
            this._editor.removeDecorations(Array.from(this._decorationsMetadata.keys()));
            for (const obj of this._decorationsMetadata.values()) {
                obj.classNameRef.dispose();
            }
            this._decorationsMetadata.clear();
        }
    };
    exports.InlayHintsController = InlayHintsController;
    exports.InlayHintsController = InlayHintsController = InlayHintsController_1 = __decorate([
        __param(1, languageFeatures_1.ILanguageFeaturesService),
        __param(2, languageFeatureDebounce_1.ILanguageFeatureDebounceService),
        __param(3, IInlayHintsCache),
        __param(4, commands_1.ICommandService),
        __param(5, notification_1.INotificationService),
        __param(6, instantiation_1.IInstantiationService)
    ], InlayHintsController);
    // Prevents the view from potentially visible whitespace
    function fixSpace(str) {
        const noBreakWhitespace = '\xa0';
        return str.replace(/[ \t]/g, noBreakWhitespace);
    }
    commands_1.CommandsRegistry.registerCommand('_executeInlayHintProvider', async (accessor, ...args) => {
        const [uri, range] = args;
        (0, types_1.assertType)(uri_1.URI.isUri(uri));
        (0, types_1.assertType)(range_1.Range.isIRange(range));
        const { inlayHintsProvider } = accessor.get(languageFeatures_1.ILanguageFeaturesService);
        const ref = await accessor.get(resolverService_1.ITextModelService).createModelReference(uri);
        try {
            const model = await inlayHints_1.InlayHintsFragments.create(inlayHintsProvider, ref.object.textEditorModel, [range_1.Range.lift(range)], cancellation_1.CancellationToken.None);
            const result = model.items.map(i => i.hint);
            setTimeout(() => model.dispose(), 0); // dispose after sending to ext host
            return result;
        }
        finally {
            ref.dispose();
        }
    });
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[432/*vs/editor/contrib/inlayHints/browser/inlayHintsHover*/], __M([1/*require*/,0/*exports*/,14/*vs/base/common/async*/,57/*vs/base/common/htmlContent*/,9/*vs/editor/common/core/position*/,35/*vs/editor/common/model/textModel*/,84/*vs/editor/contrib/hover/browser/hoverTypes*/,43/*vs/editor/common/languages/language*/,78/*vs/editor/common/services/resolverService*/,410/*vs/editor/contrib/hover/browser/getHover*/,217/*vs/editor/contrib/hover/browser/markdownHoverParticipant*/,431/*vs/editor/contrib/inlayHints/browser/inlayHintsController*/,28/*vs/platform/configuration/common/configuration*/,59/*vs/platform/opener/common/opener*/,17/*vs/editor/common/services/languageFeatures*/,3/*vs/nls*/,16/*vs/base/common/platform*/,377/*vs/editor/contrib/inlayHints/browser/inlayHints*/,13/*vs/base/common/arrays*/,31/*vs/platform/keybinding/common/keybinding*/,118/*vs/platform/hover/browser/hover*/,24/*vs/platform/commands/common/commands*/]), function (require, exports, async_1, htmlContent_1, position_1, textModel_1, hoverTypes_1, language_1, resolverService_1, getHover_1, markdownHoverParticipant_1, inlayHintsController_1, configuration_1, opener_1, languageFeatures_1, nls_1, platform, inlayHints_1, arrays_1, keybinding_1, hover_1, commands_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.InlayHintsHover = void 0;
    class InlayHintsHoverAnchor extends hoverTypes_1.HoverForeignElementAnchor {
        constructor(part, owner, initialMousePosX, initialMousePosY) {
            super(10, owner, part.item.anchor.range, initialMousePosX, initialMousePosY, true);
            this.part = part;
        }
    }
    let InlayHintsHover = class InlayHintsHover extends markdownHoverParticipant_1.MarkdownHoverParticipant {
        constructor(editor, languageService, openerService, keybindingService, hoverService, configurationService, _resolverService, languageFeaturesService, commandService) {
            super(editor, languageService, openerService, configurationService, languageFeaturesService, keybindingService, hoverService, commandService);
            this._resolverService = _resolverService;
            this.hoverOrdinal = 6;
        }
        suggestHoverAnchor(mouseEvent) {
            const controller = inlayHintsController_1.InlayHintsController.get(this._editor);
            if (!controller) {
                return null;
            }
            if (mouseEvent.target.type !== 6 /* MouseTargetType.CONTENT_TEXT */) {
                return null;
            }
            const options = mouseEvent.target.detail.injectedText?.options;
            if (!(options instanceof textModel_1.ModelDecorationInjectedTextOptions && options.attachedData instanceof inlayHintsController_1.RenderedInlayHintLabelPart)) {
                return null;
            }
            return new InlayHintsHoverAnchor(options.attachedData, this, mouseEvent.event.posx, mouseEvent.event.posy);
        }
        computeSync() {
            return [];
        }
        computeAsync(anchor, _lineDecorations, token) {
            if (!(anchor instanceof InlayHintsHoverAnchor)) {
                return async_1.AsyncIterableObject.EMPTY;
            }
            return new async_1.AsyncIterableObject(async (executor) => {
                const { part } = anchor;
                await part.item.resolve(token);
                if (token.isCancellationRequested) {
                    return;
                }
                // (1) Inlay Tooltip
                let itemTooltip;
                if (typeof part.item.hint.tooltip === 'string') {
                    itemTooltip = new htmlContent_1.MarkdownString().appendText(part.item.hint.tooltip);
                }
                else if (part.item.hint.tooltip) {
                    itemTooltip = part.item.hint.tooltip;
                }
                if (itemTooltip) {
                    executor.emitOne(new markdownHoverParticipant_1.MarkdownHover(this, anchor.range, [itemTooltip], false, 0));
                }
                // (1.2) Inlay dbl-click gesture
                if ((0, arrays_1.isNonEmptyArray)(part.item.hint.textEdits)) {
                    executor.emitOne(new markdownHoverParticipant_1.MarkdownHover(this, anchor.range, [new htmlContent_1.MarkdownString().appendText((0, nls_1.localize)(1065, "Double-click to insert"))], false, 10001));
                }
                // (2) Inlay Label Part Tooltip
                let partTooltip;
                if (typeof part.part.tooltip === 'string') {
                    partTooltip = new htmlContent_1.MarkdownString().appendText(part.part.tooltip);
                }
                else if (part.part.tooltip) {
                    partTooltip = part.part.tooltip;
                }
                if (partTooltip) {
                    executor.emitOne(new markdownHoverParticipant_1.MarkdownHover(this, anchor.range, [partTooltip], false, 1));
                }
                // (2.2) Inlay Label Part Help Hover
                if (part.part.location || part.part.command) {
                    let linkHint;
                    const useMetaKey = this._editor.getOption(78 /* EditorOption.multiCursorModifier */) === 'altKey';
                    const kb = useMetaKey
                        ? platform.isMacintosh
                            ? (0, nls_1.localize)(1066, "cmd + click")
                            : (0, nls_1.localize)(1067, "ctrl + click")
                        : platform.isMacintosh
                            ? (0, nls_1.localize)(1068, "option + click")
                            : (0, nls_1.localize)(1069, "alt + click");
                    if (part.part.location && part.part.command) {
                        linkHint = new htmlContent_1.MarkdownString().appendText((0, nls_1.localize)(1070, 'Go to Definition ({0}), right click for more', kb));
                    }
                    else if (part.part.location) {
                        linkHint = new htmlContent_1.MarkdownString().appendText((0, nls_1.localize)(1071, 'Go to Definition ({0})', kb));
                    }
                    else if (part.part.command) {
                        linkHint = new htmlContent_1.MarkdownString(`[${(0, nls_1.localize)(1072, "Execute Command")}](${(0, inlayHints_1.asCommandLink)(part.part.command)} "${part.part.command.title}") (${kb})`, { isTrusted: true });
                    }
                    if (linkHint) {
                        executor.emitOne(new markdownHoverParticipant_1.MarkdownHover(this, anchor.range, [linkHint], false, 10000));
                    }
                }
                // (3) Inlay Label Part Location tooltip
                const iterable = await this._resolveInlayHintLabelPartHover(part, token);
                for await (const item of iterable) {
                    executor.emitOne(item);
                }
            });
        }
        async _resolveInlayHintLabelPartHover(part, token) {
            if (!part.part.location) {
                return async_1.AsyncIterableObject.EMPTY;
            }
            const { uri, range } = part.part.location;
            const ref = await this._resolverService.createModelReference(uri);
            try {
                const model = ref.object.textEditorModel;
                if (!this._languageFeaturesService.hoverProvider.has(model)) {
                    return async_1.AsyncIterableObject.EMPTY;
                }
                return (0, getHover_1.getHoverProviderResultsAsAsyncIterable)(this._languageFeaturesService.hoverProvider, model, new position_1.Position(range.startLineNumber, range.startColumn), token)
                    .filter(item => !(0, htmlContent_1.isEmptyMarkdownString)(item.hover.contents))
                    .map(item => new markdownHoverParticipant_1.MarkdownHover(this, part.item.anchor.range, item.hover.contents, false, 2 + item.ordinal));
            }
            finally {
                ref.dispose();
            }
        }
    };
    exports.InlayHintsHover = InlayHintsHover;
    exports.InlayHintsHover = InlayHintsHover = __decorate([
        __param(1, language_1.ILanguageService),
        __param(2, opener_1.IOpenerService),
        __param(3, keybinding_1.IKeybindingService),
        __param(4, hover_1.IHoverService),
        __param(5, configuration_1.IConfigurationService),
        __param(6, resolverService_1.ITextModelService),
        __param(7, languageFeatures_1.ILanguageFeaturesService),
        __param(8, commands_1.ICommandService)
    ], InlayHintsHover);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[846/*vs/editor/contrib/hover/browser/contentHoverRendered*/], __M([1/*require*/,0/*exports*/,84/*vs/editor/contrib/hover/browser/hoverTypes*/,2/*vs/base/common/lifecycle*/,391/*vs/editor/contrib/hover/browser/contentHoverStatusBar*/,35/*vs/editor/common/model/textModel*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/,5/*vs/base/browser/dom*/,217/*vs/editor/contrib/hover/browser/markdownHoverParticipant*/,288/*vs/editor/contrib/colorPicker/browser/colorHoverParticipant*/,432/*vs/editor/contrib/inlayHints/browser/inlayHintsHover*/,8/*vs/base/common/errors*/]), function (require, exports, hoverTypes_1, lifecycle_1, contentHoverStatusBar_1, textModel_1, position_1, range_1, dom, markdownHoverParticipant_1, colorHoverParticipant_1, inlayHintsHover_1, errors_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.RenderedContentHover = void 0;
    class RenderedContentHover extends lifecycle_1.Disposable {
        constructor(editor, hoverResult, participants, computer, context, keybindingService) {
            super();
            const anchor = hoverResult.anchor;
            const parts = hoverResult.hoverParts;
            this._renderedHoverParts = this._register(new RenderedContentHoverParts(editor, participants, parts, keybindingService, context));
            const { showAtPosition, showAtSecondaryPosition } = RenderedContentHover.computeHoverPositions(editor, anchor.range, parts);
            this.shouldAppearBeforeContent = parts.some(m => m.isBeforeContent);
            this.showAtPosition = showAtPosition;
            this.showAtSecondaryPosition = showAtSecondaryPosition;
            this.initialMousePosX = anchor.initialMousePosX;
            this.initialMousePosY = anchor.initialMousePosY;
            this.shouldFocus = computer.shouldFocus;
            this.source = computer.source;
        }
        get domNode() {
            return this._renderedHoverParts.domNode;
        }
        get domNodeHasChildren() {
            return this._renderedHoverParts.domNodeHasChildren;
        }
        get focusedHoverPartIndex() {
            return this._renderedHoverParts.focusedHoverPartIndex;
        }
        async updateHoverVerbosityLevel(action, index, focus) {
            this._renderedHoverParts.updateHoverVerbosityLevel(action, index, focus);
        }
        isColorPickerVisible() {
            return this._renderedHoverParts.isColorPickerVisible();
        }
        static computeHoverPositions(editor, anchorRange, hoverParts) {
            let startColumnBoundary = 1;
            if (editor.hasModel()) {
                // Ensure the range is on the current view line
                const viewModel = editor._getViewModel();
                const coordinatesConverter = viewModel.coordinatesConverter;
                const anchorViewRange = coordinatesConverter.convertModelRangeToViewRange(anchorRange);
                const anchorViewMinColumn = viewModel.getLineMinColumn(anchorViewRange.startLineNumber);
                const anchorViewRangeStart = new position_1.Position(anchorViewRange.startLineNumber, anchorViewMinColumn);
                startColumnBoundary = coordinatesConverter.convertViewPositionToModelPosition(anchorViewRangeStart).column;
            }
            // The anchor range is always on a single line
            const anchorStartLineNumber = anchorRange.startLineNumber;
            let secondaryPositionColumn = anchorRange.startColumn;
            let forceShowAtRange;
            for (const hoverPart of hoverParts) {
                const hoverPartRange = hoverPart.range;
                const hoverPartRangeOnAnchorStartLine = hoverPartRange.startLineNumber === anchorStartLineNumber;
                const hoverPartRangeOnAnchorEndLine = hoverPartRange.endLineNumber === anchorStartLineNumber;
                const hoverPartRangeIsOnAnchorLine = hoverPartRangeOnAnchorStartLine && hoverPartRangeOnAnchorEndLine;
                if (hoverPartRangeIsOnAnchorLine) {
                    // this message has a range that is completely sitting on the line of the anchor
                    const hoverPartStartColumn = hoverPartRange.startColumn;
                    const minSecondaryPositionColumn = Math.min(secondaryPositionColumn, hoverPartStartColumn);
                    secondaryPositionColumn = Math.max(minSecondaryPositionColumn, startColumnBoundary);
                }
                if (hoverPart.forceShowAtRange) {
                    forceShowAtRange = hoverPartRange;
                }
            }
            let showAtPosition;
            let showAtSecondaryPosition;
            if (forceShowAtRange) {
                const forceShowAtPosition = forceShowAtRange.getStartPosition();
                showAtPosition = forceShowAtPosition;
                showAtSecondaryPosition = forceShowAtPosition;
            }
            else {
                showAtPosition = anchorRange.getStartPosition();
                showAtSecondaryPosition = new position_1.Position(anchorStartLineNumber, secondaryPositionColumn);
            }
            return {
                showAtPosition,
                showAtSecondaryPosition,
            };
        }
    }
    exports.RenderedContentHover = RenderedContentHover;
    class RenderedStatusBar {
        constructor(fragment, _statusBar) {
            this._statusBar = _statusBar;
            fragment.appendChild(this._statusBar.hoverElement);
        }
        get hoverElement() {
            return this._statusBar.hoverElement;
        }
        get actions() {
            return this._statusBar.actions;
        }
        dispose() {
            this._statusBar.dispose();
        }
    }
    class RenderedContentHoverParts extends lifecycle_1.Disposable {
        static { this._DECORATION_OPTIONS = textModel_1.ModelDecorationOptions.register({
            description: 'content-hover-highlight',
            className: 'hoverHighlight'
        }); }
        constructor(editor, participants, hoverParts, keybindingService, context) {
            super();
            this._renderedParts = [];
            this._focusedHoverPartIndex = -1;
            this._context = context;
            this._fragment = document.createDocumentFragment();
            this._register(this._renderParts(participants, hoverParts, context, keybindingService));
            this._register(this._registerListenersOnRenderedParts());
            this._register(this._createEditorDecorations(editor, hoverParts));
            this._updateMarkdownAndColorParticipantInfo(participants);
        }
        _createEditorDecorations(editor, hoverParts) {
            if (hoverParts.length === 0) {
                return lifecycle_1.Disposable.None;
            }
            let highlightRange = hoverParts[0].range;
            for (const hoverPart of hoverParts) {
                const hoverPartRange = hoverPart.range;
                highlightRange = range_1.Range.plusRange(highlightRange, hoverPartRange);
            }
            const highlightDecoration = editor.createDecorationsCollection();
            highlightDecoration.set([{
                    range: highlightRange,
                    options: RenderedContentHoverParts._DECORATION_OPTIONS
                }]);
            return (0, lifecycle_1.toDisposable)(() => {
                highlightDecoration.clear();
            });
        }
        _renderParts(participants, hoverParts, hoverContext, keybindingService) {
            const statusBar = new contentHoverStatusBar_1.EditorHoverStatusBar(keybindingService);
            const hoverRenderingContext = {
                fragment: this._fragment,
                statusBar,
                ...hoverContext
            };
            const disposables = new lifecycle_1.DisposableStore();
            for (const participant of participants) {
                const renderedHoverParts = this._renderHoverPartsForParticipant(hoverParts, participant, hoverRenderingContext);
                disposables.add(renderedHoverParts);
                for (const renderedHoverPart of renderedHoverParts.renderedHoverParts) {
                    this._renderedParts.push({
                        type: 'hoverPart',
                        participant,
                        hoverPart: renderedHoverPart.hoverPart,
                        hoverElement: renderedHoverPart.hoverElement,
                    });
                }
            }
            const renderedStatusBar = this._renderStatusBar(this._fragment, statusBar);
            if (renderedStatusBar) {
                disposables.add(renderedStatusBar);
                this._renderedParts.push({
                    type: 'statusBar',
                    hoverElement: renderedStatusBar.hoverElement,
                    actions: renderedStatusBar.actions,
                });
            }
            return (0, lifecycle_1.toDisposable)(() => { disposables.dispose(); });
        }
        _renderHoverPartsForParticipant(hoverParts, participant, hoverRenderingContext) {
            const hoverPartsForParticipant = hoverParts.filter(hoverPart => hoverPart.owner === participant);
            const hasHoverPartsForParticipant = hoverPartsForParticipant.length > 0;
            if (!hasHoverPartsForParticipant) {
                return new hoverTypes_1.RenderedHoverParts([]);
            }
            return participant.renderHoverParts(hoverRenderingContext, hoverPartsForParticipant);
        }
        _renderStatusBar(fragment, statusBar) {
            if (!statusBar.hasContent) {
                return undefined;
            }
            return new RenderedStatusBar(fragment, statusBar);
        }
        _registerListenersOnRenderedParts() {
            const disposables = new lifecycle_1.DisposableStore();
            this._renderedParts.forEach((renderedPart, index) => {
                const element = renderedPart.hoverElement;
                element.tabIndex = 0;
                disposables.add(dom.addDisposableListener(element, dom.EventType.FOCUS_IN, (event) => {
                    event.stopPropagation();
                    this._focusedHoverPartIndex = index;
                }));
                disposables.add(dom.addDisposableListener(element, dom.EventType.FOCUS_OUT, (event) => {
                    event.stopPropagation();
                    this._focusedHoverPartIndex = -1;
                }));
            });
            return disposables;
        }
        _updateMarkdownAndColorParticipantInfo(participants) {
            const markdownHoverParticipant = participants.find(p => {
                return (p instanceof markdownHoverParticipant_1.MarkdownHoverParticipant) && !(p instanceof inlayHintsHover_1.InlayHintsHover);
            });
            if (markdownHoverParticipant) {
                this._markdownHoverParticipant = markdownHoverParticipant;
            }
            this._colorHoverParticipant = participants.find(p => p instanceof colorHoverParticipant_1.ColorHoverParticipant);
        }
        async updateHoverVerbosityLevel(action, index, focus) {
            if (!this._markdownHoverParticipant) {
                return;
            }
            const normalizedMarkdownHoverIndex = this._normalizedIndexToMarkdownHoverIndexRange(this._markdownHoverParticipant, index);
            if (normalizedMarkdownHoverIndex === undefined) {
                return;
            }
            const renderedPart = await this._markdownHoverParticipant.updateMarkdownHoverVerbosityLevel(action, normalizedMarkdownHoverIndex, focus);
            if (!renderedPart) {
                return;
            }
            this._renderedParts[index] = {
                type: 'hoverPart',
                participant: this._markdownHoverParticipant,
                hoverPart: renderedPart.hoverPart,
                hoverElement: renderedPart.hoverElement,
            };
            this._context.onContentsChanged();
        }
        isColorPickerVisible() {
            return this._colorHoverParticipant?.isColorPickerVisible() ?? false;
        }
        _normalizedIndexToMarkdownHoverIndexRange(markdownHoverParticipant, index) {
            const renderedPart = this._renderedParts[index];
            if (!renderedPart || renderedPart.type !== 'hoverPart') {
                return undefined;
            }
            const isHoverPartMarkdownHover = renderedPart.participant === markdownHoverParticipant;
            if (!isHoverPartMarkdownHover) {
                return undefined;
            }
            const firstIndexOfMarkdownHovers = this._renderedParts.findIndex(renderedPart => renderedPart.type === 'hoverPart'
                && renderedPart.participant === markdownHoverParticipant);
            if (firstIndexOfMarkdownHovers === -1) {
                throw new errors_1.BugIndicatingError();
            }
            return index - firstIndexOfMarkdownHovers;
        }
        get domNode() {
            return this._fragment;
        }
        get domNodeHasChildren() {
            return this._fragment.hasChildNodes();
        }
        get focusedHoverPartIndex() {
            return this._focusedHoverPartIndex;
        }
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[847/*vs/editor/contrib/hover/browser/contentHoverWidgetWrapper*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,2/*vs/base/common/lifecycle*/,27/*vs/editor/common/languages*/,376/*vs/editor/contrib/hover/browser/hoverOperation*/,84/*vs/editor/contrib/hover/browser/hoverTypes*/,7/*vs/platform/instantiation/common/instantiation*/,31/*vs/platform/keybinding/common/keybinding*/,690/*vs/editor/contrib/hover/browser/contentHoverWidget*/,668/*vs/editor/contrib/hover/browser/contentHoverComputer*/,614/*vs/editor/contrib/hover/browser/contentHoverTypes*/,6/*vs/base/common/event*/,846/*vs/editor/contrib/hover/browser/contentHoverRendered*/,210/*vs/editor/contrib/hover/browser/hoverUtils*/]), function (require, exports, dom, lifecycle_1, languages_1, hoverOperation_1, hoverTypes_1, instantiation_1, keybinding_1, contentHoverWidget_1, contentHoverComputer_1, contentHoverTypes_1, event_1, contentHoverRendered_1, hoverUtils_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ContentHoverWidgetWrapper = void 0;
    let ContentHoverWidgetWrapper = class ContentHoverWidgetWrapper extends lifecycle_1.Disposable {
        constructor(_editor, _instantiationService, _keybindingService) {
            super();
            this._editor = _editor;
            this._instantiationService = _instantiationService;
            this._keybindingService = _keybindingService;
            this._currentResult = null;
            this._onContentsChanged = this._register(new event_1.Emitter());
            this.onContentsChanged = this._onContentsChanged.event;
            this._contentHoverWidget = this._register(this._instantiationService.createInstance(contentHoverWidget_1.ContentHoverWidget, this._editor));
            this._participants = this._initializeHoverParticipants();
            this._computer = new contentHoverComputer_1.ContentHoverComputer(this._editor, this._participants);
            this._hoverOperation = this._register(new hoverOperation_1.HoverOperation(this._editor, this._computer));
            this._registerListeners();
        }
        _initializeHoverParticipants() {
            const participants = [];
            for (const participant of hoverTypes_1.HoverParticipantRegistry.getAll()) {
                const participantInstance = this._instantiationService.createInstance(participant, this._editor);
                participants.push(participantInstance);
            }
            participants.sort((p1, p2) => p1.hoverOrdinal - p2.hoverOrdinal);
            this._register(this._contentHoverWidget.onDidResize(() => {
                this._participants.forEach(participant => participant.handleResize?.());
            }));
            return participants;
        }
        _registerListeners() {
            this._register(this._hoverOperation.onResult((result) => {
                if (!this._computer.anchor) {
                    // invalid state, ignore result
                    return;
                }
                const messages = (result.hasLoadingMessage ? this._addLoadingMessage(result.value) : result.value);
                this._withResult(new contentHoverTypes_1.HoverResult(this._computer.anchor, messages, result.isComplete));
            }));
            const contentHoverWidgetNode = this._contentHoverWidget.getDomNode();
            this._register(dom.addStandardDisposableListener(contentHoverWidgetNode, 'keydown', (e) => {
                if (e.equals(9 /* KeyCode.Escape */)) {
                    this.hide();
                }
            }));
            this._register(dom.addStandardDisposableListener(contentHoverWidgetNode, 'mouseleave', (e) => {
                this._onMouseLeave(e);
            }));
            this._register(languages_1.TokenizationRegistry.onDidChange(() => {
                if (this._contentHoverWidget.position && this._currentResult) {
                    this._setCurrentResult(this._currentResult); // render again
                }
            }));
        }
        /**
         * Returns true if the hover shows now or will show.
         */
        _startShowingOrUpdateHover(anchor, mode, source, focus, mouseEvent) {
            const contentHoverIsVisible = this._contentHoverWidget.position && this._currentResult;
            if (!contentHoverIsVisible) {
                if (anchor) {
                    this._startHoverOperationIfNecessary(anchor, mode, source, focus, false);
                    return true;
                }
                return false;
            }
            const isHoverSticky = this._editor.getOption(60 /* EditorOption.hover */).sticky;
            const isMouseGettingCloser = mouseEvent && this._contentHoverWidget.isMouseGettingCloser(mouseEvent.event.posx, mouseEvent.event.posy);
            const isHoverStickyAndIsMouseGettingCloser = isHoverSticky && isMouseGettingCloser;
            // The mouse is getting closer to the hover, so we will keep the hover untouched
            // But we will kick off a hover update at the new anchor, insisting on keeping the hover visible.
            if (isHoverStickyAndIsMouseGettingCloser) {
                if (anchor) {
                    this._startHoverOperationIfNecessary(anchor, mode, source, focus, true);
                }
                return true;
            }
            // If mouse is not getting closer and anchor not defined, hide the hover
            if (!anchor) {
                this._setCurrentResult(null);
                return false;
            }
            // If mouse if not getting closer and anchor is defined, and the new anchor is the same as the previous anchor
            const currentAnchorEqualsPreviousAnchor = this._currentResult.anchor.equals(anchor);
            if (currentAnchorEqualsPreviousAnchor) {
                return true;
            }
            // If mouse if not getting closer and anchor is defined, and the new anchor is not compatible with the previous anchor
            const currentAnchorCompatibleWithPreviousAnchor = anchor.canAdoptVisibleHover(this._currentResult.anchor, this._contentHoverWidget.position);
            if (!currentAnchorCompatibleWithPreviousAnchor) {
                this._setCurrentResult(null);
                this._startHoverOperationIfNecessary(anchor, mode, source, focus, false);
                return true;
            }
            // We aren't getting any closer to the hover, so we will filter existing results
            // and keep those which also apply to the new anchor.
            this._setCurrentResult(this._currentResult.filter(anchor));
            this._startHoverOperationIfNecessary(anchor, mode, source, focus, false);
            return true;
        }
        _startHoverOperationIfNecessary(anchor, mode, source, focus, insistOnKeepingHoverVisible) {
            const currentAnchorEqualToPreviousHover = this._computer.anchor && this._computer.anchor.equals(anchor);
            if (currentAnchorEqualToPreviousHover) {
                return;
            }
            this._hoverOperation.cancel();
            this._computer.anchor = anchor;
            this._computer.shouldFocus = focus;
            this._computer.source = source;
            this._computer.insistOnKeepingHoverVisible = insistOnKeepingHoverVisible;
            this._hoverOperation.start(mode);
        }
        _setCurrentResult(hoverResult) {
            let currentHoverResult = hoverResult;
            const currentResultEqualToPreviousResult = this._currentResult === currentHoverResult;
            if (currentResultEqualToPreviousResult) {
                return;
            }
            const currentHoverResultIsEmpty = currentHoverResult && currentHoverResult.hoverParts.length === 0;
            if (currentHoverResultIsEmpty) {
                currentHoverResult = null;
            }
            this._currentResult = currentHoverResult;
            if (this._currentResult) {
                this._showHover(this._currentResult);
            }
            else {
                this._hideHover();
            }
        }
        _addLoadingMessage(result) {
            if (!this._computer.anchor) {
                return result;
            }
            for (const participant of this._participants) {
                if (!participant.createLoadingMessage) {
                    continue;
                }
                const loadingMessage = participant.createLoadingMessage(this._computer.anchor);
                if (!loadingMessage) {
                    continue;
                }
                return result.slice(0).concat([loadingMessage]);
            }
            return result;
        }
        _withResult(hoverResult) {
            const previousHoverIsVisibleWithCompleteResult = this._contentHoverWidget.position && this._currentResult && this._currentResult.isComplete;
            if (!previousHoverIsVisibleWithCompleteResult) {
                this._setCurrentResult(hoverResult);
            }
            // The hover is visible with a previous complete result.
            const isCurrentHoverResultComplete = hoverResult.isComplete;
            if (!isCurrentHoverResultComplete) {
                // Instead of rendering the new partial result, we wait for the result to be complete.
                return;
            }
            const currentHoverResultIsEmpty = hoverResult.hoverParts.length === 0;
            const insistOnKeepingPreviousHoverVisible = this._computer.insistOnKeepingHoverVisible;
            const shouldKeepPreviousHoverVisible = currentHoverResultIsEmpty && insistOnKeepingPreviousHoverVisible;
            if (shouldKeepPreviousHoverVisible) {
                // The hover would now hide normally, so we'll keep the previous messages
                return;
            }
            this._setCurrentResult(hoverResult);
        }
        _showHover(hoverResult) {
            const context = this._getHoverContext();
            this._renderedContentHover = new contentHoverRendered_1.RenderedContentHover(this._editor, hoverResult, this._participants, this._computer, context, this._keybindingService);
            if (this._renderedContentHover.domNodeHasChildren) {
                this._contentHoverWidget.show(this._renderedContentHover);
            }
            else {
                this._renderedContentHover.dispose();
            }
        }
        _hideHover() {
            this._contentHoverWidget.hide();
        }
        _getHoverContext() {
            const hide = () => {
                this.hide();
            };
            const onContentsChanged = () => {
                this._onContentsChanged.fire();
                this._contentHoverWidget.onContentsChanged();
            };
            const setMinimumDimensions = (dimensions) => {
                this._contentHoverWidget.setMinimumDimensions(dimensions);
            };
            return { hide, onContentsChanged, setMinimumDimensions };
        }
        showsOrWillShow(mouseEvent) {
            const isContentWidgetResizing = this._contentHoverWidget.isResizing;
            if (isContentWidgetResizing) {
                return true;
            }
            const anchorCandidates = this._findHoverAnchorCandidates(mouseEvent);
            const anchorCandidatesExist = anchorCandidates.length > 0;
            if (!anchorCandidatesExist) {
                return this._startShowingOrUpdateHover(null, 0 /* HoverStartMode.Delayed */, 0 /* HoverStartSource.Mouse */, false, mouseEvent);
            }
            const anchor = anchorCandidates[0];
            return this._startShowingOrUpdateHover(anchor, 0 /* HoverStartMode.Delayed */, 0 /* HoverStartSource.Mouse */, false, mouseEvent);
        }
        _findHoverAnchorCandidates(mouseEvent) {
            const anchorCandidates = [];
            for (const participant of this._participants) {
                if (!participant.suggestHoverAnchor) {
                    continue;
                }
                const anchor = participant.suggestHoverAnchor(mouseEvent);
                if (!anchor) {
                    continue;
                }
                anchorCandidates.push(anchor);
            }
            const target = mouseEvent.target;
            switch (target.type) {
                case 6 /* MouseTargetType.CONTENT_TEXT */: {
                    anchorCandidates.push(new hoverTypes_1.HoverRangeAnchor(0, target.range, mouseEvent.event.posx, mouseEvent.event.posy));
                    break;
                }
                case 7 /* MouseTargetType.CONTENT_EMPTY */: {
                    const epsilon = this._editor.getOption(50 /* EditorOption.fontInfo */).typicalHalfwidthCharacterWidth / 2;
                    // Let hover kick in even when the mouse is technically in the empty area after a line, given the distance is small enough
                    const mouseIsWithinLinesAndCloseToHover = !target.detail.isAfterLines
                        && typeof target.detail.horizontalDistanceToText === 'number'
                        && target.detail.horizontalDistanceToText < epsilon;
                    if (!mouseIsWithinLinesAndCloseToHover) {
                        break;
                    }
                    anchorCandidates.push(new hoverTypes_1.HoverRangeAnchor(0, target.range, mouseEvent.event.posx, mouseEvent.event.posy));
                    break;
                }
            }
            anchorCandidates.sort((a, b) => b.priority - a.priority);
            return anchorCandidates;
        }
        _onMouseLeave(e) {
            const editorDomNode = this._editor.getDomNode();
            const isMousePositionOutsideOfEditor = !editorDomNode || !(0, hoverUtils_1.isMousePositionWithinElement)(editorDomNode, e.x, e.y);
            if (isMousePositionOutsideOfEditor) {
                this.hide();
            }
        }
        startShowingAtRange(range, mode, source, focus) {
            this._startShowingOrUpdateHover(new hoverTypes_1.HoverRangeAnchor(0, range, undefined, undefined), mode, source, focus, null);
        }
        async updateHoverVerbosityLevel(action, index, focus) {
            this._renderedContentHover?.updateHoverVerbosityLevel(action, index, focus);
        }
        focusedHoverPartIndex() {
            return this._renderedContentHover?.focusedHoverPartIndex ?? -1;
        }
        containsNode(node) {
            return (node ? this._contentHoverWidget.getDomNode().contains(node) : false);
        }
        focus() {
            this._contentHoverWidget.focus();
        }
        scrollUp() {
            this._contentHoverWidget.scrollUp();
        }
        scrollDown() {
            this._contentHoverWidget.scrollDown();
        }
        scrollLeft() {
            this._contentHoverWidget.scrollLeft();
        }
        scrollRight() {
            this._contentHoverWidget.scrollRight();
        }
        pageUp() {
            this._contentHoverWidget.pageUp();
        }
        pageDown() {
            this._contentHoverWidget.pageDown();
        }
        goToTop() {
            this._contentHoverWidget.goToTop();
        }
        goToBottom() {
            this._contentHoverWidget.goToBottom();
        }
        hide() {
            this._computer.anchor = null;
            this._hoverOperation.cancel();
            this._setCurrentResult(null);
        }
        getDomNode() {
            return this._contentHoverWidget.getDomNode();
        }
        get isColorPickerVisible() {
            return this._renderedContentHover?.isColorPickerVisible() ?? false;
        }
        get isVisibleFromKeyboard() {
            return this._contentHoverWidget.isVisibleFromKeyboard;
        }
        get isVisible() {
            return this._contentHoverWidget.isVisible;
        }
        get isFocused() {
            return this._contentHoverWidget.isFocused;
        }
        get isResizing() {
            return this._contentHoverWidget.isResizing;
        }
        get widget() {
            return this._contentHoverWidget;
        }
    };
    exports.ContentHoverWidgetWrapper = ContentHoverWidgetWrapper;
    exports.ContentHoverWidgetWrapper = ContentHoverWidgetWrapper = __decorate([
        __param(1, instantiation_1.IInstantiationService),
        __param(2, keybinding_1.IKeybindingService)
    ], ContentHoverWidgetWrapper);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[292/*vs/editor/contrib/hover/browser/contentHoverController2*/], __M([1/*require*/,0/*exports*/,264/*vs/editor/contrib/hover/browser/hoverActionIds*/,2/*vs/base/common/lifecycle*/,7/*vs/platform/instantiation/common/instantiation*/,283/*vs/editor/contrib/inlineCompletions/browser/hintsWidget/inlineCompletionsHintsWidget*/,31/*vs/platform/keybinding/common/keybinding*/,14/*vs/base/common/async*/,210/*vs/editor/contrib/hover/browser/hoverUtils*/,847/*vs/editor/contrib/hover/browser/contentHoverWidgetWrapper*/,6/*vs/base/common/event*/,196/*vs/css!vs/editor/contrib/hover/browser/hover*/]), function (require, exports, hoverActionIds_1, lifecycle_1, instantiation_1, inlineCompletionsHintsWidget_1, keybinding_1, async_1, hoverUtils_1, contentHoverWidgetWrapper_1, event_1) {
    "use strict";
    var ContentHoverController_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ContentHoverController = void 0;
    // sticky hover widget which doesn't disappear on focus out and such
    const _sticky = false;
    let ContentHoverController = class ContentHoverController extends lifecycle_1.Disposable {
        static { ContentHoverController_1 = this; }
        static { this.ID = 'editor.contrib.contentHover'; }
        constructor(_editor, _instantiationService, _keybindingService) {
            super();
            this._editor = _editor;
            this._instantiationService = _instantiationService;
            this._keybindingService = _keybindingService;
            this._onHoverContentsChanged = this._register(new event_1.Emitter());
            this.shouldKeepOpenOnEditorMouseMoveOrLeave = false;
            this._listenersStore = new lifecycle_1.DisposableStore();
            this._hoverState = {
                mouseDown: false,
                activatedByDecoratorClick: false
            };
            this._reactToEditorMouseMoveRunner = this._register(new async_1.RunOnceScheduler(() => this._reactToEditorMouseMove(this._mouseMoveEvent), 0));
            this._hookListeners();
            this._register(this._editor.onDidChangeConfiguration((e) => {
                if (e.hasChanged(60 /* EditorOption.hover */)) {
                    this._unhookListeners();
                    this._hookListeners();
                }
            }));
        }
        static get(editor) {
            return editor.getContribution(ContentHoverController_1.ID);
        }
        _hookListeners() {
            const hoverOpts = this._editor.getOption(60 /* EditorOption.hover */);
            this._hoverSettings = {
                enabled: hoverOpts.enabled,
                sticky: hoverOpts.sticky,
                hidingDelay: hoverOpts.hidingDelay
            };
            if (hoverOpts.enabled) {
                this._listenersStore.add(this._editor.onMouseDown((e) => this._onEditorMouseDown(e)));
                this._listenersStore.add(this._editor.onMouseUp(() => this._onEditorMouseUp()));
                this._listenersStore.add(this._editor.onMouseMove((e) => this._onEditorMouseMove(e)));
                this._listenersStore.add(this._editor.onKeyDown((e) => this._onKeyDown(e)));
            }
            else {
                this._listenersStore.add(this._editor.onMouseMove((e) => this._onEditorMouseMove(e)));
                this._listenersStore.add(this._editor.onKeyDown((e) => this._onKeyDown(e)));
            }
            this._listenersStore.add(this._editor.onMouseLeave((e) => this._onEditorMouseLeave(e)));
            this._listenersStore.add(this._editor.onDidChangeModel(() => {
                this._cancelScheduler();
                this._hideWidgets();
            }));
            this._listenersStore.add(this._editor.onDidChangeModelContent(() => this._cancelScheduler()));
            this._listenersStore.add(this._editor.onDidScrollChange((e) => this._onEditorScrollChanged(e)));
        }
        _unhookListeners() {
            this._listenersStore.clear();
        }
        _cancelScheduler() {
            this._mouseMoveEvent = undefined;
            this._reactToEditorMouseMoveRunner.cancel();
        }
        _onEditorScrollChanged(e) {
            if (e.scrollTopChanged || e.scrollLeftChanged) {
                this._hideWidgets();
            }
        }
        _onEditorMouseDown(mouseEvent) {
            this._hoverState.mouseDown = true;
            const shouldNotHideCurrentHoverWidget = this._shouldNotHideCurrentHoverWidget(mouseEvent);
            if (shouldNotHideCurrentHoverWidget) {
                return;
            }
            this._hideWidgets();
        }
        _shouldNotHideCurrentHoverWidget(mouseEvent) {
            return this._isMouseOnContentHoverWidget(mouseEvent) || this._isContentWidgetResizing();
        }
        _isMouseOnContentHoverWidget(mouseEvent) {
            const contentWidgetNode = this._contentWidget?.getDomNode();
            if (contentWidgetNode) {
                return (0, hoverUtils_1.isMousePositionWithinElement)(contentWidgetNode, mouseEvent.event.posx, mouseEvent.event.posy);
            }
            return false;
        }
        _onEditorMouseUp() {
            this._hoverState.mouseDown = false;
        }
        _onEditorMouseLeave(mouseEvent) {
            if (this.shouldKeepOpenOnEditorMouseMoveOrLeave) {
                return;
            }
            this._cancelScheduler();
            const shouldNotHideCurrentHoverWidget = this._shouldNotHideCurrentHoverWidget(mouseEvent);
            if (shouldNotHideCurrentHoverWidget) {
                return;
            }
            if (_sticky) {
                return;
            }
            this._hideWidgets();
        }
        _shouldNotRecomputeCurrentHoverWidget(mouseEvent) {
            const isHoverSticky = this._hoverSettings.sticky;
            const isMouseOnStickyContentHoverWidget = (mouseEvent, isHoverSticky) => {
                const isMouseOnContentHoverWidget = this._isMouseOnContentHoverWidget(mouseEvent);
                return isHoverSticky && isMouseOnContentHoverWidget;
            };
            const isMouseOnColorPicker = (mouseEvent) => {
                const isMouseOnContentHoverWidget = this._isMouseOnContentHoverWidget(mouseEvent);
                const isColorPickerVisible = this._contentWidget?.isColorPickerVisible ?? false;
                return isMouseOnContentHoverWidget && isColorPickerVisible;
            };
            // TODO@aiday-mar verify if the following is necessary code
            const isTextSelectedWithinContentHoverWidget = (mouseEvent, sticky) => {
                return (sticky
                    && this._contentWidget?.containsNode(mouseEvent.event.browserEvent.view?.document.activeElement)
                    && !mouseEvent.event.browserEvent.view?.getSelection()?.isCollapsed) ?? false;
            };
            return isMouseOnStickyContentHoverWidget(mouseEvent, isHoverSticky)
                || isMouseOnColorPicker(mouseEvent)
                || isTextSelectedWithinContentHoverWidget(mouseEvent, isHoverSticky);
        }
        _onEditorMouseMove(mouseEvent) {
            if (this.shouldKeepOpenOnEditorMouseMoveOrLeave) {
                return;
            }
            this._mouseMoveEvent = mouseEvent;
            if (this._contentWidget?.isFocused || this._contentWidget?.isResizing) {
                return;
            }
            const sticky = this._hoverSettings.sticky;
            if (sticky && this._contentWidget?.isVisibleFromKeyboard) {
                // Sticky mode is on and the hover has been shown via keyboard
                // so moving the mouse has no effect
                return;
            }
            const shouldNotRecomputeCurrentHoverWidget = this._shouldNotRecomputeCurrentHoverWidget(mouseEvent);
            if (shouldNotRecomputeCurrentHoverWidget) {
                this._reactToEditorMouseMoveRunner.cancel();
                return;
            }
            const hidingDelay = this._hoverSettings.hidingDelay;
            const isContentHoverWidgetVisible = this._contentWidget?.isVisible;
            // If the mouse is not over the widget, and if sticky is on,
            // then give it a grace period before reacting to the mouse event
            const shouldRescheduleHoverComputation = isContentHoverWidgetVisible && sticky && hidingDelay > 0;
            if (shouldRescheduleHoverComputation) {
                if (!this._reactToEditorMouseMoveRunner.isScheduled()) {
                    this._reactToEditorMouseMoveRunner.schedule(hidingDelay);
                }
                return;
            }
            this._reactToEditorMouseMove(mouseEvent);
        }
        _reactToEditorMouseMove(mouseEvent) {
            if (!mouseEvent) {
                return;
            }
            const target = mouseEvent.target;
            const mouseOnDecorator = target.element?.classList.contains('colorpicker-color-decoration');
            const decoratorActivatedOn = this._editor.getOption(149 /* EditorOption.colorDecoratorsActivatedOn */);
            const enabled = this._hoverSettings.enabled;
            const activatedByDecoratorClick = this._hoverState.activatedByDecoratorClick;
            if ((mouseOnDecorator && ((decoratorActivatedOn === 'click' && !activatedByDecoratorClick) ||
                (decoratorActivatedOn === 'hover' && !enabled && !_sticky) ||
                (decoratorActivatedOn === 'clickAndHover' && !enabled && !activatedByDecoratorClick))) || (!mouseOnDecorator && !enabled && !activatedByDecoratorClick)) {
                this._hideWidgets();
                return;
            }
            const contentHoverShowsOrWillShow = this._tryShowHoverWidget(mouseEvent);
            if (contentHoverShowsOrWillShow) {
                return;
            }
            if (_sticky) {
                return;
            }
            this._hideWidgets();
        }
        _tryShowHoverWidget(mouseEvent) {
            const contentWidget = this._getOrCreateContentWidget();
            return contentWidget.showsOrWillShow(mouseEvent);
        }
        _onKeyDown(e) {
            if (!this._editor.hasModel()) {
                return;
            }
            const resolvedKeyboardEvent = this._keybindingService.softDispatch(e, this._editor.getDomNode());
            // If the beginning of a multi-chord keybinding is pressed,
            // or the command aims to focus the hover,
            // set the variable to true, otherwise false
            const shouldKeepHoverVisible = (resolvedKeyboardEvent.kind === 1 /* ResultKind.MoreChordsNeeded */ ||
                (resolvedKeyboardEvent.kind === 2 /* ResultKind.KbFound */
                    && (resolvedKeyboardEvent.commandId === hoverActionIds_1.SHOW_OR_FOCUS_HOVER_ACTION_ID
                        || resolvedKeyboardEvent.commandId === hoverActionIds_1.INCREASE_HOVER_VERBOSITY_ACTION_ID
                        || resolvedKeyboardEvent.commandId === hoverActionIds_1.DECREASE_HOVER_VERBOSITY_ACTION_ID)
                    && this._contentWidget?.isVisible));
            if (e.keyCode === 5 /* KeyCode.Ctrl */
                || e.keyCode === 6 /* KeyCode.Alt */
                || e.keyCode === 57 /* KeyCode.Meta */
                || e.keyCode === 4 /* KeyCode.Shift */
                || shouldKeepHoverVisible) {
                // Do not hide hover when a modifier key is pressed
                return;
            }
            this._hideWidgets();
        }
        _hideWidgets() {
            if (_sticky) {
                return;
            }
            if ((this._hoverState.mouseDown
                && this._contentWidget?.isColorPickerVisible) || inlineCompletionsHintsWidget_1.InlineSuggestionHintsContentWidget.dropDownVisible) {
                return;
            }
            this._hoverState.activatedByDecoratorClick = false;
            this._contentWidget?.hide();
        }
        _getOrCreateContentWidget() {
            if (!this._contentWidget) {
                this._contentWidget = this._instantiationService.createInstance(contentHoverWidgetWrapper_1.ContentHoverWidgetWrapper, this._editor);
                this._listenersStore.add(this._contentWidget.onContentsChanged(() => this._onHoverContentsChanged.fire()));
            }
            return this._contentWidget;
        }
        showContentHover(range, mode, source, focus, activatedByColorDecoratorClick = false) {
            this._hoverState.activatedByDecoratorClick = activatedByColorDecoratorClick;
            this._getOrCreateContentWidget().startShowingAtRange(range, mode, source, focus);
        }
        _isContentWidgetResizing() {
            return this._contentWidget?.widget.isResizing || false;
        }
        focusedHoverPartIndex() {
            return this._getOrCreateContentWidget().focusedHoverPartIndex();
        }
        updateHoverVerbosityLevel(action, index, focus) {
            this._getOrCreateContentWidget().updateHoverVerbosityLevel(action, index, focus);
        }
        focus() {
            this._contentWidget?.focus();
        }
        scrollUp() {
            this._contentWidget?.scrollUp();
        }
        scrollDown() {
            this._contentWidget?.scrollDown();
        }
        scrollLeft() {
            this._contentWidget?.scrollLeft();
        }
        scrollRight() {
            this._contentWidget?.scrollRight();
        }
        pageUp() {
            this._contentWidget?.pageUp();
        }
        pageDown() {
            this._contentWidget?.pageDown();
        }
        goToTop() {
            this._contentWidget?.goToTop();
        }
        goToBottom() {
            this._contentWidget?.goToBottom();
        }
        get isColorPickerVisible() {
            return this._contentWidget?.isColorPickerVisible;
        }
        get isHoverVisible() {
            return this._contentWidget?.isVisible;
        }
        dispose() {
            super.dispose();
            this._unhookListeners();
            this._listenersStore.dispose();
            this._contentWidget?.dispose();
        }
    };
    exports.ContentHoverController = ContentHoverController;
    exports.ContentHoverController = ContentHoverController = ContentHoverController_1 = __decorate([
        __param(1, instantiation_1.IInstantiationService),
        __param(2, keybinding_1.IKeybindingService)
    ], ContentHoverController);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[848/*vs/editor/contrib/colorPicker/browser/colorContributions*/], __M([1/*require*/,0/*exports*/,2/*vs/base/common/lifecycle*/,15/*vs/editor/browser/editorExtensions*/,4/*vs/editor/common/core/range*/,422/*vs/editor/contrib/colorPicker/browser/colorDetector*/,288/*vs/editor/contrib/colorPicker/browser/colorHoverParticipant*/,292/*vs/editor/contrib/hover/browser/contentHoverController2*/,84/*vs/editor/contrib/hover/browser/hoverTypes*/]), function (require, exports, lifecycle_1, editorExtensions_1, range_1, colorDetector_1, colorHoverParticipant_1, contentHoverController2_1, hoverTypes_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ColorContribution = void 0;
    class ColorContribution extends lifecycle_1.Disposable {
        static { this.ID = 'editor.contrib.colorContribution'; } // ms
        constructor(_editor) {
            super();
            this._editor = _editor;
            this._register(_editor.onMouseDown((e) => this.onMouseDown(e)));
        }
        dispose() {
            super.dispose();
        }
        onMouseDown(mouseEvent) {
            const colorDecoratorsActivatedOn = this._editor.getOption(149 /* EditorOption.colorDecoratorsActivatedOn */);
            if (colorDecoratorsActivatedOn !== 'click' && colorDecoratorsActivatedOn !== 'clickAndHover') {
                return;
            }
            const target = mouseEvent.target;
            if (target.type !== 6 /* MouseTargetType.CONTENT_TEXT */) {
                return;
            }
            if (!target.detail.injectedText) {
                return;
            }
            if (target.detail.injectedText.options.attachedData !== colorDetector_1.ColorDecorationInjectedTextMarker) {
                return;
            }
            if (!target.range) {
                return;
            }
            const hoverController = this._editor.getContribution(contentHoverController2_1.ContentHoverController.ID);
            if (!hoverController) {
                return;
            }
            if (!hoverController.isColorPickerVisible) {
                const range = new range_1.Range(target.range.startLineNumber, target.range.startColumn + 1, target.range.endLineNumber, target.range.endColumn + 1);
                hoverController.showContentHover(range, 1 /* HoverStartMode.Immediate */, 0 /* HoverStartSource.Mouse */, false, true);
            }
        }
    }
    exports.ColorContribution = ColorContribution;
    (0, editorExtensions_1.registerEditorContribution)(ColorContribution.ID, ColorContribution, 2 /* EditorContributionInstantiation.BeforeFirstInteraction */);
    hoverTypes_1.HoverParticipantRegistry.register(colorHoverParticipant_1.ColorHoverParticipant);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[849/*vs/editor/contrib/hover/browser/hoverActions*/], __M([1/*require*/,0/*exports*/,264/*vs/editor/contrib/hover/browser/hoverActionIds*/,72/*vs/base/common/keyCodes*/,15/*vs/editor/browser/editorExtensions*/,4/*vs/editor/common/core/range*/,20/*vs/editor/common/editorContextKeys*/,429/*vs/editor/contrib/gotoSymbol/browser/link/goToDefinitionAtPosition*/,292/*vs/editor/contrib/hover/browser/contentHoverController2*/,27/*vs/editor/common/languages*/,3/*vs/nls*/,196/*vs/css!vs/editor/contrib/hover/browser/hover*/]), function (require, exports, hoverActionIds_1, keyCodes_1, editorExtensions_1, range_1, editorContextKeys_1, goToDefinitionAtPosition_1, contentHoverController2_1, languages_1, nls) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DecreaseHoverVerbosityLevel = exports.IncreaseHoverVerbosityLevel = exports.GoToBottomHoverAction = exports.GoToTopHoverAction = exports.PageDownHoverAction = exports.PageUpHoverAction = exports.ScrollRightHoverAction = exports.ScrollLeftHoverAction = exports.ScrollDownHoverAction = exports.ScrollUpHoverAction = exports.ShowDefinitionPreviewHoverAction = exports.ShowOrFocusHoverAction = void 0;
    var HoverFocusBehavior;
    (function (HoverFocusBehavior) {
        HoverFocusBehavior["NoAutoFocus"] = "noAutoFocus";
        HoverFocusBehavior["FocusIfVisible"] = "focusIfVisible";
        HoverFocusBehavior["AutoFocusImmediately"] = "autoFocusImmediately";
    })(HoverFocusBehavior || (HoverFocusBehavior = {}));
    class ShowOrFocusHoverAction extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: hoverActionIds_1.SHOW_OR_FOCUS_HOVER_ACTION_ID,
                label: nls.localize(1008, "Show or Focus Hover"),







                metadata: {
                    description: nls.localize2(1021, 'Show or focus the editor hover which shows documentation, references, and other content for a symbol at the current cursor position.'),
                    args: [{
                            name: 'args',
                            schema: {
                                type: 'object',
                                properties: {
                                    'focus': {
                                        description: 'Controls if and when the hover should take focus upon being triggered by this action.',
                                        enum: [HoverFocusBehavior.NoAutoFocus, HoverFocusBehavior.FocusIfVisible, HoverFocusBehavior.AutoFocusImmediately],
                                        enumDescriptions: [
                                            nls.localize(1009, 'The hover will not automatically take focus.'),
                                            nls.localize(1010, 'The hover will take focus only if it is already visible.'),
                                            nls.localize(1011, 'The hover will automatically take focus when it appears.'),
                                        ],
                                        default: HoverFocusBehavior.FocusIfVisible,
                                    }
                                },
                            }
                        }]
                },
                alias: 'Show or Focus Hover',
                precondition: undefined,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.editorTextFocus,
                    primary: (0, keyCodes_1.KeyChord)(2048 /* KeyMod.CtrlCmd */ | 41 /* KeyCode.KeyK */, 2048 /* KeyMod.CtrlCmd */ | 39 /* KeyCode.KeyI */),
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
        run(accessor, editor, args) {
            if (!editor.hasModel()) {
                return;
            }
            const controller = contentHoverController2_1.ContentHoverController.get(editor);
            if (!controller) {
                return;
            }
            const focusArgument = args?.focus;
            let focusOption = HoverFocusBehavior.FocusIfVisible;
            if (Object.values(HoverFocusBehavior).includes(focusArgument)) {
                focusOption = focusArgument;
            }
            else if (typeof focusArgument === 'boolean' && focusArgument) {
                focusOption = HoverFocusBehavior.AutoFocusImmediately;
            }
            const showContentHover = (focus) => {
                const position = editor.getPosition();
                const range = new range_1.Range(position.lineNumber, position.column, position.lineNumber, position.column);
                controller.showContentHover(range, 1 /* HoverStartMode.Immediate */, 1 /* HoverStartSource.Keyboard */, focus);
            };
            const accessibilitySupportEnabled = editor.getOption(2 /* EditorOption.accessibilitySupport */) === 2 /* AccessibilitySupport.Enabled */;
            if (controller.isHoverVisible) {
                if (focusOption !== HoverFocusBehavior.NoAutoFocus) {
                    controller.focus();
                }
                else {
                    showContentHover(accessibilitySupportEnabled);
                }
            }
            else {
                showContentHover(accessibilitySupportEnabled || focusOption === HoverFocusBehavior.AutoFocusImmediately);
            }
        }
    }
    exports.ShowOrFocusHoverAction = ShowOrFocusHoverAction;
    class ShowDefinitionPreviewHoverAction extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: hoverActionIds_1.SHOW_DEFINITION_PREVIEW_HOVER_ACTION_ID,
                label: nls.localize(1012, "Show Definition Preview Hover"),






                alias: 'Show Definition Preview Hover',
                precondition: undefined,
                metadata: {
                    description: nls.localize2(1022, 'Show the definition preview hover in the editor.'),
                },
            });
        }
        run(accessor, editor) {
            const controller = contentHoverController2_1.ContentHoverController.get(editor);
            if (!controller) {
                return;
            }
            const position = editor.getPosition();
            if (!position) {
                return;
            }
            const range = new range_1.Range(position.lineNumber, position.column, position.lineNumber, position.column);
            const goto = goToDefinitionAtPosition_1.GotoDefinitionAtPositionEditorContribution.get(editor);
            if (!goto) {
                return;
            }
            const promise = goto.startFindDefinitionFromCursor(position);
            promise.then(() => {
                controller.showContentHover(range, 1 /* HoverStartMode.Immediate */, 1 /* HoverStartSource.Keyboard */, true);
            });
        }
    }
    exports.ShowDefinitionPreviewHoverAction = ShowDefinitionPreviewHoverAction;
    class ScrollUpHoverAction extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: hoverActionIds_1.SCROLL_UP_HOVER_ACTION_ID,
                label: nls.localize(1013, "Scroll Up Hover"),





                alias: 'Scroll Up Hover',
                precondition: editorContextKeys_1.EditorContextKeys.hoverFocused,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.hoverFocused,
                    primary: 16 /* KeyCode.UpArrow */,
                    weight: 100 /* KeybindingWeight.EditorContrib */
                },
                metadata: {
                    description: nls.localize2(1023, 'Scroll up the editor hover.')
                },
            });
        }
        run(accessor, editor) {
            const controller = contentHoverController2_1.ContentHoverController.get(editor);
            if (!controller) {
                return;
            }
            controller.scrollUp();
        }
    }
    exports.ScrollUpHoverAction = ScrollUpHoverAction;
    class ScrollDownHoverAction extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: hoverActionIds_1.SCROLL_DOWN_HOVER_ACTION_ID,
                label: nls.localize(1014, "Scroll Down Hover"),





                alias: 'Scroll Down Hover',
                precondition: editorContextKeys_1.EditorContextKeys.hoverFocused,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.hoverFocused,
                    primary: 18 /* KeyCode.DownArrow */,
                    weight: 100 /* KeybindingWeight.EditorContrib */
                },
                metadata: {
                    description: nls.localize2(1024, 'Scroll down the editor hover.'),
                },
            });
        }
        run(accessor, editor) {
            const controller = contentHoverController2_1.ContentHoverController.get(editor);
            if (!controller) {
                return;
            }
            controller.scrollDown();
        }
    }
    exports.ScrollDownHoverAction = ScrollDownHoverAction;
    class ScrollLeftHoverAction extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: hoverActionIds_1.SCROLL_LEFT_HOVER_ACTION_ID,
                label: nls.localize(1015, "Scroll Left Hover"),





                alias: 'Scroll Left Hover',
                precondition: editorContextKeys_1.EditorContextKeys.hoverFocused,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.hoverFocused,
                    primary: 15 /* KeyCode.LeftArrow */,
                    weight: 100 /* KeybindingWeight.EditorContrib */
                },
                metadata: {
                    description: nls.localize2(1025, 'Scroll left the editor hover.'),
                },
            });
        }
        run(accessor, editor) {
            const controller = contentHoverController2_1.ContentHoverController.get(editor);
            if (!controller) {
                return;
            }
            controller.scrollLeft();
        }
    }
    exports.ScrollLeftHoverAction = ScrollLeftHoverAction;
    class ScrollRightHoverAction extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: hoverActionIds_1.SCROLL_RIGHT_HOVER_ACTION_ID,
                label: nls.localize(1016, "Scroll Right Hover"),





                alias: 'Scroll Right Hover',
                precondition: editorContextKeys_1.EditorContextKeys.hoverFocused,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.hoverFocused,
                    primary: 17 /* KeyCode.RightArrow */,
                    weight: 100 /* KeybindingWeight.EditorContrib */
                },
                metadata: {
                    description: nls.localize2(1026, 'Scroll right the editor hover.')
                },
            });
        }
        run(accessor, editor) {
            const controller = contentHoverController2_1.ContentHoverController.get(editor);
            if (!controller) {
                return;
            }
            controller.scrollRight();
        }
    }
    exports.ScrollRightHoverAction = ScrollRightHoverAction;
    class PageUpHoverAction extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: hoverActionIds_1.PAGE_UP_HOVER_ACTION_ID,
                label: nls.localize(1017, "Page Up Hover"),





                alias: 'Page Up Hover',
                precondition: editorContextKeys_1.EditorContextKeys.hoverFocused,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.hoverFocused,
                    primary: 11 /* KeyCode.PageUp */,
                    secondary: [512 /* KeyMod.Alt */ | 16 /* KeyCode.UpArrow */],
                    weight: 100 /* KeybindingWeight.EditorContrib */
                },
                metadata: {
                    description: nls.localize2(1027, 'Page up the editor hover.'),
                },
            });
        }
        run(accessor, editor) {
            const controller = contentHoverController2_1.ContentHoverController.get(editor);
            if (!controller) {
                return;
            }
            controller.pageUp();
        }
    }
    exports.PageUpHoverAction = PageUpHoverAction;
    class PageDownHoverAction extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: hoverActionIds_1.PAGE_DOWN_HOVER_ACTION_ID,
                label: nls.localize(1018, "Page Down Hover"),





                alias: 'Page Down Hover',
                precondition: editorContextKeys_1.EditorContextKeys.hoverFocused,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.hoverFocused,
                    primary: 12 /* KeyCode.PageDown */,
                    secondary: [512 /* KeyMod.Alt */ | 18 /* KeyCode.DownArrow */],
                    weight: 100 /* KeybindingWeight.EditorContrib */
                },
                metadata: {
                    description: nls.localize2(1028, 'Page down the editor hover.'),
                },
            });
        }
        run(accessor, editor) {
            const controller = contentHoverController2_1.ContentHoverController.get(editor);
            if (!controller) {
                return;
            }
            controller.pageDown();
        }
    }
    exports.PageDownHoverAction = PageDownHoverAction;
    class GoToTopHoverAction extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: hoverActionIds_1.GO_TO_TOP_HOVER_ACTION_ID,
                label: nls.localize(1019, "Go To Top Hover"),





                alias: 'Go To Bottom Hover',
                precondition: editorContextKeys_1.EditorContextKeys.hoverFocused,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.hoverFocused,
                    primary: 14 /* KeyCode.Home */,
                    secondary: [2048 /* KeyMod.CtrlCmd */ | 16 /* KeyCode.UpArrow */],
                    weight: 100 /* KeybindingWeight.EditorContrib */
                },
                metadata: {
                    description: nls.localize2(1029, 'Go to the top of the editor hover.'),
                },
            });
        }
        run(accessor, editor) {
            const controller = contentHoverController2_1.ContentHoverController.get(editor);
            if (!controller) {
                return;
            }
            controller.goToTop();
        }
    }
    exports.GoToTopHoverAction = GoToTopHoverAction;
    class GoToBottomHoverAction extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: hoverActionIds_1.GO_TO_BOTTOM_HOVER_ACTION_ID,
                label: nls.localize(1020, "Go To Bottom Hover"),





                alias: 'Go To Bottom Hover',
                precondition: editorContextKeys_1.EditorContextKeys.hoverFocused,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.hoverFocused,
                    primary: 13 /* KeyCode.End */,
                    secondary: [2048 /* KeyMod.CtrlCmd */ | 18 /* KeyCode.DownArrow */],
                    weight: 100 /* KeybindingWeight.EditorContrib */
                },
                metadata: {
                    description: nls.localize2(1030, 'Go to the bottom of the editor hover.')
                },
            });
        }
        run(accessor, editor) {
            const controller = contentHoverController2_1.ContentHoverController.get(editor);
            if (!controller) {
                return;
            }
            controller.goToBottom();
        }
    }
    exports.GoToBottomHoverAction = GoToBottomHoverAction;
    class IncreaseHoverVerbosityLevel extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: hoverActionIds_1.INCREASE_HOVER_VERBOSITY_ACTION_ID,
                label: hoverActionIds_1.INCREASE_HOVER_VERBOSITY_ACTION_LABEL,
                alias: 'Increase Hover Verbosity Level',
                precondition: editorContextKeys_1.EditorContextKeys.hoverVisible
            });
        }
        run(accessor, editor, args) {
            const hoverController = contentHoverController2_1.ContentHoverController.get(editor);
            if (!hoverController) {
                return;
            }
            const index = args?.index !== undefined ? args.index : hoverController.focusedHoverPartIndex();
            hoverController.updateHoverVerbosityLevel(languages_1.HoverVerbosityAction.Increase, index, args?.focus);
        }
    }
    exports.IncreaseHoverVerbosityLevel = IncreaseHoverVerbosityLevel;
    class DecreaseHoverVerbosityLevel extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: hoverActionIds_1.DECREASE_HOVER_VERBOSITY_ACTION_ID,
                label: hoverActionIds_1.DECREASE_HOVER_VERBOSITY_ACTION_LABEL,
                alias: 'Decrease Hover Verbosity Level',
                precondition: editorContextKeys_1.EditorContextKeys.hoverVisible
            });
        }
        run(accessor, editor, args) {
            const hoverController = contentHoverController2_1.ContentHoverController.get(editor);
            if (!hoverController) {
                return;
            }
            const index = args?.index !== undefined ? args.index : hoverController.focusedHoverPartIndex();
            contentHoverController2_1.ContentHoverController.get(editor)?.updateHoverVerbosityLevel(languages_1.HoverVerbosityAction.Decrease, index, args?.focus);
        }
    }
    exports.DecreaseHoverVerbosityLevel = DecreaseHoverVerbosityLevel;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[850/*vs/editor/contrib/hover/browser/hoverContribution*/], __M([1/*require*/,0/*exports*/,849/*vs/editor/contrib/hover/browser/hoverActions*/,15/*vs/editor/browser/editorExtensions*/,32/*vs/platform/theme/common/colorRegistry*/,25/*vs/platform/theme/common/themeService*/,84/*vs/editor/contrib/hover/browser/hoverTypes*/,217/*vs/editor/contrib/hover/browser/markdownHoverParticipant*/,845/*vs/editor/contrib/hover/browser/markerHoverParticipant*/,292/*vs/editor/contrib/hover/browser/contentHoverController2*/,713/*vs/editor/contrib/hover/browser/marginHoverController*/,380/*vs/platform/accessibility/browser/accessibleViewRegistry*/,615/*vs/editor/contrib/hover/browser/hoverAccessibleViews*/,196/*vs/css!vs/editor/contrib/hover/browser/hover*/]), function (require, exports, hoverActions_1, editorExtensions_1, colorRegistry_1, themeService_1, hoverTypes_1, markdownHoverParticipant_1, markerHoverParticipant_1, contentHoverController2_1, marginHoverController_1, accessibleViewRegistry_1, hoverAccessibleViews_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    (0, editorExtensions_1.registerEditorContribution)(contentHoverController2_1.ContentHoverController.ID, contentHoverController2_1.ContentHoverController, 2 /* EditorContributionInstantiation.BeforeFirstInteraction */);
    (0, editorExtensions_1.registerEditorContribution)(marginHoverController_1.MarginHoverController.ID, marginHoverController_1.MarginHoverController, 2 /* EditorContributionInstantiation.BeforeFirstInteraction */);
    (0, editorExtensions_1.registerEditorAction)(hoverActions_1.ShowOrFocusHoverAction);
    (0, editorExtensions_1.registerEditorAction)(hoverActions_1.ShowDefinitionPreviewHoverAction);
    (0, editorExtensions_1.registerEditorAction)(hoverActions_1.ScrollUpHoverAction);
    (0, editorExtensions_1.registerEditorAction)(hoverActions_1.ScrollDownHoverAction);
    (0, editorExtensions_1.registerEditorAction)(hoverActions_1.ScrollLeftHoverAction);
    (0, editorExtensions_1.registerEditorAction)(hoverActions_1.ScrollRightHoverAction);
    (0, editorExtensions_1.registerEditorAction)(hoverActions_1.PageUpHoverAction);
    (0, editorExtensions_1.registerEditorAction)(hoverActions_1.PageDownHoverAction);
    (0, editorExtensions_1.registerEditorAction)(hoverActions_1.GoToTopHoverAction);
    (0, editorExtensions_1.registerEditorAction)(hoverActions_1.GoToBottomHoverAction);
    (0, editorExtensions_1.registerEditorAction)(hoverActions_1.IncreaseHoverVerbosityLevel);
    (0, editorExtensions_1.registerEditorAction)(hoverActions_1.DecreaseHoverVerbosityLevel);
    hoverTypes_1.HoverParticipantRegistry.register(markdownHoverParticipant_1.MarkdownHoverParticipant);
    hoverTypes_1.HoverParticipantRegistry.register(markerHoverParticipant_1.MarkerHoverParticipant);
    // theming
    (0, themeService_1.registerThemingParticipant)((theme, collector) => {
        const hoverBorder = theme.getColor(colorRegistry_1.editorHoverBorder);
        if (hoverBorder) {
            collector.addRule(`.monaco-editor .monaco-hover .hover-row:not(:first-child):not(:empty) { border-top: 1px solid ${hoverBorder.transparent(0.5)}; }`);
            collector.addRule(`.monaco-editor .monaco-hover hr { border-top: 1px solid ${hoverBorder.transparent(0.5)}; }`);
            collector.addRule(`.monaco-editor .monaco-hover hr { border-bottom: 0px solid ${hoverBorder.transparent(0.5)}; }`);
        }
    });
    accessibleViewRegistry_1.AccessibleViewRegistry.register(new hoverAccessibleViews_1.HoverAccessibleView());
    accessibleViewRegistry_1.AccessibleViewRegistry.register(new hoverAccessibleViews_1.HoverAccessibilityHelp());
    accessibleViewRegistry_1.AccessibleViewRegistry.register(new hoverAccessibleViews_1.ExtHoverAccessibleView());
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[851/*vs/editor/contrib/inlayHints/browser/inlayHintsContribution*/], __M([1/*require*/,0/*exports*/,15/*vs/editor/browser/editorExtensions*/,84/*vs/editor/contrib/hover/browser/hoverTypes*/,431/*vs/editor/contrib/inlayHints/browser/inlayHintsController*/,432/*vs/editor/contrib/inlayHints/browser/inlayHintsHover*/]), function (require, exports, editorExtensions_1, hoverTypes_1, inlayHintsController_1, inlayHintsHover_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    (0, editorExtensions_1.registerEditorContribution)(inlayHintsController_1.InlayHintsController.ID, inlayHintsController_1.InlayHintsController, 1 /* EditorContributionInstantiation.AfterFirstRender */);
    hoverTypes_1.HoverParticipantRegistry.register(inlayHintsHover_1.InlayHintsHover);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[433/*vs/editor/contrib/stickyScroll/browser/stickyScrollController*/], __M([1/*require*/,0/*exports*/,2/*vs/base/common/lifecycle*/,17/*vs/editor/common/services/languageFeatures*/,838/*vs/editor/contrib/stickyScroll/browser/stickyScrollWidget*/,837/*vs/editor/contrib/stickyScroll/browser/stickyScrollProvider*/,7/*vs/platform/instantiation/common/instantiation*/,58/*vs/platform/contextview/browser/contextView*/,29/*vs/platform/actions/common/actions*/,12/*vs/platform/contextkey/common/contextkey*/,20/*vs/editor/common/editorContextKeys*/,209/*vs/editor/contrib/gotoSymbol/browser/link/clickLinkGesture*/,4/*vs/editor/common/core/range*/,277/*vs/editor/contrib/gotoSymbol/browser/goToSymbol*/,430/*vs/editor/contrib/inlayHints/browser/inlayHintsLocations*/,9/*vs/editor/common/core/position*/,18/*vs/base/common/cancellation*/,36/*vs/editor/common/languages/languageConfigurationRegistry*/,79/*vs/editor/common/services/languageFeatureDebounce*/,5/*vs/base/browser/dom*/,341/*vs/editor/contrib/stickyScroll/browser/stickyScrollElement*/,77/*vs/base/browser/mouseEvent*/,289/*vs/editor/contrib/folding/browser/folding*/,334/*vs/editor/contrib/folding/browser/foldingModel*/]), function (require, exports, lifecycle_1, languageFeatures_1, stickyScrollWidget_1, stickyScrollProvider_1, instantiation_1, contextView_1, actions_1, contextkey_1, editorContextKeys_1, clickLinkGesture_1, range_1, goToSymbol_1, inlayHintsLocations_1, position_1, cancellation_1, languageConfigurationRegistry_1, languageFeatureDebounce_1, dom, stickyScrollElement_1, mouseEvent_1, folding_1, foldingModel_1) {
    "use strict";
    var StickyScrollController_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.StickyScrollController = void 0;
    let StickyScrollController = class StickyScrollController extends lifecycle_1.Disposable {
        static { StickyScrollController_1 = this; }
        static { this.ID = 'store.contrib.stickyScrollController'; }
        constructor(_editor, _contextMenuService, _languageFeaturesService, _instaService, _languageConfigurationService, _languageFeatureDebounceService, _contextKeyService) {
            super();
            this._editor = _editor;
            this._contextMenuService = _contextMenuService;
            this._languageFeaturesService = _languageFeaturesService;
            this._instaService = _instaService;
            this._contextKeyService = _contextKeyService;
            this._sessionStore = new lifecycle_1.DisposableStore();
            this._maxStickyLines = Number.MAX_SAFE_INTEGER;
            this._candidateDefinitionsLength = -1;
            this._focusedStickyElementIndex = -1;
            this._enabled = false;
            this._focused = false;
            this._positionRevealed = false;
            this._onMouseDown = false;
            this._endLineNumbers = [];
            this._stickyScrollWidget = new stickyScrollWidget_1.StickyScrollWidget(this._editor);
            this._stickyLineCandidateProvider = new stickyScrollProvider_1.StickyLineCandidateProvider(this._editor, _languageFeaturesService, _languageConfigurationService);
            this._register(this._stickyScrollWidget);
            this._register(this._stickyLineCandidateProvider);
            this._widgetState = stickyScrollWidget_1.StickyScrollWidgetState.Empty;
            this._onDidResize();
            this._readConfiguration();
            const stickyScrollDomNode = this._stickyScrollWidget.getDomNode();
            this._register(this._editor.onDidChangeConfiguration(e => {
                this._readConfigurationChange(e);
            }));
            this._register(dom.addDisposableListener(stickyScrollDomNode, dom.EventType.CONTEXT_MENU, async (event) => {
                this._onContextMenu(dom.getWindow(stickyScrollDomNode), event);
            }));
            this._stickyScrollFocusedContextKey = editorContextKeys_1.EditorContextKeys.stickyScrollFocused.bindTo(this._contextKeyService);
            this._stickyScrollVisibleContextKey = editorContextKeys_1.EditorContextKeys.stickyScrollVisible.bindTo(this._contextKeyService);
            const focusTracker = this._register(dom.trackFocus(stickyScrollDomNode));
            this._register(focusTracker.onDidBlur(_ => {
                // Suppose that the blurring is caused by scrolling, then keep the focus on the sticky scroll
                // This is determined by the fact that the height of the widget has become zero and there has been no position revealing
                if (this._positionRevealed === false && stickyScrollDomNode.clientHeight === 0) {
                    this._focusedStickyElementIndex = -1;
                    this.focus();
                }
                // In all other casees, dispose the focus on the sticky scroll
                else {
                    this._disposeFocusStickyScrollStore();
                }
            }));
            this._register(focusTracker.onDidFocus(_ => {
                this.focus();
            }));
            this._registerMouseListeners();
            // Suppose that mouse down on the sticky scroll, then do not focus on the sticky scroll because this will be followed by the revealing of a position
            this._register(dom.addDisposableListener(stickyScrollDomNode, dom.EventType.MOUSE_DOWN, (e) => {
                this._onMouseDown = true;
            }));
        }
        static get(editor) {
            return editor.getContribution(StickyScrollController_1.ID);
        }
        _disposeFocusStickyScrollStore() {
            this._stickyScrollFocusedContextKey.set(false);
            this._focusDisposableStore?.dispose();
            this._focused = false;
            this._positionRevealed = false;
            this._onMouseDown = false;
        }
        focus() {
            // If the mouse is down, do not focus on the sticky scroll
            if (this._onMouseDown) {
                this._onMouseDown = false;
                this._editor.focus();
                return;
            }
            const focusState = this._stickyScrollFocusedContextKey.get();
            if (focusState === true) {
                return;
            }
            this._focused = true;
            this._focusDisposableStore = new lifecycle_1.DisposableStore();
            this._stickyScrollFocusedContextKey.set(true);
            this._focusedStickyElementIndex = this._stickyScrollWidget.lineNumbers.length - 1;
            this._stickyScrollWidget.focusLineWithIndex(this._focusedStickyElementIndex);
        }
        focusNext() {
            if (this._focusedStickyElementIndex < this._stickyScrollWidget.lineNumberCount - 1) {
                this._focusNav(true);
            }
        }
        focusPrevious() {
            if (this._focusedStickyElementIndex > 0) {
                this._focusNav(false);
            }
        }
        selectEditor() {
            this._editor.focus();
        }
        // True is next, false is previous
        _focusNav(direction) {
            this._focusedStickyElementIndex = direction ? this._focusedStickyElementIndex + 1 : this._focusedStickyElementIndex - 1;
            this._stickyScrollWidget.focusLineWithIndex(this._focusedStickyElementIndex);
        }
        goToFocused() {
            const lineNumbers = this._stickyScrollWidget.lineNumbers;
            this._disposeFocusStickyScrollStore();
            this._revealPosition({ lineNumber: lineNumbers[this._focusedStickyElementIndex], column: 1 });
        }
        _revealPosition(position) {
            this._reveaInEditor(position, () => this._editor.revealPosition(position));
        }
        _revealLineInCenterIfOutsideViewport(position) {
            this._reveaInEditor(position, () => this._editor.revealLineInCenterIfOutsideViewport(position.lineNumber, 0 /* ScrollType.Smooth */));
        }
        _reveaInEditor(position, revealFunction) {
            if (this._focused) {
                this._disposeFocusStickyScrollStore();
            }
            this._positionRevealed = true;
            revealFunction();
            this._editor.setSelection(range_1.Range.fromPositions(position));
            this._editor.focus();
        }
        _registerMouseListeners() {
            const sessionStore = this._register(new lifecycle_1.DisposableStore());
            const gesture = this._register(new clickLinkGesture_1.ClickLinkGesture(this._editor, {
                extractLineNumberFromMouseEvent: (e) => {
                    const position = this._stickyScrollWidget.getEditorPositionFromNode(e.target.element);
                    return position ? position.lineNumber : 0;
                }
            }));
            const getMouseEventTarget = (mouseEvent) => {
                if (!this._editor.hasModel()) {
                    return null;
                }
                if (mouseEvent.target.type !== 12 /* MouseTargetType.OVERLAY_WIDGET */ || mouseEvent.target.detail !== this._stickyScrollWidget.getId()) {
                    // not hovering over our widget
                    return null;
                }
                const mouseTargetElement = mouseEvent.target.element;
                if (!mouseTargetElement || mouseTargetElement.innerText !== mouseTargetElement.innerHTML) {
                    // not on a span element rendering text
                    return null;
                }
                const position = this._stickyScrollWidget.getEditorPositionFromNode(mouseTargetElement);
                if (!position) {
                    // not hovering a sticky scroll line
                    return null;
                }
                return {
                    range: new range_1.Range(position.lineNumber, position.column, position.lineNumber, position.column + mouseTargetElement.innerText.length),
                    textElement: mouseTargetElement
                };
            };
            const stickyScrollWidgetDomNode = this._stickyScrollWidget.getDomNode();
            this._register(dom.addStandardDisposableListener(stickyScrollWidgetDomNode, dom.EventType.CLICK, (mouseEvent) => {
                if (mouseEvent.ctrlKey || mouseEvent.altKey || mouseEvent.metaKey) {
                    // modifier pressed
                    return;
                }
                if (!mouseEvent.leftButton) {
                    // not left click
                    return;
                }
                if (mouseEvent.shiftKey) {
                    // shift click
                    const lineIndex = this._stickyScrollWidget.getLineIndexFromChildDomNode(mouseEvent.target);
                    if (lineIndex === null) {
                        return;
                    }
                    const position = new position_1.Position(this._endLineNumbers[lineIndex], 1);
                    this._revealLineInCenterIfOutsideViewport(position);
                    return;
                }
                const isInFoldingIconDomNode = this._stickyScrollWidget.isInFoldingIconDomNode(mouseEvent.target);
                if (isInFoldingIconDomNode) {
                    // clicked on folding icon
                    const lineNumber = this._stickyScrollWidget.getLineNumberFromChildDomNode(mouseEvent.target);
                    this._toggleFoldingRegionForLine(lineNumber);
                    return;
                }
                const isInStickyLine = this._stickyScrollWidget.isInStickyLine(mouseEvent.target);
                if (!isInStickyLine) {
                    return;
                }
                // normal click
                let position = this._stickyScrollWidget.getEditorPositionFromNode(mouseEvent.target);
                if (!position) {
                    const lineNumber = this._stickyScrollWidget.getLineNumberFromChildDomNode(mouseEvent.target);
                    if (lineNumber === null) {
                        // not hovering a sticky scroll line
                        return;
                    }
                    position = new position_1.Position(lineNumber, 1);
                }
                this._revealPosition(position);
            }));
            this._register(dom.addStandardDisposableListener(stickyScrollWidgetDomNode, dom.EventType.MOUSE_MOVE, (mouseEvent) => {
                if (mouseEvent.shiftKey) {
                    const currentEndForLineIndex = this._stickyScrollWidget.getLineIndexFromChildDomNode(mouseEvent.target);
                    if (currentEndForLineIndex === null || this._showEndForLine !== null && this._showEndForLine === currentEndForLineIndex) {
                        return;
                    }
                    this._showEndForLine = currentEndForLineIndex;
                    this._renderStickyScroll();
                    return;
                }
                if (this._showEndForLine !== undefined) {
                    this._showEndForLine = undefined;
                    this._renderStickyScroll();
                }
            }));
            this._register(dom.addDisposableListener(stickyScrollWidgetDomNode, dom.EventType.MOUSE_LEAVE, (e) => {
                if (this._showEndForLine !== undefined) {
                    this._showEndForLine = undefined;
                    this._renderStickyScroll();
                }
            }));
            this._register(gesture.onMouseMoveOrRelevantKeyDown(([mouseEvent, _keyboardEvent]) => {
                const mouseTarget = getMouseEventTarget(mouseEvent);
                if (!mouseTarget || !mouseEvent.hasTriggerModifier || !this._editor.hasModel()) {
                    sessionStore.clear();
                    return;
                }
                const { range, textElement } = mouseTarget;
                if (!range.equalsRange(this._stickyRangeProjectedOnEditor)) {
                    this._stickyRangeProjectedOnEditor = range;
                    sessionStore.clear();
                }
                else if (textElement.style.textDecoration === 'underline') {
                    return;
                }
                const cancellationToken = new cancellation_1.CancellationTokenSource();
                sessionStore.add((0, lifecycle_1.toDisposable)(() => cancellationToken.dispose(true)));
                let currentHTMLChild;
                (0, goToSymbol_1.getDefinitionsAtPosition)(this._languageFeaturesService.definitionProvider, this._editor.getModel(), new position_1.Position(range.startLineNumber, range.startColumn + 1), false, cancellationToken.token).then((candidateDefinitions => {
                    if (cancellationToken.token.isCancellationRequested) {
                        return;
                    }
                    if (candidateDefinitions.length !== 0) {
                        this._candidateDefinitionsLength = candidateDefinitions.length;
                        const childHTML = textElement;
                        if (currentHTMLChild !== childHTML) {
                            sessionStore.clear();
                            currentHTMLChild = childHTML;
                            currentHTMLChild.style.textDecoration = 'underline';
                            sessionStore.add((0, lifecycle_1.toDisposable)(() => {
                                currentHTMLChild.style.textDecoration = 'none';
                            }));
                        }
                        else if (!currentHTMLChild) {
                            currentHTMLChild = childHTML;
                            currentHTMLChild.style.textDecoration = 'underline';
                            sessionStore.add((0, lifecycle_1.toDisposable)(() => {
                                currentHTMLChild.style.textDecoration = 'none';
                            }));
                        }
                    }
                    else {
                        sessionStore.clear();
                    }
                }));
            }));
            this._register(gesture.onCancel(() => {
                sessionStore.clear();
            }));
            this._register(gesture.onExecute(async (e) => {
                if (e.target.type !== 12 /* MouseTargetType.OVERLAY_WIDGET */ || e.target.detail !== this._stickyScrollWidget.getId()) {
                    // not hovering over our widget
                    return;
                }
                const position = this._stickyScrollWidget.getEditorPositionFromNode(e.target.element);
                if (!position) {
                    // not hovering a sticky scroll line
                    return;
                }
                if (!this._editor.hasModel() || !this._stickyRangeProjectedOnEditor) {
                    return;
                }
                if (this._candidateDefinitionsLength > 1) {
                    if (this._focused) {
                        this._disposeFocusStickyScrollStore();
                    }
                    this._revealPosition({ lineNumber: position.lineNumber, column: 1 });
                }
                this._instaService.invokeFunction(inlayHintsLocations_1.goToDefinitionWithLocation, e, this._editor, { uri: this._editor.getModel().uri, range: this._stickyRangeProjectedOnEditor });
            }));
        }
        _onContextMenu(targetWindow, e) {
            const event = new mouseEvent_1.StandardMouseEvent(targetWindow, e);
            this._contextMenuService.showContextMenu({
                menuId: actions_1.MenuId.StickyScrollContext,
                getAnchor: () => event,
            });
        }
        _toggleFoldingRegionForLine(line) {
            if (!this._foldingModel || line === null) {
                return;
            }
            const stickyLine = this._stickyScrollWidget.getRenderedStickyLine(line);
            const foldingIcon = stickyLine?.foldingIcon;
            if (!foldingIcon) {
                return;
            }
            (0, foldingModel_1.toggleCollapseState)(this._foldingModel, Number.MAX_VALUE, [line]);
            foldingIcon.isCollapsed = !foldingIcon.isCollapsed;
            const scrollTop = (foldingIcon.isCollapsed ?
                this._editor.getTopForLineNumber(foldingIcon.foldingEndLine)
                : this._editor.getTopForLineNumber(foldingIcon.foldingStartLine))
                - this._editor.getOption(67 /* EditorOption.lineHeight */) * stickyLine.index + 1;
            this._editor.setScrollTop(scrollTop);
            this._renderStickyScroll(line);
        }
        _readConfiguration() {
            const options = this._editor.getOption(116 /* EditorOption.stickyScroll */);
            if (options.enabled === false) {
                this._editor.removeOverlayWidget(this._stickyScrollWidget);
                this._sessionStore.clear();
                this._enabled = false;
                return;
            }
            else if (options.enabled && !this._enabled) {
                // When sticky scroll was just enabled, add the listeners on the sticky scroll
                this._editor.addOverlayWidget(this._stickyScrollWidget);
                this._sessionStore.add(this._editor.onDidScrollChange((e) => {
                    if (e.scrollTopChanged) {
                        this._showEndForLine = undefined;
                        this._renderStickyScroll();
                    }
                }));
                this._sessionStore.add(this._editor.onDidLayoutChange(() => this._onDidResize()));
                this._sessionStore.add(this._editor.onDidChangeModelTokens((e) => this._onTokensChange(e)));
                this._sessionStore.add(this._stickyLineCandidateProvider.onDidChangeStickyScroll(() => {
                    this._showEndForLine = undefined;
                    this._renderStickyScroll();
                }));
                this._enabled = true;
            }
            const lineNumberOption = this._editor.getOption(68 /* EditorOption.lineNumbers */);
            if (lineNumberOption.renderType === 2 /* RenderLineNumbersType.Relative */) {
                this._sessionStore.add(this._editor.onDidChangeCursorPosition(() => {
                    this._showEndForLine = undefined;
                    this._renderStickyScroll(0);
                }));
            }
        }
        _readConfigurationChange(event) {
            if (event.hasChanged(116 /* EditorOption.stickyScroll */)
                || event.hasChanged(73 /* EditorOption.minimap */)
                || event.hasChanged(67 /* EditorOption.lineHeight */)
                || event.hasChanged(111 /* EditorOption.showFoldingControls */)
                || event.hasChanged(68 /* EditorOption.lineNumbers */)) {
                this._readConfiguration();
            }
            if (event.hasChanged(68 /* EditorOption.lineNumbers */)) {
                this._renderStickyScroll(0);
            }
        }
        _needsUpdate(event) {
            const stickyLineNumbers = this._stickyScrollWidget.getCurrentLines();
            for (const stickyLineNumber of stickyLineNumbers) {
                for (const range of event.ranges) {
                    if (stickyLineNumber >= range.fromLineNumber && stickyLineNumber <= range.toLineNumber) {
                        return true;
                    }
                }
            }
            return false;
        }
        _onTokensChange(event) {
            if (this._needsUpdate(event)) {
                // Rebuilding the whole widget from line 0
                this._renderStickyScroll(0);
            }
        }
        _onDidResize() {
            const layoutInfo = this._editor.getLayoutInfo();
            // Make sure sticky scroll doesn't take up more than 25% of the editor
            const theoreticalLines = layoutInfo.height / this._editor.getOption(67 /* EditorOption.lineHeight */);
            this._maxStickyLines = Math.round(theoreticalLines * .25);
        }
        async _renderStickyScroll(rebuildFromLine) {
            const model = this._editor.getModel();
            if (!model || model.isTooLargeForTokenization()) {
                this._resetState();
                return;
            }
            const nextRebuildFromLine = this._updateAndGetMinRebuildFromLine(rebuildFromLine);
            const stickyWidgetVersion = this._stickyLineCandidateProvider.getVersionId();
            const shouldUpdateState = stickyWidgetVersion === undefined || stickyWidgetVersion === model.getVersionId();
            if (shouldUpdateState) {
                if (!this._focused) {
                    await this._updateState(nextRebuildFromLine);
                }
                else {
                    // Suppose that previously the sticky scroll widget had height 0, then if there are visible lines, set the last line as focused
                    if (this._focusedStickyElementIndex === -1) {
                        await this._updateState(nextRebuildFromLine);
                        this._focusedStickyElementIndex = this._stickyScrollWidget.lineNumberCount - 1;
                        if (this._focusedStickyElementIndex !== -1) {
                            this._stickyScrollWidget.focusLineWithIndex(this._focusedStickyElementIndex);
                        }
                    }
                    else {
                        const focusedStickyElementLineNumber = this._stickyScrollWidget.lineNumbers[this._focusedStickyElementIndex];
                        await this._updateState(nextRebuildFromLine);
                        // Suppose that after setting the state, there are no sticky lines, set the focused index to -1
                        if (this._stickyScrollWidget.lineNumberCount === 0) {
                            this._focusedStickyElementIndex = -1;
                        }
                        else {
                            const previousFocusedLineNumberExists = this._stickyScrollWidget.lineNumbers.includes(focusedStickyElementLineNumber);
                            // If the line number is still there, do not change anything
                            // If the line number is not there, set the new focused line to be the last line
                            if (!previousFocusedLineNumberExists) {
                                this._focusedStickyElementIndex = this._stickyScrollWidget.lineNumberCount - 1;
                            }
                            this._stickyScrollWidget.focusLineWithIndex(this._focusedStickyElementIndex);
                        }
                    }
                }
            }
        }
        _updateAndGetMinRebuildFromLine(rebuildFromLine) {
            if (rebuildFromLine !== undefined) {
                const minRebuildFromLineOrInfinity = this._minRebuildFromLine !== undefined ? this._minRebuildFromLine : Infinity;
                this._minRebuildFromLine = Math.min(rebuildFromLine, minRebuildFromLineOrInfinity);
            }
            return this._minRebuildFromLine;
        }
        async _updateState(rebuildFromLine) {
            this._minRebuildFromLine = undefined;
            this._foldingModel = await folding_1.FoldingController.get(this._editor)?.getFoldingModel() ?? undefined;
            this._widgetState = this.findScrollWidgetState();
            const stickyWidgetHasLines = this._widgetState.startLineNumbers.length > 0;
            this._stickyScrollVisibleContextKey.set(stickyWidgetHasLines);
            this._stickyScrollWidget.setState(this._widgetState, this._foldingModel, rebuildFromLine);
        }
        async _resetState() {
            this._minRebuildFromLine = undefined;
            this._foldingModel = undefined;
            this._widgetState = stickyScrollWidget_1.StickyScrollWidgetState.Empty;
            this._stickyScrollVisibleContextKey.set(false);
            this._stickyScrollWidget.setState(undefined, undefined);
        }
        findScrollWidgetState() {
            const lineHeight = this._editor.getOption(67 /* EditorOption.lineHeight */);
            const maxNumberStickyLines = Math.min(this._maxStickyLines, this._editor.getOption(116 /* EditorOption.stickyScroll */).maxLineCount);
            const scrollTop = this._editor.getScrollTop();
            let lastLineRelativePosition = 0;
            const startLineNumbers = [];
            const endLineNumbers = [];
            const arrayVisibleRanges = this._editor.getVisibleRanges();
            if (arrayVisibleRanges.length !== 0) {
                const fullVisibleRange = new stickyScrollElement_1.StickyRange(arrayVisibleRanges[0].startLineNumber, arrayVisibleRanges[arrayVisibleRanges.length - 1].endLineNumber);
                const candidateRanges = this._stickyLineCandidateProvider.getCandidateStickyLinesIntersecting(fullVisibleRange);
                for (const range of candidateRanges) {
                    const start = range.startLineNumber;
                    const end = range.endLineNumber;
                    const depth = range.nestingDepth;
                    if (end - start > 0) {
                        const topOfElementAtDepth = (depth - 1) * lineHeight;
                        const bottomOfElementAtDepth = depth * lineHeight;
                        const bottomOfBeginningLine = this._editor.getBottomForLineNumber(start) - scrollTop;
                        const topOfEndLine = this._editor.getTopForLineNumber(end) - scrollTop;
                        const bottomOfEndLine = this._editor.getBottomForLineNumber(end) - scrollTop;
                        if (topOfElementAtDepth > topOfEndLine && topOfElementAtDepth <= bottomOfEndLine) {
                            startLineNumbers.push(start);
                            endLineNumbers.push(end + 1);
                            lastLineRelativePosition = bottomOfEndLine - bottomOfElementAtDepth;
                            break;
                        }
                        else if (bottomOfElementAtDepth > bottomOfBeginningLine && bottomOfElementAtDepth <= bottomOfEndLine) {
                            startLineNumbers.push(start);
                            endLineNumbers.push(end + 1);
                        }
                        if (startLineNumbers.length === maxNumberStickyLines) {
                            break;
                        }
                    }
                }
            }
            this._endLineNumbers = endLineNumbers;
            return new stickyScrollWidget_1.StickyScrollWidgetState(startLineNumbers, endLineNumbers, lastLineRelativePosition, this._showEndForLine);
        }
        dispose() {
            super.dispose();
            this._sessionStore.dispose();
        }
    };
    exports.StickyScrollController = StickyScrollController;
    exports.StickyScrollController = StickyScrollController = StickyScrollController_1 = __decorate([
        __param(1, contextView_1.IContextMenuService),
        __param(2, languageFeatures_1.ILanguageFeaturesService),
        __param(3, instantiation_1.IInstantiationService),
        __param(4, languageConfigurationRegistry_1.ILanguageConfigurationService),
        __param(5, languageFeatureDebounce_1.ILanguageFeatureDebounceService),
        __param(6, contextkey_1.IContextKeyService)
    ], StickyScrollController);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[852/*vs/editor/contrib/stickyScroll/browser/stickyScrollActions*/], __M([1/*require*/,0/*exports*/,15/*vs/editor/browser/editorExtensions*/,3/*vs/nls*/,671/*vs/platform/action/common/actionCommonCategories*/,29/*vs/platform/actions/common/actions*/,28/*vs/platform/configuration/common/configuration*/,12/*vs/platform/contextkey/common/contextkey*/,20/*vs/editor/common/editorContextKeys*/,433/*vs/editor/contrib/stickyScroll/browser/stickyScrollController*/]), function (require, exports, editorExtensions_1, nls_1, actionCommonCategories_1, actions_1, configuration_1, contextkey_1, editorContextKeys_1, stickyScrollController_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SelectEditor = exports.GoToStickyScrollLine = exports.SelectPreviousStickyScrollLine = exports.SelectNextStickyScrollLine = exports.FocusStickyScroll = exports.ToggleStickyScroll = void 0;
    class ToggleStickyScroll extends actions_1.Action2 {
        constructor() {
            super({
                id: 'editor.action.toggleStickyScroll',
                title: {
                    ...(0, nls_1.localize2)(1303, "Toggle Editor Sticky Scroll"),
                    mnemonicTitle: (0, nls_1.localize)(1299, "&&Toggle Editor Sticky Scroll"),
                },
                metadata: {
                    description: (0, nls_1.localize2)(1304, "Toggle/enable the editor sticky scroll which shows the nested scopes at the top of the viewport"),
                },
                category: actionCommonCategories_1.Categories.View,
                toggled: {
                    condition: contextkey_1.ContextKeyExpr.equals('config.editor.stickyScroll.enabled', true),
                    title: (0, nls_1.localize)(1300, "Sticky Scroll"),
                    mnemonicTitle: (0, nls_1.localize)(1301, "&&Sticky Scroll"),
                },
                menu: [
                    { id: actions_1.MenuId.CommandPalette },
                    { id: actions_1.MenuId.MenubarAppearanceMenu, group: '4_editor', order: 3 },
                    { id: actions_1.MenuId.StickyScrollContext }
                ]
            });
        }
        async run(accessor) {
            const configurationService = accessor.get(configuration_1.IConfigurationService);
            const newValue = !configurationService.getValue('editor.stickyScroll.enabled');
            return configurationService.updateValue('editor.stickyScroll.enabled', newValue);
        }
    }
    exports.ToggleStickyScroll = ToggleStickyScroll;
    const weight = 100 /* KeybindingWeight.EditorContrib */;
    class FocusStickyScroll extends editorExtensions_1.EditorAction2 {
        constructor() {
            super({
                id: 'editor.action.focusStickyScroll',
                title: {
                    ...(0, nls_1.localize2)(1305, "Focus on the editor sticky scroll"),
                    mnemonicTitle: (0, nls_1.localize)(1302, "&&Focus Sticky Scroll"),
                },
                precondition: contextkey_1.ContextKeyExpr.and(contextkey_1.ContextKeyExpr.has('config.editor.stickyScroll.enabled'), editorContextKeys_1.EditorContextKeys.stickyScrollVisible),
                menu: [
                    { id: actions_1.MenuId.CommandPalette },
                ]
            });
        }
        runEditorCommand(_accessor, editor) {
            stickyScrollController_1.StickyScrollController.get(editor)?.focus();
        }
    }
    exports.FocusStickyScroll = FocusStickyScroll;
    class SelectNextStickyScrollLine extends editorExtensions_1.EditorAction2 {
        constructor() {
            super({
                id: 'editor.action.selectNextStickyScrollLine',
                title: (0, nls_1.localize2)(1306, "Select the next editor sticky scroll line"),
                precondition: editorContextKeys_1.EditorContextKeys.stickyScrollFocused.isEqualTo(true),
                keybinding: {
                    weight,
                    primary: 18 /* KeyCode.DownArrow */
                }
            });
        }
        runEditorCommand(_accessor, editor) {
            stickyScrollController_1.StickyScrollController.get(editor)?.focusNext();
        }
    }
    exports.SelectNextStickyScrollLine = SelectNextStickyScrollLine;
    class SelectPreviousStickyScrollLine extends editorExtensions_1.EditorAction2 {
        constructor() {
            super({
                id: 'editor.action.selectPreviousStickyScrollLine',
                title: (0, nls_1.localize2)(1307, "Select the previous sticky scroll line"),
                precondition: editorContextKeys_1.EditorContextKeys.stickyScrollFocused.isEqualTo(true),
                keybinding: {
                    weight,
                    primary: 16 /* KeyCode.UpArrow */
                }
            });
        }
        runEditorCommand(_accessor, editor) {
            stickyScrollController_1.StickyScrollController.get(editor)?.focusPrevious();
        }
    }
    exports.SelectPreviousStickyScrollLine = SelectPreviousStickyScrollLine;
    class GoToStickyScrollLine extends editorExtensions_1.EditorAction2 {
        constructor() {
            super({
                id: 'editor.action.goToFocusedStickyScrollLine',
                title: (0, nls_1.localize2)(1308, "Go to the focused sticky scroll line"),
                precondition: editorContextKeys_1.EditorContextKeys.stickyScrollFocused.isEqualTo(true),
                keybinding: {
                    weight,
                    primary: 3 /* KeyCode.Enter */
                }
            });
        }
        runEditorCommand(_accessor, editor) {
            stickyScrollController_1.StickyScrollController.get(editor)?.goToFocused();
        }
    }
    exports.GoToStickyScrollLine = GoToStickyScrollLine;
    class SelectEditor extends editorExtensions_1.EditorAction2 {
        constructor() {
            super({
                id: 'editor.action.selectEditor',
                title: (0, nls_1.localize2)(1309, "Select Editor"),
                precondition: editorContextKeys_1.EditorContextKeys.stickyScrollFocused.isEqualTo(true),
                keybinding: {
                    weight,
                    primary: 9 /* KeyCode.Escape */
                }
            });
        }
        runEditorCommand(_accessor, editor) {
            stickyScrollController_1.StickyScrollController.get(editor)?.selectEditor();
        }
    }
    exports.SelectEditor = SelectEditor;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[853/*vs/editor/contrib/stickyScroll/browser/stickyScrollContribution*/], __M([1/*require*/,0/*exports*/,15/*vs/editor/browser/editorExtensions*/,852/*vs/editor/contrib/stickyScroll/browser/stickyScrollActions*/,433/*vs/editor/contrib/stickyScroll/browser/stickyScrollController*/,29/*vs/platform/actions/common/actions*/]), function (require, exports, editorExtensions_1, stickyScrollActions_1, stickyScrollController_1, actions_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    (0, editorExtensions_1.registerEditorContribution)(stickyScrollController_1.StickyScrollController.ID, stickyScrollController_1.StickyScrollController, 1 /* EditorContributionInstantiation.AfterFirstRender */);
    (0, actions_1.registerAction2)(stickyScrollActions_1.ToggleStickyScroll);
    (0, actions_1.registerAction2)(stickyScrollActions_1.FocusStickyScroll);
    (0, actions_1.registerAction2)(stickyScrollActions_1.SelectPreviousStickyScrollLine);
    (0, actions_1.registerAction2)(stickyScrollActions_1.SelectNextStickyScrollLine);
    (0, actions_1.registerAction2)(stickyScrollActions_1.GoToStickyScrollLine);
    (0, actions_1.registerAction2)(stickyScrollActions_1.SelectEditor);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[854/*vs/editor/standalone/browser/referenceSearch/standaloneReferenceSearch*/], __M([1/*require*/,0/*exports*/,15/*vs/editor/browser/editorExtensions*/,34/*vs/editor/browser/services/codeEditorService*/,428/*vs/editor/contrib/gotoSymbol/browser/peek/referencesController*/,28/*vs/platform/configuration/common/configuration*/,12/*vs/platform/contextkey/common/contextkey*/,7/*vs/platform/instantiation/common/instantiation*/,50/*vs/platform/notification/common/notification*/,101/*vs/platform/storage/common/storage*/]), function (require, exports, editorExtensions_1, codeEditorService_1, referencesController_1, configuration_1, contextkey_1, instantiation_1, notification_1, storage_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.StandaloneReferencesController = void 0;
    let StandaloneReferencesController = class StandaloneReferencesController extends referencesController_1.ReferencesController {
        constructor(editor, contextKeyService, editorService, notificationService, instantiationService, storageService, configurationService) {
            super(true, editor, contextKeyService, editorService, notificationService, instantiationService, storageService, configurationService);
        }
    };
    exports.StandaloneReferencesController = StandaloneReferencesController;
    exports.StandaloneReferencesController = StandaloneReferencesController = __decorate([
        __param(1, contextkey_1.IContextKeyService),
        __param(2, codeEditorService_1.ICodeEditorService),
        __param(3, notification_1.INotificationService),
        __param(4, instantiation_1.IInstantiationService),
        __param(5, storage_1.IStorageService),
        __param(6, configuration_1.IConfigurationService)
    ], StandaloneReferencesController);
    (0, editorExtensions_1.registerEditorContribution)(referencesController_1.ReferencesController.ID, StandaloneReferencesController, 4 /* EditorContributionInstantiation.Lazy */);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[855/*vs/platform/undoRedo/common/undoRedoService*/], __M([1/*require*/,0/*exports*/,8/*vs/base/common/errors*/,2/*vs/base/common/lifecycle*/,42/*vs/base/common/network*/,111/*vs/base/common/severity*/,3/*vs/nls*/,180/*vs/platform/dialogs/common/dialogs*/,49/*vs/platform/instantiation/common/extensions*/,50/*vs/platform/notification/common/notification*/,284/*vs/platform/undoRedo/common/undoRedo*/]), function (require, exports, errors_1, lifecycle_1, network_1, severity_1, nls, dialogs_1, extensions_1, notification_1, undoRedo_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.UndoRedoService = void 0;
    const DEBUG = false;
    function getResourceLabel(resource) {
        return resource.scheme === network_1.Schemas.file ? resource.fsPath : resource.path;
    }
    let stackElementCounter = 0;
    class ResourceStackElement {
        constructor(actual, resourceLabel, strResource, groupId, groupOrder, sourceId, sourceOrder) {
            this.id = (++stackElementCounter);
            this.type = 0 /* UndoRedoElementType.Resource */;
            this.actual = actual;
            this.label = actual.label;
            this.confirmBeforeUndo = actual.confirmBeforeUndo || false;
            this.resourceLabel = resourceLabel;
            this.strResource = strResource;
            this.resourceLabels = [this.resourceLabel];
            this.strResources = [this.strResource];
            this.groupId = groupId;
            this.groupOrder = groupOrder;
            this.sourceId = sourceId;
            this.sourceOrder = sourceOrder;
            this.isValid = true;
        }
        setValid(isValid) {
            this.isValid = isValid;
        }
        toString() {
            return `[id:${this.id}] [group:${this.groupId}] [${this.isValid ? '  VALID' : 'INVALID'}] ${this.actual.constructor.name} - ${this.actual}`;
        }
    }
    class ResourceReasonPair {
        constructor(resourceLabel, reason) {
            this.resourceLabel = resourceLabel;
            this.reason = reason;
        }
    }
    class RemovedResources {
        constructor() {
            this.elements = new Map();
        }
        createMessage() {
            const externalRemoval = [];
            const noParallelUniverses = [];
            for (const [, element] of this.elements) {
                const dest = (element.reason === 0 /* RemovedResourceReason.ExternalRemoval */
                    ? externalRemoval
                    : noParallelUniverses);
                dest.push(element.resourceLabel);
            }
            const messages = [];
            if (externalRemoval.length > 0) {
                messages.push(nls.localize(1843, "The following files have been closed and modified on disk: {0}.", externalRemoval.join(', ')));
            }
            if (noParallelUniverses.length > 0) {
                messages.push(nls.localize(1844, "The following files have been modified in an incompatible way: {0}.", noParallelUniverses.join(', ')));
            }
            return messages.join('\n');
        }
        get size() {
            return this.elements.size;
        }
        has(strResource) {
            return this.elements.has(strResource);
        }
        set(strResource, value) {
            this.elements.set(strResource, value);
        }
        delete(strResource) {
            return this.elements.delete(strResource);
        }
    }
    class WorkspaceStackElement {
        constructor(actual, resourceLabels, strResources, groupId, groupOrder, sourceId, sourceOrder) {
            this.id = (++stackElementCounter);
            this.type = 1 /* UndoRedoElementType.Workspace */;
            this.actual = actual;
            this.label = actual.label;
            this.confirmBeforeUndo = actual.confirmBeforeUndo || false;
            this.resourceLabels = resourceLabels;
            this.strResources = strResources;
            this.groupId = groupId;
            this.groupOrder = groupOrder;
            this.sourceId = sourceId;
            this.sourceOrder = sourceOrder;
            this.removedResources = null;
            this.invalidatedResources = null;
        }
        canSplit() {
            return (typeof this.actual.split === 'function');
        }
        removeResource(resourceLabel, strResource, reason) {
            if (!this.removedResources) {
                this.removedResources = new RemovedResources();
            }
            if (!this.removedResources.has(strResource)) {
                this.removedResources.set(strResource, new ResourceReasonPair(resourceLabel, reason));
            }
        }
        setValid(resourceLabel, strResource, isValid) {
            if (isValid) {
                if (this.invalidatedResources) {
                    this.invalidatedResources.delete(strResource);
                    if (this.invalidatedResources.size === 0) {
                        this.invalidatedResources = null;
                    }
                }
            }
            else {
                if (!this.invalidatedResources) {
                    this.invalidatedResources = new RemovedResources();
                }
                if (!this.invalidatedResources.has(strResource)) {
                    this.invalidatedResources.set(strResource, new ResourceReasonPair(resourceLabel, 0 /* RemovedResourceReason.ExternalRemoval */));
                }
            }
        }
        toString() {
            return `[id:${this.id}] [group:${this.groupId}] [${this.invalidatedResources ? 'INVALID' : '  VALID'}] ${this.actual.constructor.name} - ${this.actual}`;
        }
    }
    class ResourceEditStack {
        constructor(resourceLabel, strResource) {
            this.resourceLabel = resourceLabel;
            this.strResource = strResource;
            this._past = [];
            this._future = [];
            this.locked = false;
            this.versionId = 1;
        }
        dispose() {
            for (const element of this._past) {
                if (element.type === 1 /* UndoRedoElementType.Workspace */) {
                    element.removeResource(this.resourceLabel, this.strResource, 0 /* RemovedResourceReason.ExternalRemoval */);
                }
            }
            for (const element of this._future) {
                if (element.type === 1 /* UndoRedoElementType.Workspace */) {
                    element.removeResource(this.resourceLabel, this.strResource, 0 /* RemovedResourceReason.ExternalRemoval */);
                }
            }
            this.versionId++;
        }
        toString() {
            const result = [];
            result.push(`* ${this.strResource}:`);
            for (let i = 0; i < this._past.length; i++) {
                result.push(`   * [UNDO] ${this._past[i]}`);
            }
            for (let i = this._future.length - 1; i >= 0; i--) {
                result.push(`   * [REDO] ${this._future[i]}`);
            }
            return result.join('\n');
        }
        flushAllElements() {
            this._past = [];
            this._future = [];
            this.versionId++;
        }
        _setElementValidFlag(element, isValid) {
            if (element.type === 1 /* UndoRedoElementType.Workspace */) {
                element.setValid(this.resourceLabel, this.strResource, isValid);
            }
            else {
                element.setValid(isValid);
            }
        }
        setElementsValidFlag(isValid, filter) {
            for (const element of this._past) {
                if (filter(element.actual)) {
                    this._setElementValidFlag(element, isValid);
                }
            }
            for (const element of this._future) {
                if (filter(element.actual)) {
                    this._setElementValidFlag(element, isValid);
                }
            }
        }
        pushElement(element) {
            // remove the future
            for (const futureElement of this._future) {
                if (futureElement.type === 1 /* UndoRedoElementType.Workspace */) {
                    futureElement.removeResource(this.resourceLabel, this.strResource, 1 /* RemovedResourceReason.NoParallelUniverses */);
                }
            }
            this._future = [];
            this._past.push(element);
            this.versionId++;
        }
        createSnapshot(resource) {
            const elements = [];
            for (let i = 0, len = this._past.length; i < len; i++) {
                elements.push(this._past[i].id);
            }
            for (let i = this._future.length - 1; i >= 0; i--) {
                elements.push(this._future[i].id);
            }
            return new undoRedo_1.ResourceEditStackSnapshot(resource, elements);
        }
        restoreSnapshot(snapshot) {
            const snapshotLength = snapshot.elements.length;
            let isOK = true;
            let snapshotIndex = 0;
            let removePastAfter = -1;
            for (let i = 0, len = this._past.length; i < len; i++, snapshotIndex++) {
                const element = this._past[i];
                if (isOK && (snapshotIndex >= snapshotLength || element.id !== snapshot.elements[snapshotIndex])) {
                    isOK = false;
                    removePastAfter = 0;
                }
                if (!isOK && element.type === 1 /* UndoRedoElementType.Workspace */) {
                    element.removeResource(this.resourceLabel, this.strResource, 0 /* RemovedResourceReason.ExternalRemoval */);
                }
            }
            let removeFutureBefore = -1;
            for (let i = this._future.length - 1; i >= 0; i--, snapshotIndex++) {
                const element = this._future[i];
                if (isOK && (snapshotIndex >= snapshotLength || element.id !== snapshot.elements[snapshotIndex])) {
                    isOK = false;
                    removeFutureBefore = i;
                }
                if (!isOK && element.type === 1 /* UndoRedoElementType.Workspace */) {
                    element.removeResource(this.resourceLabel, this.strResource, 0 /* RemovedResourceReason.ExternalRemoval */);
                }
            }
            if (removePastAfter !== -1) {
                this._past = this._past.slice(0, removePastAfter);
            }
            if (removeFutureBefore !== -1) {
                this._future = this._future.slice(removeFutureBefore + 1);
            }
            this.versionId++;
        }
        getElements() {
            const past = [];
            const future = [];
            for (const element of this._past) {
                past.push(element.actual);
            }
            for (const element of this._future) {
                future.push(element.actual);
            }
            return { past, future };
        }
        getClosestPastElement() {
            if (this._past.length === 0) {
                return null;
            }
            return this._past[this._past.length - 1];
        }
        getSecondClosestPastElement() {
            if (this._past.length < 2) {
                return null;
            }
            return this._past[this._past.length - 2];
        }
        getClosestFutureElement() {
            if (this._future.length === 0) {
                return null;
            }
            return this._future[this._future.length - 1];
        }
        hasPastElements() {
            return (this._past.length > 0);
        }
        hasFutureElements() {
            return (this._future.length > 0);
        }
        splitPastWorkspaceElement(toRemove, individualMap) {
            for (let j = this._past.length - 1; j >= 0; j--) {
                if (this._past[j] === toRemove) {
                    if (individualMap.has(this.strResource)) {
                        // gets replaced
                        this._past[j] = individualMap.get(this.strResource);
                    }
                    else {
                        // gets deleted
                        this._past.splice(j, 1);
                    }
                    break;
                }
            }
            this.versionId++;
        }
        splitFutureWorkspaceElement(toRemove, individualMap) {
            for (let j = this._future.length - 1; j >= 0; j--) {
                if (this._future[j] === toRemove) {
                    if (individualMap.has(this.strResource)) {
                        // gets replaced
                        this._future[j] = individualMap.get(this.strResource);
                    }
                    else {
                        // gets deleted
                        this._future.splice(j, 1);
                    }
                    break;
                }
            }
            this.versionId++;
        }
        moveBackward(element) {
            this._past.pop();
            this._future.push(element);
            this.versionId++;
        }
        moveForward(element) {
            this._future.pop();
            this._past.push(element);
            this.versionId++;
        }
    }
    class EditStackSnapshot {
        constructor(editStacks) {
            this.editStacks = editStacks;
            this._versionIds = [];
            for (let i = 0, len = this.editStacks.length; i < len; i++) {
                this._versionIds[i] = this.editStacks[i].versionId;
            }
        }
        isValid() {
            for (let i = 0, len = this.editStacks.length; i < len; i++) {
                if (this._versionIds[i] !== this.editStacks[i].versionId) {
                    return false;
                }
            }
            return true;
        }
    }
    const missingEditStack = new ResourceEditStack('', '');
    missingEditStack.locked = true;
    let UndoRedoService = class UndoRedoService {
        constructor(_dialogService, _notificationService) {
            this._dialogService = _dialogService;
            this._notificationService = _notificationService;
            this._editStacks = new Map();
            this._uriComparisonKeyComputers = [];
        }
        getUriComparisonKey(resource) {
            for (const uriComparisonKeyComputer of this._uriComparisonKeyComputers) {
                if (uriComparisonKeyComputer[0] === resource.scheme) {
                    return uriComparisonKeyComputer[1].getComparisonKey(resource);
                }
            }
            return resource.toString();
        }
        _print(label) {
            console.log(`------------------------------------`);
            console.log(`AFTER ${label}: `);
            const str = [];
            for (const element of this._editStacks) {
                str.push(element[1].toString());
            }
            console.log(str.join('\n'));
        }
        pushElement(element, group = undoRedo_1.UndoRedoGroup.None, source = undoRedo_1.UndoRedoSource.None) {
            if (element.type === 0 /* UndoRedoElementType.Resource */) {
                const resourceLabel = getResourceLabel(element.resource);
                const strResource = this.getUriComparisonKey(element.resource);
                this._pushElement(new ResourceStackElement(element, resourceLabel, strResource, group.id, group.nextOrder(), source.id, source.nextOrder()));
            }
            else {
                const seen = new Set();
                const resourceLabels = [];
                const strResources = [];
                for (const resource of element.resources) {
                    const resourceLabel = getResourceLabel(resource);
                    const strResource = this.getUriComparisonKey(resource);
                    if (seen.has(strResource)) {
                        continue;
                    }
                    seen.add(strResource);
                    resourceLabels.push(resourceLabel);
                    strResources.push(strResource);
                }
                if (resourceLabels.length === 1) {
                    this._pushElement(new ResourceStackElement(element, resourceLabels[0], strResources[0], group.id, group.nextOrder(), source.id, source.nextOrder()));
                }
                else {
                    this._pushElement(new WorkspaceStackElement(element, resourceLabels, strResources, group.id, group.nextOrder(), source.id, source.nextOrder()));
                }
            }
            if (DEBUG) {
                this._print('pushElement');
            }
        }
        _pushElement(element) {
            for (let i = 0, len = element.strResources.length; i < len; i++) {
                const resourceLabel = element.resourceLabels[i];
                const strResource = element.strResources[i];
                let editStack;
                if (this._editStacks.has(strResource)) {
                    editStack = this._editStacks.get(strResource);
                }
                else {
                    editStack = new ResourceEditStack(resourceLabel, strResource);
                    this._editStacks.set(strResource, editStack);
                }
                editStack.pushElement(element);
            }
        }
        getLastElement(resource) {
            const strResource = this.getUriComparisonKey(resource);
            if (this._editStacks.has(strResource)) {
                const editStack = this._editStacks.get(strResource);
                if (editStack.hasFutureElements()) {
                    return null;
                }
                const closestPastElement = editStack.getClosestPastElement();
                return closestPastElement ? closestPastElement.actual : null;
            }
            return null;
        }
        _splitPastWorkspaceElement(toRemove, ignoreResources) {
            const individualArr = toRemove.actual.split();
            const individualMap = new Map();
            for (const _element of individualArr) {
                const resourceLabel = getResourceLabel(_element.resource);
                const strResource = this.getUriComparisonKey(_element.resource);
                const element = new ResourceStackElement(_element, resourceLabel, strResource, 0, 0, 0, 0);
                individualMap.set(element.strResource, element);
            }
            for (const strResource of toRemove.strResources) {
                if (ignoreResources && ignoreResources.has(strResource)) {
                    continue;
                }
                const editStack = this._editStacks.get(strResource);
                editStack.splitPastWorkspaceElement(toRemove, individualMap);
            }
        }
        _splitFutureWorkspaceElement(toRemove, ignoreResources) {
            const individualArr = toRemove.actual.split();
            const individualMap = new Map();
            for (const _element of individualArr) {
                const resourceLabel = getResourceLabel(_element.resource);
                const strResource = this.getUriComparisonKey(_element.resource);
                const element = new ResourceStackElement(_element, resourceLabel, strResource, 0, 0, 0, 0);
                individualMap.set(element.strResource, element);
            }
            for (const strResource of toRemove.strResources) {
                if (ignoreResources && ignoreResources.has(strResource)) {
                    continue;
                }
                const editStack = this._editStacks.get(strResource);
                editStack.splitFutureWorkspaceElement(toRemove, individualMap);
            }
        }
        removeElements(resource) {
            const strResource = typeof resource === 'string' ? resource : this.getUriComparisonKey(resource);
            if (this._editStacks.has(strResource)) {
                const editStack = this._editStacks.get(strResource);
                editStack.dispose();
                this._editStacks.delete(strResource);
            }
            if (DEBUG) {
                this._print('removeElements');
            }
        }
        setElementsValidFlag(resource, isValid, filter) {
            const strResource = this.getUriComparisonKey(resource);
            if (this._editStacks.has(strResource)) {
                const editStack = this._editStacks.get(strResource);
                editStack.setElementsValidFlag(isValid, filter);
            }
            if (DEBUG) {
                this._print('setElementsValidFlag');
            }
        }
        createSnapshot(resource) {
            const strResource = this.getUriComparisonKey(resource);
            if (this._editStacks.has(strResource)) {
                const editStack = this._editStacks.get(strResource);
                return editStack.createSnapshot(resource);
            }
            return new undoRedo_1.ResourceEditStackSnapshot(resource, []);
        }
        restoreSnapshot(snapshot) {
            const strResource = this.getUriComparisonKey(snapshot.resource);
            if (this._editStacks.has(strResource)) {
                const editStack = this._editStacks.get(strResource);
                editStack.restoreSnapshot(snapshot);
                if (!editStack.hasPastElements() && !editStack.hasFutureElements()) {
                    // the edit stack is now empty, just remove it entirely
                    editStack.dispose();
                    this._editStacks.delete(strResource);
                }
            }
            if (DEBUG) {
                this._print('restoreSnapshot');
            }
        }
        getElements(resource) {
            const strResource = this.getUriComparisonKey(resource);
            if (this._editStacks.has(strResource)) {
                const editStack = this._editStacks.get(strResource);
                return editStack.getElements();
            }
            return { past: [], future: [] };
        }
        _findClosestUndoElementWithSource(sourceId) {
            if (!sourceId) {
                return [null, null];
            }
            // find an element with the sourceId and with the highest sourceOrder ready to be undone
            let matchedElement = null;
            let matchedStrResource = null;
            for (const [strResource, editStack] of this._editStacks) {
                const candidate = editStack.getClosestPastElement();
                if (!candidate) {
                    continue;
                }
                if (candidate.sourceId === sourceId) {
                    if (!matchedElement || candidate.sourceOrder > matchedElement.sourceOrder) {
                        matchedElement = candidate;
                        matchedStrResource = strResource;
                    }
                }
            }
            return [matchedElement, matchedStrResource];
        }
        canUndo(resourceOrSource) {
            if (resourceOrSource instanceof undoRedo_1.UndoRedoSource) {
                const [, matchedStrResource] = this._findClosestUndoElementWithSource(resourceOrSource.id);
                return matchedStrResource ? true : false;
            }
            const strResource = this.getUriComparisonKey(resourceOrSource);
            if (this._editStacks.has(strResource)) {
                const editStack = this._editStacks.get(strResource);
                return editStack.hasPastElements();
            }
            return false;
        }
        _onError(err, element) {
            (0, errors_1.onUnexpectedError)(err);
            // An error occurred while undoing or redoing => drop the undo/redo stack for all affected resources
            for (const strResource of element.strResources) {
                this.removeElements(strResource);
            }
            this._notificationService.error(err);
        }
        _acquireLocks(editStackSnapshot) {
            // first, check if all locks can be acquired
            for (const editStack of editStackSnapshot.editStacks) {
                if (editStack.locked) {
                    throw new Error('Cannot acquire edit stack lock');
                }
            }
            // can acquire all locks
            for (const editStack of editStackSnapshot.editStacks) {
                editStack.locked = true;
            }
            return () => {
                // release all locks
                for (const editStack of editStackSnapshot.editStacks) {
                    editStack.locked = false;
                }
            };
        }
        _safeInvokeWithLocks(element, invoke, editStackSnapshot, cleanup, continuation) {
            const releaseLocks = this._acquireLocks(editStackSnapshot);
            let result;
            try {
                result = invoke();
            }
            catch (err) {
                releaseLocks();
                cleanup.dispose();
                return this._onError(err, element);
            }
            if (result) {
                // result is Promise<void>
                return result.then(() => {
                    releaseLocks();
                    cleanup.dispose();
                    return continuation();
                }, (err) => {
                    releaseLocks();
                    cleanup.dispose();
                    return this._onError(err, element);
                });
            }
            else {
                // result is void
                releaseLocks();
                cleanup.dispose();
                return continuation();
            }
        }
        async _invokeWorkspacePrepare(element) {
            if (typeof element.actual.prepareUndoRedo === 'undefined') {
                return lifecycle_1.Disposable.None;
            }
            const result = element.actual.prepareUndoRedo();
            if (typeof result === 'undefined') {
                return lifecycle_1.Disposable.None;
            }
            return result;
        }
        _invokeResourcePrepare(element, callback) {
            if (element.actual.type !== 1 /* UndoRedoElementType.Workspace */ || typeof element.actual.prepareUndoRedo === 'undefined') {
                // no preparation needed
                return callback(lifecycle_1.Disposable.None);
            }
            const r = element.actual.prepareUndoRedo();
            if (!r) {
                // nothing to clean up
                return callback(lifecycle_1.Disposable.None);
            }
            if ((0, lifecycle_1.isDisposable)(r)) {
                return callback(r);
            }
            return r.then((disposable) => {
                return callback(disposable);
            });
        }
        _getAffectedEditStacks(element) {
            const affectedEditStacks = [];
            for (const strResource of element.strResources) {
                affectedEditStacks.push(this._editStacks.get(strResource) || missingEditStack);
            }
            return new EditStackSnapshot(affectedEditStacks);
        }
        _tryToSplitAndUndo(strResource, element, ignoreResources, message) {
            if (element.canSplit()) {
                this._splitPastWorkspaceElement(element, ignoreResources);
                this._notificationService.warn(message);
                return new WorkspaceVerificationError(this._undo(strResource, 0, true));
            }
            else {
                // Cannot safely split this workspace element => flush all undo/redo stacks
                for (const strResource of element.strResources) {
                    this.removeElements(strResource);
                }
                this._notificationService.warn(message);
                return new WorkspaceVerificationError();
            }
        }
        _checkWorkspaceUndo(strResource, element, editStackSnapshot, checkInvalidatedResources) {
            if (element.removedResources) {
                return this._tryToSplitAndUndo(strResource, element, element.removedResources, nls.localize(1845, "Could not undo '{0}' across all files. {1}", element.label, element.removedResources.createMessage()));
            }
            if (checkInvalidatedResources && element.invalidatedResources) {
                return this._tryToSplitAndUndo(strResource, element, element.invalidatedResources, nls.localize(1846, "Could not undo '{0}' across all files. {1}", element.label, element.invalidatedResources.createMessage()));
            }
            // this must be the last past element in all the impacted resources!
            const cannotUndoDueToResources = [];
            for (const editStack of editStackSnapshot.editStacks) {
                if (editStack.getClosestPastElement() !== element) {
                    cannotUndoDueToResources.push(editStack.resourceLabel);
                }
            }
            if (cannotUndoDueToResources.length > 0) {
                return this._tryToSplitAndUndo(strResource, element, null, nls.localize(1847, "Could not undo '{0}' across all files because changes were made to {1}", element.label, cannotUndoDueToResources.join(', ')));
            }
            const cannotLockDueToResources = [];
            for (const editStack of editStackSnapshot.editStacks) {
                if (editStack.locked) {
                    cannotLockDueToResources.push(editStack.resourceLabel);
                }
            }
            if (cannotLockDueToResources.length > 0) {
                return this._tryToSplitAndUndo(strResource, element, null, nls.localize(1848, "Could not undo '{0}' across all files because there is already an undo or redo operation running on {1}", element.label, cannotLockDueToResources.join(', ')));
            }
            // check if new stack elements were added in the meantime...
            if (!editStackSnapshot.isValid()) {
                return this._tryToSplitAndUndo(strResource, element, null, nls.localize(1849, "Could not undo '{0}' across all files because an undo or redo operation occurred in the meantime", element.label));
            }
            return null;
        }
        _workspaceUndo(strResource, element, undoConfirmed) {
            const affectedEditStacks = this._getAffectedEditStacks(element);
            const verificationError = this._checkWorkspaceUndo(strResource, element, affectedEditStacks, /*invalidated resources will be checked after the prepare call*/ false);
            if (verificationError) {
                return verificationError.returnValue;
            }
            return this._confirmAndExecuteWorkspaceUndo(strResource, element, affectedEditStacks, undoConfirmed);
        }
        _isPartOfUndoGroup(element) {
            if (!element.groupId) {
                return false;
            }
            // check that there is at least another element with the same groupId ready to be undone
            for (const [, editStack] of this._editStacks) {
                const pastElement = editStack.getClosestPastElement();
                if (!pastElement) {
                    continue;
                }
                if (pastElement === element) {
                    const secondPastElement = editStack.getSecondClosestPastElement();
                    if (secondPastElement && secondPastElement.groupId === element.groupId) {
                        // there is another element with the same group id in the same stack!
                        return true;
                    }
                }
                if (pastElement.groupId === element.groupId) {
                    // there is another element with the same group id in another stack!
                    return true;
                }
            }
            return false;
        }
        async _confirmAndExecuteWorkspaceUndo(strResource, element, editStackSnapshot, undoConfirmed) {
            if (element.canSplit() && !this._isPartOfUndoGroup(element)) {
                // this element can be split
                let UndoChoice;
                (function (UndoChoice) {
                    UndoChoice[UndoChoice["All"] = 0] = "All";
                    UndoChoice[UndoChoice["This"] = 1] = "This";
                    UndoChoice[UndoChoice["Cancel"] = 2] = "Cancel";
                })(UndoChoice || (UndoChoice = {}));
                const { result } = await this._dialogService.prompt({
                    type: severity_1.default.Info,
                    message: nls.localize(1850, "Would you like to undo '{0}' across all files?", element.label),
                    buttons: [
                        {
                            label: nls.localize(1851, "&&Undo in {0} Files", editStackSnapshot.editStacks.length),
                            run: () => UndoChoice.All
                        },
                        {
                            label: nls.localize(1852, "Undo this &&File"),
                            run: () => UndoChoice.This
                        }
                    ],
                    cancelButton: {
                        run: () => UndoChoice.Cancel
                    }
                });
                if (result === UndoChoice.Cancel) {
                    // choice: cancel
                    return;
                }
                if (result === UndoChoice.This) {
                    // choice: undo this file
                    this._splitPastWorkspaceElement(element, null);
                    return this._undo(strResource, 0, true);
                }
                // choice: undo in all files
                // At this point, it is possible that the element has been made invalid in the meantime (due to the confirmation await)
                const verificationError1 = this._checkWorkspaceUndo(strResource, element, editStackSnapshot, /*invalidated resources will be checked after the prepare call*/ false);
                if (verificationError1) {
                    return verificationError1.returnValue;
                }
                undoConfirmed = true;
            }
            // prepare
            let cleanup;
            try {
                cleanup = await this._invokeWorkspacePrepare(element);
            }
            catch (err) {
                return this._onError(err, element);
            }
            // At this point, it is possible that the element has been made invalid in the meantime (due to the prepare await)
            const verificationError2 = this._checkWorkspaceUndo(strResource, element, editStackSnapshot, /*now also check that there are no more invalidated resources*/ true);
            if (verificationError2) {
                cleanup.dispose();
                return verificationError2.returnValue;
            }
            for (const editStack of editStackSnapshot.editStacks) {
                editStack.moveBackward(element);
            }
            return this._safeInvokeWithLocks(element, () => element.actual.undo(), editStackSnapshot, cleanup, () => this._continueUndoInGroup(element.groupId, undoConfirmed));
        }
        _resourceUndo(editStack, element, undoConfirmed) {
            if (!element.isValid) {
                // invalid element => immediately flush edit stack!
                editStack.flushAllElements();
                return;
            }
            if (editStack.locked) {
                const message = nls.localize(1853, "Could not undo '{0}' because there is already an undo or redo operation running.", element.label);
                this._notificationService.warn(message);
                return;
            }
            return this._invokeResourcePrepare(element, (cleanup) => {
                editStack.moveBackward(element);
                return this._safeInvokeWithLocks(element, () => element.actual.undo(), new EditStackSnapshot([editStack]), cleanup, () => this._continueUndoInGroup(element.groupId, undoConfirmed));
            });
        }
        _findClosestUndoElementInGroup(groupId) {
            if (!groupId) {
                return [null, null];
            }
            // find another element with the same groupId and with the highest groupOrder ready to be undone
            let matchedElement = null;
            let matchedStrResource = null;
            for (const [strResource, editStack] of this._editStacks) {
                const candidate = editStack.getClosestPastElement();
                if (!candidate) {
                    continue;
                }
                if (candidate.groupId === groupId) {
                    if (!matchedElement || candidate.groupOrder > matchedElement.groupOrder) {
                        matchedElement = candidate;
                        matchedStrResource = strResource;
                    }
                }
            }
            return [matchedElement, matchedStrResource];
        }
        _continueUndoInGroup(groupId, undoConfirmed) {
            if (!groupId) {
                return;
            }
            const [, matchedStrResource] = this._findClosestUndoElementInGroup(groupId);
            if (matchedStrResource) {
                return this._undo(matchedStrResource, 0, undoConfirmed);
            }
        }
        undo(resourceOrSource) {
            if (resourceOrSource instanceof undoRedo_1.UndoRedoSource) {
                const [, matchedStrResource] = this._findClosestUndoElementWithSource(resourceOrSource.id);
                return matchedStrResource ? this._undo(matchedStrResource, resourceOrSource.id, false) : undefined;
            }
            if (typeof resourceOrSource === 'string') {
                return this._undo(resourceOrSource, 0, false);
            }
            return this._undo(this.getUriComparisonKey(resourceOrSource), 0, false);
        }
        _undo(strResource, sourceId = 0, undoConfirmed) {
            if (!this._editStacks.has(strResource)) {
                return;
            }
            const editStack = this._editStacks.get(strResource);
            const element = editStack.getClosestPastElement();
            if (!element) {
                return;
            }
            if (element.groupId) {
                // this element is a part of a group, we need to make sure undoing in a group is in order
                const [matchedElement, matchedStrResource] = this._findClosestUndoElementInGroup(element.groupId);
                if (element !== matchedElement && matchedStrResource) {
                    // there is an element in the same group that should be undone before this one
                    return this._undo(matchedStrResource, sourceId, undoConfirmed);
                }
            }
            const shouldPromptForConfirmation = (element.sourceId !== sourceId || element.confirmBeforeUndo);
            if (shouldPromptForConfirmation && !undoConfirmed) {
                // Hit a different source or the element asks for prompt before undo, prompt for confirmation
                return this._confirmAndContinueUndo(strResource, sourceId, element);
            }
            try {
                if (element.type === 1 /* UndoRedoElementType.Workspace */) {
                    return this._workspaceUndo(strResource, element, undoConfirmed);
                }
                else {
                    return this._resourceUndo(editStack, element, undoConfirmed);
                }
            }
            finally {
                if (DEBUG) {
                    this._print('undo');
                }
            }
        }
        async _confirmAndContinueUndo(strResource, sourceId, element) {
            const result = await this._dialogService.confirm({
                message: nls.localize(1854, "Would you like to undo '{0}'?", element.label),
                primaryButton: nls.localize(1855, "&&Yes"),
                cancelButton: nls.localize(1856, "No")
            });
            if (!result.confirmed) {
                return;
            }
            return this._undo(strResource, sourceId, true);
        }
        _findClosestRedoElementWithSource(sourceId) {
            if (!sourceId) {
                return [null, null];
            }
            // find an element with sourceId and with the lowest sourceOrder ready to be redone
            let matchedElement = null;
            let matchedStrResource = null;
            for (const [strResource, editStack] of this._editStacks) {
                const candidate = editStack.getClosestFutureElement();
                if (!candidate) {
                    continue;
                }
                if (candidate.sourceId === sourceId) {
                    if (!matchedElement || candidate.sourceOrder < matchedElement.sourceOrder) {
                        matchedElement = candidate;
                        matchedStrResource = strResource;
                    }
                }
            }
            return [matchedElement, matchedStrResource];
        }
        canRedo(resourceOrSource) {
            if (resourceOrSource instanceof undoRedo_1.UndoRedoSource) {
                const [, matchedStrResource] = this._findClosestRedoElementWithSource(resourceOrSource.id);
                return matchedStrResource ? true : false;
            }
            const strResource = this.getUriComparisonKey(resourceOrSource);
            if (this._editStacks.has(strResource)) {
                const editStack = this._editStacks.get(strResource);
                return editStack.hasFutureElements();
            }
            return false;
        }
        _tryToSplitAndRedo(strResource, element, ignoreResources, message) {
            if (element.canSplit()) {
                this._splitFutureWorkspaceElement(element, ignoreResources);
                this._notificationService.warn(message);
                return new WorkspaceVerificationError(this._redo(strResource));
            }
            else {
                // Cannot safely split this workspace element => flush all undo/redo stacks
                for (const strResource of element.strResources) {
                    this.removeElements(strResource);
                }
                this._notificationService.warn(message);
                return new WorkspaceVerificationError();
            }
        }
        _checkWorkspaceRedo(strResource, element, editStackSnapshot, checkInvalidatedResources) {
            if (element.removedResources) {
                return this._tryToSplitAndRedo(strResource, element, element.removedResources, nls.localize(1857, "Could not redo '{0}' across all files. {1}", element.label, element.removedResources.createMessage()));
            }
            if (checkInvalidatedResources && element.invalidatedResources) {
                return this._tryToSplitAndRedo(strResource, element, element.invalidatedResources, nls.localize(1858, "Could not redo '{0}' across all files. {1}", element.label, element.invalidatedResources.createMessage()));
            }
            // this must be the last future element in all the impacted resources!
            const cannotRedoDueToResources = [];
            for (const editStack of editStackSnapshot.editStacks) {
                if (editStack.getClosestFutureElement() !== element) {
                    cannotRedoDueToResources.push(editStack.resourceLabel);
                }
            }
            if (cannotRedoDueToResources.length > 0) {
                return this._tryToSplitAndRedo(strResource, element, null, nls.localize(1859, "Could not redo '{0}' across all files because changes were made to {1}", element.label, cannotRedoDueToResources.join(', ')));
            }
            const cannotLockDueToResources = [];
            for (const editStack of editStackSnapshot.editStacks) {
                if (editStack.locked) {
                    cannotLockDueToResources.push(editStack.resourceLabel);
                }
            }
            if (cannotLockDueToResources.length > 0) {
                return this._tryToSplitAndRedo(strResource, element, null, nls.localize(1860, "Could not redo '{0}' across all files because there is already an undo or redo operation running on {1}", element.label, cannotLockDueToResources.join(', ')));
            }
            // check if new stack elements were added in the meantime...
            if (!editStackSnapshot.isValid()) {
                return this._tryToSplitAndRedo(strResource, element, null, nls.localize(1861, "Could not redo '{0}' across all files because an undo or redo operation occurred in the meantime", element.label));
            }
            return null;
        }
        _workspaceRedo(strResource, element) {
            const affectedEditStacks = this._getAffectedEditStacks(element);
            const verificationError = this._checkWorkspaceRedo(strResource, element, affectedEditStacks, /*invalidated resources will be checked after the prepare call*/ false);
            if (verificationError) {
                return verificationError.returnValue;
            }
            return this._executeWorkspaceRedo(strResource, element, affectedEditStacks);
        }
        async _executeWorkspaceRedo(strResource, element, editStackSnapshot) {
            // prepare
            let cleanup;
            try {
                cleanup = await this._invokeWorkspacePrepare(element);
            }
            catch (err) {
                return this._onError(err, element);
            }
            // At this point, it is possible that the element has been made invalid in the meantime (due to the prepare await)
            const verificationError = this._checkWorkspaceRedo(strResource, element, editStackSnapshot, /*now also check that there are no more invalidated resources*/ true);
            if (verificationError) {
                cleanup.dispose();
                return verificationError.returnValue;
            }
            for (const editStack of editStackSnapshot.editStacks) {
                editStack.moveForward(element);
            }
            return this._safeInvokeWithLocks(element, () => element.actual.redo(), editStackSnapshot, cleanup, () => this._continueRedoInGroup(element.groupId));
        }
        _resourceRedo(editStack, element) {
            if (!element.isValid) {
                // invalid element => immediately flush edit stack!
                editStack.flushAllElements();
                return;
            }
            if (editStack.locked) {
                const message = nls.localize(1862, "Could not redo '{0}' because there is already an undo or redo operation running.", element.label);
                this._notificationService.warn(message);
                return;
            }
            return this._invokeResourcePrepare(element, (cleanup) => {
                editStack.moveForward(element);
                return this._safeInvokeWithLocks(element, () => element.actual.redo(), new EditStackSnapshot([editStack]), cleanup, () => this._continueRedoInGroup(element.groupId));
            });
        }
        _findClosestRedoElementInGroup(groupId) {
            if (!groupId) {
                return [null, null];
            }
            // find another element with the same groupId and with the lowest groupOrder ready to be redone
            let matchedElement = null;
            let matchedStrResource = null;
            for (const [strResource, editStack] of this._editStacks) {
                const candidate = editStack.getClosestFutureElement();
                if (!candidate) {
                    continue;
                }
                if (candidate.groupId === groupId) {
                    if (!matchedElement || candidate.groupOrder < matchedElement.groupOrder) {
                        matchedElement = candidate;
                        matchedStrResource = strResource;
                    }
                }
            }
            return [matchedElement, matchedStrResource];
        }
        _continueRedoInGroup(groupId) {
            if (!groupId) {
                return;
            }
            const [, matchedStrResource] = this._findClosestRedoElementInGroup(groupId);
            if (matchedStrResource) {
                return this._redo(matchedStrResource);
            }
        }
        redo(resourceOrSource) {
            if (resourceOrSource instanceof undoRedo_1.UndoRedoSource) {
                const [, matchedStrResource] = this._findClosestRedoElementWithSource(resourceOrSource.id);
                return matchedStrResource ? this._redo(matchedStrResource) : undefined;
            }
            if (typeof resourceOrSource === 'string') {
                return this._redo(resourceOrSource);
            }
            return this._redo(this.getUriComparisonKey(resourceOrSource));
        }
        _redo(strResource) {
            if (!this._editStacks.has(strResource)) {
                return;
            }
            const editStack = this._editStacks.get(strResource);
            const element = editStack.getClosestFutureElement();
            if (!element) {
                return;
            }
            if (element.groupId) {
                // this element is a part of a group, we need to make sure redoing in a group is in order
                const [matchedElement, matchedStrResource] = this._findClosestRedoElementInGroup(element.groupId);
                if (element !== matchedElement && matchedStrResource) {
                    // there is an element in the same group that should be redone before this one
                    return this._redo(matchedStrResource);
                }
            }
            try {
                if (element.type === 1 /* UndoRedoElementType.Workspace */) {
                    return this._workspaceRedo(strResource, element);
                }
                else {
                    return this._resourceRedo(editStack, element);
                }
            }
            finally {
                if (DEBUG) {
                    this._print('redo');
                }
            }
        }
    };
    exports.UndoRedoService = UndoRedoService;
    exports.UndoRedoService = UndoRedoService = __decorate([
        __param(0, dialogs_1.IDialogService),
        __param(1, notification_1.INotificationService)
    ], UndoRedoService);
    class WorkspaceVerificationError {
        constructor(returnValue) {
            this.returnValue = returnValue;
        }
    }
    (0, extensions_1.registerSingleton)(undoRedo_1.IUndoRedoService, UndoRedoService, 1 /* InstantiationType.Delayed */);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[186/*vs/platform/workspace/common/workspace*/], __M([1/*require*/,0/*exports*/,3/*vs/nls*/,99/*vs/base/common/path*/,225/*vs/base/common/ternarySearchTree*/,22/*vs/base/common/uri*/,7/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, nls_1, path_1, ternarySearchTree_1, uri_1, instantiation_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.STANDALONE_EDITOR_WORKSPACE_ID = exports.WORKSPACE_FILTER = exports.WORKSPACE_EXTENSION = exports.WorkspaceFolder = exports.Workspace = exports.UNKNOWN_EMPTY_WINDOW_WORKSPACE = exports.EXTENSION_DEVELOPMENT_EMPTY_WINDOW_WORKSPACE = exports.IWorkspaceContextService = void 0;
    exports.isSingleFolderWorkspaceIdentifier = isSingleFolderWorkspaceIdentifier;
    exports.isEmptyWorkspaceIdentifier = isEmptyWorkspaceIdentifier;
    exports.toWorkspaceIdentifier = toWorkspaceIdentifier;
    exports.isWorkspaceIdentifier = isWorkspaceIdentifier;
    exports.isStandaloneEditorWorkspace = isStandaloneEditorWorkspace;
    exports.IWorkspaceContextService = (0, instantiation_1.createDecorator)('contextService');
    function isSingleFolderWorkspaceIdentifier(obj) {
        const singleFolderIdentifier = obj;
        return typeof singleFolderIdentifier?.id === 'string' && uri_1.URI.isUri(singleFolderIdentifier.uri);
    }
    function isEmptyWorkspaceIdentifier(obj) {
        const emptyWorkspaceIdentifier = obj;
        return typeof emptyWorkspaceIdentifier?.id === 'string'
            && !isSingleFolderWorkspaceIdentifier(obj)
            && !isWorkspaceIdentifier(obj);
    }
    exports.EXTENSION_DEVELOPMENT_EMPTY_WINDOW_WORKSPACE = { id: 'ext-dev' };
    exports.UNKNOWN_EMPTY_WINDOW_WORKSPACE = { id: 'empty-window' };
    function toWorkspaceIdentifier(arg0, isExtensionDevelopment) {
        // Empty workspace
        if (typeof arg0 === 'string' || typeof arg0 === 'undefined') {
            // With a backupPath, the basename is the empty workspace identifier
            if (typeof arg0 === 'string') {
                return {
                    id: (0, path_1.basename)(arg0)
                };
            }
            // Extension development empty windows have backups disabled
            // so we return a constant workspace identifier for extension
            // authors to allow to restore their workspace state even then.
            if (isExtensionDevelopment) {
                return exports.EXTENSION_DEVELOPMENT_EMPTY_WINDOW_WORKSPACE;
            }
            return exports.UNKNOWN_EMPTY_WINDOW_WORKSPACE;
        }
        // Multi root
        const workspace = arg0;
        if (workspace.configuration) {
            return {
                id: workspace.id,
                configPath: workspace.configuration
            };
        }
        // Single folder
        if (workspace.folders.length === 1) {
            return {
                id: workspace.id,
                uri: workspace.folders[0].uri
            };
        }
        // Empty window
        return {
            id: workspace.id
        };
    }
    function isWorkspaceIdentifier(obj) {
        const workspaceIdentifier = obj;
        return typeof workspaceIdentifier?.id === 'string' && uri_1.URI.isUri(workspaceIdentifier.configPath);
    }
    class Workspace {
        constructor(_id, folders, _transient, _configuration, _ignorePathCasing) {
            this._id = _id;
            this._transient = _transient;
            this._configuration = _configuration;
            this._ignorePathCasing = _ignorePathCasing;
            this._foldersMap = ternarySearchTree_1.TernarySearchTree.forUris(this._ignorePathCasing, () => true);
            this.folders = folders;
        }
        get folders() {
            return this._folders;
        }
        set folders(folders) {
            this._folders = folders;
            this.updateFoldersMap();
        }
        get id() {
            return this._id;
        }
        get transient() {
            return this._transient;
        }
        get configuration() {
            return this._configuration;
        }
        set configuration(configuration) {
            this._configuration = configuration;
        }
        getFolder(resource) {
            if (!resource) {
                return null;
            }
            return this._foldersMap.findSubstr(resource) || null;
        }
        updateFoldersMap() {
            this._foldersMap = ternarySearchTree_1.TernarySearchTree.forUris(this._ignorePathCasing, () => true);
            for (const folder of this.folders) {
                this._foldersMap.set(folder.uri, folder);
            }
        }
        toJSON() {
            return { id: this.id, folders: this.folders, transient: this.transient, configuration: this.configuration };
        }
    }
    exports.Workspace = Workspace;
    class WorkspaceFolder {
        constructor(data, 
        /**
         * Provides access to the original metadata for this workspace
         * folder. This can be different from the metadata provided in
         * this class:
         * - raw paths can be relative
         * - raw paths are not normalized
         */
        raw) {
            this.raw = raw;
            this.uri = data.uri;
            this.index = data.index;
            this.name = data.name;
        }
        toJSON() {
            return { uri: this.uri, name: this.name, index: this.index };
        }
    }
    exports.WorkspaceFolder = WorkspaceFolder;
    exports.WORKSPACE_EXTENSION = 'code-workspace';
    exports.WORKSPACE_FILTER = [{ name: (0, nls_1.localize)(1863, "Code Workspace"), extensions: [exports.WORKSPACE_EXTENSION] }];
    exports.STANDALONE_EDITOR_WORKSPACE_ID = '4064f6ec-cb38-4ad0-af64-ee6467e63c82';
    function isStandaloneEditorWorkspace(workspace) {
        return workspace.id === exports.STANDALONE_EDITOR_WORKSPACE_ID;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[434/*vs/editor/contrib/contextmenu/browser/contextmenu*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,151/*vs/base/browser/ui/actionbar/actionViewItems*/,41/*vs/base/common/actions*/,2/*vs/base/common/lifecycle*/,16/*vs/base/common/platform*/,15/*vs/editor/browser/editorExtensions*/,20/*vs/editor/common/editorContextKeys*/,3/*vs/nls*/,29/*vs/platform/actions/common/actions*/,12/*vs/platform/contextkey/common/contextkey*/,58/*vs/platform/contextview/browser/contextView*/,31/*vs/platform/keybinding/common/keybinding*/,28/*vs/platform/configuration/common/configuration*/,186/*vs/platform/workspace/common/workspace*/]), function (require, exports, dom, actionViewItems_1, actions_1, lifecycle_1, platform_1, editorExtensions_1, editorContextKeys_1, nls, actions_2, contextkey_1, contextView_1, keybinding_1, configuration_1, workspace_1) {
    "use strict";
    var ContextMenuController_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ContextMenuController = void 0;
    let ContextMenuController = class ContextMenuController {
        static { ContextMenuController_1 = this; }
        static { this.ID = 'editor.contrib.contextmenu'; }
        static get(editor) {
            return editor.getContribution(ContextMenuController_1.ID);
        }
        constructor(editor, _contextMenuService, _contextViewService, _contextKeyService, _keybindingService, _menuService, _configurationService, _workspaceContextService) {
            this._contextMenuService = _contextMenuService;
            this._contextViewService = _contextViewService;
            this._contextKeyService = _contextKeyService;
            this._keybindingService = _keybindingService;
            this._menuService = _menuService;
            this._configurationService = _configurationService;
            this._workspaceContextService = _workspaceContextService;
            this._toDispose = new lifecycle_1.DisposableStore();
            this._contextMenuIsBeingShownCount = 0;
            this._editor = editor;
            this._toDispose.add(this._editor.onContextMenu((e) => this._onContextMenu(e)));
            this._toDispose.add(this._editor.onMouseWheel((e) => {
                if (this._contextMenuIsBeingShownCount > 0) {
                    const view = this._contextViewService.getContextViewElement();
                    const target = e.srcElement;
                    // Event triggers on shadow root host first
                    // Check if the context view is under this host before hiding it #103169
                    if (!(target.shadowRoot && dom.getShadowRoot(view) === target.shadowRoot)) {
                        this._contextViewService.hideContextView();
                    }
                }
            }));
            this._toDispose.add(this._editor.onKeyDown((e) => {
                if (!this._editor.getOption(24 /* EditorOption.contextmenu */)) {
                    return; // Context menu is turned off through configuration
                }
                if (e.keyCode === 58 /* KeyCode.ContextMenu */) {
                    // Chrome is funny like that
                    e.preventDefault();
                    e.stopPropagation();
                    this.showContextMenu();
                }
            }));
        }
        _onContextMenu(e) {
            if (!this._editor.hasModel()) {
                return;
            }
            if (!this._editor.getOption(24 /* EditorOption.contextmenu */)) {
                this._editor.focus();
                // Ensure the cursor is at the position of the mouse click
                if (e.target.position && !this._editor.getSelection().containsPosition(e.target.position)) {
                    this._editor.setPosition(e.target.position);
                }
                return; // Context menu is turned off through configuration
            }
            if (e.target.type === 12 /* MouseTargetType.OVERLAY_WIDGET */) {
                return; // allow native menu on widgets to support right click on input field for example in find
            }
            if (e.target.type === 6 /* MouseTargetType.CONTENT_TEXT */ && e.target.detail.injectedText) {
                return; // allow native menu on injected text
            }
            e.event.preventDefault();
            e.event.stopPropagation();
            if (e.target.type === 11 /* MouseTargetType.SCROLLBAR */) {
                return this._showScrollbarContextMenu(e.event);
            }
            if (e.target.type !== 6 /* MouseTargetType.CONTENT_TEXT */ && e.target.type !== 7 /* MouseTargetType.CONTENT_EMPTY */ && e.target.type !== 1 /* MouseTargetType.TEXTAREA */) {
                return; // only support mouse click into text or native context menu key for now
            }
            // Ensure the editor gets focus if it hasn't, so the right events are being sent to other contributions
            this._editor.focus();
            // Ensure the cursor is at the position of the mouse click
            if (e.target.position) {
                let hasSelectionAtPosition = false;
                for (const selection of this._editor.getSelections()) {
                    if (selection.containsPosition(e.target.position)) {
                        hasSelectionAtPosition = true;
                        break;
                    }
                }
                if (!hasSelectionAtPosition) {
                    this._editor.setPosition(e.target.position);
                }
            }
            // Unless the user triggerd the context menu through Shift+F10, use the mouse position as menu position
            let anchor = null;
            if (e.target.type !== 1 /* MouseTargetType.TEXTAREA */) {
                anchor = e.event;
            }
            // Show the context menu
            this.showContextMenu(anchor);
        }
        showContextMenu(anchor) {
            if (!this._editor.getOption(24 /* EditorOption.contextmenu */)) {
                return; // Context menu is turned off through configuration
            }
            if (!this._editor.hasModel()) {
                return;
            }
            // Find actions available for menu
            const menuActions = this._getMenuActions(this._editor.getModel(), this._editor.contextMenuId);
            // Show menu if we have actions to show
            if (menuActions.length > 0) {
                this._doShowContextMenu(menuActions, anchor);
            }
        }
        _getMenuActions(model, menuId) {
            const result = [];
            // get menu groups
            const groups = this._menuService.getMenuActions(menuId, this._contextKeyService, { arg: model.uri });
            // translate them into other actions
            for (const group of groups) {
                const [, actions] = group;
                let addedItems = 0;
                for (const action of actions) {
                    if (action instanceof actions_2.SubmenuItemAction) {
                        const subActions = this._getMenuActions(model, action.item.submenu);
                        if (subActions.length > 0) {
                            result.push(new actions_1.SubmenuAction(action.id, action.label, subActions));
                            addedItems++;
                        }
                    }
                    else {
                        result.push(action);
                        addedItems++;
                    }
                }
                if (addedItems) {
                    result.push(new actions_1.Separator());
                }
            }
            if (result.length) {
                result.pop(); // remove last separator
            }
            return result;
        }
        _doShowContextMenu(actions, event = null) {
            if (!this._editor.hasModel()) {
                return;
            }
            // Disable hover
            const oldHoverSetting = this._editor.getOption(60 /* EditorOption.hover */);
            this._editor.updateOptions({
                hover: {
                    enabled: false
                }
            });
            let anchor = event;
            if (!anchor) {
                // Ensure selection is visible
                this._editor.revealPosition(this._editor.getPosition(), 1 /* ScrollType.Immediate */);
                this._editor.render();
                const cursorCoords = this._editor.getScrolledVisiblePosition(this._editor.getPosition());
                // Translate to absolute editor position
                const editorCoords = dom.getDomNodePagePosition(this._editor.getDomNode());
                const posx = editorCoords.left + cursorCoords.left;
                const posy = editorCoords.top + cursorCoords.top + cursorCoords.height;
                anchor = { x: posx, y: posy };
            }
            const useShadowDOM = this._editor.getOption(128 /* EditorOption.useShadowDOM */) && !platform_1.isIOS; // Do not use shadow dom on IOS #122035
            // Show menu
            this._contextMenuIsBeingShownCount++;
            this._contextMenuService.showContextMenu({
                domForShadowRoot: useShadowDOM ? this._editor.getOverflowWidgetsDomNode() ?? this._editor.getDomNode() : undefined,
                getAnchor: () => anchor,
                getActions: () => actions,
                getActionViewItem: (action) => {
                    const keybinding = this._keybindingFor(action);
                    if (keybinding) {
                        return new actionViewItems_1.ActionViewItem(action, action, { label: true, keybinding: keybinding.getLabel(), isMenu: true });
                    }
                    const customActionViewItem = action;
                    if (typeof customActionViewItem.getActionViewItem === 'function') {
                        return customActionViewItem.getActionViewItem();
                    }
                    return new actionViewItems_1.ActionViewItem(action, action, { icon: true, label: true, isMenu: true });
                },
                getKeyBinding: (action) => {
                    return this._keybindingFor(action);
                },
                onHide: (wasCancelled) => {
                    this._contextMenuIsBeingShownCount--;
                    this._editor.updateOptions({
                        hover: oldHoverSetting
                    });
                }
            });
        }
        _showScrollbarContextMenu(anchor) {
            if (!this._editor.hasModel()) {
                return;
            }
            if ((0, workspace_1.isStandaloneEditorWorkspace)(this._workspaceContextService.getWorkspace())) {
                // can't update the configuration properly in the standalone editor
                return;
            }
            const minimapOptions = this._editor.getOption(73 /* EditorOption.minimap */);
            let lastId = 0;
            const createAction = (opts) => {
                return {
                    id: `menu-action-${++lastId}`,
                    label: opts.label,
                    tooltip: '',
                    class: undefined,
                    enabled: (typeof opts.enabled === 'undefined' ? true : opts.enabled),
                    checked: opts.checked,
                    run: opts.run
                };
            };
            const createSubmenuAction = (label, actions) => {
                return new actions_1.SubmenuAction(`menu-action-${++lastId}`, label, actions, undefined);
            };
            const createEnumAction = (label, enabled, configName, configuredValue, options) => {
                if (!enabled) {
                    return createAction({ label, enabled, run: () => { } });
                }
                const createRunner = (value) => {
                    return () => {
                        this._configurationService.updateValue(configName, value);
                    };
                };
                const actions = [];
                for (const option of options) {
                    actions.push(createAction({
                        label: option.label,
                        checked: configuredValue === option.value,
                        run: createRunner(option.value)
                    }));
                }
                return createSubmenuAction(label, actions);
            };
            const actions = [];
            actions.push(createAction({
                label: nls.localize(811, "Minimap"),
                checked: minimapOptions.enabled,
                run: () => {
                    this._configurationService.updateValue(`editor.minimap.enabled`, !minimapOptions.enabled);
                }
            }));
            actions.push(new actions_1.Separator());
            actions.push(createAction({
                label: nls.localize(812, "Render Characters"),
                enabled: minimapOptions.enabled,
                checked: minimapOptions.renderCharacters,
                run: () => {
                    this._configurationService.updateValue(`editor.minimap.renderCharacters`, !minimapOptions.renderCharacters);
                }
            }));
            actions.push(createEnumAction(nls.localize(813, "Vertical size"), minimapOptions.enabled, 'editor.minimap.size', minimapOptions.size, [{
                    label: nls.localize(814, "Proportional"),
                    value: 'proportional'
                }, {
                    label: nls.localize(815, "Fill"),
                    value: 'fill'
                }, {
                    label: nls.localize(816, "Fit"),
                    value: 'fit'
                }]));
            actions.push(createEnumAction(nls.localize(817, "Slider"), minimapOptions.enabled, 'editor.minimap.showSlider', minimapOptions.showSlider, [{
                    label: nls.localize(818, "Mouse Over"),
                    value: 'mouseover'
                }, {
                    label: nls.localize(819, "Always"),
                    value: 'always'
                }]));
            const useShadowDOM = this._editor.getOption(128 /* EditorOption.useShadowDOM */) && !platform_1.isIOS; // Do not use shadow dom on IOS #122035
            this._contextMenuIsBeingShownCount++;
            this._contextMenuService.showContextMenu({
                domForShadowRoot: useShadowDOM ? this._editor.getDomNode() : undefined,
                getAnchor: () => anchor,
                getActions: () => actions,
                onHide: (wasCancelled) => {
                    this._contextMenuIsBeingShownCount--;
                    this._editor.focus();
                }
            });
        }
        _keybindingFor(action) {
            return this._keybindingService.lookupKeybinding(action.id);
        }
        dispose() {
            if (this._contextMenuIsBeingShownCount > 0) {
                this._contextViewService.hideContextView();
            }
            this._toDispose.dispose();
        }
    };
    exports.ContextMenuController = ContextMenuController;
    exports.ContextMenuController = ContextMenuController = ContextMenuController_1 = __decorate([
        __param(1, contextView_1.IContextMenuService),
        __param(2, contextView_1.IContextViewService),
        __param(3, contextkey_1.IContextKeyService),
        __param(4, keybinding_1.IKeybindingService),
        __param(5, actions_2.IMenuService),
        __param(6, configuration_1.IConfigurationService),
        __param(7, workspace_1.IWorkspaceContextService)
    ], ContextMenuController);
    class ShowContextMenu extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: 'editor.action.showContextMenu',
                label: nls.localize(820, "Show Editor Context Menu"),
                alias: 'Show Editor Context Menu',
                precondition: undefined,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                    primary: 1024 /* KeyMod.Shift */ | 68 /* KeyCode.F10 */,
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
        run(accessor, editor) {
            ContextMenuController.get(editor)?.showContextMenu();
        }
    }
    (0, editorExtensions_1.registerEditorContribution)(ContextMenuController.ID, ContextMenuController, 2 /* EditorContributionInstantiation.BeforeFirstInteraction */);
    (0, editorExtensions_1.registerEditorAction)(ShowContextMenu);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[293/*vs/editor/contrib/dropOrPasteInto/browser/defaultProviders*/], __M([1/*require*/,0/*exports*/,13/*vs/base/common/arrays*/,194/*vs/base/common/dataTransfer*/,91/*vs/base/common/hierarchicalKind*/,2/*vs/base/common/lifecycle*/,128/*vs/base/common/mime*/,42/*vs/base/common/network*/,48/*vs/base/common/resources*/,22/*vs/base/common/uri*/,27/*vs/editor/common/languages*/,17/*vs/editor/common/services/languageFeatures*/,3/*vs/nls*/,186/*vs/platform/workspace/common/workspace*/]), function (require, exports, arrays_1, dataTransfer_1, hierarchicalKind_1, lifecycle_1, mime_1, network_1, resources_1, uri_1, languages_1, languageFeatures_1, nls_1, workspace_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DefaultPasteProvidersFeature = exports.DefaultDropProvidersFeature = exports.DefaultTextPasteOrDropEditProvider = void 0;
    class SimplePasteAndDropProvider {
        async provideDocumentPasteEdits(_model, _ranges, dataTransfer, context, token) {
            const edit = await this.getEdit(dataTransfer, token);
            if (!edit) {
                return undefined;
            }
            return {
                edits: [{ insertText: edit.insertText, title: edit.title, kind: edit.kind, handledMimeType: edit.handledMimeType, yieldTo: edit.yieldTo }],
                dispose() { },
            };
        }
        async provideDocumentDropEdits(_model, _position, dataTransfer, token) {
            const edit = await this.getEdit(dataTransfer, token);
            if (!edit) {
                return;
            }
            return {
                edits: [{ insertText: edit.insertText, title: edit.title, kind: edit.kind, handledMimeType: edit.handledMimeType, yieldTo: edit.yieldTo }],
                dispose() { },
            };
        }
    }
    class DefaultTextPasteOrDropEditProvider extends SimplePasteAndDropProvider {
        constructor() {
            super(...arguments);
            this.kind = DefaultTextPasteOrDropEditProvider.kind;
            this.dropMimeTypes = [mime_1.Mimes.text];
            this.pasteMimeTypes = [mime_1.Mimes.text];
        }
        static { this.id = 'text'; }
        static { this.kind = new hierarchicalKind_1.HierarchicalKind('text.plain'); }
        async getEdit(dataTransfer, _token) {
            const textEntry = dataTransfer.get(mime_1.Mimes.text);
            if (!textEntry) {
                return;
            }
            // Suppress if there's also a uriList entry.
            // Typically the uri-list contains the same text as the text entry so showing both is confusing.
            if (dataTransfer.has(mime_1.Mimes.uriList)) {
                return;
            }
            const insertText = await textEntry.asString();
            return {
                handledMimeType: mime_1.Mimes.text,
                title: (0, nls_1.localize)(833, "Insert Plain Text"),
                insertText,
                kind: this.kind,
            };
        }
    }
    exports.DefaultTextPasteOrDropEditProvider = DefaultTextPasteOrDropEditProvider;
    class PathProvider extends SimplePasteAndDropProvider {
        constructor() {
            super(...arguments);
            this.kind = new hierarchicalKind_1.HierarchicalKind('uri.absolute');
            this.dropMimeTypes = [mime_1.Mimes.uriList];
            this.pasteMimeTypes = [mime_1.Mimes.uriList];
        }
        async getEdit(dataTransfer, token) {
            const entries = await extractUriList(dataTransfer);
            if (!entries.length || token.isCancellationRequested) {
                return;
            }
            let uriCount = 0;
            const insertText = entries
                .map(({ uri, originalText }) => {
                if (uri.scheme === network_1.Schemas.file) {
                    return uri.fsPath;
                }
                else {
                    uriCount++;
                    return originalText;
                }
            })
                .join(' ');
            let label;
            if (uriCount > 0) {
                // Dropping at least one generic uri (such as https) so use most generic label
                label = entries.length > 1
                    ? (0, nls_1.localize)(834, "Insert Uris")
                    : (0, nls_1.localize)(835, "Insert Uri");
            }
            else {
                // All the paths are file paths
                label = entries.length > 1
                    ? (0, nls_1.localize)(836, "Insert Paths")
                    : (0, nls_1.localize)(837, "Insert Path");
            }
            return {
                handledMimeType: mime_1.Mimes.uriList,
                insertText,
                title: label,
                kind: this.kind,
            };
        }
    }
    let RelativePathProvider = class RelativePathProvider extends SimplePasteAndDropProvider {
        constructor(_workspaceContextService) {
            super();
            this._workspaceContextService = _workspaceContextService;
            this.kind = new hierarchicalKind_1.HierarchicalKind('uri.relative');
            this.dropMimeTypes = [mime_1.Mimes.uriList];
            this.pasteMimeTypes = [mime_1.Mimes.uriList];
        }
        async getEdit(dataTransfer, token) {
            const entries = await extractUriList(dataTransfer);
            if (!entries.length || token.isCancellationRequested) {
                return;
            }
            const relativeUris = (0, arrays_1.coalesce)(entries.map(({ uri }) => {
                const root = this._workspaceContextService.getWorkspaceFolder(uri);
                return root ? (0, resources_1.relativePath)(root.uri, uri) : undefined;
            }));
            if (!relativeUris.length) {
                return;
            }
            return {
                handledMimeType: mime_1.Mimes.uriList,
                insertText: relativeUris.join(' '),
                title: entries.length > 1
                    ? (0, nls_1.localize)(838, "Insert Relative Paths")
                    : (0, nls_1.localize)(839, "Insert Relative Path"),
                kind: this.kind,
            };
        }
    };
    RelativePathProvider = __decorate([
        __param(0, workspace_1.IWorkspaceContextService)
    ], RelativePathProvider);
    class PasteHtmlProvider {
        constructor() {
            this.kind = new hierarchicalKind_1.HierarchicalKind('html');
            this.pasteMimeTypes = ['text/html'];
            this._yieldTo = [{ mimeType: mime_1.Mimes.text }];
        }
        async provideDocumentPasteEdits(_model, _ranges, dataTransfer, context, token) {
            if (context.triggerKind !== languages_1.DocumentPasteTriggerKind.PasteAs && !context.only?.contains(this.kind)) {
                return;
            }
            const entry = dataTransfer.get('text/html');
            const htmlText = await entry?.asString();
            if (!htmlText || token.isCancellationRequested) {
                return;
            }
            return {
                dispose() { },
                edits: [{
                        insertText: htmlText,
                        yieldTo: this._yieldTo,
                        title: (0, nls_1.localize)(840, 'Insert HTML'),
                        kind: this.kind,
                    }],
            };
        }
    }
    async function extractUriList(dataTransfer) {
        const urlListEntry = dataTransfer.get(mime_1.Mimes.uriList);
        if (!urlListEntry) {
            return [];
        }
        const strUriList = await urlListEntry.asString();
        const entries = [];
        for (const entry of dataTransfer_1.UriList.parse(strUriList)) {
            try {
                entries.push({ uri: uri_1.URI.parse(entry), originalText: entry });
            }
            catch {
                // noop
            }
        }
        return entries;
    }
    let DefaultDropProvidersFeature = class DefaultDropProvidersFeature extends lifecycle_1.Disposable {
        constructor(languageFeaturesService, workspaceContextService) {
            super();
            this._register(languageFeaturesService.documentDropEditProvider.register('*', new DefaultTextPasteOrDropEditProvider()));
            this._register(languageFeaturesService.documentDropEditProvider.register('*', new PathProvider()));
            this._register(languageFeaturesService.documentDropEditProvider.register('*', new RelativePathProvider(workspaceContextService)));
        }
    };
    exports.DefaultDropProvidersFeature = DefaultDropProvidersFeature;
    exports.DefaultDropProvidersFeature = DefaultDropProvidersFeature = __decorate([
        __param(0, languageFeatures_1.ILanguageFeaturesService),
        __param(1, workspace_1.IWorkspaceContextService)
    ], DefaultDropProvidersFeature);
    let DefaultPasteProvidersFeature = class DefaultPasteProvidersFeature extends lifecycle_1.Disposable {
        constructor(languageFeaturesService, workspaceContextService) {
            super();
            this._register(languageFeaturesService.documentPasteEditProvider.register('*', new DefaultTextPasteOrDropEditProvider()));
            this._register(languageFeaturesService.documentPasteEditProvider.register('*', new PathProvider()));
            this._register(languageFeaturesService.documentPasteEditProvider.register('*', new RelativePathProvider(workspaceContextService)));
            this._register(languageFeaturesService.documentPasteEditProvider.register('*', new PasteHtmlProvider()));
        }
    };
    exports.DefaultPasteProvidersFeature = DefaultPasteProvidersFeature;
    exports.DefaultPasteProvidersFeature = DefaultPasteProvidersFeature = __decorate([
        __param(0, languageFeatures_1.ILanguageFeaturesService),
        __param(1, workspace_1.IWorkspaceContextService)
    ], DefaultPasteProvidersFeature);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[435/*vs/editor/contrib/dropOrPasteInto/browser/copyPasteController*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,13/*vs/base/common/arrays*/,14/*vs/base/common/async*/,18/*vs/base/common/cancellation*/,194/*vs/base/common/dataTransfer*/,91/*vs/base/common/hierarchicalKind*/,2/*vs/base/common/lifecycle*/,128/*vs/base/common/mime*/,16/*vs/base/common/platform*/,193/*vs/base/common/uuid*/,212/*vs/editor/browser/controller/textAreaInput*/,400/*vs/editor/browser/dnd*/,152/*vs/editor/browser/services/bulkEditService*/,4/*vs/editor/common/core/range*/,27/*vs/editor/common/languages*/,17/*vs/editor/common/services/languageFeatures*/,293/*vs/editor/contrib/dropOrPasteInto/browser/defaultProviders*/,268/*vs/editor/contrib/dropOrPasteInto/browser/edit*/,122/*vs/editor/contrib/editorState/browser/editorState*/,290/*vs/editor/contrib/inlineProgress/browser/inlineProgress*/,184/*vs/editor/contrib/message/browser/messageController*/,3/*vs/nls*/,117/*vs/platform/clipboard/common/clipboardService*/,12/*vs/platform/contextkey/common/contextkey*/,7/*vs/platform/instantiation/common/instantiation*/,96/*vs/platform/progress/common/progress*/,66/*vs/platform/quickinput/common/quickInput*/,396/*vs/editor/contrib/dropOrPasteInto/browser/postEditWidget*/,8/*vs/base/common/errors*/]), function (require, exports, dom_1, arrays_1, async_1, cancellation_1, dataTransfer_1, hierarchicalKind_1, lifecycle_1, mime_1, platform, uuid_1, textAreaInput_1, dnd_1, bulkEditService_1, range_1, languages_1, languageFeatures_1, defaultProviders_1, edit_1, editorState_1, inlineProgress_1, messageController_1, nls_1, clipboardService_1, contextkey_1, instantiation_1, progress_1, quickInput_1, postEditWidget_1, errors_1) {
    "use strict";
    var CopyPasteController_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CopyPasteController = exports.pasteWidgetVisibleCtx = exports.changePasteTypeCommandId = void 0;
    exports.changePasteTypeCommandId = 'editor.changePasteType';
    exports.pasteWidgetVisibleCtx = new contextkey_1.RawContextKey('pasteWidgetVisible', false, (0, nls_1.localize)(826, "Whether the paste widget is showing"));
    const vscodeClipboardMime = 'application/vnd.code.copyMetadata';
    let CopyPasteController = class CopyPasteController extends lifecycle_1.Disposable {
        static { CopyPasteController_1 = this; }
        static { this.ID = 'editor.contrib.copyPasteActionController'; }
        static get(editor) {
            return editor.getContribution(CopyPasteController_1.ID);
        }
        constructor(editor, instantiationService, _bulkEditService, _clipboardService, _languageFeaturesService, _quickInputService, _progressService) {
            super();
            this._bulkEditService = _bulkEditService;
            this._clipboardService = _clipboardService;
            this._languageFeaturesService = _languageFeaturesService;
            this._quickInputService = _quickInputService;
            this._progressService = _progressService;
            this._editor = editor;
            const container = editor.getContainerDomNode();
            this._register((0, dom_1.addDisposableListener)(container, 'copy', e => this.handleCopy(e)));
            this._register((0, dom_1.addDisposableListener)(container, 'cut', e => this.handleCopy(e)));
            this._register((0, dom_1.addDisposableListener)(container, 'paste', e => this.handlePaste(e), true));
            this._pasteProgressManager = this._register(new inlineProgress_1.InlineProgressManager('pasteIntoEditor', editor, instantiationService));
            this._postPasteWidgetManager = this._register(instantiationService.createInstance(postEditWidget_1.PostEditWidgetManager, 'pasteIntoEditor', editor, exports.pasteWidgetVisibleCtx, { id: exports.changePasteTypeCommandId, label: (0, nls_1.localize)(827, "Show paste options...") }));
        }
        changePasteType() {
            this._postPasteWidgetManager.tryShowSelector();
        }
        pasteAs(preferred) {
            this._editor.focus();
            try {
                this._pasteAsActionContext = { preferred };
                (0, dom_1.getActiveDocument)().execCommand('paste');
            }
            finally {
                this._pasteAsActionContext = undefined;
            }
        }
        clearWidgets() {
            this._postPasteWidgetManager.clear();
        }
        isPasteAsEnabled() {
            return this._editor.getOption(85 /* EditorOption.pasteAs */).enabled;
        }
        async finishedPaste() {
            await this._currentPasteOperation;
        }
        handleCopy(e) {
            if (!this._editor.hasTextFocus()) {
                return;
            }
            // Explicitly clear the clipboard internal state.
            // This is needed because on web, the browser clipboard is faked out using an in-memory store.
            // This means the resources clipboard is not properly updated when copying from the editor.
            this._clipboardService.clearInternalState?.();
            if (!e.clipboardData || !this.isPasteAsEnabled()) {
                return;
            }
            const model = this._editor.getModel();
            const selections = this._editor.getSelections();
            if (!model || !selections?.length) {
                return;
            }
            const enableEmptySelectionClipboard = this._editor.getOption(37 /* EditorOption.emptySelectionClipboard */);
            let ranges = selections;
            const wasFromEmptySelection = selections.length === 1 && selections[0].isEmpty();
            if (wasFromEmptySelection) {
                if (!enableEmptySelectionClipboard) {
                    return;
                }
                ranges = [new range_1.Range(ranges[0].startLineNumber, 1, ranges[0].startLineNumber, 1 + model.getLineLength(ranges[0].startLineNumber))];
            }
            const toCopy = this._editor._getViewModel()?.getPlainTextToCopy(selections, enableEmptySelectionClipboard, platform.isWindows);
            const multicursorText = Array.isArray(toCopy) ? toCopy : null;
            const defaultPastePayload = {
                multicursorText,
                pasteOnNewLine: wasFromEmptySelection,
                mode: null
            };
            const providers = this._languageFeaturesService.documentPasteEditProvider
                .ordered(model)
                .filter(x => !!x.prepareDocumentPaste);
            if (!providers.length) {
                this.setCopyMetadata(e.clipboardData, { defaultPastePayload });
                return;
            }
            const dataTransfer = (0, dnd_1.toVSDataTransfer)(e.clipboardData);
            const providerCopyMimeTypes = providers.flatMap(x => x.copyMimeTypes ?? []);
            // Save off a handle pointing to data that VS Code maintains.
            const handle = (0, uuid_1.generateUuid)();
            this.setCopyMetadata(e.clipboardData, {
                id: handle,
                providerCopyMimeTypes,
                defaultPastePayload
            });
            const promise = (0, async_1.createCancelablePromise)(async (token) => {
                const results = (0, arrays_1.coalesce)(await Promise.all(providers.map(async (provider) => {
                    try {
                        return await provider.prepareDocumentPaste(model, ranges, dataTransfer, token);
                    }
                    catch (err) {
                        console.error(err);
                        return undefined;
                    }
                })));
                // Values from higher priority providers should overwrite values from lower priority ones.
                // Reverse the array to so that the calls to `replace` below will do this
                results.reverse();
                for (const result of results) {
                    for (const [mime, value] of result) {
                        dataTransfer.replace(mime, value);
                    }
                }
                return dataTransfer;
            });
            CopyPasteController_1._currentCopyOperation?.dataTransferPromise.cancel();
            CopyPasteController_1._currentCopyOperation = { handle: handle, dataTransferPromise: promise };
        }
        async handlePaste(e) {
            if (!e.clipboardData || !this._editor.hasTextFocus()) {
                return;
            }
            messageController_1.MessageController.get(this._editor)?.closeMessage();
            this._currentPasteOperation?.cancel();
            this._currentPasteOperation = undefined;
            const model = this._editor.getModel();
            const selections = this._editor.getSelections();
            if (!selections?.length || !model) {
                return;
            }
            if (this._editor.getOption(92 /* EditorOption.readOnly */) // Never enabled if editor is readonly.
                || (!this.isPasteAsEnabled() && !this._pasteAsActionContext) // Or feature disabled (but still enable if paste was explicitly requested)
            ) {
                return;
            }
            const metadata = this.fetchCopyMetadata(e);
            const dataTransfer = (0, dnd_1.toExternalVSDataTransfer)(e.clipboardData);
            dataTransfer.delete(vscodeClipboardMime);
            const allPotentialMimeTypes = [
                ...e.clipboardData.types,
                ...metadata?.providerCopyMimeTypes ?? [],
                // TODO: always adds `uri-list` because this get set if there are resources in the system clipboard.
                // However we can only check the system clipboard async. For this early check, just add it in.
                // We filter providers again once we have the final dataTransfer we will use.
                mime_1.Mimes.uriList,
            ];
            const allProviders = this._languageFeaturesService.documentPasteEditProvider
                .ordered(model)
                .filter(provider => {
                // Filter out providers that don't match the requested paste types
                const preference = this._pasteAsActionContext?.preferred;
                if (preference) {
                    if (provider.providedPasteEditKinds && !this.providerMatchesPreference(provider, preference)) {
                        return false;
                    }
                }
                // And providers that don't handle any of mime types in the clipboard
                return provider.pasteMimeTypes?.some(type => (0, dataTransfer_1.matchesMimeType)(type, allPotentialMimeTypes));
            });
            if (!allProviders.length) {
                if (this._pasteAsActionContext?.preferred) {
                    this.showPasteAsNoEditMessage(selections, this._pasteAsActionContext.preferred);
                }
                return;
            }
            // Prevent the editor's default paste handler from running.
            // Note that after this point, we are fully responsible for handling paste.
            // If we can't provider a paste for any reason, we need to explicitly delegate pasting back to the editor.
            e.preventDefault();
            e.stopImmediatePropagation();
            if (this._pasteAsActionContext) {
                this.showPasteAsPick(this._pasteAsActionContext.preferred, allProviders, selections, dataTransfer, metadata);
            }
            else {
                this.doPasteInline(allProviders, selections, dataTransfer, metadata, e);
            }
        }
        showPasteAsNoEditMessage(selections, preference) {
            messageController_1.MessageController.get(this._editor)?.showMessage((0, nls_1.localize)(828, "No paste edits for '{0}' found", preference instanceof hierarchicalKind_1.HierarchicalKind ? preference.value : preference.providerId), selections[0].getStartPosition());
        }
        doPasteInline(allProviders, selections, dataTransfer, metadata, clipboardEvent) {
            const editor = this._editor;
            if (!editor.hasModel()) {
                return;
            }
            const editorStateCts = new editorState_1.EditorStateCancellationTokenSource(editor, 1 /* CodeEditorStateFlag.Value */ | 2 /* CodeEditorStateFlag.Selection */, undefined);
            const p = (0, async_1.createCancelablePromise)(async (pToken) => {
                const editor = this._editor;
                if (!editor.hasModel()) {
                    return;
                }
                const model = editor.getModel();
                const disposables = new lifecycle_1.DisposableStore();
                const cts = disposables.add(new cancellation_1.CancellationTokenSource(pToken));
                disposables.add(editorStateCts.token.onCancellationRequested(() => cts.cancel()));
                const token = cts.token;
                try {
                    await this.mergeInDataFromCopy(dataTransfer, metadata, token);
                    if (token.isCancellationRequested) {
                        return;
                    }
                    const supportedProviders = allProviders.filter(provider => this.isSupportedPasteProvider(provider, dataTransfer));
                    if (!supportedProviders.length
                        || (supportedProviders.length === 1 && supportedProviders[0] instanceof defaultProviders_1.DefaultTextPasteOrDropEditProvider) // Only our default text provider is active
                    ) {
                        return this.applyDefaultPasteHandler(dataTransfer, metadata, token, clipboardEvent);
                    }
                    const context = {
                        triggerKind: languages_1.DocumentPasteTriggerKind.Automatic,
                    };
                    const editSession = await this.getPasteEdits(supportedProviders, dataTransfer, model, selections, context, token);
                    disposables.add(editSession);
                    if (token.isCancellationRequested) {
                        return;
                    }
                    // If the only edit returned is our default text edit, use the default paste handler
                    if (editSession.edits.length === 1 && editSession.edits[0].provider instanceof defaultProviders_1.DefaultTextPasteOrDropEditProvider) {
                        return this.applyDefaultPasteHandler(dataTransfer, metadata, token, clipboardEvent);
                    }
                    if (editSession.edits.length) {
                        const canShowWidget = editor.getOption(85 /* EditorOption.pasteAs */).showPasteSelector === 'afterPaste';
                        return this._postPasteWidgetManager.applyEditAndShowIfNeeded(selections, { activeEditIndex: 0, allEdits: editSession.edits }, canShowWidget, (edit, token) => {
                            return new Promise((resolve, reject) => {
                                (async () => {
                                    try {
                                        const resolveP = edit.provider.resolveDocumentPasteEdit?.(edit, token);
                                        const showP = new async_1.DeferredPromise();
                                        const resolved = resolveP && await this._pasteProgressManager.showWhile(selections[0].getEndPosition(), (0, nls_1.localize)(829, "Resolving paste edit. Click to cancel"), Promise.race([showP.p, resolveP]), {
                                            cancel: () => {
                                                showP.cancel();
                                                return reject(new errors_1.CancellationError());
                                            }
                                        }, 0);
                                        if (resolved) {
                                            edit.additionalEdit = resolved.additionalEdit;
                                        }
                                        return resolve(edit);
                                    }
                                    catch (err) {
                                        return reject(err);
                                    }
                                })();
                            });
                        }, token);
                    }
                    await this.applyDefaultPasteHandler(dataTransfer, metadata, token, clipboardEvent);
                }
                finally {
                    disposables.dispose();
                    if (this._currentPasteOperation === p) {
                        this._currentPasteOperation = undefined;
                    }
                }
            });
            this._pasteProgressManager.showWhile(selections[0].getEndPosition(), (0, nls_1.localize)(830, "Running paste handlers. Click to cancel and do basic paste"), p, {
                cancel: async () => {
                    try {
                        p.cancel();
                        if (editorStateCts.token.isCancellationRequested) {
                            return;
                        }
                        await this.applyDefaultPasteHandler(dataTransfer, metadata, editorStateCts.token, clipboardEvent);
                    }
                    finally {
                        editorStateCts.dispose();
                    }
                }
            }).then(() => {
                editorStateCts.dispose();
            });
            this._currentPasteOperation = p;
        }
        showPasteAsPick(preference, allProviders, selections, dataTransfer, metadata) {
            const p = (0, async_1.createCancelablePromise)(async (token) => {
                const editor = this._editor;
                if (!editor.hasModel()) {
                    return;
                }
                const model = editor.getModel();
                const disposables = new lifecycle_1.DisposableStore();
                const tokenSource = disposables.add(new editorState_1.EditorStateCancellationTokenSource(editor, 1 /* CodeEditorStateFlag.Value */ | 2 /* CodeEditorStateFlag.Selection */, undefined, token));
                try {
                    await this.mergeInDataFromCopy(dataTransfer, metadata, tokenSource.token);
                    if (tokenSource.token.isCancellationRequested) {
                        return;
                    }
                    // Filter out any providers the don't match the full data transfer we will send them.
                    let supportedProviders = allProviders.filter(provider => this.isSupportedPasteProvider(provider, dataTransfer, preference));
                    if (preference) {
                        // We are looking for a specific edit
                        supportedProviders = supportedProviders.filter(provider => this.providerMatchesPreference(provider, preference));
                    }
                    const context = {
                        triggerKind: languages_1.DocumentPasteTriggerKind.PasteAs,
                        only: preference && preference instanceof hierarchicalKind_1.HierarchicalKind ? preference : undefined,
                    };
                    let editSession = disposables.add(await this.getPasteEdits(supportedProviders, dataTransfer, model, selections, context, tokenSource.token));
                    if (tokenSource.token.isCancellationRequested) {
                        return;
                    }
                    // Filter out any edits that don't match the requested kind
                    if (preference) {
                        editSession = {
                            edits: editSession.edits.filter(edit => {
                                if (preference instanceof hierarchicalKind_1.HierarchicalKind) {
                                    return preference.contains(edit.kind);
                                }
                                else {
                                    return preference.providerId === edit.provider.id;
                                }
                            }),
                            dispose: editSession.dispose
                        };
                    }
                    if (!editSession.edits.length) {
                        if (context.only) {
                            this.showPasteAsNoEditMessage(selections, context.only);
                        }
                        return;
                    }
                    let pickedEdit;
                    if (preference) {
                        pickedEdit = editSession.edits.at(0);
                    }
                    else {
                        const selected = await this._quickInputService.pick(editSession.edits.map((edit) => ({
                            label: edit.title,
                            description: edit.kind?.value,
                            edit,
                        })), {
                            placeHolder: (0, nls_1.localize)(831, "Select Paste Action"),
                        });
                        pickedEdit = selected?.edit;
                    }
                    if (!pickedEdit) {
                        return;
                    }
                    const combinedWorkspaceEdit = (0, edit_1.createCombinedWorkspaceEdit)(model.uri, selections, pickedEdit);
                    await this._bulkEditService.apply(combinedWorkspaceEdit, { editor: this._editor });
                }
                finally {
                    disposables.dispose();
                    if (this._currentPasteOperation === p) {
                        this._currentPasteOperation = undefined;
                    }
                }
            });
            this._progressService.withProgress({
                location: 10 /* ProgressLocation.Window */,
                title: (0, nls_1.localize)(832, "Running paste handlers"),
            }, () => p);
        }
        setCopyMetadata(dataTransfer, metadata) {
            dataTransfer.setData(vscodeClipboardMime, JSON.stringify(metadata));
        }
        fetchCopyMetadata(e) {
            if (!e.clipboardData) {
                return;
            }
            // Prefer using the clipboard data we saved off
            const rawMetadata = e.clipboardData.getData(vscodeClipboardMime);
            if (rawMetadata) {
                try {
                    return JSON.parse(rawMetadata);
                }
                catch {
                    return undefined;
                }
            }
            // Otherwise try to extract the generic text editor metadata
            const [_, metadata] = textAreaInput_1.ClipboardEventUtils.getTextData(e.clipboardData);
            if (metadata) {
                return {
                    defaultPastePayload: {
                        mode: metadata.mode,
                        multicursorText: metadata.multicursorText ?? null,
                        pasteOnNewLine: !!metadata.isFromEmptySelection,
                    },
                };
            }
            return undefined;
        }
        async mergeInDataFromCopy(dataTransfer, metadata, token) {
            if (metadata?.id && CopyPasteController_1._currentCopyOperation?.handle === metadata.id) {
                const toMergeDataTransfer = await CopyPasteController_1._currentCopyOperation.dataTransferPromise;
                if (token.isCancellationRequested) {
                    return;
                }
                for (const [key, value] of toMergeDataTransfer) {
                    dataTransfer.replace(key, value);
                }
            }
            if (!dataTransfer.has(mime_1.Mimes.uriList)) {
                const resources = await this._clipboardService.readResources();
                if (token.isCancellationRequested) {
                    return;
                }
                if (resources.length) {
                    dataTransfer.append(mime_1.Mimes.uriList, (0, dataTransfer_1.createStringDataTransferItem)(dataTransfer_1.UriList.create(resources)));
                }
            }
        }
        async getPasteEdits(providers, dataTransfer, model, selections, context, token) {
            const disposables = new lifecycle_1.DisposableStore();
            const results = await (0, async_1.raceCancellation)(Promise.all(providers.map(async (provider) => {
                try {
                    const edits = await provider.provideDocumentPasteEdits?.(model, selections, dataTransfer, context, token);
                    if (edits) {
                        disposables.add(edits);
                    }
                    return edits?.edits?.map(edit => ({ ...edit, provider }));
                }
                catch (err) {
                    if (!(0, errors_1.isCancellationError)(err)) {
                        console.error(err);
                    }
                    return undefined;
                }
            })), token);
            const edits = (0, arrays_1.coalesce)(results ?? []).flat().filter(edit => {
                return !context.only || context.only.contains(edit.kind);
            });
            return {
                edits: (0, edit_1.sortEditsByYieldTo)(edits),
                dispose: () => disposables.dispose()
            };
        }
        async applyDefaultPasteHandler(dataTransfer, metadata, token, clipboardEvent) {
            const textDataTransfer = dataTransfer.get(mime_1.Mimes.text) ?? dataTransfer.get('text');
            const text = (await textDataTransfer?.asString()) ?? '';
            if (token.isCancellationRequested) {
                return;
            }
            const payload = {
                clipboardEvent,
                text,
                pasteOnNewLine: metadata?.defaultPastePayload.pasteOnNewLine ?? false,
                multicursorText: metadata?.defaultPastePayload.multicursorText ?? null,
                mode: null,
            };
            this._editor.trigger('keyboard', "paste" /* Handler.Paste */, payload);
        }
        /**
         * Filter out providers if they:
         * - Don't handle any of the data transfer types we have
         * - Don't match the preferred paste kind
         */
        isSupportedPasteProvider(provider, dataTransfer, preference) {
            if (!provider.pasteMimeTypes?.some(type => dataTransfer.matches(type))) {
                return false;
            }
            return !preference || this.providerMatchesPreference(provider, preference);
        }
        providerMatchesPreference(provider, preference) {
            if (preference instanceof hierarchicalKind_1.HierarchicalKind) {
                if (!provider.providedPasteEditKinds) {
                    return true;
                }
                return provider.providedPasteEditKinds.some(providedKind => preference.contains(providedKind));
            }
            else {
                return provider.id === preference.providerId;
            }
        }
    };
    exports.CopyPasteController = CopyPasteController;
    exports.CopyPasteController = CopyPasteController = CopyPasteController_1 = __decorate([
        __param(1, instantiation_1.IInstantiationService),
        __param(2, bulkEditService_1.IBulkEditService),
        __param(3, clipboardService_1.IClipboardService),
        __param(4, languageFeatures_1.ILanguageFeaturesService),
        __param(5, quickInput_1.IQuickInputService),
        __param(6, progress_1.IProgressService)
    ], CopyPasteController);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[856/*vs/editor/contrib/clipboard/browser/clipboard*/], __M([1/*require*/,0/*exports*/,64/*vs/base/browser/browser*/,5/*vs/base/browser/dom*/,16/*vs/base/common/platform*/,212/*vs/editor/browser/controller/textAreaInput*/,15/*vs/editor/browser/editorExtensions*/,34/*vs/editor/browser/services/codeEditorService*/,20/*vs/editor/common/editorContextKeys*/,435/*vs/editor/contrib/dropOrPasteInto/browser/copyPasteController*/,3/*vs/nls*/,29/*vs/platform/actions/common/actions*/,117/*vs/platform/clipboard/common/clipboardService*/,12/*vs/platform/contextkey/common/contextkey*/]), function (require, exports, browser, dom_1, platform, textAreaInput_1, editorExtensions_1, codeEditorService_1, editorContextKeys_1, copyPasteController_1, nls, actions_1, clipboardService_1, contextkey_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.PasteAction = exports.CopyAction = exports.CutAction = void 0;
    const CLIPBOARD_CONTEXT_MENU_GROUP = '9_cutcopypaste';
    const supportsCut = (platform.isNative || document.queryCommandSupported('cut'));
    const supportsCopy = (platform.isNative || document.queryCommandSupported('copy'));
    // Firefox only supports navigator.clipboard.readText() in browser extensions.
    // See https://developer.mozilla.org/en-US/docs/Web/API/Clipboard/readText#Browser_compatibility
    // When loading over http, navigator.clipboard can be undefined. See https://github.com/microsoft/monaco-editor/issues/2313
    const supportsPaste = (typeof navigator.clipboard === 'undefined' || browser.isFirefox) ? document.queryCommandSupported('paste') : true;
    function registerCommand(command) {
        command.register();
        return command;
    }
    exports.CutAction = supportsCut ? registerCommand(new editorExtensions_1.MultiCommand({
        id: 'editor.action.clipboardCutAction',
        precondition: undefined,
        kbOpts: (
        // Do not bind cut keybindings in the browser,
        // since browsers do that for us and it avoids security prompts
        platform.isNative ? {
            primary: 2048 /* KeyMod.CtrlCmd */ | 54 /* KeyCode.KeyX */,
            win: { primary: 2048 /* KeyMod.CtrlCmd */ | 54 /* KeyCode.KeyX */, secondary: [1024 /* KeyMod.Shift */ | 20 /* KeyCode.Delete */] },
            weight: 100 /* KeybindingWeight.EditorContrib */
        } : undefined),
        menuOpts: [{
                menuId: actions_1.MenuId.MenubarEditMenu,
                group: '2_ccp',
                title: nls.localize(725, "Cu&&t"),
                order: 1
            }, {
                menuId: actions_1.MenuId.EditorContext,
                group: CLIPBOARD_CONTEXT_MENU_GROUP,
                title: nls.localize(726, "Cut"),
                when: editorContextKeys_1.EditorContextKeys.writable,
                order: 1,
            }, {
                menuId: actions_1.MenuId.CommandPalette,
                group: '',
                title: nls.localize(727, "Cut"),
                order: 1
            }, {
                menuId: actions_1.MenuId.SimpleEditorContext,
                group: CLIPBOARD_CONTEXT_MENU_GROUP,
                title: nls.localize(728, "Cut"),
                when: editorContextKeys_1.EditorContextKeys.writable,
                order: 1,
            }]
    })) : undefined;
    exports.CopyAction = supportsCopy ? registerCommand(new editorExtensions_1.MultiCommand({
        id: 'editor.action.clipboardCopyAction',
        precondition: undefined,
        kbOpts: (
        // Do not bind copy keybindings in the browser,
        // since browsers do that for us and it avoids security prompts
        platform.isNative ? {
            primary: 2048 /* KeyMod.CtrlCmd */ | 33 /* KeyCode.KeyC */,
            win: { primary: 2048 /* KeyMod.CtrlCmd */ | 33 /* KeyCode.KeyC */, secondary: [2048 /* KeyMod.CtrlCmd */ | 19 /* KeyCode.Insert */] },
            weight: 100 /* KeybindingWeight.EditorContrib */
        } : undefined),
        menuOpts: [{
                menuId: actions_1.MenuId.MenubarEditMenu,
                group: '2_ccp',
                title: nls.localize(729, "&&Copy"),
                order: 2
            }, {
                menuId: actions_1.MenuId.EditorContext,
                group: CLIPBOARD_CONTEXT_MENU_GROUP,
                title: nls.localize(730, "Copy"),
                order: 2,
            }, {
                menuId: actions_1.MenuId.CommandPalette,
                group: '',
                title: nls.localize(731, "Copy"),
                order: 1
            }, {
                menuId: actions_1.MenuId.SimpleEditorContext,
                group: CLIPBOARD_CONTEXT_MENU_GROUP,
                title: nls.localize(732, "Copy"),
                order: 2,
            }]
    })) : undefined;
    actions_1.MenuRegistry.appendMenuItem(actions_1.MenuId.MenubarEditMenu, { submenu: actions_1.MenuId.MenubarCopy, title: nls.localize2(738, "Copy As"), group: '2_ccp', order: 3 });
    actions_1.MenuRegistry.appendMenuItem(actions_1.MenuId.EditorContext, { submenu: actions_1.MenuId.EditorContextCopy, title: nls.localize2(739, "Copy As"), group: CLIPBOARD_CONTEXT_MENU_GROUP, order: 3 });
    actions_1.MenuRegistry.appendMenuItem(actions_1.MenuId.EditorContext, { submenu: actions_1.MenuId.EditorContextShare, title: nls.localize2(740, "Share"), group: '11_share', order: -1, when: contextkey_1.ContextKeyExpr.and(contextkey_1.ContextKeyExpr.notEquals('resourceScheme', 'output'), editorContextKeys_1.EditorContextKeys.editorTextFocus) });
    actions_1.MenuRegistry.appendMenuItem(actions_1.MenuId.ExplorerContext, { submenu: actions_1.MenuId.ExplorerContextShare, title: nls.localize2(741, "Share"), group: '11_share', order: -1 });
    exports.PasteAction = supportsPaste ? registerCommand(new editorExtensions_1.MultiCommand({
        id: 'editor.action.clipboardPasteAction',
        precondition: undefined,
        kbOpts: (
        // Do not bind paste keybindings in the browser,
        // since browsers do that for us and it avoids security prompts
        platform.isNative ? {
            primary: 2048 /* KeyMod.CtrlCmd */ | 52 /* KeyCode.KeyV */,
            win: { primary: 2048 /* KeyMod.CtrlCmd */ | 52 /* KeyCode.KeyV */, secondary: [1024 /* KeyMod.Shift */ | 19 /* KeyCode.Insert */] },
            linux: { primary: 2048 /* KeyMod.CtrlCmd */ | 52 /* KeyCode.KeyV */, secondary: [1024 /* KeyMod.Shift */ | 19 /* KeyCode.Insert */] },
            weight: 100 /* KeybindingWeight.EditorContrib */
        } : undefined),
        menuOpts: [{
                menuId: actions_1.MenuId.MenubarEditMenu,
                group: '2_ccp',
                title: nls.localize(733, "&&Paste"),
                order: 4
            }, {
                menuId: actions_1.MenuId.EditorContext,
                group: CLIPBOARD_CONTEXT_MENU_GROUP,
                title: nls.localize(734, "Paste"),
                when: editorContextKeys_1.EditorContextKeys.writable,
                order: 4,
            }, {
                menuId: actions_1.MenuId.CommandPalette,
                group: '',
                title: nls.localize(735, "Paste"),
                order: 1
            }, {
                menuId: actions_1.MenuId.SimpleEditorContext,
                group: CLIPBOARD_CONTEXT_MENU_GROUP,
                title: nls.localize(736, "Paste"),
                when: editorContextKeys_1.EditorContextKeys.writable,
                order: 4,
            }]
    })) : undefined;
    class ExecCommandCopyWithSyntaxHighlightingAction extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: 'editor.action.clipboardCopyWithSyntaxHighlightingAction',
                label: nls.localize(737, "Copy With Syntax Highlighting"),
                alias: 'Copy With Syntax Highlighting',
                precondition: undefined,
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                    primary: 0,
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
        run(accessor, editor) {
            if (!editor.hasModel()) {
                return;
            }
            const emptySelectionClipboard = editor.getOption(37 /* EditorOption.emptySelectionClipboard */);
            if (!emptySelectionClipboard && editor.getSelection().isEmpty()) {
                return;
            }
            textAreaInput_1.CopyOptions.forceCopyWithSyntaxHighlighting = true;
            editor.focus();
            editor.getContainerDomNode().ownerDocument.execCommand('copy');
            textAreaInput_1.CopyOptions.forceCopyWithSyntaxHighlighting = false;
        }
    }
    function registerExecCommandImpl(target, browserCommand) {
        if (!target) {
            return;
        }
        // 1. handle case when focus is in editor.
        target.addImplementation(10000, 'code-editor', (accessor, args) => {
            // Only if editor text focus (i.e. not if editor has widget focus).
            const focusedEditor = accessor.get(codeEditorService_1.ICodeEditorService).getFocusedCodeEditor();
            if (focusedEditor && focusedEditor.hasTextFocus()) {
                // Do not execute if there is no selection and empty selection clipboard is off
                const emptySelectionClipboard = focusedEditor.getOption(37 /* EditorOption.emptySelectionClipboard */);
                const selection = focusedEditor.getSelection();
                if (selection && selection.isEmpty() && !emptySelectionClipboard) {
                    return true;
                }
                focusedEditor.getContainerDomNode().ownerDocument.execCommand(browserCommand);
                return true;
            }
            return false;
        });
        // 2. (default) handle case when focus is somewhere else.
        target.addImplementation(0, 'generic-dom', (accessor, args) => {
            (0, dom_1.getActiveDocument)().execCommand(browserCommand);
            return true;
        });
    }
    registerExecCommandImpl(exports.CutAction, 'cut');
    registerExecCommandImpl(exports.CopyAction, 'copy');
    if (exports.PasteAction) {
        // 1. Paste: handle case when focus is in editor.
        exports.PasteAction.addImplementation(10000, 'code-editor', (accessor, args) => {
            const codeEditorService = accessor.get(codeEditorService_1.ICodeEditorService);
            const clipboardService = accessor.get(clipboardService_1.IClipboardService);
            // Only if editor text focus (i.e. not if editor has widget focus).
            const focusedEditor = codeEditorService.getFocusedCodeEditor();
            if (focusedEditor && focusedEditor.hasTextFocus()) {
                const result = focusedEditor.getContainerDomNode().ownerDocument.execCommand('paste');
                if (result) {
                    return copyPasteController_1.CopyPasteController.get(focusedEditor)?.finishedPaste() ?? Promise.resolve();
                }
                else if (platform.isWeb) {
                    // Use the clipboard service if document.execCommand('paste') was not successful
                    return (async () => {
                        const clipboardText = await clipboardService.readText();
                        if (clipboardText !== '') {
                            const metadata = textAreaInput_1.InMemoryClipboardMetadataManager.INSTANCE.get(clipboardText);
                            let pasteOnNewLine = false;
                            let multicursorText = null;
                            let mode = null;
                            if (metadata) {
                                pasteOnNewLine = (focusedEditor.getOption(37 /* EditorOption.emptySelectionClipboard */) && !!metadata.isFromEmptySelection);
                                multicursorText = (typeof metadata.multicursorText !== 'undefined' ? metadata.multicursorText : null);
                                mode = metadata.mode;
                            }
                            focusedEditor.trigger('keyboard', "paste" /* Handler.Paste */, {
                                text: clipboardText,
                                pasteOnNewLine,
                                multicursorText,
                                mode
                            });
                        }
                    })();
                }
                return true;
            }
            return false;
        });
        // 2. Paste: (default) handle case when focus is somewhere else.
        exports.PasteAction.addImplementation(0, 'generic-dom', (accessor, args) => {
            (0, dom_1.getActiveDocument)().execCommand('paste');
            return true;
        });
    }
    if (supportsCopy) {
        (0, editorExtensions_1.registerEditorAction)(ExecCommandCopyWithSyntaxHighlightingAction);
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[857/*vs/editor/contrib/dropOrPasteInto/browser/copyPasteContribution*/], __M([1/*require*/,0/*exports*/,91/*vs/base/common/hierarchicalKind*/,15/*vs/editor/browser/editorExtensions*/,20/*vs/editor/common/editorContextKeys*/,130/*vs/editor/common/editorFeatures*/,435/*vs/editor/contrib/dropOrPasteInto/browser/copyPasteController*/,293/*vs/editor/contrib/dropOrPasteInto/browser/defaultProviders*/,3/*vs/nls*/]), function (require, exports, hierarchicalKind_1, editorExtensions_1, editorContextKeys_1, editorFeatures_1, copyPasteController_1, defaultProviders_1, nls) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    (0, editorExtensions_1.registerEditorContribution)(copyPasteController_1.CopyPasteController.ID, copyPasteController_1.CopyPasteController, 0 /* EditorContributionInstantiation.Eager */); // eager because it listens to events on the container dom node of the editor
    (0, editorFeatures_1.registerEditorFeature)(defaultProviders_1.DefaultPasteProvidersFeature);
    (0, editorExtensions_1.registerEditorCommand)(new class extends editorExtensions_1.EditorCommand {
        constructor() {
            super({
                id: copyPasteController_1.changePasteTypeCommandId,
                precondition: copyPasteController_1.pasteWidgetVisibleCtx,
                kbOpts: {
                    weight: 100 /* KeybindingWeight.EditorContrib */,
                    primary: 2048 /* KeyMod.CtrlCmd */ | 89 /* KeyCode.Period */,
                }
            });
        }
        runEditorCommand(_accessor, editor) {
            return copyPasteController_1.CopyPasteController.get(editor)?.changePasteType();
        }
    });
    (0, editorExtensions_1.registerEditorCommand)(new class extends editorExtensions_1.EditorCommand {
        constructor() {
            super({
                id: 'editor.hidePasteWidget',
                precondition: copyPasteController_1.pasteWidgetVisibleCtx,
                kbOpts: {
                    weight: 100 /* KeybindingWeight.EditorContrib */,
                    primary: 9 /* KeyCode.Escape */,
                }
            });
        }
        runEditorCommand(_accessor, editor) {
            copyPasteController_1.CopyPasteController.get(editor)?.clearWidgets();
        }
    });
    (0, editorExtensions_1.registerEditorAction)(class PasteAsAction extends editorExtensions_1.EditorAction {
        static { this.argsSchema = {
            type: 'object',
            properties: {
                kind: {
                    type: 'string',
                    description: nls.localize(823, "The kind of the paste edit to try applying. If not provided or there are multiple edits for this kind, the editor will show a picker."),
                }
            },
        }; }
        constructor() {
            super({
                id: 'editor.action.pasteAs',
                label: nls.localize(824, "Paste As..."),
                alias: 'Paste As...',
                precondition: editorContextKeys_1.EditorContextKeys.writable,
                metadata: {
                    description: 'Paste as',
                    args: [{
                            name: 'args',
                            schema: PasteAsAction.argsSchema
                        }]
                }
            });
        }
        run(_accessor, editor, args) {
            let kind = typeof args?.kind === 'string' ? args.kind : undefined;
            if (!kind && args) {
                // Support old id property
                // TODO: remove this in the future
                kind = typeof args.id === 'string' ? args.id : undefined;
            }
            return copyPasteController_1.CopyPasteController.get(editor)?.pasteAs(kind ? new hierarchicalKind_1.HierarchicalKind(kind) : undefined);
        }
    });
    (0, editorExtensions_1.registerEditorAction)(class extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: 'editor.action.pasteAsText',
                label: nls.localize(825, "Paste as Text"),
                alias: 'Paste as Text',
                precondition: editorContextKeys_1.EditorContextKeys.writable,
            });
        }
        run(_accessor, editor) {
            return copyPasteController_1.CopyPasteController.get(editor)?.pasteAs({ providerId: defaultProviders_1.DefaultTextPasteOrDropEditProvider.id });
        }
    });
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[858/*vs/editor/contrib/dropOrPasteInto/browser/dropIntoEditorContribution*/], __M([1/*require*/,0/*exports*/,15/*vs/editor/browser/editorExtensions*/,274/*vs/editor/common/config/editorConfigurationSchema*/,130/*vs/editor/common/editorFeatures*/,293/*vs/editor/contrib/dropOrPasteInto/browser/defaultProviders*/,3/*vs/nls*/,109/*vs/platform/configuration/common/configurationRegistry*/,38/*vs/platform/registry/common/platform*/,832/*vs/editor/contrib/dropOrPasteInto/browser/dropIntoEditorController*/]), function (require, exports, editorExtensions_1, editorConfigurationSchema_1, editorFeatures_1, defaultProviders_1, nls, configurationRegistry_1, platform_1, dropIntoEditorController_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    (0, editorExtensions_1.registerEditorContribution)(dropIntoEditorController_1.DropIntoEditorController.ID, dropIntoEditorController_1.DropIntoEditorController, 2 /* EditorContributionInstantiation.BeforeFirstInteraction */);
    (0, editorFeatures_1.registerEditorFeature)(defaultProviders_1.DefaultDropProvidersFeature);
    (0, editorExtensions_1.registerEditorCommand)(new class extends editorExtensions_1.EditorCommand {
        constructor() {
            super({
                id: dropIntoEditorController_1.changeDropTypeCommandId,
                precondition: dropIntoEditorController_1.dropWidgetVisibleCtx,
                kbOpts: {
                    weight: 100 /* KeybindingWeight.EditorContrib */,
                    primary: 2048 /* KeyMod.CtrlCmd */ | 89 /* KeyCode.Period */,
                }
            });
        }
        runEditorCommand(_accessor, editor, _args) {
            dropIntoEditorController_1.DropIntoEditorController.get(editor)?.changeDropType();
        }
    });
    (0, editorExtensions_1.registerEditorCommand)(new class extends editorExtensions_1.EditorCommand {
        constructor() {
            super({
                id: 'editor.hideDropWidget',
                precondition: dropIntoEditorController_1.dropWidgetVisibleCtx,
                kbOpts: {
                    weight: 100 /* KeybindingWeight.EditorContrib */,
                    primary: 9 /* KeyCode.Escape */,
                }
            });
        }
        runEditorCommand(_accessor, editor, _args) {
            dropIntoEditorController_1.DropIntoEditorController.get(editor)?.clearWidgets();
        }
    });
    platform_1.Registry.as(configurationRegistry_1.Extensions.Configuration).registerConfiguration({
        ...editorConfigurationSchema_1.editorConfigurationBaseNode,
        properties: {
            [dropIntoEditorController_1.defaultProviderConfig]: {
                type: 'object',
                scope: 5 /* ConfigurationScope.LANGUAGE_OVERRIDABLE */,
                description: nls.localize(841, "Configures the default drop provider to use for content of a given mime type."),
                default: {},
                additionalProperties: {
                    type: 'string',
                },
            },
        }
    });
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[859/*vs/editor/contrib/snippet/browser/snippetVariables*/], __M([1/*require*/,0/*exports*/,629/*vs/base/common/labels*/,99/*vs/base/common/path*/,48/*vs/base/common/resources*/,11/*vs/base/common/strings*/,193/*vs/base/common/uuid*/,36/*vs/editor/common/languages/languageConfigurationRegistry*/,135/*vs/editor/contrib/snippet/browser/snippetParser*/,3/*vs/nls*/,186/*vs/platform/workspace/common/workspace*/]), function (require, exports, labels_1, path, resources_1, strings_1, uuid_1, languageConfigurationRegistry_1, snippetParser_1, nls, workspace_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.RandomBasedVariableResolver = exports.WorkspaceBasedVariableResolver = exports.TimeBasedVariableResolver = exports.CommentBasedVariableResolver = exports.ClipboardBasedVariableResolver = exports.ModelBasedVariableResolver = exports.SelectionBasedVariableResolver = exports.CompositeSnippetVariableResolver = exports.KnownSnippetVariableNames = void 0;
    exports.KnownSnippetVariableNames = Object.freeze({
        'CURRENT_YEAR': true,
        'CURRENT_YEAR_SHORT': true,
        'CURRENT_MONTH': true,
        'CURRENT_DATE': true,
        'CURRENT_HOUR': true,
        'CURRENT_MINUTE': true,
        'CURRENT_SECOND': true,
        'CURRENT_DAY_NAME': true,
        'CURRENT_DAY_NAME_SHORT': true,
        'CURRENT_MONTH_NAME': true,
        'CURRENT_MONTH_NAME_SHORT': true,
        'CURRENT_SECONDS_UNIX': true,
        'CURRENT_TIMEZONE_OFFSET': true,
        'SELECTION': true,
        'CLIPBOARD': true,
        'TM_SELECTED_TEXT': true,
        'TM_CURRENT_LINE': true,
        'TM_CURRENT_WORD': true,
        'TM_LINE_INDEX': true,
        'TM_LINE_NUMBER': true,
        'TM_FILENAME': true,
        'TM_FILENAME_BASE': true,
        'TM_DIRECTORY': true,
        'TM_FILEPATH': true,
        'CURSOR_INDEX': true, // 0-offset
        'CURSOR_NUMBER': true, // 1-offset
        'RELATIVE_FILEPATH': true,
        'BLOCK_COMMENT_START': true,
        'BLOCK_COMMENT_END': true,
        'LINE_COMMENT': true,
        'WORKSPACE_NAME': true,
        'WORKSPACE_FOLDER': true,
        'RANDOM': true,
        'RANDOM_HEX': true,
        'UUID': true
    });
    class CompositeSnippetVariableResolver {
        constructor(_delegates) {
            this._delegates = _delegates;
            //
        }
        resolve(variable) {
            for (const delegate of this._delegates) {
                const value = delegate.resolve(variable);
                if (value !== undefined) {
                    return value;
                }
            }
            return undefined;
        }
    }
    exports.CompositeSnippetVariableResolver = CompositeSnippetVariableResolver;
    class SelectionBasedVariableResolver {
        constructor(_model, _selection, _selectionIdx, _overtypingCapturer) {
            this._model = _model;
            this._selection = _selection;
            this._selectionIdx = _selectionIdx;
            this._overtypingCapturer = _overtypingCapturer;
            //
        }
        resolve(variable) {
            const { name } = variable;
            if (name === 'SELECTION' || name === 'TM_SELECTED_TEXT') {
                let value = this._model.getValueInRange(this._selection) || undefined;
                let isMultiline = this._selection.startLineNumber !== this._selection.endLineNumber;
                // If there was no selected text, try to get last overtyped text
                if (!value && this._overtypingCapturer) {
                    const info = this._overtypingCapturer.getLastOvertypedInfo(this._selectionIdx);
                    if (info) {
                        value = info.value;
                        isMultiline = info.multiline;
                    }
                }
                if (value && isMultiline && variable.snippet) {
                    // Selection is a multiline string which we indentation we now
                    // need to adjust. We compare the indentation of this variable
                    // with the indentation at the editor position and add potential
                    // extra indentation to the value
                    const line = this._model.getLineContent(this._selection.startLineNumber);
                    const lineLeadingWhitespace = (0, strings_1.getLeadingWhitespace)(line, 0, this._selection.startColumn - 1);
                    let varLeadingWhitespace = lineLeadingWhitespace;
                    variable.snippet.walk(marker => {
                        if (marker === variable) {
                            return false;
                        }
                        if (marker instanceof snippetParser_1.Text) {
                            varLeadingWhitespace = (0, strings_1.getLeadingWhitespace)((0, strings_1.splitLines)(marker.value).pop());
                        }
                        return true;
                    });
                    const whitespaceCommonLength = (0, strings_1.commonPrefixLength)(varLeadingWhitespace, lineLeadingWhitespace);
                    value = value.replace(/(\r\n|\r|\n)(.*)/g, (m, newline, rest) => `${newline}${varLeadingWhitespace.substr(whitespaceCommonLength)}${rest}`);
                }
                return value;
            }
            else if (name === 'TM_CURRENT_LINE') {
                return this._model.getLineContent(this._selection.positionLineNumber);
            }
            else if (name === 'TM_CURRENT_WORD') {
                const info = this._model.getWordAtPosition({
                    lineNumber: this._selection.positionLineNumber,
                    column: this._selection.positionColumn
                });
                return info && info.word || undefined;
            }
            else if (name === 'TM_LINE_INDEX') {
                return String(this._selection.positionLineNumber - 1);
            }
            else if (name === 'TM_LINE_NUMBER') {
                return String(this._selection.positionLineNumber);
            }
            else if (name === 'CURSOR_INDEX') {
                return String(this._selectionIdx);
            }
            else if (name === 'CURSOR_NUMBER') {
                return String(this._selectionIdx + 1);
            }
            return undefined;
        }
    }
    exports.SelectionBasedVariableResolver = SelectionBasedVariableResolver;
    class ModelBasedVariableResolver {
        constructor(_labelService, _model) {
            this._labelService = _labelService;
            this._model = _model;
            //
        }
        resolve(variable) {
            const { name } = variable;
            if (name === 'TM_FILENAME') {
                return path.basename(this._model.uri.fsPath);
            }
            else if (name === 'TM_FILENAME_BASE') {
                const name = path.basename(this._model.uri.fsPath);
                const idx = name.lastIndexOf('.');
                if (idx <= 0) {
                    return name;
                }
                else {
                    return name.slice(0, idx);
                }
            }
            else if (name === 'TM_DIRECTORY') {
                if (path.dirname(this._model.uri.fsPath) === '.') {
                    return '';
                }
                return this._labelService.getUriLabel((0, resources_1.dirname)(this._model.uri));
            }
            else if (name === 'TM_FILEPATH') {
                return this._labelService.getUriLabel(this._model.uri);
            }
            else if (name === 'RELATIVE_FILEPATH') {
                return this._labelService.getUriLabel(this._model.uri, { relative: true, noPrefix: true });
            }
            return undefined;
        }
    }
    exports.ModelBasedVariableResolver = ModelBasedVariableResolver;
    class ClipboardBasedVariableResolver {
        constructor(_readClipboardText, _selectionIdx, _selectionCount, _spread) {
            this._readClipboardText = _readClipboardText;
            this._selectionIdx = _selectionIdx;
            this._selectionCount = _selectionCount;
            this._spread = _spread;
            //
        }
        resolve(variable) {
            if (variable.name !== 'CLIPBOARD') {
                return undefined;
            }
            const clipboardText = this._readClipboardText();
            if (!clipboardText) {
                return undefined;
            }
            // `spread` is assigning each cursor a line of the clipboard
            // text whenever there the line count equals the cursor count
            // and when enabled
            if (this._spread) {
                const lines = clipboardText.split(/\r\n|\n|\r/).filter(s => !(0, strings_1.isFalsyOrWhitespace)(s));
                if (lines.length === this._selectionCount) {
                    return lines[this._selectionIdx];
                }
            }
            return clipboardText;
        }
    }
    exports.ClipboardBasedVariableResolver = ClipboardBasedVariableResolver;
    let CommentBasedVariableResolver = class CommentBasedVariableResolver {
        constructor(_model, _selection, _languageConfigurationService) {
            this._model = _model;
            this._selection = _selection;
            this._languageConfigurationService = _languageConfigurationService;
            //
        }
        resolve(variable) {
            const { name } = variable;
            const langId = this._model.getLanguageIdAtPosition(this._selection.selectionStartLineNumber, this._selection.selectionStartColumn);
            const config = this._languageConfigurationService.getLanguageConfiguration(langId).comments;
            if (!config) {
                return undefined;
            }
            if (name === 'LINE_COMMENT') {
                return config.lineCommentToken || undefined;
            }
            else if (name === 'BLOCK_COMMENT_START') {
                return config.blockCommentStartToken || undefined;
            }
            else if (name === 'BLOCK_COMMENT_END') {
                return config.blockCommentEndToken || undefined;
            }
            return undefined;
        }
    };
    exports.CommentBasedVariableResolver = CommentBasedVariableResolver;
    exports.CommentBasedVariableResolver = CommentBasedVariableResolver = __decorate([
        __param(2, languageConfigurationRegistry_1.ILanguageConfigurationService)
    ], CommentBasedVariableResolver);
    class TimeBasedVariableResolver {
        constructor() {
            this._date = new Date();
        }
        static { this.dayNames = [nls.localize(1261, "Sunday"), nls.localize(1262, "Monday"), nls.localize(1263, "Tuesday"), nls.localize(1264, "Wednesday"), nls.localize(1265, "Thursday"), nls.localize(1266, "Friday"), nls.localize(1267, "Saturday")]; }
        static { this.dayNamesShort = [nls.localize(1268, "Sun"), nls.localize(1269, "Mon"), nls.localize(1270, "Tue"), nls.localize(1271, "Wed"), nls.localize(1272, "Thu"), nls.localize(1273, "Fri"), nls.localize(1274, "Sat")]; }
        static { this.monthNames = [nls.localize(1275, "January"), nls.localize(1276, "February"), nls.localize(1277, "March"), nls.localize(1278, "April"), nls.localize(1279, "May"), nls.localize(1280, "June"), nls.localize(1281, "July"), nls.localize(1282, "August"), nls.localize(1283, "September"), nls.localize(1284, "October"), nls.localize(1285, "November"), nls.localize(1286, "December")]; }
        static { this.monthNamesShort = [nls.localize(1287, "Jan"), nls.localize(1288, "Feb"), nls.localize(1289, "Mar"), nls.localize(1290, "Apr"), nls.localize(1291, "May"), nls.localize(1292, "Jun"), nls.localize(1293, "Jul"), nls.localize(1294, "Aug"), nls.localize(1295, "Sep"), nls.localize(1296, "Oct"), nls.localize(1297, "Nov"), nls.localize(1298, "Dec")]; }
        resolve(variable) {
            const { name } = variable;
            if (name === 'CURRENT_YEAR') {
                return String(this._date.getFullYear());
            }
            else if (name === 'CURRENT_YEAR_SHORT') {
                return String(this._date.getFullYear()).slice(-2);
            }
            else if (name === 'CURRENT_MONTH') {
                return String(this._date.getMonth().valueOf() + 1).padStart(2, '0');
            }
            else if (name === 'CURRENT_DATE') {
                return String(this._date.getDate().valueOf()).padStart(2, '0');
            }
            else if (name === 'CURRENT_HOUR') {
                return String(this._date.getHours().valueOf()).padStart(2, '0');
            }
            else if (name === 'CURRENT_MINUTE') {
                return String(this._date.getMinutes().valueOf()).padStart(2, '0');
            }
            else if (name === 'CURRENT_SECOND') {
                return String(this._date.getSeconds().valueOf()).padStart(2, '0');
            }
            else if (name === 'CURRENT_DAY_NAME') {
                return TimeBasedVariableResolver.dayNames[this._date.getDay()];
            }
            else if (name === 'CURRENT_DAY_NAME_SHORT') {
                return TimeBasedVariableResolver.dayNamesShort[this._date.getDay()];
            }
            else if (name === 'CURRENT_MONTH_NAME') {
                return TimeBasedVariableResolver.monthNames[this._date.getMonth()];
            }
            else if (name === 'CURRENT_MONTH_NAME_SHORT') {
                return TimeBasedVariableResolver.monthNamesShort[this._date.getMonth()];
            }
            else if (name === 'CURRENT_SECONDS_UNIX') {
                return String(Math.floor(this._date.getTime() / 1000));
            }
            else if (name === 'CURRENT_TIMEZONE_OFFSET') {
                const rawTimeOffset = this._date.getTimezoneOffset();
                const sign = rawTimeOffset > 0 ? '-' : '+';
                const hours = Math.trunc(Math.abs(rawTimeOffset / 60));
                const hoursString = (hours < 10 ? '0' + hours : hours);
                const minutes = Math.abs(rawTimeOffset) - hours * 60;
                const minutesString = (minutes < 10 ? '0' + minutes : minutes);
                return sign + hoursString + ':' + minutesString;
            }
            return undefined;
        }
    }
    exports.TimeBasedVariableResolver = TimeBasedVariableResolver;
    class WorkspaceBasedVariableResolver {
        constructor(_workspaceService) {
            this._workspaceService = _workspaceService;
            //
        }
        resolve(variable) {
            if (!this._workspaceService) {
                return undefined;
            }
            const workspaceIdentifier = (0, workspace_1.toWorkspaceIdentifier)(this._workspaceService.getWorkspace());
            if ((0, workspace_1.isEmptyWorkspaceIdentifier)(workspaceIdentifier)) {
                return undefined;
            }
            if (variable.name === 'WORKSPACE_NAME') {
                return this._resolveWorkspaceName(workspaceIdentifier);
            }
            else if (variable.name === 'WORKSPACE_FOLDER') {
                return this._resoveWorkspacePath(workspaceIdentifier);
            }
            return undefined;
        }
        _resolveWorkspaceName(workspaceIdentifier) {
            if ((0, workspace_1.isSingleFolderWorkspaceIdentifier)(workspaceIdentifier)) {
                return path.basename(workspaceIdentifier.uri.path);
            }
            let filename = path.basename(workspaceIdentifier.configPath.path);
            if (filename.endsWith(workspace_1.WORKSPACE_EXTENSION)) {
                filename = filename.substr(0, filename.length - workspace_1.WORKSPACE_EXTENSION.length - 1);
            }
            return filename;
        }
        _resoveWorkspacePath(workspaceIdentifier) {
            if ((0, workspace_1.isSingleFolderWorkspaceIdentifier)(workspaceIdentifier)) {
                return (0, labels_1.normalizeDriveLetter)(workspaceIdentifier.uri.fsPath);
            }
            const filename = path.basename(workspaceIdentifier.configPath.path);
            let folderpath = workspaceIdentifier.configPath.fsPath;
            if (folderpath.endsWith(filename)) {
                folderpath = folderpath.substr(0, folderpath.length - filename.length - 1);
            }
            return (folderpath ? (0, labels_1.normalizeDriveLetter)(folderpath) : '/');
        }
    }
    exports.WorkspaceBasedVariableResolver = WorkspaceBasedVariableResolver;
    class RandomBasedVariableResolver {
        resolve(variable) {
            const { name } = variable;
            if (name === 'RANDOM') {
                return Math.random().toString().slice(-6);
            }
            else if (name === 'RANDOM_HEX') {
                return Math.random().toString(16).slice(-6);
            }
            else if (name === 'UUID') {
                return (0, uuid_1.generateUuid)();
            }
            return undefined;
        }
    }
    exports.RandomBasedVariableResolver = RandomBasedVariableResolver;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[436/*vs/editor/contrib/snippet/browser/snippetSession*/], __M([1/*require*/,0/*exports*/,13/*vs/base/common/arrays*/,2/*vs/base/common/lifecycle*/,11/*vs/base/common/strings*/,75/*vs/editor/common/core/editOperation*/,4/*vs/editor/common/core/range*/,23/*vs/editor/common/core/selection*/,36/*vs/editor/common/languages/languageConfigurationRegistry*/,35/*vs/editor/common/model/textModel*/,181/*vs/platform/label/common/label*/,186/*vs/platform/workspace/common/workspace*/,135/*vs/editor/contrib/snippet/browser/snippetParser*/,859/*vs/editor/contrib/snippet/browser/snippetVariables*/,530/*vs/css!vs/editor/contrib/snippet/browser/snippetSession*/]), function (require, exports, arrays_1, lifecycle_1, strings_1, editOperation_1, range_1, selection_1, languageConfigurationRegistry_1, textModel_1, label_1, workspace_1, snippetParser_1, snippetVariables_1) {
    "use strict";
    var SnippetSession_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SnippetSession = exports.OneSnippet = void 0;
    class OneSnippet {
        static { this._decor = {
            active: textModel_1.ModelDecorationOptions.register({ description: 'snippet-placeholder-1', stickiness: 0 /* TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges */, className: 'snippet-placeholder' }),
            inactive: textModel_1.ModelDecorationOptions.register({ description: 'snippet-placeholder-2', stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */, className: 'snippet-placeholder' }),
            activeFinal: textModel_1.ModelDecorationOptions.register({ description: 'snippet-placeholder-3', stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */, className: 'finish-snippet-placeholder' }),
            inactiveFinal: textModel_1.ModelDecorationOptions.register({ description: 'snippet-placeholder-4', stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */, className: 'finish-snippet-placeholder' }),
        }; }
        constructor(_editor, _snippet, _snippetLineLeadingWhitespace) {
            this._editor = _editor;
            this._snippet = _snippet;
            this._snippetLineLeadingWhitespace = _snippetLineLeadingWhitespace;
            this._offset = -1;
            this._nestingLevel = 1;
            this._placeholderGroups = (0, arrays_1.groupBy)(_snippet.placeholders, snippetParser_1.Placeholder.compareByIndex);
            this._placeholderGroupsIdx = -1;
        }
        initialize(textChange) {
            this._offset = textChange.newPosition;
        }
        dispose() {
            if (this._placeholderDecorations) {
                this._editor.removeDecorations([...this._placeholderDecorations.values()]);
            }
            this._placeholderGroups.length = 0;
        }
        _initDecorations() {
            if (this._offset === -1) {
                throw new Error(`Snippet not initialized!`);
            }
            if (this._placeholderDecorations) {
                // already initialized
                return;
            }
            this._placeholderDecorations = new Map();
            const model = this._editor.getModel();
            this._editor.changeDecorations(accessor => {
                // create a decoration for each placeholder
                for (const placeholder of this._snippet.placeholders) {
                    const placeholderOffset = this._snippet.offset(placeholder);
                    const placeholderLen = this._snippet.fullLen(placeholder);
                    const range = range_1.Range.fromPositions(model.getPositionAt(this._offset + placeholderOffset), model.getPositionAt(this._offset + placeholderOffset + placeholderLen));
                    const options = placeholder.isFinalTabstop ? OneSnippet._decor.inactiveFinal : OneSnippet._decor.inactive;
                    const handle = accessor.addDecoration(range, options);
                    this._placeholderDecorations.set(placeholder, handle);
                }
            });
        }
        move(fwd) {
            if (!this._editor.hasModel()) {
                return [];
            }
            this._initDecorations();
            // Transform placeholder text if necessary
            if (this._placeholderGroupsIdx >= 0) {
                const operations = [];
                for (const placeholder of this._placeholderGroups[this._placeholderGroupsIdx]) {
                    // Check if the placeholder has a transformation
                    if (placeholder.transform) {
                        const id = this._placeholderDecorations.get(placeholder);
                        const range = this._editor.getModel().getDecorationRange(id);
                        const currentValue = this._editor.getModel().getValueInRange(range);
                        const transformedValueLines = placeholder.transform.resolve(currentValue).split(/\r\n|\r|\n/);
                        // fix indentation for transformed lines
                        for (let i = 1; i < transformedValueLines.length; i++) {
                            transformedValueLines[i] = this._editor.getModel().normalizeIndentation(this._snippetLineLeadingWhitespace + transformedValueLines[i]);
                        }
                        operations.push(editOperation_1.EditOperation.replace(range, transformedValueLines.join(this._editor.getModel().getEOL())));
                    }
                }
                if (operations.length > 0) {
                    this._editor.executeEdits('snippet.placeholderTransform', operations);
                }
            }
            let couldSkipThisPlaceholder = false;
            if (fwd === true && this._placeholderGroupsIdx < this._placeholderGroups.length - 1) {
                this._placeholderGroupsIdx += 1;
                couldSkipThisPlaceholder = true;
            }
            else if (fwd === false && this._placeholderGroupsIdx > 0) {
                this._placeholderGroupsIdx -= 1;
                couldSkipThisPlaceholder = true;
            }
            else {
                // the selection of the current placeholder might
                // not acurate any more -> simply restore it
            }
            const newSelections = this._editor.getModel().changeDecorations(accessor => {
                const activePlaceholders = new Set();
                // change stickiness to always grow when typing at its edges
                // because these decorations represent the currently active
                // tabstop.
                // Special case #1: reaching the final tabstop
                // Special case #2: placeholders enclosing active placeholders
                const selections = [];
                for (const placeholder of this._placeholderGroups[this._placeholderGroupsIdx]) {
                    const id = this._placeholderDecorations.get(placeholder);
                    const range = this._editor.getModel().getDecorationRange(id);
                    selections.push(new selection_1.Selection(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn));
                    // consider to skip this placeholder index when the decoration
                    // range is empty but when the placeholder wasn't. that's a strong
                    // hint that the placeholder has been deleted. (all placeholder must match this)
                    couldSkipThisPlaceholder = couldSkipThisPlaceholder && this._hasPlaceholderBeenCollapsed(placeholder);
                    accessor.changeDecorationOptions(id, placeholder.isFinalTabstop ? OneSnippet._decor.activeFinal : OneSnippet._decor.active);
                    activePlaceholders.add(placeholder);
                    for (const enclosingPlaceholder of this._snippet.enclosingPlaceholders(placeholder)) {
                        const id = this._placeholderDecorations.get(enclosingPlaceholder);
                        accessor.changeDecorationOptions(id, enclosingPlaceholder.isFinalTabstop ? OneSnippet._decor.activeFinal : OneSnippet._decor.active);
                        activePlaceholders.add(enclosingPlaceholder);
                    }
                }
                // change stickness to never grow when typing at its edges
                // so that in-active tabstops never grow
                for (const [placeholder, id] of this._placeholderDecorations) {
                    if (!activePlaceholders.has(placeholder)) {
                        accessor.changeDecorationOptions(id, placeholder.isFinalTabstop ? OneSnippet._decor.inactiveFinal : OneSnippet._decor.inactive);
                    }
                }
                return selections;
            });
            return !couldSkipThisPlaceholder ? newSelections ?? [] : this.move(fwd);
        }
        _hasPlaceholderBeenCollapsed(placeholder) {
            // A placeholder is empty when it wasn't empty when authored but
            // when its tracking decoration is empty. This also applies to all
            // potential parent placeholders
            let marker = placeholder;
            while (marker) {
                if (marker instanceof snippetParser_1.Placeholder) {
                    const id = this._placeholderDecorations.get(marker);
                    const range = this._editor.getModel().getDecorationRange(id);
                    if (range.isEmpty() && marker.toString().length > 0) {
                        return true;
                    }
                }
                marker = marker.parent;
            }
            return false;
        }
        get isAtFirstPlaceholder() {
            return this._placeholderGroupsIdx <= 0 || this._placeholderGroups.length === 0;
        }
        get isAtLastPlaceholder() {
            return this._placeholderGroupsIdx === this._placeholderGroups.length - 1;
        }
        get hasPlaceholder() {
            return this._snippet.placeholders.length > 0;
        }
        /**
         * A snippet is trivial when it has no placeholder or only a final placeholder at
         * its very end
         */
        get isTrivialSnippet() {
            if (this._snippet.placeholders.length === 0) {
                return true;
            }
            if (this._snippet.placeholders.length === 1) {
                const [placeholder] = this._snippet.placeholders;
                if (placeholder.isFinalTabstop) {
                    if (this._snippet.rightMostDescendant === placeholder) {
                        return true;
                    }
                }
            }
            return false;
        }
        computePossibleSelections() {
            const result = new Map();
            for (const placeholdersWithEqualIndex of this._placeholderGroups) {
                let ranges;
                for (const placeholder of placeholdersWithEqualIndex) {
                    if (placeholder.isFinalTabstop) {
                        // ignore those
                        break;
                    }
                    if (!ranges) {
                        ranges = [];
                        result.set(placeholder.index, ranges);
                    }
                    const id = this._placeholderDecorations.get(placeholder);
                    const range = this._editor.getModel().getDecorationRange(id);
                    if (!range) {
                        // one of the placeholder lost its decoration and
                        // therefore we bail out and pretend the placeholder
                        // (with its mirrors) doesn't exist anymore.
                        result.delete(placeholder.index);
                        break;
                    }
                    ranges.push(range);
                }
            }
            return result;
        }
        get activeChoice() {
            if (!this._placeholderDecorations) {
                return undefined;
            }
            const placeholder = this._placeholderGroups[this._placeholderGroupsIdx][0];
            if (!placeholder?.choice) {
                return undefined;
            }
            const id = this._placeholderDecorations.get(placeholder);
            if (!id) {
                return undefined;
            }
            const range = this._editor.getModel().getDecorationRange(id);
            if (!range) {
                return undefined;
            }
            return { range, choice: placeholder.choice };
        }
        get hasChoice() {
            let result = false;
            this._snippet.walk(marker => {
                result = marker instanceof snippetParser_1.Choice;
                return !result;
            });
            return result;
        }
        merge(others) {
            const model = this._editor.getModel();
            this._nestingLevel *= 10;
            this._editor.changeDecorations(accessor => {
                // For each active placeholder take one snippet and merge it
                // in that the placeholder (can be many for `$1foo$1foo`). Because
                // everything is sorted by editor selection we can simply remove
                // elements from the beginning of the array
                for (const placeholder of this._placeholderGroups[this._placeholderGroupsIdx]) {
                    const nested = others.shift();
                    console.assert(nested._offset !== -1);
                    console.assert(!nested._placeholderDecorations);
                    // Massage placeholder-indicies of the nested snippet to be
                    // sorted right after the insertion point. This ensures we move
                    // through the placeholders in the correct order
                    const indexLastPlaceholder = nested._snippet.placeholderInfo.last.index;
                    for (const nestedPlaceholder of nested._snippet.placeholderInfo.all) {
                        if (nestedPlaceholder.isFinalTabstop) {
                            nestedPlaceholder.index = placeholder.index + ((indexLastPlaceholder + 1) / this._nestingLevel);
                        }
                        else {
                            nestedPlaceholder.index = placeholder.index + (nestedPlaceholder.index / this._nestingLevel);
                        }
                    }
                    this._snippet.replace(placeholder, nested._snippet.children);
                    // Remove the placeholder at which position are inserting
                    // the snippet and also remove its decoration.
                    const id = this._placeholderDecorations.get(placeholder);
                    accessor.removeDecoration(id);
                    this._placeholderDecorations.delete(placeholder);
                    // For each *new* placeholder we create decoration to monitor
                    // how and if it grows/shrinks.
                    for (const placeholder of nested._snippet.placeholders) {
                        const placeholderOffset = nested._snippet.offset(placeholder);
                        const placeholderLen = nested._snippet.fullLen(placeholder);
                        const range = range_1.Range.fromPositions(model.getPositionAt(nested._offset + placeholderOffset), model.getPositionAt(nested._offset + placeholderOffset + placeholderLen));
                        const handle = accessor.addDecoration(range, OneSnippet._decor.inactive);
                        this._placeholderDecorations.set(placeholder, handle);
                    }
                }
                // Last, re-create the placeholder groups by sorting placeholders by their index.
                this._placeholderGroups = (0, arrays_1.groupBy)(this._snippet.placeholders, snippetParser_1.Placeholder.compareByIndex);
            });
        }
    }
    exports.OneSnippet = OneSnippet;
    const _defaultOptions = {
        overwriteBefore: 0,
        overwriteAfter: 0,
        adjustWhitespace: true,
        clipboardText: undefined,
        overtypingCapturer: undefined
    };
    let SnippetSession = SnippetSession_1 = class SnippetSession {
        static adjustWhitespace(model, position, adjustIndentation, snippet, filter) {
            const line = model.getLineContent(position.lineNumber);
            const lineLeadingWhitespace = (0, strings_1.getLeadingWhitespace)(line, 0, position.column - 1);
            // the snippet as inserted
            let snippetTextString;
            snippet.walk(marker => {
                // all text elements that are not inside choice
                if (!(marker instanceof snippetParser_1.Text) || marker.parent instanceof snippetParser_1.Choice) {
                    return true;
                }
                // check with filter (iff provided)
                if (filter && !filter.has(marker)) {
                    return true;
                }
                const lines = marker.value.split(/\r\n|\r|\n/);
                if (adjustIndentation) {
                    // adjust indentation of snippet test
                    // -the snippet-start doesn't get extra-indented (lineLeadingWhitespace), only normalized
                    // -all N+1 lines get extra-indented and normalized
                    // -the text start get extra-indented and normalized when following a linebreak
                    const offset = snippet.offset(marker);
                    if (offset === 0) {
                        // snippet start
                        lines[0] = model.normalizeIndentation(lines[0]);
                    }
                    else {
                        // check if text start is after a linebreak
                        snippetTextString = snippetTextString ?? snippet.toString();
                        const prevChar = snippetTextString.charCodeAt(offset - 1);
                        if (prevChar === 10 /* CharCode.LineFeed */ || prevChar === 13 /* CharCode.CarriageReturn */) {
                            lines[0] = model.normalizeIndentation(lineLeadingWhitespace + lines[0]);
                        }
                    }
                    for (let i = 1; i < lines.length; i++) {
                        lines[i] = model.normalizeIndentation(lineLeadingWhitespace + lines[i]);
                    }
                }
                const newValue = lines.join(model.getEOL());
                if (newValue !== marker.value) {
                    marker.parent.replace(marker, [new snippetParser_1.Text(newValue)]);
                    snippetTextString = undefined;
                }
                return true;
            });
            return lineLeadingWhitespace;
        }
        static adjustSelection(model, selection, overwriteBefore, overwriteAfter) {
            if (overwriteBefore !== 0 || overwriteAfter !== 0) {
                // overwrite[Before|After] is compute using the position, not the whole
                // selection. therefore we adjust the selection around that position
                const { positionLineNumber, positionColumn } = selection;
                const positionColumnBefore = positionColumn - overwriteBefore;
                const positionColumnAfter = positionColumn + overwriteAfter;
                const range = model.validateRange({
                    startLineNumber: positionLineNumber,
                    startColumn: positionColumnBefore,
                    endLineNumber: positionLineNumber,
                    endColumn: positionColumnAfter
                });
                selection = selection_1.Selection.createWithDirection(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn, selection.getDirection());
            }
            return selection;
        }
        static createEditsAndSnippetsFromSelections(editor, template, overwriteBefore, overwriteAfter, enforceFinalTabstop, adjustWhitespace, clipboardText, overtypingCapturer, languageConfigurationService) {
            const edits = [];
            const snippets = [];
            if (!editor.hasModel()) {
                return { edits, snippets };
            }
            const model = editor.getModel();
            const workspaceService = editor.invokeWithinContext(accessor => accessor.get(workspace_1.IWorkspaceContextService));
            const modelBasedVariableResolver = editor.invokeWithinContext(accessor => new snippetVariables_1.ModelBasedVariableResolver(accessor.get(label_1.ILabelService), model));
            const readClipboardText = () => clipboardText;
            // know what text the overwrite[Before|After] extensions
            // of the primary curser have selected because only when
            // secondary selections extend to the same text we can grow them
            const firstBeforeText = model.getValueInRange(SnippetSession_1.adjustSelection(model, editor.getSelection(), overwriteBefore, 0));
            const firstAfterText = model.getValueInRange(SnippetSession_1.adjustSelection(model, editor.getSelection(), 0, overwriteAfter));
            // remember the first non-whitespace column to decide if
            // `keepWhitespace` should be overruled for secondary selections
            const firstLineFirstNonWhitespace = model.getLineFirstNonWhitespaceColumn(editor.getSelection().positionLineNumber);
            // sort selections by their start position but remeber
            // the original index. that allows you to create correct
            // offset-based selection logic without changing the
            // primary selection
            const indexedSelections = editor.getSelections()
                .map((selection, idx) => ({ selection, idx }))
                .sort((a, b) => range_1.Range.compareRangesUsingStarts(a.selection, b.selection));
            for (const { selection, idx } of indexedSelections) {
                // extend selection with the `overwriteBefore` and `overwriteAfter` and then
                // compare if this matches the extensions of the primary selection
                let extensionBefore = SnippetSession_1.adjustSelection(model, selection, overwriteBefore, 0);
                let extensionAfter = SnippetSession_1.adjustSelection(model, selection, 0, overwriteAfter);
                if (firstBeforeText !== model.getValueInRange(extensionBefore)) {
                    extensionBefore = selection;
                }
                if (firstAfterText !== model.getValueInRange(extensionAfter)) {
                    extensionAfter = selection;
                }
                // merge the before and after selection into one
                const snippetSelection = selection
                    .setStartPosition(extensionBefore.startLineNumber, extensionBefore.startColumn)
                    .setEndPosition(extensionAfter.endLineNumber, extensionAfter.endColumn);
                const snippet = new snippetParser_1.SnippetParser().parse(template, true, enforceFinalTabstop);
                // adjust the template string to match the indentation and
                // whitespace rules of this insert location (can be different for each cursor)
                // happens when being asked for (default) or when this is a secondary
                // cursor and the leading whitespace is different
                const start = snippetSelection.getStartPosition();
                const snippetLineLeadingWhitespace = SnippetSession_1.adjustWhitespace(model, start, adjustWhitespace || (idx > 0 && firstLineFirstNonWhitespace !== model.getLineFirstNonWhitespaceColumn(selection.positionLineNumber)), snippet);
                snippet.resolveVariables(new snippetVariables_1.CompositeSnippetVariableResolver([
                    modelBasedVariableResolver,
                    new snippetVariables_1.ClipboardBasedVariableResolver(readClipboardText, idx, indexedSelections.length, editor.getOption(79 /* EditorOption.multiCursorPaste */) === 'spread'),
                    new snippetVariables_1.SelectionBasedVariableResolver(model, selection, idx, overtypingCapturer),
                    new snippetVariables_1.CommentBasedVariableResolver(model, selection, languageConfigurationService),
                    new snippetVariables_1.TimeBasedVariableResolver,
                    new snippetVariables_1.WorkspaceBasedVariableResolver(workspaceService),
                    new snippetVariables_1.RandomBasedVariableResolver,
                ]));
                // store snippets with the index of their originating selection.
                // that ensures the primiary cursor stays primary despite not being
                // the one with lowest start position
                edits[idx] = editOperation_1.EditOperation.replace(snippetSelection, snippet.toString());
                edits[idx].identifier = { major: idx, minor: 0 }; // mark the edit so only our undo edits will be used to generate end cursors
                edits[idx]._isTracked = true;
                snippets[idx] = new OneSnippet(editor, snippet, snippetLineLeadingWhitespace);
            }
            return { edits, snippets };
        }
        static createEditsAndSnippetsFromEdits(editor, snippetEdits, enforceFinalTabstop, adjustWhitespace, clipboardText, overtypingCapturer, languageConfigurationService) {
            if (!editor.hasModel() || snippetEdits.length === 0) {
                return { edits: [], snippets: [] };
            }
            const edits = [];
            const model = editor.getModel();
            const parser = new snippetParser_1.SnippetParser();
            const snippet = new snippetParser_1.TextmateSnippet();
            // snippet variables resolver
            const resolver = new snippetVariables_1.CompositeSnippetVariableResolver([
                editor.invokeWithinContext(accessor => new snippetVariables_1.ModelBasedVariableResolver(accessor.get(label_1.ILabelService), model)),
                new snippetVariables_1.ClipboardBasedVariableResolver(() => clipboardText, 0, editor.getSelections().length, editor.getOption(79 /* EditorOption.multiCursorPaste */) === 'spread'),
                new snippetVariables_1.SelectionBasedVariableResolver(model, editor.getSelection(), 0, overtypingCapturer),
                new snippetVariables_1.CommentBasedVariableResolver(model, editor.getSelection(), languageConfigurationService),
                new snippetVariables_1.TimeBasedVariableResolver,
                new snippetVariables_1.WorkspaceBasedVariableResolver(editor.invokeWithinContext(accessor => accessor.get(workspace_1.IWorkspaceContextService))),
                new snippetVariables_1.RandomBasedVariableResolver,
            ]);
            //
            snippetEdits = snippetEdits.sort((a, b) => range_1.Range.compareRangesUsingStarts(a.range, b.range));
            let offset = 0;
            for (let i = 0; i < snippetEdits.length; i++) {
                const { range, template } = snippetEdits[i];
                // gaps between snippet edits are appended as text nodes. this
                // ensures placeholder-offsets are later correct
                if (i > 0) {
                    const lastRange = snippetEdits[i - 1].range;
                    const textRange = range_1.Range.fromPositions(lastRange.getEndPosition(), range.getStartPosition());
                    const textNode = new snippetParser_1.Text(model.getValueInRange(textRange));
                    snippet.appendChild(textNode);
                    offset += textNode.value.length;
                }
                const newNodes = parser.parseFragment(template, snippet);
                SnippetSession_1.adjustWhitespace(model, range.getStartPosition(), true, snippet, new Set(newNodes));
                snippet.resolveVariables(resolver);
                const snippetText = snippet.toString();
                const snippetFragmentText = snippetText.slice(offset);
                offset = snippetText.length;
                // make edit
                const edit = editOperation_1.EditOperation.replace(range, snippetFragmentText);
                edit.identifier = { major: i, minor: 0 }; // mark the edit so only our undo edits will be used to generate end cursors
                edit._isTracked = true;
                edits.push(edit);
            }
            //
            parser.ensureFinalTabstop(snippet, enforceFinalTabstop, true);
            return {
                edits,
                snippets: [new OneSnippet(editor, snippet, '')]
            };
        }
        constructor(_editor, _template, _options = _defaultOptions, _languageConfigurationService) {
            this._editor = _editor;
            this._template = _template;
            this._options = _options;
            this._languageConfigurationService = _languageConfigurationService;
            this._templateMerges = [];
            this._snippets = [];
        }
        dispose() {
            (0, lifecycle_1.dispose)(this._snippets);
        }
        _logInfo() {
            return `template="${this._template}", merged_templates="${this._templateMerges.join(' -> ')}"`;
        }
        insert() {
            if (!this._editor.hasModel()) {
                return;
            }
            // make insert edit and start with first selections
            const { edits, snippets } = typeof this._template === 'string'
                ? SnippetSession_1.createEditsAndSnippetsFromSelections(this._editor, this._template, this._options.overwriteBefore, this._options.overwriteAfter, false, this._options.adjustWhitespace, this._options.clipboardText, this._options.overtypingCapturer, this._languageConfigurationService)
                : SnippetSession_1.createEditsAndSnippetsFromEdits(this._editor, this._template, false, this._options.adjustWhitespace, this._options.clipboardText, this._options.overtypingCapturer, this._languageConfigurationService);
            this._snippets = snippets;
            this._editor.executeEdits('snippet', edits, _undoEdits => {
                // Sometimes, the text buffer will remove automatic whitespace when doing any edits,
                // so we need to look only at the undo edits relevant for us.
                // Our edits have an identifier set so that's how we can distinguish them
                const undoEdits = _undoEdits.filter(edit => !!edit.identifier);
                for (let idx = 0; idx < snippets.length; idx++) {
                    snippets[idx].initialize(undoEdits[idx].textChange);
                }
                if (this._snippets[0].hasPlaceholder) {
                    return this._move(true);
                }
                else {
                    return undoEdits
                        .map(edit => selection_1.Selection.fromPositions(edit.range.getEndPosition()));
                }
            });
            this._editor.revealRange(this._editor.getSelections()[0]);
        }
        merge(template, options = _defaultOptions) {
            if (!this._editor.hasModel()) {
                return;
            }
            this._templateMerges.push([this._snippets[0]._nestingLevel, this._snippets[0]._placeholderGroupsIdx, template]);
            const { edits, snippets } = SnippetSession_1.createEditsAndSnippetsFromSelections(this._editor, template, options.overwriteBefore, options.overwriteAfter, true, options.adjustWhitespace, options.clipboardText, options.overtypingCapturer, this._languageConfigurationService);
            this._editor.executeEdits('snippet', edits, _undoEdits => {
                // Sometimes, the text buffer will remove automatic whitespace when doing any edits,
                // so we need to look only at the undo edits relevant for us.
                // Our edits have an identifier set so that's how we can distinguish them
                const undoEdits = _undoEdits.filter(edit => !!edit.identifier);
                for (let idx = 0; idx < snippets.length; idx++) {
                    snippets[idx].initialize(undoEdits[idx].textChange);
                }
                // Trivial snippets have no placeholder or are just the final placeholder. That means they
                // are just text insertions and we don't need to merge the nested snippet into the existing
                // snippet
                const isTrivialSnippet = snippets[0].isTrivialSnippet;
                if (!isTrivialSnippet) {
                    for (const snippet of this._snippets) {
                        snippet.merge(snippets);
                    }
                    console.assert(snippets.length === 0);
                }
                if (this._snippets[0].hasPlaceholder && !isTrivialSnippet) {
                    return this._move(undefined);
                }
                else {
                    return undoEdits.map(edit => selection_1.Selection.fromPositions(edit.range.getEndPosition()));
                }
            });
        }
        next() {
            const newSelections = this._move(true);
            this._editor.setSelections(newSelections);
            this._editor.revealPositionInCenterIfOutsideViewport(newSelections[0].getPosition());
        }
        prev() {
            const newSelections = this._move(false);
            this._editor.setSelections(newSelections);
            this._editor.revealPositionInCenterIfOutsideViewport(newSelections[0].getPosition());
        }
        _move(fwd) {
            const selections = [];
            for (const snippet of this._snippets) {
                const oneSelection = snippet.move(fwd);
                selections.push(...oneSelection);
            }
            return selections;
        }
        get isAtFirstPlaceholder() {
            return this._snippets[0].isAtFirstPlaceholder;
        }
        get isAtLastPlaceholder() {
            return this._snippets[0].isAtLastPlaceholder;
        }
        get hasPlaceholder() {
            return this._snippets[0].hasPlaceholder;
        }
        get hasChoice() {
            return this._snippets[0].hasChoice;
        }
        get activeChoice() {
            return this._snippets[0].activeChoice;
        }
        isSelectionWithinPlaceholders() {
            if (!this.hasPlaceholder) {
                return false;
            }
            const selections = this._editor.getSelections();
            if (selections.length < this._snippets.length) {
                // this means we started snippet mode with N
                // selections and have M (N > M) selections.
                // So one snippet is without selection -> cancel
                return false;
            }
            const allPossibleSelections = new Map();
            for (const snippet of this._snippets) {
                const possibleSelections = snippet.computePossibleSelections();
                // for the first snippet find the placeholder (and its ranges)
                // that contain at least one selection. for all remaining snippets
                // the same placeholder (and their ranges) must be used.
                if (allPossibleSelections.size === 0) {
                    for (const [index, ranges] of possibleSelections) {
                        ranges.sort(range_1.Range.compareRangesUsingStarts);
                        for (const selection of selections) {
                            if (ranges[0].containsRange(selection)) {
                                allPossibleSelections.set(index, []);
                                break;
                            }
                        }
                    }
                }
                if (allPossibleSelections.size === 0) {
                    // return false if we couldn't associate a selection to
                    // this (the first) snippet
                    return false;
                }
                // add selections from 'this' snippet so that we know all
                // selections for this placeholder
                allPossibleSelections.forEach((array, index) => {
                    array.push(...possibleSelections.get(index));
                });
            }
            // sort selections (and later placeholder-ranges). then walk both
            // arrays and make sure the placeholder-ranges contain the corresponding
            // selection
            selections.sort(range_1.Range.compareRangesUsingStarts);
            for (const [index, ranges] of allPossibleSelections) {
                if (ranges.length !== selections.length) {
                    allPossibleSelections.delete(index);
                    continue;
                }
                ranges.sort(range_1.Range.compareRangesUsingStarts);
                for (let i = 0; i < ranges.length; i++) {
                    if (!ranges[i].containsRange(selections[i])) {
                        allPossibleSelections.delete(index);
                        continue;
                    }
                }
            }
            // from all possible selections we have deleted those
            // that don't match with the current selection. if we don't
            // have any left, we don't have a selection anymore
            return allPossibleSelections.size > 0;
        }
    };
    exports.SnippetSession = SnippetSession;
    exports.SnippetSession = SnippetSession = SnippetSession_1 = __decorate([
        __param(3, languageConfigurationRegistry_1.ILanguageConfigurationService)
    ], SnippetSession);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[221/*vs/editor/contrib/snippet/browser/snippetController2*/], __M([1/*require*/,0/*exports*/,2/*vs/base/common/lifecycle*/,19/*vs/base/common/types*/,15/*vs/editor/browser/editorExtensions*/,9/*vs/editor/common/core/position*/,20/*vs/editor/common/editorContextKeys*/,36/*vs/editor/common/languages/languageConfigurationRegistry*/,17/*vs/editor/common/services/languageFeatures*/,155/*vs/editor/contrib/suggest/browser/suggest*/,3/*vs/nls*/,12/*vs/platform/contextkey/common/contextkey*/,62/*vs/platform/log/common/log*/,436/*vs/editor/contrib/snippet/browser/snippetSession*/]), function (require, exports, lifecycle_1, types_1, editorExtensions_1, position_1, editorContextKeys_1, languageConfigurationRegistry_1, languageFeatures_1, suggest_1, nls_1, contextkey_1, log_1, snippetSession_1) {
    "use strict";
    var SnippetController2_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SnippetController2 = void 0;
    const _defaultOptions = {
        overwriteBefore: 0,
        overwriteAfter: 0,
        undoStopBefore: true,
        undoStopAfter: true,
        adjustWhitespace: true,
        clipboardText: undefined,
        overtypingCapturer: undefined
    };
    let SnippetController2 = class SnippetController2 {
        static { SnippetController2_1 = this; }
        static { this.ID = 'snippetController2'; }
        static get(editor) {
            return editor.getContribution(SnippetController2_1.ID);
        }
        static { this.InSnippetMode = new contextkey_1.RawContextKey('inSnippetMode', false, (0, nls_1.localize)(1257, "Whether the editor in current in snippet mode")); }
        static { this.HasNextTabstop = new contextkey_1.RawContextKey('hasNextTabstop', false, (0, nls_1.localize)(1258, "Whether there is a next tab stop when in snippet mode")); }
        static { this.HasPrevTabstop = new contextkey_1.RawContextKey('hasPrevTabstop', false, (0, nls_1.localize)(1259, "Whether there is a previous tab stop when in snippet mode")); }
        constructor(_editor, _logService, _languageFeaturesService, contextKeyService, _languageConfigurationService) {
            this._editor = _editor;
            this._logService = _logService;
            this._languageFeaturesService = _languageFeaturesService;
            this._languageConfigurationService = _languageConfigurationService;
            this._snippetListener = new lifecycle_1.DisposableStore();
            this._modelVersionId = -1;
            this._inSnippet = SnippetController2_1.InSnippetMode.bindTo(contextKeyService);
            this._hasNextTabstop = SnippetController2_1.HasNextTabstop.bindTo(contextKeyService);
            this._hasPrevTabstop = SnippetController2_1.HasPrevTabstop.bindTo(contextKeyService);
        }
        dispose() {
            this._inSnippet.reset();
            this._hasPrevTabstop.reset();
            this._hasNextTabstop.reset();
            this._session?.dispose();
            this._snippetListener.dispose();
        }
        insert(template, opts) {
            // this is here to find out more about the yet-not-understood
            // error that sometimes happens when we fail to inserted a nested
            // snippet
            try {
                this._doInsert(template, typeof opts === 'undefined' ? _defaultOptions : { ..._defaultOptions, ...opts });
            }
            catch (e) {
                this.cancel();
                this._logService.error(e);
                this._logService.error('snippet_error');
                this._logService.error('insert_template=', template);
                this._logService.error('existing_template=', this._session ? this._session._logInfo() : '<no_session>');
            }
        }
        _doInsert(template, opts) {
            if (!this._editor.hasModel()) {
                return;
            }
            // don't listen while inserting the snippet
            // as that is the inflight state causing cancelation
            this._snippetListener.clear();
            if (opts.undoStopBefore) {
                this._editor.getModel().pushStackElement();
            }
            // don't merge
            if (this._session && typeof template !== 'string') {
                this.cancel();
            }
            if (!this._session) {
                this._modelVersionId = this._editor.getModel().getAlternativeVersionId();
                this._session = new snippetSession_1.SnippetSession(this._editor, template, opts, this._languageConfigurationService);
                this._session.insert();
            }
            else {
                (0, types_1.assertType)(typeof template === 'string');
                this._session.merge(template, opts);
            }
            if (opts.undoStopAfter) {
                this._editor.getModel().pushStackElement();
            }
            // regster completion item provider when there is any choice element
            if (this._session?.hasChoice) {
                const provider = {
                    _debugDisplayName: 'snippetChoiceCompletions',
                    provideCompletionItems: (model, position) => {
                        if (!this._session || model !== this._editor.getModel() || !position_1.Position.equals(this._editor.getPosition(), position)) {
                            return undefined;
                        }
                        const { activeChoice } = this._session;
                        if (!activeChoice || activeChoice.choice.options.length === 0) {
                            return undefined;
                        }
                        const word = model.getValueInRange(activeChoice.range);
                        const isAnyOfOptions = Boolean(activeChoice.choice.options.find(o => o.value === word));
                        const suggestions = [];
                        for (let i = 0; i < activeChoice.choice.options.length; i++) {
                            const option = activeChoice.choice.options[i];
                            suggestions.push({
                                kind: 13 /* CompletionItemKind.Value */,
                                label: option.value,
                                insertText: option.value,
                                sortText: 'a'.repeat(i + 1),
                                range: activeChoice.range,
                                filterText: isAnyOfOptions ? `${word}_${option.value}` : undefined,
                                command: { id: 'jumpToNextSnippetPlaceholder', title: (0, nls_1.localize)(1260, 'Go to next placeholder...') }
                            });
                        }
                        return { suggestions };
                    }
                };
                const model = this._editor.getModel();
                let registration;
                let isRegistered = false;
                const disable = () => {
                    registration?.dispose();
                    isRegistered = false;
                };
                const enable = () => {
                    if (!isRegistered) {
                        registration = this._languageFeaturesService.completionProvider.register({
                            language: model.getLanguageId(),
                            pattern: model.uri.fsPath,
                            scheme: model.uri.scheme,
                            exclusive: true
                        }, provider);
                        this._snippetListener.add(registration);
                        isRegistered = true;
                    }
                };
                this._choiceCompletions = { provider, enable, disable };
            }
            this._updateState();
            this._snippetListener.add(this._editor.onDidChangeModelContent(e => e.isFlush && this.cancel()));
            this._snippetListener.add(this._editor.onDidChangeModel(() => this.cancel()));
            this._snippetListener.add(this._editor.onDidChangeCursorSelection(() => this._updateState()));
        }
        _updateState() {
            if (!this._session || !this._editor.hasModel()) {
                // canceled in the meanwhile
                return;
            }
            if (this._modelVersionId === this._editor.getModel().getAlternativeVersionId()) {
                // undo until the 'before' state happened
                // and makes use cancel snippet mode
                return this.cancel();
            }
            if (!this._session.hasPlaceholder) {
                // don't listen for selection changes and don't
                // update context keys when the snippet is plain text
                return this.cancel();
            }
            if (this._session.isAtLastPlaceholder || !this._session.isSelectionWithinPlaceholders()) {
                this._editor.getModel().pushStackElement();
                return this.cancel();
            }
            this._inSnippet.set(true);
            this._hasPrevTabstop.set(!this._session.isAtFirstPlaceholder);
            this._hasNextTabstop.set(!this._session.isAtLastPlaceholder);
            this._handleChoice();
        }
        _handleChoice() {
            if (!this._session || !this._editor.hasModel()) {
                this._currentChoice = undefined;
                return;
            }
            const { activeChoice } = this._session;
            if (!activeChoice || !this._choiceCompletions) {
                this._choiceCompletions?.disable();
                this._currentChoice = undefined;
                return;
            }
            if (this._currentChoice !== activeChoice.choice) {
                this._currentChoice = activeChoice.choice;
                this._choiceCompletions.enable();
                // trigger suggest with the special choice completion provider
                queueMicrotask(() => {
                    (0, suggest_1.showSimpleSuggestions)(this._editor, this._choiceCompletions.provider);
                });
            }
        }
        finish() {
            while (this._inSnippet.get()) {
                this.next();
            }
        }
        cancel(resetSelection = false) {
            this._inSnippet.reset();
            this._hasPrevTabstop.reset();
            this._hasNextTabstop.reset();
            this._snippetListener.clear();
            this._currentChoice = undefined;
            this._session?.dispose();
            this._session = undefined;
            this._modelVersionId = -1;
            if (resetSelection) {
                // reset selection to the primary cursor when being asked
                // for. this happens when explicitly cancelling snippet mode,
                // e.g. when pressing ESC
                this._editor.setSelections([this._editor.getSelection()]);
            }
        }
        prev() {
            this._session?.prev();
            this._updateState();
        }
        next() {
            this._session?.next();
            this._updateState();
        }
        isInSnippet() {
            return Boolean(this._inSnippet.get());
        }
    };
    exports.SnippetController2 = SnippetController2;
    exports.SnippetController2 = SnippetController2 = SnippetController2_1 = __decorate([
        __param(1, log_1.ILogService),
        __param(2, languageFeatures_1.ILanguageFeaturesService),
        __param(3, contextkey_1.IContextKeyService),
        __param(4, languageConfigurationRegistry_1.ILanguageConfigurationService)
    ], SnippetController2);
    (0, editorExtensions_1.registerEditorContribution)(SnippetController2.ID, SnippetController2, 4 /* EditorContributionInstantiation.Lazy */);
    const CommandCtor = editorExtensions_1.EditorCommand.bindToContribution(SnippetController2.get);
    (0, editorExtensions_1.registerEditorCommand)(new CommandCtor({
        id: 'jumpToNextSnippetPlaceholder',
        precondition: contextkey_1.ContextKeyExpr.and(SnippetController2.InSnippetMode, SnippetController2.HasNextTabstop),
        handler: ctrl => ctrl.next(),
        kbOpts: {
            weight: 100 /* KeybindingWeight.EditorContrib */ + 30,
            kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
            primary: 2 /* KeyCode.Tab */
        }
    }));
    (0, editorExtensions_1.registerEditorCommand)(new CommandCtor({
        id: 'jumpToPrevSnippetPlaceholder',
        precondition: contextkey_1.ContextKeyExpr.and(SnippetController2.InSnippetMode, SnippetController2.HasPrevTabstop),
        handler: ctrl => ctrl.prev(),
        kbOpts: {
            weight: 100 /* KeybindingWeight.EditorContrib */ + 30,
            kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
            primary: 1024 /* KeyMod.Shift */ | 2 /* KeyCode.Tab */
        }
    }));
    (0, editorExtensions_1.registerEditorCommand)(new CommandCtor({
        id: 'leaveSnippet',
        precondition: SnippetController2.InSnippetMode,
        handler: ctrl => ctrl.cancel(true),
        kbOpts: {
            weight: 100 /* KeybindingWeight.EditorContrib */ + 30,
            kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
            primary: 9 /* KeyCode.Escape */,
            secondary: [1024 /* KeyMod.Shift */ | 9 /* KeyCode.Escape */]
        }
    }));
    (0, editorExtensions_1.registerEditorCommand)(new CommandCtor({
        id: 'acceptSnippet',
        precondition: SnippetController2.InSnippetMode,
        handler: ctrl => ctrl.finish(),
        // kbOpts: {
        // 	weight: KeybindingWeight.EditorContrib + 30,
        // 	kbExpr: EditorContextKeys.textFocus,
        // 	primary: KeyCode.Enter,
        // }
    }));
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[860/*vs/editor/contrib/inlineCompletions/browser/model/inlineCompletionsModel*/], __M([1/*require*/,0/*exports*/,13/*vs/base/common/arrays*/,67/*vs/base/common/arraysFind*/,102/*vs/base/common/equals*/,8/*vs/base/common/errors*/,2/*vs/base/common/lifecycle*/,21/*vs/base/common/observable*/,11/*vs/base/common/strings*/,19/*vs/base/common/types*/,75/*vs/editor/common/core/editOperation*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/,23/*vs/editor/common/core/selection*/,104/*vs/editor/common/core/textEdit*/,113/*vs/editor/common/core/textLength*/,27/*vs/editor/common/languages*/,36/*vs/editor/common/languages/languageConfigurationRegistry*/,204/*vs/editor/contrib/inlineCompletions/browser/model/ghostText*/,715/*vs/editor/contrib/inlineCompletions/browser/model/inlineCompletionsSource*/,246/*vs/editor/contrib/inlineCompletions/browser/model/singleTextEdit*/,205/*vs/editor/contrib/inlineCompletions/browser/utils*/,221/*vs/editor/contrib/snippet/browser/snippetController2*/,24/*vs/platform/commands/common/commands*/,7/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, arrays_1, arraysFind_1, equals_1, errors_1, lifecycle_1, observable_1, strings_1, types_1, editOperation_1, position_1, range_1, selection_1, textEdit_1, textLength_1, languages_1, languageConfigurationRegistry_1, ghostText_1, inlineCompletionsSource_1, singleTextEdit_1, utils_1, snippetController2_1, commands_1, instantiation_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.VersionIdChangeReason = exports.InlineCompletionsModel = void 0;
    exports.getSecondaryEdits = getSecondaryEdits;
    let InlineCompletionsModel = class InlineCompletionsModel extends lifecycle_1.Disposable {
        get isAcceptingPartially() { return this._isAcceptingPartially; }
        constructor(textModel, selectedSuggestItem, _textModelVersionId, _positions, _debounceValue, _suggestPreviewEnabled, _suggestPreviewMode, _inlineSuggestMode, _enabled, _instantiationService, _commandService, _languageConfigurationService) {
            super();
            this.textModel = textModel;
            this.selectedSuggestItem = selectedSuggestItem;
            this._textModelVersionId = _textModelVersionId;
            this._positions = _positions;
            this._debounceValue = _debounceValue;
            this._suggestPreviewEnabled = _suggestPreviewEnabled;
            this._suggestPreviewMode = _suggestPreviewMode;
            this._inlineSuggestMode = _inlineSuggestMode;
            this._enabled = _enabled;
            this._instantiationService = _instantiationService;
            this._commandService = _commandService;
            this._languageConfigurationService = _languageConfigurationService;
            this._source = this._register(this._instantiationService.createInstance(inlineCompletionsSource_1.InlineCompletionsSource, this.textModel, this._textModelVersionId, this._debounceValue));
            this._isActive = (0, observable_1.observableValue)(this, false);
            this._forceUpdateExplicitlySignal = (0, observable_1.observableSignal)(this);
            // We use a semantic id to keep the same inline completion selected even if the provider reorders the completions.
            this._selectedInlineCompletionId = (0, observable_1.observableValue)(this, undefined);
            this._primaryPosition = (0, observable_1.derived)(this, reader => this._positions.read(reader)[0] ?? new position_1.Position(1, 1));
            this._isAcceptingPartially = false;
            this._preserveCurrentCompletionReasons = new Set([
                VersionIdChangeReason.Redo,
                VersionIdChangeReason.Undo,
                VersionIdChangeReason.AcceptWord,
            ]);
            this._fetchInlineCompletionsPromise = (0, observable_1.derivedHandleChanges)({
                owner: this,
                createEmptyChangeSummary: () => ({
                    preserveCurrentCompletion: false,
                    inlineCompletionTriggerKind: languages_1.InlineCompletionTriggerKind.Automatic
                }),
                handleChange: (ctx, changeSummary) => {
                    /** @description fetch inline completions */
                    if (ctx.didChange(this._textModelVersionId) && this._preserveCurrentCompletionReasons.has(this._getReason(ctx.change))) {
                        changeSummary.preserveCurrentCompletion = true;
                    }
                    else if (ctx.didChange(this._forceUpdateExplicitlySignal)) {
                        changeSummary.inlineCompletionTriggerKind = languages_1.InlineCompletionTriggerKind.Explicit;
                    }
                    return true;
                },
            }, (reader, changeSummary) => {
                this._forceUpdateExplicitlySignal.read(reader);
                const shouldUpdate = (this._enabled.read(reader) && this.selectedSuggestItem.read(reader)) || this._isActive.read(reader);
                if (!shouldUpdate) {
                    this._source.cancelUpdate();
                    return undefined;
                }
                this._textModelVersionId.read(reader); // Refetch on text change
                const suggestWidgetInlineCompletions = this._source.suggestWidgetInlineCompletions.get();
                const suggestItem = this.selectedSuggestItem.read(reader);
                if (suggestWidgetInlineCompletions && !suggestItem) {
                    const inlineCompletions = this._source.inlineCompletions.get();
                    (0, observable_1.transaction)(tx => {
                        /** @description Seed inline completions with (newer) suggest widget inline completions */
                        if (!inlineCompletions || suggestWidgetInlineCompletions.request.versionId > inlineCompletions.request.versionId) {
                            this._source.inlineCompletions.set(suggestWidgetInlineCompletions.clone(), tx);
                        }
                        this._source.clearSuggestWidgetInlineCompletions(tx);
                    });
                }
                const cursorPosition = this._primaryPosition.read(reader);
                const context = {
                    triggerKind: changeSummary.inlineCompletionTriggerKind,
                    selectedSuggestionInfo: suggestItem?.toSelectedSuggestionInfo(),
                };
                const itemToPreserveCandidate = this.selectedInlineCompletion.get();
                const itemToPreserve = changeSummary.preserveCurrentCompletion || itemToPreserveCandidate?.forwardStable
                    ? itemToPreserveCandidate : undefined;
                return this._source.fetch(cursorPosition, context, itemToPreserve);
            });
            this._filteredInlineCompletionItems = (0, observable_1.derivedOpts)({ owner: this, equalsFn: (0, equals_1.itemsEquals)() }, reader => {
                const c = this._source.inlineCompletions.read(reader);
                if (!c) {
                    return [];
                }
                const cursorPosition = this._primaryPosition.read(reader);
                const filteredCompletions = c.inlineCompletions.filter(c => c.isVisible(this.textModel, cursorPosition, reader));
                return filteredCompletions;
            });
            this.selectedInlineCompletionIndex = (0, observable_1.derived)(this, (reader) => {
                const selectedInlineCompletionId = this._selectedInlineCompletionId.read(reader);
                const filteredCompletions = this._filteredInlineCompletionItems.read(reader);
                const idx = this._selectedInlineCompletionId === undefined ? -1
                    : filteredCompletions.findIndex(v => v.semanticId === selectedInlineCompletionId);
                if (idx === -1) {
                    // Reset the selection so that the selection does not jump back when it appears again
                    this._selectedInlineCompletionId.set(undefined, undefined);
                    return 0;
                }
                return idx;
            });
            this.selectedInlineCompletion = (0, observable_1.derived)(this, (reader) => {
                const filteredCompletions = this._filteredInlineCompletionItems.read(reader);
                const idx = this.selectedInlineCompletionIndex.read(reader);
                return filteredCompletions[idx];
            });
            this.activeCommands = (0, observable_1.derivedOpts)({ owner: this, equalsFn: (0, equals_1.itemsEquals)() }, r => this.selectedInlineCompletion.read(r)?.inlineCompletion.source.inlineCompletions.commands ?? []);
            this.lastTriggerKind = this._source.inlineCompletions.map(this, v => v?.request.context.triggerKind);
            this.inlineCompletionsCount = (0, observable_1.derived)(this, reader => {
                if (this.lastTriggerKind.read(reader) === languages_1.InlineCompletionTriggerKind.Explicit) {
                    return this._filteredInlineCompletionItems.read(reader).length;
                }
                else {
                    return undefined;
                }
            });
            this.state = (0, observable_1.derivedOpts)({
                owner: this,
                equalsFn: (a, b) => {
                    if (!a || !b) {
                        return a === b;
                    }
                    return (0, ghostText_1.ghostTextsOrReplacementsEqual)(a.ghostTexts, b.ghostTexts)
                        && a.inlineCompletion === b.inlineCompletion
                        && a.suggestItem === b.suggestItem;
                }
            }, (reader) => {
                const model = this.textModel;
                const suggestItem = this.selectedSuggestItem.read(reader);
                if (suggestItem) {
                    const suggestCompletionEdit = (0, singleTextEdit_1.singleTextRemoveCommonPrefix)(suggestItem.toSingleTextEdit(), model);
                    const augmentation = this._computeAugmentation(suggestCompletionEdit, reader);
                    const isSuggestionPreviewEnabled = this._suggestPreviewEnabled.read(reader);
                    if (!isSuggestionPreviewEnabled && !augmentation) {
                        return undefined;
                    }
                    const fullEdit = augmentation?.edit ?? suggestCompletionEdit;
                    const fullEditPreviewLength = augmentation ? augmentation.edit.text.length - suggestCompletionEdit.text.length : 0;
                    const mode = this._suggestPreviewMode.read(reader);
                    const positions = this._positions.read(reader);
                    const edits = [fullEdit, ...getSecondaryEdits(this.textModel, positions, fullEdit)];
                    const ghostTexts = edits
                        .map((edit, idx) => (0, singleTextEdit_1.computeGhostText)(edit, model, mode, positions[idx], fullEditPreviewLength))
                        .filter(types_1.isDefined);
                    const primaryGhostText = ghostTexts[0] ?? new ghostText_1.GhostText(fullEdit.range.endLineNumber, []);
                    return { edits, primaryGhostText, ghostTexts, inlineCompletion: augmentation?.completion, suggestItem };
                }
                else {
                    if (!this._isActive.read(reader)) {
                        return undefined;
                    }
                    const inlineCompletion = this.selectedInlineCompletion.read(reader);
                    if (!inlineCompletion) {
                        return undefined;
                    }
                    const replacement = inlineCompletion.toSingleTextEdit(reader);
                    const mode = this._inlineSuggestMode.read(reader);
                    const positions = this._positions.read(reader);
                    const edits = [replacement, ...getSecondaryEdits(this.textModel, positions, replacement)];
                    const ghostTexts = edits
                        .map((edit, idx) => (0, singleTextEdit_1.computeGhostText)(edit, model, mode, positions[idx], 0))
                        .filter(types_1.isDefined);
                    if (!ghostTexts[0]) {
                        return undefined;
                    }
                    return { edits, primaryGhostText: ghostTexts[0], ghostTexts, inlineCompletion, suggestItem: undefined };
                }
            });
            this.ghostTexts = (0, observable_1.derivedOpts)({ owner: this, equalsFn: ghostText_1.ghostTextsOrReplacementsEqual }, reader => {
                const v = this.state.read(reader);
                if (!v) {
                    return undefined;
                }
                return v.ghostTexts;
            });
            this.primaryGhostText = (0, observable_1.derivedOpts)({ owner: this, equalsFn: ghostText_1.ghostTextOrReplacementEquals }, reader => {
                const v = this.state.read(reader);
                if (!v) {
                    return undefined;
                }
                return v?.primaryGhostText;
            });
            this._register((0, observable_1.recomputeInitiallyAndOnChange)(this._fetchInlineCompletionsPromise));
            let lastItem = undefined;
            this._register((0, observable_1.autorun)(reader => {
                /** @description call handleItemDidShow */
                const item = this.state.read(reader);
                const completion = item?.inlineCompletion;
                if (completion?.semanticId !== lastItem?.semanticId) {
                    lastItem = completion;
                    if (completion) {
                        const i = completion.inlineCompletion;
                        const src = i.source;
                        src.provider.handleItemDidShow?.(src.inlineCompletions, i.sourceInlineCompletion, i.insertText);
                    }
                }
            }));
        }
        _getReason(e) {
            if (e?.isUndoing) {
                return VersionIdChangeReason.Undo;
            }
            if (e?.isRedoing) {
                return VersionIdChangeReason.Redo;
            }
            if (this.isAcceptingPartially) {
                return VersionIdChangeReason.AcceptWord;
            }
            return VersionIdChangeReason.Other;
        }
        async trigger(tx) {
            this._isActive.set(true, tx);
            await this._fetchInlineCompletionsPromise.get();
        }
        async triggerExplicitly(tx) {
            (0, observable_1.subtransaction)(tx, tx => {
                this._isActive.set(true, tx);
                this._forceUpdateExplicitlySignal.trigger(tx);
            });
            await this._fetchInlineCompletionsPromise.get();
        }
        stop(tx) {
            (0, observable_1.subtransaction)(tx, tx => {
                this._isActive.set(false, tx);
                this._source.clear(tx);
            });
        }
        _computeAugmentation(suggestCompletion, reader) {
            const model = this.textModel;
            const suggestWidgetInlineCompletions = this._source.suggestWidgetInlineCompletions.read(reader);
            const candidateInlineCompletions = suggestWidgetInlineCompletions
                ? suggestWidgetInlineCompletions.inlineCompletions
                : [this.selectedInlineCompletion.read(reader)].filter(types_1.isDefined);
            const augmentedCompletion = (0, arraysFind_1.mapFindFirst)(candidateInlineCompletions, completion => {
                let r = completion.toSingleTextEdit(reader);
                r = (0, singleTextEdit_1.singleTextRemoveCommonPrefix)(r, model, range_1.Range.fromPositions(r.range.getStartPosition(), suggestCompletion.range.getEndPosition()));
                return (0, singleTextEdit_1.singleTextEditAugments)(r, suggestCompletion) ? { completion, edit: r } : undefined;
            });
            return augmentedCompletion;
        }
        async _deltaSelectedInlineCompletionIndex(delta) {
            await this.triggerExplicitly();
            const completions = this._filteredInlineCompletionItems.get() || [];
            if (completions.length > 0) {
                const newIdx = (this.selectedInlineCompletionIndex.get() + delta + completions.length) % completions.length;
                this._selectedInlineCompletionId.set(completions[newIdx].semanticId, undefined);
            }
            else {
                this._selectedInlineCompletionId.set(undefined, undefined);
            }
        }
        async next() {
            await this._deltaSelectedInlineCompletionIndex(1);
        }
        async previous() {
            await this._deltaSelectedInlineCompletionIndex(-1);
        }
        async accept(editor) {
            if (editor.getModel() !== this.textModel) {
                throw new errors_1.BugIndicatingError();
            }
            const state = this.state.get();
            if (!state || state.primaryGhostText.isEmpty() || !state.inlineCompletion) {
                return;
            }
            const completion = state.inlineCompletion.toInlineCompletion(undefined);
            if (completion.command) {
                // Make sure the completion list will not be disposed.
                completion.source.addRef();
            }
            editor.pushUndoStop();
            if (completion.snippetInfo) {
                editor.executeEdits('inlineSuggestion.accept', [
                    editOperation_1.EditOperation.replace(completion.range, ''),
                    ...completion.additionalTextEdits
                ]);
                editor.setPosition(completion.snippetInfo.range.getStartPosition(), 'inlineCompletionAccept');
                snippetController2_1.SnippetController2.get(editor)?.insert(completion.snippetInfo.snippet, { undoStopBefore: false });
            }
            else {
                const edits = state.edits;
                const selections = getEndPositionsAfterApplying(edits).map(p => selection_1.Selection.fromPositions(p));
                editor.executeEdits('inlineSuggestion.accept', [
                    ...edits.map(edit => editOperation_1.EditOperation.replace(edit.range, edit.text)),
                    ...completion.additionalTextEdits
                ]);
                editor.setSelections(selections, 'inlineCompletionAccept');
            }
            // Reset before invoking the command, as the command might cause a follow up trigger (which we don't want to reset).
            this.stop();
            if (completion.command) {
                await this._commandService
                    .executeCommand(completion.command.id, ...(completion.command.arguments || []))
                    .then(undefined, errors_1.onUnexpectedExternalError);
                completion.source.removeRef();
            }
        }
        async acceptNextWord(editor) {
            await this._acceptNext(editor, (pos, text) => {
                const langId = this.textModel.getLanguageIdAtPosition(pos.lineNumber, pos.column);
                const config = this._languageConfigurationService.getLanguageConfiguration(langId);
                const wordRegExp = new RegExp(config.wordDefinition.source, config.wordDefinition.flags.replace('g', ''));
                const m1 = text.match(wordRegExp);
                let acceptUntilIndexExclusive = 0;
                if (m1 && m1.index !== undefined) {
                    if (m1.index === 0) {
                        acceptUntilIndexExclusive = m1[0].length;
                    }
                    else {
                        acceptUntilIndexExclusive = m1.index;
                    }
                }
                else {
                    acceptUntilIndexExclusive = text.length;
                }
                const wsRegExp = /\s+/g;
                const m2 = wsRegExp.exec(text);
                if (m2 && m2.index !== undefined) {
                    if (m2.index + m2[0].length < acceptUntilIndexExclusive) {
                        acceptUntilIndexExclusive = m2.index + m2[0].length;
                    }
                }
                return acceptUntilIndexExclusive;
            }, 0 /* PartialAcceptTriggerKind.Word */);
        }
        async acceptNextLine(editor) {
            await this._acceptNext(editor, (pos, text) => {
                const m = text.match(/\n/);
                if (m && m.index !== undefined) {
                    return m.index + 1;
                }
                return text.length;
            }, 1 /* PartialAcceptTriggerKind.Line */);
        }
        async _acceptNext(editor, getAcceptUntilIndex, kind) {
            if (editor.getModel() !== this.textModel) {
                throw new errors_1.BugIndicatingError();
            }
            const state = this.state.get();
            if (!state || state.primaryGhostText.isEmpty() || !state.inlineCompletion) {
                return;
            }
            const ghostText = state.primaryGhostText;
            const completion = state.inlineCompletion.toInlineCompletion(undefined);
            if (completion.snippetInfo || completion.filterText !== completion.insertText) {
                // not in WYSIWYG mode, partial commit might change completion, thus it is not supported
                await this.accept(editor);
                return;
            }
            const firstPart = ghostText.parts[0];
            const ghostTextPos = new position_1.Position(ghostText.lineNumber, firstPart.column);
            const ghostTextVal = firstPart.text;
            const acceptUntilIndexExclusive = getAcceptUntilIndex(ghostTextPos, ghostTextVal);
            if (acceptUntilIndexExclusive === ghostTextVal.length && ghostText.parts.length === 1) {
                this.accept(editor);
                return;
            }
            const partialGhostTextVal = ghostTextVal.substring(0, acceptUntilIndexExclusive);
            const positions = this._positions.get();
            const cursorPosition = positions[0];
            // Executing the edit might free the completion, so we have to hold a reference on it.
            completion.source.addRef();
            try {
                this._isAcceptingPartially = true;
                try {
                    editor.pushUndoStop();
                    const replaceRange = range_1.Range.fromPositions(cursorPosition, ghostTextPos);
                    const newText = editor.getModel().getValueInRange(replaceRange) + partialGhostTextVal;
                    const primaryEdit = new textEdit_1.SingleTextEdit(replaceRange, newText);
                    const edits = [primaryEdit, ...getSecondaryEdits(this.textModel, positions, primaryEdit)];
                    const selections = getEndPositionsAfterApplying(edits).map(p => selection_1.Selection.fromPositions(p));
                    editor.executeEdits('inlineSuggestion.accept', edits.map(edit => editOperation_1.EditOperation.replace(edit.range, edit.text)));
                    editor.setSelections(selections, 'inlineCompletionPartialAccept');
                    editor.revealPositionInCenterIfOutsideViewport(editor.getPosition(), 1 /* ScrollType.Immediate */);
                }
                finally {
                    this._isAcceptingPartially = false;
                }
                if (completion.source.provider.handlePartialAccept) {
                    const acceptedRange = range_1.Range.fromPositions(completion.range.getStartPosition(), textLength_1.TextLength.ofText(partialGhostTextVal).addToPosition(ghostTextPos));
                    // This assumes that the inline completion and the model use the same EOL style.
                    const text = editor.getModel().getValueInRange(acceptedRange, 1 /* EndOfLinePreference.LF */);
                    completion.source.provider.handlePartialAccept(completion.source.inlineCompletions, completion.sourceInlineCompletion, text.length, { kind, });
                }
            }
            finally {
                completion.source.removeRef();
            }
        }
        handleSuggestAccepted(item) {
            const itemEdit = (0, singleTextEdit_1.singleTextRemoveCommonPrefix)(item.toSingleTextEdit(), this.textModel);
            const augmentedCompletion = this._computeAugmentation(itemEdit, undefined);
            if (!augmentedCompletion) {
                return;
            }
            const inlineCompletion = augmentedCompletion.completion.inlineCompletion;
            inlineCompletion.source.provider.handlePartialAccept?.(inlineCompletion.source.inlineCompletions, inlineCompletion.sourceInlineCompletion, itemEdit.text.length, {
                kind: 2 /* PartialAcceptTriggerKind.Suggest */,
            });
        }
    };
    exports.InlineCompletionsModel = InlineCompletionsModel;
    exports.InlineCompletionsModel = InlineCompletionsModel = __decorate([
        __param(9, instantiation_1.IInstantiationService),
        __param(10, commands_1.ICommandService),
        __param(11, languageConfigurationRegistry_1.ILanguageConfigurationService)
    ], InlineCompletionsModel);
    var VersionIdChangeReason;
    (function (VersionIdChangeReason) {
        VersionIdChangeReason[VersionIdChangeReason["Undo"] = 0] = "Undo";
        VersionIdChangeReason[VersionIdChangeReason["Redo"] = 1] = "Redo";
        VersionIdChangeReason[VersionIdChangeReason["AcceptWord"] = 2] = "AcceptWord";
        VersionIdChangeReason[VersionIdChangeReason["Other"] = 3] = "Other";
    })(VersionIdChangeReason || (exports.VersionIdChangeReason = VersionIdChangeReason = {}));
    function getSecondaryEdits(textModel, positions, primaryEdit) {
        if (positions.length === 1) {
            // No secondary cursor positions
            return [];
        }
        const primaryPosition = positions[0];
        const secondaryPositions = positions.slice(1);
        const primaryEditStartPosition = primaryEdit.range.getStartPosition();
        const primaryEditEndPosition = primaryEdit.range.getEndPosition();
        const replacedTextAfterPrimaryCursor = textModel.getValueInRange(range_1.Range.fromPositions(primaryPosition, primaryEditEndPosition));
        const positionWithinTextEdit = (0, utils_1.subtractPositions)(primaryPosition, primaryEditStartPosition);
        if (positionWithinTextEdit.lineNumber < 1) {
            (0, errors_1.onUnexpectedError)(new errors_1.BugIndicatingError(`positionWithinTextEdit line number should be bigger than 0.
			Invalid subtraction between ${primaryPosition.toString()} and ${primaryEditStartPosition.toString()}`));
            return [];
        }
        const secondaryEditText = substringPos(primaryEdit.text, positionWithinTextEdit);
        return secondaryPositions.map(pos => {
            const posEnd = (0, utils_1.addPositions)((0, utils_1.subtractPositions)(pos, primaryEditStartPosition), primaryEditEndPosition);
            const textAfterSecondaryCursor = textModel.getValueInRange(range_1.Range.fromPositions(pos, posEnd));
            const l = (0, strings_1.commonPrefixLength)(replacedTextAfterPrimaryCursor, textAfterSecondaryCursor);
            const range = range_1.Range.fromPositions(pos, pos.delta(0, l));
            return new textEdit_1.SingleTextEdit(range, secondaryEditText);
        });
    }
    function substringPos(text, pos) {
        let subtext = '';
        const lines = (0, strings_1.splitLinesIncludeSeparators)(text);
        for (let i = pos.lineNumber - 1; i < lines.length; i++) {
            subtext += lines[i].substring(i === pos.lineNumber - 1 ? pos.column - 1 : 0);
        }
        return subtext;
    }
    function getEndPositionsAfterApplying(edits) {
        const sortPerm = arrays_1.Permutation.createSortPermutation(edits, (0, arrays_1.compareBy)(e => e.range, range_1.Range.compareRangesUsingStarts));
        const edit = new textEdit_1.TextEdit(sortPerm.apply(edits));
        const sortedNewRanges = edit.getNewRanges();
        const newRanges = sortPerm.inverse().apply(sortedNewRanges);
        return newRanges.map(range => range.getEndPosition());
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[437/*vs/editor/contrib/suggest/browser/suggestModel*/], __M([1/*require*/,0/*exports*/,14/*vs/base/common/async*/,18/*vs/base/common/cancellation*/,8/*vs/base/common/errors*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,11/*vs/base/common/strings*/,23/*vs/editor/common/core/selection*/,100/*vs/editor/common/services/editorWorker*/,343/*vs/editor/contrib/suggest/browser/wordDistance*/,117/*vs/platform/clipboard/common/clipboardService*/,28/*vs/platform/configuration/common/configuration*/,12/*vs/platform/contextkey/common/contextkey*/,62/*vs/platform/log/common/log*/,63/*vs/platform/telemetry/common/telemetry*/,342/*vs/editor/contrib/suggest/browser/completionModel*/,155/*vs/editor/contrib/suggest/browser/suggest*/,17/*vs/editor/common/services/languageFeatures*/,82/*vs/base/common/filters*/,19/*vs/base/common/types*/,269/*vs/editor/contrib/inlineCompletions/browser/controller/inlineCompletionContextKeys*/,221/*vs/editor/contrib/snippet/browser/snippetController2*/,271/*vs/platform/environment/common/environment*/]), function (require, exports, async_1, cancellation_1, errors_1, event_1, lifecycle_1, strings_1, selection_1, editorWorker_1, wordDistance_1, clipboardService_1, configuration_1, contextkey_1, log_1, telemetry_1, completionModel_1, suggest_1, languageFeatures_1, filters_1, types_1, inlineCompletionContextKeys_1, snippetController2_1, environment_1) {
    "use strict";
    var SuggestModel_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SuggestModel = exports.LineContext = void 0;
    class LineContext {
        static shouldAutoTrigger(editor) {
            if (!editor.hasModel()) {
                return false;
            }
            const model = editor.getModel();
            const pos = editor.getPosition();
            model.tokenization.tokenizeIfCheap(pos.lineNumber);
            const word = model.getWordAtPosition(pos);
            if (!word) {
                return false;
            }
            if (word.endColumn !== pos.column &&
                word.startColumn + 1 !== pos.column /* after typing a single character before a word */) {
                return false;
            }
            if (!isNaN(Number(word.word))) {
                return false;
            }
            return true;
        }
        constructor(model, position, triggerOptions) {
            this.leadingLineContent = model.getLineContent(position.lineNumber).substr(0, position.column - 1);
            this.leadingWord = model.getWordUntilPosition(position);
            this.lineNumber = position.lineNumber;
            this.column = position.column;
            this.triggerOptions = triggerOptions;
        }
    }
    exports.LineContext = LineContext;
    function canShowQuickSuggest(editor, contextKeyService, configurationService) {
        if (!Boolean(contextKeyService.getContextKeyValue(inlineCompletionContextKeys_1.InlineCompletionContextKeys.inlineSuggestionVisible.key))) {
            // Allow if there is no inline suggestion.
            return true;
        }
        const suppressSuggestions = contextKeyService.getContextKeyValue(inlineCompletionContextKeys_1.InlineCompletionContextKeys.suppressSuggestions.key);
        if (suppressSuggestions !== undefined) {
            return !suppressSuggestions;
        }
        return !editor.getOption(62 /* EditorOption.inlineSuggest */).suppressSuggestions;
    }
    function canShowSuggestOnTriggerCharacters(editor, contextKeyService, configurationService) {
        if (!Boolean(contextKeyService.getContextKeyValue('inlineSuggestionVisible'))) {
            // Allow if there is no inline suggestion.
            return true;
        }
        const suppressSuggestions = contextKeyService.getContextKeyValue(inlineCompletionContextKeys_1.InlineCompletionContextKeys.suppressSuggestions.key);
        if (suppressSuggestions !== undefined) {
            return !suppressSuggestions;
        }
        return !editor.getOption(62 /* EditorOption.inlineSuggest */).suppressSuggestions;
    }
    let SuggestModel = SuggestModel_1 = class SuggestModel {
        constructor(_editor, _editorWorkerService, _clipboardService, _telemetryService, _logService, _contextKeyService, _configurationService, _languageFeaturesService, _envService) {
            this._editor = _editor;
            this._editorWorkerService = _editorWorkerService;
            this._clipboardService = _clipboardService;
            this._telemetryService = _telemetryService;
            this._logService = _logService;
            this._contextKeyService = _contextKeyService;
            this._configurationService = _configurationService;
            this._languageFeaturesService = _languageFeaturesService;
            this._envService = _envService;
            this._toDispose = new lifecycle_1.DisposableStore();
            this._triggerCharacterListener = new lifecycle_1.DisposableStore();
            this._triggerQuickSuggest = new async_1.TimeoutTimer();
            this._triggerState = undefined;
            this._completionDisposables = new lifecycle_1.DisposableStore();
            this._onDidCancel = new event_1.Emitter();
            this._onDidTrigger = new event_1.Emitter();
            this._onDidSuggest = new event_1.Emitter();
            this.onDidCancel = this._onDidCancel.event;
            this.onDidTrigger = this._onDidTrigger.event;
            this.onDidSuggest = this._onDidSuggest.event;
            this._telemetryGate = 0;
            this._currentSelection = this._editor.getSelection() || new selection_1.Selection(1, 1, 1, 1);
            // wire up various listeners
            this._toDispose.add(this._editor.onDidChangeModel(() => {
                this._updateTriggerCharacters();
                this.cancel();
            }));
            this._toDispose.add(this._editor.onDidChangeModelLanguage(() => {
                this._updateTriggerCharacters();
                this.cancel();
            }));
            this._toDispose.add(this._editor.onDidChangeConfiguration(() => {
                this._updateTriggerCharacters();
            }));
            this._toDispose.add(this._languageFeaturesService.completionProvider.onDidChange(() => {
                this._updateTriggerCharacters();
                this._updateActiveSuggestSession();
            }));
            let editorIsComposing = false;
            this._toDispose.add(this._editor.onDidCompositionStart(() => {
                editorIsComposing = true;
            }));
            this._toDispose.add(this._editor.onDidCompositionEnd(() => {
                editorIsComposing = false;
                this._onCompositionEnd();
            }));
            this._toDispose.add(this._editor.onDidChangeCursorSelection(e => {
                // only trigger suggest when the editor isn't composing a character
                if (!editorIsComposing) {
                    this._onCursorChange(e);
                }
            }));
            this._toDispose.add(this._editor.onDidChangeModelContent(() => {
                // only filter completions when the editor isn't composing a character
                // allow-any-unicode-next-line
                // e.g. ¨ + u makes ü but just ¨ cannot be used for filtering
                if (!editorIsComposing && this._triggerState !== undefined) {
                    this._refilterCompletionItems();
                }
            }));
            this._updateTriggerCharacters();
        }
        dispose() {
            (0, lifecycle_1.dispose)(this._triggerCharacterListener);
            (0, lifecycle_1.dispose)([this._onDidCancel, this._onDidSuggest, this._onDidTrigger, this._triggerQuickSuggest]);
            this._toDispose.dispose();
            this._completionDisposables.dispose();
            this.cancel();
        }
        _updateTriggerCharacters() {
            this._triggerCharacterListener.clear();
            if (this._editor.getOption(92 /* EditorOption.readOnly */)
                || !this._editor.hasModel()
                || !this._editor.getOption(122 /* EditorOption.suggestOnTriggerCharacters */)) {
                return;
            }
            const supportsByTriggerCharacter = new Map();
            for (const support of this._languageFeaturesService.completionProvider.all(this._editor.getModel())) {
                for (const ch of support.triggerCharacters || []) {
                    let set = supportsByTriggerCharacter.get(ch);
                    if (!set) {
                        set = new Set();
                        const suggestSupport = (0, suggest_1.getSnippetSuggestSupport)();
                        if (suggestSupport) {
                            set.add(suggestSupport);
                        }
                        supportsByTriggerCharacter.set(ch, set);
                    }
                    set.add(support);
                }
            }
            const checkTriggerCharacter = (text) => {
                if (!canShowSuggestOnTriggerCharacters(this._editor, this._contextKeyService, this._configurationService)) {
                    return;
                }
                if (LineContext.shouldAutoTrigger(this._editor)) {
                    // don't trigger by trigger characters when this is a case for quick suggest
                    return;
                }
                if (!text) {
                    // came here from the compositionEnd-event
                    const position = this._editor.getPosition();
                    const model = this._editor.getModel();
                    text = model.getLineContent(position.lineNumber).substr(0, position.column - 1);
                }
                let lastChar = '';
                if ((0, strings_1.isLowSurrogate)(text.charCodeAt(text.length - 1))) {
                    if ((0, strings_1.isHighSurrogate)(text.charCodeAt(text.length - 2))) {
                        lastChar = text.substr(text.length - 2);
                    }
                }
                else {
                    lastChar = text.charAt(text.length - 1);
                }
                const supports = supportsByTriggerCharacter.get(lastChar);
                if (supports) {
                    // keep existing items that where not computed by the
                    // supports/providers that want to trigger now
                    const providerItemsToReuse = new Map();
                    if (this._completionModel) {
                        for (const [provider, items] of this._completionModel.getItemsByProvider()) {
                            if (!supports.has(provider)) {
                                providerItemsToReuse.set(provider, items);
                            }
                        }
                    }
                    this.trigger({
                        auto: true,
                        triggerKind: 1 /* CompletionTriggerKind.TriggerCharacter */,
                        triggerCharacter: lastChar,
                        retrigger: Boolean(this._completionModel),
                        clipboardText: this._completionModel?.clipboardText,
                        completionOptions: { providerFilter: supports, providerItemsToReuse }
                    });
                }
            };
            this._triggerCharacterListener.add(this._editor.onDidType(checkTriggerCharacter));
            this._triggerCharacterListener.add(this._editor.onDidCompositionEnd(() => checkTriggerCharacter()));
        }
        // --- trigger/retrigger/cancel suggest
        get state() {
            if (!this._triggerState) {
                return 0 /* State.Idle */;
            }
            else if (!this._triggerState.auto) {
                return 1 /* State.Manual */;
            }
            else {
                return 2 /* State.Auto */;
            }
        }
        cancel(retrigger = false) {
            if (this._triggerState !== undefined) {
                this._triggerQuickSuggest.cancel();
                this._requestToken?.cancel();
                this._requestToken = undefined;
                this._triggerState = undefined;
                this._completionModel = undefined;
                this._context = undefined;
                this._onDidCancel.fire({ retrigger });
            }
        }
        clear() {
            this._completionDisposables.clear();
        }
        _updateActiveSuggestSession() {
            if (this._triggerState !== undefined) {
                if (!this._editor.hasModel() || !this._languageFeaturesService.completionProvider.has(this._editor.getModel())) {
                    this.cancel();
                }
                else {
                    this.trigger({ auto: this._triggerState.auto, retrigger: true });
                }
            }
        }
        _onCursorChange(e) {
            if (!this._editor.hasModel()) {
                return;
            }
            const prevSelection = this._currentSelection;
            this._currentSelection = this._editor.getSelection();
            if (!e.selection.isEmpty()
                || (e.reason !== 0 /* CursorChangeReason.NotSet */ && e.reason !== 3 /* CursorChangeReason.Explicit */)
                || (e.source !== 'keyboard' && e.source !== 'deleteLeft')) {
                // Early exit if nothing needs to be done!
                // Leave some form of early exit check here if you wish to continue being a cursor position change listener ;)
                this.cancel();
                return;
            }
            if (this._triggerState === undefined && e.reason === 0 /* CursorChangeReason.NotSet */) {
                if (prevSelection.containsRange(this._currentSelection) || prevSelection.getEndPosition().isBeforeOrEqual(this._currentSelection.getPosition())) {
                    // cursor did move RIGHT due to typing -> trigger quick suggest
                    this._doTriggerQuickSuggest();
                }
            }
            else if (this._triggerState !== undefined && e.reason === 3 /* CursorChangeReason.Explicit */) {
                // suggest is active and something like cursor keys are used to move
                // the cursor. this means we can refilter at the new position
                this._refilterCompletionItems();
            }
        }
        _onCompositionEnd() {
            // trigger or refilter when composition ends
            if (this._triggerState === undefined) {
                this._doTriggerQuickSuggest();
            }
            else {
                this._refilterCompletionItems();
            }
        }
        _doTriggerQuickSuggest() {
            if (suggest_1.QuickSuggestionsOptions.isAllOff(this._editor.getOption(90 /* EditorOption.quickSuggestions */))) {
                // not enabled
                return;
            }
            if (this._editor.getOption(119 /* EditorOption.suggest */).snippetsPreventQuickSuggestions && snippetController2_1.SnippetController2.get(this._editor)?.isInSnippet()) {
                // no quick suggestion when in snippet mode
                return;
            }
            this.cancel();
            this._triggerQuickSuggest.cancelAndSet(() => {
                if (this._triggerState !== undefined) {
                    return;
                }
                if (!LineContext.shouldAutoTrigger(this._editor)) {
                    return;
                }
                if (!this._editor.hasModel() || !this._editor.hasWidgetFocus()) {
                    return;
                }
                const model = this._editor.getModel();
                const pos = this._editor.getPosition();
                // validate enabled now
                const config = this._editor.getOption(90 /* EditorOption.quickSuggestions */);
                if (suggest_1.QuickSuggestionsOptions.isAllOff(config)) {
                    return;
                }
                if (!suggest_1.QuickSuggestionsOptions.isAllOn(config)) {
                    // Check the type of the token that triggered this
                    model.tokenization.tokenizeIfCheap(pos.lineNumber);
                    const lineTokens = model.tokenization.getLineTokens(pos.lineNumber);
                    const tokenType = lineTokens.getStandardTokenType(lineTokens.findTokenIndexAtOffset(Math.max(pos.column - 1 - 1, 0)));
                    if (suggest_1.QuickSuggestionsOptions.valueFor(config, tokenType) !== 'on') {
                        return;
                    }
                }
                if (!canShowQuickSuggest(this._editor, this._contextKeyService, this._configurationService)) {
                    // do not trigger quick suggestions if inline suggestions are shown
                    return;
                }
                if (!this._languageFeaturesService.completionProvider.has(model)) {
                    return;
                }
                // we made it till here -> trigger now
                this.trigger({ auto: true });
            }, this._editor.getOption(91 /* EditorOption.quickSuggestionsDelay */));
        }
        _refilterCompletionItems() {
            (0, types_1.assertType)(this._editor.hasModel());
            (0, types_1.assertType)(this._triggerState !== undefined);
            const model = this._editor.getModel();
            const position = this._editor.getPosition();
            const ctx = new LineContext(model, position, { ...this._triggerState, refilter: true });
            this._onNewContext(ctx);
        }
        trigger(options) {
            if (!this._editor.hasModel()) {
                return;
            }
            const model = this._editor.getModel();
            const ctx = new LineContext(model, this._editor.getPosition(), options);
            // Cancel previous requests, change state & update UI
            this.cancel(options.retrigger);
            this._triggerState = options;
            this._onDidTrigger.fire({ auto: options.auto, shy: options.shy ?? false, position: this._editor.getPosition() });
            // Capture context when request was sent
            this._context = ctx;
            // Build context for request
            let suggestCtx = { triggerKind: options.triggerKind ?? 0 /* CompletionTriggerKind.Invoke */ };
            if (options.triggerCharacter) {
                suggestCtx = {
                    triggerKind: 1 /* CompletionTriggerKind.TriggerCharacter */,
                    triggerCharacter: options.triggerCharacter
                };
            }
            this._requestToken = new cancellation_1.CancellationTokenSource();
            // kind filter and snippet sort rules
            const snippetSuggestions = this._editor.getOption(113 /* EditorOption.snippetSuggestions */);
            let snippetSortOrder = 1 /* SnippetSortOrder.Inline */;
            switch (snippetSuggestions) {
                case 'top':
                    snippetSortOrder = 0 /* SnippetSortOrder.Top */;
                    break;
                // 	↓ that's the default anyways...
                // case 'inline':
                // 	snippetSortOrder = SnippetSortOrder.Inline;
                // 	break;
                case 'bottom':
                    snippetSortOrder = 2 /* SnippetSortOrder.Bottom */;
                    break;
            }
            const { itemKind: itemKindFilter, showDeprecated } = SuggestModel_1.createSuggestFilter(this._editor);
            const completionOptions = new suggest_1.CompletionOptions(snippetSortOrder, options.completionOptions?.kindFilter ?? itemKindFilter, options.completionOptions?.providerFilter, options.completionOptions?.providerItemsToReuse, showDeprecated);
            const wordDistance = wordDistance_1.WordDistance.create(this._editorWorkerService, this._editor);
            const completions = (0, suggest_1.provideSuggestionItems)(this._languageFeaturesService.completionProvider, model, this._editor.getPosition(), completionOptions, suggestCtx, this._requestToken.token);
            Promise.all([completions, wordDistance]).then(async ([completions, wordDistance]) => {
                this._requestToken?.dispose();
                if (!this._editor.hasModel()) {
                    return;
                }
                let clipboardText = options?.clipboardText;
                if (!clipboardText && completions.needsClipboard) {
                    clipboardText = await this._clipboardService.readText();
                }
                if (this._triggerState === undefined) {
                    return;
                }
                const model = this._editor.getModel();
                // const items = completions.items;
                // if (existing) {
                // 	const cmpFn = getSuggestionComparator(snippetSortOrder);
                // 	items = items.concat(existing.items).sort(cmpFn);
                // }
                const ctx = new LineContext(model, this._editor.getPosition(), options);
                const fuzzySearchOptions = {
                    ...filters_1.FuzzyScoreOptions.default,
                    firstMatchCanBeWeak: !this._editor.getOption(119 /* EditorOption.suggest */).matchOnWordStartOnly
                };
                this._completionModel = new completionModel_1.CompletionModel(completions.items, this._context.column, {
                    leadingLineContent: ctx.leadingLineContent,
                    characterCountDelta: ctx.column - this._context.column
                }, wordDistance, this._editor.getOption(119 /* EditorOption.suggest */), this._editor.getOption(113 /* EditorOption.snippetSuggestions */), fuzzySearchOptions, clipboardText);
                // store containers so that they can be disposed later
                this._completionDisposables.add(completions.disposable);
                this._onNewContext(ctx);
                // finally report telemetry about durations
                this._reportDurationsTelemetry(completions.durations);
                // report invalid completions by source
                if (!this._envService.isBuilt || this._envService.isExtensionDevelopment) {
                    for (const item of completions.items) {
                        if (item.isInvalid) {
                            this._logService.warn(`[suggest] did IGNORE invalid completion item from ${item.provider._debugDisplayName}`, item.completion);
                        }
                    }
                }
            }).catch(errors_1.onUnexpectedError);
        }
        _reportDurationsTelemetry(durations) {
            if (this._telemetryGate++ % 230 !== 0) {
                return;
            }
            setTimeout(() => {
                this._telemetryService.publicLog2('suggest.durations.json', { data: JSON.stringify(durations) });
                this._logService.debug('suggest.durations.json', durations);
            });
        }
        static createSuggestFilter(editor) {
            // kind filter and snippet sort rules
            const result = new Set();
            // snippet setting
            const snippetSuggestions = editor.getOption(113 /* EditorOption.snippetSuggestions */);
            if (snippetSuggestions === 'none') {
                result.add(27 /* CompletionItemKind.Snippet */);
            }
            // type setting
            const suggestOptions = editor.getOption(119 /* EditorOption.suggest */);
            if (!suggestOptions.showMethods) {
                result.add(0 /* CompletionItemKind.Method */);
            }
            if (!suggestOptions.showFunctions) {
                result.add(1 /* CompletionItemKind.Function */);
            }
            if (!suggestOptions.showConstructors) {
                result.add(2 /* CompletionItemKind.Constructor */);
            }
            if (!suggestOptions.showFields) {
                result.add(3 /* CompletionItemKind.Field */);
            }
            if (!suggestOptions.showVariables) {
                result.add(4 /* CompletionItemKind.Variable */);
            }
            if (!suggestOptions.showClasses) {
                result.add(5 /* CompletionItemKind.Class */);
            }
            if (!suggestOptions.showStructs) {
                result.add(6 /* CompletionItemKind.Struct */);
            }
            if (!suggestOptions.showInterfaces) {
                result.add(7 /* CompletionItemKind.Interface */);
            }
            if (!suggestOptions.showModules) {
                result.add(8 /* CompletionItemKind.Module */);
            }
            if (!suggestOptions.showProperties) {
                result.add(9 /* CompletionItemKind.Property */);
            }
            if (!suggestOptions.showEvents) {
                result.add(10 /* CompletionItemKind.Event */);
            }
            if (!suggestOptions.showOperators) {
                result.add(11 /* CompletionItemKind.Operator */);
            }
            if (!suggestOptions.showUnits) {
                result.add(12 /* CompletionItemKind.Unit */);
            }
            if (!suggestOptions.showValues) {
                result.add(13 /* CompletionItemKind.Value */);
            }
            if (!suggestOptions.showConstants) {
                result.add(14 /* CompletionItemKind.Constant */);
            }
            if (!suggestOptions.showEnums) {
                result.add(15 /* CompletionItemKind.Enum */);
            }
            if (!suggestOptions.showEnumMembers) {
                result.add(16 /* CompletionItemKind.EnumMember */);
            }
            if (!suggestOptions.showKeywords) {
                result.add(17 /* CompletionItemKind.Keyword */);
            }
            if (!suggestOptions.showWords) {
                result.add(18 /* CompletionItemKind.Text */);
            }
            if (!suggestOptions.showColors) {
                result.add(19 /* CompletionItemKind.Color */);
            }
            if (!suggestOptions.showFiles) {
                result.add(20 /* CompletionItemKind.File */);
            }
            if (!suggestOptions.showReferences) {
                result.add(21 /* CompletionItemKind.Reference */);
            }
            if (!suggestOptions.showColors) {
                result.add(22 /* CompletionItemKind.Customcolor */);
            }
            if (!suggestOptions.showFolders) {
                result.add(23 /* CompletionItemKind.Folder */);
            }
            if (!suggestOptions.showTypeParameters) {
                result.add(24 /* CompletionItemKind.TypeParameter */);
            }
            if (!suggestOptions.showSnippets) {
                result.add(27 /* CompletionItemKind.Snippet */);
            }
            if (!suggestOptions.showUsers) {
                result.add(25 /* CompletionItemKind.User */);
            }
            if (!suggestOptions.showIssues) {
                result.add(26 /* CompletionItemKind.Issue */);
            }
            return { itemKind: result, showDeprecated: suggestOptions.showDeprecated };
        }
        _onNewContext(ctx) {
            if (!this._context) {
                // happens when 24x7 IntelliSense is enabled and still in its delay
                return;
            }
            if (ctx.lineNumber !== this._context.lineNumber) {
                // e.g. happens when pressing Enter while IntelliSense is computed
                this.cancel();
                return;
            }
            if ((0, strings_1.getLeadingWhitespace)(ctx.leadingLineContent) !== (0, strings_1.getLeadingWhitespace)(this._context.leadingLineContent)) {
                // cancel IntelliSense when line start changes
                // happens when the current word gets outdented
                this.cancel();
                return;
            }
            if (ctx.column < this._context.column) {
                // typed -> moved cursor LEFT -> retrigger if still on a word
                if (ctx.leadingWord.word) {
                    this.trigger({ auto: this._context.triggerOptions.auto, retrigger: true });
                }
                else {
                    this.cancel();
                }
                return;
            }
            if (!this._completionModel) {
                // happens when IntelliSense is not yet computed
                return;
            }
            if (ctx.leadingWord.word.length !== 0 && ctx.leadingWord.startColumn > this._context.leadingWord.startColumn) {
                // started a new word while IntelliSense shows -> retrigger but reuse all items that we currently have
                const shouldAutoTrigger = LineContext.shouldAutoTrigger(this._editor);
                if (shouldAutoTrigger && this._context) {
                    // shouldAutoTrigger forces tokenization, which can cause pending cursor change events to be emitted, which can cause
                    // suggestions to be cancelled, which causes `this._context` to be undefined
                    const map = this._completionModel.getItemsByProvider();
                    this.trigger({
                        auto: this._context.triggerOptions.auto,
                        retrigger: true,
                        clipboardText: this._completionModel.clipboardText,
                        completionOptions: { providerItemsToReuse: map }
                    });
                }
                return;
            }
            if (ctx.column > this._context.column && this._completionModel.getIncompleteProvider().size > 0 && ctx.leadingWord.word.length !== 0) {
                // typed -> moved cursor RIGHT & incomple model & still on a word -> retrigger
                const providerItemsToReuse = new Map();
                const providerFilter = new Set();
                for (const [provider, items] of this._completionModel.getItemsByProvider()) {
                    if (items.length > 0 && items[0].container.incomplete) {
                        providerFilter.add(provider);
                    }
                    else {
                        providerItemsToReuse.set(provider, items);
                    }
                }
                this.trigger({
                    auto: this._context.triggerOptions.auto,
                    triggerKind: 2 /* CompletionTriggerKind.TriggerForIncompleteCompletions */,
                    retrigger: true,
                    clipboardText: this._completionModel.clipboardText,
                    completionOptions: { providerFilter, providerItemsToReuse }
                });
            }
            else {
                // typed -> moved cursor RIGHT -> update UI
                const oldLineContext = this._completionModel.lineContext;
                let isFrozen = false;
                this._completionModel.lineContext = {
                    leadingLineContent: ctx.leadingLineContent,
                    characterCountDelta: ctx.column - this._context.column
                };
                if (this._completionModel.items.length === 0) {
                    const shouldAutoTrigger = LineContext.shouldAutoTrigger(this._editor);
                    if (!this._context) {
                        // shouldAutoTrigger forces tokenization, which can cause pending cursor change events to be emitted, which can cause
                        // suggestions to be cancelled, which causes `this._context` to be undefined
                        this.cancel();
                        return;
                    }
                    if (shouldAutoTrigger && this._context.leadingWord.endColumn < ctx.leadingWord.startColumn) {
                        // retrigger when heading into a new word
                        this.trigger({ auto: this._context.triggerOptions.auto, retrigger: true });
                        return;
                    }
                    if (!this._context.triggerOptions.auto) {
                        // freeze when IntelliSense was manually requested
                        this._completionModel.lineContext = oldLineContext;
                        isFrozen = this._completionModel.items.length > 0;
                        if (isFrozen && ctx.leadingWord.word.length === 0) {
                            // there were results before but now there aren't
                            // and also we are not on a word anymore -> cancel
                            this.cancel();
                            return;
                        }
                    }
                    else {
                        // nothing left
                        this.cancel();
                        return;
                    }
                }
                this._onDidSuggest.fire({
                    completionModel: this._completionModel,
                    triggerOptions: ctx.triggerOptions,
                    isFrozen,
                });
            }
        }
    };
    exports.SuggestModel = SuggestModel;
    exports.SuggestModel = SuggestModel = SuggestModel_1 = __decorate([
        __param(1, editorWorker_1.IEditorWorkerService),
        __param(2, clipboardService_1.IClipboardService),
        __param(3, telemetry_1.ITelemetryService),
        __param(4, log_1.ILogService),
        __param(5, contextkey_1.IContextKeyService),
        __param(6, configuration_1.IConfigurationService),
        __param(7, languageFeatures_1.ILanguageFeaturesService),
        __param(8, environment_1.IEnvironmentService)
    ], SuggestModel);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[294/*vs/editor/contrib/suggest/browser/suggestController*/], __M([1/*require*/,0/*exports*/,46/*vs/base/browser/ui/aria/aria*/,13/*vs/base/common/arrays*/,18/*vs/base/common/cancellation*/,8/*vs/base/common/errors*/,6/*vs/base/common/event*/,140/*vs/base/common/keybindings*/,2/*vs/base/common/lifecycle*/,16/*vs/base/common/platform*/,54/*vs/base/common/stopwatch*/,19/*vs/base/common/types*/,143/*vs/editor/browser/stableEditorScroll*/,15/*vs/editor/browser/editorExtensions*/,75/*vs/editor/common/core/editOperation*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/,20/*vs/editor/common/editorContextKeys*/,221/*vs/editor/contrib/snippet/browser/snippetController2*/,135/*vs/editor/contrib/snippet/browser/snippetParser*/,405/*vs/editor/contrib/suggest/browser/suggestMemory*/,685/*vs/editor/contrib/suggest/browser/wordContextKey*/,3/*vs/nls*/,24/*vs/platform/commands/common/commands*/,12/*vs/platform/contextkey/common/contextkey*/,7/*vs/platform/instantiation/common/instantiation*/,62/*vs/platform/log/common/log*/,155/*vs/editor/contrib/suggest/browser/suggest*/,684/*vs/editor/contrib/suggest/browser/suggestAlternatives*/,622/*vs/editor/contrib/suggest/browser/suggestCommitCharacters*/,437/*vs/editor/contrib/suggest/browser/suggestModel*/,623/*vs/editor/contrib/suggest/browser/suggestOvertypingCapturer*/,839/*vs/editor/contrib/suggest/browser/suggestWidget*/,63/*vs/platform/telemetry/common/telemetry*/,48/*vs/base/common/resources*/,129/*vs/base/common/hash*/,5/*vs/base/browser/dom*/,35/*vs/editor/common/model/textModel*/]), function (require, exports, aria_1, arrays_1, cancellation_1, errors_1, event_1, keybindings_1, lifecycle_1, platform, stopwatch_1, types_1, stableEditorScroll_1, editorExtensions_1, editOperation_1, position_1, range_1, editorContextKeys_1, snippetController2_1, snippetParser_1, suggestMemory_1, wordContextKey_1, nls, commands_1, contextkey_1, instantiation_1, log_1, suggest_1, suggestAlternatives_1, suggestCommitCharacters_1, suggestModel_1, suggestOvertypingCapturer_1, suggestWidget_1, telemetry_1, resources_1, hash_1, dom_1, textModel_1) {
    "use strict";
    var SuggestController_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.TriggerSuggestAction = exports.SuggestController = void 0;
    // sticky suggest widget which doesn't disappear on focus out and such
    const _sticky = false;
    class LineSuffix {
        constructor(_model, _position) {
            this._model = _model;
            this._position = _position;
            this._decorationOptions = textModel_1.ModelDecorationOptions.register({
                description: 'suggest-line-suffix',
                stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */
            });
            // spy on what's happening right of the cursor. two cases:
            // 1. end of line -> check that it's still end of line
            // 2. mid of line -> add a marker and compute the delta
            const maxColumn = _model.getLineMaxColumn(_position.lineNumber);
            if (maxColumn !== _position.column) {
                const offset = _model.getOffsetAt(_position);
                const end = _model.getPositionAt(offset + 1);
                _model.changeDecorations(accessor => {
                    if (this._marker) {
                        accessor.removeDecoration(this._marker);
                    }
                    this._marker = accessor.addDecoration(range_1.Range.fromPositions(_position, end), this._decorationOptions);
                });
            }
        }
        dispose() {
            if (this._marker && !this._model.isDisposed()) {
                this._model.changeDecorations(accessor => {
                    accessor.removeDecoration(this._marker);
                    this._marker = undefined;
                });
            }
        }
        delta(position) {
            if (this._model.isDisposed() || this._position.lineNumber !== position.lineNumber) {
                // bail out early if things seems fishy
                return 0;
            }
            // read the marker (in case suggest was triggered at line end) or compare
            // the cursor to the line end.
            if (this._marker) {
                const range = this._model.getDecorationRange(this._marker);
                const end = this._model.getOffsetAt(range.getStartPosition());
                return end - this._model.getOffsetAt(position);
            }
            else {
                return this._model.getLineMaxColumn(position.lineNumber) - position.column;
            }
        }
    }
    let SuggestController = class SuggestController {
        static { SuggestController_1 = this; }
        static { this.ID = 'editor.contrib.suggestController'; }
        static get(editor) {
            return editor.getContribution(SuggestController_1.ID);
        }
        constructor(editor, _memoryService, _commandService, _contextKeyService, _instantiationService, _logService, _telemetryService) {
            this._memoryService = _memoryService;
            this._commandService = _commandService;
            this._contextKeyService = _contextKeyService;
            this._instantiationService = _instantiationService;
            this._logService = _logService;
            this._telemetryService = _telemetryService;
            this._lineSuffix = new lifecycle_1.MutableDisposable();
            this._toDispose = new lifecycle_1.DisposableStore();
            this._selectors = new PriorityRegistry(s => s.priority);
            this._onWillInsertSuggestItem = new event_1.Emitter();
            this.onWillInsertSuggestItem = this._onWillInsertSuggestItem.event;
            this.editor = editor;
            this.model = _instantiationService.createInstance(suggestModel_1.SuggestModel, this.editor);
            // default selector
            this._selectors.register({
                priority: 0,
                select: (model, pos, items) => this._memoryService.select(model, pos, items)
            });
            // context key: update insert/replace mode
            const ctxInsertMode = suggest_1.Context.InsertMode.bindTo(_contextKeyService);
            ctxInsertMode.set(editor.getOption(119 /* EditorOption.suggest */).insertMode);
            this._toDispose.add(this.model.onDidTrigger(() => ctxInsertMode.set(editor.getOption(119 /* EditorOption.suggest */).insertMode)));
            this.widget = this._toDispose.add(new dom_1.WindowIdleValue((0, dom_1.getWindow)(editor.getDomNode()), () => {
                const widget = this._instantiationService.createInstance(suggestWidget_1.SuggestWidget, this.editor);
                this._toDispose.add(widget);
                this._toDispose.add(widget.onDidSelect(item => this._insertSuggestion(item, 0 /* InsertFlags.None */), this));
                // Wire up logic to accept a suggestion on certain characters
                const commitCharacterController = new suggestCommitCharacters_1.CommitCharacterController(this.editor, widget, this.model, item => this._insertSuggestion(item, 2 /* InsertFlags.NoAfterUndoStop */));
                this._toDispose.add(commitCharacterController);
                // Wire up makes text edit context key
                const ctxMakesTextEdit = suggest_1.Context.MakesTextEdit.bindTo(this._contextKeyService);
                const ctxHasInsertAndReplace = suggest_1.Context.HasInsertAndReplaceRange.bindTo(this._contextKeyService);
                const ctxCanResolve = suggest_1.Context.CanResolve.bindTo(this._contextKeyService);
                this._toDispose.add((0, lifecycle_1.toDisposable)(() => {
                    ctxMakesTextEdit.reset();
                    ctxHasInsertAndReplace.reset();
                    ctxCanResolve.reset();
                }));
                this._toDispose.add(widget.onDidFocus(({ item }) => {
                    // (ctx: makesTextEdit)
                    const position = this.editor.getPosition();
                    const startColumn = item.editStart.column;
                    const endColumn = position.column;
                    let value = true;
                    if (this.editor.getOption(1 /* EditorOption.acceptSuggestionOnEnter */) === 'smart'
                        && this.model.state === 2 /* State.Auto */
                        && !item.completion.additionalTextEdits
                        && !(item.completion.insertTextRules & 4 /* CompletionItemInsertTextRule.InsertAsSnippet */)
                        && endColumn - startColumn === item.completion.insertText.length) {
                        const oldText = this.editor.getModel().getValueInRange({
                            startLineNumber: position.lineNumber,
                            startColumn,
                            endLineNumber: position.lineNumber,
                            endColumn
                        });
                        value = oldText !== item.completion.insertText;
                    }
                    ctxMakesTextEdit.set(value);
                    // (ctx: hasInsertAndReplaceRange)
                    ctxHasInsertAndReplace.set(!position_1.Position.equals(item.editInsertEnd, item.editReplaceEnd));
                    // (ctx: canResolve)
                    ctxCanResolve.set(Boolean(item.provider.resolveCompletionItem) || Boolean(item.completion.documentation) || item.completion.detail !== item.completion.label);
                }));
                this._toDispose.add(widget.onDetailsKeyDown(e => {
                    // cmd + c on macOS, ctrl + c on Win / Linux
                    if (e.toKeyCodeChord().equals(new keybindings_1.KeyCodeChord(true, false, false, false, 33 /* KeyCode.KeyC */)) ||
                        (platform.isMacintosh && e.toKeyCodeChord().equals(new keybindings_1.KeyCodeChord(false, false, false, true, 33 /* KeyCode.KeyC */)))) {
                        e.stopPropagation();
                        return;
                    }
                    if (!e.toKeyCodeChord().isModifierKey()) {
                        this.editor.focus();
                    }
                }));
                return widget;
            }));
            // Wire up text overtyping capture
            this._overtypingCapturer = this._toDispose.add(new dom_1.WindowIdleValue((0, dom_1.getWindow)(editor.getDomNode()), () => {
                return this._toDispose.add(new suggestOvertypingCapturer_1.OvertypingCapturer(this.editor, this.model));
            }));
            this._alternatives = this._toDispose.add(new dom_1.WindowIdleValue((0, dom_1.getWindow)(editor.getDomNode()), () => {
                return this._toDispose.add(new suggestAlternatives_1.SuggestAlternatives(this.editor, this._contextKeyService));
            }));
            this._toDispose.add(_instantiationService.createInstance(wordContextKey_1.WordContextKey, editor));
            this._toDispose.add(this.model.onDidTrigger(e => {
                this.widget.value.showTriggered(e.auto, e.shy ? 250 : 50);
                this._lineSuffix.value = new LineSuffix(this.editor.getModel(), e.position);
            }));
            this._toDispose.add(this.model.onDidSuggest(e => {
                if (e.triggerOptions.shy) {
                    return;
                }
                let index = -1;
                for (const selector of this._selectors.itemsOrderedByPriorityDesc) {
                    index = selector.select(this.editor.getModel(), this.editor.getPosition(), e.completionModel.items);
                    if (index !== -1) {
                        break;
                    }
                }
                if (index === -1) {
                    index = 0;
                }
                if (this.model.state === 0 /* State.Idle */) {
                    // selecting an item can "pump" out selection/cursor change events
                    // which can cancel suggest halfway through this function. therefore
                    // we need to check again and bail if the session has been canceled
                    return;
                }
                let noFocus = false;
                if (e.triggerOptions.auto) {
                    // don't "focus" item when configured to do
                    const options = this.editor.getOption(119 /* EditorOption.suggest */);
                    if (options.selectionMode === 'never' || options.selectionMode === 'always') {
                        // simple: always or never
                        noFocus = options.selectionMode === 'never';
                    }
                    else if (options.selectionMode === 'whenTriggerCharacter') {
                        // on with trigger character
                        noFocus = e.triggerOptions.triggerKind !== 1 /* CompletionTriggerKind.TriggerCharacter */;
                    }
                    else if (options.selectionMode === 'whenQuickSuggestion') {
                        // without trigger character or when refiltering
                        noFocus = e.triggerOptions.triggerKind === 1 /* CompletionTriggerKind.TriggerCharacter */ && !e.triggerOptions.refilter;
                    }
                }
                this.widget.value.showSuggestions(e.completionModel, index, e.isFrozen, e.triggerOptions.auto, noFocus);
            }));
            this._toDispose.add(this.model.onDidCancel(e => {
                if (!e.retrigger) {
                    this.widget.value.hideWidget();
                }
            }));
            this._toDispose.add(this.editor.onDidBlurEditorWidget(() => {
                if (!_sticky) {
                    this.model.cancel();
                    this.model.clear();
                }
            }));
            // Manage the acceptSuggestionsOnEnter context key
            const acceptSuggestionsOnEnter = suggest_1.Context.AcceptSuggestionsOnEnter.bindTo(_contextKeyService);
            const updateFromConfig = () => {
                const acceptSuggestionOnEnter = this.editor.getOption(1 /* EditorOption.acceptSuggestionOnEnter */);
                acceptSuggestionsOnEnter.set(acceptSuggestionOnEnter === 'on' || acceptSuggestionOnEnter === 'smart');
            };
            this._toDispose.add(this.editor.onDidChangeConfiguration(() => updateFromConfig()));
            updateFromConfig();
        }
        dispose() {
            this._alternatives.dispose();
            this._toDispose.dispose();
            this.widget.dispose();
            this.model.dispose();
            this._lineSuffix.dispose();
            this._onWillInsertSuggestItem.dispose();
        }
        _insertSuggestion(event, flags) {
            if (!event || !event.item) {
                this._alternatives.value.reset();
                this.model.cancel();
                this.model.clear();
                return;
            }
            if (!this.editor.hasModel()) {
                return;
            }
            const snippetController = snippetController2_1.SnippetController2.get(this.editor);
            if (!snippetController) {
                return;
            }
            this._onWillInsertSuggestItem.fire({ item: event.item });
            const model = this.editor.getModel();
            const modelVersionNow = model.getAlternativeVersionId();
            const { item } = event;
            //
            const tasks = [];
            const cts = new cancellation_1.CancellationTokenSource();
            // pushing undo stops *before* additional text edits and
            // *after* the main edit
            if (!(flags & 1 /* InsertFlags.NoBeforeUndoStop */)) {
                this.editor.pushUndoStop();
            }
            // compute overwrite[Before|After] deltas BEFORE applying extra edits
            const info = this.getOverwriteInfo(item, Boolean(flags & 8 /* InsertFlags.AlternativeOverwriteConfig */));
            // keep item in memory
            this._memoryService.memorize(model, this.editor.getPosition(), item);
            const isResolved = item.isResolved;
            // telemetry data points: duration of command execution, info about async additional edits (-1=n/a, -2=none, 1=success, 0=failed)
            let _commandExectionDuration = -1;
            let _additionalEditsAppliedAsync = -1;
            if (Array.isArray(item.completion.additionalTextEdits)) {
                // cancel -> stops all listening and closes widget
                this.model.cancel();
                // sync additional edits
                const scrollState = stableEditorScroll_1.StableEditorScrollState.capture(this.editor);
                this.editor.executeEdits('suggestController.additionalTextEdits.sync', item.completion.additionalTextEdits.map(edit => {
                    let range = range_1.Range.lift(edit.range);
                    if (range.startLineNumber === item.position.lineNumber && range.startColumn > item.position.column) {
                        // shift additional edit when it is "after" the completion insertion position
                        const columnDelta = this.editor.getPosition().column - item.position.column;
                        const startColumnDelta = columnDelta;
                        const endColumnDelta = range_1.Range.spansMultipleLines(range) ? 0 : columnDelta;
                        range = new range_1.Range(range.startLineNumber, range.startColumn + startColumnDelta, range.endLineNumber, range.endColumn + endColumnDelta);
                    }
                    return editOperation_1.EditOperation.replaceMove(range, edit.text);
                }));
                scrollState.restoreRelativeVerticalPositionOfCursor(this.editor);
            }
            else if (!isResolved) {
                // async additional edits
                const sw = new stopwatch_1.StopWatch();
                let position;
                const docListener = model.onDidChangeContent(e => {
                    if (e.isFlush) {
                        cts.cancel();
                        docListener.dispose();
                        return;
                    }
                    for (const change of e.changes) {
                        const thisPosition = range_1.Range.getEndPosition(change.range);
                        if (!position || position_1.Position.isBefore(thisPosition, position)) {
                            position = thisPosition;
                        }
                    }
                });
                const oldFlags = flags;
                flags |= 2 /* InsertFlags.NoAfterUndoStop */;
                let didType = false;
                const typeListener = this.editor.onWillType(() => {
                    typeListener.dispose();
                    didType = true;
                    if (!(oldFlags & 2 /* InsertFlags.NoAfterUndoStop */)) {
                        this.editor.pushUndoStop();
                    }
                });
                tasks.push(item.resolve(cts.token).then(() => {
                    if (!item.completion.additionalTextEdits || cts.token.isCancellationRequested) {
                        return undefined;
                    }
                    if (position && item.completion.additionalTextEdits.some(edit => position_1.Position.isBefore(position, range_1.Range.getStartPosition(edit.range)))) {
                        return false;
                    }
                    if (didType) {
                        this.editor.pushUndoStop();
                    }
                    const scrollState = stableEditorScroll_1.StableEditorScrollState.capture(this.editor);
                    this.editor.executeEdits('suggestController.additionalTextEdits.async', item.completion.additionalTextEdits.map(edit => editOperation_1.EditOperation.replaceMove(range_1.Range.lift(edit.range), edit.text)));
                    scrollState.restoreRelativeVerticalPositionOfCursor(this.editor);
                    if (didType || !(oldFlags & 2 /* InsertFlags.NoAfterUndoStop */)) {
                        this.editor.pushUndoStop();
                    }
                    return true;
                }).then(applied => {
                    this._logService.trace('[suggest] async resolving of edits DONE (ms, applied?)', sw.elapsed(), applied);
                    _additionalEditsAppliedAsync = applied === true ? 1 : applied === false ? 0 : -2;
                }).finally(() => {
                    docListener.dispose();
                    typeListener.dispose();
                }));
            }
            let { insertText } = item.completion;
            if (!(item.completion.insertTextRules & 4 /* CompletionItemInsertTextRule.InsertAsSnippet */)) {
                insertText = snippetParser_1.SnippetParser.escape(insertText);
            }
            // cancel -> stops all listening and closes widget
            this.model.cancel();
            snippetController.insert(insertText, {
                overwriteBefore: info.overwriteBefore,
                overwriteAfter: info.overwriteAfter,
                undoStopBefore: false,
                undoStopAfter: false,
                adjustWhitespace: !(item.completion.insertTextRules & 1 /* CompletionItemInsertTextRule.KeepWhitespace */),
                clipboardText: event.model.clipboardText,
                overtypingCapturer: this._overtypingCapturer.value
            });
            if (!(flags & 2 /* InsertFlags.NoAfterUndoStop */)) {
                this.editor.pushUndoStop();
            }
            if (item.completion.command) {
                if (item.completion.command.id === TriggerSuggestAction.id) {
                    // retigger
                    this.model.trigger({ auto: true, retrigger: true });
                }
                else {
                    // exec command, done
                    const sw = new stopwatch_1.StopWatch();
                    tasks.push(this._commandService.executeCommand(item.completion.command.id, ...(item.completion.command.arguments ? [...item.completion.command.arguments] : [])).catch(e => {
                        if (item.completion.extensionId) {
                            (0, errors_1.onUnexpectedExternalError)(e);
                        }
                        else {
                            (0, errors_1.onUnexpectedError)(e);
                        }
                    }).finally(() => {
                        _commandExectionDuration = sw.elapsed();
                    }));
                }
            }
            if (flags & 4 /* InsertFlags.KeepAlternativeSuggestions */) {
                this._alternatives.value.set(event, next => {
                    // cancel resolving of additional edits
                    cts.cancel();
                    // this is not so pretty. when inserting the 'next'
                    // suggestion we undo until we are at the state at
                    // which we were before inserting the previous suggestion...
                    while (model.canUndo()) {
                        if (modelVersionNow !== model.getAlternativeVersionId()) {
                            model.undo();
                        }
                        this._insertSuggestion(next, 1 /* InsertFlags.NoBeforeUndoStop */ | 2 /* InsertFlags.NoAfterUndoStop */ | (flags & 8 /* InsertFlags.AlternativeOverwriteConfig */ ? 8 /* InsertFlags.AlternativeOverwriteConfig */ : 0));
                        break;
                    }
                });
            }
            this._alertCompletionItem(item);
            // clear only now - after all tasks are done
            Promise.all(tasks).finally(() => {
                this._reportSuggestionAcceptedTelemetry(item, model, isResolved, _commandExectionDuration, _additionalEditsAppliedAsync, event.index, event.model.items);
                this.model.clear();
                cts.dispose();
            });
        }
        _reportSuggestionAcceptedTelemetry(item, model, itemResolved, commandExectionDuration, additionalEditsAppliedAsync, index, completionItems) {
            if (Math.floor(Math.random() * 100) === 0) {
                // throttle telemetry event because accepting completions happens a lot
                return;
            }
            const labelMap = new Map();
            for (let i = 0; i < Math.min(30, completionItems.length); i++) {
                const label = completionItems[i].textLabel;
                if (labelMap.has(label)) {
                    labelMap.get(label).push(i);
                }
                else {
                    labelMap.set(label, [i]);
                }
            }
            const firstIndexArray = labelMap.get(item.textLabel);
            const hasDuplicates = firstIndexArray && firstIndexArray.length > 1;
            const firstIndex = hasDuplicates ? firstIndexArray[0] : -1;
            this._telemetryService.publicLog2('suggest.acceptedSuggestion', {
                extensionId: item.extensionId?.value ?? 'unknown',
                providerId: item.provider._debugDisplayName ?? 'unknown',
                kind: item.completion.kind,
                basenameHash: (0, hash_1.hash)((0, resources_1.basename)(model.uri)).toString(16),
                languageId: model.getLanguageId(),
                fileExtension: (0, resources_1.extname)(model.uri),
                resolveInfo: !item.provider.resolveCompletionItem ? -1 : itemResolved ? 1 : 0,
                resolveDuration: item.resolveDuration,
                commandDuration: commandExectionDuration,
                additionalEditsAsync: additionalEditsAppliedAsync,
                index,
                firstIndex,
            });
        }
        getOverwriteInfo(item, toggleMode) {
            (0, types_1.assertType)(this.editor.hasModel());
            let replace = this.editor.getOption(119 /* EditorOption.suggest */).insertMode === 'replace';
            if (toggleMode) {
                replace = !replace;
            }
            const overwriteBefore = item.position.column - item.editStart.column;
            const overwriteAfter = (replace ? item.editReplaceEnd.column : item.editInsertEnd.column) - item.position.column;
            const columnDelta = this.editor.getPosition().column - item.position.column;
            const suffixDelta = this._lineSuffix.value ? this._lineSuffix.value.delta(this.editor.getPosition()) : 0;
            return {
                overwriteBefore: overwriteBefore + columnDelta,
                overwriteAfter: overwriteAfter + suffixDelta
            };
        }
        _alertCompletionItem(item) {
            if ((0, arrays_1.isNonEmptyArray)(item.completion.additionalTextEdits)) {
                const msg = nls.localize(1318, "Accepting '{0}' made {1} additional edits", item.textLabel, item.completion.additionalTextEdits.length);
                (0, aria_1.alert)(msg);
            }
        }
        triggerSuggest(onlyFrom, auto, noFilter) {
            if (this.editor.hasModel()) {
                this.model.trigger({
                    auto: auto ?? false,
                    completionOptions: { providerFilter: onlyFrom, kindFilter: noFilter ? new Set() : undefined }
                });
                this.editor.revealPosition(this.editor.getPosition(), 0 /* ScrollType.Smooth */);
                this.editor.focus();
            }
        }
        triggerSuggestAndAcceptBest(arg) {
            if (!this.editor.hasModel()) {
                return;
            }
            const positionNow = this.editor.getPosition();
            const fallback = () => {
                if (positionNow.equals(this.editor.getPosition())) {
                    this._commandService.executeCommand(arg.fallback);
                }
            };
            const makesTextEdit = (item) => {
                if (item.completion.insertTextRules & 4 /* CompletionItemInsertTextRule.InsertAsSnippet */ || item.completion.additionalTextEdits) {
                    // snippet, other editor -> makes edit
                    return true;
                }
                const position = this.editor.getPosition();
                const startColumn = item.editStart.column;
                const endColumn = position.column;
                if (endColumn - startColumn !== item.completion.insertText.length) {
                    // unequal lengths -> makes edit
                    return true;
                }
                const textNow = this.editor.getModel().getValueInRange({
                    startLineNumber: position.lineNumber,
                    startColumn,
                    endLineNumber: position.lineNumber,
                    endColumn
                });
                // unequal text -> makes edit
                return textNow !== item.completion.insertText;
            };
            event_1.Event.once(this.model.onDidTrigger)(_ => {
                // wait for trigger because only then the cancel-event is trustworthy
                const listener = [];
                event_1.Event.any(this.model.onDidTrigger, this.model.onDidCancel)(() => {
                    // retrigger or cancel -> try to type default text
                    (0, lifecycle_1.dispose)(listener);
                    fallback();
                }, undefined, listener);
                this.model.onDidSuggest(({ completionModel }) => {
                    (0, lifecycle_1.dispose)(listener);
                    if (completionModel.items.length === 0) {
                        fallback();
                        return;
                    }
                    const index = this._memoryService.select(this.editor.getModel(), this.editor.getPosition(), completionModel.items);
                    const item = completionModel.items[index];
                    if (!makesTextEdit(item)) {
                        fallback();
                        return;
                    }
                    this.editor.pushUndoStop();
                    this._insertSuggestion({ index, item, model: completionModel }, 4 /* InsertFlags.KeepAlternativeSuggestions */ | 1 /* InsertFlags.NoBeforeUndoStop */ | 2 /* InsertFlags.NoAfterUndoStop */);
                }, undefined, listener);
            });
            this.model.trigger({ auto: false, shy: true });
            this.editor.revealPosition(positionNow, 0 /* ScrollType.Smooth */);
            this.editor.focus();
        }
        acceptSelectedSuggestion(keepAlternativeSuggestions, alternativeOverwriteConfig) {
            const item = this.widget.value.getFocusedItem();
            let flags = 0;
            if (keepAlternativeSuggestions) {
                flags |= 4 /* InsertFlags.KeepAlternativeSuggestions */;
            }
            if (alternativeOverwriteConfig) {
                flags |= 8 /* InsertFlags.AlternativeOverwriteConfig */;
            }
            this._insertSuggestion(item, flags);
        }
        acceptNextSuggestion() {
            this._alternatives.value.next();
        }
        acceptPrevSuggestion() {
            this._alternatives.value.prev();
        }
        cancelSuggestWidget() {
            this.model.cancel();
            this.model.clear();
            this.widget.value.hideWidget();
        }
        focusSuggestion() {
            this.widget.value.focusSelected();
        }
        selectNextSuggestion() {
            this.widget.value.selectNext();
        }
        selectNextPageSuggestion() {
            this.widget.value.selectNextPage();
        }
        selectLastSuggestion() {
            this.widget.value.selectLast();
        }
        selectPrevSuggestion() {
            this.widget.value.selectPrevious();
        }
        selectPrevPageSuggestion() {
            this.widget.value.selectPreviousPage();
        }
        selectFirstSuggestion() {
            this.widget.value.selectFirst();
        }
        toggleSuggestionDetails() {
            this.widget.value.toggleDetails();
        }
        toggleExplainMode() {
            this.widget.value.toggleExplainMode();
        }
        toggleSuggestionFocus() {
            this.widget.value.toggleDetailsFocus();
        }
        resetWidgetSize() {
            this.widget.value.resetPersistedSize();
        }
        forceRenderingAbove() {
            this.widget.value.forceRenderingAbove();
        }
        stopForceRenderingAbove() {
            if (!this.widget.isInitialized) {
                // This method has no effect if the widget is not initialized yet.
                return;
            }
            this.widget.value.stopForceRenderingAbove();
        }
        registerSelector(selector) {
            return this._selectors.register(selector);
        }
    };
    exports.SuggestController = SuggestController;
    exports.SuggestController = SuggestController = SuggestController_1 = __decorate([
        __param(1, suggestMemory_1.ISuggestMemoryService),
        __param(2, commands_1.ICommandService),
        __param(3, contextkey_1.IContextKeyService),
        __param(4, instantiation_1.IInstantiationService),
        __param(5, log_1.ILogService),
        __param(6, telemetry_1.ITelemetryService)
    ], SuggestController);
    class PriorityRegistry {
        constructor(prioritySelector) {
            this.prioritySelector = prioritySelector;
            this._items = new Array();
        }
        register(value) {
            if (this._items.indexOf(value) !== -1) {
                throw new Error('Value is already registered');
            }
            this._items.push(value);
            this._items.sort((s1, s2) => this.prioritySelector(s2) - this.prioritySelector(s1));
            return {
                dispose: () => {
                    const idx = this._items.indexOf(value);
                    if (idx >= 0) {
                        this._items.splice(idx, 1);
                    }
                }
            };
        }
        get itemsOrderedByPriorityDesc() {
            return this._items;
        }
    }
    class TriggerSuggestAction extends editorExtensions_1.EditorAction {
        static { this.id = 'editor.action.triggerSuggest'; }
        constructor() {
            super({
                id: TriggerSuggestAction.id,
                label: nls.localize(1319, "Trigger Suggest"),
                alias: 'Trigger Suggest',
                precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, editorContextKeys_1.EditorContextKeys.hasCompletionItemProvider, suggest_1.Context.Visible.toNegated()),
                kbOpts: {
                    kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
                    primary: 2048 /* KeyMod.CtrlCmd */ | 10 /* KeyCode.Space */,
                    secondary: [2048 /* KeyMod.CtrlCmd */ | 39 /* KeyCode.KeyI */],
                    mac: { primary: 256 /* KeyMod.WinCtrl */ | 10 /* KeyCode.Space */, secondary: [512 /* KeyMod.Alt */ | 9 /* KeyCode.Escape */, 2048 /* KeyMod.CtrlCmd */ | 39 /* KeyCode.KeyI */] },
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
        }
        run(_accessor, editor, args) {
            const controller = SuggestController.get(editor);
            if (!controller) {
                return;
            }
            let auto;
            if (args && typeof args === 'object') {
                if (args.auto === true) {
                    auto = true;
                }
            }
            controller.triggerSuggest(undefined, auto, undefined);
        }
    }
    exports.TriggerSuggestAction = TriggerSuggestAction;
    (0, editorExtensions_1.registerEditorContribution)(SuggestController.ID, SuggestController, 2 /* EditorContributionInstantiation.BeforeFirstInteraction */);
    (0, editorExtensions_1.registerEditorAction)(TriggerSuggestAction);
    const weight = 100 /* KeybindingWeight.EditorContrib */ + 90;
    const SuggestCommand = editorExtensions_1.EditorCommand.bindToContribution(SuggestController.get);
    (0, editorExtensions_1.registerEditorCommand)(new SuggestCommand({
        id: 'acceptSelectedSuggestion',
        precondition: contextkey_1.ContextKeyExpr.and(suggest_1.Context.Visible, suggest_1.Context.HasFocusedSuggestion),
        handler(x) {
            x.acceptSelectedSuggestion(true, false);
        },
        kbOpts: [{
                // normal tab
                primary: 2 /* KeyCode.Tab */,
                kbExpr: contextkey_1.ContextKeyExpr.and(suggest_1.Context.Visible, editorContextKeys_1.EditorContextKeys.textInputFocus),
                weight,
            }, {
                // accept on enter has special rules
                primary: 3 /* KeyCode.Enter */,
                kbExpr: contextkey_1.ContextKeyExpr.and(suggest_1.Context.Visible, editorContextKeys_1.EditorContextKeys.textInputFocus, suggest_1.Context.AcceptSuggestionsOnEnter, suggest_1.Context.MakesTextEdit),
                weight,
            }],
        menuOpts: [{
                menuId: suggest_1.suggestWidgetStatusbarMenu,
                title: nls.localize(1320, "Insert"),
                group: 'left',
                order: 1,
                when: suggest_1.Context.HasInsertAndReplaceRange.toNegated()
            }, {
                menuId: suggest_1.suggestWidgetStatusbarMenu,
                title: nls.localize(1321, "Insert"),
                group: 'left',
                order: 1,
                when: contextkey_1.ContextKeyExpr.and(suggest_1.Context.HasInsertAndReplaceRange, suggest_1.Context.InsertMode.isEqualTo('insert'))
            }, {
                menuId: suggest_1.suggestWidgetStatusbarMenu,
                title: nls.localize(1322, "Replace"),
                group: 'left',
                order: 1,
                when: contextkey_1.ContextKeyExpr.and(suggest_1.Context.HasInsertAndReplaceRange, suggest_1.Context.InsertMode.isEqualTo('replace'))
            }]
    }));
    (0, editorExtensions_1.registerEditorCommand)(new SuggestCommand({
        id: 'acceptAlternativeSelectedSuggestion',
        precondition: contextkey_1.ContextKeyExpr.and(suggest_1.Context.Visible, editorContextKeys_1.EditorContextKeys.textInputFocus, suggest_1.Context.HasFocusedSuggestion),
        kbOpts: {
            weight: weight,
            kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
            primary: 1024 /* KeyMod.Shift */ | 3 /* KeyCode.Enter */,
            secondary: [1024 /* KeyMod.Shift */ | 2 /* KeyCode.Tab */],
        },
        handler(x) {
            x.acceptSelectedSuggestion(false, true);
        },
        menuOpts: [{
                menuId: suggest_1.suggestWidgetStatusbarMenu,
                group: 'left',
                order: 2,
                when: contextkey_1.ContextKeyExpr.and(suggest_1.Context.HasInsertAndReplaceRange, suggest_1.Context.InsertMode.isEqualTo('insert')),
                title: nls.localize(1323, "Replace")
            }, {
                menuId: suggest_1.suggestWidgetStatusbarMenu,
                group: 'left',
                order: 2,
                when: contextkey_1.ContextKeyExpr.and(suggest_1.Context.HasInsertAndReplaceRange, suggest_1.Context.InsertMode.isEqualTo('replace')),
                title: nls.localize(1324, "Insert")
            }]
    }));
    // continue to support the old command
    commands_1.CommandsRegistry.registerCommandAlias('acceptSelectedSuggestionOnEnter', 'acceptSelectedSuggestion');
    (0, editorExtensions_1.registerEditorCommand)(new SuggestCommand({
        id: 'hideSuggestWidget',
        precondition: suggest_1.Context.Visible,
        handler: x => x.cancelSuggestWidget(),
        kbOpts: {
            weight: weight,
            kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
            primary: 9 /* KeyCode.Escape */,
            secondary: [1024 /* KeyMod.Shift */ | 9 /* KeyCode.Escape */]
        }
    }));
    (0, editorExtensions_1.registerEditorCommand)(new SuggestCommand({
        id: 'selectNextSuggestion',
        precondition: contextkey_1.ContextKeyExpr.and(suggest_1.Context.Visible, contextkey_1.ContextKeyExpr.or(suggest_1.Context.MultipleSuggestions, suggest_1.Context.HasFocusedSuggestion.negate())),
        handler: c => c.selectNextSuggestion(),
        kbOpts: {
            weight: weight,
            kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
            primary: 18 /* KeyCode.DownArrow */,
            secondary: [2048 /* KeyMod.CtrlCmd */ | 18 /* KeyCode.DownArrow */],
            mac: { primary: 18 /* KeyCode.DownArrow */, secondary: [2048 /* KeyMod.CtrlCmd */ | 18 /* KeyCode.DownArrow */, 256 /* KeyMod.WinCtrl */ | 44 /* KeyCode.KeyN */] }
        }
    }));
    (0, editorExtensions_1.registerEditorCommand)(new SuggestCommand({
        id: 'selectNextPageSuggestion',
        precondition: contextkey_1.ContextKeyExpr.and(suggest_1.Context.Visible, contextkey_1.ContextKeyExpr.or(suggest_1.Context.MultipleSuggestions, suggest_1.Context.HasFocusedSuggestion.negate())),
        handler: c => c.selectNextPageSuggestion(),
        kbOpts: {
            weight: weight,
            kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
            primary: 12 /* KeyCode.PageDown */,
            secondary: [2048 /* KeyMod.CtrlCmd */ | 12 /* KeyCode.PageDown */]
        }
    }));
    (0, editorExtensions_1.registerEditorCommand)(new SuggestCommand({
        id: 'selectLastSuggestion',
        precondition: contextkey_1.ContextKeyExpr.and(suggest_1.Context.Visible, contextkey_1.ContextKeyExpr.or(suggest_1.Context.MultipleSuggestions, suggest_1.Context.HasFocusedSuggestion.negate())),
        handler: c => c.selectLastSuggestion()
    }));
    (0, editorExtensions_1.registerEditorCommand)(new SuggestCommand({
        id: 'selectPrevSuggestion',
        precondition: contextkey_1.ContextKeyExpr.and(suggest_1.Context.Visible, contextkey_1.ContextKeyExpr.or(suggest_1.Context.MultipleSuggestions, suggest_1.Context.HasFocusedSuggestion.negate())),
        handler: c => c.selectPrevSuggestion(),
        kbOpts: {
            weight: weight,
            kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
            primary: 16 /* KeyCode.UpArrow */,
            secondary: [2048 /* KeyMod.CtrlCmd */ | 16 /* KeyCode.UpArrow */],
            mac: { primary: 16 /* KeyCode.UpArrow */, secondary: [2048 /* KeyMod.CtrlCmd */ | 16 /* KeyCode.UpArrow */, 256 /* KeyMod.WinCtrl */ | 46 /* KeyCode.KeyP */] }
        }
    }));
    (0, editorExtensions_1.registerEditorCommand)(new SuggestCommand({
        id: 'selectPrevPageSuggestion',
        precondition: contextkey_1.ContextKeyExpr.and(suggest_1.Context.Visible, contextkey_1.ContextKeyExpr.or(suggest_1.Context.MultipleSuggestions, suggest_1.Context.HasFocusedSuggestion.negate())),
        handler: c => c.selectPrevPageSuggestion(),
        kbOpts: {
            weight: weight,
            kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
            primary: 11 /* KeyCode.PageUp */,
            secondary: [2048 /* KeyMod.CtrlCmd */ | 11 /* KeyCode.PageUp */]
        }
    }));
    (0, editorExtensions_1.registerEditorCommand)(new SuggestCommand({
        id: 'selectFirstSuggestion',
        precondition: contextkey_1.ContextKeyExpr.and(suggest_1.Context.Visible, contextkey_1.ContextKeyExpr.or(suggest_1.Context.MultipleSuggestions, suggest_1.Context.HasFocusedSuggestion.negate())),
        handler: c => c.selectFirstSuggestion()
    }));
    (0, editorExtensions_1.registerEditorCommand)(new SuggestCommand({
        id: 'focusSuggestion',
        precondition: contextkey_1.ContextKeyExpr.and(suggest_1.Context.Visible, suggest_1.Context.HasFocusedSuggestion.negate()),
        handler: x => x.focusSuggestion(),
        kbOpts: {
            weight: weight,
            kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
            primary: 2048 /* KeyMod.CtrlCmd */ | 10 /* KeyCode.Space */,
            secondary: [2048 /* KeyMod.CtrlCmd */ | 39 /* KeyCode.KeyI */],
            mac: { primary: 256 /* KeyMod.WinCtrl */ | 10 /* KeyCode.Space */, secondary: [2048 /* KeyMod.CtrlCmd */ | 39 /* KeyCode.KeyI */] }
        },
    }));
    (0, editorExtensions_1.registerEditorCommand)(new SuggestCommand({
        id: 'focusAndAcceptSuggestion',
        precondition: contextkey_1.ContextKeyExpr.and(suggest_1.Context.Visible, suggest_1.Context.HasFocusedSuggestion.negate()),
        handler: c => {
            c.focusSuggestion();
            c.acceptSelectedSuggestion(true, false);
        }
    }));
    (0, editorExtensions_1.registerEditorCommand)(new SuggestCommand({
        id: 'toggleSuggestionDetails',
        precondition: contextkey_1.ContextKeyExpr.and(suggest_1.Context.Visible, suggest_1.Context.HasFocusedSuggestion),
        handler: x => x.toggleSuggestionDetails(),
        kbOpts: {
            weight: weight,
            kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
            primary: 2048 /* KeyMod.CtrlCmd */ | 10 /* KeyCode.Space */,
            secondary: [2048 /* KeyMod.CtrlCmd */ | 39 /* KeyCode.KeyI */],
            mac: { primary: 256 /* KeyMod.WinCtrl */ | 10 /* KeyCode.Space */, secondary: [2048 /* KeyMod.CtrlCmd */ | 39 /* KeyCode.KeyI */] }
        },
        menuOpts: [{
                menuId: suggest_1.suggestWidgetStatusbarMenu,
                group: 'right',
                order: 1,
                when: contextkey_1.ContextKeyExpr.and(suggest_1.Context.DetailsVisible, suggest_1.Context.CanResolve),
                title: nls.localize(1325, "Show Less")
            }, {
                menuId: suggest_1.suggestWidgetStatusbarMenu,
                group: 'right',
                order: 1,
                when: contextkey_1.ContextKeyExpr.and(suggest_1.Context.DetailsVisible.toNegated(), suggest_1.Context.CanResolve),
                title: nls.localize(1326, "Show More")
            }]
    }));
    (0, editorExtensions_1.registerEditorCommand)(new SuggestCommand({
        id: 'toggleExplainMode',
        precondition: suggest_1.Context.Visible,
        handler: x => x.toggleExplainMode(),
        kbOpts: {
            weight: 100 /* KeybindingWeight.EditorContrib */,
            primary: 2048 /* KeyMod.CtrlCmd */ | 90 /* KeyCode.Slash */,
        }
    }));
    (0, editorExtensions_1.registerEditorCommand)(new SuggestCommand({
        id: 'toggleSuggestionFocus',
        precondition: suggest_1.Context.Visible,
        handler: x => x.toggleSuggestionFocus(),
        kbOpts: {
            weight: weight,
            kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
            primary: 2048 /* KeyMod.CtrlCmd */ | 512 /* KeyMod.Alt */ | 10 /* KeyCode.Space */,
            mac: { primary: 256 /* KeyMod.WinCtrl */ | 512 /* KeyMod.Alt */ | 10 /* KeyCode.Space */ }
        }
    }));
    //#region tab completions
    (0, editorExtensions_1.registerEditorCommand)(new SuggestCommand({
        id: 'insertBestCompletion',
        precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.textInputFocus, contextkey_1.ContextKeyExpr.equals('config.editor.tabCompletion', 'on'), wordContextKey_1.WordContextKey.AtEnd, suggest_1.Context.Visible.toNegated(), suggestAlternatives_1.SuggestAlternatives.OtherSuggestions.toNegated(), snippetController2_1.SnippetController2.InSnippetMode.toNegated()),
        handler: (x, arg) => {
            x.triggerSuggestAndAcceptBest((0, types_1.isObject)(arg) ? { fallback: 'tab', ...arg } : { fallback: 'tab' });
        },
        kbOpts: {
            weight,
            primary: 2 /* KeyCode.Tab */
        }
    }));
    (0, editorExtensions_1.registerEditorCommand)(new SuggestCommand({
        id: 'insertNextSuggestion',
        precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.textInputFocus, contextkey_1.ContextKeyExpr.equals('config.editor.tabCompletion', 'on'), suggestAlternatives_1.SuggestAlternatives.OtherSuggestions, suggest_1.Context.Visible.toNegated(), snippetController2_1.SnippetController2.InSnippetMode.toNegated()),
        handler: x => x.acceptNextSuggestion(),
        kbOpts: {
            weight: weight,
            kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
            primary: 2 /* KeyCode.Tab */
        }
    }));
    (0, editorExtensions_1.registerEditorCommand)(new SuggestCommand({
        id: 'insertPrevSuggestion',
        precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.textInputFocus, contextkey_1.ContextKeyExpr.equals('config.editor.tabCompletion', 'on'), suggestAlternatives_1.SuggestAlternatives.OtherSuggestions, suggest_1.Context.Visible.toNegated(), snippetController2_1.SnippetController2.InSnippetMode.toNegated()),
        handler: x => x.acceptPrevSuggestion(),
        kbOpts: {
            weight: weight,
            kbExpr: editorContextKeys_1.EditorContextKeys.textInputFocus,
            primary: 1024 /* KeyMod.Shift */ | 2 /* KeyCode.Tab */
        }
    }));
    (0, editorExtensions_1.registerEditorAction)(class extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: 'editor.action.resetSuggestSize',
                label: nls.localize(1327, "Reset Suggest Widget Size"),
                alias: 'Reset Suggest Widget Size',
                precondition: undefined
            });
        }
        run(_accessor, editor) {
            SuggestController.get(editor)?.resetWidgetSize();
        }
    });
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[861/*vs/editor/contrib/inlineCompletions/browser/model/suggestWidgetAdaptor*/], __M([1/*require*/,0/*exports*/,13/*vs/base/common/arrays*/,67/*vs/base/common/arraysFind*/,6/*vs/base/common/event*/,2/*vs/base/common/lifecycle*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/,104/*vs/editor/common/core/textEdit*/,27/*vs/editor/common/languages*/,246/*vs/editor/contrib/inlineCompletions/browser/model/singleTextEdit*/,135/*vs/editor/contrib/snippet/browser/snippetParser*/,436/*vs/editor/contrib/snippet/browser/snippetSession*/,294/*vs/editor/contrib/suggest/browser/suggestController*/]), function (require, exports, arrays_1, arraysFind_1, event_1, lifecycle_1, position_1, range_1, textEdit_1, languages_1, singleTextEdit_1, snippetParser_1, snippetSession_1, suggestController_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SuggestItemInfo = exports.SuggestWidgetAdaptor = void 0;
    class SuggestWidgetAdaptor extends lifecycle_1.Disposable {
        get selectedItem() {
            return this._currentSuggestItemInfo;
        }
        constructor(editor, suggestControllerPreselector, onWillAccept) {
            super();
            this.editor = editor;
            this.suggestControllerPreselector = suggestControllerPreselector;
            this.onWillAccept = onWillAccept;
            this.isSuggestWidgetVisible = false;
            this.isShiftKeyPressed = false;
            this._isActive = false;
            this._currentSuggestItemInfo = undefined;
            this._onDidSelectedItemChange = this._register(new event_1.Emitter());
            this.onDidSelectedItemChange = this._onDidSelectedItemChange.event;
            // See the command acceptAlternativeSelectedSuggestion that is bound to shift+tab
            this._register(editor.onKeyDown(e => {
                if (e.shiftKey && !this.isShiftKeyPressed) {
                    this.isShiftKeyPressed = true;
                    this.update(this._isActive);
                }
            }));
            this._register(editor.onKeyUp(e => {
                if (e.shiftKey && this.isShiftKeyPressed) {
                    this.isShiftKeyPressed = false;
                    this.update(this._isActive);
                }
            }));
            const suggestController = suggestController_1.SuggestController.get(this.editor);
            if (suggestController) {
                this._register(suggestController.registerSelector({
                    priority: 100,
                    select: (model, pos, suggestItems) => {
                        const textModel = this.editor.getModel();
                        if (!textModel) {
                            // Should not happen
                            return -1;
                        }
                        const i = this.suggestControllerPreselector();
                        const itemToPreselect = i ? (0, singleTextEdit_1.singleTextRemoveCommonPrefix)(i, textModel) : undefined;
                        if (!itemToPreselect) {
                            return -1;
                        }
                        const position = position_1.Position.lift(pos);
                        const candidates = suggestItems
                            .map((suggestItem, index) => {
                            const suggestItemInfo = SuggestItemInfo.fromSuggestion(suggestController, textModel, position, suggestItem, this.isShiftKeyPressed);
                            const suggestItemTextEdit = (0, singleTextEdit_1.singleTextRemoveCommonPrefix)(suggestItemInfo.toSingleTextEdit(), textModel);
                            const valid = (0, singleTextEdit_1.singleTextEditAugments)(itemToPreselect, suggestItemTextEdit);
                            return { index, valid, prefixLength: suggestItemTextEdit.text.length, suggestItem };
                        })
                            .filter(item => item && item.valid && item.prefixLength > 0);
                        const result = (0, arraysFind_1.findFirstMax)(candidates, (0, arrays_1.compareBy)(s => s.prefixLength, arrays_1.numberComparator));
                        return result ? result.index : -1;
                    }
                }));
                let isBoundToSuggestWidget = false;
                const bindToSuggestWidget = () => {
                    if (isBoundToSuggestWidget) {
                        return;
                    }
                    isBoundToSuggestWidget = true;
                    this._register(suggestController.widget.value.onDidShow(() => {
                        this.isSuggestWidgetVisible = true;
                        this.update(true);
                    }));
                    this._register(suggestController.widget.value.onDidHide(() => {
                        this.isSuggestWidgetVisible = false;
                        this.update(false);
                    }));
                    this._register(suggestController.widget.value.onDidFocus(() => {
                        this.isSuggestWidgetVisible = true;
                        this.update(true);
                    }));
                };
                this._register(event_1.Event.once(suggestController.model.onDidTrigger)(e => {
                    bindToSuggestWidget();
                }));
                this._register(suggestController.onWillInsertSuggestItem(e => {
                    const position = this.editor.getPosition();
                    const model = this.editor.getModel();
                    if (!position || !model) {
                        return undefined;
                    }
                    const suggestItemInfo = SuggestItemInfo.fromSuggestion(suggestController, model, position, e.item, this.isShiftKeyPressed);
                    this.onWillAccept(suggestItemInfo);
                }));
            }
            this.update(this._isActive);
        }
        update(newActive) {
            const newInlineCompletion = this.getSuggestItemInfo();
            if (this._isActive !== newActive || !suggestItemInfoEquals(this._currentSuggestItemInfo, newInlineCompletion)) {
                this._isActive = newActive;
                this._currentSuggestItemInfo = newInlineCompletion;
                this._onDidSelectedItemChange.fire();
            }
        }
        getSuggestItemInfo() {
            const suggestController = suggestController_1.SuggestController.get(this.editor);
            if (!suggestController || !this.isSuggestWidgetVisible) {
                return undefined;
            }
            const focusedItem = suggestController.widget.value.getFocusedItem();
            const position = this.editor.getPosition();
            const model = this.editor.getModel();
            if (!focusedItem || !position || !model) {
                return undefined;
            }
            return SuggestItemInfo.fromSuggestion(suggestController, model, position, focusedItem.item, this.isShiftKeyPressed);
        }
        stopForceRenderingAbove() {
            const suggestController = suggestController_1.SuggestController.get(this.editor);
            suggestController?.stopForceRenderingAbove();
        }
        forceRenderingAbove() {
            const suggestController = suggestController_1.SuggestController.get(this.editor);
            suggestController?.forceRenderingAbove();
        }
    }
    exports.SuggestWidgetAdaptor = SuggestWidgetAdaptor;
    class SuggestItemInfo {
        static fromSuggestion(suggestController, model, position, item, toggleMode) {
            let { insertText } = item.completion;
            let isSnippetText = false;
            if (item.completion.insertTextRules & 4 /* CompletionItemInsertTextRule.InsertAsSnippet */) {
                const snippet = new snippetParser_1.SnippetParser().parse(insertText);
                if (snippet.children.length < 100) {
                    // Adjust whitespace is expensive.
                    snippetSession_1.SnippetSession.adjustWhitespace(model, position, true, snippet);
                }
                insertText = snippet.toString();
                isSnippetText = true;
            }
            const info = suggestController.getOverwriteInfo(item, toggleMode);
            return new SuggestItemInfo(range_1.Range.fromPositions(position.delta(0, -info.overwriteBefore), position.delta(0, Math.max(info.overwriteAfter, 0))), insertText, item.completion.kind, isSnippetText);
        }
        constructor(range, insertText, completionItemKind, isSnippetText) {
            this.range = range;
            this.insertText = insertText;
            this.completionItemKind = completionItemKind;
            this.isSnippetText = isSnippetText;
        }
        equals(other) {
            return this.range.equalsRange(other.range)
                && this.insertText === other.insertText
                && this.completionItemKind === other.completionItemKind
                && this.isSnippetText === other.isSnippetText;
        }
        toSelectedSuggestionInfo() {
            return new languages_1.SelectedSuggestionInfo(this.range, this.insertText, this.completionItemKind, this.isSnippetText);
        }
        toSingleTextEdit() {
            return new textEdit_1.SingleTextEdit(this.range, this.insertText);
        }
    }
    exports.SuggestItemInfo = SuggestItemInfo;
    function suggestItemInfoEquals(a, b) {
        if (a === b) {
            return true;
        }
        if (!a || !b) {
            return false;
        }
        return a.equals(b);
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[295/*vs/editor/contrib/inlineCompletions/browser/controller/inlineCompletionsController*/], __M([1/*require*/,0/*exports*/,630/*vs/base/browser/domObservable*/,46/*vs/base/browser/ui/aria/aria*/,14/*vs/base/common/async*/,18/*vs/base/common/cancellation*/,2/*vs/base/common/lifecycle*/,21/*vs/base/common/observable*/,65/*vs/base/common/observableInternal/derived*/,189/*vs/base/common/observableInternal/utils*/,19/*vs/base/common/types*/,214/*vs/editor/browser/coreCommands*/,112/*vs/editor/browser/observableCodeEditor*/,9/*vs/editor/common/core/position*/,79/*vs/editor/common/services/languageFeatureDebounce*/,17/*vs/editor/common/services/languageFeatures*/,245/*vs/editor/contrib/inlineCompletions/browser/controller/commandIds*/,679/*vs/editor/contrib/inlineCompletions/browser/view/ghostTextView*/,269/*vs/editor/contrib/inlineCompletions/browser/controller/inlineCompletionContextKeys*/,283/*vs/editor/contrib/inlineCompletions/browser/hintsWidget/inlineCompletionsHintsWidget*/,860/*vs/editor/contrib/inlineCompletions/browser/model/inlineCompletionsModel*/,861/*vs/editor/contrib/inlineCompletions/browser/model/suggestWidgetAdaptor*/,3/*vs/nls*/,61/*vs/platform/accessibility/common/accessibility*/,137/*vs/platform/accessibilitySignal/browser/accessibilitySignalService*/,24/*vs/platform/commands/common/commands*/,28/*vs/platform/configuration/common/configuration*/,12/*vs/platform/contextkey/common/contextkey*/,7/*vs/platform/instantiation/common/instantiation*/,31/*vs/platform/keybinding/common/keybinding*/]), function (require, exports, domObservable_1, aria_1, async_1, cancellation_1, lifecycle_1, observable_1, derived_1, utils_1, types_1, coreCommands_1, observableCodeEditor_1, position_1, languageFeatureDebounce_1, languageFeatures_1, commandIds_1, ghostTextView_1, inlineCompletionContextKeys_1, inlineCompletionsHintsWidget_1, inlineCompletionsModel_1, suggestWidgetAdaptor_1, nls_1, accessibility_1, accessibilitySignalService_1, commands_1, configuration_1, contextkey_1, instantiation_1, keybinding_1) {
    "use strict";
    var InlineCompletionsController_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.InlineCompletionsController = void 0;
    let InlineCompletionsController = class InlineCompletionsController extends lifecycle_1.Disposable {
        static { InlineCompletionsController_1 = this; }
        static { this.ID = 'editor.contrib.inlineCompletionsController'; }
        static get(editor) {
            return editor.getContribution(InlineCompletionsController_1.ID);
        }
        constructor(editor, _instantiationService, _contextKeyService, _configurationService, _commandService, _debounceService, _languageFeaturesService, _accessibilitySignalService, _keybindingService, _accessibilityService) {
            super();
            this.editor = editor;
            this._instantiationService = _instantiationService;
            this._contextKeyService = _contextKeyService;
            this._configurationService = _configurationService;
            this._commandService = _commandService;
            this._debounceService = _debounceService;
            this._languageFeaturesService = _languageFeaturesService;
            this._accessibilitySignalService = _accessibilitySignalService;
            this._keybindingService = _keybindingService;
            this._accessibilityService = _accessibilityService;
            this._editorObs = (0, observableCodeEditor_1.observableCodeEditor)(this.editor);
            this._positions = (0, observable_1.derived)(this, reader => this._editorObs.selections.read(reader)?.map(s => s.getEndPosition()) ?? [new position_1.Position(1, 1)]);
            this._suggestWidgetAdaptor = this._register(new suggestWidgetAdaptor_1.SuggestWidgetAdaptor(this.editor, () => {
                this._editorObs.forceUpdate();
                return this.model.get()?.selectedInlineCompletion.get()?.toSingleTextEdit(undefined);
            }, (item) => this._editorObs.forceUpdate(_tx => {
                /** @description InlineCompletionsController.handleSuggestAccepted */
                this.model.get()?.handleSuggestAccepted(item);
            })));
            this._suggestWidgetSelectedItem = (0, observable_1.observableFromEvent)(this, cb => this._suggestWidgetAdaptor.onDidSelectedItemChange(() => {
                this._editorObs.forceUpdate(_tx => cb(undefined));
            }), () => this._suggestWidgetAdaptor.selectedItem);
            this._enabledInConfig = (0, observable_1.observableFromEvent)(this, this.editor.onDidChangeConfiguration, () => this.editor.getOption(62 /* EditorOption.inlineSuggest */).enabled);
            this._isScreenReaderEnabled = (0, observable_1.observableFromEvent)(this, this._accessibilityService.onDidChangeScreenReaderOptimized, () => this._accessibilityService.isScreenReaderOptimized());
            this._editorDictationInProgress = (0, observable_1.observableFromEvent)(this, this._contextKeyService.onDidChangeContext, () => this._contextKeyService.getContext(this.editor.getDomNode()).getValue('editorDictation.inProgress') === true);
            this._enabled = (0, observable_1.derived)(this, reader => this._enabledInConfig.read(reader) && (!this._isScreenReaderEnabled.read(reader) || !this._editorDictationInProgress.read(reader)));
            this._debounceValue = this._debounceService.for(this._languageFeaturesService.inlineCompletionsProvider, 'InlineCompletionsDebounce', { min: 50, max: 50 });
            this.model = (0, derived_1.derivedDisposable)(this, reader => {
                if (this._editorObs.isReadonly.read(reader)) {
                    return undefined;
                }
                const textModel = this._editorObs.model.read(reader);
                if (!textModel) {
                    return undefined;
                }
                const model = this._instantiationService.createInstance(inlineCompletionsModel_1.InlineCompletionsModel, textModel, this._suggestWidgetSelectedItem, this._editorObs.versionId, this._positions, this._debounceValue, (0, observable_1.observableFromEvent)(this.editor.onDidChangeConfiguration, () => this.editor.getOption(119 /* EditorOption.suggest */).preview), (0, observable_1.observableFromEvent)(this.editor.onDidChangeConfiguration, () => this.editor.getOption(119 /* EditorOption.suggest */).previewMode), (0, observable_1.observableFromEvent)(this.editor.onDidChangeConfiguration, () => this.editor.getOption(62 /* EditorOption.inlineSuggest */).mode), this._enabled);
                return model;
            }).recomputeInitiallyAndOnChange(this._store);
            this._ghostTexts = (0, observable_1.derived)(this, (reader) => {
                const model = this.model.read(reader);
                return model?.ghostTexts.read(reader) ?? [];
            });
            this._stablizedGhostTexts = convertItemsToStableObservables(this._ghostTexts, this._store);
            this._ghostTextWidgets = (0, utils_1.mapObservableArrayCached)(this, this._stablizedGhostTexts, (ghostText, store) => store.add(this._instantiationService.createInstance(ghostTextView_1.GhostTextView, this.editor, {
                ghostText: ghostText,
                minReservedLineCount: (0, observable_1.constObservable)(0),
                targetTextModel: this.model.map(v => v?.textModel),
            }))).recomputeInitiallyAndOnChange(this._store);
            this._playAccessibilitySignal = (0, observable_1.observableSignal)(this);
            this._fontFamily = (0, observable_1.observableFromEvent)(this, this.editor.onDidChangeConfiguration, () => this.editor.getOption(62 /* EditorOption.inlineSuggest */).fontFamily);
            this._register(new inlineCompletionContextKeys_1.InlineCompletionContextKeys(this._contextKeyService, this.model));
            this._register((0, observableCodeEditor_1.reactToChange)(this._editorObs.onDidType, (_value, _changes) => {
                if (this._enabled.get()) {
                    this.model.get()?.trigger();
                }
            }));
            this._register(this._commandService.onDidExecuteCommand((e) => {
                // These commands don't trigger onDidType.
                const commands = new Set([
                    coreCommands_1.CoreEditingCommands.Tab.id,
                    coreCommands_1.CoreEditingCommands.DeleteLeft.id,
                    coreCommands_1.CoreEditingCommands.DeleteRight.id,
                    commandIds_1.inlineSuggestCommitId,
                    'acceptSelectedSuggestion',
                ]);
                if (commands.has(e.commandId) && editor.hasTextFocus() && this._enabled.get()) {
                    this._editorObs.forceUpdate(tx => {
                        /** @description onDidExecuteCommand */
                        this.model.get()?.trigger(tx);
                    });
                }
            }));
            this._register((0, observableCodeEditor_1.reactToChange)(this._editorObs.selections, (_value, changes) => {
                if (changes.some(e => e.reason === 3 /* CursorChangeReason.Explicit */ || e.source === 'api')) {
                    this.model.get()?.stop();
                }
            }));
            this._register(this.editor.onDidBlurEditorWidget(() => {
                // This is a hidden setting very useful for debugging
                if (this._contextKeyService.getContextKeyValue('accessibleViewIsShown')
                    || this._configurationService.getValue('editor.inlineSuggest.keepOnBlur')
                    || editor.getOption(62 /* EditorOption.inlineSuggest */).keepOnBlur
                    || inlineCompletionsHintsWidget_1.InlineSuggestionHintsContentWidget.dropDownVisible) {
                    return;
                }
                (0, observable_1.transaction)(tx => {
                    /** @description InlineCompletionsController.onDidBlurEditorWidget */
                    this.model.get()?.stop(tx);
                });
            }));
            this._register((0, observable_1.autorun)(reader => {
                /** @description InlineCompletionsController.forceRenderingAbove */
                const state = this.model.read(reader)?.state.read(reader);
                if (state?.suggestItem) {
                    if (state.primaryGhostText.lineCount >= 2) {
                        this._suggestWidgetAdaptor.forceRenderingAbove();
                    }
                }
                else {
                    this._suggestWidgetAdaptor.stopForceRenderingAbove();
                }
            }));
            this._register((0, lifecycle_1.toDisposable)(() => {
                this._suggestWidgetAdaptor.stopForceRenderingAbove();
            }));
            const currentInlineCompletionBySemanticId = (0, utils_1.derivedObservableWithCache)(this, (reader, last) => {
                const model = this.model.read(reader);
                const state = model?.state.read(reader);
                if (this._suggestWidgetSelectedItem.get()) {
                    return last;
                }
                return state?.inlineCompletion?.semanticId;
            });
            this._register((0, observableCodeEditor_1.reactToChangeWithStore)((0, observable_1.derived)(reader => {
                this._playAccessibilitySignal.read(reader);
                currentInlineCompletionBySemanticId.read(reader);
                return {};
            }), async (_value, _deltas, store) => {
                /** @description InlineCompletionsController.playAccessibilitySignalAndReadSuggestion */
                const model = this.model.get();
                const state = model?.state.get();
                if (!state || !model) {
                    return;
                }
                const lineText = model.textModel.getLineContent(state.primaryGhostText.lineNumber);
                await (0, async_1.timeout)(50, (0, cancellation_1.cancelOnDispose)(store));
                await (0, observable_1.waitForState)(this._suggestWidgetSelectedItem, types_1.isUndefined, () => false, (0, cancellation_1.cancelOnDispose)(store));
                await this._accessibilitySignalService.playSignal(accessibilitySignalService_1.AccessibilitySignal.inlineSuggestion);
                if (this.editor.getOption(8 /* EditorOption.screenReaderAnnounceInlineSuggestion */)) {
                    this._provideScreenReaderUpdate(state.primaryGhostText.renderForScreenReader(lineText));
                }
            }));
            this._register(new inlineCompletionsHintsWidget_1.InlineCompletionsHintsWidget(this.editor, this.model, this._instantiationService));
            this._register((0, domObservable_1.createStyleSheetFromObservable)((0, observable_1.derived)(reader => {
                const fontFamily = this._fontFamily.read(reader);
                if (fontFamily === '' || fontFamily === 'default') {
                    return '';
                }
                return `
.monaco-editor .ghost-text-decoration,
.monaco-editor .ghost-text-decoration-preview,
.monaco-editor .ghost-text {
	font-family: ${fontFamily};
}`;
            })));
            // TODO@hediet
            this._register(this._configurationService.onDidChangeConfiguration(e => {
                if (e.affectsConfiguration('accessibility.verbosity.inlineCompletions')) {
                    this.editor.updateOptions({ inlineCompletionsAccessibilityVerbose: this._configurationService.getValue('accessibility.verbosity.inlineCompletions') });
                }
            }));
            this.editor.updateOptions({ inlineCompletionsAccessibilityVerbose: this._configurationService.getValue('accessibility.verbosity.inlineCompletions') });
        }
        playAccessibilitySignal(tx) {
            this._playAccessibilitySignal.trigger(tx);
        }
        _provideScreenReaderUpdate(content) {
            const accessibleViewShowing = this._contextKeyService.getContextKeyValue('accessibleViewIsShown');
            const accessibleViewKeybinding = this._keybindingService.lookupKeybinding('editor.action.accessibleView');
            let hint;
            if (!accessibleViewShowing && accessibleViewKeybinding && this.editor.getOption(150 /* EditorOption.inlineCompletionsAccessibilityVerbose */)) {
                hint = (0, nls_1.localize)(1088, "Inspect this in the accessible view ({0})", accessibleViewKeybinding.getAriaLabel());
            }
            (0, aria_1.alert)(hint ? content + ', ' + hint : content);
        }
        shouldShowHoverAt(range) {
            const ghostText = this.model.get()?.primaryGhostText.get();
            if (ghostText) {
                return ghostText.parts.some(p => range.containsPosition(new position_1.Position(ghostText.lineNumber, p.column)));
            }
            return false;
        }
        shouldShowHoverAtViewZone(viewZoneId) {
            return this._ghostTextWidgets.get()[0]?.ownsViewZone(viewZoneId) ?? false;
        }
    };
    exports.InlineCompletionsController = InlineCompletionsController;
    exports.InlineCompletionsController = InlineCompletionsController = InlineCompletionsController_1 = __decorate([
        __param(1, instantiation_1.IInstantiationService),
        __param(2, contextkey_1.IContextKeyService),
        __param(3, configuration_1.IConfigurationService),
        __param(4, commands_1.ICommandService),
        __param(5, languageFeatureDebounce_1.ILanguageFeatureDebounceService),
        __param(6, languageFeatures_1.ILanguageFeaturesService),
        __param(7, accessibilitySignalService_1.IAccessibilitySignalService),
        __param(8, keybinding_1.IKeybindingService),
        __param(9, accessibility_1.IAccessibilityService)
    ], InlineCompletionsController);
    function convertItemsToStableObservables(items, store) {
        const result = (0, observable_1.observableValue)('result', []);
        const innerObservables = [];
        store.add((0, observable_1.autorun)(reader => {
            const itemsValue = items.read(reader);
            (0, observable_1.transaction)(tx => {
                if (itemsValue.length !== innerObservables.length) {
                    innerObservables.length = itemsValue.length;
                    for (let i = 0; i < innerObservables.length; i++) {
                        if (!innerObservables[i]) {
                            innerObservables[i] = (0, observable_1.observableValue)('item', itemsValue[i]);
                        }
                    }
                    result.set([...innerObservables], tx);
                }
                innerObservables.forEach((o, i) => o.set(itemsValue[i], tx));
            });
        }));
        return result;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[862/*vs/editor/contrib/inlineCompletions/browser/controller/commands*/], __M([1/*require*/,0/*exports*/,21/*vs/base/common/observable*/,92/*vs/base/common/observableInternal/base*/,15/*vs/editor/browser/editorExtensions*/,20/*vs/editor/common/editorContextKeys*/,245/*vs/editor/contrib/inlineCompletions/browser/controller/commandIds*/,269/*vs/editor/contrib/inlineCompletions/browser/controller/inlineCompletionContextKeys*/,295/*vs/editor/contrib/inlineCompletions/browser/controller/inlineCompletionsController*/,155/*vs/editor/contrib/suggest/browser/suggest*/,3/*vs/nls*/,29/*vs/platform/actions/common/actions*/,28/*vs/platform/configuration/common/configuration*/,12/*vs/platform/contextkey/common/contextkey*/]), function (require, exports, observable_1, base_1, editorExtensions_1, editorContextKeys_1, commandIds_1, inlineCompletionContextKeys_1, inlineCompletionsController_1, suggest_1, nls, actions_1, configuration_1, contextkey_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ToggleAlwaysShowInlineSuggestionToolbar = exports.HideInlineCompletion = exports.AcceptInlineCompletion = exports.AcceptNextLineOfInlineCompletion = exports.AcceptNextWordOfInlineCompletion = exports.TriggerInlineSuggestionAction = exports.ShowPreviousInlineSuggestionAction = exports.ShowNextInlineSuggestionAction = void 0;
    class ShowNextInlineSuggestionAction extends editorExtensions_1.EditorAction {
        static { this.ID = commandIds_1.showNextInlineSuggestionActionId; }
        constructor() {
            super({
                id: ShowNextInlineSuggestionAction.ID,
                label: nls.localize(1073, "Show Next Inline Suggestion"),
                alias: 'Show Next Inline Suggestion',
                precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, inlineCompletionContextKeys_1.InlineCompletionContextKeys.inlineSuggestionVisible),
                kbOpts: {
                    weight: 100,
                    primary: 512 /* KeyMod.Alt */ | 94 /* KeyCode.BracketRight */,
                },
            });
        }
        async run(accessor, editor) {
            const controller = inlineCompletionsController_1.InlineCompletionsController.get(editor);
            controller?.model.get()?.next();
        }
    }
    exports.ShowNextInlineSuggestionAction = ShowNextInlineSuggestionAction;
    class ShowPreviousInlineSuggestionAction extends editorExtensions_1.EditorAction {
        static { this.ID = commandIds_1.showPreviousInlineSuggestionActionId; }
        constructor() {
            super({
                id: ShowPreviousInlineSuggestionAction.ID,
                label: nls.localize(1074, "Show Previous Inline Suggestion"),
                alias: 'Show Previous Inline Suggestion',
                precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, inlineCompletionContextKeys_1.InlineCompletionContextKeys.inlineSuggestionVisible),
                kbOpts: {
                    weight: 100,
                    primary: 512 /* KeyMod.Alt */ | 92 /* KeyCode.BracketLeft */,
                },
            });
        }
        async run(accessor, editor) {
            const controller = inlineCompletionsController_1.InlineCompletionsController.get(editor);
            controller?.model.get()?.previous();
        }
    }
    exports.ShowPreviousInlineSuggestionAction = ShowPreviousInlineSuggestionAction;
    class TriggerInlineSuggestionAction extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: 'editor.action.inlineSuggest.trigger',
                label: nls.localize(1075, "Trigger Inline Suggestion"),
                alias: 'Trigger Inline Suggestion',
                precondition: editorContextKeys_1.EditorContextKeys.writable
            });
        }
        async run(accessor, editor) {
            const controller = inlineCompletionsController_1.InlineCompletionsController.get(editor);
            await (0, base_1.asyncTransaction)(async (tx) => {
                /** @description triggerExplicitly from command */
                await controller?.model.get()?.triggerExplicitly(tx);
                controller?.playAccessibilitySignal(tx);
            });
        }
    }
    exports.TriggerInlineSuggestionAction = TriggerInlineSuggestionAction;
    class AcceptNextWordOfInlineCompletion extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: 'editor.action.inlineSuggest.acceptNextWord',
                label: nls.localize(1076, "Accept Next Word Of Inline Suggestion"),
                alias: 'Accept Next Word Of Inline Suggestion',
                precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, inlineCompletionContextKeys_1.InlineCompletionContextKeys.inlineSuggestionVisible),
                kbOpts: {
                    weight: 100 /* KeybindingWeight.EditorContrib */ + 1,
                    primary: 2048 /* KeyMod.CtrlCmd */ | 17 /* KeyCode.RightArrow */,
                    kbExpr: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, inlineCompletionContextKeys_1.InlineCompletionContextKeys.inlineSuggestionVisible),
                },
                menuOpts: [{
                        menuId: actions_1.MenuId.InlineSuggestionToolbar,
                        title: nls.localize(1077, 'Accept Word'),
                        group: 'primary',
                        order: 2,
                    }],
            });
        }
        async run(accessor, editor) {
            const controller = inlineCompletionsController_1.InlineCompletionsController.get(editor);
            await controller?.model.get()?.acceptNextWord(controller.editor);
        }
    }
    exports.AcceptNextWordOfInlineCompletion = AcceptNextWordOfInlineCompletion;
    class AcceptNextLineOfInlineCompletion extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: 'editor.action.inlineSuggest.acceptNextLine',
                label: nls.localize(1078, "Accept Next Line Of Inline Suggestion"),
                alias: 'Accept Next Line Of Inline Suggestion',
                precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, inlineCompletionContextKeys_1.InlineCompletionContextKeys.inlineSuggestionVisible),
                kbOpts: {
                    weight: 100 /* KeybindingWeight.EditorContrib */ + 1,
                },
                menuOpts: [{
                        menuId: actions_1.MenuId.InlineSuggestionToolbar,
                        title: nls.localize(1079, 'Accept Line'),
                        group: 'secondary',
                        order: 2,
                    }],
            });
        }
        async run(accessor, editor) {
            const controller = inlineCompletionsController_1.InlineCompletionsController.get(editor);
            await controller?.model.get()?.acceptNextLine(controller.editor);
        }
    }
    exports.AcceptNextLineOfInlineCompletion = AcceptNextLineOfInlineCompletion;
    class AcceptInlineCompletion extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: commandIds_1.inlineSuggestCommitId,
                label: nls.localize(1080, "Accept Inline Suggestion"),
                alias: 'Accept Inline Suggestion',
                precondition: inlineCompletionContextKeys_1.InlineCompletionContextKeys.inlineSuggestionVisible,
                menuOpts: [{
                        menuId: actions_1.MenuId.InlineSuggestionToolbar,
                        title: nls.localize(1081, "Accept"),
                        group: 'primary',
                        order: 1,
                    }],
                kbOpts: {
                    primary: 2 /* KeyCode.Tab */,
                    weight: 200,
                    kbExpr: contextkey_1.ContextKeyExpr.and(inlineCompletionContextKeys_1.InlineCompletionContextKeys.inlineSuggestionVisible, editorContextKeys_1.EditorContextKeys.tabMovesFocus.toNegated(), inlineCompletionContextKeys_1.InlineCompletionContextKeys.inlineSuggestionHasIndentationLessThanTabSize, suggest_1.Context.Visible.toNegated(), editorContextKeys_1.EditorContextKeys.hoverFocused.toNegated()),
                }
            });
        }
        async run(accessor, editor) {
            const controller = inlineCompletionsController_1.InlineCompletionsController.get(editor);
            if (controller) {
                controller.model.get()?.accept(controller.editor);
                controller.editor.focus();
            }
        }
    }
    exports.AcceptInlineCompletion = AcceptInlineCompletion;
    class HideInlineCompletion extends editorExtensions_1.EditorAction {
        static { this.ID = 'editor.action.inlineSuggest.hide'; }
        constructor() {
            super({
                id: HideInlineCompletion.ID,
                label: nls.localize(1082, "Hide Inline Suggestion"),
                alias: 'Hide Inline Suggestion',
                precondition: inlineCompletionContextKeys_1.InlineCompletionContextKeys.inlineSuggestionVisible,
                kbOpts: {
                    weight: 100,
                    primary: 9 /* KeyCode.Escape */,
                }
            });
        }
        async run(accessor, editor) {
            const controller = inlineCompletionsController_1.InlineCompletionsController.get(editor);
            (0, observable_1.transaction)(tx => {
                controller?.model.get()?.stop(tx);
            });
        }
    }
    exports.HideInlineCompletion = HideInlineCompletion;
    class ToggleAlwaysShowInlineSuggestionToolbar extends actions_1.Action2 {
        static { this.ID = 'editor.action.inlineSuggest.toggleAlwaysShowToolbar'; }
        constructor() {
            super({
                id: ToggleAlwaysShowInlineSuggestionToolbar.ID,
                title: nls.localize(1083, "Always Show Toolbar"),
                f1: false,
                precondition: undefined,
                menu: [{
                        id: actions_1.MenuId.InlineSuggestionToolbar,
                        group: 'secondary',
                        order: 10,
                    }],
                toggled: contextkey_1.ContextKeyExpr.equals('config.editor.inlineSuggest.showToolbar', 'always')
            });
        }
        async run(accessor, editor) {
            const configService = accessor.get(configuration_1.IConfigurationService);
            const currentValue = configService.getValue('editor.inlineSuggest.showToolbar');
            const newValue = currentValue === 'always' ? 'onHover' : 'always';
            configService.updateValue('editor.inlineSuggest.showToolbar', newValue);
        }
    }
    exports.ToggleAlwaysShowInlineSuggestionToolbar = ToggleAlwaysShowInlineSuggestionToolbar;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[863/*vs/editor/contrib/inlineCompletions/browser/hintsWidget/hoverParticipant*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,57/*vs/base/common/htmlContent*/,2/*vs/base/common/lifecycle*/,21/*vs/base/common/observable*/,4/*vs/editor/common/core/range*/,43/*vs/editor/common/languages/language*/,84/*vs/editor/contrib/hover/browser/hoverTypes*/,295/*vs/editor/contrib/inlineCompletions/browser/controller/inlineCompletionsController*/,283/*vs/editor/contrib/inlineCompletions/browser/hintsWidget/inlineCompletionsHintsWidget*/,120/*vs/editor/browser/widget/markdownRenderer/browser/markdownRenderer*/,3/*vs/nls*/,61/*vs/platform/accessibility/common/accessibility*/,7/*vs/platform/instantiation/common/instantiation*/,59/*vs/platform/opener/common/opener*/,63/*vs/platform/telemetry/common/telemetry*/]), function (require, exports, dom, htmlContent_1, lifecycle_1, observable_1, range_1, language_1, hoverTypes_1, inlineCompletionsController_1, inlineCompletionsHintsWidget_1, markdownRenderer_1, nls, accessibility_1, instantiation_1, opener_1, telemetry_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.InlineCompletionsHoverParticipant = exports.InlineCompletionsHover = void 0;
    class InlineCompletionsHover {
        constructor(owner, range, controller) {
            this.owner = owner;
            this.range = range;
            this.controller = controller;
        }
        isValidForHoverAnchor(anchor) {
            return (anchor.type === 1 /* HoverAnchorType.Range */
                && this.range.startColumn <= anchor.range.startColumn
                && this.range.endColumn >= anchor.range.endColumn);
        }
    }
    exports.InlineCompletionsHover = InlineCompletionsHover;
    let InlineCompletionsHoverParticipant = class InlineCompletionsHoverParticipant {
        constructor(_editor, _languageService, _openerService, accessibilityService, _instantiationService, _telemetryService) {
            this._editor = _editor;
            this._languageService = _languageService;
            this._openerService = _openerService;
            this.accessibilityService = accessibilityService;
            this._instantiationService = _instantiationService;
            this._telemetryService = _telemetryService;
            this.hoverOrdinal = 4;
        }
        suggestHoverAnchor(mouseEvent) {
            const controller = inlineCompletionsController_1.InlineCompletionsController.get(this._editor);
            if (!controller) {
                return null;
            }
            const target = mouseEvent.target;
            if (target.type === 8 /* MouseTargetType.CONTENT_VIEW_ZONE */) {
                // handle the case where the mouse is over the view zone
                const viewZoneData = target.detail;
                if (controller.shouldShowHoverAtViewZone(viewZoneData.viewZoneId)) {
                    return new hoverTypes_1.HoverForeignElementAnchor(1000, this, range_1.Range.fromPositions(this._editor.getModel().validatePosition(viewZoneData.positionBefore || viewZoneData.position)), mouseEvent.event.posx, mouseEvent.event.posy, false);
                }
            }
            if (target.type === 7 /* MouseTargetType.CONTENT_EMPTY */) {
                // handle the case where the mouse is over the empty portion of a line following ghost text
                if (controller.shouldShowHoverAt(target.range)) {
                    return new hoverTypes_1.HoverForeignElementAnchor(1000, this, target.range, mouseEvent.event.posx, mouseEvent.event.posy, false);
                }
            }
            if (target.type === 6 /* MouseTargetType.CONTENT_TEXT */) {
                // handle the case where the mouse is directly over ghost text
                const mightBeForeignElement = target.detail.mightBeForeignElement;
                if (mightBeForeignElement && controller.shouldShowHoverAt(target.range)) {
                    return new hoverTypes_1.HoverForeignElementAnchor(1000, this, target.range, mouseEvent.event.posx, mouseEvent.event.posy, false);
                }
            }
            return null;
        }
        computeSync(anchor, lineDecorations) {
            if (this._editor.getOption(62 /* EditorOption.inlineSuggest */).showToolbar !== 'onHover') {
                return [];
            }
            const controller = inlineCompletionsController_1.InlineCompletionsController.get(this._editor);
            if (controller && controller.shouldShowHoverAt(anchor.range)) {
                return [new InlineCompletionsHover(this, anchor.range, controller)];
            }
            return [];
        }
        renderHoverParts(context, hoverParts) {
            const disposables = new lifecycle_1.DisposableStore();
            const part = hoverParts[0];
            this._telemetryService.publicLog2('inlineCompletionHover.shown');
            if (this.accessibilityService.isScreenReaderOptimized() && !this._editor.getOption(8 /* EditorOption.screenReaderAnnounceInlineSuggestion */)) {
                disposables.add(this.renderScreenReaderText(context, part));
            }
            const model = part.controller.model.get();
            const w = this._instantiationService.createInstance(inlineCompletionsHintsWidget_1.InlineSuggestionHintsContentWidget, this._editor, false, (0, observable_1.constObservable)(null), model.selectedInlineCompletionIndex, model.inlineCompletionsCount, model.activeCommands);
            const widgetNode = w.getDomNode();
            context.fragment.appendChild(widgetNode);
            model.triggerExplicitly();
            disposables.add(w);
            const renderedHoverPart = {
                hoverPart: part,
                hoverElement: widgetNode,
                dispose() { disposables.dispose(); }
            };
            return new hoverTypes_1.RenderedHoverParts([renderedHoverPart]);
        }
        renderScreenReaderText(context, part) {
            const disposables = new lifecycle_1.DisposableStore();
            const $ = dom.$;
            const markdownHoverElement = $('div.hover-row.markdown-hover');
            const hoverContentsElement = dom.append(markdownHoverElement, $('div.hover-contents', { ['aria-live']: 'assertive' }));
            const renderer = disposables.add(new markdownRenderer_1.MarkdownRenderer({ editor: this._editor }, this._languageService, this._openerService));
            const render = (code) => {
                disposables.add(renderer.onDidRenderAsync(() => {
                    hoverContentsElement.className = 'hover-contents code-hover-contents';
                    context.onContentsChanged();
                }));
                const inlineSuggestionAvailable = nls.localize(1089, "Suggestion:");
                const renderedContents = disposables.add(renderer.render(new htmlContent_1.MarkdownString().appendText(inlineSuggestionAvailable).appendCodeblock('text', code)));
                hoverContentsElement.replaceChildren(renderedContents.element);
            };
            disposables.add((0, observable_1.autorun)(reader => {
                /** @description update hover */
                const ghostText = part.controller.model.read(reader)?.primaryGhostText.read(reader);
                if (ghostText) {
                    const lineText = this._editor.getModel().getLineContent(ghostText.lineNumber);
                    render(ghostText.renderForScreenReader(lineText));
                }
                else {
                    dom.reset(hoverContentsElement);
                }
            }));
            context.fragment.appendChild(markdownHoverElement);
            return disposables;
        }
    };
    exports.InlineCompletionsHoverParticipant = InlineCompletionsHoverParticipant;
    exports.InlineCompletionsHoverParticipant = InlineCompletionsHoverParticipant = __decorate([
        __param(1, language_1.ILanguageService),
        __param(2, opener_1.IOpenerService),
        __param(3, accessibility_1.IAccessibilityService),
        __param(4, instantiation_1.IInstantiationService),
        __param(5, telemetry_1.ITelemetryService)
    ], InlineCompletionsHoverParticipant);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[864/*vs/editor/contrib/inlineCompletions/browser/inlineCompletions.contribution*/], __M([1/*require*/,0/*exports*/,15/*vs/editor/browser/editorExtensions*/,84/*vs/editor/contrib/hover/browser/hoverTypes*/,862/*vs/editor/contrib/inlineCompletions/browser/controller/commands*/,863/*vs/editor/contrib/inlineCompletions/browser/hintsWidget/hoverParticipant*/,617/*vs/editor/contrib/inlineCompletions/browser/inlineCompletionsAccessibleView*/,295/*vs/editor/contrib/inlineCompletions/browser/controller/inlineCompletionsController*/,380/*vs/platform/accessibility/browser/accessibleViewRegistry*/,29/*vs/platform/actions/common/actions*/]), function (require, exports, editorExtensions_1, hoverTypes_1, commands_1, hoverParticipant_1, inlineCompletionsAccessibleView_1, inlineCompletionsController_1, accessibleViewRegistry_1, actions_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    (0, editorExtensions_1.registerEditorContribution)(inlineCompletionsController_1.InlineCompletionsController.ID, inlineCompletionsController_1.InlineCompletionsController, 3 /* EditorContributionInstantiation.Eventually */);
    (0, editorExtensions_1.registerEditorAction)(commands_1.TriggerInlineSuggestionAction);
    (0, editorExtensions_1.registerEditorAction)(commands_1.ShowNextInlineSuggestionAction);
    (0, editorExtensions_1.registerEditorAction)(commands_1.ShowPreviousInlineSuggestionAction);
    (0, editorExtensions_1.registerEditorAction)(commands_1.AcceptNextWordOfInlineCompletion);
    (0, editorExtensions_1.registerEditorAction)(commands_1.AcceptNextLineOfInlineCompletion);
    (0, editorExtensions_1.registerEditorAction)(commands_1.AcceptInlineCompletion);
    (0, editorExtensions_1.registerEditorAction)(commands_1.HideInlineCompletion);
    (0, actions_1.registerAction2)(commands_1.ToggleAlwaysShowInlineSuggestionToolbar);
    hoverTypes_1.HoverParticipantRegistry.register(hoverParticipant_1.InlineCompletionsHoverParticipant);
    accessibleViewRegistry_1.AccessibleViewRegistry.register(new inlineCompletionsAccessibleView_1.InlineCompletionsAccessibleView());
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[438/*vs/editor/contrib/inlineEdits/browser/inlineEditsWidget*/], __M([1/*require*/,0/*exports*/,5/*vs/base/browser/dom*/,347/*vs/base/browser/fonts*/,2/*vs/base/common/lifecycle*/,21/*vs/base/common/observable*/,65/*vs/base/common/observableInternal/derived*/,15/*vs/editor/browser/editorExtensions*/,112/*vs/editor/browser/observableCodeEditor*/,125/*vs/editor/browser/widget/codeEditor/embeddedCodeEditorWidget*/,139/*vs/editor/browser/widget/diffEditor/registrations.contribution*/,88/*vs/editor/browser/widget/diffEditor/utils*/,70/*vs/editor/common/languages/modesRegistry*/,35/*vs/editor/common/model/textModel*/,434/*vs/editor/contrib/contextmenu/browser/contextmenu*/,379/*vs/editor/contrib/placeholderText/browser/placeholderTextContribution*/,294/*vs/editor/contrib/suggest/browser/suggestController*/,7/*vs/platform/instantiation/common/instantiation*/,521/*vs/css!vs/editor/contrib/inlineEdits/browser/inlineEditsWidget*/]), function (require, exports, dom_1, fonts_1, lifecycle_1, observable_1, derived_1, editorExtensions_1, observableCodeEditor_1, embeddedCodeEditorWidget_1, registrations_contribution_1, utils_1, modesRegistry_1, textModel_1, contextmenu_1, placeholderTextContribution_1, suggestController_1, instantiation_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.InlineEditsWidget = exports.InlineEdit = void 0;
    class InlineEdit {
        constructor(range, newLines, changes) {
            this.range = range;
            this.newLines = newLines;
            this.changes = changes;
        }
    }
    exports.InlineEdit = InlineEdit;
    let InlineEditsWidget = class InlineEditsWidget extends lifecycle_1.Disposable {
        constructor(_editor, _edit, _userPrompt, _instantiationService) {
            super();
            this._editor = _editor;
            this._edit = _edit;
            this._userPrompt = _userPrompt;
            this._instantiationService = _instantiationService;
            this._editorObs = (0, observableCodeEditor_1.observableCodeEditor)(this._editor);
            this._elements = (0, dom_1.h)('div.inline-edits-widget', {
                style: {
                    position: 'absolute',
                    overflow: 'visible',
                    top: '0px',
                    left: '0px',
                },
            }, [
                (0, dom_1.h)('div@editorContainer', { style: { position: 'absolute', top: '0px', left: '0px', width: '500px', height: '500px', } }, [
                    (0, dom_1.h)('div.toolbar@toolbar', { style: { position: 'absolute', top: '-25px', left: '0px' } }),
                    (0, dom_1.h)('div.promptEditor@promptEditor', { style: { position: 'absolute', top: '-25px', left: '80px', width: '300px', height: '22px' } }),
                    (0, dom_1.h)('div.preview@editor', { style: { position: 'absolute', top: '0px', left: '0px' } }),
                ]),
                (0, dom_1.svgElem)('svg', { style: { overflow: 'visible', pointerEvents: 'none' }, }, [
                    (0, dom_1.svgElem)('defs', [
                        (0, dom_1.svgElem)('linearGradient', {
                            id: 'Gradient2',
                            x1: '0',
                            y1: '0',
                            x2: '1',
                            y2: '0',
                        }, [
                            /*svgElem('stop', { offset: '0%', class: 'gradient-start', }),
                            svgElem('stop', { offset: '0%', class: 'gradient-start', }),
                            svgElem('stop', { offset: '20%', class: 'gradient-stop', }),*/
                            (0, dom_1.svgElem)('stop', { offset: '0%', class: 'gradient-stop', }),
                            (0, dom_1.svgElem)('stop', { offset: '100%', class: 'gradient-stop', }),
                        ]),
                    ]),
                    (0, dom_1.svgElem)('path@path', {
                        d: '',
                        fill: 'url(#Gradient2)',
                    }),
                ]),
            ]);
            this._previewTextModel = this._register(this._instantiationService.createInstance(textModel_1.TextModel, '', modesRegistry_1.PLAINTEXT_LANGUAGE_ID, textModel_1.TextModel.DEFAULT_CREATION_OPTIONS, null));
            this._setText = (0, observable_1.derived)(reader => {
                const edit = this._edit.read(reader);
                if (!edit) {
                    return;
                }
                this._previewTextModel.setValue(edit.newLines.join('\n'));
            }).recomputeInitiallyAndOnChange(this._store);
            this._promptTextModel = this._register(this._instantiationService.createInstance(textModel_1.TextModel, '', modesRegistry_1.PLAINTEXT_LANGUAGE_ID, textModel_1.TextModel.DEFAULT_CREATION_OPTIONS, null));
            this._promptEditor = this._register(this._instantiationService.createInstance(embeddedCodeEditorWidget_1.EmbeddedCodeEditorWidget, this._elements.promptEditor, {
                glyphMargin: false,
                lineNumbers: 'off',
                minimap: { enabled: false },
                guides: {
                    indentation: false,
                    bracketPairs: false,
                    bracketPairsHorizontal: false,
                    highlightActiveIndentation: false,
                },
                folding: false,
                selectOnLineNumbers: false,
                selectionHighlight: false,
                columnSelection: false,
                overviewRulerBorder: false,
                overviewRulerLanes: 0,
                lineDecorationsWidth: 0,
                lineNumbersMinChars: 0,
                placeholder: 'Describe the change you want...',
                fontFamily: fonts_1.DEFAULT_FONT_FAMILY,
            }, {
                contributions: editorExtensions_1.EditorExtensionsRegistry.getSomeEditorContributions([
                    suggestController_1.SuggestController.ID,
                    placeholderTextContribution_1.PlaceholderTextContribution.ID,
                    contextmenu_1.ContextMenuController.ID,
                ]),
                isSimpleWidget: true
            }, this._editor));
            this._previewEditor = this._register(this._instantiationService.createInstance(embeddedCodeEditorWidget_1.EmbeddedCodeEditorWidget, this._elements.editor, {
                glyphMargin: false,
                lineNumbers: 'off',
                minimap: { enabled: false },
                guides: {
                    indentation: false,
                    bracketPairs: false,
                    bracketPairsHorizontal: false,
                    highlightActiveIndentation: false,
                },
                folding: false,
                selectOnLineNumbers: false,
                selectionHighlight: false,
                columnSelection: false,
                overviewRulerBorder: false,
                overviewRulerLanes: 0,
                lineDecorationsWidth: 0,
                lineNumbersMinChars: 0,
            }, { contributions: [], }, this._editor));
            this._previewEditorObs = (0, observableCodeEditor_1.observableCodeEditor)(this._previewEditor);
            this._decorations = (0, observable_1.derived)(this, (reader) => {
                this._setText.read(reader);
                const diff = this._edit.read(reader)?.changes;
                if (!diff) {
                    return [];
                }
                const originalDecorations = [];
                const modifiedDecorations = [];
                if (diff.length === 1 && diff[0].innerChanges[0].modifiedRange.equalsRange(this._previewTextModel.getFullModelRange())) {
                    return [];
                }
                for (const m of diff) {
                    if (!m.original.isEmpty) {
                        originalDecorations.push({ range: m.original.toInclusiveRange(), options: registrations_contribution_1.diffLineDeleteDecorationBackgroundWithIndicator });
                    }
                    if (!m.modified.isEmpty) {
                        modifiedDecorations.push({ range: m.modified.toInclusiveRange(), options: registrations_contribution_1.diffLineAddDecorationBackgroundWithIndicator });
                    }
                    if (m.modified.isEmpty || m.original.isEmpty) {
                        if (!m.original.isEmpty) {
                            originalDecorations.push({ range: m.original.toInclusiveRange(), options: registrations_contribution_1.diffWholeLineDeleteDecoration });
                        }
                        if (!m.modified.isEmpty) {
                            modifiedDecorations.push({ range: m.modified.toInclusiveRange(), options: registrations_contribution_1.diffWholeLineAddDecoration });
                        }
                    }
                    else {
                        for (const i of m.innerChanges || []) {
                            // Don't show empty markers outside the line range
                            if (m.original.contains(i.originalRange.startLineNumber)) {
                                originalDecorations.push({ range: i.originalRange, options: i.originalRange.isEmpty() ? registrations_contribution_1.diffDeleteDecorationEmpty : registrations_contribution_1.diffDeleteDecoration });
                            }
                            if (m.modified.contains(i.modifiedRange.startLineNumber)) {
                                modifiedDecorations.push({ range: i.modifiedRange, options: i.modifiedRange.isEmpty() ? registrations_contribution_1.diffAddDecorationEmpty : registrations_contribution_1.diffAddDecoration });
                            }
                        }
                    }
                }
                return modifiedDecorations;
            });
            this._layout1 = (0, observable_1.derived)(this, reader => {
                const model = this._editor.getModel();
                const inlineEdit = this._edit.read(reader);
                if (!inlineEdit) {
                    return null;
                }
                const range = inlineEdit.range;
                let maxLeft = 0;
                for (let i = range.startLineNumber; i < range.endLineNumberExclusive; i++) {
                    const column = model.getLineMaxColumn(i);
                    const left = this._editor.getOffsetForColumn(i, column);
                    maxLeft = Math.max(maxLeft, left);
                }
                const layoutInfo = this._editor.getLayoutInfo();
                const contentLeft = layoutInfo.contentLeft;
                return { left: contentLeft + maxLeft };
            });
            this._layout = (0, observable_1.derived)(this, (reader) => {
                const inlineEdit = this._edit.read(reader);
                if (!inlineEdit) {
                    return null;
                }
                const range = inlineEdit.range;
                const scrollLeft = this._editorObs.scrollLeft.read(reader);
                const left = this._layout1.read(reader).left + 20 - scrollLeft;
                const selectionTop = this._editor.getTopForLineNumber(range.startLineNumber) - this._editorObs.scrollTop.read(reader);
                const selectionBottom = this._editor.getTopForLineNumber(range.endLineNumberExclusive) - this._editorObs.scrollTop.read(reader);
                const topCode = new Point(left, selectionTop);
                const bottomCode = new Point(left, selectionBottom);
                const codeHeight = selectionBottom - selectionTop;
                const codeEditDist = 50;
                const editHeight = this._editor.getOption(67 /* EditorOption.lineHeight */) * inlineEdit.newLines.length;
                const difference = codeHeight - editHeight;
                const topEdit = new Point(left + codeEditDist, selectionTop + (difference / 2));
                const bottomEdit = new Point(left + codeEditDist, selectionBottom - (difference / 2));
                return {
                    topCode,
                    bottomCode,
                    codeHeight,
                    topEdit,
                    bottomEdit,
                    editHeight,
                };
            });
            const visible = (0, observable_1.derived)(this, reader => this._edit.read(reader) !== undefined || this._userPrompt.read(reader) !== undefined);
            this._register((0, utils_1.applyStyle)(this._elements.root, {
                display: (0, observable_1.derived)(this, reader => visible.read(reader) ? 'block' : 'none')
            }));
            this._register((0, utils_1.appendRemoveOnDispose)(this._editor.getDomNode(), this._elements.root));
            this._register((0, observableCodeEditor_1.observableCodeEditor)(_editor).createOverlayWidget({
                domNode: this._elements.root,
                position: (0, observable_1.constObservable)(null),
                allowEditorOverflow: false,
                minContentWidthInPx: (0, observable_1.derived)(reader => {
                    const x = this._layout1.read(reader)?.left;
                    if (x === undefined) {
                        return 0;
                    }
                    const width = this._previewEditorObs.contentWidth.read(reader);
                    return x + width;
                }),
            }));
            this._previewEditor.setModel(this._previewTextModel);
            this._register(this._previewEditorObs.setDecorations(this._decorations));
            this._register((0, observable_1.autorun)(reader => {
                const layoutInfo = this._layout.read(reader);
                if (!layoutInfo) {
                    return;
                }
                const { topCode, bottomCode, topEdit, bottomEdit, editHeight } = layoutInfo;
                const straightWidthCode = 10;
                const straightWidthEdit = 0;
                const bezierDist = 40;
                const path = new PathBuilder()
                    .moveTo(topCode)
                    .lineTo(topCode.deltaX(straightWidthCode))
                    .curveTo(topCode.deltaX(straightWidthCode + bezierDist), topEdit.deltaX(-bezierDist - straightWidthEdit), topEdit.deltaX(-straightWidthEdit))
                    .lineTo(topEdit)
                    .lineTo(bottomEdit)
                    .lineTo(bottomEdit.deltaX(-straightWidthEdit))
                    .curveTo(bottomEdit.deltaX(-bezierDist - straightWidthEdit), bottomCode.deltaX(straightWidthCode + bezierDist), bottomCode.deltaX(straightWidthCode))
                    .lineTo(bottomCode)
                    .build();
                this._elements.path.setAttribute('d', path);
                this._elements.editorContainer.style.top = `${topEdit.y}px`;
                this._elements.editorContainer.style.left = `${topEdit.x}px`;
                this._elements.editorContainer.style.height = `${editHeight}px`;
                const width = this._previewEditorObs.contentWidth.read(reader);
                this._previewEditor.layout({ height: editHeight, width });
            }));
            this._promptEditor.setModel(this._promptTextModel);
            this._promptEditor.layout();
            this._register(createTwoWaySync(mapSettableObservable(this._userPrompt, v => v ?? '', v => v), (0, observableCodeEditor_1.observableCodeEditor)(this._promptEditor).value));
            this._register((0, observable_1.autorun)(reader => {
                const isFocused = (0, observableCodeEditor_1.observableCodeEditor)(this._promptEditor).isFocused.read(reader);
                this._elements.root.classList.toggle('focused', isFocused);
            }));
        }
    };
    exports.InlineEditsWidget = InlineEditsWidget;
    exports.InlineEditsWidget = InlineEditsWidget = __decorate([
        __param(3, instantiation_1.IInstantiationService)
    ], InlineEditsWidget);
    function mapSettableObservable(obs, fn1, fn2) {
        return (0, derived_1.derivedWithSetter)(undefined, reader => fn1(obs.read(reader)), (value, tx) => obs.set(fn2(value), tx));
    }
    class Point {
        constructor(x, y) {
            this.x = x;
            this.y = y;
        }
        deltaX(delta) {
            return new Point(this.x + delta, this.y);
        }
    }
    class PathBuilder {
        constructor() {
            this._data = '';
        }
        moveTo(point) {
            this._data += `M ${point.x} ${point.y} `;
            return this;
        }
        lineTo(point) {
            this._data += `L ${point.x} ${point.y} `;
            return this;
        }
        curveTo(cp1, cp2, to) {
            this._data += `C ${cp1.x} ${cp1.y} ${cp2.x} ${cp2.y} ${to.x} ${to.y} `;
            return this;
        }
        build() {
            return this._data;
        }
    }
    function createTwoWaySync(main, target) {
        const store = new lifecycle_1.DisposableStore();
        store.add((0, observable_1.autorun)(reader => {
            const value = main.read(reader);
            target.set(value, undefined);
        }));
        store.add((0, observable_1.autorun)(reader => {
            const value = target.read(reader);
            main.set(value, undefined);
        }));
        return store;
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[865/*vs/editor/contrib/inlineEdits/browser/inlineEditsModel*/], __M([1/*require*/,0/*exports*/,14/*vs/base/common/async*/,18/*vs/base/common/cancellation*/,102/*vs/base/common/equals*/,8/*vs/base/common/errors*/,2/*vs/base/common/lifecycle*/,21/*vs/base/common/observable*/,65/*vs/base/common/observableInternal/derived*/,22/*vs/base/common/uri*/,215/*vs/editor/browser/widget/diffEditor/diffProviderFactoryService*/,55/*vs/editor/common/core/lineRange*/,27/*vs/editor/common/languages*/,17/*vs/editor/common/services/languageFeatures*/,51/*vs/editor/common/services/model*/,378/*vs/editor/contrib/inlineCompletions/browser/model/provideInlineCompletions*/,438/*vs/editor/contrib/inlineEdits/browser/inlineEditsWidget*/]), function (require, exports, async_1, cancellation_1, equals_1, errors_1, lifecycle_1, observable_1, derived_1, uri_1, diffProviderFactoryService_1, lineRange_1, languages_1, languageFeatures_1, model_1, provideInlineCompletions_1, inlineEditsWidget_1) {
    "use strict";
    var InlineEditsModel_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.InlineEditsModel = void 0;
    let InlineEditsModel = class InlineEditsModel extends lifecycle_1.Disposable {
        static { InlineEditsModel_1 = this; }
        static { this._modelId = 0; }
        static _createUniqueUri() {
            return uri_1.URI.from({ scheme: 'inline-edits', path: new Date().toString() + String(InlineEditsModel_1._modelId++) });
        }
        constructor(textModel, _textModelVersionId, _selection, _debounceValue, languageFeaturesService, _diffProviderFactoryService, _modelService) {
            super();
            this.textModel = textModel;
            this._textModelVersionId = _textModelVersionId;
            this._selection = _selection;
            this._debounceValue = _debounceValue;
            this.languageFeaturesService = languageFeaturesService;
            this._diffProviderFactoryService = _diffProviderFactoryService;
            this._modelService = _modelService;
            this._forceUpdateExplicitlySignal = (0, observable_1.observableSignal)(this);
            // We use a semantic id to keep the same inline completion selected even if the provider reorders the completions.
            this._selectedInlineCompletionId = (0, observable_1.observableValue)(this, undefined);
            this._isActive = (0, observable_1.observableValue)(this, false);
            this._originalModel = (0, derived_1.derivedDisposable)(() => this._modelService.createModel('', null, InlineEditsModel_1._createUniqueUri())).keepObserved(this._store);
            this._modifiedModel = (0, derived_1.derivedDisposable)(() => this._modelService.createModel('', null, InlineEditsModel_1._createUniqueUri())).keepObserved(this._store);
            this._pinnedRange = new TrackedRange(this.textModel, this._textModelVersionId);
            this.isPinned = this._pinnedRange.range.map(range => !!range);
            this.userPrompt = (0, observable_1.observableValue)(this, undefined);
            this.inlineEdit = (0, observable_1.derived)(this, reader => {
                return this._inlineEdit.read(reader)?.promiseResult.read(reader)?.data;
            });
            this._inlineEdit = (0, observable_1.derived)(this, reader => {
                const edit = this.selectedInlineEdit.read(reader);
                if (!edit) {
                    return undefined;
                }
                const range = edit.inlineCompletion.range;
                if (edit.inlineCompletion.insertText.trim() === '') {
                    return undefined;
                }
                let newLines = edit.inlineCompletion.insertText.split(/\r\n|\r|\n/);
                function removeIndentation(lines) {
                    const indentation = lines[0].match(/^\s*/)?.[0] ?? '';
                    return lines.map(l => l.replace(new RegExp('^' + indentation), ''));
                }
                newLines = removeIndentation(newLines);
                const existing = this.textModel.getValueInRange(range);
                let existingLines = existing.split(/\r\n|\r|\n/);
                existingLines = removeIndentation(existingLines);
                this._originalModel.get().setValue(existingLines.join('\n'));
                this._modifiedModel.get().setValue(newLines.join('\n'));
                const d = this._diffProviderFactoryService.createDiffProvider({ diffAlgorithm: 'advanced' });
                return observable_1.ObservablePromise.fromFn(async () => {
                    const result = await d.computeDiff(this._originalModel.get(), this._modifiedModel.get(), {
                        computeMoves: false,
                        ignoreTrimWhitespace: false,
                        maxComputationTimeMs: 1000,
                    }, cancellation_1.CancellationToken.None);
                    if (result.identical) {
                        return undefined;
                    }
                    return new inlineEditsWidget_1.InlineEdit(lineRange_1.LineRange.fromRangeInclusive(range), removeIndentation(newLines), result.changes);
                });
            });
            this._fetchStore = this._register(new lifecycle_1.DisposableStore());
            this._inlineEditsFetchResult = (0, observable_1.disposableObservableValue)(this, undefined);
            this._inlineEdits = (0, observable_1.derivedOpts)({ owner: this, equalsFn: equals_1.structuralEquals }, reader => {
                return this._inlineEditsFetchResult.read(reader)?.completions.map(c => new InlineEditData(c)) ?? [];
            });
            this._fetchInlineEditsPromise = (0, observable_1.derivedHandleChanges)({
                owner: this,
                createEmptyChangeSummary: () => ({
                    inlineCompletionTriggerKind: languages_1.InlineCompletionTriggerKind.Automatic
                }),
                handleChange: (ctx, changeSummary) => {
                    /** @description fetch inline completions */
                    if (ctx.didChange(this._forceUpdateExplicitlySignal)) {
                        changeSummary.inlineCompletionTriggerKind = languages_1.InlineCompletionTriggerKind.Explicit;
                    }
                    return true;
                },
            }, async (reader, changeSummary) => {
                this._fetchStore.clear();
                this._forceUpdateExplicitlySignal.read(reader);
                /*if (!this._isActive.read(reader)) {
                    return undefined;
                }*/
                this._textModelVersionId.read(reader);
                function mapValue(value, fn) {
                    return fn(value);
                }
                const selection = this._pinnedRange.range.read(reader) ?? mapValue(this._selection.read(reader), v => v.isEmpty() ? undefined : v);
                if (!selection) {
                    this._inlineEditsFetchResult.set(undefined, undefined);
                    this.userPrompt.set(undefined, undefined);
                    return undefined;
                }
                const context = {
                    triggerKind: changeSummary.inlineCompletionTriggerKind,
                    selectedSuggestionInfo: undefined,
                    userPrompt: this.userPrompt.read(reader),
                };
                const token = (0, cancellation_1.cancelOnDispose)(this._fetchStore);
                await (0, async_1.timeout)(200, token);
                const result = await (0, provideInlineCompletions_1.provideInlineCompletions)(this.languageFeaturesService.inlineCompletionsProvider, selection, this.textModel, context, token);
                if (token.isCancellationRequested) {
                    return;
                }
                this._inlineEditsFetchResult.set(result, undefined);
            });
            this._filteredInlineEditItems = (0, observable_1.derivedOpts)({ owner: this, equalsFn: (0, equals_1.itemsEquals)() }, reader => {
                return this._inlineEdits.read(reader);
            });
            this.selectedInlineCompletionIndex = (0, observable_1.derived)(this, (reader) => {
                const selectedInlineCompletionId = this._selectedInlineCompletionId.read(reader);
                const filteredCompletions = this._filteredInlineEditItems.read(reader);
                const idx = this._selectedInlineCompletionId === undefined ? -1
                    : filteredCompletions.findIndex(v => v.semanticId === selectedInlineCompletionId);
                if (idx === -1) {
                    // Reset the selection so that the selection does not jump back when it appears again
                    this._selectedInlineCompletionId.set(undefined, undefined);
                    return 0;
                }
                return idx;
            });
            this.selectedInlineEdit = (0, observable_1.derived)(this, (reader) => {
                const filteredCompletions = this._filteredInlineEditItems.read(reader);
                const idx = this.selectedInlineCompletionIndex.read(reader);
                return filteredCompletions[idx];
            });
            this._register((0, observable_1.recomputeInitiallyAndOnChange)(this._fetchInlineEditsPromise));
        }
        async triggerExplicitly(tx) {
            (0, observable_1.subtransaction)(tx, tx => {
                this._isActive.set(true, tx);
                this._forceUpdateExplicitlySignal.trigger(tx);
            });
            await this._fetchInlineEditsPromise.get();
        }
        stop(tx) {
            (0, observable_1.subtransaction)(tx, tx => {
                this.userPrompt.set(undefined, tx);
                this._isActive.set(false, tx);
                this._inlineEditsFetchResult.set(undefined, tx);
                this._pinnedRange.setRange(undefined, tx);
                //this._source.clear(tx);
            });
        }
        async _deltaSelectedInlineCompletionIndex(delta) {
            await this.triggerExplicitly();
            const completions = this._filteredInlineEditItems.get() || [];
            if (completions.length > 0) {
                const newIdx = (this.selectedInlineCompletionIndex.get() + delta + completions.length) % completions.length;
                this._selectedInlineCompletionId.set(completions[newIdx].semanticId, undefined);
            }
            else {
                this._selectedInlineCompletionId.set(undefined, undefined);
            }
        }
        async next() {
            await this._deltaSelectedInlineCompletionIndex(1);
        }
        async previous() {
            await this._deltaSelectedInlineCompletionIndex(-1);
        }
        async accept(editor) {
            if (editor.getModel() !== this.textModel) {
                throw new errors_1.BugIndicatingError();
            }
            const edit = this.selectedInlineEdit.get();
            if (!edit) {
                return;
            }
            editor.pushUndoStop();
            editor.executeEdits('inlineSuggestion.accept', [
                edit.inlineCompletion.toSingleTextEdit().toSingleEditOperation()
            ]);
            this.stop();
        }
    };
    exports.InlineEditsModel = InlineEditsModel;
    exports.InlineEditsModel = InlineEditsModel = InlineEditsModel_1 = __decorate([
        __param(4, languageFeatures_1.ILanguageFeaturesService),
        __param(5, diffProviderFactoryService_1.IDiffProviderFactoryService),
        __param(6, model_1.IModelService)
    ], InlineEditsModel);
    class InlineEditData {
        constructor(inlineCompletion) {
            this.inlineCompletion = inlineCompletion;
            this.semanticId = this.inlineCompletion.hash();
        }
    }
    class TrackedRange extends lifecycle_1.Disposable {
        constructor(_textModel, _versionId) {
            super();
            this._textModel = _textModel;
            this._versionId = _versionId;
            this._decorations = (0, observable_1.observableValue)(this, []);
            this.range = (0, observable_1.derived)(this, reader => {
                this._versionId.read(reader);
                const deco = this._decorations.read(reader)[0];
                if (!deco) {
                    return null;
                }
                return this._textModel.getDecorationRange(deco) ?? null;
            });
            this._register((0, lifecycle_1.toDisposable)(() => {
                this._textModel.deltaDecorations(this._decorations.get(), []);
            }));
        }
        setRange(range, tx) {
            this._decorations.set(this._textModel.deltaDecorations(this._decorations.get(), range ? [{ range, options: { description: 'trackedRange' } }] : []), tx);
        }
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[439/*vs/editor/contrib/inlineEdits/browser/inlineEditsController*/], __M([1/*require*/,0/*exports*/,2/*vs/base/common/lifecycle*/,21/*vs/base/common/observable*/,65/*vs/base/common/observableInternal/derived*/,112/*vs/editor/browser/observableCodeEditor*/,171/*vs/base/common/hotReloadHelpers*/,23/*vs/editor/common/core/selection*/,79/*vs/editor/common/services/languageFeatureDebounce*/,17/*vs/editor/common/services/languageFeatures*/,390/*vs/editor/contrib/inlineEdits/browser/consts*/,865/*vs/editor/contrib/inlineEdits/browser/inlineEditsModel*/,438/*vs/editor/contrib/inlineEdits/browser/inlineEditsWidget*/,28/*vs/platform/configuration/common/configuration*/,12/*vs/platform/contextkey/common/contextkey*/,7/*vs/platform/instantiation/common/instantiation*/,397/*vs/platform/observable/common/platformObservableUtils*/]), function (require, exports, lifecycle_1, observable_1, derived_1, observableCodeEditor_1, hotReloadHelpers_1, selection_1, languageFeatureDebounce_1, languageFeatures_1, consts_1, inlineEditsModel_1, inlineEditsWidget_1, configuration_1, contextkey_1, instantiation_1, platformObservableUtils_1) {
    "use strict";
    var InlineEditsController_1;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.InlineEditsController = void 0;
    let InlineEditsController = class InlineEditsController extends lifecycle_1.Disposable {
        static { InlineEditsController_1 = this; }
        static { this.ID = 'editor.contrib.inlineEditsController'; }
        static get(editor) {
            return editor.getContribution(InlineEditsController_1.ID);
        }
        constructor(editor, _instantiationService, _contextKeyService, _debounceService, _languageFeaturesService, _configurationService) {
            super();
            this.editor = editor;
            this._instantiationService = _instantiationService;
            this._contextKeyService = _contextKeyService;
            this._debounceService = _debounceService;
            this._languageFeaturesService = _languageFeaturesService;
            this._configurationService = _configurationService;
            this._enabled = (0, platformObservableUtils_1.observableConfigValue)('editor.inlineEdits.enabled', false, this._configurationService);
            this._editorObs = (0, observableCodeEditor_1.observableCodeEditor)(this.editor);
            this._selection = (0, observable_1.derived)(this, reader => this._editorObs.cursorSelection.read(reader) ?? new selection_1.Selection(1, 1, 1, 1));
            this._debounceValue = this._debounceService.for(this._languageFeaturesService.inlineCompletionsProvider, 'InlineEditsDebounce', { min: 50, max: 50 });
            this.model = (0, derived_1.derivedDisposable)(this, reader => {
                if (!this._enabled.read(reader)) {
                    return undefined;
                }
                if (this._editorObs.isReadonly.read(reader)) {
                    return undefined;
                }
                const textModel = this._editorObs.model.read(reader);
                if (!textModel) {
                    return undefined;
                }
                const model = this._instantiationService.createInstance((0, hotReloadHelpers_1.readHotReloadableExport)(inlineEditsModel_1.InlineEditsModel, reader), textModel, this._editorObs.versionId, this._selection, this._debounceValue);
                return model;
            });
            this._hadInlineEdit = (0, observable_1.derivedObservableWithCache)(this, (reader, lastValue) => lastValue || this.model.read(reader)?.inlineEdit.read(reader) !== undefined);
            this._widget = (0, derived_1.derivedDisposable)(this, reader => {
                if (!this._hadInlineEdit.read(reader)) {
                    return undefined;
                }
                return this._instantiationService.createInstance((0, hotReloadHelpers_1.readHotReloadableExport)(inlineEditsWidget_1.InlineEditsWidget, reader), this.editor, this.model.map((m, reader) => m?.inlineEdit.read(reader)), flattenSettableObservable((reader) => this.model.read(reader)?.userPrompt ?? (0, observable_1.observableValue)('empty', '')));
            });
            this._register((0, platformObservableUtils_1.bindContextKey)(consts_1.inlineEditVisible, this._contextKeyService, r => !!this.model.read(r)?.inlineEdit.read(r)));
            this._register((0, platformObservableUtils_1.bindContextKey)(consts_1.isPinnedContextKey, this._contextKeyService, r => !!this.model.read(r)?.isPinned.read(r)));
            this.model.recomputeInitiallyAndOnChange(this._store);
            this._widget.recomputeInitiallyAndOnChange(this._store);
        }
    };
    exports.InlineEditsController = InlineEditsController;
    exports.InlineEditsController = InlineEditsController = InlineEditsController_1 = __decorate([
        __param(1, instantiation_1.IInstantiationService),
        __param(2, contextkey_1.IContextKeyService),
        __param(3, languageFeatureDebounce_1.ILanguageFeatureDebounceService),
        __param(4, languageFeatures_1.ILanguageFeaturesService),
        __param(5, configuration_1.IConfigurationService)
    ], InlineEditsController);
    function flattenSettableObservable(fn) {
        return (0, derived_1.derivedWithSetter)(undefined, reader => {
            const obs = fn(reader);
            return obs.read(reader);
        }, (value, tx) => {
            fn(undefined).set(value, tx);
        });
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[866/*vs/editor/contrib/inlineEdits/browser/commands*/], __M([1/*require*/,0/*exports*/,26/*vs/base/common/codicons*/,21/*vs/base/common/observable*/,92/*vs/base/common/observableInternal/base*/,15/*vs/editor/browser/editorExtensions*/,125/*vs/editor/browser/widget/codeEditor/embeddedCodeEditorWidget*/,20/*vs/editor/common/editorContextKeys*/,390/*vs/editor/contrib/inlineEdits/browser/consts*/,439/*vs/editor/contrib/inlineEdits/browser/inlineEditsController*/,3/*vs/nls*/,29/*vs/platform/actions/common/actions*/,12/*vs/platform/contextkey/common/contextkey*/]), function (require, exports, codicons_1, observable_1, base_1, editorExtensions_1, embeddedCodeEditorWidget_1, editorContextKeys_1, consts_1, inlineEditsController_1, nls, actions_1, contextkey_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.HideInlineEdit = exports.AcceptInlineEdit = exports.TriggerInlineEditAction = exports.ShowPreviousInlineEditAction = exports.ShowNextInlineEditAction = void 0;
    function labelAndAlias(str) {
        return {
            label: str.value,
            alias: str.original,
        };
    }
    class ShowNextInlineEditAction extends editorExtensions_1.EditorAction {
        static { this.ID = consts_1.showNextInlineEditActionId; }
        constructor() {
            super({
                id: ShowNextInlineEditAction.ID,
                ...labelAndAlias(nls.localize2(1096, "Show Next Inline Edit")),
                precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, consts_1.inlineEditVisible),
                kbOpts: {
                    weight: 100,
                    primary: 512 /* KeyMod.Alt */ | 94 /* KeyCode.BracketRight */,
                },
            });
        }
        async run(accessor, editor) {
            const controller = inlineEditsController_1.InlineEditsController.get(editor);
            controller?.model.get()?.next();
        }
    }
    exports.ShowNextInlineEditAction = ShowNextInlineEditAction;
    class ShowPreviousInlineEditAction extends editorExtensions_1.EditorAction {
        static { this.ID = consts_1.showPreviousInlineEditActionId; }
        constructor() {
            super({
                id: ShowPreviousInlineEditAction.ID,
                ...labelAndAlias(nls.localize2(1097, "Show Previous Inline Edit")),
                precondition: contextkey_1.ContextKeyExpr.and(editorContextKeys_1.EditorContextKeys.writable, consts_1.inlineEditVisible),
                kbOpts: {
                    weight: 100,
                    primary: 512 /* KeyMod.Alt */ | 92 /* KeyCode.BracketLeft */,
                },
            });
        }
        async run(accessor, editor) {
            const controller = inlineEditsController_1.InlineEditsController.get(editor);
            controller?.model.get()?.previous();
        }
    }
    exports.ShowPreviousInlineEditAction = ShowPreviousInlineEditAction;
    class TriggerInlineEditAction extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: 'editor.action.inlineEdits.trigger',
                ...labelAndAlias(nls.localize2(1098, "Trigger Inline Edit")),
                precondition: editorContextKeys_1.EditorContextKeys.writable
            });
        }
        async run(accessor, editor) {
            const controller = inlineEditsController_1.InlineEditsController.get(editor);
            await (0, base_1.asyncTransaction)(async (tx) => {
                /** @description triggerExplicitly from command */
                await controller?.model.get()?.triggerExplicitly(tx);
            });
        }
    }
    exports.TriggerInlineEditAction = TriggerInlineEditAction;
    class AcceptInlineEdit extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: consts_1.inlineEditAcceptId,
                ...labelAndAlias(nls.localize2(1099, "Accept Inline Edit")),
                precondition: consts_1.inlineEditVisible,
                menuOpts: {
                    menuId: actions_1.MenuId.InlineEditsActions,
                    title: nls.localize(1095, "Accept Inline Edit"),
                    group: 'primary',
                    order: 1,
                    icon: codicons_1.Codicon.check,
                },
                kbOpts: {
                    primary: 2048 /* KeyMod.CtrlCmd */ | 10 /* KeyCode.Space */,
                    weight: 20000,
                    kbExpr: consts_1.inlineEditVisible,
                }
            });
        }
        async run(accessor, editor) {
            if (editor instanceof embeddedCodeEditorWidget_1.EmbeddedCodeEditorWidget) {
                editor = editor.getParentEditor();
            }
            const controller = inlineEditsController_1.InlineEditsController.get(editor);
            if (controller) {
                controller.model.get()?.accept(controller.editor);
                controller.editor.focus();
            }
        }
    }
    exports.AcceptInlineEdit = AcceptInlineEdit;
    /*
    TODO@hediet
    export class PinInlineEdit extends EditorAction {
        constructor() {
            super({
                id: 'editor.action.inlineEdits.pin',
                ...labelAndAlias(nls.localize2('action.inlineEdits.pin', "Pin Inline Edit")),
                precondition: undefined,
                kbOpts: {
                    primary: KeyMod.Shift | KeyCode.Space,
                    weight: 20000,
                }
            });
        }
    
        public async run(accessor: ServicesAccessor | undefined, editor: ICodeEditor): Promise<void> {
            const controller = InlineEditsController.get(editor);
            if (controller) {
                controller.model.get()?.togglePin();
            }
        }
    }
    
    MenuRegistry.appendMenuItem(MenuId.InlineEditsActions, {
        command: {
            id: 'editor.action.inlineEdits.pin',
            title: nls.localize('Pin', "Pin"),
            icon: Codicon.pin,
        },
        group: 'primary',
        order: 1,
        when: isPinnedContextKey.negate(),
    });
    
    MenuRegistry.appendMenuItem(MenuId.InlineEditsActions, {
        command: {
            id: 'editor.action.inlineEdits.unpin',
            title: nls.localize('Unpin', "Unpin"),
            icon: Codicon.pinned,
        },
        group: 'primary',
        order: 1,
        when: isPinnedContextKey,
    });*/
    class HideInlineEdit extends editorExtensions_1.EditorAction {
        static { this.ID = 'editor.action.inlineEdits.hide'; }
        constructor() {
            super({
                id: HideInlineEdit.ID,
                ...labelAndAlias(nls.localize2(1100, "Hide Inline Edit")),
                precondition: consts_1.inlineEditVisible,
                kbOpts: {
                    weight: 100,
                    primary: 9 /* KeyCode.Escape */,
                }
            });
        }
        async run(accessor, editor) {
            const controller = inlineEditsController_1.InlineEditsController.get(editor);
            (0, observable_1.transaction)(tx => {
                controller?.model.get()?.stop(tx);
            });
        }
    }
    exports.HideInlineEdit = HideInlineEdit;
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[867/*vs/editor/contrib/inlineEdits/browser/inlineEdits.contribution*/], __M([1/*require*/,0/*exports*/,15/*vs/editor/browser/editorExtensions*/,866/*vs/editor/contrib/inlineEdits/browser/commands*/,439/*vs/editor/contrib/inlineEdits/browser/inlineEditsController*/]), function (require, exports, editorExtensions_1, commands_1, inlineEditsController_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    (0, editorExtensions_1.registerEditorContribution)(inlineEditsController_1.InlineEditsController.ID, inlineEditsController_1.InlineEditsController, 3 /* EditorContributionInstantiation.Eventually */);
    (0, editorExtensions_1.registerEditorAction)(commands_1.TriggerInlineEditAction);
    (0, editorExtensions_1.registerEditorAction)(commands_1.ShowNextInlineEditAction);
    (0, editorExtensions_1.registerEditorAction)(commands_1.ShowPreviousInlineEditAction);
    (0, editorExtensions_1.registerEditorAction)(commands_1.AcceptInlineEdit);
    (0, editorExtensions_1.registerEditorAction)(commands_1.HideInlineEdit);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[868/*vs/editor/contrib/suggest/browser/suggestInlineCompletions*/], __M([1/*require*/,0/*exports*/,18/*vs/base/common/cancellation*/,82/*vs/base/common/filters*/,53/*vs/base/common/iterator*/,2/*vs/base/common/lifecycle*/,34/*vs/editor/browser/services/codeEditorService*/,4/*vs/editor/common/core/range*/,130/*vs/editor/common/editorFeatures*/,17/*vs/editor/common/services/languageFeatures*/,342/*vs/editor/contrib/suggest/browser/completionModel*/,155/*vs/editor/contrib/suggest/browser/suggest*/,405/*vs/editor/contrib/suggest/browser/suggestMemory*/,437/*vs/editor/contrib/suggest/browser/suggestModel*/,343/*vs/editor/contrib/suggest/browser/wordDistance*/,117/*vs/platform/clipboard/common/clipboardService*/]), function (require, exports, cancellation_1, filters_1, iterator_1, lifecycle_1, codeEditorService_1, range_1, editorFeatures_1, languageFeatures_1, completionModel_1, suggest_1, suggestMemory_1, suggestModel_1, wordDistance_1, clipboardService_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SuggestInlineCompletions = void 0;
    class SuggestInlineCompletion {
        constructor(range, insertText, filterText, additionalTextEdits, command, completion) {
            this.range = range;
            this.insertText = insertText;
            this.filterText = filterText;
            this.additionalTextEdits = additionalTextEdits;
            this.command = command;
            this.completion = completion;
        }
    }
    let InlineCompletionResults = class InlineCompletionResults extends lifecycle_1.RefCountedDisposable {
        constructor(model, line, word, completionModel, completions, _suggestMemoryService) {
            super(completions.disposable);
            this.model = model;
            this.line = line;
            this.word = word;
            this.completionModel = completionModel;
            this._suggestMemoryService = _suggestMemoryService;
        }
        canBeReused(model, line, word) {
            return this.model === model // same model
                && this.line === line
                && this.word.word.length > 0
                && this.word.startColumn === word.startColumn && this.word.endColumn < word.endColumn // same word
                && this.completionModel.getIncompleteProvider().size === 0; // no incomplete results
        }
        get items() {
            const result = [];
            // Split items by preselected index. This ensures the memory-selected item shows first and that better/worst
            // ranked items are before/after
            const { items } = this.completionModel;
            const selectedIndex = this._suggestMemoryService.select(this.model, { lineNumber: this.line, column: this.word.endColumn + this.completionModel.lineContext.characterCountDelta }, items);
            const first = iterator_1.Iterable.slice(items, selectedIndex);
            const second = iterator_1.Iterable.slice(items, 0, selectedIndex);
            let resolveCount = 5;
            for (const item of iterator_1.Iterable.concat(first, second)) {
                if (item.score === filters_1.FuzzyScore.Default) {
                    // skip items that have no overlap
                    continue;
                }
                const range = new range_1.Range(item.editStart.lineNumber, item.editStart.column, item.editInsertEnd.lineNumber, item.editInsertEnd.column + this.completionModel.lineContext.characterCountDelta // end PLUS character delta
                );
                const insertText = item.completion.insertTextRules && (item.completion.insertTextRules & 4 /* CompletionItemInsertTextRule.InsertAsSnippet */)
                    ? { snippet: item.completion.insertText }
                    : item.completion.insertText;
                result.push(new SuggestInlineCompletion(range, insertText, item.filterTextLow ?? item.labelLow, item.completion.additionalTextEdits, item.completion.command, item));
                // resolve the first N suggestions eagerly
                if (resolveCount-- >= 0) {
                    item.resolve(cancellation_1.CancellationToken.None);
                }
            }
            return result;
        }
    };
    InlineCompletionResults = __decorate([
        __param(5, suggestMemory_1.ISuggestMemoryService)
    ], InlineCompletionResults);
    let SuggestInlineCompletions = class SuggestInlineCompletions extends lifecycle_1.Disposable {
        constructor(_languageFeatureService, _clipboardService, _suggestMemoryService, _editorService) {
            super();
            this._languageFeatureService = _languageFeatureService;
            this._clipboardService = _clipboardService;
            this._suggestMemoryService = _suggestMemoryService;
            this._editorService = _editorService;
            this._store.add(_languageFeatureService.inlineCompletionsProvider.register('*', this));
        }
        async provideInlineCompletions(model, position, context, token) {
            if (context.selectedSuggestionInfo) {
                return;
            }
            let editor;
            for (const candidate of this._editorService.listCodeEditors()) {
                if (candidate.getModel() === model) {
                    editor = candidate;
                    break;
                }
            }
            if (!editor) {
                return;
            }
            const config = editor.getOption(90 /* EditorOption.quickSuggestions */);
            if (suggest_1.QuickSuggestionsOptions.isAllOff(config)) {
                // quick suggest is off (for this model/language)
                return;
            }
            model.tokenization.tokenizeIfCheap(position.lineNumber);
            const lineTokens = model.tokenization.getLineTokens(position.lineNumber);
            const tokenType = lineTokens.getStandardTokenType(lineTokens.findTokenIndexAtOffset(Math.max(position.column - 1 - 1, 0)));
            if (suggest_1.QuickSuggestionsOptions.valueFor(config, tokenType) !== 'inline') {
                // quick suggest is off (for this token)
                return undefined;
            }
            // We consider non-empty leading words and trigger characters. The latter only
            // when no word is being typed (word characters superseed trigger characters)
            let wordInfo = model.getWordAtPosition(position);
            let triggerCharacterInfo;
            if (!wordInfo?.word) {
                triggerCharacterInfo = this._getTriggerCharacterInfo(model, position);
            }
            if (!wordInfo?.word && !triggerCharacterInfo) {
                // not at word, not a trigger character
                return;
            }
            // ensure that we have word information and that we are at the end of a word
            // otherwise we stop because we don't want to do quick suggestions inside words
            if (!wordInfo) {
                wordInfo = model.getWordUntilPosition(position);
            }
            if (wordInfo.endColumn !== position.column) {
                return;
            }
            let result;
            const leadingLineContents = model.getValueInRange(new range_1.Range(position.lineNumber, 1, position.lineNumber, position.column));
            if (!triggerCharacterInfo && this._lastResult?.canBeReused(model, position.lineNumber, wordInfo)) {
                // reuse a previous result iff possible, only a refilter is needed
                // TODO@jrieken this can be improved further and only incomplete results can be updated
                // console.log(`REUSE with ${wordInfo.word}`);
                const newLineContext = new completionModel_1.LineContext(leadingLineContents, position.column - this._lastResult.word.endColumn);
                this._lastResult.completionModel.lineContext = newLineContext;
                this._lastResult.acquire();
                result = this._lastResult;
            }
            else {
                // refesh model is required
                const completions = await (0, suggest_1.provideSuggestionItems)(this._languageFeatureService.completionProvider, model, position, new suggest_1.CompletionOptions(undefined, suggestModel_1.SuggestModel.createSuggestFilter(editor).itemKind, triggerCharacterInfo?.providers), triggerCharacterInfo && { triggerKind: 1 /* CompletionTriggerKind.TriggerCharacter */, triggerCharacter: triggerCharacterInfo.ch }, token);
                let clipboardText;
                if (completions.needsClipboard) {
                    clipboardText = await this._clipboardService.readText();
                }
                const completionModel = new completionModel_1.CompletionModel(completions.items, position.column, new completionModel_1.LineContext(leadingLineContents, 0), wordDistance_1.WordDistance.None, editor.getOption(119 /* EditorOption.suggest */), editor.getOption(113 /* EditorOption.snippetSuggestions */), { boostFullMatch: false, firstMatchCanBeWeak: false }, clipboardText);
                result = new InlineCompletionResults(model, position.lineNumber, wordInfo, completionModel, completions, this._suggestMemoryService);
            }
            this._lastResult = result;
            return result;
        }
        handleItemDidShow(_completions, item) {
            item.completion.resolve(cancellation_1.CancellationToken.None);
        }
        freeInlineCompletions(result) {
            result.release();
        }
        _getTriggerCharacterInfo(model, position) {
            const ch = model.getValueInRange(range_1.Range.fromPositions({ lineNumber: position.lineNumber, column: position.column - 1 }, position));
            const providers = new Set();
            for (const provider of this._languageFeatureService.completionProvider.all(model)) {
                if (provider.triggerCharacters?.includes(ch)) {
                    providers.add(provider);
                }
            }
            if (providers.size === 0) {
                return undefined;
            }
            return { providers, ch };
        }
    };
    exports.SuggestInlineCompletions = SuggestInlineCompletions;
    exports.SuggestInlineCompletions = SuggestInlineCompletions = __decorate([
        __param(0, languageFeatures_1.ILanguageFeaturesService),
        __param(1, clipboardService_1.IClipboardService),
        __param(2, suggestMemory_1.ISuggestMemoryService),
        __param(3, codeEditorService_1.ICodeEditorService)
    ], SuggestInlineCompletions);
    (0, editorFeatures_1.registerEditorFeature)(SuggestInlineCompletions);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[440/*vs/platform/workspace/common/workspaceTrust*/], __M([1/*require*/,0/*exports*/,7/*vs/platform/instantiation/common/instantiation*/]), function (require, exports, instantiation_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.IWorkspaceTrustManagementService = void 0;
    exports.IWorkspaceTrustManagementService = (0, instantiation_1.createDecorator)('workspaceTrustManagementService');
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[869/*vs/editor/contrib/unicodeHighlighter/browser/unicodeHighlighter*/], __M([1/*require*/,0/*exports*/,14/*vs/base/common/async*/,26/*vs/base/common/codicons*/,57/*vs/base/common/htmlContent*/,2/*vs/base/common/lifecycle*/,16/*vs/base/common/platform*/,11/*vs/base/common/strings*/,15/*vs/editor/browser/editorExtensions*/,37/*vs/editor/common/config/editorOptions*/,35/*vs/editor/common/model/textModel*/,328/*vs/editor/common/services/unicodeTextModelHighlighter*/,100/*vs/editor/common/services/editorWorker*/,43/*vs/editor/common/languages/language*/,375/*vs/editor/common/viewModel/viewModelDecorations*/,84/*vs/editor/contrib/hover/browser/hoverTypes*/,217/*vs/editor/contrib/hover/browser/markdownHoverParticipant*/,766/*vs/editor/contrib/unicodeHighlighter/browser/bannerController*/,3/*vs/nls*/,28/*vs/platform/configuration/common/configuration*/,7/*vs/platform/instantiation/common/instantiation*/,59/*vs/platform/opener/common/opener*/,66/*vs/platform/quickinput/common/quickInput*/,71/*vs/platform/theme/common/iconRegistry*/,440/*vs/platform/workspace/common/workspaceTrust*/,535/*vs/css!vs/editor/contrib/unicodeHighlighter/browser/unicodeHighlighter*/]), function (require, exports, async_1, codicons_1, htmlContent_1, lifecycle_1, platform, strings_1, editorExtensions_1, editorOptions_1, textModel_1, unicodeTextModelHighlighter_1, editorWorker_1, language_1, viewModelDecorations_1, hoverTypes_1, markdownHoverParticipant_1, bannerController_1, nls, configuration_1, instantiation_1, opener_1, quickInput_1, iconRegistry_1, workspaceTrust_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ShowExcludeOptions = exports.DisableHighlightingOfNonBasicAsciiCharactersAction = exports.DisableHighlightingOfInvisibleCharactersAction = exports.DisableHighlightingOfAmbiguousCharactersAction = exports.DisableHighlightingInStringsAction = exports.DisableHighlightingInCommentsAction = exports.UnicodeHighlighterHoverParticipant = exports.UnicodeHighlighter = exports.warningIcon = void 0;
    exports.warningIcon = (0, iconRegistry_1.registerIcon)('extensions-warning-message', codicons_1.Codicon.warning, nls.localize(1386, 'Icon shown with a warning message in the extensions editor.'));
    let UnicodeHighlighter = class UnicodeHighlighter extends lifecycle_1.Disposable {
        static { this.ID = 'editor.contrib.unicodeHighlighter'; }
        constructor(_editor, _editorWorkerService, _workspaceTrustService, instantiationService) {
            super();
            this._editor = _editor;
            this._editorWorkerService = _editorWorkerService;
            this._workspaceTrustService = _workspaceTrustService;
            this._highlighter = null;
            this._bannerClosed = false;
            this._updateState = (state) => {
                if (state && state.hasMore) {
                    if (this._bannerClosed) {
                        return;
                    }
                    // This document contains many non-basic ASCII characters.
                    const max = Math.max(state.ambiguousCharacterCount, state.nonBasicAsciiCharacterCount, state.invisibleCharacterCount);
                    let data;
                    if (state.nonBasicAsciiCharacterCount >= max) {
                        data = {
                            message: nls.localize(1387, 'This document contains many non-basic ASCII unicode characters'),
                            command: new DisableHighlightingOfNonBasicAsciiCharactersAction(),
                        };
                    }
                    else if (state.ambiguousCharacterCount >= max) {
                        data = {
                            message: nls.localize(1388, 'This document contains many ambiguous unicode characters'),
                            command: new DisableHighlightingOfAmbiguousCharactersAction(),
                        };
                    }
                    else if (state.invisibleCharacterCount >= max) {
                        data = {
                            message: nls.localize(1389, 'This document contains many invisible unicode characters'),
                            command: new DisableHighlightingOfInvisibleCharactersAction(),
                        };
                    }
                    else {
                        throw new Error('Unreachable');
                    }
                    this._bannerController.show({
                        id: 'unicodeHighlightBanner',
                        message: data.message,
                        icon: exports.warningIcon,
                        actions: [
                            {
                                label: data.command.shortLabel,
                                href: `command:${data.command.id}`
                            }
                        ],
                        onClose: () => {
                            this._bannerClosed = true;
                        },
                    });
                }
                else {
                    this._bannerController.hide();
                }
            };
            this._bannerController = this._register(instantiationService.createInstance(bannerController_1.BannerController, _editor));
            this._register(this._editor.onDidChangeModel(() => {
                this._bannerClosed = false;
                this._updateHighlighter();
            }));
            this._options = _editor.getOption(126 /* EditorOption.unicodeHighlighting */);
            this._register(_workspaceTrustService.onDidChangeTrust(e => {
                this._updateHighlighter();
            }));
            this._register(_editor.onDidChangeConfiguration(e => {
                if (e.hasChanged(126 /* EditorOption.unicodeHighlighting */)) {
                    this._options = _editor.getOption(126 /* EditorOption.unicodeHighlighting */);
                    this._updateHighlighter();
                }
            }));
            this._updateHighlighter();
        }
        dispose() {
            if (this._highlighter) {
                this._highlighter.dispose();
                this._highlighter = null;
            }
            super.dispose();
        }
        _updateHighlighter() {
            this._updateState(null);
            if (this._highlighter) {
                this._highlighter.dispose();
                this._highlighter = null;
            }
            if (!this._editor.hasModel()) {
                return;
            }
            const options = resolveOptions(this._workspaceTrustService.isWorkspaceTrusted(), this._options);
            if ([
                options.nonBasicASCII,
                options.ambiguousCharacters,
                options.invisibleCharacters,
            ].every((option) => option === false)) {
                // Don't do anything if the feature is fully disabled
                return;
            }
            const highlightOptions = {
                nonBasicASCII: options.nonBasicASCII,
                ambiguousCharacters: options.ambiguousCharacters,
                invisibleCharacters: options.invisibleCharacters,
                includeComments: options.includeComments,
                includeStrings: options.includeStrings,
                allowedCodePoints: Object.keys(options.allowedCharacters).map(c => c.codePointAt(0)),
                allowedLocales: Object.keys(options.allowedLocales).map(locale => {
                    if (locale === '_os') {
                        const osLocale = new Intl.NumberFormat().resolvedOptions().locale;
                        return osLocale;
                    }
                    else if (locale === '_vscode') {
                        return platform.language;
                    }
                    return locale;
                }),
            };
            if (this._editorWorkerService.canComputeUnicodeHighlights(this._editor.getModel().uri)) {
                this._highlighter = new DocumentUnicodeHighlighter(this._editor, highlightOptions, this._updateState, this._editorWorkerService);
            }
            else {
                this._highlighter = new ViewportUnicodeHighlighter(this._editor, highlightOptions, this._updateState);
            }
        }
        getDecorationInfo(decoration) {
            if (this._highlighter) {
                return this._highlighter.getDecorationInfo(decoration);
            }
            return null;
        }
    };
    exports.UnicodeHighlighter = UnicodeHighlighter;
    exports.UnicodeHighlighter = UnicodeHighlighter = __decorate([
        __param(1, editorWorker_1.IEditorWorkerService),
        __param(2, workspaceTrust_1.IWorkspaceTrustManagementService),
        __param(3, instantiation_1.IInstantiationService)
    ], UnicodeHighlighter);
    function resolveOptions(trusted, options) {
        return {
            nonBasicASCII: options.nonBasicASCII === editorOptions_1.inUntrustedWorkspace ? !trusted : options.nonBasicASCII,
            ambiguousCharacters: options.ambiguousCharacters,
            invisibleCharacters: options.invisibleCharacters,
            includeComments: options.includeComments === editorOptions_1.inUntrustedWorkspace ? !trusted : options.includeComments,
            includeStrings: options.includeStrings === editorOptions_1.inUntrustedWorkspace ? !trusted : options.includeStrings,
            allowedCharacters: options.allowedCharacters,
            allowedLocales: options.allowedLocales,
        };
    }
    let DocumentUnicodeHighlighter = class DocumentUnicodeHighlighter extends lifecycle_1.Disposable {
        constructor(_editor, _options, _updateState, _editorWorkerService) {
            super();
            this._editor = _editor;
            this._options = _options;
            this._updateState = _updateState;
            this._editorWorkerService = _editorWorkerService;
            this._model = this._editor.getModel();
            this._decorations = this._editor.createDecorationsCollection();
            this._updateSoon = this._register(new async_1.RunOnceScheduler(() => this._update(), 250));
            this._register(this._editor.onDidChangeModelContent(() => {
                this._updateSoon.schedule();
            }));
            this._updateSoon.schedule();
        }
        dispose() {
            this._decorations.clear();
            super.dispose();
        }
        _update() {
            if (this._model.isDisposed()) {
                return;
            }
            if (!this._model.mightContainNonBasicASCII()) {
                this._decorations.clear();
                return;
            }
            const modelVersionId = this._model.getVersionId();
            this._editorWorkerService
                .computedUnicodeHighlights(this._model.uri, this._options)
                .then((info) => {
                if (this._model.isDisposed()) {
                    return;
                }
                if (this._model.getVersionId() !== modelVersionId) {
                    // model changed in the meantime
                    return;
                }
                this._updateState(info);
                const decorations = [];
                if (!info.hasMore) {
                    // Don't show decoration if there are too many.
                    // In this case, a banner is shown.
                    for (const range of info.ranges) {
                        decorations.push({
                            range: range,
                            options: Decorations.instance.getDecorationFromOptions(this._options),
                        });
                    }
                }
                this._decorations.set(decorations);
            });
        }
        getDecorationInfo(decoration) {
            if (!this._decorations.has(decoration)) {
                return null;
            }
            const model = this._editor.getModel();
            if (!(0, viewModelDecorations_1.isModelDecorationVisible)(model, decoration)) {
                return null;
            }
            const text = model.getValueInRange(decoration.range);
            return {
                reason: computeReason(text, this._options),
                inComment: (0, viewModelDecorations_1.isModelDecorationInComment)(model, decoration),
                inString: (0, viewModelDecorations_1.isModelDecorationInString)(model, decoration),
            };
        }
    };
    DocumentUnicodeHighlighter = __decorate([
        __param(3, editorWorker_1.IEditorWorkerService)
    ], DocumentUnicodeHighlighter);
    class ViewportUnicodeHighlighter extends lifecycle_1.Disposable {
        constructor(_editor, _options, _updateState) {
            super();
            this._editor = _editor;
            this._options = _options;
            this._updateState = _updateState;
            this._model = this._editor.getModel();
            this._decorations = this._editor.createDecorationsCollection();
            this._updateSoon = this._register(new async_1.RunOnceScheduler(() => this._update(), 250));
            this._register(this._editor.onDidLayoutChange(() => {
                this._updateSoon.schedule();
            }));
            this._register(this._editor.onDidScrollChange(() => {
                this._updateSoon.schedule();
            }));
            this._register(this._editor.onDidChangeHiddenAreas(() => {
                this._updateSoon.schedule();
            }));
            this._register(this._editor.onDidChangeModelContent(() => {
                this._updateSoon.schedule();
            }));
            this._updateSoon.schedule();
        }
        dispose() {
            this._decorations.clear();
            super.dispose();
        }
        _update() {
            if (this._model.isDisposed()) {
                return;
            }
            if (!this._model.mightContainNonBasicASCII()) {
                this._decorations.clear();
                return;
            }
            const ranges = this._editor.getVisibleRanges();
            const decorations = [];
            const totalResult = {
                ranges: [],
                ambiguousCharacterCount: 0,
                invisibleCharacterCount: 0,
                nonBasicAsciiCharacterCount: 0,
                hasMore: false,
            };
            for (const range of ranges) {
                const result = unicodeTextModelHighlighter_1.UnicodeTextModelHighlighter.computeUnicodeHighlights(this._model, this._options, range);
                for (const r of result.ranges) {
                    totalResult.ranges.push(r);
                }
                totalResult.ambiguousCharacterCount += totalResult.ambiguousCharacterCount;
                totalResult.invisibleCharacterCount += totalResult.invisibleCharacterCount;
                totalResult.nonBasicAsciiCharacterCount += totalResult.nonBasicAsciiCharacterCount;
                totalResult.hasMore = totalResult.hasMore || result.hasMore;
            }
            if (!totalResult.hasMore) {
                // Don't show decorations if there are too many.
                // A banner will be shown instead.
                for (const range of totalResult.ranges) {
                    decorations.push({ range, options: Decorations.instance.getDecorationFromOptions(this._options) });
                }
            }
            this._updateState(totalResult);
            this._decorations.set(decorations);
        }
        getDecorationInfo(decoration) {
            if (!this._decorations.has(decoration)) {
                return null;
            }
            const model = this._editor.getModel();
            const text = model.getValueInRange(decoration.range);
            if (!(0, viewModelDecorations_1.isModelDecorationVisible)(model, decoration)) {
                return null;
            }
            return {
                reason: computeReason(text, this._options),
                inComment: (0, viewModelDecorations_1.isModelDecorationInComment)(model, decoration),
                inString: (0, viewModelDecorations_1.isModelDecorationInString)(model, decoration),
            };
        }
    }
    const configureUnicodeHighlightOptionsStr = nls.localize(1390, 'Configure Unicode Highlight Options');
    let UnicodeHighlighterHoverParticipant = class UnicodeHighlighterHoverParticipant {
        constructor(_editor, _languageService, _openerService) {
            this._editor = _editor;
            this._languageService = _languageService;
            this._openerService = _openerService;
            this.hoverOrdinal = 5;
        }
        computeSync(anchor, lineDecorations) {
            if (!this._editor.hasModel() || anchor.type !== 1 /* HoverAnchorType.Range */) {
                return [];
            }
            const model = this._editor.getModel();
            const unicodeHighlighter = this._editor.getContribution(UnicodeHighlighter.ID);
            if (!unicodeHighlighter) {
                return [];
            }
            const result = [];
            const existedReason = new Set();
            let index = 300;
            for (const d of lineDecorations) {
                const highlightInfo = unicodeHighlighter.getDecorationInfo(d);
                if (!highlightInfo) {
                    continue;
                }
                const char = model.getValueInRange(d.range);
                // text refers to a single character.
                const codePoint = char.codePointAt(0);
                const codePointStr = formatCodePointMarkdown(codePoint);
                let reason;
                switch (highlightInfo.reason.kind) {
                    case 0 /* UnicodeHighlighterReasonKind.Ambiguous */: {
                        if ((0, strings_1.isBasicASCII)(highlightInfo.reason.confusableWith)) {
                            reason = nls.localize(1391, 'The character {0} could be confused with the ASCII character {1}, which is more common in source code.', codePointStr, formatCodePointMarkdown(highlightInfo.reason.confusableWith.codePointAt(0)));
                        }
                        else {
                            reason = nls.localize(1392, 'The character {0} could be confused with the character {1}, which is more common in source code.', codePointStr, formatCodePointMarkdown(highlightInfo.reason.confusableWith.codePointAt(0)));
                        }
                        break;
                    }
                    case 1 /* UnicodeHighlighterReasonKind.Invisible */:
                        reason = nls.localize(1393, 'The character {0} is invisible.', codePointStr);
                        break;
                    case 2 /* UnicodeHighlighterReasonKind.NonBasicAscii */:
                        reason = nls.localize(1394, 'The character {0} is not a basic ASCII character.', codePointStr);
                        break;
                }
                if (existedReason.has(reason)) {
                    continue;
                }
                existedReason.add(reason);
                const adjustSettingsArgs = {
                    codePoint: codePoint,
                    reason: highlightInfo.reason,
                    inComment: highlightInfo.inComment,
                    inString: highlightInfo.inString,
                };
                const adjustSettings = nls.localize(1395, 'Adjust settings');
                const uri = `command:${ShowExcludeOptions.ID}?${encodeURIComponent(JSON.stringify(adjustSettingsArgs))}`;
                const markdown = new htmlContent_1.MarkdownString('', true)
                    .appendMarkdown(reason)
                    .appendText(' ')
                    .appendLink(uri, adjustSettings, configureUnicodeHighlightOptionsStr);
                result.push(new markdownHoverParticipant_1.MarkdownHover(this, d.range, [markdown], false, index++));
            }
            return result;
        }
        renderHoverParts(context, hoverParts) {
            return (0, markdownHoverParticipant_1.renderMarkdownHovers)(context, hoverParts, this._editor, this._languageService, this._openerService);
        }
    };
    exports.UnicodeHighlighterHoverParticipant = UnicodeHighlighterHoverParticipant;
    exports.UnicodeHighlighterHoverParticipant = UnicodeHighlighterHoverParticipant = __decorate([
        __param(1, language_1.ILanguageService),
        __param(2, opener_1.IOpenerService)
    ], UnicodeHighlighterHoverParticipant);
    function codePointToHex(codePoint) {
        return `U+${codePoint.toString(16).padStart(4, '0')}`;
    }
    function formatCodePointMarkdown(codePoint) {
        let value = `\`${codePointToHex(codePoint)}\``;
        if (!strings_1.InvisibleCharacters.isInvisibleCharacter(codePoint)) {
            // Don't render any control characters or any invisible characters, as they cannot be seen anyways.
            value += ` "${`${renderCodePointAsInlineCode(codePoint)}`}"`;
        }
        return value;
    }
    function renderCodePointAsInlineCode(codePoint) {
        if (codePoint === 96 /* CharCode.BackTick */) {
            return '`` ` ``';
        }
        return '`' + String.fromCodePoint(codePoint) + '`';
    }
    function computeReason(char, options) {
        return unicodeTextModelHighlighter_1.UnicodeTextModelHighlighter.computeUnicodeHighlightReason(char, options);
    }
    class Decorations {
        constructor() {
            this.map = new Map();
        }
        static { this.instance = new Decorations(); }
        getDecorationFromOptions(options) {
            return this.getDecoration(!options.includeComments, !options.includeStrings);
        }
        getDecoration(hideInComments, hideInStrings) {
            const key = `${hideInComments}${hideInStrings}`;
            let options = this.map.get(key);
            if (!options) {
                options = textModel_1.ModelDecorationOptions.createDynamic({
                    description: 'unicode-highlight',
                    stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */,
                    className: 'unicode-highlight',
                    showIfCollapsed: true,
                    overviewRuler: null,
                    minimap: null,
                    hideInCommentTokens: hideInComments,
                    hideInStringTokens: hideInStrings,
                });
                this.map.set(key, options);
            }
            return options;
        }
    }
    class DisableHighlightingInCommentsAction extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: DisableHighlightingOfAmbiguousCharactersAction.ID,
                label: nls.localize(1397, 'Disable highlighting of characters in comments'),
                alias: 'Disable highlighting of characters in comments',
                precondition: undefined
            });
            this.shortLabel = nls.localize(1396, 'Disable Highlight In Comments');
        }
        async run(accessor, editor, args) {
            const configurationService = accessor?.get(configuration_1.IConfigurationService);
            if (configurationService) {
                this.runAction(configurationService);
            }
        }
        async runAction(configurationService) {
            await configurationService.updateValue(editorOptions_1.unicodeHighlightConfigKeys.includeComments, false, 2 /* ConfigurationTarget.USER */);
        }
    }
    exports.DisableHighlightingInCommentsAction = DisableHighlightingInCommentsAction;
    class DisableHighlightingInStringsAction extends editorExtensions_1.EditorAction {
        constructor() {
            super({
                id: DisableHighlightingOfAmbiguousCharactersAction.ID,
                label: nls.localize(1399, 'Disable highlighting of characters in strings'),
                alias: 'Disable highlighting of characters in strings',
                precondition: undefined
            });
            this.shortLabel = nls.localize(1398, 'Disable Highlight In Strings');
        }
        async run(accessor, editor, args) {
            const configurationService = accessor?.get(configuration_1.IConfigurationService);
            if (configurationService) {
                this.runAction(configurationService);
            }
        }
        async runAction(configurationService) {
            await configurationService.updateValue(editorOptions_1.unicodeHighlightConfigKeys.includeStrings, false, 2 /* ConfigurationTarget.USER */);
        }
    }
    exports.DisableHighlightingInStringsAction = DisableHighlightingInStringsAction;
    class DisableHighlightingOfAmbiguousCharactersAction extends editorExtensions_1.EditorAction {
        static { this.ID = 'editor.action.unicodeHighlight.disableHighlightingOfAmbiguousCharacters'; }
        constructor() {
            super({
                id: DisableHighlightingOfAmbiguousCharactersAction.ID,
                label: nls.localize(1401, 'Disable highlighting of ambiguous characters'),
                alias: 'Disable highlighting of ambiguous characters',
                precondition: undefined
            });
            this.shortLabel = nls.localize(1400, 'Disable Ambiguous Highlight');
        }
        async run(accessor, editor, args) {
            const configurationService = accessor?.get(configuration_1.IConfigurationService);
            if (configurationService) {
                this.runAction(configurationService);
            }
        }
        async runAction(configurationService) {
            await configurationService.updateValue(editorOptions_1.unicodeHighlightConfigKeys.ambiguousCharacters, false, 2 /* ConfigurationTarget.USER */);
        }
    }
    exports.DisableHighlightingOfAmbiguousCharactersAction = DisableHighlightingOfAmbiguousCharactersAction;
    class DisableHighlightingOfInvisibleCharactersAction extends editorExtensions_1.EditorAction {
        static { this.ID = 'editor.action.unicodeHighlight.disableHighlightingOfInvisibleCharacters'; }
        constructor() {
            super({
                id: DisableHighlightingOfInvisibleCharactersAction.ID,
                label: nls.localize(1403, 'Disable highlighting of invisible characters'),
                alias: 'Disable highlighting of invisible characters',
                precondition: undefined
            });
            this.shortLabel = nls.localize(1402, 'Disable Invisible Highlight');
        }
        async run(accessor, editor, args) {
            const configurationService = accessor?.get(configuration_1.IConfigurationService);
            if (configurationService) {
                this.runAction(configurationService);
            }
        }
        async runAction(configurationService) {
            await configurationService.updateValue(editorOptions_1.unicodeHighlightConfigKeys.invisibleCharacters, false, 2 /* ConfigurationTarget.USER */);
        }
    }
    exports.DisableHighlightingOfInvisibleCharactersAction = DisableHighlightingOfInvisibleCharactersAction;
    class DisableHighlightingOfNonBasicAsciiCharactersAction extends editorExtensions_1.EditorAction {
        static { this.ID = 'editor.action.unicodeHighlight.disableHighlightingOfNonBasicAsciiCharacters'; }
        constructor() {
            super({
                id: DisableHighlightingOfNonBasicAsciiCharactersAction.ID,
                label: nls.localize(1405, 'Disable highlighting of non basic ASCII characters'),
                alias: 'Disable highlighting of non basic ASCII characters',
                precondition: undefined
            });
            this.shortLabel = nls.localize(1404, 'Disable Non ASCII Highlight');
        }
        async run(accessor, editor, args) {
            const configurationService = accessor?.get(configuration_1.IConfigurationService);
            if (configurationService) {
                this.runAction(configurationService);
            }
        }
        async runAction(configurationService) {
            await configurationService.updateValue(editorOptions_1.unicodeHighlightConfigKeys.nonBasicASCII, false, 2 /* ConfigurationTarget.USER */);
        }
    }
    exports.DisableHighlightingOfNonBasicAsciiCharactersAction = DisableHighlightingOfNonBasicAsciiCharactersAction;
    class ShowExcludeOptions extends editorExtensions_1.EditorAction {
        static { this.ID = 'editor.action.unicodeHighlight.showExcludeOptions'; }
        constructor() {
            super({
                id: ShowExcludeOptions.ID,
                label: nls.localize(1406, "Show Exclude Options"),
                alias: 'Show Exclude Options',
                precondition: undefined
            });
        }
        async run(accessor, editor, args) {
            const { codePoint, reason, inString, inComment } = args;
            const char = String.fromCodePoint(codePoint);
            const quickPickService = accessor.get(quickInput_1.IQuickInputService);
            const configurationService = accessor.get(configuration_1.IConfigurationService);
            function getExcludeCharFromBeingHighlightedLabel(codePoint) {
                if (strings_1.InvisibleCharacters.isInvisibleCharacter(codePoint)) {
                    return nls.localize(1407, 'Exclude {0} (invisible character) from being highlighted', codePointToHex(codePoint));
                }
                return nls.localize(1408, 'Exclude {0} from being highlighted', `${codePointToHex(codePoint)} "${char}"`);
            }
            const options = [];
            if (reason.kind === 0 /* UnicodeHighlighterReasonKind.Ambiguous */) {
                for (const locale of reason.notAmbiguousInLocales) {
                    options.push({
                        label: nls.localize(1409, "Allow unicode characters that are more common in the language \"{0}\".", locale),
                        run: async () => {
                            excludeLocaleFromBeingHighlighted(configurationService, [locale]);
                        },
                    });
                }
            }
            options.push({
                label: getExcludeCharFromBeingHighlightedLabel(codePoint),
                run: () => excludeCharFromBeingHighlighted(configurationService, [codePoint])
            });
            if (inComment) {
                const action = new DisableHighlightingInCommentsAction();
                options.push({ label: action.label, run: async () => action.runAction(configurationService) });
            }
            else if (inString) {
                const action = new DisableHighlightingInStringsAction();
                options.push({ label: action.label, run: async () => action.runAction(configurationService) });
            }
            if (reason.kind === 0 /* UnicodeHighlighterReasonKind.Ambiguous */) {
                const action = new DisableHighlightingOfAmbiguousCharactersAction();
                options.push({ label: action.label, run: async () => action.runAction(configurationService) });
            }
            else if (reason.kind === 1 /* UnicodeHighlighterReasonKind.Invisible */) {
                const action = new DisableHighlightingOfInvisibleCharactersAction();
                options.push({ label: action.label, run: async () => action.runAction(configurationService) });
            }
            else if (reason.kind === 2 /* UnicodeHighlighterReasonKind.NonBasicAscii */) {
                const action = new DisableHighlightingOfNonBasicAsciiCharactersAction();
                options.push({ label: action.label, run: async () => action.runAction(configurationService) });
            }
            else {
                expectNever(reason);
            }
            const result = await quickPickService.pick(options, { title: configureUnicodeHighlightOptionsStr });
            if (result) {
                await result.run();
            }
        }
    }
    exports.ShowExcludeOptions = ShowExcludeOptions;
    async function excludeCharFromBeingHighlighted(configurationService, charCodes) {
        const existingValue = configurationService.getValue(editorOptions_1.unicodeHighlightConfigKeys.allowedCharacters);
        let value;
        if ((typeof existingValue === 'object') && existingValue) {
            value = existingValue;
        }
        else {
            value = {};
        }
        for (const charCode of charCodes) {
            value[String.fromCodePoint(charCode)] = true;
        }
        await configurationService.updateValue(editorOptions_1.unicodeHighlightConfigKeys.allowedCharacters, value, 2 /* ConfigurationTarget.USER */);
    }
    async function excludeLocaleFromBeingHighlighted(configurationService, locales) {
        const existingValue = configurationService.inspect(editorOptions_1.unicodeHighlightConfigKeys.allowedLocales).user?.value;
        let value;
        if ((typeof existingValue === 'object') && existingValue) {
            // Copy value, as the existing value is read only
            value = Object.assign({}, existingValue);
        }
        else {
            value = {};
        }
        for (const locale of locales) {
            value[locale] = true;
        }
        await configurationService.updateValue(editorOptions_1.unicodeHighlightConfigKeys.allowedLocales, value, 2 /* ConfigurationTarget.USER */);
    }
    function expectNever(value) {
        throw new Error(`Unexpected value: ${value}`);
    }
    (0, editorExtensions_1.registerEditorAction)(DisableHighlightingOfAmbiguousCharactersAction);
    (0, editorExtensions_1.registerEditorAction)(DisableHighlightingOfInvisibleCharactersAction);
    (0, editorExtensions_1.registerEditorAction)(DisableHighlightingOfNonBasicAsciiCharactersAction);
    (0, editorExtensions_1.registerEditorAction)(ShowExcludeOptions);
    (0, editorExtensions_1.registerEditorContribution)(UnicodeHighlighter.ID, UnicodeHighlighter, 1 /* EditorContributionInstantiation.AfterFirstRender */);
    hoverTypes_1.HoverParticipantRegistry.register(UnicodeHighlighterHoverParticipant);
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[870/*vs/editor/editor.all*/], __M([1/*require*/,0/*exports*/,214/*vs/editor/browser/coreCommands*/,219/*vs/editor/browser/widget/codeEditor/codeEditorWidget*/,812/*vs/editor/browser/widget/diffEditor/diffEditor.contribution*/,727/*vs/editor/contrib/anchorSelect/browser/anchorSelect*/,815/*vs/editor/contrib/bracketMatching/browser/bracketMatching*/,728/*vs/editor/contrib/caretOperations/browser/caretOperations*/,729/*vs/editor/contrib/caretOperations/browser/transpose*/,856/*vs/editor/contrib/clipboard/browser/clipboard*/,817/*vs/editor/contrib/codeAction/browser/codeActionContributions*/,819/*vs/editor/contrib/codelens/browser/codelensController*/,848/*vs/editor/contrib/colorPicker/browser/colorContributions*/,821/*vs/editor/contrib/colorPicker/browser/standaloneColorPickerActions*/,730/*vs/editor/contrib/comment/browser/comment*/,434/*vs/editor/contrib/contextmenu/browser/contextmenu*/,731/*vs/editor/contrib/cursorUndo/browser/cursorUndo*/,822/*vs/editor/contrib/dnd/browser/dnd*/,857/*vs/editor/contrib/dropOrPasteInto/browser/copyPasteContribution*/,858/*vs/editor/contrib/dropOrPasteInto/browser/dropIntoEditorContribution*/,423/*vs/editor/contrib/find/browser/findController*/,289/*vs/editor/contrib/folding/browser/folding*/,734/*vs/editor/contrib/fontZoom/browser/fontZoom*/,735/*vs/editor/contrib/format/browser/formatActions*/,695/*vs/editor/contrib/documentSymbols/browser/documentSymbols*/,864/*vs/editor/contrib/inlineCompletions/browser/inlineCompletions.contribution*/,290/*vs/editor/contrib/inlineProgress/browser/inlineProgress*/,291/*vs/editor/contrib/gotoSymbol/browser/goToCommands*/,429/*vs/editor/contrib/gotoSymbol/browser/link/goToDefinitionAtPosition*/,427/*vs/editor/contrib/gotoError/browser/gotoError*/,850/*vs/editor/contrib/hover/browser/hoverContribution*/,737/*vs/editor/contrib/indentation/browser/indentation*/,851/*vs/editor/contrib/inlayHints/browser/inlayHintsContribution*/,827/*vs/editor/contrib/inPlaceReplace/browser/inPlaceReplace*/,738/*vs/editor/contrib/lineSelection/browser/lineSelection*/,739/*vs/editor/contrib/linesOperations/browser/linesOperations*/,833/*vs/editor/contrib/linkedEditing/browser/linkedEditing*/,834/*vs/editor/contrib/links/browser/links*/,740/*vs/editor/contrib/longLinesHelper/browser/longLinesHelper*/,840/*vs/editor/contrib/multicursor/browser/multicursor*/,831/*vs/editor/contrib/inlineEdit/browser/inlineEdit.contribution*/,867/*vs/editor/contrib/inlineEdits/browser/inlineEdits.contribution*/,765/*vs/editor/contrib/parameterHints/browser/parameterHints*/,786/*vs/editor/contrib/placeholderText/browser/placeholderText.contribution*/,790/*vs/editor/contrib/rename/browser/rename*/,835/*vs/editor/contrib/sectionHeaders/browser/sectionHeaders*/,791/*vs/editor/contrib/semanticTokens/browser/documentSemanticTokens*/,792/*vs/editor/contrib/semanticTokens/browser/viewportSemanticTokens*/,742/*vs/editor/contrib/smartSelect/browser/smartSelect*/,221/*vs/editor/contrib/snippet/browser/snippetController2*/,853/*vs/editor/contrib/stickyScroll/browser/stickyScrollContribution*/,294/*vs/editor/contrib/suggest/browser/suggestController*/,868/*vs/editor/contrib/suggest/browser/suggestInlineCompletions*/,743/*vs/editor/contrib/tokenization/browser/tokenization*/,718/*vs/editor/contrib/toggleTabFocusMode/browser/toggleTabFocusMode*/,869/*vs/editor/contrib/unicodeHighlighter/browser/unicodeHighlighter*/,744/*vs/editor/contrib/unusualLineTerminators/browser/unusualLineTerminators*/,841/*vs/editor/contrib/wordHighlighter/browser/wordHighlighter*/,411/*vs/editor/contrib/wordOperations/browser/wordOperations*/,745/*vs/editor/contrib/wordPartOperations/browser/wordPartOperations*/,741/*vs/editor/contrib/readOnlyMessage/browser/contribution*/,694/*vs/editor/contrib/diffEditorBreadcrumbs/browser/contribution*/,107/*vs/editor/common/standaloneStrings*/,195/*vs/base/browser/ui/codicons/codiconStyles*/]), function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[222/*vs/editor/standalone/browser/standaloneServices*/], __M([1/*require*/,0/*exports*/,11/*vs/base/common/strings*/,5/*vs/base/browser/dom*/,47/*vs/base/browser/keyboardEvent*/,6/*vs/base/common/event*/,140/*vs/base/common/keybindings*/,2/*vs/base/common/lifecycle*/,16/*vs/base/common/platform*/,111/*vs/base/common/severity*/,22/*vs/base/common/uri*/,152/*vs/editor/browser/services/bulkEditService*/,274/*vs/editor/common/config/editorConfigurationSchema*/,75/*vs/editor/common/core/editOperation*/,9/*vs/editor/common/core/position*/,4/*vs/editor/common/core/range*/,51/*vs/editor/common/services/model*/,78/*vs/editor/common/services/resolverService*/,211/*vs/editor/common/services/textResourceConfiguration*/,24/*vs/platform/commands/common/commands*/,28/*vs/platform/configuration/common/configuration*/,403/*vs/platform/configuration/common/configurationModels*/,12/*vs/platform/contextkey/common/contextkey*/,180/*vs/platform/dialogs/common/dialogs*/,7/*vs/platform/instantiation/common/instantiation*/,691/*vs/platform/keybinding/common/abstractKeybindingService*/,31/*vs/platform/keybinding/common/keybinding*/,392/*vs/platform/keybinding/common/keybindingResolver*/,121/*vs/platform/keybinding/common/keybindingsRegistry*/,393/*vs/platform/keybinding/common/resolvedKeybindingItem*/,692/*vs/platform/keybinding/common/usLayoutResolvedKeybinding*/,181/*vs/platform/label/common/label*/,50/*vs/platform/notification/common/notification*/,96/*vs/platform/progress/common/progress*/,63/*vs/platform/telemetry/common/telemetry*/,186/*vs/platform/workspace/common/workspace*/,119/*vs/platform/layout/browser/layoutService*/,107/*vs/editor/common/standaloneStrings*/,48/*vs/base/common/resources*/,34/*vs/editor/browser/services/codeEditorService*/,62/*vs/platform/log/common/log*/,440/*vs/platform/workspace/common/workspaceTrust*/,58/*vs/platform/contextview/browser/contextView*/,395/*vs/platform/contextview/browser/contextViewService*/,711/*vs/editor/common/services/languageService*/,801/*vs/platform/contextview/browser/contextMenuService*/,49/*vs/platform/instantiation/common/extensions*/,701/*vs/editor/browser/services/openerService*/,100/*vs/editor/common/services/editorWorker*/,401/*vs/editor/browser/services/editorWorkerService*/,43/*vs/editor/common/languages/language*/,784/*vs/editor/common/services/markerDecorationsService*/,266/*vs/editor/common/services/markerDecorations*/,808/*vs/editor/common/services/modelService*/,805/*vs/editor/standalone/browser/quickInput/standaloneQuickInputService*/,419/*vs/editor/standalone/browser/standaloneThemeService*/,153/*vs/editor/standalone/common/standaloneTheme*/,693/*vs/platform/accessibility/browser/accessibilityService*/,61/*vs/platform/accessibility/common/accessibility*/,29/*vs/platform/actions/common/actions*/,406/*vs/platform/actions/common/menuService*/,696/*vs/platform/clipboard/browser/clipboardService*/,117/*vs/platform/clipboard/common/clipboardService*/,687/*vs/platform/contextkey/browser/contextKeyService*/,265/*vs/platform/instantiation/common/descriptors*/,688/*vs/platform/instantiation/common/instantiationService*/,154/*vs/platform/instantiation/common/serviceCollection*/,216/*vs/platform/list/browser/listService*/,108/*vs/platform/markers/common/markers*/,699/*vs/platform/markers/common/markerService*/,59/*vs/platform/opener/common/opener*/,66/*vs/platform/quickinput/common/quickInput*/,101/*vs/platform/storage/common/storage*/,717/*vs/platform/configuration/common/configurations*/,137/*vs/platform/accessibilitySignal/browser/accessibilitySignalService*/,17/*vs/editor/common/services/languageFeatures*/,36/*vs/editor/common/languages/languageConfigurationRegistry*/,697/*vs/platform/log/common/logService*/,130/*vs/editor/common/editorFeatures*/,8/*vs/base/common/errors*/,271/*vs/platform/environment/common/environment*/,52/*vs/base/browser/window*/,45/*vs/base/common/map*/,384/*vs/editor/common/services/treeSitterParserService*/,624/*vs/editor/standalone/browser/standaloneTreeSitterService*/,418/*vs/editor/standalone/browser/standaloneCodeEditorService*/,394/*vs/editor/standalone/browser/standaloneLayoutService*/,855/*vs/platform/undoRedo/common/undoRedoService*/,79/*vs/editor/common/services/languageFeatureDebounce*/,785/*vs/editor/common/services/semanticTokensStylingService*/,677/*vs/editor/common/services/languageFeaturesService*/,772/*vs/editor/browser/services/hoverService/hoverService*/]), function (require, exports, strings, dom, keyboardEvent_1, event_1, keybindings_1, lifecycle_1, platform_1, severity_1, uri_1, bulkEditService_1, editorConfigurationSchema_1, editOperation_1, position_1, range_1, model_1, resolverService_1, textResourceConfiguration_1, commands_1, configuration_1, configurationModels_1, contextkey_1, dialogs_1, instantiation_1, abstractKeybindingService_1, keybinding_1, keybindingResolver_1, keybindingsRegistry_1, resolvedKeybindingItem_1, usLayoutResolvedKeybinding_1, label_1, notification_1, progress_1, telemetry_1, workspace_1, layoutService_1, standaloneStrings_1, resources_1, codeEditorService_1, log_1, workspaceTrust_1, contextView_1, contextViewService_1, languageService_1, contextMenuService_1, extensions_1, openerService_1, editorWorker_1, editorWorkerService_1, language_1, markerDecorationsService_1, markerDecorations_1, modelService_1, standaloneQuickInputService_1, standaloneThemeService_1, standaloneTheme_1, accessibilityService_1, accessibility_1, actions_1, menuService_1, clipboardService_1, clipboardService_2, contextKeyService_1, descriptors_1, instantiationService_1, serviceCollection_1, listService_1, markers_1, markerService_1, opener_1, quickInput_1, storage_1, configurations_1, accessibilitySignalService_1, languageFeatures_1, languageConfigurationRegistry_1, logService_1, editorFeatures_1, errors_1, environment_1, window_1, map_1, treeSitterParserService_1, standaloneTreeSitterService_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.StandaloneServices = exports.standaloneEditorWorkerDescriptor = exports.StandaloneConfigurationService = exports.StandaloneKeybindingService = exports.StandaloneCommandService = exports.StandaloneNotificationService = void 0;
    exports.updateConfigurationService = updateConfigurationService;
    class SimpleModel {
        constructor(model) {
            this.disposed = false;
            this.model = model;
            this._onWillDispose = new event_1.Emitter();
        }
        get textEditorModel() {
            return this.model;
        }
        dispose() {
            this.disposed = true;
            this._onWillDispose.fire();
        }
    }
    let StandaloneTextModelService = class StandaloneTextModelService {
        constructor(modelService) {
            this.modelService = modelService;
        }
        createModelReference(resource) {
            const model = this.modelService.getModel(resource);
            if (!model) {
                return Promise.reject(new Error(`Model not found`));
            }
            return Promise.resolve(new lifecycle_1.ImmortalReference(new SimpleModel(model)));
        }
    };
    StandaloneTextModelService = __decorate([
        __param(0, model_1.IModelService)
    ], StandaloneTextModelService);
    class StandaloneEditorProgressService {
        static { this.NULL_PROGRESS_RUNNER = {
            done: () => { },
            total: () => { },
            worked: () => { }
        }; }
        show() {
            return StandaloneEditorProgressService.NULL_PROGRESS_RUNNER;
        }
        async showWhile(promise, delay) {
            await promise;
        }
    }
    class StandaloneProgressService {
        withProgress(_options, task, onDidCancel) {
            return task({
                report: () => { },
            });
        }
    }
    class StandaloneEnvironmentService {
        constructor() {
            this.isExtensionDevelopment = false;
            this.isBuilt = false;
        }
    }
    class StandaloneDialogService {
        async confirm(confirmation) {
            const confirmed = this.doConfirm(confirmation.message, confirmation.detail);
            return {
                confirmed,
                checkboxChecked: false // unsupported
            };
        }
        doConfirm(message, detail) {
            let messageText = message;
            if (detail) {
                messageText = messageText + '\n\n' + detail;
            }
            return window_1.mainWindow.confirm(messageText);
        }
        async prompt(prompt) {
            let result = undefined;
            const confirmed = this.doConfirm(prompt.message, prompt.detail);
            if (confirmed) {
                const promptButtons = [...(prompt.buttons ?? [])];
                if (prompt.cancelButton && typeof prompt.cancelButton !== 'string' && typeof prompt.cancelButton !== 'boolean') {
                    promptButtons.push(prompt.cancelButton);
                }
                result = await promptButtons[0]?.run({ checkboxChecked: false });
            }
            return { result };
        }
        async error(message, detail) {
            await this.prompt({ type: severity_1.default.Error, message, detail });
        }
    }
    class StandaloneNotificationService {
        static { this.NO_OP = new notification_1.NoOpNotification(); }
        info(message) {
            return this.notify({ severity: severity_1.default.Info, message });
        }
        warn(message) {
            return this.notify({ severity: severity_1.default.Warning, message });
        }
        error(error) {
            return this.notify({ severity: severity_1.default.Error, message: error });
        }
        notify(notification) {
            switch (notification.severity) {
                case severity_1.default.Error:
                    console.error(notification.message);
                    break;
                case severity_1.default.Warning:
                    console.warn(notification.message);
                    break;
                default:
                    console.log(notification.message);
                    break;
            }
            return StandaloneNotificationService.NO_OP;
        }
        prompt(severity, message, choices, options) {
            return StandaloneNotificationService.NO_OP;
        }
        status(message, options) {
            return lifecycle_1.Disposable.None;
        }
    }
    exports.StandaloneNotificationService = StandaloneNotificationService;
    let StandaloneCommandService = class StandaloneCommandService {
        constructor(instantiationService) {
            this._onWillExecuteCommand = new event_1.Emitter();
            this._onDidExecuteCommand = new event_1.Emitter();
            this.onDidExecuteCommand = this._onDidExecuteCommand.event;
            this._instantiationService = instantiationService;
        }
        executeCommand(id, ...args) {
            const command = commands_1.CommandsRegistry.getCommand(id);
            if (!command) {
                return Promise.reject(new Error(`command '${id}' not found`));
            }
            try {
                this._onWillExecuteCommand.fire({ commandId: id, args });
                const result = this._instantiationService.invokeFunction.apply(this._instantiationService, [command.handler, ...args]);
                this._onDidExecuteCommand.fire({ commandId: id, args });
                return Promise.resolve(result);
            }
            catch (err) {
                return Promise.reject(err);
            }
        }
    };
    exports.StandaloneCommandService = StandaloneCommandService;
    exports.StandaloneCommandService = StandaloneCommandService = __decorate([
        __param(0, instantiation_1.IInstantiationService)
    ], StandaloneCommandService);
    let StandaloneKeybindingService = class StandaloneKeybindingService extends abstractKeybindingService_1.AbstractKeybindingService {
        constructor(contextKeyService, commandService, telemetryService, notificationService, logService, codeEditorService) {
            super(contextKeyService, commandService, telemetryService, notificationService, logService);
            this._cachedResolver = null;
            this._dynamicKeybindings = [];
            this._domNodeListeners = [];
            const addContainer = (domNode) => {
                const disposables = new lifecycle_1.DisposableStore();
                // for standard keybindings
                disposables.add(dom.addDisposableListener(domNode, dom.EventType.KEY_DOWN, (e) => {
                    const keyEvent = new keyboardEvent_1.StandardKeyboardEvent(e);
                    const shouldPreventDefault = this._dispatch(keyEvent, keyEvent.target);
                    if (shouldPreventDefault) {
                        keyEvent.preventDefault();
                        keyEvent.stopPropagation();
                    }
                }));
                // for single modifier chord keybindings (e.g. shift shift)
                disposables.add(dom.addDisposableListener(domNode, dom.EventType.KEY_UP, (e) => {
                    const keyEvent = new keyboardEvent_1.StandardKeyboardEvent(e);
                    const shouldPreventDefault = this._singleModifierDispatch(keyEvent, keyEvent.target);
                    if (shouldPreventDefault) {
                        keyEvent.preventDefault();
                    }
                }));
                this._domNodeListeners.push(new DomNodeListeners(domNode, disposables));
            };
            const removeContainer = (domNode) => {
                for (let i = 0; i < this._domNodeListeners.length; i++) {
                    const domNodeListeners = this._domNodeListeners[i];
                    if (domNodeListeners.domNode === domNode) {
                        this._domNodeListeners.splice(i, 1);
                        domNodeListeners.dispose();
                    }
                }
            };
            const addCodeEditor = (codeEditor) => {
                if (codeEditor.getOption(61 /* EditorOption.inDiffEditor */)) {
                    return;
                }
                addContainer(codeEditor.getContainerDomNode());
            };
            const removeCodeEditor = (codeEditor) => {
                if (codeEditor.getOption(61 /* EditorOption.inDiffEditor */)) {
                    return;
                }
                removeContainer(codeEditor.getContainerDomNode());
            };
            this._register(codeEditorService.onCodeEditorAdd(addCodeEditor));
            this._register(codeEditorService.onCodeEditorRemove(removeCodeEditor));
            codeEditorService.listCodeEditors().forEach(addCodeEditor);
            const addDiffEditor = (diffEditor) => {
                addContainer(diffEditor.getContainerDomNode());
            };
            const removeDiffEditor = (diffEditor) => {
                removeContainer(diffEditor.getContainerDomNode());
            };
            this._register(codeEditorService.onDiffEditorAdd(addDiffEditor));
            this._register(codeEditorService.onDiffEditorRemove(removeDiffEditor));
            codeEditorService.listDiffEditors().forEach(addDiffEditor);
        }
        addDynamicKeybinding(command, keybinding, handler, when) {
            return (0, lifecycle_1.combinedDisposable)(commands_1.CommandsRegistry.registerCommand(command, handler), this.addDynamicKeybindings([{
                    keybinding,
                    command,
                    when
                }]));
        }
        addDynamicKeybindings(rules) {
            const entries = rules.map((rule) => {
                const keybinding = (0, keybindings_1.decodeKeybinding)(rule.keybinding, platform_1.OS);
                return {
                    keybinding,
                    command: rule.command ?? null,
                    commandArgs: rule.commandArgs,
                    when: rule.when,
                    weight1: 1000,
                    weight2: 0,
                    extensionId: null,
                    isBuiltinExtension: false
                };
            });
            this._dynamicKeybindings = this._dynamicKeybindings.concat(entries);
            this.updateResolver();
            return (0, lifecycle_1.toDisposable)(() => {
                // Search the first entry and remove them all since they will be contiguous
                for (let i = 0; i < this._dynamicKeybindings.length; i++) {
                    if (this._dynamicKeybindings[i] === entries[0]) {
                        this._dynamicKeybindings.splice(i, entries.length);
                        this.updateResolver();
                        return;
                    }
                }
            });
        }
        updateResolver() {
            this._cachedResolver = null;
            this._onDidUpdateKeybindings.fire();
        }
        _getResolver() {
            if (!this._cachedResolver) {
                const defaults = this._toNormalizedKeybindingItems(keybindingsRegistry_1.KeybindingsRegistry.getDefaultKeybindings(), true);
                const overrides = this._toNormalizedKeybindingItems(this._dynamicKeybindings, false);
                this._cachedResolver = new keybindingResolver_1.KeybindingResolver(defaults, overrides, (str) => this._log(str));
            }
            return this._cachedResolver;
        }
        _documentHasFocus() {
            return window_1.mainWindow.document.hasFocus();
        }
        _toNormalizedKeybindingItems(items, isDefault) {
            const result = [];
            let resultLen = 0;
            for (const item of items) {
                const when = item.when || undefined;
                const keybinding = item.keybinding;
                if (!keybinding) {
                    // This might be a removal keybinding item in user settings => accept it
                    result[resultLen++] = new resolvedKeybindingItem_1.ResolvedKeybindingItem(undefined, item.command, item.commandArgs, when, isDefault, null, false);
                }
                else {
                    const resolvedKeybindings = usLayoutResolvedKeybinding_1.USLayoutResolvedKeybinding.resolveKeybinding(keybinding, platform_1.OS);
                    for (const resolvedKeybinding of resolvedKeybindings) {
                        result[resultLen++] = new resolvedKeybindingItem_1.ResolvedKeybindingItem(resolvedKeybinding, item.command, item.commandArgs, when, isDefault, null, false);
                    }
                }
            }
            return result;
        }
        resolveKeyboardEvent(keyboardEvent) {
            const chord = new keybindings_1.KeyCodeChord(keyboardEvent.ctrlKey, keyboardEvent.shiftKey, keyboardEvent.altKey, keyboardEvent.metaKey, keyboardEvent.keyCode);
            return new usLayoutResolvedKeybinding_1.USLayoutResolvedKeybinding([chord], platform_1.OS);
        }
    };
    exports.StandaloneKeybindingService = StandaloneKeybindingService;
    exports.StandaloneKeybindingService = StandaloneKeybindingService = __decorate([
        __param(0, contextkey_1.IContextKeyService),
        __param(1, commands_1.ICommandService),
        __param(2, telemetry_1.ITelemetryService),
        __param(3, notification_1.INotificationService),
        __param(4, log_1.ILogService),
        __param(5, codeEditorService_1.ICodeEditorService)
    ], StandaloneKeybindingService);
    class DomNodeListeners extends lifecycle_1.Disposable {
        constructor(domNode, disposables) {
            super();
            this.domNode = domNode;
            this._register(disposables);
        }
    }
    function isConfigurationOverrides(thing) {
        return thing
            && typeof thing === 'object'
            && (!thing.overrideIdentifier || typeof thing.overrideIdentifier === 'string')
            && (!thing.resource || thing.resource instanceof uri_1.URI);
    }
    let StandaloneConfigurationService = class StandaloneConfigurationService {
        constructor(logService) {
            this.logService = logService;
            this._onDidChangeConfiguration = new event_1.Emitter();
            this.onDidChangeConfiguration = this._onDidChangeConfiguration.event;
            const defaultConfiguration = new configurations_1.DefaultConfiguration(logService);
            this._configuration = new configurationModels_1.Configuration(defaultConfiguration.reload(), configurationModels_1.ConfigurationModel.createEmptyModel(logService), configurationModels_1.ConfigurationModel.createEmptyModel(logService), configurationModels_1.ConfigurationModel.createEmptyModel(logService), configurationModels_1.ConfigurationModel.createEmptyModel(logService), configurationModels_1.ConfigurationModel.createEmptyModel(logService), new map_1.ResourceMap(), configurationModels_1.ConfigurationModel.createEmptyModel(logService), new map_1.ResourceMap(), logService);
            defaultConfiguration.dispose();
        }
        getValue(arg1, arg2) {
            const section = typeof arg1 === 'string' ? arg1 : undefined;
            const overrides = isConfigurationOverrides(arg1) ? arg1 : isConfigurationOverrides(arg2) ? arg2 : {};
            return this._configuration.getValue(section, overrides, undefined);
        }
        updateValues(values) {
            const previous = { data: this._configuration.toData() };
            const changedKeys = [];
            for (const entry of values) {
                const [key, value] = entry;
                if (this.getValue(key) === value) {
                    continue;
                }
                this._configuration.updateValue(key, value);
                changedKeys.push(key);
            }
            if (changedKeys.length > 0) {
                const configurationChangeEvent = new configurationModels_1.ConfigurationChangeEvent({ keys: changedKeys, overrides: [] }, previous, this._configuration, undefined, this.logService);
                configurationChangeEvent.source = 8 /* ConfigurationTarget.MEMORY */;
                this._onDidChangeConfiguration.fire(configurationChangeEvent);
            }
            return Promise.resolve();
        }
        updateValue(key, value, arg3, arg4) {
            return this.updateValues([[key, value]]);
        }
        inspect(key, options = {}) {
            return this._configuration.inspect(key, options, undefined);
        }
    };
    exports.StandaloneConfigurationService = StandaloneConfigurationService;
    exports.StandaloneConfigurationService = StandaloneConfigurationService = __decorate([
        __param(0, log_1.ILogService)
    ], StandaloneConfigurationService);
    let StandaloneResourceConfigurationService = class StandaloneResourceConfigurationService {
        constructor(configurationService, modelService, languageService) {
            this.configurationService = configurationService;
            this.modelService = modelService;
            this.languageService = languageService;
            this._onDidChangeConfiguration = new event_1.Emitter();
            this.configurationService.onDidChangeConfiguration((e) => {
                this._onDidChangeConfiguration.fire({ affectedKeys: e.affectedKeys, affectsConfiguration: (resource, configuration) => e.affectsConfiguration(configuration) });
            });
        }
        getValue(resource, arg2, arg3) {
            const position = position_1.Position.isIPosition(arg2) ? arg2 : null;
            const section = position ? (typeof arg3 === 'string' ? arg3 : undefined) : (typeof arg2 === 'string' ? arg2 : undefined);
            const language = resource ? this.getLanguage(resource, position) : undefined;
            if (typeof section === 'undefined') {
                return this.configurationService.getValue({
                    resource,
                    overrideIdentifier: language
                });
            }
            return this.configurationService.getValue(section, {
                resource,
                overrideIdentifier: language
            });
        }
        getLanguage(resource, position) {
            const model = this.modelService.getModel(resource);
            if (model) {
                return position ? model.getLanguageIdAtPosition(position.lineNumber, position.column) : model.getLanguageId();
            }
            return this.languageService.guessLanguageIdByFilepathOrFirstLine(resource);
        }
    };
    StandaloneResourceConfigurationService = __decorate([
        __param(0, configuration_1.IConfigurationService),
        __param(1, model_1.IModelService),
        __param(2, language_1.ILanguageService)
    ], StandaloneResourceConfigurationService);
    let StandaloneResourcePropertiesService = class StandaloneResourcePropertiesService {
        constructor(configurationService) {
            this.configurationService = configurationService;
        }
        getEOL(resource, language) {
            const eol = this.configurationService.getValue('files.eol', { overrideIdentifier: language, resource });
            if (eol && typeof eol === 'string' && eol !== 'auto') {
                return eol;
            }
            return (platform_1.isLinux || platform_1.isMacintosh) ? '\n' : '\r\n';
        }
    };
    StandaloneResourcePropertiesService = __decorate([
        __param(0, configuration_1.IConfigurationService)
    ], StandaloneResourcePropertiesService);
    class StandaloneTelemetryService {
        publicLog2() { }
    }
    class StandaloneWorkspaceContextService {
        static { this.SCHEME = 'inmemory'; }
        constructor() {
            const resource = uri_1.URI.from({ scheme: StandaloneWorkspaceContextService.SCHEME, authority: 'model', path: '/' });
            this.workspace = { id: workspace_1.STANDALONE_EDITOR_WORKSPACE_ID, folders: [new workspace_1.WorkspaceFolder({ uri: resource, name: '', index: 0 })] };
        }
        getWorkspace() {
            return this.workspace;
        }
        getWorkspaceFolder(resource) {
            return resource && resource.scheme === StandaloneWorkspaceContextService.SCHEME ? this.workspace.folders[0] : null;
        }
    }
    function updateConfigurationService(configurationService, source, isDiffEditor) {
        if (!source) {
            return;
        }
        if (!(configurationService instanceof StandaloneConfigurationService)) {
            return;
        }
        const toUpdate = [];
        Object.keys(source).forEach((key) => {
            if ((0, editorConfigurationSchema_1.isEditorConfigurationKey)(key)) {
                toUpdate.push([`editor.${key}`, source[key]]);
            }
            if (isDiffEditor && (0, editorConfigurationSchema_1.isDiffEditorConfigurationKey)(key)) {
                toUpdate.push([`diffEditor.${key}`, source[key]]);
            }
        });
        if (toUpdate.length > 0) {
            configurationService.updateValues(toUpdate);
        }
    }
    let StandaloneBulkEditService = class StandaloneBulkEditService {
        constructor(_modelService) {
            this._modelService = _modelService;
            //
        }
        hasPreviewHandler() {
            return false;
        }
        async apply(editsIn, _options) {
            const edits = Array.isArray(editsIn) ? editsIn : bulkEditService_1.ResourceEdit.convert(editsIn);
            const textEdits = new Map();
            for (const edit of edits) {
                if (!(edit instanceof bulkEditService_1.ResourceTextEdit)) {
                    throw new Error('bad edit - only text edits are supported');
                }
                const model = this._modelService.getModel(edit.resource);
                if (!model) {
                    throw new Error('bad edit - model not found');
                }
                if (typeof edit.versionId === 'number' && model.getVersionId() !== edit.versionId) {
                    throw new Error('bad state - model changed in the meantime');
                }
                let array = textEdits.get(model);
                if (!array) {
                    array = [];
                    textEdits.set(model, array);
                }
                array.push(editOperation_1.EditOperation.replaceMove(range_1.Range.lift(edit.textEdit.range), edit.textEdit.text));
            }
            let totalEdits = 0;
            let totalFiles = 0;
            for (const [model, edits] of textEdits) {
                model.pushStackElement();
                model.pushEditOperations([], edits, () => []);
                model.pushStackElement();
                totalFiles += 1;
                totalEdits += edits.length;
            }
            return {
                ariaSummary: strings.format(standaloneStrings_1.StandaloneServicesNLS.bulkEditServiceSummary, totalEdits, totalFiles),
                isApplied: totalEdits > 0
            };
        }
    };
    StandaloneBulkEditService = __decorate([
        __param(0, model_1.IModelService)
    ], StandaloneBulkEditService);
    class StandaloneUriLabelService {
        getUriLabel(resource, options) {
            if (resource.scheme === 'file') {
                return resource.fsPath;
            }
            return resource.path;
        }
        getUriBasenameLabel(resource) {
            return (0, resources_1.basename)(resource);
        }
    }
    let StandaloneContextViewService = class StandaloneContextViewService extends contextViewService_1.ContextViewService {
        constructor(layoutService, _codeEditorService) {
            super(layoutService);
            this._codeEditorService = _codeEditorService;
        }
        showContextView(delegate, container, shadowRoot) {
            if (!container) {
                const codeEditor = this._codeEditorService.getFocusedCodeEditor() || this._codeEditorService.getActiveCodeEditor();
                if (codeEditor) {
                    container = codeEditor.getContainerDomNode();
                }
            }
            return super.showContextView(delegate, container, shadowRoot);
        }
    };
    StandaloneContextViewService = __decorate([
        __param(0, layoutService_1.ILayoutService),
        __param(1, codeEditorService_1.ICodeEditorService)
    ], StandaloneContextViewService);
    class StandaloneWorkspaceTrustManagementService {
        constructor() {
            this._neverEmitter = new event_1.Emitter();
            this.onDidChangeTrust = this._neverEmitter.event;
        }
        isWorkspaceTrusted() {
            return true;
        }
    }
    class StandaloneLanguageService extends languageService_1.LanguageService {
        constructor() {
            super();
        }
    }
    class StandaloneLogService extends logService_1.LogService {
        constructor() {
            super(new log_1.ConsoleLogger());
        }
    }
    let StandaloneContextMenuService = class StandaloneContextMenuService extends contextMenuService_1.ContextMenuService {
        constructor(telemetryService, notificationService, contextViewService, keybindingService, menuService, contextKeyService) {
            super(telemetryService, notificationService, contextViewService, keybindingService, menuService, contextKeyService);
            this.configure({ blockMouse: false }); // we do not want that in the standalone editor
        }
    };
    StandaloneContextMenuService = __decorate([
        __param(0, telemetry_1.ITelemetryService),
        __param(1, notification_1.INotificationService),
        __param(2, contextView_1.IContextViewService),
        __param(3, keybinding_1.IKeybindingService),
        __param(4, actions_1.IMenuService),
        __param(5, contextkey_1.IContextKeyService)
    ], StandaloneContextMenuService);
    exports.standaloneEditorWorkerDescriptor = {
        amdModuleId: 'vs/editor/common/services/editorSimpleWorker',
        esmModuleLocation: undefined,
        label: 'editorWorkerService'
    };
    let StandaloneEditorWorkerService = class StandaloneEditorWorkerService extends editorWorkerService_1.EditorWorkerService {
        constructor(modelService, configurationService, logService, languageConfigurationService, languageFeaturesService) {
            super(exports.standaloneEditorWorkerDescriptor, modelService, configurationService, logService, languageConfigurationService, languageFeaturesService);
        }
    };
    StandaloneEditorWorkerService = __decorate([
        __param(0, model_1.IModelService),
        __param(1, textResourceConfiguration_1.ITextResourceConfigurationService),
        __param(2, log_1.ILogService),
        __param(3, languageConfigurationRegistry_1.ILanguageConfigurationService),
        __param(4, languageFeatures_1.ILanguageFeaturesService)
    ], StandaloneEditorWorkerService);
    class StandaloneAccessbilitySignalService {
        async playSignal(cue, options) {
        }
    }
    (0, extensions_1.registerSingleton)(log_1.ILogService, StandaloneLogService, 0 /* InstantiationType.Eager */);
    (0, extensions_1.registerSingleton)(configuration_1.IConfigurationService, StandaloneConfigurationService, 0 /* InstantiationType.Eager */);
    (0, extensions_1.registerSingleton)(textResourceConfiguration_1.ITextResourceConfigurationService, StandaloneResourceConfigurationService, 0 /* InstantiationType.Eager */);
    (0, extensions_1.registerSingleton)(textResourceConfiguration_1.ITextResourcePropertiesService, StandaloneResourcePropertiesService, 0 /* InstantiationType.Eager */);
    (0, extensions_1.registerSingleton)(workspace_1.IWorkspaceContextService, StandaloneWorkspaceContextService, 0 /* InstantiationType.Eager */);
    (0, extensions_1.registerSingleton)(label_1.ILabelService, StandaloneUriLabelService, 0 /* InstantiationType.Eager */);
    (0, extensions_1.registerSingleton)(telemetry_1.ITelemetryService, StandaloneTelemetryService, 0 /* InstantiationType.Eager */);
    (0, extensions_1.registerSingleton)(dialogs_1.IDialogService, StandaloneDialogService, 0 /* InstantiationType.Eager */);
    (0, extensions_1.registerSingleton)(environment_1.IEnvironmentService, StandaloneEnvironmentService, 0 /* InstantiationType.Eager */);
    (0, extensions_1.registerSingleton)(notification_1.INotificationService, StandaloneNotificationService, 0 /* InstantiationType.Eager */);
    (0, extensions_1.registerSingleton)(markers_1.IMarkerService, markerService_1.MarkerService, 0 /* InstantiationType.Eager */);
    (0, extensions_1.registerSingleton)(language_1.ILanguageService, StandaloneLanguageService, 0 /* InstantiationType.Eager */);
    (0, extensions_1.registerSingleton)(standaloneTheme_1.IStandaloneThemeService, standaloneThemeService_1.StandaloneThemeService, 0 /* InstantiationType.Eager */);
    (0, extensions_1.registerSingleton)(model_1.IModelService, modelService_1.ModelService, 0 /* InstantiationType.Eager */);
    (0, extensions_1.registerSingleton)(markerDecorations_1.IMarkerDecorationsService, markerDecorationsService_1.MarkerDecorationsService, 0 /* InstantiationType.Eager */);
    (0, extensions_1.registerSingleton)(contextkey_1.IContextKeyService, contextKeyService_1.ContextKeyService, 0 /* InstantiationType.Eager */);
    (0, extensions_1.registerSingleton)(progress_1.IProgressService, StandaloneProgressService, 0 /* InstantiationType.Eager */);
    (0, extensions_1.registerSingleton)(progress_1.IEditorProgressService, StandaloneEditorProgressService, 0 /* InstantiationType.Eager */);
    (0, extensions_1.registerSingleton)(storage_1.IStorageService, storage_1.InMemoryStorageService, 0 /* InstantiationType.Eager */);
    (0, extensions_1.registerSingleton)(editorWorker_1.IEditorWorkerService, StandaloneEditorWorkerService, 0 /* InstantiationType.Eager */);
    (0, extensions_1.registerSingleton)(bulkEditService_1.IBulkEditService, StandaloneBulkEditService, 0 /* InstantiationType.Eager */);
    (0, extensions_1.registerSingleton)(workspaceTrust_1.IWorkspaceTrustManagementService, StandaloneWorkspaceTrustManagementService, 0 /* InstantiationType.Eager */);
    (0, extensions_1.registerSingleton)(resolverService_1.ITextModelService, StandaloneTextModelService, 0 /* InstantiationType.Eager */);
    (0, extensions_1.registerSingleton)(accessibility_1.IAccessibilityService, accessibilityService_1.AccessibilityService, 0 /* InstantiationType.Eager */);
    (0, extensions_1.registerSingleton)(listService_1.IListService, listService_1.ListService, 0 /* InstantiationType.Eager */);
    (0, extensions_1.registerSingleton)(commands_1.ICommandService, StandaloneCommandService, 0 /* InstantiationType.Eager */);
    (0, extensions_1.registerSingleton)(keybinding_1.IKeybindingService, StandaloneKeybindingService, 0 /* InstantiationType.Eager */);
    (0, extensions_1.registerSingleton)(quickInput_1.IQuickInputService, standaloneQuickInputService_1.StandaloneQuickInputService, 0 /* InstantiationType.Eager */);
    (0, extensions_1.registerSingleton)(contextView_1.IContextViewService, StandaloneContextViewService, 0 /* InstantiationType.Eager */);
    (0, extensions_1.registerSingleton)(opener_1.IOpenerService, openerService_1.OpenerService, 0 /* InstantiationType.Eager */);
    (0, extensions_1.registerSingleton)(clipboardService_2.IClipboardService, clipboardService_1.BrowserClipboardService, 0 /* InstantiationType.Eager */);
    (0, extensions_1.registerSingleton)(contextView_1.IContextMenuService, StandaloneContextMenuService, 0 /* InstantiationType.Eager */);
    (0, extensions_1.registerSingleton)(actions_1.IMenuService, menuService_1.MenuService, 0 /* InstantiationType.Eager */);
    (0, extensions_1.registerSingleton)(accessibilitySignalService_1.IAccessibilitySignalService, StandaloneAccessbilitySignalService, 0 /* InstantiationType.Eager */);
    (0, extensions_1.registerSingleton)(treeSitterParserService_1.ITreeSitterParserService, standaloneTreeSitterService_1.StandaloneTreeSitterParserService, 0 /* InstantiationType.Eager */);
    /**
     * We don't want to eagerly instantiate services because embedders get a one time chance
     * to override services when they create the first editor.
     */
    var StandaloneServices;
    (function (StandaloneServices) {
        const serviceCollection = new serviceCollection_1.ServiceCollection();
        for (const [id, descriptor] of (0, extensions_1.getSingletonServiceDescriptors)()) {
            serviceCollection.set(id, descriptor);
        }
        const instantiationService = new instantiationService_1.InstantiationService(serviceCollection, true);
        serviceCollection.set(instantiation_1.IInstantiationService, instantiationService);
        function get(serviceId) {
            if (!initialized) {
                initialize({});
            }
            const r = serviceCollection.get(serviceId);
            if (!r) {
                throw new Error('Missing service ' + serviceId);
            }
            if (r instanceof descriptors_1.SyncDescriptor) {
                return instantiationService.invokeFunction((accessor) => accessor.get(serviceId));
            }
            else {
                return r;
            }
        }
        StandaloneServices.get = get;
        let initialized = false;
        const onDidInitialize = new event_1.Emitter();
        function initialize(overrides) {
            if (initialized) {
                return instantiationService;
            }
            initialized = true;
            // Add singletons that were registered after this module loaded
            for (const [id, descriptor] of (0, extensions_1.getSingletonServiceDescriptors)()) {
                if (!serviceCollection.get(id)) {
                    serviceCollection.set(id, descriptor);
                }
            }
            // Initialize the service collection with the overrides, but only if the
            // service was not instantiated in the meantime.
            for (const serviceId in overrides) {
                if (overrides.hasOwnProperty(serviceId)) {
                    const serviceIdentifier = (0, instantiation_1.createDecorator)(serviceId);
                    const r = serviceCollection.get(serviceIdentifier);
                    if (r instanceof descriptors_1.SyncDescriptor) {
                        serviceCollection.set(serviceIdentifier, overrides[serviceId]);
                    }
                }
            }
            // Instantiate all editor features
            const editorFeatures = (0, editorFeatures_1.getEditorFeatures)();
            for (const feature of editorFeatures) {
                try {
                    instantiationService.createInstance(feature);
                }
                catch (err) {
                    (0, errors_1.onUnexpectedError)(err);
                }
            }
            onDidInitialize.fire();
            return instantiationService;
        }
        StandaloneServices.initialize = initialize;
        /**
         * Executes callback once services are initialized.
         */
        function withServices(callback) {
            if (initialized) {
                return callback();
            }
            const disposable = new lifecycle_1.DisposableStore();
            const listener = disposable.add(onDidInitialize.event(() => {
                listener.dispose();
                disposable.add(callback());
            }));
            return disposable;
        }
        StandaloneServices.withServices = withServices;
    })(StandaloneServices || (exports.StandaloneServices = StandaloneServices = {}));
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









define(__m[871/*vs/editor/standalone/browser/standaloneCodeEditor*/], __M([1/*require*/,0/*exports*/,46/*vs/base/browser/ui/aria/aria*/,2/*vs/base/common/lifecycle*/,34/*vs/editor/browser/services/codeEditorService*/,219/*vs/editor/browser/widget/codeEditor/codeEditorWidget*/,318/*vs/editor/common/editorAction*/,222/*vs/editor/standalone/browser/standaloneServices*/,153/*vs/editor/standalone/common/standaloneTheme*/,29/*vs/platform/actions/common/actions*/,24/*vs/platform/commands/common/commands*/,28/*vs/platform/configuration/common/configuration*/,12/*vs/platform/contextkey/common/contextkey*/,58/*vs/platform/contextview/browser/contextView*/,7/*vs/platform/instantiation/common/instantiation*/,31/*vs/platform/keybinding/common/keybinding*/,50/*vs/platform/notification/common/notification*/,25/*vs/platform/theme/common/themeService*/,61/*vs/platform/accessibility/common/accessibility*/,107/*vs/editor/common/standaloneStrings*/,117/*vs/platform/clipboard/common/clipboardService*/,96/*vs/platform/progress/common/progress*/,51/*vs/editor/common/services/model*/,43/*vs/editor/common/languages/language*/,418/*vs/editor/standalone/browser/standaloneCodeEditorService*/,70/*vs/editor/common/languages/modesRegistry*/,36/*vs/editor/common/languages/languageConfigurationRegistry*/,17/*vs/editor/common/services/languageFeatures*/,286/*vs/editor/browser/widget/diffEditor/diffEditorWidget*/,137/*vs/platform/accessibilitySignal/browser/accessibilitySignalService*/,52/*vs/base/browser/window*/,44/*vs/base/browser/ui/hover/hoverDelegateFactory*/,118/*vs/platform/hover/browser/hover*/,81/*vs/base/browser/ui/hover/hoverDelegate2*/]), function (require, exports, aria, lifecycle_1, codeEditorService_1, codeEditorWidget_1, editorAction_1, standaloneServices_1, standaloneTheme_1, actions_1, commands_1, configuration_1, contextkey_1, contextView_1, instantiation_1, keybinding_1, notification_1, themeService_1, accessibility_1, standaloneStrings_1, clipboardService_1, progress_1, model_1, language_1, standaloneCodeEditorService_1, modesRegistry_1, languageConfigurationRegistry_1, languageFeatures_1, diffEditorWidget_1, accessibilitySignalService_1, window_1, hoverDelegateFactory_1, hover_1, hoverDelegate2_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.StandaloneDiffEditor2 = exports.StandaloneEditor = exports.StandaloneCodeEditor = void 0;
    exports.createTextModel = createTextModel;
    let LAST_GENERATED_COMMAND_ID = 0;
    let ariaDomNodeCreated = false;
    /**
     * Create ARIA dom node inside parent,
     * or only for the first editor instantiation inside document.body.
     * @param parent container element for ARIA dom node
     */
    function createAriaDomNode(parent) {
        if (!parent) {
            if (ariaDomNodeCreated) {
                return;
            }
            ariaDomNodeCreated = true;
        }
        aria.setARIAContainer(parent || window_1.mainWindow.document.body);
    }
    /**
     * A code editor to be used both by the standalone editor and the standalone diff editor.
     */
    let StandaloneCodeEditor = class StandaloneCodeEditor extends codeEditorWidget_1.CodeEditorWidget {
        constructor(domElement, _options, instantiationService, codeEditorService, commandService, contextKeyService, hoverService, keybindingService, themeService, notificationService, accessibilityService, languageConfigurationService, languageFeaturesService) {
            const options = { ..._options };
            options.ariaLabel = options.ariaLabel || standaloneStrings_1.StandaloneCodeEditorNLS.editorViewAccessibleLabel;
            super(domElement, options, {}, instantiationService, codeEditorService, commandService, contextKeyService, themeService, notificationService, accessibilityService, languageConfigurationService, languageFeaturesService);
            if (keybindingService instanceof standaloneServices_1.StandaloneKeybindingService) {
                this._standaloneKeybindingService = keybindingService;
            }
            else {
                this._standaloneKeybindingService = null;
            }
            createAriaDomNode(options.ariaContainerElement);
            (0, hoverDelegateFactory_1.setHoverDelegateFactory)((placement, enableInstantHover) => instantiationService.createInstance(hover_1.WorkbenchHoverDelegate, placement, enableInstantHover, {}));
            (0, hoverDelegate2_1.setBaseLayerHoverDelegate)(hoverService);
        }
        addCommand(keybinding, handler, context) {
            if (!this._standaloneKeybindingService) {
                console.warn('Cannot add command because the editor is configured with an unrecognized KeybindingService');
                return null;
            }
            const commandId = 'DYNAMIC_' + (++LAST_GENERATED_COMMAND_ID);
            const whenExpression = contextkey_1.ContextKeyExpr.deserialize(context);
            this._standaloneKeybindingService.addDynamicKeybinding(commandId, keybinding, handler, whenExpression);
            return commandId;
        }
        createContextKey(key, defaultValue) {
            return this._contextKeyService.createKey(key, defaultValue);
        }
        addAction(_descriptor) {
            if ((typeof _descriptor.id !== 'string') || (typeof _descriptor.label !== 'string') || (typeof _descriptor.run !== 'function')) {
                throw new Error('Invalid action descriptor, `id`, `label` and `run` are required properties!');
            }
            if (!this._standaloneKeybindingService) {
                console.warn('Cannot add keybinding because the editor is configured with an unrecognized KeybindingService');
                return lifecycle_1.Disposable.None;
            }
            // Read descriptor options
            const id = _descriptor.id;
            const label = _descriptor.label;
            const precondition = contextkey_1.ContextKeyExpr.and(contextkey_1.ContextKeyExpr.equals('editorId', this.getId()), contextkey_1.ContextKeyExpr.deserialize(_descriptor.precondition));
            const keybindings = _descriptor.keybindings;
            const keybindingsWhen = contextkey_1.ContextKeyExpr.and(precondition, contextkey_1.ContextKeyExpr.deserialize(_descriptor.keybindingContext));
            const contextMenuGroupId = _descriptor.contextMenuGroupId || null;
            const contextMenuOrder = _descriptor.contextMenuOrder || 0;
            const run = (_accessor, ...args) => {
                return Promise.resolve(_descriptor.run(this, ...args));
            };
            const toDispose = new lifecycle_1.DisposableStore();
            // Generate a unique id to allow the same descriptor.id across multiple editor instances
            const uniqueId = this.getId() + ':' + id;
            // Register the command
            toDispose.add(commands_1.CommandsRegistry.registerCommand(uniqueId, run));
            // Register the context menu item
            if (contextMenuGroupId) {
                const menuItem = {
                    command: {
                        id: uniqueId,
                        title: label
                    },
                    when: precondition,
                    group: contextMenuGroupId,
                    order: contextMenuOrder
                };
                toDispose.add(actions_1.MenuRegistry.appendMenuItem(actions_1.MenuId.EditorContext, menuItem));
            }
            // Register the keybindings
            if (Array.isArray(keybindings)) {
                for (const kb of keybindings) {
                    toDispose.add(this._standaloneKeybindingService.addDynamicKeybinding(uniqueId, kb, run, keybindingsWhen));
                }
            }
            // Finally, register an internal editor action
            const internalAction = new editorAction_1.InternalEditorAction(uniqueId, label, label, undefined, precondition, (...args) => Promise.resolve(_descriptor.run(this, ...args)), this._contextKeyService);
            // Store it under the original id, such that trigger with the original id will work
            this._actions.set(id, internalAction);
            toDispose.add((0, lifecycle_1.toDisposable)(() => {
                this._actions.delete(id);
            }));
            return toDispose;
        }
        _triggerCommand(handlerId, payload) {
            if (this._codeEditorService instanceof standaloneCodeEditorService_1.StandaloneCodeEditorService) {
                // Help commands find this editor as the active editor
                try {
                    this._codeEditorService.setActiveCodeEditor(this);
                    super._triggerCommand(handlerId, payload);
                }
                finally {
                    this._codeEditorService.setActiveCodeEditor(null);
                }
            }
            else {
                super._triggerCommand(handlerId, payload);
            }
        }
    };
    exports.StandaloneCodeEditor = StandaloneCodeEditor;
    exports.StandaloneCodeEditor = StandaloneCodeEditor = __decorate([
        __param(2, instantiation_1.IInstantiationService),
        __param(3, codeEditorService_1.ICodeEditorService),
        __param(4, commands_1.ICommandService),
        __param(5, contextkey_1.IContextKeyService),
        __param(6, hover_1.IHoverService),
        __param(7, keybinding_1.IKeybindingService),
        __param(8, themeService_1.IThemeService),
        __param(9, notification_1.INotificationService),
        __param(10, accessibility_1.IAccessibilityService),
        __param(11, languageConfigurationRegistry_1.ILanguageConfigurationService),
        __param(12, languageFeatures_1.ILanguageFeaturesService)
    ], StandaloneCodeEditor);
    let StandaloneEditor = class StandaloneEditor extends StandaloneCodeEditor {
        constructor(domElement, _options, instantiationService, codeEditorService, commandService, contextKeyService, hoverService, keybindingService, themeService, notificationService, configurationService, accessibilityService, modelService, languageService, languageConfigurationService, languageFeaturesService) {
            const options = { ..._options };
            (0, standaloneServices_1.updateConfigurationService)(configurationService, options, false);
            const themeDomRegistration = themeService.registerEditorContainer(domElement);
            if (typeof options.theme === 'string') {
                themeService.setTheme(options.theme);
            }
            if (typeof options.autoDetectHighContrast !== 'undefined') {
                themeService.setAutoDetectHighContrast(Boolean(options.autoDetectHighContrast));
            }
            const _model = options.model;
            delete options.model;
            super(domElement, options, instantiationService, codeEditorService, commandService, contextKeyService, hoverService, keybindingService, themeService, notificationService, accessibilityService, languageConfigurationService, languageFeaturesService);
            this._configurationService = configurationService;
            this._standaloneThemeService = themeService;
            this._register(themeDomRegistration);
            let model;
            if (typeof _model === 'undefined') {
                const languageId = languageService.getLanguageIdByMimeType(options.language) || options.language || modesRegistry_1.PLAINTEXT_LANGUAGE_ID;
                model = createTextModel(modelService, languageService, options.value || '', languageId, undefined);
                this._ownsModel = true;
            }
            else {
                model = _model;
                this._ownsModel = false;
            }
            this._attachModel(model);
            if (model) {
                const e = {
                    oldModelUrl: null,
                    newModelUrl: model.uri
                };
                this._onDidChangeModel.fire(e);
            }
        }
        dispose() {
            super.dispose();
        }
        updateOptions(newOptions) {
            (0, standaloneServices_1.updateConfigurationService)(this._configurationService, newOptions, false);
            if (typeof newOptions.theme === 'string') {
                this._standaloneThemeService.setTheme(newOptions.theme);
            }
            if (typeof newOptions.autoDetectHighContrast !== 'undefined') {
                this._standaloneThemeService.setAutoDetectHighContrast(Boolean(newOptions.autoDetectHighContrast));
            }
            super.updateOptions(newOptions);
        }
        _postDetachModelCleanup(detachedModel) {
            super._postDetachModelCleanup(detachedModel);
            if (detachedModel && this._ownsModel) {
                detachedModel.dispose();
                this._ownsModel = false;
            }
        }
    };
    exports.StandaloneEditor = StandaloneEditor;
    exports.StandaloneEditor = StandaloneEditor = __decorate([
        __param(2, instantiation_1.IInstantiationService),
        __param(3, codeEditorService_1.ICodeEditorService),
        __param(4, commands_1.ICommandService),
        __param(5, contextkey_1.IContextKeyService),
        __param(6, hover_1.IHoverService),
        __param(7, keybinding_1.IKeybindingService),
        __param(8, standaloneTheme_1.IStandaloneThemeService),
        __param(9, notification_1.INotificationService),
        __param(10, configuration_1.IConfigurationService),
        __param(11, accessibility_1.IAccessibilityService),
        __param(12, model_1.IModelService),
        __param(13, language_1.ILanguageService),
        __param(14, languageConfigurationRegistry_1.ILanguageConfigurationService),
        __param(15, languageFeatures_1.ILanguageFeaturesService)
    ], StandaloneEditor);
    let StandaloneDiffEditor2 = class StandaloneDiffEditor2 extends diffEditorWidget_1.DiffEditorWidget {
        constructor(domElement, _options, instantiationService, contextKeyService, codeEditorService, themeService, notificationService, configurationService, contextMenuService, editorProgressService, clipboardService, accessibilitySignalService) {
            const options = { ..._options };
            (0, standaloneServices_1.updateConfigurationService)(configurationService, options, true);
            const themeDomRegistration = themeService.registerEditorContainer(domElement);
            if (typeof options.theme === 'string') {
                themeService.setTheme(options.theme);
            }
            if (typeof options.autoDetectHighContrast !== 'undefined') {
                themeService.setAutoDetectHighContrast(Boolean(options.autoDetectHighContrast));
            }
            super(domElement, options, {}, contextKeyService, instantiationService, codeEditorService, accessibilitySignalService, editorProgressService);
            this._configurationService = configurationService;
            this._standaloneThemeService = themeService;
            this._register(themeDomRegistration);
        }
        dispose() {
            super.dispose();
        }
        updateOptions(newOptions) {
            (0, standaloneServices_1.updateConfigurationService)(this._configurationService, newOptions, true);
            if (typeof newOptions.theme === 'string') {
                this._standaloneThemeService.setTheme(newOptions.theme);
            }
            if (typeof newOptions.autoDetectHighContrast !== 'undefined') {
                this._standaloneThemeService.setAutoDetectHighContrast(Boolean(newOptions.autoDetectHighContrast));
            }
            super.updateOptions(newOptions);
        }
        _createInnerEditor(instantiationService, container, options) {
            return instantiationService.createInstance(StandaloneCodeEditor, container, options);
        }
        getOriginalEditor() {
            return super.getOriginalEditor();
        }
        getModifiedEditor() {
            return super.getModifiedEditor();
        }
        addCommand(keybinding, handler, context) {
            return this.getModifiedEditor().addCommand(keybinding, handler, context);
        }
        createContextKey(key, defaultValue) {
            return this.getModifiedEditor().createContextKey(key, defaultValue);
        }
        addAction(descriptor) {
            return this.getModifiedEditor().addAction(descriptor);
        }
    };
    exports.StandaloneDiffEditor2 = StandaloneDiffEditor2;
    exports.StandaloneDiffEditor2 = StandaloneDiffEditor2 = __decorate([
        __param(2, instantiation_1.IInstantiationService),
        __param(3, contextkey_1.IContextKeyService),
        __param(4, codeEditorService_1.ICodeEditorService),
        __param(5, standaloneTheme_1.IStandaloneThemeService),
        __param(6, notification_1.INotificationService),
        __param(7, configuration_1.IConfigurationService),
        __param(8, contextView_1.IContextMenuService),
        __param(9, progress_1.IEditorProgressService),
        __param(10, clipboardService_1.IClipboardService),
        __param(11, accessibilitySignalService_1.IAccessibilitySignalService)
    ], StandaloneDiffEditor2);
    /**
     * @internal
     */
    function createTextModel(modelService, languageService, value, languageId, uri) {
        value = value || '';
        if (!languageId) {
            const firstLF = value.indexOf('\n');
            let firstLine = value;
            if (firstLF !== -1) {
                firstLine = value.substring(0, firstLF);
            }
            return doCreateModel(modelService, value, languageService.createByFilepathOrFirstLine(uri || null, firstLine), uri);
        }
        return doCreateModel(modelService, value, languageService.createById(languageId), uri);
    }
    /**
     * @internal
     */
    function doCreateModel(modelService, value, languageSelection, uri) {
        return modelService.createModel(value, languageSelection, uri);
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[872/*vs/editor/standalone/browser/standaloneLanguages*/], __M([1/*require*/,0/*exports*/,33/*vs/base/common/color*/,4/*vs/editor/common/core/range*/,27/*vs/editor/common/languages*/,43/*vs/editor/common/languages/language*/,36/*vs/editor/common/languages/languageConfigurationRegistry*/,70/*vs/editor/common/languages/modesRegistry*/,17/*vs/editor/common/services/languageFeatures*/,238/*vs/editor/common/standalone/standaloneEnums*/,222/*vs/editor/standalone/browser/standaloneServices*/,625/*vs/editor/standalone/common/monarch/monarchCompile*/,389/*vs/editor/standalone/common/monarch/monarchLexer*/,153/*vs/editor/standalone/common/standaloneTheme*/,28/*vs/platform/configuration/common/configuration*/,108/*vs/platform/markers/common/markers*/]), function (require, exports, color_1, range_1, languages, language_1, languageConfigurationRegistry_1, modesRegistry_1, languageFeatures_1, standaloneEnums, standaloneServices_1, monarchCompile_1, monarchLexer_1, standaloneTheme_1, configuration_1, markers_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.TokenizationSupportAdapter = exports.EncodedTokenizationSupportAdapter = void 0;
    exports.register = register;
    exports.getLanguages = getLanguages;
    exports.getEncodedLanguageId = getEncodedLanguageId;
    exports.onLanguage = onLanguage;
    exports.onLanguageEncountered = onLanguageEncountered;
    exports.setLanguageConfiguration = setLanguageConfiguration;
    exports.setColorMap = setColorMap;
    exports.registerTokensProviderFactory = registerTokensProviderFactory;
    exports.setTokensProvider = setTokensProvider;
    exports.setMonarchTokensProvider = setMonarchTokensProvider;
    exports.registerReferenceProvider = registerReferenceProvider;
    exports.registerRenameProvider = registerRenameProvider;
    exports.registerNewSymbolNameProvider = registerNewSymbolNameProvider;
    exports.registerSignatureHelpProvider = registerSignatureHelpProvider;
    exports.registerHoverProvider = registerHoverProvider;
    exports.registerDocumentSymbolProvider = registerDocumentSymbolProvider;
    exports.registerDocumentHighlightProvider = registerDocumentHighlightProvider;
    exports.registerLinkedEditingRangeProvider = registerLinkedEditingRangeProvider;
    exports.registerDefinitionProvider = registerDefinitionProvider;
    exports.registerImplementationProvider = registerImplementationProvider;
    exports.registerTypeDefinitionProvider = registerTypeDefinitionProvider;
    exports.registerCodeLensProvider = registerCodeLensProvider;
    exports.registerCodeActionProvider = registerCodeActionProvider;
    exports.registerDocumentFormattingEditProvider = registerDocumentFormattingEditProvider;
    exports.registerDocumentRangeFormattingEditProvider = registerDocumentRangeFormattingEditProvider;
    exports.registerOnTypeFormattingEditProvider = registerOnTypeFormattingEditProvider;
    exports.registerLinkProvider = registerLinkProvider;
    exports.registerCompletionItemProvider = registerCompletionItemProvider;
    exports.registerColorProvider = registerColorProvider;
    exports.registerFoldingRangeProvider = registerFoldingRangeProvider;
    exports.registerDeclarationProvider = registerDeclarationProvider;
    exports.registerSelectionRangeProvider = registerSelectionRangeProvider;
    exports.registerDocumentSemanticTokensProvider = registerDocumentSemanticTokensProvider;
    exports.registerDocumentRangeSemanticTokensProvider = registerDocumentRangeSemanticTokensProvider;
    exports.registerInlineCompletionsProvider = registerInlineCompletionsProvider;
    exports.registerInlineEditProvider = registerInlineEditProvider;
    exports.registerInlayHintsProvider = registerInlayHintsProvider;
    exports.createMonacoLanguagesAPI = createMonacoLanguagesAPI;
    /**
     * Register information about a new language.
     */
    function register(language) {
        // Intentionally using the `ModesRegistry` here to avoid
        // instantiating services too quickly in the standalone editor.
        modesRegistry_1.ModesRegistry.registerLanguage(language);
    }
    /**
     * Get the information of all the registered languages.
     */
    function getLanguages() {
        let result = [];
        result = result.concat(modesRegistry_1.ModesRegistry.getLanguages());
        return result;
    }
    function getEncodedLanguageId(languageId) {
        const languageService = standaloneServices_1.StandaloneServices.get(language_1.ILanguageService);
        return languageService.languageIdCodec.encodeLanguageId(languageId);
    }
    /**
     * An event emitted when a language is associated for the first time with a text model.
     * @event
     */
    function onLanguage(languageId, callback) {
        return standaloneServices_1.StandaloneServices.withServices(() => {
            const languageService = standaloneServices_1.StandaloneServices.get(language_1.ILanguageService);
            const disposable = languageService.onDidRequestRichLanguageFeatures((encounteredLanguageId) => {
                if (encounteredLanguageId === languageId) {
                    // stop listening
                    disposable.dispose();
                    // invoke actual listener
                    callback();
                }
            });
            return disposable;
        });
    }
    /**
     * An event emitted when a language is associated for the first time with a text model or
     * when a language is encountered during the tokenization of another language.
     * @event
     */
    function onLanguageEncountered(languageId, callback) {
        return standaloneServices_1.StandaloneServices.withServices(() => {
            const languageService = standaloneServices_1.StandaloneServices.get(language_1.ILanguageService);
            const disposable = languageService.onDidRequestBasicLanguageFeatures((encounteredLanguageId) => {
                if (encounteredLanguageId === languageId) {
                    // stop listening
                    disposable.dispose();
                    // invoke actual listener
                    callback();
                }
            });
            return disposable;
        });
    }
    /**
     * Set the editing configuration for a language.
     */
    function setLanguageConfiguration(languageId, configuration) {
        const languageService = standaloneServices_1.StandaloneServices.get(language_1.ILanguageService);
        if (!languageService.isRegisteredLanguageId(languageId)) {
            throw new Error(`Cannot set configuration for unknown language ${languageId}`);
        }
        const languageConfigurationService = standaloneServices_1.StandaloneServices.get(languageConfigurationRegistry_1.ILanguageConfigurationService);
        return languageConfigurationService.register(languageId, configuration, 100);
    }
    /**
     * @internal
     */
    class EncodedTokenizationSupportAdapter {
        constructor(languageId, actual) {
            this._languageId = languageId;
            this._actual = actual;
        }
        dispose() {
            // NOOP
        }
        getInitialState() {
            return this._actual.getInitialState();
        }
        tokenize(line, hasEOL, state) {
            if (typeof this._actual.tokenize === 'function') {
                return TokenizationSupportAdapter.adaptTokenize(this._languageId, this._actual, line, state);
            }
            throw new Error('Not supported!');
        }
        tokenizeEncoded(line, hasEOL, state) {
            const result = this._actual.tokenizeEncoded(line, state);
            return new languages.EncodedTokenizationResult(result.tokens, result.endState);
        }
    }
    exports.EncodedTokenizationSupportAdapter = EncodedTokenizationSupportAdapter;
    /**
     * @internal
     */
    class TokenizationSupportAdapter {
        constructor(_languageId, _actual, _languageService, _standaloneThemeService) {
            this._languageId = _languageId;
            this._actual = _actual;
            this._languageService = _languageService;
            this._standaloneThemeService = _standaloneThemeService;
        }
        dispose() {
            // NOOP
        }
        getInitialState() {
            return this._actual.getInitialState();
        }
        static _toClassicTokens(tokens, language) {
            const result = [];
            let previousStartIndex = 0;
            for (let i = 0, len = tokens.length; i < len; i++) {
                const t = tokens[i];
                let startIndex = t.startIndex;
                // Prevent issues stemming from a buggy external tokenizer.
                if (i === 0) {
                    // Force first token to start at first index!
                    startIndex = 0;
                }
                else if (startIndex < previousStartIndex) {
                    // Force tokens to be after one another!
                    startIndex = previousStartIndex;
                }
                result[i] = new languages.Token(startIndex, t.scopes, language);
                previousStartIndex = startIndex;
            }
            return result;
        }
        static adaptTokenize(language, actual, line, state) {
            const actualResult = actual.tokenize(line, state);
            const tokens = TokenizationSupportAdapter._toClassicTokens(actualResult.tokens, language);
            let endState;
            // try to save an object if possible
            if (actualResult.endState.equals(state)) {
                endState = state;
            }
            else {
                endState = actualResult.endState;
            }
            return new languages.TokenizationResult(tokens, endState);
        }
        tokenize(line, hasEOL, state) {
            return TokenizationSupportAdapter.adaptTokenize(this._languageId, this._actual, line, state);
        }
        _toBinaryTokens(languageIdCodec, tokens) {
            const languageId = languageIdCodec.encodeLanguageId(this._languageId);
            const tokenTheme = this._standaloneThemeService.getColorTheme().tokenTheme;
            const result = [];
            let resultLen = 0;
            let previousStartIndex = 0;
            for (let i = 0, len = tokens.length; i < len; i++) {
                const t = tokens[i];
                const metadata = tokenTheme.match(languageId, t.scopes) | 1024 /* MetadataConsts.BALANCED_BRACKETS_MASK */;
                if (resultLen > 0 && result[resultLen - 1] === metadata) {
                    // same metadata
                    continue;
                }
                let startIndex = t.startIndex;
                // Prevent issues stemming from a buggy external tokenizer.
                if (i === 0) {
                    // Force first token to start at first index!
                    startIndex = 0;
                }
                else if (startIndex < previousStartIndex) {
                    // Force tokens to be after one another!
                    startIndex = previousStartIndex;
                }
                result[resultLen++] = startIndex;
                result[resultLen++] = metadata;
                previousStartIndex = startIndex;
            }
            const actualResult = new Uint32Array(resultLen);
            for (let i = 0; i < resultLen; i++) {
                actualResult[i] = result[i];
            }
            return actualResult;
        }
        tokenizeEncoded(line, hasEOL, state) {
            const actualResult = this._actual.tokenize(line, state);
            const tokens = this._toBinaryTokens(this._languageService.languageIdCodec, actualResult.tokens);
            let endState;
            // try to save an object if possible
            if (actualResult.endState.equals(state)) {
                endState = state;
            }
            else {
                endState = actualResult.endState;
            }
            return new languages.EncodedTokenizationResult(tokens, endState);
        }
    }
    exports.TokenizationSupportAdapter = TokenizationSupportAdapter;
    function isATokensProvider(provider) {
        return (typeof provider.getInitialState === 'function');
    }
    function isEncodedTokensProvider(provider) {
        return 'tokenizeEncoded' in provider;
    }
    function isThenable(obj) {
        return obj && typeof obj.then === 'function';
    }
    /**
     * Change the color map that is used for token colors.
     * Supported formats (hex): #RRGGBB, $RRGGBBAA, #RGB, #RGBA
     */
    function setColorMap(colorMap) {
        const standaloneThemeService = standaloneServices_1.StandaloneServices.get(standaloneTheme_1.IStandaloneThemeService);
        if (colorMap) {
            const result = [null];
            for (let i = 1, len = colorMap.length; i < len; i++) {
                result[i] = color_1.Color.fromHex(colorMap[i]);
            }
            standaloneThemeService.setColorMapOverride(result);
        }
        else {
            standaloneThemeService.setColorMapOverride(null);
        }
    }
    /**
     * @internal
     */
    function createTokenizationSupportAdapter(languageId, provider) {
        if (isEncodedTokensProvider(provider)) {
            return new EncodedTokenizationSupportAdapter(languageId, provider);
        }
        else {
            return new TokenizationSupportAdapter(languageId, provider, standaloneServices_1.StandaloneServices.get(language_1.ILanguageService), standaloneServices_1.StandaloneServices.get(standaloneTheme_1.IStandaloneThemeService));
        }
    }
    /**
     * Register a tokens provider factory for a language. This tokenizer will be exclusive with a tokenizer
     * set using `setTokensProvider` or one created using `setMonarchTokensProvider`, but will work together
     * with a tokens provider set using `registerDocumentSemanticTokensProvider` or `registerDocumentRangeSemanticTokensProvider`.
     */
    function registerTokensProviderFactory(languageId, factory) {
        const adaptedFactory = new languages.LazyTokenizationSupport(async () => {
            const result = await Promise.resolve(factory.create());
            if (!result) {
                return null;
            }
            if (isATokensProvider(result)) {
                return createTokenizationSupportAdapter(languageId, result);
            }
            return new monarchLexer_1.MonarchTokenizer(standaloneServices_1.StandaloneServices.get(language_1.ILanguageService), standaloneServices_1.StandaloneServices.get(standaloneTheme_1.IStandaloneThemeService), languageId, (0, monarchCompile_1.compile)(languageId, result), standaloneServices_1.StandaloneServices.get(configuration_1.IConfigurationService));
        });
        return languages.TokenizationRegistry.registerFactory(languageId, adaptedFactory);
    }
    /**
     * Set the tokens provider for a language (manual implementation). This tokenizer will be exclusive
     * with a tokenizer created using `setMonarchTokensProvider`, or with `registerTokensProviderFactory`,
     * but will work together with a tokens provider set using `registerDocumentSemanticTokensProvider`
     * or `registerDocumentRangeSemanticTokensProvider`.
     */
    function setTokensProvider(languageId, provider) {
        const languageService = standaloneServices_1.StandaloneServices.get(language_1.ILanguageService);
        if (!languageService.isRegisteredLanguageId(languageId)) {
            throw new Error(`Cannot set tokens provider for unknown language ${languageId}`);
        }
        if (isThenable(provider)) {
            return registerTokensProviderFactory(languageId, { create: () => provider });
        }
        return languages.TokenizationRegistry.register(languageId, createTokenizationSupportAdapter(languageId, provider));
    }
    /**
     * Set the tokens provider for a language (monarch implementation). This tokenizer will be exclusive
     * with a tokenizer set using `setTokensProvider`, or with `registerTokensProviderFactory`, but will
     * work together with a tokens provider set using `registerDocumentSemanticTokensProvider` or
     * `registerDocumentRangeSemanticTokensProvider`.
     */
    function setMonarchTokensProvider(languageId, languageDef) {
        const create = (languageDef) => {
            return new monarchLexer_1.MonarchTokenizer(standaloneServices_1.StandaloneServices.get(language_1.ILanguageService), standaloneServices_1.StandaloneServices.get(standaloneTheme_1.IStandaloneThemeService), languageId, (0, monarchCompile_1.compile)(languageId, languageDef), standaloneServices_1.StandaloneServices.get(configuration_1.IConfigurationService));
        };
        if (isThenable(languageDef)) {
            return registerTokensProviderFactory(languageId, { create: () => languageDef });
        }
        return languages.TokenizationRegistry.register(languageId, create(languageDef));
    }
    /**
     * Register a reference provider (used by e.g. reference search).
     */
    function registerReferenceProvider(languageSelector, provider) {
        const languageFeaturesService = standaloneServices_1.StandaloneServices.get(languageFeatures_1.ILanguageFeaturesService);
        return languageFeaturesService.referenceProvider.register(languageSelector, provider);
    }
    /**
     * Register a rename provider (used by e.g. rename symbol).
     */
    function registerRenameProvider(languageSelector, provider) {
        const languageFeaturesService = standaloneServices_1.StandaloneServices.get(languageFeatures_1.ILanguageFeaturesService);
        return languageFeaturesService.renameProvider.register(languageSelector, provider);
    }
    /**
     * Register a new symbol-name provider (e.g., when a symbol is being renamed, show new possible symbol-names)
     */
    function registerNewSymbolNameProvider(languageSelector, provider) {
        const languageFeaturesService = standaloneServices_1.StandaloneServices.get(languageFeatures_1.ILanguageFeaturesService);
        return languageFeaturesService.newSymbolNamesProvider.register(languageSelector, provider);
    }
    /**
     * Register a signature help provider (used by e.g. parameter hints).
     */
    function registerSignatureHelpProvider(languageSelector, provider) {
        const languageFeaturesService = standaloneServices_1.StandaloneServices.get(languageFeatures_1.ILanguageFeaturesService);
        return languageFeaturesService.signatureHelpProvider.register(languageSelector, provider);
    }
    /**
     * Register a hover provider (used by e.g. editor hover).
     */
    function registerHoverProvider(languageSelector, provider) {
        const languageFeaturesService = standaloneServices_1.StandaloneServices.get(languageFeatures_1.ILanguageFeaturesService);
        return languageFeaturesService.hoverProvider.register(languageSelector, {
            provideHover: async (model, position, token, context) => {
                const word = model.getWordAtPosition(position);
                return Promise.resolve(provider.provideHover(model, position, token, context)).then((value) => {
                    if (!value) {
                        return undefined;
                    }
                    if (!value.range && word) {
                        value.range = new range_1.Range(position.lineNumber, word.startColumn, position.lineNumber, word.endColumn);
                    }
                    if (!value.range) {
                        value.range = new range_1.Range(position.lineNumber, position.column, position.lineNumber, position.column);
                    }
                    return value;
                });
            }
        });
    }
    /**
     * Register a document symbol provider (used by e.g. outline).
     */
    function registerDocumentSymbolProvider(languageSelector, provider) {
        const languageFeaturesService = standaloneServices_1.StandaloneServices.get(languageFeatures_1.ILanguageFeaturesService);
        return languageFeaturesService.documentSymbolProvider.register(languageSelector, provider);
    }
    /**
     * Register a document highlight provider (used by e.g. highlight occurrences).
     */
    function registerDocumentHighlightProvider(languageSelector, provider) {
        const languageFeaturesService = standaloneServices_1.StandaloneServices.get(languageFeatures_1.ILanguageFeaturesService);
        return languageFeaturesService.documentHighlightProvider.register(languageSelector, provider);
    }
    /**
     * Register an linked editing range provider.
     */
    function registerLinkedEditingRangeProvider(languageSelector, provider) {
        const languageFeaturesService = standaloneServices_1.StandaloneServices.get(languageFeatures_1.ILanguageFeaturesService);
        return languageFeaturesService.linkedEditingRangeProvider.register(languageSelector, provider);
    }
    /**
     * Register a definition provider (used by e.g. go to definition).
     */
    function registerDefinitionProvider(languageSelector, provider) {
        const languageFeaturesService = standaloneServices_1.StandaloneServices.get(languageFeatures_1.ILanguageFeaturesService);
        return languageFeaturesService.definitionProvider.register(languageSelector, provider);
    }
    /**
     * Register a implementation provider (used by e.g. go to implementation).
     */
    function registerImplementationProvider(languageSelector, provider) {
        const languageFeaturesService = standaloneServices_1.StandaloneServices.get(languageFeatures_1.ILanguageFeaturesService);
        return languageFeaturesService.implementationProvider.register(languageSelector, provider);
    }
    /**
     * Register a type definition provider (used by e.g. go to type definition).
     */
    function registerTypeDefinitionProvider(languageSelector, provider) {
        const languageFeaturesService = standaloneServices_1.StandaloneServices.get(languageFeatures_1.ILanguageFeaturesService);
        return languageFeaturesService.typeDefinitionProvider.register(languageSelector, provider);
    }
    /**
     * Register a code lens provider (used by e.g. inline code lenses).
     */
    function registerCodeLensProvider(languageSelector, provider) {
        const languageFeaturesService = standaloneServices_1.StandaloneServices.get(languageFeatures_1.ILanguageFeaturesService);
        return languageFeaturesService.codeLensProvider.register(languageSelector, provider);
    }
    /**
     * Register a code action provider (used by e.g. quick fix).
     */
    function registerCodeActionProvider(languageSelector, provider, metadata) {
        const languageFeaturesService = standaloneServices_1.StandaloneServices.get(languageFeatures_1.ILanguageFeaturesService);
        return languageFeaturesService.codeActionProvider.register(languageSelector, {
            providedCodeActionKinds: metadata?.providedCodeActionKinds,
            documentation: metadata?.documentation,
            provideCodeActions: (model, range, context, token) => {
                const markerService = standaloneServices_1.StandaloneServices.get(markers_1.IMarkerService);
                const markers = markerService.read({ resource: model.uri }).filter(m => {
                    return range_1.Range.areIntersectingOrTouching(m, range);
                });
                return provider.provideCodeActions(model, range, { markers, only: context.only, trigger: context.trigger }, token);
            },
            resolveCodeAction: provider.resolveCodeAction
        });
    }
    /**
     * Register a formatter that can handle only entire models.
     */
    function registerDocumentFormattingEditProvider(languageSelector, provider) {
        const languageFeaturesService = standaloneServices_1.StandaloneServices.get(languageFeatures_1.ILanguageFeaturesService);
        return languageFeaturesService.documentFormattingEditProvider.register(languageSelector, provider);
    }
    /**
     * Register a formatter that can handle a range inside a model.
     */
    function registerDocumentRangeFormattingEditProvider(languageSelector, provider) {
        const languageFeaturesService = standaloneServices_1.StandaloneServices.get(languageFeatures_1.ILanguageFeaturesService);
        return languageFeaturesService.documentRangeFormattingEditProvider.register(languageSelector, provider);
    }
    /**
     * Register a formatter than can do formatting as the user types.
     */
    function registerOnTypeFormattingEditProvider(languageSelector, provider) {
        const languageFeaturesService = standaloneServices_1.StandaloneServices.get(languageFeatures_1.ILanguageFeaturesService);
        return languageFeaturesService.onTypeFormattingEditProvider.register(languageSelector, provider);
    }
    /**
     * Register a link provider that can find links in text.
     */
    function registerLinkProvider(languageSelector, provider) {
        const languageFeaturesService = standaloneServices_1.StandaloneServices.get(languageFeatures_1.ILanguageFeaturesService);
        return languageFeaturesService.linkProvider.register(languageSelector, provider);
    }
    /**
     * Register a completion item provider (use by e.g. suggestions).
     */
    function registerCompletionItemProvider(languageSelector, provider) {
        const languageFeaturesService = standaloneServices_1.StandaloneServices.get(languageFeatures_1.ILanguageFeaturesService);
        return languageFeaturesService.completionProvider.register(languageSelector, provider);
    }
    /**
     * Register a document color provider (used by Color Picker, Color Decorator).
     */
    function registerColorProvider(languageSelector, provider) {
        const languageFeaturesService = standaloneServices_1.StandaloneServices.get(languageFeatures_1.ILanguageFeaturesService);
        return languageFeaturesService.colorProvider.register(languageSelector, provider);
    }
    /**
     * Register a folding range provider
     */
    function registerFoldingRangeProvider(languageSelector, provider) {
        const languageFeaturesService = standaloneServices_1.StandaloneServices.get(languageFeatures_1.ILanguageFeaturesService);
        return languageFeaturesService.foldingRangeProvider.register(languageSelector, provider);
    }
    /**
     * Register a declaration provider
     */
    function registerDeclarationProvider(languageSelector, provider) {
        const languageFeaturesService = standaloneServices_1.StandaloneServices.get(languageFeatures_1.ILanguageFeaturesService);
        return languageFeaturesService.declarationProvider.register(languageSelector, provider);
    }
    /**
     * Register a selection range provider
     */
    function registerSelectionRangeProvider(languageSelector, provider) {
        const languageFeaturesService = standaloneServices_1.StandaloneServices.get(languageFeatures_1.ILanguageFeaturesService);
        return languageFeaturesService.selectionRangeProvider.register(languageSelector, provider);
    }
    /**
     * Register a document semantic tokens provider. A semantic tokens provider will complement and enhance a
     * simple top-down tokenizer. Simple top-down tokenizers can be set either via `setMonarchTokensProvider`
     * or `setTokensProvider`.
     *
     * For the best user experience, register both a semantic tokens provider and a top-down tokenizer.
     */
    function registerDocumentSemanticTokensProvider(languageSelector, provider) {
        const languageFeaturesService = standaloneServices_1.StandaloneServices.get(languageFeatures_1.ILanguageFeaturesService);
        return languageFeaturesService.documentSemanticTokensProvider.register(languageSelector, provider);
    }
    /**
     * Register a document range semantic tokens provider. A semantic tokens provider will complement and enhance a
     * simple top-down tokenizer. Simple top-down tokenizers can be set either via `setMonarchTokensProvider`
     * or `setTokensProvider`.
     *
     * For the best user experience, register both a semantic tokens provider and a top-down tokenizer.
     */
    function registerDocumentRangeSemanticTokensProvider(languageSelector, provider) {
        const languageFeaturesService = standaloneServices_1.StandaloneServices.get(languageFeatures_1.ILanguageFeaturesService);
        return languageFeaturesService.documentRangeSemanticTokensProvider.register(languageSelector, provider);
    }
    /**
     * Register an inline completions provider.
     */
    function registerInlineCompletionsProvider(languageSelector, provider) {
        const languageFeaturesService = standaloneServices_1.StandaloneServices.get(languageFeatures_1.ILanguageFeaturesService);
        return languageFeaturesService.inlineCompletionsProvider.register(languageSelector, provider);
    }
    function registerInlineEditProvider(languageSelector, provider) {
        const languageFeaturesService = standaloneServices_1.StandaloneServices.get(languageFeatures_1.ILanguageFeaturesService);
        return languageFeaturesService.inlineEditProvider.register(languageSelector, provider);
    }
    /**
     * Register an inlay hints provider.
     */
    function registerInlayHintsProvider(languageSelector, provider) {
        const languageFeaturesService = standaloneServices_1.StandaloneServices.get(languageFeatures_1.ILanguageFeaturesService);
        return languageFeaturesService.inlayHintsProvider.register(languageSelector, provider);
    }
    /**
     * @internal
     */
    function createMonacoLanguagesAPI() {
        return {
            register: register,
            getLanguages: getLanguages,
            onLanguage: onLanguage,
            onLanguageEncountered: onLanguageEncountered,
            getEncodedLanguageId: getEncodedLanguageId,
            // provider methods
            setLanguageConfiguration: setLanguageConfiguration,
            setColorMap: setColorMap,
            registerTokensProviderFactory: registerTokensProviderFactory,
            setTokensProvider: setTokensProvider,
            setMonarchTokensProvider: setMonarchTokensProvider,
            registerReferenceProvider: registerReferenceProvider,
            registerRenameProvider: registerRenameProvider,
            registerNewSymbolNameProvider: registerNewSymbolNameProvider,
            registerCompletionItemProvider: registerCompletionItemProvider,
            registerSignatureHelpProvider: registerSignatureHelpProvider,
            registerHoverProvider: registerHoverProvider,
            registerDocumentSymbolProvider: registerDocumentSymbolProvider,
            registerDocumentHighlightProvider: registerDocumentHighlightProvider,
            registerLinkedEditingRangeProvider: registerLinkedEditingRangeProvider,
            registerDefinitionProvider: registerDefinitionProvider,
            registerImplementationProvider: registerImplementationProvider,
            registerTypeDefinitionProvider: registerTypeDefinitionProvider,
            registerCodeLensProvider: registerCodeLensProvider,
            registerCodeActionProvider: registerCodeActionProvider,
            registerDocumentFormattingEditProvider: registerDocumentFormattingEditProvider,
            registerDocumentRangeFormattingEditProvider: registerDocumentRangeFormattingEditProvider,
            registerOnTypeFormattingEditProvider: registerOnTypeFormattingEditProvider,
            registerLinkProvider: registerLinkProvider,
            registerColorProvider: registerColorProvider,
            registerFoldingRangeProvider: registerFoldingRangeProvider,
            registerDeclarationProvider: registerDeclarationProvider,
            registerSelectionRangeProvider: registerSelectionRangeProvider,
            registerDocumentSemanticTokensProvider: registerDocumentSemanticTokensProvider,
            registerDocumentRangeSemanticTokensProvider: registerDocumentRangeSemanticTokensProvider,
            registerInlineCompletionsProvider: registerInlineCompletionsProvider,
            registerInlineEditProvider: registerInlineEditProvider,
            registerInlayHintsProvider: registerInlayHintsProvider,
            // enums
            DocumentHighlightKind: standaloneEnums.DocumentHighlightKind,
            CompletionItemKind: standaloneEnums.CompletionItemKind,
            CompletionItemTag: standaloneEnums.CompletionItemTag,
            CompletionItemInsertTextRule: standaloneEnums.CompletionItemInsertTextRule,
            SymbolKind: standaloneEnums.SymbolKind,
            SymbolTag: standaloneEnums.SymbolTag,
            IndentAction: standaloneEnums.IndentAction,
            CompletionTriggerKind: standaloneEnums.CompletionTriggerKind,
            SignatureHelpTriggerKind: standaloneEnums.SignatureHelpTriggerKind,
            InlayHintKind: standaloneEnums.InlayHintKind,
            InlineCompletionTriggerKind: standaloneEnums.InlineCompletionTriggerKind,
            InlineEditTriggerKind: standaloneEnums.InlineEditTriggerKind,
            CodeActionTriggerType: standaloneEnums.CodeActionTriggerType,
            NewSymbolNameTag: standaloneEnums.NewSymbolNameTag,
            NewSymbolNameTriggerKind: standaloneEnums.NewSymbolNameTriggerKind,
            PartialAcceptTriggerKind: standaloneEnums.PartialAcceptTriggerKind,
            HoverVerbosityAction: standaloneEnums.HoverVerbosityAction,
            // classes
            FoldingRangeKind: languages.FoldingRangeKind,
            SelectedSuggestionInfo: languages.SelectedSuggestionInfo,
        };
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[873/*vs/editor/standalone/browser/standaloneWebWorker*/], __M([1/*require*/,0/*exports*/,60/*vs/base/common/objects*/,401/*vs/editor/browser/services/editorWorkerService*/,222/*vs/editor/standalone/browser/standaloneServices*/]), function (require, exports, objects_1, editorWorkerService_1, standaloneServices_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.createWebWorker = createWebWorker;
    /**
     * Create a new web worker that has model syncing capabilities built in.
     * Specify an AMD module to load that will `create` an object that will be proxied.
     */
    function createWebWorker(modelService, opts) {
        return new MonacoWebWorkerImpl(modelService, opts);
    }
    class MonacoWebWorkerImpl extends editorWorkerService_1.EditorWorkerClient {
        constructor(modelService, opts) {
            const workerDescriptor = {
                amdModuleId: standaloneServices_1.standaloneEditorWorkerDescriptor.amdModuleId,
                esmModuleLocation: standaloneServices_1.standaloneEditorWorkerDescriptor.esmModuleLocation,
                label: opts.label,
            };
            super(workerDescriptor, opts.keepIdleModels || false, modelService);
            this._foreignModuleId = opts.moduleId;
            this._foreignModuleCreateData = opts.createData || null;
            this._foreignModuleHost = opts.host || null;
            this._foreignProxy = null;
        }
        // foreign host request
        fhr(method, args) {
            if (!this._foreignModuleHost || typeof this._foreignModuleHost[method] !== 'function') {
                return Promise.reject(new Error('Missing method ' + method + ' or missing main thread foreign host.'));
            }
            try {
                return Promise.resolve(this._foreignModuleHost[method].apply(this._foreignModuleHost, args));
            }
            catch (e) {
                return Promise.reject(e);
            }
        }
        _getForeignProxy() {
            if (!this._foreignProxy) {
                this._foreignProxy = this._getProxy().then((proxy) => {
                    const foreignHostMethods = this._foreignModuleHost ? (0, objects_1.getAllMethodNames)(this._foreignModuleHost) : [];
                    return proxy.$loadForeignModule(this._foreignModuleId, this._foreignModuleCreateData, foreignHostMethods).then((foreignMethods) => {
                        this._foreignModuleCreateData = null;
                        const proxyMethodRequest = (method, args) => {
                            return proxy.$fmr(method, args);
                        };
                        const createProxyMethod = (method, proxyMethodRequest) => {
                            return function () {
                                const args = Array.prototype.slice.call(arguments, 0);
                                return proxyMethodRequest(method, args);
                            };
                        };
                        const foreignProxy = {};
                        for (const foreignMethod of foreignMethods) {
                            foreignProxy[foreignMethod] = createProxyMethod(foreignMethod, proxyMethodRequest);
                        }
                        return foreignProxy;
                    });
                });
            }
            return this._foreignProxy;
        }
        getProxy() {
            return this._getForeignProxy();
        }
        withSyncedResources(resources) {
            return this.workerWithSyncedResources(resources).then(_ => this.getProxy());
        }
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[874/*vs/editor/standalone/browser/standaloneEditor*/], __M([1/*require*/,0/*exports*/,52/*vs/base/browser/window*/,2/*vs/base/common/lifecycle*/,11/*vs/base/common/strings*/,22/*vs/base/common/uri*/,366/*vs/editor/browser/config/fontMeasurements*/,15/*vs/editor/browser/editorExtensions*/,34/*vs/editor/browser/services/codeEditorService*/,873/*vs/editor/standalone/browser/standaloneWebWorker*/,37/*vs/editor/common/config/editorOptions*/,165/*vs/editor/common/config/editorZoom*/,261/*vs/editor/common/config/fontInfo*/,198/*vs/editor/common/editorCommon*/,27/*vs/editor/common/languages*/,43/*vs/editor/common/languages/language*/,70/*vs/editor/common/languages/modesRegistry*/,177/*vs/editor/common/languages/nullTokenize*/,40/*vs/editor/common/model*/,51/*vs/editor/common/services/model*/,238/*vs/editor/common/standalone/standaloneEnums*/,682/*vs/editor/standalone/browser/colorizer*/,871/*vs/editor/standalone/browser/standaloneCodeEditor*/,222/*vs/editor/standalone/browser/standaloneServices*/,153/*vs/editor/standalone/common/standaloneTheme*/,29/*vs/platform/actions/common/actions*/,24/*vs/platform/commands/common/commands*/,12/*vs/platform/contextkey/common/contextkey*/,31/*vs/platform/keybinding/common/keybinding*/,108/*vs/platform/markers/common/markers*/,59/*vs/platform/opener/common/opener*/,814/*vs/editor/browser/widget/multiDiffEditor/multiDiffEditorWidget*/,541/*vs/css!vs/editor/standalone/browser/standalone-tokens*/]), function (require, exports, window_1, lifecycle_1, strings_1, uri_1, fontMeasurements_1, editorExtensions_1, codeEditorService_1, standaloneWebWorker_1, editorOptions_1, editorZoom_1, fontInfo_1, editorCommon_1, languages, language_1, modesRegistry_1, nullTokenize_1, model_1, model_2, standaloneEnums, colorizer_1, standaloneCodeEditor_1, standaloneServices_1, standaloneTheme_1, actions_1, commands_1, contextkey_1, keybinding_1, markers_1, opener_1, multiDiffEditorWidget_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.create = create;
    exports.onDidCreateEditor = onDidCreateEditor;
    exports.onDidCreateDiffEditor = onDidCreateDiffEditor;
    exports.getEditors = getEditors;
    exports.getDiffEditors = getDiffEditors;
    exports.createDiffEditor = createDiffEditor;
    exports.createMultiFileDiffEditor = createMultiFileDiffEditor;
    exports.addCommand = addCommand;
    exports.addEditorAction = addEditorAction;
    exports.addKeybindingRule = addKeybindingRule;
    exports.addKeybindingRules = addKeybindingRules;
    exports.createModel = createModel;
    exports.setModelLanguage = setModelLanguage;
    exports.setModelMarkers = setModelMarkers;
    exports.removeAllMarkers = removeAllMarkers;
    exports.getModelMarkers = getModelMarkers;
    exports.onDidChangeMarkers = onDidChangeMarkers;
    exports.getModel = getModel;
    exports.getModels = getModels;
    exports.onDidCreateModel = onDidCreateModel;
    exports.onWillDisposeModel = onWillDisposeModel;
    exports.onDidChangeModelLanguage = onDidChangeModelLanguage;
    exports.createWebWorker = createWebWorker;
    exports.colorizeElement = colorizeElement;
    exports.colorize = colorize;
    exports.colorizeModelLine = colorizeModelLine;
    exports.tokenize = tokenize;
    exports.defineTheme = defineTheme;
    exports.setTheme = setTheme;
    exports.remeasureFonts = remeasureFonts;
    exports.registerCommand = registerCommand;
    exports.registerLinkOpener = registerLinkOpener;
    exports.registerEditorOpener = registerEditorOpener;
    exports.createMonacoEditorAPI = createMonacoEditorAPI;
    /**
     * Create a new editor under `domElement`.
     * `domElement` should be empty (not contain other dom nodes).
     * The editor will read the size of `domElement`.
     */
    function create(domElement, options, override) {
        const instantiationService = standaloneServices_1.StandaloneServices.initialize(override || {});
        return instantiationService.createInstance(standaloneCodeEditor_1.StandaloneEditor, domElement, options);
    }
    /**
     * Emitted when an editor is created.
     * Creating a diff editor might cause this listener to be invoked with the two editors.
     * @event
     */
    function onDidCreateEditor(listener) {
        const codeEditorService = standaloneServices_1.StandaloneServices.get(codeEditorService_1.ICodeEditorService);
        return codeEditorService.onCodeEditorAdd((editor) => {
            listener(editor);
        });
    }
    /**
     * Emitted when an diff editor is created.
     * @event
     */
    function onDidCreateDiffEditor(listener) {
        const codeEditorService = standaloneServices_1.StandaloneServices.get(codeEditorService_1.ICodeEditorService);
        return codeEditorService.onDiffEditorAdd((editor) => {
            listener(editor);
        });
    }
    /**
     * Get all the created editors.
     */
    function getEditors() {
        const codeEditorService = standaloneServices_1.StandaloneServices.get(codeEditorService_1.ICodeEditorService);
        return codeEditorService.listCodeEditors();
    }
    /**
     * Get all the created diff editors.
     */
    function getDiffEditors() {
        const codeEditorService = standaloneServices_1.StandaloneServices.get(codeEditorService_1.ICodeEditorService);
        return codeEditorService.listDiffEditors();
    }
    /**
     * Create a new diff editor under `domElement`.
     * `domElement` should be empty (not contain other dom nodes).
     * The editor will read the size of `domElement`.
     */
    function createDiffEditor(domElement, options, override) {
        const instantiationService = standaloneServices_1.StandaloneServices.initialize(override || {});
        return instantiationService.createInstance(standaloneCodeEditor_1.StandaloneDiffEditor2, domElement, options);
    }
    function createMultiFileDiffEditor(domElement, override) {
        const instantiationService = standaloneServices_1.StandaloneServices.initialize(override || {});
        return new multiDiffEditorWidget_1.MultiDiffEditorWidget(domElement, {}, instantiationService);
    }
    /**
     * Add a command.
     */
    function addCommand(descriptor) {
        if ((typeof descriptor.id !== 'string') || (typeof descriptor.run !== 'function')) {
            throw new Error('Invalid command descriptor, `id` and `run` are required properties!');
        }
        return commands_1.CommandsRegistry.registerCommand(descriptor.id, descriptor.run);
    }
    /**
     * Add an action to all editors.
     */
    function addEditorAction(descriptor) {
        if ((typeof descriptor.id !== 'string') || (typeof descriptor.label !== 'string') || (typeof descriptor.run !== 'function')) {
            throw new Error('Invalid action descriptor, `id`, `label` and `run` are required properties!');
        }
        const precondition = contextkey_1.ContextKeyExpr.deserialize(descriptor.precondition);
        const run = (accessor, ...args) => {
            return editorExtensions_1.EditorCommand.runEditorCommand(accessor, args, precondition, (accessor, editor, args) => Promise.resolve(descriptor.run(editor, ...args)));
        };
        const toDispose = new lifecycle_1.DisposableStore();
        // Register the command
        toDispose.add(commands_1.CommandsRegistry.registerCommand(descriptor.id, run));
        // Register the context menu item
        if (descriptor.contextMenuGroupId) {
            const menuItem = {
                command: {
                    id: descriptor.id,
                    title: descriptor.label
                },
                when: precondition,
                group: descriptor.contextMenuGroupId,
                order: descriptor.contextMenuOrder || 0
            };
            toDispose.add(actions_1.MenuRegistry.appendMenuItem(actions_1.MenuId.EditorContext, menuItem));
        }
        // Register the keybindings
        if (Array.isArray(descriptor.keybindings)) {
            const keybindingService = standaloneServices_1.StandaloneServices.get(keybinding_1.IKeybindingService);
            if (!(keybindingService instanceof standaloneServices_1.StandaloneKeybindingService)) {
                console.warn('Cannot add keybinding because the editor is configured with an unrecognized KeybindingService');
            }
            else {
                const keybindingsWhen = contextkey_1.ContextKeyExpr.and(precondition, contextkey_1.ContextKeyExpr.deserialize(descriptor.keybindingContext));
                toDispose.add(keybindingService.addDynamicKeybindings(descriptor.keybindings.map((keybinding) => {
                    return {
                        keybinding,
                        command: descriptor.id,
                        when: keybindingsWhen
                    };
                })));
            }
        }
        return toDispose;
    }
    /**
     * Add a keybinding rule.
     */
    function addKeybindingRule(rule) {
        return addKeybindingRules([rule]);
    }
    /**
     * Add keybinding rules.
     */
    function addKeybindingRules(rules) {
        const keybindingService = standaloneServices_1.StandaloneServices.get(keybinding_1.IKeybindingService);
        if (!(keybindingService instanceof standaloneServices_1.StandaloneKeybindingService)) {
            console.warn('Cannot add keybinding because the editor is configured with an unrecognized KeybindingService');
            return lifecycle_1.Disposable.None;
        }
        return keybindingService.addDynamicKeybindings(rules.map((rule) => {
            return {
                keybinding: rule.keybinding,
                command: rule.command,
                commandArgs: rule.commandArgs,
                when: contextkey_1.ContextKeyExpr.deserialize(rule.when),
            };
        }));
    }
    /**
     * Create a new editor model.
     * You can specify the language that should be set for this model or let the language be inferred from the `uri`.
     */
    function createModel(value, language, uri) {
        const languageService = standaloneServices_1.StandaloneServices.get(language_1.ILanguageService);
        const languageId = languageService.getLanguageIdByMimeType(language) || language;
        return (0, standaloneCodeEditor_1.createTextModel)(standaloneServices_1.StandaloneServices.get(model_2.IModelService), languageService, value, languageId, uri);
    }
    /**
     * Change the language for a model.
     */
    function setModelLanguage(model, mimeTypeOrLanguageId) {
        const languageService = standaloneServices_1.StandaloneServices.get(language_1.ILanguageService);
        const languageId = languageService.getLanguageIdByMimeType(mimeTypeOrLanguageId) || mimeTypeOrLanguageId || modesRegistry_1.PLAINTEXT_LANGUAGE_ID;
        model.setLanguage(languageService.createById(languageId));
    }
    /**
     * Set the markers for a model.
     */
    function setModelMarkers(model, owner, markers) {
        if (model) {
            const markerService = standaloneServices_1.StandaloneServices.get(markers_1.IMarkerService);
            markerService.changeOne(owner, model.uri, markers);
        }
    }
    /**
     * Remove all markers of an owner.
     */
    function removeAllMarkers(owner) {
        const markerService = standaloneServices_1.StandaloneServices.get(markers_1.IMarkerService);
        markerService.changeAll(owner, []);
    }
    /**
     * Get markers for owner and/or resource
     *
     * @returns list of markers
     */
    function getModelMarkers(filter) {
        const markerService = standaloneServices_1.StandaloneServices.get(markers_1.IMarkerService);
        return markerService.read(filter);
    }
    /**
     * Emitted when markers change for a model.
     * @event
     */
    function onDidChangeMarkers(listener) {
        const markerService = standaloneServices_1.StandaloneServices.get(markers_1.IMarkerService);
        return markerService.onMarkerChanged(listener);
    }
    /**
     * Get the model that has `uri` if it exists.
     */
    function getModel(uri) {
        const modelService = standaloneServices_1.StandaloneServices.get(model_2.IModelService);
        return modelService.getModel(uri);
    }
    /**
     * Get all the created models.
     */
    function getModels() {
        const modelService = standaloneServices_1.StandaloneServices.get(model_2.IModelService);
        return modelService.getModels();
    }
    /**
     * Emitted when a model is created.
     * @event
     */
    function onDidCreateModel(listener) {
        const modelService = standaloneServices_1.StandaloneServices.get(model_2.IModelService);
        return modelService.onModelAdded(listener);
    }
    /**
     * Emitted right before a model is disposed.
     * @event
     */
    function onWillDisposeModel(listener) {
        const modelService = standaloneServices_1.StandaloneServices.get(model_2.IModelService);
        return modelService.onModelRemoved(listener);
    }
    /**
     * Emitted when a different language is set to a model.
     * @event
     */
    function onDidChangeModelLanguage(listener) {
        const modelService = standaloneServices_1.StandaloneServices.get(model_2.IModelService);
        return modelService.onModelLanguageChanged((e) => {
            listener({
                model: e.model,
                oldLanguage: e.oldLanguageId
            });
        });
    }
    /**
     * Create a new web worker that has model syncing capabilities built in.
     * Specify an AMD module to load that will `create` an object that will be proxied.
     */
    function createWebWorker(opts) {
        return (0, standaloneWebWorker_1.createWebWorker)(standaloneServices_1.StandaloneServices.get(model_2.IModelService), opts);
    }
    /**
     * Colorize the contents of `domNode` using attribute `data-lang`.
     */
    function colorizeElement(domNode, options) {
        const languageService = standaloneServices_1.StandaloneServices.get(language_1.ILanguageService);
        const themeService = standaloneServices_1.StandaloneServices.get(standaloneTheme_1.IStandaloneThemeService);
        return colorizer_1.Colorizer.colorizeElement(themeService, languageService, domNode, options).then(() => {
            themeService.registerEditorContainer(domNode);
        });
    }
    /**
     * Colorize `text` using language `languageId`.
     */
    function colorize(text, languageId, options) {
        const languageService = standaloneServices_1.StandaloneServices.get(language_1.ILanguageService);
        const themeService = standaloneServices_1.StandaloneServices.get(standaloneTheme_1.IStandaloneThemeService);
        themeService.registerEditorContainer(window_1.mainWindow.document.body);
        return colorizer_1.Colorizer.colorize(languageService, text, languageId, options);
    }
    /**
     * Colorize a line in a model.
     */
    function colorizeModelLine(model, lineNumber, tabSize = 4) {
        const themeService = standaloneServices_1.StandaloneServices.get(standaloneTheme_1.IStandaloneThemeService);
        themeService.registerEditorContainer(window_1.mainWindow.document.body);
        return colorizer_1.Colorizer.colorizeModelLine(model, lineNumber, tabSize);
    }
    /**
     * @internal
     */
    function getSafeTokenizationSupport(language) {
        const tokenizationSupport = languages.TokenizationRegistry.get(language);
        if (tokenizationSupport) {
            return tokenizationSupport;
        }
        return {
            getInitialState: () => nullTokenize_1.NullState,
            tokenize: (line, hasEOL, state) => (0, nullTokenize_1.nullTokenize)(language, state)
        };
    }
    /**
     * Tokenize `text` using language `languageId`
     */
    function tokenize(text, languageId) {
        // Needed in order to get the mode registered for subsequent look-ups
        languages.TokenizationRegistry.getOrCreate(languageId);
        const tokenizationSupport = getSafeTokenizationSupport(languageId);
        const lines = (0, strings_1.splitLines)(text);
        const result = [];
        let state = tokenizationSupport.getInitialState();
        for (let i = 0, len = lines.length; i < len; i++) {
            const line = lines[i];
            const tokenizationResult = tokenizationSupport.tokenize(line, true, state);
            result[i] = tokenizationResult.tokens;
            state = tokenizationResult.endState;
        }
        return result;
    }
    /**
     * Define a new theme or update an existing theme.
     */
    function defineTheme(themeName, themeData) {
        const standaloneThemeService = standaloneServices_1.StandaloneServices.get(standaloneTheme_1.IStandaloneThemeService);
        standaloneThemeService.defineTheme(themeName, themeData);
    }
    /**
     * Switches to a theme.
     */
    function setTheme(themeName) {
        const standaloneThemeService = standaloneServices_1.StandaloneServices.get(standaloneTheme_1.IStandaloneThemeService);
        standaloneThemeService.setTheme(themeName);
    }
    /**
     * Clears all cached font measurements and triggers re-measurement.
     */
    function remeasureFonts() {
        fontMeasurements_1.FontMeasurements.clearAllFontInfos();
    }
    /**
     * Register a command.
     */
    function registerCommand(id, handler) {
        return commands_1.CommandsRegistry.registerCommand({ id, handler });
    }
    /**
     * Registers a handler that is called when a link is opened in any editor. The handler callback should return `true` if the link was handled and `false` otherwise.
     * The handler that was registered last will be called first when a link is opened.
     *
     * Returns a disposable that can unregister the opener again.
     */
    function registerLinkOpener(opener) {
        const openerService = standaloneServices_1.StandaloneServices.get(opener_1.IOpenerService);
        return openerService.registerOpener({
            async open(resource) {
                if (typeof resource === 'string') {
                    resource = uri_1.URI.parse(resource);
                }
                return opener.open(resource);
            }
        });
    }
    /**
     * Registers a handler that is called when a resource other than the current model should be opened in the editor (e.g. "go to definition").
     * The handler callback should return `true` if the request was handled and `false` otherwise.
     *
     * Returns a disposable that can unregister the opener again.
     *
     * If no handler is registered the default behavior is to do nothing for models other than the currently attached one.
     */
    function registerEditorOpener(opener) {
        const codeEditorService = standaloneServices_1.StandaloneServices.get(codeEditorService_1.ICodeEditorService);
        return codeEditorService.registerCodeEditorOpenHandler(async (input, source, sideBySide) => {
            if (!source) {
                return null;
            }
            const selection = input.options?.selection;
            let selectionOrPosition;
            if (selection && typeof selection.endLineNumber === 'number' && typeof selection.endColumn === 'number') {
                selectionOrPosition = selection;
            }
            else if (selection) {
                selectionOrPosition = { lineNumber: selection.startLineNumber, column: selection.startColumn };
            }
            if (await opener.openCodeEditor(source, input.resource, selectionOrPosition)) {
                return source; // return source editor to indicate that this handler has successfully handled the opening
            }
            return null; // fallback to other registered handlers
        });
    }
    /**
     * @internal
     */
    function createMonacoEditorAPI() {
        return {
            // methods
            create: create,
            getEditors: getEditors,
            getDiffEditors: getDiffEditors,
            onDidCreateEditor: onDidCreateEditor,
            onDidCreateDiffEditor: onDidCreateDiffEditor,
            createDiffEditor: createDiffEditor,
            addCommand: addCommand,
            addEditorAction: addEditorAction,
            addKeybindingRule: addKeybindingRule,
            addKeybindingRules: addKeybindingRules,
            createModel: createModel,
            setModelLanguage: setModelLanguage,
            setModelMarkers: setModelMarkers,
            getModelMarkers: getModelMarkers,
            removeAllMarkers: removeAllMarkers,
            onDidChangeMarkers: onDidChangeMarkers,
            getModels: getModels,
            getModel: getModel,
            onDidCreateModel: onDidCreateModel,
            onWillDisposeModel: onWillDisposeModel,
            onDidChangeModelLanguage: onDidChangeModelLanguage,
            createWebWorker: createWebWorker,
            colorizeElement: colorizeElement,
            colorize: colorize,
            colorizeModelLine: colorizeModelLine,
            tokenize: tokenize,
            defineTheme: defineTheme,
            setTheme: setTheme,
            remeasureFonts: remeasureFonts,
            registerCommand: registerCommand,
            registerLinkOpener: registerLinkOpener,
            registerEditorOpener: registerEditorOpener,
            // enums
            AccessibilitySupport: standaloneEnums.AccessibilitySupport,
            ContentWidgetPositionPreference: standaloneEnums.ContentWidgetPositionPreference,
            CursorChangeReason: standaloneEnums.CursorChangeReason,
            DefaultEndOfLine: standaloneEnums.DefaultEndOfLine,
            EditorAutoIndentStrategy: standaloneEnums.EditorAutoIndentStrategy,
            EditorOption: standaloneEnums.EditorOption,
            EndOfLinePreference: standaloneEnums.EndOfLinePreference,
            EndOfLineSequence: standaloneEnums.EndOfLineSequence,
            MinimapPosition: standaloneEnums.MinimapPosition,
            MinimapSectionHeaderStyle: standaloneEnums.MinimapSectionHeaderStyle,
            MouseTargetType: standaloneEnums.MouseTargetType,
            OverlayWidgetPositionPreference: standaloneEnums.OverlayWidgetPositionPreference,
            OverviewRulerLane: standaloneEnums.OverviewRulerLane,
            GlyphMarginLane: standaloneEnums.GlyphMarginLane,
            RenderLineNumbersType: standaloneEnums.RenderLineNumbersType,
            RenderMinimap: standaloneEnums.RenderMinimap,
            ScrollbarVisibility: standaloneEnums.ScrollbarVisibility,
            ScrollType: standaloneEnums.ScrollType,
            TextEditorCursorBlinkingStyle: standaloneEnums.TextEditorCursorBlinkingStyle,
            TextEditorCursorStyle: standaloneEnums.TextEditorCursorStyle,
            TrackedRangeStickiness: standaloneEnums.TrackedRangeStickiness,
            WrappingIndent: standaloneEnums.WrappingIndent,
            InjectedTextCursorStops: standaloneEnums.InjectedTextCursorStops,
            PositionAffinity: standaloneEnums.PositionAffinity,
            ShowLightbulbIconMode: standaloneEnums.ShowLightbulbIconMode,
            // classes
            ConfigurationChangedEvent: editorOptions_1.ConfigurationChangedEvent,
            BareFontInfo: fontInfo_1.BareFontInfo,
            FontInfo: fontInfo_1.FontInfo,
            TextModelResolvedOptions: model_1.TextModelResolvedOptions,
            FindMatch: model_1.FindMatch,
            ApplyUpdateResult: editorOptions_1.ApplyUpdateResult,
            EditorZoom: editorZoom_1.EditorZoom,
            createMultiFileDiffEditor: createMultiFileDiffEditor,
            // vars
            EditorType: editorCommon_1.EditorType,
            EditorOptions: editorOptions_1.EditorOptions
        };
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
define(__m[875/*vs/editor/editor.api*/], __M([1/*require*/,0/*exports*/,37/*vs/editor/common/config/editorOptions*/,372/*vs/editor/common/services/editorBaseApi*/,874/*vs/editor/standalone/browser/standaloneEditor*/,872/*vs/editor/standalone/browser/standaloneLanguages*/,409/*vs/editor/contrib/format/browser/format*/]), function (require, exports, editorOptions_1, editorBaseApi_1, standaloneEditor_1, standaloneLanguages_1, format_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.languages = exports.editor = exports.Token = exports.Uri = exports.MarkerTag = exports.MarkerSeverity = exports.SelectionDirection = exports.Selection = exports.Range = exports.Position = exports.KeyMod = exports.KeyCode = exports.Emitter = exports.CancellationTokenSource = void 0;
    // Set defaults for standalone editor
    editorOptions_1.EditorOptions.wrappingIndent.defaultValue = 0 /* WrappingIndent.None */;
    editorOptions_1.EditorOptions.glyphMargin.defaultValue = false;
    editorOptions_1.EditorOptions.autoIndent.defaultValue = 3 /* EditorAutoIndentStrategy.Advanced */;
    editorOptions_1.EditorOptions.overviewRulerLanes.defaultValue = 2;
    // We need to register a formatter selector which simply picks the first available formatter.
    // See https://github.com/microsoft/monaco-editor/issues/2327
    format_1.FormattingConflicts.setFormatterSelector((formatter, document, mode) => Promise.resolve(formatter[0]));
    const api = (0, editorBaseApi_1.createMonacoBaseAPI)();
    api.editor = (0, standaloneEditor_1.createMonacoEditorAPI)();
    api.languages = (0, standaloneLanguages_1.createMonacoLanguagesAPI)();
    exports.CancellationTokenSource = api.CancellationTokenSource;
    exports.Emitter = api.Emitter;
    exports.KeyCode = api.KeyCode;
    exports.KeyMod = api.KeyMod;
    exports.Position = api.Position;
    exports.Range = api.Range;
    exports.Selection = api.Selection;
    exports.SelectionDirection = api.SelectionDirection;
    exports.MarkerSeverity = api.MarkerSeverity;
    exports.MarkerTag = api.MarkerTag;
    exports.Uri = api.Uri;
    exports.Token = api.Token;
    exports.editor = api.editor;
    exports.languages = api.languages;
    const monacoEnvironment = globalThis.MonacoEnvironment;
    if (monacoEnvironment?.globalAPI || (typeof define === 'function' && define.amd)) {
        globalThis.monaco = api;
    }
    if (typeof globalThis.require !== 'undefined' && typeof globalThis.require.config === 'function') {
        globalThis.require.config({
            ignoreDuplicateModules: [
                'vscode-languageserver-types',
                'vscode-languageserver-types/main',
                'vscode-languageserver-textdocument',
                'vscode-languageserver-textdocument/main',
                'vscode-nls',
                'vscode-nls/vscode-nls',
                'jsonc-parser',
                'jsonc-parser/main',
                'vscode-uri',
                'vscode-uri/index',
                'vs/basic-languages/typescript/typescript'
            ]
        });
    }
});

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/











var __exportStar = (this && this.__exportStar) || function(m, exports) {
    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
define(__m[877/*vs/editor/editor.main*/], __M([1/*require*/,0/*exports*/,875/*vs/editor/editor.api*/,870/*vs/editor/editor.all*/,746/*vs/editor/standalone/browser/iPadShowKeyboard/iPadShowKeyboard*/,747/*vs/editor/standalone/browser/inspectTokens/inspectTokens*/,721/*vs/editor/standalone/browser/quickAccess/standaloneHelpQuickAccess*/,794/*vs/editor/standalone/browser/quickAccess/standaloneGotoLineQuickAccess*/,795/*vs/editor/standalone/browser/quickAccess/standaloneGotoSymbolQuickAccess*/,750/*vs/editor/standalone/browser/quickAccess/standaloneCommandsQuickAccess*/,854/*vs/editor/standalone/browser/referenceSearch/standaloneReferenceSearch*/,797/*vs/editor/standalone/browser/toggleHighContrast/toggleHighContrast*/]), function (require, exports, editor_api_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    __exportStar(editor_api_1, exports);
});

}).call(this);

/*!-----------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Version: 0.52.0(f6dc0eb8fce67e57f6036f4769d92c1666cdf546)
 * Released under the MIT license
 * https://github.com/microsoft/monaco-editor/blob/main/LICENSE.txt
 *-----------------------------------------------------------------------------*/
define("vs/basic-languages/monaco.contribution", ["require","vs/editor/editor.api"],(require)=>{
"use strict";
var moduleExports = (() => {
  var __create = Object.create;
  var __defProp = Object.defineProperty;
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  var __getOwnPropNames = Object.getOwnPropertyNames;
  var __getProtoOf = Object.getPrototypeOf;
  var __hasOwnProp = Object.prototype.hasOwnProperty;
  var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
    get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
  }) : x)(function(x) {
    if (typeof require !== "undefined")
      return require.apply(this, arguments);
    throw Error('Dynamic require of "' + x + '" is not supported');
  });
  var __commonJS = (cb, mod) => function __require2() {
    return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
  };
  var __copyProps = (to, from, except, desc) => {
    if (from && typeof from === "object" || typeof from === "function") {
      for (let key of __getOwnPropNames(from))
        if (!__hasOwnProp.call(to, key) && key !== except)
          __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
    }
    return to;
  };
  var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
  var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
    // If the importer is in node compatibility mode or this is not an ESM
    // file that has been converted to a CommonJS file using a Babel-
    // compatible transform (i.e. "__esModule" has not been set), then set
    // "default" to the CommonJS "module.exports" for node compatibility.
    isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
    mod
  ));

  // src/fillers/monaco-editor-core-amd.ts
  var require_monaco_editor_core_amd = __commonJS({
    "src/fillers/monaco-editor-core-amd.ts"(exports, module) {
      var api = __toESM(__require("vs/editor/editor.api"));
      module.exports = api;
    }
  });

  // src/fillers/monaco-editor-core.ts
  var monaco_editor_core_exports = {};
  __reExport(monaco_editor_core_exports, __toESM(require_monaco_editor_core_amd()));

  // src/basic-languages/_.contribution.ts
  var languageDefinitions = {};
  var lazyLanguageLoaders = {};
  var LazyLanguageLoader = class _LazyLanguageLoader {
    static getOrCreate(languageId) {
      if (!lazyLanguageLoaders[languageId]) {
        lazyLanguageLoaders[languageId] = new _LazyLanguageLoader(languageId);
      }
      return lazyLanguageLoaders[languageId];
    }
    constructor(languageId) {
      this._languageId = languageId;
      this._loadingTriggered = false;
      this._lazyLoadPromise = new Promise((resolve, reject) => {
        this._lazyLoadPromiseResolve = resolve;
        this._lazyLoadPromiseReject = reject;
      });
    }
    load() {
      if (!this._loadingTriggered) {
        this._loadingTriggered = true;
        languageDefinitions[this._languageId].loader().then(
          (mod) => this._lazyLoadPromiseResolve(mod),
          (err) => this._lazyLoadPromiseReject(err)
        );
      }
      return this._lazyLoadPromise;
    }
  };
  function registerLanguage(def) {
    const languageId = def.id;
    languageDefinitions[languageId] = def;
    monaco_editor_core_exports.languages.register(def);
    const lazyLanguageLoader = LazyLanguageLoader.getOrCreate(languageId);
    monaco_editor_core_exports.languages.registerTokensProviderFactory(languageId, {
      create: async () => {
        const mod = await lazyLanguageLoader.load();
        return mod.language;
      }
    });
    monaco_editor_core_exports.languages.onLanguageEncountered(languageId, async () => {
      const mod = await lazyLanguageLoader.load();
      monaco_editor_core_exports.languages.setLanguageConfiguration(languageId, mod.conf);
    });
  }

  // src/basic-languages/abap/abap.contribution.ts
  registerLanguage({
    id: "abap",
    extensions: [".abap"],
    aliases: ["abap", "ABAP"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/abap/abap"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/apex/apex.contribution.ts
  registerLanguage({
    id: "apex",
    extensions: [".cls"],
    aliases: ["Apex", "apex"],
    mimetypes: ["text/x-apex-source", "text/x-apex"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/apex/apex"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/azcli/azcli.contribution.ts
  registerLanguage({
    id: "azcli",
    extensions: [".azcli"],
    aliases: ["Azure CLI", "azcli"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/azcli/azcli"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/bat/bat.contribution.ts
  registerLanguage({
    id: "bat",
    extensions: [".bat", ".cmd"],
    aliases: ["Batch", "bat"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/bat/bat"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/bicep/bicep.contribution.ts
  registerLanguage({
    id: "bicep",
    extensions: [".bicep"],
    aliases: ["Bicep"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/bicep/bicep"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/cameligo/cameligo.contribution.ts
  registerLanguage({
    id: "cameligo",
    extensions: [".mligo"],
    aliases: ["Cameligo"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/cameligo/cameligo"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/clojure/clojure.contribution.ts
  registerLanguage({
    id: "clojure",
    extensions: [".clj", ".cljs", ".cljc", ".edn"],
    aliases: ["clojure", "Clojure"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/clojure/clojure"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/coffee/coffee.contribution.ts
  registerLanguage({
    id: "coffeescript",
    extensions: [".coffee"],
    aliases: ["CoffeeScript", "coffeescript", "coffee"],
    mimetypes: ["text/x-coffeescript", "text/coffeescript"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/coffee/coffee"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/cpp/cpp.contribution.ts
  registerLanguage({
    id: "c",
    extensions: [".c", ".h"],
    aliases: ["C", "c"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/cpp/cpp"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });
  registerLanguage({
    id: "cpp",
    extensions: [".cpp", ".cc", ".cxx", ".hpp", ".hh", ".hxx"],
    aliases: ["C++", "Cpp", "cpp"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/cpp/cpp"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/csharp/csharp.contribution.ts
  registerLanguage({
    id: "csharp",
    extensions: [".cs", ".csx", ".cake"],
    aliases: ["C#", "csharp"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/csharp/csharp"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/csp/csp.contribution.ts
  registerLanguage({
    id: "csp",
    extensions: [".csp"],
    aliases: ["CSP", "csp"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/csp/csp"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/css/css.contribution.ts
  registerLanguage({
    id: "css",
    extensions: [".css"],
    aliases: ["CSS", "css"],
    mimetypes: ["text/css"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/css/css"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/cypher/cypher.contribution.ts
  registerLanguage({
    id: "cypher",
    extensions: [".cypher", ".cyp"],
    aliases: ["Cypher", "OpenCypher"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/cypher/cypher"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/dart/dart.contribution.ts
  registerLanguage({
    id: "dart",
    extensions: [".dart"],
    aliases: ["Dart", "dart"],
    mimetypes: ["text/x-dart-source", "text/x-dart"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/dart/dart"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/dockerfile/dockerfile.contribution.ts
  registerLanguage({
    id: "dockerfile",
    extensions: [".dockerfile"],
    filenames: ["Dockerfile"],
    aliases: ["Dockerfile"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/dockerfile/dockerfile"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/ecl/ecl.contribution.ts
  registerLanguage({
    id: "ecl",
    extensions: [".ecl"],
    aliases: ["ECL", "Ecl", "ecl"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/ecl/ecl"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/elixir/elixir.contribution.ts
  registerLanguage({
    id: "elixir",
    extensions: [".ex", ".exs"],
    aliases: ["Elixir", "elixir", "ex"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/elixir/elixir"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/flow9/flow9.contribution.ts
  registerLanguage({
    id: "flow9",
    extensions: [".flow"],
    aliases: ["Flow9", "Flow", "flow9", "flow"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/flow9/flow9"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/fsharp/fsharp.contribution.ts
  registerLanguage({
    id: "fsharp",
    extensions: [".fs", ".fsi", ".ml", ".mli", ".fsx", ".fsscript"],
    aliases: ["F#", "FSharp", "fsharp"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/fsharp/fsharp"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/freemarker2/freemarker2.contribution.ts
  registerLanguage({
    id: "freemarker2",
    extensions: [".ftl", ".ftlh", ".ftlx"],
    aliases: ["FreeMarker2", "Apache FreeMarker2"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/freemarker2/freemarker2"], resolve, reject);
        }).then((m) => m.TagAngleInterpolationDollar);
      } else {
        return null.then((m) => m.TagAutoInterpolationDollar);
      }
    }
  });
  registerLanguage({
    id: "freemarker2.tag-angle.interpolation-dollar",
    aliases: ["FreeMarker2 (Angle/Dollar)", "Apache FreeMarker2 (Angle/Dollar)"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/freemarker2/freemarker2"], resolve, reject);
        }).then((m) => m.TagAngleInterpolationDollar);
      } else {
        return null.then((m) => m.TagAngleInterpolationDollar);
      }
    }
  });
  registerLanguage({
    id: "freemarker2.tag-bracket.interpolation-dollar",
    aliases: ["FreeMarker2 (Bracket/Dollar)", "Apache FreeMarker2 (Bracket/Dollar)"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/freemarker2/freemarker2"], resolve, reject);
        }).then((m) => m.TagBracketInterpolationDollar);
      } else {
        return null.then((m) => m.TagBracketInterpolationDollar);
      }
    }
  });
  registerLanguage({
    id: "freemarker2.tag-angle.interpolation-bracket",
    aliases: ["FreeMarker2 (Angle/Bracket)", "Apache FreeMarker2 (Angle/Bracket)"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/freemarker2/freemarker2"], resolve, reject);
        }).then((m) => m.TagAngleInterpolationBracket);
      } else {
        return null.then((m) => m.TagAngleInterpolationBracket);
      }
    }
  });
  registerLanguage({
    id: "freemarker2.tag-bracket.interpolation-bracket",
    aliases: ["FreeMarker2 (Bracket/Bracket)", "Apache FreeMarker2 (Bracket/Bracket)"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/freemarker2/freemarker2"], resolve, reject);
        }).then((m) => m.TagBracketInterpolationBracket);
      } else {
        return null.then((m) => m.TagBracketInterpolationBracket);
      }
    }
  });
  registerLanguage({
    id: "freemarker2.tag-auto.interpolation-dollar",
    aliases: ["FreeMarker2 (Auto/Dollar)", "Apache FreeMarker2 (Auto/Dollar)"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/freemarker2/freemarker2"], resolve, reject);
        }).then((m) => m.TagAutoInterpolationDollar);
      } else {
        return null.then((m) => m.TagAutoInterpolationDollar);
      }
    }
  });
  registerLanguage({
    id: "freemarker2.tag-auto.interpolation-bracket",
    aliases: ["FreeMarker2 (Auto/Bracket)", "Apache FreeMarker2 (Auto/Bracket)"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/freemarker2/freemarker2"], resolve, reject);
        }).then((m) => m.TagAutoInterpolationBracket);
      } else {
        return null.then((m) => m.TagAutoInterpolationBracket);
      }
    }
  });

  // src/basic-languages/go/go.contribution.ts
  registerLanguage({
    id: "go",
    extensions: [".go"],
    aliases: ["Go"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/go/go"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/graphql/graphql.contribution.ts
  registerLanguage({
    id: "graphql",
    extensions: [".graphql", ".gql"],
    aliases: ["GraphQL", "graphql", "gql"],
    mimetypes: ["application/graphql"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/graphql/graphql"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/handlebars/handlebars.contribution.ts
  registerLanguage({
    id: "handlebars",
    extensions: [".handlebars", ".hbs"],
    aliases: ["Handlebars", "handlebars", "hbs"],
    mimetypes: ["text/x-handlebars-template"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/handlebars/handlebars"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/hcl/hcl.contribution.ts
  registerLanguage({
    id: "hcl",
    extensions: [".tf", ".tfvars", ".hcl"],
    aliases: ["Terraform", "tf", "HCL", "hcl"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/hcl/hcl"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/html/html.contribution.ts
  registerLanguage({
    id: "html",
    extensions: [".html", ".htm", ".shtml", ".xhtml", ".mdoc", ".jsp", ".asp", ".aspx", ".jshtm"],
    aliases: ["HTML", "htm", "html", "xhtml"],
    mimetypes: ["text/html", "text/x-jshtm", "text/template", "text/ng-template"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/html/html"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/ini/ini.contribution.ts
  registerLanguage({
    id: "ini",
    extensions: [".ini", ".properties", ".gitconfig"],
    filenames: ["config", ".gitattributes", ".gitconfig", ".editorconfig"],
    aliases: ["Ini", "ini"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/ini/ini"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/java/java.contribution.ts
  registerLanguage({
    id: "java",
    extensions: [".java", ".jav"],
    aliases: ["Java", "java"],
    mimetypes: ["text/x-java-source", "text/x-java"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/java/java"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/javascript/javascript.contribution.ts
  registerLanguage({
    id: "javascript",
    extensions: [".js", ".es6", ".jsx", ".mjs", ".cjs"],
    firstLine: "^#!.*\\bnode",
    filenames: ["jakefile"],
    aliases: ["JavaScript", "javascript", "js"],
    mimetypes: ["text/javascript"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/javascript/javascript"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/julia/julia.contribution.ts
  registerLanguage({
    id: "julia",
    extensions: [".jl"],
    aliases: ["julia", "Julia"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/julia/julia"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/kotlin/kotlin.contribution.ts
  registerLanguage({
    id: "kotlin",
    extensions: [".kt", ".kts"],
    aliases: ["Kotlin", "kotlin"],
    mimetypes: ["text/x-kotlin-source", "text/x-kotlin"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/kotlin/kotlin"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/less/less.contribution.ts
  registerLanguage({
    id: "less",
    extensions: [".less"],
    aliases: ["Less", "less"],
    mimetypes: ["text/x-less", "text/less"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/less/less"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/lexon/lexon.contribution.ts
  registerLanguage({
    id: "lexon",
    extensions: [".lex"],
    aliases: ["Lexon"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/lexon/lexon"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/lua/lua.contribution.ts
  registerLanguage({
    id: "lua",
    extensions: [".lua"],
    aliases: ["Lua", "lua"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/lua/lua"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/liquid/liquid.contribution.ts
  registerLanguage({
    id: "liquid",
    extensions: [".liquid", ".html.liquid"],
    aliases: ["Liquid", "liquid"],
    mimetypes: ["application/liquid"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/liquid/liquid"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/m3/m3.contribution.ts
  registerLanguage({
    id: "m3",
    extensions: [".m3", ".i3", ".mg", ".ig"],
    aliases: ["Modula-3", "Modula3", "modula3", "m3"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/m3/m3"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/markdown/markdown.contribution.ts
  registerLanguage({
    id: "markdown",
    extensions: [".md", ".markdown", ".mdown", ".mkdn", ".mkd", ".mdwn", ".mdtxt", ".mdtext"],
    aliases: ["Markdown", "markdown"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/markdown/markdown"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/mdx/mdx.contribution.ts
  registerLanguage({
    id: "mdx",
    extensions: [".mdx"],
    aliases: ["MDX", "mdx"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/mdx/mdx"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/mips/mips.contribution.ts
  registerLanguage({
    id: "mips",
    extensions: [".s"],
    aliases: ["MIPS", "MIPS-V"],
    mimetypes: ["text/x-mips", "text/mips", "text/plaintext"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/mips/mips"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/msdax/msdax.contribution.ts
  registerLanguage({
    id: "msdax",
    extensions: [".dax", ".msdax"],
    aliases: ["DAX", "MSDAX"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/msdax/msdax"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/mysql/mysql.contribution.ts
  registerLanguage({
    id: "mysql",
    extensions: [],
    aliases: ["MySQL", "mysql"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/mysql/mysql"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/objective-c/objective-c.contribution.ts
  registerLanguage({
    id: "objective-c",
    extensions: [".m"],
    aliases: ["Objective-C"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/objective-c/objective-c"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/pascal/pascal.contribution.ts
  registerLanguage({
    id: "pascal",
    extensions: [".pas", ".p", ".pp"],
    aliases: ["Pascal", "pas"],
    mimetypes: ["text/x-pascal-source", "text/x-pascal"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/pascal/pascal"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/pascaligo/pascaligo.contribution.ts
  registerLanguage({
    id: "pascaligo",
    extensions: [".ligo"],
    aliases: ["Pascaligo", "ligo"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/pascaligo/pascaligo"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/perl/perl.contribution.ts
  registerLanguage({
    id: "perl",
    extensions: [".pl", ".pm"],
    aliases: ["Perl", "pl"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/perl/perl"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/pgsql/pgsql.contribution.ts
  registerLanguage({
    id: "pgsql",
    extensions: [],
    aliases: ["PostgreSQL", "postgres", "pg", "postgre"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/pgsql/pgsql"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/php/php.contribution.ts
  registerLanguage({
    id: "php",
    extensions: [".php", ".php4", ".php5", ".phtml", ".ctp"],
    aliases: ["PHP", "php"],
    mimetypes: ["application/x-php"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/php/php"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/pla/pla.contribution.ts
  registerLanguage({
    id: "pla",
    extensions: [".pla"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/pla/pla"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/postiats/postiats.contribution.ts
  registerLanguage({
    id: "postiats",
    extensions: [".dats", ".sats", ".hats"],
    aliases: ["ATS", "ATS/Postiats"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/postiats/postiats"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/powerquery/powerquery.contribution.ts
  registerLanguage({
    id: "powerquery",
    extensions: [".pq", ".pqm"],
    aliases: ["PQ", "M", "Power Query", "Power Query M"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/powerquery/powerquery"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/powershell/powershell.contribution.ts
  registerLanguage({
    id: "powershell",
    extensions: [".ps1", ".psm1", ".psd1"],
    aliases: ["PowerShell", "powershell", "ps", "ps1"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/powershell/powershell"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/protobuf/protobuf.contribution.ts
  registerLanguage({
    id: "proto",
    extensions: [".proto"],
    aliases: ["protobuf", "Protocol Buffers"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/protobuf/protobuf"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/pug/pug.contribution.ts
  registerLanguage({
    id: "pug",
    extensions: [".jade", ".pug"],
    aliases: ["Pug", "Jade", "jade"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/pug/pug"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/python/python.contribution.ts
  registerLanguage({
    id: "python",
    extensions: [".py", ".rpy", ".pyw", ".cpy", ".gyp", ".gypi"],
    aliases: ["Python", "py"],
    firstLine: "^#!/.*\\bpython[0-9.-]*\\b",
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/python/python"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/qsharp/qsharp.contribution.ts
  registerLanguage({
    id: "qsharp",
    extensions: [".qs"],
    aliases: ["Q#", "qsharp"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/qsharp/qsharp"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/r/r.contribution.ts
  registerLanguage({
    id: "r",
    extensions: [".r", ".rhistory", ".rmd", ".rprofile", ".rt"],
    aliases: ["R", "r"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/r/r"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/razor/razor.contribution.ts
  registerLanguage({
    id: "razor",
    extensions: [".cshtml"],
    aliases: ["Razor", "razor"],
    mimetypes: ["text/x-cshtml"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/razor/razor"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/redis/redis.contribution.ts
  registerLanguage({
    id: "redis",
    extensions: [".redis"],
    aliases: ["redis"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/redis/redis"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/redshift/redshift.contribution.ts
  registerLanguage({
    id: "redshift",
    extensions: [],
    aliases: ["Redshift", "redshift"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/redshift/redshift"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/restructuredtext/restructuredtext.contribution.ts
  registerLanguage({
    id: "restructuredtext",
    extensions: [".rst"],
    aliases: ["reStructuredText", "restructuredtext"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/restructuredtext/restructuredtext"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/ruby/ruby.contribution.ts
  registerLanguage({
    id: "ruby",
    extensions: [".rb", ".rbx", ".rjs", ".gemspec", ".pp"],
    filenames: ["rakefile", "Gemfile"],
    aliases: ["Ruby", "rb"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/ruby/ruby"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/rust/rust.contribution.ts
  registerLanguage({
    id: "rust",
    extensions: [".rs", ".rlib"],
    aliases: ["Rust", "rust"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/rust/rust"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/sb/sb.contribution.ts
  registerLanguage({
    id: "sb",
    extensions: [".sb"],
    aliases: ["Small Basic", "sb"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/sb/sb"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/scala/scala.contribution.ts
  registerLanguage({
    id: "scala",
    extensions: [".scala", ".sc", ".sbt"],
    aliases: ["Scala", "scala", "SBT", "Sbt", "sbt", "Dotty", "dotty"],
    mimetypes: ["text/x-scala-source", "text/x-scala", "text/x-sbt", "text/x-dotty"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/scala/scala"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/scheme/scheme.contribution.ts
  registerLanguage({
    id: "scheme",
    extensions: [".scm", ".ss", ".sch", ".rkt"],
    aliases: ["scheme", "Scheme"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/scheme/scheme"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/scss/scss.contribution.ts
  registerLanguage({
    id: "scss",
    extensions: [".scss"],
    aliases: ["Sass", "sass", "scss"],
    mimetypes: ["text/x-scss", "text/scss"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/scss/scss"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/shell/shell.contribution.ts
  registerLanguage({
    id: "shell",
    extensions: [".sh", ".bash"],
    aliases: ["Shell", "sh"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/shell/shell"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/solidity/solidity.contribution.ts
  registerLanguage({
    id: "sol",
    extensions: [".sol"],
    aliases: ["sol", "solidity", "Solidity"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/solidity/solidity"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/sophia/sophia.contribution.ts
  registerLanguage({
    id: "aes",
    extensions: [".aes"],
    aliases: ["aes", "sophia", "Sophia"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/sophia/sophia"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/sparql/sparql.contribution.ts
  registerLanguage({
    id: "sparql",
    extensions: [".rq"],
    aliases: ["sparql", "SPARQL"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/sparql/sparql"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/sql/sql.contribution.ts
  registerLanguage({
    id: "sql",
    extensions: [".sql"],
    aliases: ["SQL"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/sql/sql"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/st/st.contribution.ts
  registerLanguage({
    id: "st",
    extensions: [".st", ".iecst", ".iecplc", ".lc3lib", ".TcPOU", ".TcDUT", ".TcGVL", ".TcIO"],
    aliases: ["StructuredText", "scl", "stl"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/st/st"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/swift/swift.contribution.ts
  registerLanguage({
    id: "swift",
    aliases: ["Swift", "swift"],
    extensions: [".swift"],
    mimetypes: ["text/swift"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/swift/swift"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/systemverilog/systemverilog.contribution.ts
  registerLanguage({
    id: "systemverilog",
    extensions: [".sv", ".svh"],
    aliases: ["SV", "sv", "SystemVerilog", "systemverilog"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/systemverilog/systemverilog"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });
  registerLanguage({
    id: "verilog",
    extensions: [".v", ".vh"],
    aliases: ["V", "v", "Verilog", "verilog"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/systemverilog/systemverilog"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/tcl/tcl.contribution.ts
  registerLanguage({
    id: "tcl",
    extensions: [".tcl"],
    aliases: ["tcl", "Tcl", "tcltk", "TclTk", "tcl/tk", "Tcl/Tk"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/tcl/tcl"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/twig/twig.contribution.ts
  registerLanguage({
    id: "twig",
    extensions: [".twig"],
    aliases: ["Twig", "twig"],
    mimetypes: ["text/x-twig"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/twig/twig"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/typescript/typescript.contribution.ts
  registerLanguage({
    id: "typescript",
    extensions: [".ts", ".tsx", ".cts", ".mts"],
    aliases: ["TypeScript", "ts", "typescript"],
    mimetypes: ["text/typescript"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/typescript/typescript"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/typespec/typespec.contribution.ts
  registerLanguage({
    id: "typespec",
    extensions: [".tsp"],
    aliases: ["TypeSpec"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/typespec/typespec"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/vb/vb.contribution.ts
  registerLanguage({
    id: "vb",
    extensions: [".vb"],
    aliases: ["Visual Basic", "vb"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/vb/vb"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/wgsl/wgsl.contribution.ts
  registerLanguage({
    id: "wgsl",
    extensions: [".wgsl"],
    aliases: ["WebGPU Shading Language", "WGSL", "wgsl"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/wgsl/wgsl"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/xml/xml.contribution.ts
  registerLanguage({
    id: "xml",
    extensions: [
      ".xml",
      ".xsd",
      ".dtd",
      ".ascx",
      ".csproj",
      ".config",
      ".props",
      ".targets",
      ".wxi",
      ".wxl",
      ".wxs",
      ".xaml",
      ".svg",
      ".svgz",
      ".opf",
      ".xslt",
      ".xsl"
    ],
    firstLine: "(\\<\\?xml.*)|(\\<svg)|(\\<\\!doctype\\s+svg)",
    aliases: ["XML", "xml"],
    mimetypes: ["text/xml", "application/xml", "application/xaml+xml", "application/xml-dtd"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/xml/xml"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });

  // src/basic-languages/yaml/yaml.contribution.ts
  registerLanguage({
    id: "yaml",
    extensions: [".yaml", ".yml"],
    aliases: ["YAML", "yaml", "YML", "yml"],
    mimetypes: ["application/x-yaml", "text/x-yaml"],
    loader: () => {
      if (true) {
        return new Promise((resolve, reject) => {
          __require(["vs/basic-languages/yaml/yaml"], resolve, reject);
        });
      } else {
        return null;
      }
    }
  });
})();
return moduleExports;
});

/*!-----------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Version: 0.52.0(f6dc0eb8fce67e57f6036f4769d92c1666cdf546)
 * Released under the MIT license
 * https://github.com/microsoft/monaco-editor/blob/main/LICENSE.txt
 *-----------------------------------------------------------------------------*/
define("vs/language/css/monaco.contribution", ["require","vs/editor/editor.api"],(require)=>{
"use strict";
var moduleExports = (() => {
  var __create = Object.create;
  var __defProp = Object.defineProperty;
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  var __getOwnPropNames = Object.getOwnPropertyNames;
  var __getProtoOf = Object.getPrototypeOf;
  var __hasOwnProp = Object.prototype.hasOwnProperty;
  var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
    get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
  }) : x)(function(x) {
    if (typeof require !== "undefined")
      return require.apply(this, arguments);
    throw Error('Dynamic require of "' + x + '" is not supported');
  });
  var __commonJS = (cb, mod) => function __require2() {
    return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
  };
  var __export = (target, all) => {
    for (var name in all)
      __defProp(target, name, { get: all[name], enumerable: true });
  };
  var __copyProps = (to, from, except, desc) => {
    if (from && typeof from === "object" || typeof from === "function") {
      for (let key of __getOwnPropNames(from))
        if (!__hasOwnProp.call(to, key) && key !== except)
          __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
    }
    return to;
  };
  var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
  var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
    // If the importer is in node compatibility mode or this is not an ESM
    // file that has been converted to a CommonJS file using a Babel-
    // compatible transform (i.e. "__esModule" has not been set), then set
    // "default" to the CommonJS "module.exports" for node compatibility.
    isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
    mod
  ));
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

  // src/fillers/monaco-editor-core-amd.ts
  var require_monaco_editor_core_amd = __commonJS({
    "src/fillers/monaco-editor-core-amd.ts"(exports, module) {
      var api = __toESM(__require("vs/editor/editor.api"));
      module.exports = api;
    }
  });

  // src/language/css/monaco.contribution.ts
  var monaco_contribution_exports = {};
  __export(monaco_contribution_exports, {
    cssDefaults: () => cssDefaults,
    lessDefaults: () => lessDefaults,
    scssDefaults: () => scssDefaults
  });

  // src/fillers/monaco-editor-core.ts
  var monaco_editor_core_exports = {};
  __reExport(monaco_editor_core_exports, __toESM(require_monaco_editor_core_amd()));

  // src/language/css/monaco.contribution.ts
  var LanguageServiceDefaultsImpl = class {
    constructor(languageId, options, modeConfiguration) {
      this._onDidChange = new monaco_editor_core_exports.Emitter();
      this._languageId = languageId;
      this.setOptions(options);
      this.setModeConfiguration(modeConfiguration);
    }
    get onDidChange() {
      return this._onDidChange.event;
    }
    get languageId() {
      return this._languageId;
    }
    get modeConfiguration() {
      return this._modeConfiguration;
    }
    get diagnosticsOptions() {
      return this.options;
    }
    get options() {
      return this._options;
    }
    setOptions(options) {
      this._options = options || /* @__PURE__ */ Object.create(null);
      this._onDidChange.fire(this);
    }
    setDiagnosticsOptions(options) {
      this.setOptions(options);
    }
    setModeConfiguration(modeConfiguration) {
      this._modeConfiguration = modeConfiguration || /* @__PURE__ */ Object.create(null);
      this._onDidChange.fire(this);
    }
  };
  var optionsDefault = {
    validate: true,
    lint: {
      compatibleVendorPrefixes: "ignore",
      vendorPrefix: "warning",
      duplicateProperties: "warning",
      emptyRules: "warning",
      importStatement: "ignore",
      boxModel: "ignore",
      universalSelector: "ignore",
      zeroUnits: "ignore",
      fontFaceProperties: "warning",
      hexColorLength: "error",
      argumentsInColorFunction: "error",
      unknownProperties: "warning",
      ieHack: "ignore",
      unknownVendorSpecificProperties: "ignore",
      propertyIgnoredDueToDisplay: "warning",
      important: "ignore",
      float: "ignore",
      idSelector: "ignore"
    },
    data: { useDefaultDataProvider: true },
    format: {
      newlineBetweenSelectors: true,
      newlineBetweenRules: true,
      spaceAroundSelectorSeparator: false,
      braceStyle: "collapse",
      maxPreserveNewLines: void 0,
      preserveNewLines: true
    }
  };
  var modeConfigurationDefault = {
    completionItems: true,
    hovers: true,
    documentSymbols: true,
    definitions: true,
    references: true,
    documentHighlights: true,
    rename: true,
    colors: true,
    foldingRanges: true,
    diagnostics: true,
    selectionRanges: true,
    documentFormattingEdits: true,
    documentRangeFormattingEdits: true
  };
  var cssDefaults = new LanguageServiceDefaultsImpl(
    "css",
    optionsDefault,
    modeConfigurationDefault
  );
  var scssDefaults = new LanguageServiceDefaultsImpl(
    "scss",
    optionsDefault,
    modeConfigurationDefault
  );
  var lessDefaults = new LanguageServiceDefaultsImpl(
    "less",
    optionsDefault,
    modeConfigurationDefault
  );
  monaco_editor_core_exports.languages.css = { cssDefaults, lessDefaults, scssDefaults };
  function getMode() {
    if (true) {
      return new Promise((resolve, reject) => {
        __require(["vs/language/css/cssMode"], resolve, reject);
      });
    } else {
      return null;
    }
  }
  monaco_editor_core_exports.languages.onLanguage("less", () => {
    getMode().then((mode) => mode.setupMode(lessDefaults));
  });
  monaco_editor_core_exports.languages.onLanguage("scss", () => {
    getMode().then((mode) => mode.setupMode(scssDefaults));
  });
  monaco_editor_core_exports.languages.onLanguage("css", () => {
    getMode().then((mode) => mode.setupMode(cssDefaults));
  });
  return __toCommonJS(monaco_contribution_exports);
})();
return moduleExports;
});

/*!-----------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Version: 0.52.0(f6dc0eb8fce67e57f6036f4769d92c1666cdf546)
 * Released under the MIT license
 * https://github.com/microsoft/monaco-editor/blob/main/LICENSE.txt
 *-----------------------------------------------------------------------------*/
define("vs/language/html/monaco.contribution", ["require","vs/editor/editor.api"],(require)=>{
"use strict";
var moduleExports = (() => {
  var __create = Object.create;
  var __defProp = Object.defineProperty;
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  var __getOwnPropNames = Object.getOwnPropertyNames;
  var __getProtoOf = Object.getPrototypeOf;
  var __hasOwnProp = Object.prototype.hasOwnProperty;
  var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
    get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
  }) : x)(function(x) {
    if (typeof require !== "undefined")
      return require.apply(this, arguments);
    throw Error('Dynamic require of "' + x + '" is not supported');
  });
  var __commonJS = (cb, mod) => function __require2() {
    return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
  };
  var __export = (target, all) => {
    for (var name in all)
      __defProp(target, name, { get: all[name], enumerable: true });
  };
  var __copyProps = (to, from, except, desc) => {
    if (from && typeof from === "object" || typeof from === "function") {
      for (let key of __getOwnPropNames(from))
        if (!__hasOwnProp.call(to, key) && key !== except)
          __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
    }
    return to;
  };
  var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
  var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
    // If the importer is in node compatibility mode or this is not an ESM
    // file that has been converted to a CommonJS file using a Babel-
    // compatible transform (i.e. "__esModule" has not been set), then set
    // "default" to the CommonJS "module.exports" for node compatibility.
    isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
    mod
  ));
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

  // src/fillers/monaco-editor-core-amd.ts
  var require_monaco_editor_core_amd = __commonJS({
    "src/fillers/monaco-editor-core-amd.ts"(exports, module) {
      var api = __toESM(__require("vs/editor/editor.api"));
      module.exports = api;
    }
  });

  // src/language/html/monaco.contribution.ts
  var monaco_contribution_exports = {};
  __export(monaco_contribution_exports, {
    handlebarDefaults: () => handlebarDefaults,
    handlebarLanguageService: () => handlebarLanguageService,
    htmlDefaults: () => htmlDefaults,
    htmlLanguageService: () => htmlLanguageService,
    razorDefaults: () => razorDefaults,
    razorLanguageService: () => razorLanguageService,
    registerHTMLLanguageService: () => registerHTMLLanguageService
  });

  // src/fillers/monaco-editor-core.ts
  var monaco_editor_core_exports = {};
  __reExport(monaco_editor_core_exports, __toESM(require_monaco_editor_core_amd()));

  // src/language/html/monaco.contribution.ts
  var LanguageServiceDefaultsImpl = class {
    constructor(languageId, options, modeConfiguration) {
      this._onDidChange = new monaco_editor_core_exports.Emitter();
      this._languageId = languageId;
      this.setOptions(options);
      this.setModeConfiguration(modeConfiguration);
    }
    get onDidChange() {
      return this._onDidChange.event;
    }
    get languageId() {
      return this._languageId;
    }
    get options() {
      return this._options;
    }
    get modeConfiguration() {
      return this._modeConfiguration;
    }
    setOptions(options) {
      this._options = options || /* @__PURE__ */ Object.create(null);
      this._onDidChange.fire(this);
    }
    setModeConfiguration(modeConfiguration) {
      this._modeConfiguration = modeConfiguration || /* @__PURE__ */ Object.create(null);
      this._onDidChange.fire(this);
    }
  };
  var formatDefaults = {
    tabSize: 4,
    insertSpaces: false,
    wrapLineLength: 120,
    unformatted: 'default": "a, abbr, acronym, b, bdo, big, br, button, cite, code, dfn, em, i, img, input, kbd, label, map, object, q, samp, select, small, span, strong, sub, sup, textarea, tt, var',
    contentUnformatted: "pre",
    indentInnerHtml: false,
    preserveNewLines: true,
    maxPreserveNewLines: void 0,
    indentHandlebars: false,
    endWithNewline: false,
    extraLiners: "head, body, /html",
    wrapAttributes: "auto"
  };
  var optionsDefault = {
    format: formatDefaults,
    suggest: {},
    data: { useDefaultDataProvider: true }
  };
  function getConfigurationDefault(languageId) {
    return {
      completionItems: true,
      hovers: true,
      documentSymbols: true,
      links: true,
      documentHighlights: true,
      rename: true,
      colors: true,
      foldingRanges: true,
      selectionRanges: true,
      diagnostics: languageId === htmlLanguageId,
      // turned off for Razor and Handlebar
      documentFormattingEdits: languageId === htmlLanguageId,
      // turned off for Razor and Handlebar
      documentRangeFormattingEdits: languageId === htmlLanguageId
      // turned off for Razor and Handlebar
    };
  }
  var htmlLanguageId = "html";
  var handlebarsLanguageId = "handlebars";
  var razorLanguageId = "razor";
  var htmlLanguageService = registerHTMLLanguageService(
    htmlLanguageId,
    optionsDefault,
    getConfigurationDefault(htmlLanguageId)
  );
  var htmlDefaults = htmlLanguageService.defaults;
  var handlebarLanguageService = registerHTMLLanguageService(
    handlebarsLanguageId,
    optionsDefault,
    getConfigurationDefault(handlebarsLanguageId)
  );
  var handlebarDefaults = handlebarLanguageService.defaults;
  var razorLanguageService = registerHTMLLanguageService(
    razorLanguageId,
    optionsDefault,
    getConfigurationDefault(razorLanguageId)
  );
  var razorDefaults = razorLanguageService.defaults;
  monaco_editor_core_exports.languages.html = {
    htmlDefaults,
    razorDefaults,
    handlebarDefaults,
    htmlLanguageService,
    handlebarLanguageService,
    razorLanguageService,
    registerHTMLLanguageService
  };
  function getMode() {
    if (true) {
      return new Promise((resolve, reject) => {
        __require(["vs/language/html/htmlMode"], resolve, reject);
      });
    } else {
      return null;
    }
  }
  function registerHTMLLanguageService(languageId, options = optionsDefault, modeConfiguration = getConfigurationDefault(languageId)) {
    const defaults = new LanguageServiceDefaultsImpl(languageId, options, modeConfiguration);
    let mode;
    const onLanguageListener = monaco_editor_core_exports.languages.onLanguage(languageId, async () => {
      mode = (await getMode()).setupMode(defaults);
    });
    return {
      defaults,
      dispose() {
        onLanguageListener.dispose();
        mode?.dispose();
        mode = void 0;
      }
    };
  }
  return __toCommonJS(monaco_contribution_exports);
})();
return moduleExports;
});

/*!-----------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Version: 0.52.0(f6dc0eb8fce67e57f6036f4769d92c1666cdf546)
 * Released under the MIT license
 * https://github.com/microsoft/monaco-editor/blob/main/LICENSE.txt
 *-----------------------------------------------------------------------------*/
define("vs/language/json/monaco.contribution", ["require","vs/editor/editor.api"],(require)=>{
"use strict";
var moduleExports = (() => {
  var __create = Object.create;
  var __defProp = Object.defineProperty;
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  var __getOwnPropNames = Object.getOwnPropertyNames;
  var __getProtoOf = Object.getPrototypeOf;
  var __hasOwnProp = Object.prototype.hasOwnProperty;
  var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
    get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
  }) : x)(function(x) {
    if (typeof require !== "undefined")
      return require.apply(this, arguments);
    throw Error('Dynamic require of "' + x + '" is not supported');
  });
  var __commonJS = (cb, mod) => function __require2() {
    return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
  };
  var __export = (target, all) => {
    for (var name in all)
      __defProp(target, name, { get: all[name], enumerable: true });
  };
  var __copyProps = (to, from, except, desc) => {
    if (from && typeof from === "object" || typeof from === "function") {
      for (let key of __getOwnPropNames(from))
        if (!__hasOwnProp.call(to, key) && key !== except)
          __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
    }
    return to;
  };
  var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
  var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
    // If the importer is in node compatibility mode or this is not an ESM
    // file that has been converted to a CommonJS file using a Babel-
    // compatible transform (i.e. "__esModule" has not been set), then set
    // "default" to the CommonJS "module.exports" for node compatibility.
    isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
    mod
  ));
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

  // src/fillers/monaco-editor-core-amd.ts
  var require_monaco_editor_core_amd = __commonJS({
    "src/fillers/monaco-editor-core-amd.ts"(exports, module) {
      var api = __toESM(__require("vs/editor/editor.api"));
      module.exports = api;
    }
  });

  // src/language/json/monaco.contribution.ts
  var monaco_contribution_exports = {};
  __export(monaco_contribution_exports, {
    getWorker: () => getWorker,
    jsonDefaults: () => jsonDefaults
  });

  // src/fillers/monaco-editor-core.ts
  var monaco_editor_core_exports = {};
  __reExport(monaco_editor_core_exports, __toESM(require_monaco_editor_core_amd()));

  // src/language/json/monaco.contribution.ts
  var LanguageServiceDefaultsImpl = class {
    constructor(languageId, diagnosticsOptions, modeConfiguration) {
      this._onDidChange = new monaco_editor_core_exports.Emitter();
      this._languageId = languageId;
      this.setDiagnosticsOptions(diagnosticsOptions);
      this.setModeConfiguration(modeConfiguration);
    }
    get onDidChange() {
      return this._onDidChange.event;
    }
    get languageId() {
      return this._languageId;
    }
    get modeConfiguration() {
      return this._modeConfiguration;
    }
    get diagnosticsOptions() {
      return this._diagnosticsOptions;
    }
    setDiagnosticsOptions(options) {
      this._diagnosticsOptions = options || /* @__PURE__ */ Object.create(null);
      this._onDidChange.fire(this);
    }
    setModeConfiguration(modeConfiguration) {
      this._modeConfiguration = modeConfiguration || /* @__PURE__ */ Object.create(null);
      this._onDidChange.fire(this);
    }
  };
  var diagnosticDefault = {
    validate: true,
    allowComments: true,
    schemas: [],
    enableSchemaRequest: false,
    schemaRequest: "warning",
    schemaValidation: "warning",
    comments: "error",
    trailingCommas: "error"
  };
  var modeConfigurationDefault = {
    documentFormattingEdits: true,
    documentRangeFormattingEdits: true,
    completionItems: true,
    hovers: true,
    documentSymbols: true,
    tokens: true,
    colors: true,
    foldingRanges: true,
    diagnostics: true,
    selectionRanges: true
  };
  var jsonDefaults = new LanguageServiceDefaultsImpl(
    "json",
    diagnosticDefault,
    modeConfigurationDefault
  );
  var getWorker = () => getMode().then((mode) => mode.getWorker());
  monaco_editor_core_exports.languages.json = { jsonDefaults, getWorker };
  function getMode() {
    if (true) {
      return new Promise((resolve, reject) => {
        __require(["vs/language/json/jsonMode"], resolve, reject);
      });
    } else {
      return null;
    }
  }
  monaco_editor_core_exports.languages.register({
    id: "json",
    extensions: [".json", ".bowerrc", ".jshintrc", ".jscsrc", ".eslintrc", ".babelrc", ".har"],
    aliases: ["JSON", "json"],
    mimetypes: ["application/json"]
  });
  monaco_editor_core_exports.languages.onLanguage("json", () => {
    getMode().then((mode) => mode.setupMode(jsonDefaults));
  });
  return __toCommonJS(monaco_contribution_exports);
})();
return moduleExports;
});

/*!-----------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Version: 0.52.0(f6dc0eb8fce67e57f6036f4769d92c1666cdf546)
 * Released under the MIT license
 * https://github.com/microsoft/monaco-editor/blob/main/LICENSE.txt
 *-----------------------------------------------------------------------------*/
define("vs/language/typescript/monaco.contribution", ["require","vs/editor/editor.api"],(require)=>{
"use strict";
var moduleExports = (() => {
  var __create = Object.create;
  var __defProp = Object.defineProperty;
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  var __getOwnPropNames = Object.getOwnPropertyNames;
  var __getProtoOf = Object.getPrototypeOf;
  var __hasOwnProp = Object.prototype.hasOwnProperty;
  var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
    get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
  }) : x)(function(x) {
    if (typeof require !== "undefined")
      return require.apply(this, arguments);
    throw Error('Dynamic require of "' + x + '" is not supported');
  });
  var __commonJS = (cb, mod) => function __require2() {
    return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
  };
  var __export = (target, all) => {
    for (var name in all)
      __defProp(target, name, { get: all[name], enumerable: true });
  };
  var __copyProps = (to, from, except, desc) => {
    if (from && typeof from === "object" || typeof from === "function") {
      for (let key of __getOwnPropNames(from))
        if (!__hasOwnProp.call(to, key) && key !== except)
          __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
    }
    return to;
  };
  var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
  var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
    // If the importer is in node compatibility mode or this is not an ESM
    // file that has been converted to a CommonJS file using a Babel-
    // compatible transform (i.e. "__esModule" has not been set), then set
    // "default" to the CommonJS "module.exports" for node compatibility.
    isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
    mod
  ));
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

  // src/fillers/monaco-editor-core-amd.ts
  var require_monaco_editor_core_amd = __commonJS({
    "src/fillers/monaco-editor-core-amd.ts"(exports, module) {
      var api = __toESM(__require("vs/editor/editor.api"));
      module.exports = api;
    }
  });

  // src/language/typescript/monaco.contribution.ts
  var monaco_contribution_exports = {};
  __export(monaco_contribution_exports, {
    JsxEmit: () => JsxEmit,
    ModuleKind: () => ModuleKind,
    ModuleResolutionKind: () => ModuleResolutionKind,
    NewLineKind: () => NewLineKind,
    ScriptTarget: () => ScriptTarget,
    getJavaScriptWorker: () => getJavaScriptWorker,
    getTypeScriptWorker: () => getTypeScriptWorker,
    javascriptDefaults: () => javascriptDefaults,
    typescriptDefaults: () => typescriptDefaults,
    typescriptVersion: () => typescriptVersion2
  });

  // src/language/typescript/lib/typescriptServicesMetadata.ts
  var typescriptVersion = "5.4.5";

  // src/fillers/monaco-editor-core.ts
  var monaco_editor_core_exports = {};
  __reExport(monaco_editor_core_exports, __toESM(require_monaco_editor_core_amd()));

  // src/language/typescript/monaco.contribution.ts
  var ModuleKind = /* @__PURE__ */ ((ModuleKind2) => {
    ModuleKind2[ModuleKind2["None"] = 0] = "None";
    ModuleKind2[ModuleKind2["CommonJS"] = 1] = "CommonJS";
    ModuleKind2[ModuleKind2["AMD"] = 2] = "AMD";
    ModuleKind2[ModuleKind2["UMD"] = 3] = "UMD";
    ModuleKind2[ModuleKind2["System"] = 4] = "System";
    ModuleKind2[ModuleKind2["ES2015"] = 5] = "ES2015";
    ModuleKind2[ModuleKind2["ESNext"] = 99] = "ESNext";
    return ModuleKind2;
  })(ModuleKind || {});
  var JsxEmit = /* @__PURE__ */ ((JsxEmit2) => {
    JsxEmit2[JsxEmit2["None"] = 0] = "None";
    JsxEmit2[JsxEmit2["Preserve"] = 1] = "Preserve";
    JsxEmit2[JsxEmit2["React"] = 2] = "React";
    JsxEmit2[JsxEmit2["ReactNative"] = 3] = "ReactNative";
    JsxEmit2[JsxEmit2["ReactJSX"] = 4] = "ReactJSX";
    JsxEmit2[JsxEmit2["ReactJSXDev"] = 5] = "ReactJSXDev";
    return JsxEmit2;
  })(JsxEmit || {});
  var NewLineKind = /* @__PURE__ */ ((NewLineKind2) => {
    NewLineKind2[NewLineKind2["CarriageReturnLineFeed"] = 0] = "CarriageReturnLineFeed";
    NewLineKind2[NewLineKind2["LineFeed"] = 1] = "LineFeed";
    return NewLineKind2;
  })(NewLineKind || {});
  var ScriptTarget = /* @__PURE__ */ ((ScriptTarget2) => {
    ScriptTarget2[ScriptTarget2["ES3"] = 0] = "ES3";
    ScriptTarget2[ScriptTarget2["ES5"] = 1] = "ES5";
    ScriptTarget2[ScriptTarget2["ES2015"] = 2] = "ES2015";
    ScriptTarget2[ScriptTarget2["ES2016"] = 3] = "ES2016";
    ScriptTarget2[ScriptTarget2["ES2017"] = 4] = "ES2017";
    ScriptTarget2[ScriptTarget2["ES2018"] = 5] = "ES2018";
    ScriptTarget2[ScriptTarget2["ES2019"] = 6] = "ES2019";
    ScriptTarget2[ScriptTarget2["ES2020"] = 7] = "ES2020";
    ScriptTarget2[ScriptTarget2["ESNext"] = 99] = "ESNext";
    ScriptTarget2[ScriptTarget2["JSON"] = 100] = "JSON";
    ScriptTarget2[ScriptTarget2["Latest"] = 99 /* ESNext */] = "Latest";
    return ScriptTarget2;
  })(ScriptTarget || {});
  var ModuleResolutionKind = /* @__PURE__ */ ((ModuleResolutionKind2) => {
    ModuleResolutionKind2[ModuleResolutionKind2["Classic"] = 1] = "Classic";
    ModuleResolutionKind2[ModuleResolutionKind2["NodeJs"] = 2] = "NodeJs";
    return ModuleResolutionKind2;
  })(ModuleResolutionKind || {});
  var LanguageServiceDefaultsImpl = class {
    constructor(compilerOptions, diagnosticsOptions, workerOptions, inlayHintsOptions, modeConfiguration) {
      this._onDidChange = new monaco_editor_core_exports.Emitter();
      this._onDidExtraLibsChange = new monaco_editor_core_exports.Emitter();
      this._extraLibs = /* @__PURE__ */ Object.create(null);
      this._removedExtraLibs = /* @__PURE__ */ Object.create(null);
      this._eagerModelSync = false;
      this.setCompilerOptions(compilerOptions);
      this.setDiagnosticsOptions(diagnosticsOptions);
      this.setWorkerOptions(workerOptions);
      this.setInlayHintsOptions(inlayHintsOptions);
      this.setModeConfiguration(modeConfiguration);
      this._onDidExtraLibsChangeTimeout = -1;
    }
    get onDidChange() {
      return this._onDidChange.event;
    }
    get onDidExtraLibsChange() {
      return this._onDidExtraLibsChange.event;
    }
    get modeConfiguration() {
      return this._modeConfiguration;
    }
    get workerOptions() {
      return this._workerOptions;
    }
    get inlayHintsOptions() {
      return this._inlayHintsOptions;
    }
    getExtraLibs() {
      return this._extraLibs;
    }
    addExtraLib(content, _filePath) {
      let filePath;
      if (typeof _filePath === "undefined") {
        filePath = `ts:extralib-${Math.random().toString(36).substring(2, 15)}`;
      } else {
        filePath = _filePath;
      }
      if (this._extraLibs[filePath] && this._extraLibs[filePath].content === content) {
        return {
          dispose: () => {
          }
        };
      }
      let myVersion = 1;
      if (this._removedExtraLibs[filePath]) {
        myVersion = this._removedExtraLibs[filePath] + 1;
      }
      if (this._extraLibs[filePath]) {
        myVersion = this._extraLibs[filePath].version + 1;
      }
      this._extraLibs[filePath] = {
        content,
        version: myVersion
      };
      this._fireOnDidExtraLibsChangeSoon();
      return {
        dispose: () => {
          let extraLib = this._extraLibs[filePath];
          if (!extraLib) {
            return;
          }
          if (extraLib.version !== myVersion) {
            return;
          }
          delete this._extraLibs[filePath];
          this._removedExtraLibs[filePath] = myVersion;
          this._fireOnDidExtraLibsChangeSoon();
        }
      };
    }
    setExtraLibs(libs) {
      for (const filePath in this._extraLibs) {
        this._removedExtraLibs[filePath] = this._extraLibs[filePath].version;
      }
      this._extraLibs = /* @__PURE__ */ Object.create(null);
      if (libs && libs.length > 0) {
        for (const lib of libs) {
          const filePath = lib.filePath || `ts:extralib-${Math.random().toString(36).substring(2, 15)}`;
          const content = lib.content;
          let myVersion = 1;
          if (this._removedExtraLibs[filePath]) {
            myVersion = this._removedExtraLibs[filePath] + 1;
          }
          this._extraLibs[filePath] = {
            content,
            version: myVersion
          };
        }
      }
      this._fireOnDidExtraLibsChangeSoon();
    }
    _fireOnDidExtraLibsChangeSoon() {
      if (this._onDidExtraLibsChangeTimeout !== -1) {
        return;
      }
      this._onDidExtraLibsChangeTimeout = window.setTimeout(() => {
        this._onDidExtraLibsChangeTimeout = -1;
        this._onDidExtraLibsChange.fire(void 0);
      }, 0);
    }
    getCompilerOptions() {
      return this._compilerOptions;
    }
    setCompilerOptions(options) {
      this._compilerOptions = options || /* @__PURE__ */ Object.create(null);
      this._onDidChange.fire(void 0);
    }
    getDiagnosticsOptions() {
      return this._diagnosticsOptions;
    }
    setDiagnosticsOptions(options) {
      this._diagnosticsOptions = options || /* @__PURE__ */ Object.create(null);
      this._onDidChange.fire(void 0);
    }
    setWorkerOptions(options) {
      this._workerOptions = options || /* @__PURE__ */ Object.create(null);
      this._onDidChange.fire(void 0);
    }
    setInlayHintsOptions(options) {
      this._inlayHintsOptions = options || /* @__PURE__ */ Object.create(null);
      this._onDidChange.fire(void 0);
    }
    setMaximumWorkerIdleTime(value) {
    }
    setEagerModelSync(value) {
      this._eagerModelSync = value;
    }
    getEagerModelSync() {
      return this._eagerModelSync;
    }
    setModeConfiguration(modeConfiguration) {
      this._modeConfiguration = modeConfiguration || /* @__PURE__ */ Object.create(null);
      this._onDidChange.fire(void 0);
    }
  };
  var typescriptVersion2 = typescriptVersion;
  var modeConfigurationDefault = {
    completionItems: true,
    hovers: true,
    documentSymbols: true,
    definitions: true,
    references: true,
    documentHighlights: true,
    rename: true,
    diagnostics: true,
    documentRangeFormattingEdits: true,
    signatureHelp: true,
    onTypeFormattingEdits: true,
    codeActions: true,
    inlayHints: true
  };
  var typescriptDefaults = new LanguageServiceDefaultsImpl(
    { allowNonTsExtensions: true, target: 99 /* Latest */ },
    { noSemanticValidation: false, noSyntaxValidation: false, onlyVisible: false },
    {},
    {},
    modeConfigurationDefault
  );
  var javascriptDefaults = new LanguageServiceDefaultsImpl(
    { allowNonTsExtensions: true, allowJs: true, target: 99 /* Latest */ },
    { noSemanticValidation: true, noSyntaxValidation: false, onlyVisible: false },
    {},
    {},
    modeConfigurationDefault
  );
  var getTypeScriptWorker = () => {
    return getMode().then((mode) => mode.getTypeScriptWorker());
  };
  var getJavaScriptWorker = () => {
    return getMode().then((mode) => mode.getJavaScriptWorker());
  };
  monaco_editor_core_exports.languages.typescript = {
    ModuleKind,
    JsxEmit,
    NewLineKind,
    ScriptTarget,
    ModuleResolutionKind,
    typescriptVersion: typescriptVersion2,
    typescriptDefaults,
    javascriptDefaults,
    getTypeScriptWorker,
    getJavaScriptWorker
  };
  function getMode() {
    if (true) {
      return new Promise((resolve, reject) => {
        __require(["vs/language/typescript/tsMode"], resolve, reject);
      });
    } else {
      return null;
    }
  }
  monaco_editor_core_exports.languages.onLanguage("typescript", () => {
    return getMode().then((mode) => mode.setupTypeScript(typescriptDefaults));
  });
  monaco_editor_core_exports.languages.onLanguage("javascript", () => {
    return getMode().then((mode) => mode.setupJavaScript(javascriptDefaults));
  });
  return __toCommonJS(monaco_contribution_exports);
})();
return moduleExports;
});

define("vs/editor/editor.main", ["vs/editor/edcore.main","vs/basic-languages/monaco.contribution","vs/language/css/monaco.contribution","vs/language/html/monaco.contribution","vs/language/json/monaco.contribution","vs/language/typescript/monaco.contribution"], function(api) { return api; });
//# sourceMappingURL=editor.main.js.map